Initial commit

This commit is contained in:
2025-04-15 22:27:20 -04:00
parent 5b7b68f81f
commit 771d8fe8e8
597 changed files with 149544 additions and 0 deletions

View File

@@ -0,0 +1,844 @@
#if defined _easyjson_included
#endinput
#endif
#define _easyjson_included
enum JSONType
{
Type_String,
Type_Integer,
Type_Float,
Type_Object,
Type_Boolean,
Type_Array
}
stock Handle:CreateJSON()
{
new Handle:m_hJSON = CreateTrie();
new Handle:m_hJSONKeys = CreateArray(512);
SetTrieValue(m_hJSON, "json_key_array", m_hJSONKeys);
return m_hJSON;
}
stock Handle:DecodeJSON(const String:json[], &len=0)
{
decl m_iPos, m_iIgnore;
new m_iLength = strlen(json);
m_iPos = JSONIgnore(json);
if(m_iPos == -1 || json[m_iPos] != '{')
return INVALID_HANDLE;
++m_iPos;
m_iIgnore = JSONIgnore(json[m_iPos]);
if(m_iIgnore == -1)
return INVALID_HANDLE;
m_iPos += m_iIgnore;
if(json[m_iPos] == '}')
return INVALID_HANDLE;
decl m_iStringStart;
decl m_iStringEnd;
new bool:m_bEnd = false;
new Handle:m_hJSON = CreateJSON();
while(m_iPos<m_iLength && json[m_iPos] != '}' && !m_bEnd)
{
if(GetJSONString(json[m_iPos], m_iStringStart, m_iStringEnd))
{
new String:m_szKey[m_iStringEnd-m_iStringStart+1];
strcopy(m_szKey, m_iStringEnd-m_iStringStart+1, json[m_iPos+m_iStringStart]);
m_iPos += m_iStringEnd+1;
m_iPos += JSONIgnore(json[m_iPos]);
if(json[m_iPos] == '{')
{
new m_iLen = -1;
new Handle:m_hObject = DecodeJSON(json[m_iPos], m_iLen);
if(m_hObject != INVALID_HANDLE)
{
JSONSetObject(m_hJSON, m_szKey, m_hObject);
m_iPos += m_iLen;
m_iPos += JSONIgnore(json[m_iPos]);
}
else
{
DestroyJSON(m_hJSON);
return INVALID_HANDLE;
}
} else if(json[m_iPos] == '[')
{
new m_iLen = -1;
new Handle:m_hObject = DecodeArray(json[m_iPos], m_iLen);
if(m_hObject != INVALID_HANDLE)
{
JSONSetArray(m_hJSON, m_szKey, m_hObject);
m_iPos += m_iLen;
m_iPos += JSONIgnore(json[m_iPos]);
}
else
{
DestroyJSON(m_hJSON);
return INVALID_HANDLE;
}
} else if(GetJSONString(json[m_iPos], m_iStringStart, m_iStringEnd))
{
new String:m_szValue[m_iStringEnd-m_iStringStart+1];
strcopy(m_szValue, m_iStringEnd-m_iStringStart+1, json[m_iPos+m_iStringStart]);
if(json[m_iPos+m_iStringEnd]=='}')
m_bEnd = true;
m_iPos += m_iStringEnd+1;
m_iPos += JSONIgnore(json[m_iPos]);
new m_iDot = 0;
if(m_iStringStart != 0)
JSONSetString(m_hJSON, m_szKey, m_szValue);
else if(strcmp(m_szValue, "true")==0)
JSONSetBoolean(m_hJSON, m_szKey, true);
else if(strcmp(m_szValue, "false")==0)
JSONSetBoolean(m_hJSON, m_szKey, false);
else if(JSONIsNumeric(m_szValue))
JSONSetInteger(m_hJSON, m_szKey, StringToInt(m_szValue));
else if((m_iDot = FindCharInString(m_szValue, '.'))!=-1)
{
m_szValue[m_iDot] = 0;
if(JSONIsNumeric(m_szValue) && JSONIsNumeric(m_szValue[m_iDot+1]))
{
m_szValue[m_iDot] = '.';
JSONSetFloat(m_hJSON, m_szKey, StringToFloat(m_szValue));
}
}
}
}
}
if(len != 0)
len = m_iPos;
return m_hJSON;
}
stock Handle:DecodeArray(const String:json[], &len=0)
{
decl m_iPos, m_iIgnore;
new m_iLength = strlen(json);
m_iPos = JSONIgnore(json);
if(m_iPos == -1 || json[m_iPos] != '[')
return INVALID_HANDLE;
++m_iPos;
m_iIgnore = JSONIgnore(json[m_iPos]);
if(m_iIgnore == -1)
return INVALID_HANDLE;
m_iPos += m_iIgnore;
if(json[m_iPos] == ']')
return INVALID_HANDLE;
decl m_iStringStart;
decl m_iStringEnd;
new bool:m_bEnd = false;
new Handle:m_hArray = CreateArray(1);
while(m_iPos<m_iLength && json[m_iPos] != ']' && !m_bEnd)
{
m_iPos += JSONIgnore(json[m_iPos]);
if(json[m_iPos] == '{')
{
new m_iLen = -1;
new Handle:m_hObject = DecodeJSON(json[m_iPos], m_iLen);
if(m_hObject != INVALID_HANDLE)
{
PushArrayCell(m_hArray, JSONCreateObject(m_hObject));
m_iPos += m_iLen;
m_iPos += JSONIgnore(json[m_iPos]);
}
else
{
DestroyJSONArray(m_hArray);
return INVALID_HANDLE;
}
} else if(json[m_iPos] == '[')
{
new m_iLen = -1;
new Handle:m_hObject = DecodeArray(json[m_iPos], m_iLen);
if(m_hArray != INVALID_HANDLE)
{
PushArrayCell(m_hArray, JSONCreateArray(m_hObject));
m_iPos += m_iLen;
m_iPos += JSONIgnore(json[m_iPos]);
}
else
{
DestroyJSONArray(m_hArray);
return INVALID_HANDLE;
}
} else if(GetJSONString(json[m_iPos], m_iStringStart, m_iStringEnd))
{
new String:m_szValue[m_iStringEnd-m_iStringStart+1];
strcopy(m_szValue, m_iStringEnd-m_iStringStart+1, json[m_iPos+m_iStringStart]);
if(json[m_iPos+m_iStringEnd]==']')
m_bEnd = true;
m_iPos += m_iStringEnd+1;
m_iPos += JSONIgnore(json[m_iPos]);
new m_iDot = 0;
if(m_iStringStart != 0)
PushArrayCell(m_hArray, JSONCreateString(m_szValue));
else if(strcmp(m_szValue, "true")==0)
PushArrayCell(m_hArray, JSONCreateBoolean(true));
else if(strcmp(m_szValue, "false")==0)
PushArrayCell(m_hArray, JSONCreateBoolean(false));
else if(JSONIsNumeric(m_szValue))
PushArrayCell(m_hArray, JSONCreateInteger(StringToInt(m_szValue)));
else if((m_iDot = FindCharInString(m_szValue, '.'))!=-1)
{
m_szValue[m_iDot] = 0;
if(JSONIsNumeric(m_szValue) && JSONIsNumeric(m_szValue[m_iDot+1]))
{
m_szValue[m_iDot] = '.';
PushArrayCell(m_hArray, JSONCreateFloat(StringToFloat(m_szValue)));
}
}
}
}
if(len != 0)
len = m_iPos+1;
return m_hArray;
}
stock EncodeJSON(&Handle:json, String:output[], maxlen, bool:beautify=true, &len=0, tabs=1)
{
new Handle:m_hKeyArray = INVALID_HANDLE;
if(!GetTrieValue(json, "json_key_array", m_hKeyArray))
return;
new m_iKeys = GetArraySize(m_hKeyArray);
decl String:m_szKey[512];
decl Handle:m_hObject;
if(2 >= maxlen)
return;
new String:m_szTabs[tabs+1];
if(beautify)
for(new i=0;i<tabs;++i)
m_szTabs[i] = '\t';
new m_iPos = 1;
output[0] = '{';
if(beautify)
{
output[1] = '\n';
++m_iPos;
}
for(new i=0;i<m_iKeys;++i)
{
GetArrayString(m_hKeyArray, i, m_szKey, sizeof(m_szKey));
if(!GetTrieValue(json, m_szKey, m_hObject))
continue;
decl JSONType:m_eType;
GetTrieValue(m_hObject, "type", m_eType);
switch(m_eType)
{
case Type_String:
{
decl m_iLength;
GetTrieValue(m_hObject, "size", m_iLength);
decl String:m_szValue[m_iLength*2+1];
GetTrieString(m_hObject, "value", m_szValue, m_iLength+1);
ReplaceString(m_szValue, m_iLength*2+1, "\"", "\\\"");
m_iPos += Format(output[m_iPos], maxlen-m_iPos, "%s\"%s\": \"%s\"", m_szTabs, m_szKey, m_szValue);
}
case Type_Boolean:
{
decl bool:m_bValue;
GetTrieValue(m_hObject, "value", m_bValue);
if(m_bValue)
m_iPos += Format(output[m_iPos], maxlen-m_iPos, "%s\"%s\": true", m_szTabs, m_szKey);
else
m_iPos += Format(output[m_iPos], maxlen-m_iPos, "%s\"%s\": false", m_szTabs, m_szKey);
}
case Type_Integer:
{
decl m_iValue;
GetTrieValue(m_hObject, "value", m_iValue);
m_iPos += Format(output[m_iPos], maxlen-m_iPos, "%s\"%s\": %d", m_szTabs, m_szKey, m_iValue);
}
case Type_Float:
{
decl Float:m_fValue;
GetTrieValue(m_hObject, "value", m_fValue);
m_iPos += Format(output[m_iPos], maxlen-m_iPos, "%s\"%s\": %f", m_szTabs, m_szKey, m_fValue);
}
case Type_Object:
{
decl Handle:m_hValue;
GetTrieValue(m_hObject, "value", m_hValue);
m_iPos += Format(output[m_iPos], maxlen-m_iPos, "%s\"%s\": ", m_szTabs, m_szKey);
new m_iLen = -1;
EncodeJSON(m_hValue, output[m_iPos], maxlen-m_iPos, beautify, m_iLen, tabs+1);
m_iPos += m_iLen;
}
case Type_Array:
{
decl Handle:m_hValue;
GetTrieValue(m_hObject, "value", m_hValue);
m_iPos += Format(output[m_iPos], maxlen-m_iPos, "%s\"%s\": ", m_szTabs, m_szKey);
new m_iLen = -1;
EncodeArray(m_hValue, output[m_iPos], maxlen-m_iPos, beautify, m_iLen, tabs+1);
m_iPos += m_iLen+1;
}
default:
{
continue;
}
}
if(m_iPos >= maxlen)
return;
if(m_iKeys != i+1)
{
output[m_iPos] = ',';
++m_iPos;
}
if(m_iPos >= maxlen)
return;
if(beautify)
{
output[m_iPos] = '\n';
++m_iPos;
}
}
if(m_iPos < maxlen)
{
m_szTabs[tabs-1] = 0;
m_iPos += Format(output[m_iPos], maxlen-m_iPos, "%s}", m_szTabs);
}
if(len != 0)
len=m_iPos;
}
stock EncodeArray(&Handle:json, String:output[], maxlen, bool:beautify=true, &len=0, tabs=1)
{
decl Handle:m_hObject;
if(2 >= maxlen)
return;
new String:m_szTabs[tabs+1];
if(beautify)
for(new i=0;i<tabs;++i)
m_szTabs[i] = '\t';
new m_iPos = 1;
output[0] = '[';
if(beautify)
{
output[1] = '\n';
++m_iPos;
}
new m_iKeys = GetArraySize(json);
for(new i=0;i<m_iKeys;++i)
{
m_hObject = GetArrayCell(json, i);
decl JSONType:m_eType;
GetTrieValue(m_hObject, "type", m_eType);
switch(m_eType)
{
case Type_String:
{
decl m_iLength;
GetTrieValue(m_hObject, "size", m_iLength);
decl String:m_szValue[m_iLength*2+1];
GetTrieString(m_hObject, "value", m_szValue, m_iLength+1);
ReplaceString(m_szValue, m_iLength*2+1, "\"", "\\\"");
m_iPos += Format(output[m_iPos], maxlen-m_iPos, "%s\"%s\"", m_szTabs, m_szValue);
}
case Type_Boolean:
{
decl bool:m_bValue;
GetTrieValue(m_hObject, "value", m_bValue);
if(m_bValue)
m_iPos += Format(output[m_iPos], maxlen-m_iPos, "%strue", m_szTabs);
else
m_iPos += Format(output[m_iPos], maxlen-m_iPos, "%sfalse", m_szTabs);
}
case Type_Integer:
{
decl m_iValue;
GetTrieValue(m_hObject, "value", m_iValue);
m_iPos += Format(output[m_iPos], maxlen-m_iPos, "%s%d", m_szTabs, m_iValue);
}
case Type_Float:
{
decl Float:m_fValue;
GetTrieValue(m_hObject, "value", m_fValue);
m_iPos += Format(output[m_iPos], maxlen-m_iPos, "%s%f", m_szTabs, m_fValue);
}
case Type_Object:
{
decl Handle:m_hValue;
GetTrieValue(m_hObject, "value", m_hValue);
m_iPos += Format(output[m_iPos], maxlen-m_iPos, "%s", m_szTabs);
new m_iLen = -1;
EncodeJSON(m_hValue, output[m_iPos], maxlen-m_iPos, beautify, m_iLen, tabs+1);
m_iPos += m_iLen;
}
case Type_Array:
{
decl Handle:m_hValue;
GetTrieValue(m_hObject, "value", m_hValue);
m_iPos += Format(output[m_iPos], maxlen-m_iPos, "%s", m_szTabs);
new m_iLen = -1;
EncodeArray(m_hValue, output[m_iPos], maxlen-m_iPos, beautify, m_iLen, tabs+1);
m_iPos += m_iLen;
}
}
if(m_iPos >= maxlen)
return;
if(m_iKeys != i+1)
{
output[m_iPos] = ',';
++m_iPos;
}
if(m_iPos >= maxlen)
return;
if(beautify)
{
output[m_iPos] = '\n';
++m_iPos;
}
}
if(m_iPos < maxlen)
{
m_szTabs[tabs-1] = 0;
m_iPos += Format(output[m_iPos], maxlen-m_iPos, "%s]", m_szTabs);
}
if(len != 0)
len=m_iPos-1;
}
stock JSONSetString(&Handle:json, const String:key[], const String:value[])
{
new Handle:m_hKeyArray = INVALID_HANDLE;
if(!GetTrieValue(json, "json_key_array", m_hKeyArray))
return;
PushArrayString(m_hKeyArray, key);
new Handle:m_hObject = JSONCreateString(value);
SetTrieValue(json, key, m_hObject);
}
stock JSONSetBoolean(&Handle:json, const String:key[], bool:value)
{
new Handle:m_hKeyArray = INVALID_HANDLE;
if(!GetTrieValue(json, "json_key_array", m_hKeyArray))
return;
PushArrayString(m_hKeyArray, key);
new Handle:m_hObject = JSONCreateBoolean(value);
SetTrieValue(json, key, m_hObject);
}
stock JSONSetInteger(&Handle:json, const String:key[], value)
{
new Handle:m_hKeyArray = INVALID_HANDLE;
if(!GetTrieValue(json, "json_key_array", m_hKeyArray))
return;
PushArrayString(m_hKeyArray, key);
new Handle:m_hObject = JSONCreateInteger(value);
SetTrieValue(json, key, m_hObject);
}
stock JSONSetFloat(&Handle:json, const String:key[], Float:value)
{
new Handle:m_hKeyArray = INVALID_HANDLE;
if(!GetTrieValue(json, "json_key_array", m_hKeyArray))
return;
PushArrayString(m_hKeyArray, key);
new Handle:m_hObject = JSONCreateFloat(value);
SetTrieValue(json, key, m_hObject);
}
stock JSONSetObject(&Handle:json, const String:key[], Handle:value)
{
new Handle:m_hKeyArray = INVALID_HANDLE;
if(!GetTrieValue(json, "json_key_array", m_hKeyArray))
return;
PushArrayString(m_hKeyArray, key);
new Handle:m_hObject = JSONCreateObject(value);
SetTrieValue(json, key, m_hObject);
}
stock JSONSetArray(&Handle:json, const String:key[], Handle:value)
{
new Handle:m_hKeyArray = INVALID_HANDLE;
if(!GetTrieValue(json, "json_key_array", m_hKeyArray))
return;
PushArrayString(m_hKeyArray, key);
new Handle:m_hObject = JSONCreateArray(value);
SetTrieValue(json, key, m_hObject);
}
stock Handle:JSONCreateString(const String:value[])
{
new Handle:m_hObject = CreateTrie();
SetTrieString(m_hObject, "value", value);
SetTrieValue(m_hObject, "type", Type_String);
SetTrieValue(m_hObject, "size", strlen(value));
return m_hObject;
}
stock Handle:JSONCreateBoolean(bool:value)
{
new Handle:m_hObject = CreateTrie();
SetTrieValue(m_hObject, "value", value);
SetTrieValue(m_hObject, "type", Type_Boolean);
SetTrieValue(m_hObject, "size", sizeof(value));
return m_hObject;
}
stock Handle:JSONCreateInteger(value)
{
new Handle:m_hObject = CreateTrie();
SetTrieValue(m_hObject, "value", value);
SetTrieValue(m_hObject, "type", Type_Integer);
SetTrieValue(m_hObject, "size", sizeof(value));
return m_hObject;
}
stock Handle:JSONCreateFloat(Float:value)
{
new Handle:m_hObject = CreateTrie();
SetTrieValue(m_hObject, "value", value);
SetTrieValue(m_hObject, "type", Type_Float);
SetTrieValue(m_hObject, "size", sizeof(value));
return m_hObject;
}
stock Handle:JSONCreateObject(Handle:value)
{
new Handle:m_hObject = CreateTrie();
SetTrieValue(m_hObject, "value", value);
SetTrieValue(m_hObject, "type", Type_Object);
SetTrieValue(m_hObject, "size", sizeof(value));
return m_hObject;
}
stock Handle:JSONCreateArray(Handle:value)
{
new Handle:m_hObject = CreateTrie();
SetTrieValue(m_hObject, "value", value);
SetTrieValue(m_hObject, "type", Type_Array);
SetTrieValue(m_hObject, "size", sizeof(value));
return m_hObject;
}
stock bool:JSONGetString(&Handle:json, const String:key[], String:out[], maxlen)
{
decl Handle:m_hObject;
if(!GetTrieValue(json, key, m_hObject))
return false;
decl JSONType:m_eType;
GetTrieValue(m_hObject, "type", m_eType);
if(m_eType != Type_String)
return false;
GetTrieString(m_hObject, "value", out, maxlen);
return true;
}
stock bool:JSONGetObject(&Handle:json, const String:key[], &Handle:out)
{
decl Handle:m_hObject;
if(!GetTrieValue(json, key, m_hObject))
return false;
decl JSONType:m_eType;
GetTrieValue(m_hObject, "type", m_eType);
if(m_eType != Type_Object)
return false;
GetTrieValue(m_hObject, "value", out);
return true;
}
stock bool:JSONGetArray(&Handle:json, const String:key[], &Handle:out)
{
decl Handle:m_hObject;
if(!GetTrieValue(json, key, m_hObject))
return false;
decl JSONType:m_eType;
GetTrieValue(m_hObject, "type", m_eType);
if(m_eType != Type_Array)
return false;
GetTrieValue(m_hObject, "value", out);
return true;
}
stock bool:JSONGetBoolean(&Handle:json, const String:key[], &bool:value)
{
decl Handle:m_hObject;
if(!GetTrieValue(json, key, m_hObject))
return false;
decl JSONType:m_eType;
GetTrieValue(m_hObject, "type", m_eType);
if(m_eType != Type_Boolean)
return false;
GetTrieValue(m_hObject, "value", value);
return true;
}
stock bool:JSONGetInteger(&Handle:json, const String:key[], &value)
{
decl Handle:m_hObject;
if(!GetTrieValue(json, key, m_hObject))
return false;
decl JSONType:m_eType;
GetTrieValue(m_hObject, "type", m_eType);
if(m_eType != Type_Integer)
return false;
GetTrieValue(m_hObject, "value", value);
return true;
}
stock bool:JSONGetFloat(&Handle:json, const String:key[], &Float:value)
{
decl Handle:m_hObject;
if(!GetTrieValue(json, key, m_hObject))
return false;
decl JSONType:m_eType;
GetTrieValue(m_hObject, "type", m_eType);
// For compatibility reasons only, but you should follow strict types
if(m_eType != Type_Float && m_eType != Type_Integer)
return false;
if(m_eType == Type_Integer)
{
decl m_iValue;
GetTrieValue(m_hObject, "value", m_iValue);
value = float(m_iValue);
}
else
GetTrieValue(m_hObject, "value", value);
return true;
}
stock bool:JSONGetArrayString(&Handle:array, idx, String:out[], maxlen)
{
new Handle:m_hObject = GetArrayCell(array, idx);
decl JSONType:m_eType;
GetTrieValue(m_hObject, "type", m_eType);
if(m_eType != Type_String)
return false;
GetTrieString(m_hObject, "value", out, maxlen);
return true;
}
stock bool:JSONGetArrayObject(&Handle:array, idx, &Handle:out)
{
new Handle:m_hObject = GetArrayCell(array, idx);
decl JSONType:m_eType;
GetTrieValue(m_hObject, "type", m_eType);
if(m_eType != Type_Object)
return false;
GetTrieValue(m_hObject, "value", out);
return true;
}
stock bool:JSONGetArrayArray(&Handle:array, idx, &Handle:out)
{
new Handle:m_hObject = GetArrayCell(array, idx);
decl JSONType:m_eType;
GetTrieValue(m_hObject, "type", m_eType);
if(m_eType != Type_Array)
return false;
GetTrieValue(m_hObject, "value", out);
return true;
}
stock bool:JSONGetArrayBoolean(&Handle:array, idx, &bool:value)
{
new Handle:m_hObject = GetArrayCell(array, idx);
decl JSONType:m_eType;
GetTrieValue(m_hObject, "type", m_eType);
if(m_eType != Type_Boolean)
return false;
GetTrieValue(m_hObject, "value", value);
return true;
}
stock bool:JSONGetArrayInteger(&Handle:array, idx, &value)
{
new Handle:m_hObject = GetArrayCell(array, idx);
decl JSONType:m_eType;
GetTrieValue(m_hObject, "type", m_eType);
if(m_eType != Type_Integer)
return false;
GetTrieValue(m_hObject, "value", value);
return true;
}
stock bool:JSONGetArrayFloat(&Handle:array, idx, &Float:value)
{
new Handle:m_hObject = GetArrayCell(array, idx);
decl JSONType:m_eType;
GetTrieValue(m_hObject, "type", m_eType);
// For compatibility reasons only, but you should follow strict types
if(m_eType != Type_Float && m_eType != Type_Integer)
return false;
if(m_eType == Type_Integer)
{
decl m_iValue;
GetTrieValue(m_hObject, "value", m_iValue);
value = float(m_iValue);
}
else
GetTrieValue(m_hObject, "value", value);
return true;
}
stock JSONIgnore(const String:json[])
{
new m_iLength = strlen(json);
for(new i=0;i<m_iLength;++i)
if(json[i] != ' ' && json[i] != '\t' && json[i] != ':' && json[i] != '\n' && json[i] != '\r' && json[i] != ',')
return i;
return -1;
}
stock JSONIsNumeric(const String:string[])
{
new m_iLength = strlen(string);
new i = 0;
if(string[0] == '-')
i = 1;
for(;i<m_iLength;++i)
if(!(48<=string[i]<=57))
return false;
return true;
}
stock bool:GetJSONString(const String:json[], &start, &end)
{
decl m_iCharPos;
new m_iPos = JSONIgnore(json);
if(json[m_iPos] == '"')
++m_iPos;
start = m_iPos;
if(json[m_iPos-1] == '"')
{
while((m_iCharPos = FindCharInString(json[m_iPos], '"')) != -1)
{
m_iPos += m_iCharPos;
if(json[m_iPos-1] == '\\')
continue;
end = m_iPos;
return true;
}
}
new m_iLength = strlen(json);
for(;m_iPos<m_iLength;++m_iPos)
{
if(m_iPos != 0 && !(48<=json[m_iPos]<=57) && !(97<=json[m_iPos]<=122) && json[m_iPos] != '-' && json[m_iPos] != '.')
{
end = m_iPos;
return true;
}
}
return false;
}
stock DestroyJSON(&Handle:json)
{
new Handle:m_hKeyArray = INVALID_HANDLE;
if(!GetTrieValue(json, "json_key_array", m_hKeyArray))
{
CloseHandle(json);
return;
}
new m_iKeys = GetArraySize(m_hKeyArray);
decl String:m_szKey[512];
decl Handle:m_hObject;
for(new i=0;i<m_iKeys;++i)
{
GetArrayString(m_hKeyArray, i, m_szKey, sizeof(m_szKey));
if(!GetTrieValue(json, m_szKey, m_hObject))
continue;
decl JSONType:m_eType;
GetTrieValue(m_hObject, "type", m_eType);
if(m_eType == Type_Object)
{
new Handle:m_hValue;
GetTrieValue(m_hObject, "value", m_hValue);
DestroyJSON(m_hValue);
} else if(m_eType == Type_Array)
{
new Handle:m_hValue;
GetTrieValue(m_hObject, "value", m_hValue);
DestroyJSONArray(m_hValue);
}
else
CloseHandle(m_hObject);
}
CloseHandle(m_hKeyArray);
CloseHandle(json);
}
stock DestroyJSONArray(&Handle:array)
{
new m_iLength = GetArraySize(array);
for(new i=0;i<m_iLength;++i)
{
new Handle:m_hItem;
m_hItem = GetArrayCell(array, i);
decl JSONType:m_eType;
GetTrieValue(m_hItem, "type", m_eType);
if(m_eType == Type_Object)
{
new Handle:m_hValue;
GetTrieValue(m_hItem, "value", m_hValue);
DestroyJSON(m_hValue);
} else if(m_eType == Type_Array)
{
new Handle:m_hValue;
GetTrieValue(m_hItem, "value", m_hValue);
DestroyJSONArray(m_hValue);
}
else
CloseHandle(m_hItem);
}
CloseHandle(array);
}

View File

@@ -0,0 +1,53 @@
// File Name : IsTargetInSightRange.inc
// File Version : 1.1
// File Updated date : 03-07-2013
/*
*Thanks to Javalia. he has helped to solve my question.
*/
stock bool:IsTargetInSightRange(client, target, Float:angle=90.0, Float:distance=0.0, bool:heightcheck=true, bool:negativeangle=false)
{
if(angle > 360.0 || angle < 0.0)
ThrowError("Angle Max : 360 & Min : 0. %d isn't proper angle.", angle);
if(!IsValidClient(client))
ThrowError("Client is not Alive.");
if(!IsValidClient(target))
ThrowError("Target is not Alive.");
decl Float:clientpos[3], Float:targetpos[3], Float:anglevector[3], Float:targetvector[3], Float:resultangle, Float:resultdistance;
GetClientEyeAngles(client, anglevector);
anglevector[0] = anglevector[2] = 0.0;
GetAngleVectors(anglevector, anglevector, NULL_VECTOR, NULL_VECTOR);
NormalizeVector(anglevector, anglevector);
if(negativeangle)
NegateVector(anglevector);
GetClientAbsOrigin(client, clientpos);
GetClientAbsOrigin(target, targetpos);
if(heightcheck && distance > 0)
resultdistance = GetVectorDistance(clientpos, targetpos);
clientpos[2] = targetpos[2] = 0.0;
MakeVectorFromPoints(clientpos, targetpos, targetvector);
NormalizeVector(targetvector, targetvector);
resultangle = RadToDeg(ArcCosine(GetVectorDotProduct(targetvector, anglevector)));
if(resultangle <= angle/2)
{
if(distance > 0)
{
if(!heightcheck)
resultdistance = GetVectorDistance(clientpos, targetpos);
if(distance >= resultdistance)
return true;
else
return false;
}
else
return true;
}
else
return false;
}

View File

@@ -0,0 +1,381 @@
#if defined _SteamWorks_Included
#endinput
#endif
#define _SteamWorks_Included
/* results from UserHasLicenseForApp */
enum EUserHasLicenseForAppResult
{
k_EUserHasLicenseResultHasLicense = 0, // User has a license for specified app
k_EUserHasLicenseResultDoesNotHaveLicense = 1, // User does not have a license for the specified app
k_EUserHasLicenseResultNoAuth = 2, // User has not been authenticated
};
/* General result codes */
enum EResult
{
k_EResultOK = 1, // success
k_EResultFail = 2, // generic failure
k_EResultNoConnection = 3, // no/failed network connection
// k_EResultNoConnectionRetry = 4, // OBSOLETE - removed
k_EResultInvalidPassword = 5, // password/ticket is invalid
k_EResultLoggedInElsewhere = 6, // same user logged in elsewhere
k_EResultInvalidProtocolVer = 7, // protocol version is incorrect
k_EResultInvalidParam = 8, // a parameter is incorrect
k_EResultFileNotFound = 9, // file was not found
k_EResultBusy = 10, // called method busy - action not taken
k_EResultInvalidState = 11, // called object was in an invalid state
k_EResultInvalidName = 12, // name is invalid
k_EResultInvalidEmail = 13, // email is invalid
k_EResultDuplicateName = 14, // name is not unique
k_EResultAccessDenied = 15, // access is denied
k_EResultTimeout = 16, // operation timed out
k_EResultBanned = 17, // VAC2 banned
k_EResultAccountNotFound = 18, // account not found
k_EResultInvalidSteamID = 19, // steamID is invalid
k_EResultServiceUnavailable = 20, // The requested service is currently unavailable
k_EResultNotLoggedOn = 21, // The user is not logged on
k_EResultPending = 22, // Request is pending (may be in process, or waiting on third party)
k_EResultEncryptionFailure = 23, // Encryption or Decryption failed
k_EResultInsufficientPrivilege = 24, // Insufficient privilege
k_EResultLimitExceeded = 25, // Too much of a good thing
k_EResultRevoked = 26, // Access has been revoked (used for revoked guest passes)
k_EResultExpired = 27, // License/Guest pass the user is trying to access is expired
k_EResultAlreadyRedeemed = 28, // Guest pass has already been redeemed by account, cannot be acked again
k_EResultDuplicateRequest = 29, // The request is a duplicate and the action has already occurred in the past, ignored this time
k_EResultAlreadyOwned = 30, // All the games in this guest pass redemption request are already owned by the user
k_EResultIPNotFound = 31, // IP address not found
k_EResultPersistFailed = 32, // failed to write change to the data store
k_EResultLockingFailed = 33, // failed to acquire access lock for this operation
k_EResultLogonSessionReplaced = 34,
k_EResultConnectFailed = 35,
k_EResultHandshakeFailed = 36,
k_EResultIOFailure = 37,
k_EResultRemoteDisconnect = 38,
k_EResultShoppingCartNotFound = 39, // failed to find the shopping cart requested
k_EResultBlocked = 40, // a user didn't allow it
k_EResultIgnored = 41, // target is ignoring sender
k_EResultNoMatch = 42, // nothing matching the request found
k_EResultAccountDisabled = 43,
k_EResultServiceReadOnly = 44, // this service is not accepting content changes right now
k_EResultAccountNotFeatured = 45, // account doesn't have value, so this feature isn't available
k_EResultAdministratorOK = 46, // allowed to take this action, but only because requester is admin
k_EResultContentVersion = 47, // A Version mismatch in content transmitted within the Steam protocol.
k_EResultTryAnotherCM = 48, // The current CM can't service the user making a request, user should try another.
k_EResultPasswordRequiredToKickSession = 49,// You are already logged in elsewhere, this cached credential login has failed.
k_EResultAlreadyLoggedInElsewhere = 50, // You are already logged in elsewhere, you must wait
k_EResultSuspended = 51, // Long running operation (content download) suspended/paused
k_EResultCancelled = 52, // Operation canceled (typically by user: content download)
k_EResultDataCorruption = 53, // Operation canceled because data is ill formed or unrecoverable
k_EResultDiskFull = 54, // Operation canceled - not enough disk space.
k_EResultRemoteCallFailed = 55, // an remote call or IPC call failed
k_EResultPasswordUnset = 56, // Password could not be verified as it's unset server side
k_EResultExternalAccountUnlinked = 57, // External account (PSN, Facebook...) is not linked to a Steam account
k_EResultPSNTicketInvalid = 58, // PSN ticket was invalid
k_EResultExternalAccountAlreadyLinked = 59, // External account (PSN, Facebook...) is already linked to some other account, must explicitly request to replace/delete the link first
k_EResultRemoteFileConflict = 60, // The sync cannot resume due to a conflict between the local and remote files
k_EResultIllegalPassword = 61, // The requested new password is not legal
k_EResultSameAsPreviousValue = 62, // new value is the same as the old one ( secret question and answer )
k_EResultAccountLogonDenied = 63, // account login denied due to 2nd factor authentication failure
k_EResultCannotUseOldPassword = 64, // The requested new password is not legal
k_EResultInvalidLoginAuthCode = 65, // account login denied due to auth code invalid
k_EResultAccountLogonDeniedNoMail = 66, // account login denied due to 2nd factor auth failure - and no mail has been sent
k_EResultHardwareNotCapableOfIPT = 67, //
k_EResultIPTInitError = 68, //
k_EResultParentalControlRestricted = 69, // operation failed due to parental control restrictions for current user
k_EResultFacebookQueryError = 70, // Facebook query returned an error
k_EResultExpiredLoginAuthCode = 71, // account login denied due to auth code expired
k_EResultIPLoginRestrictionFailed = 72,
k_EResultAccountLockedDown = 73,
k_EResultAccountLogonDeniedVerifiedEmailRequired = 74,
k_EResultNoMatchingURL = 75,
k_EResultBadResponse = 76, // parse failure, missing field, etc.
k_EResultRequirePasswordReEntry = 77, // The user cannot complete the action until they re-enter their password
k_EResultValueOutOfRange = 78, // the value entered is outside the acceptable range
k_EResultUnexpectedError = 79, // something happened that we didn't expect to ever happen
k_EResultDisabled = 80, // The requested service has been configured to be unavailable
k_EResultInvalidCEGSubmission = 81, // The set of files submitted to the CEG server are not valid !
k_EResultRestrictedDevice = 82, // The device being used is not allowed to perform this action
k_EResultRegionLocked = 83, // The action could not be complete because it is region restricted
k_EResultRateLimitExceeded = 84, // Temporary rate limit exceeded, try again later, different from k_EResultLimitExceeded which may be permanent
k_EResultAccountLoginDeniedNeedTwoFactor = 85, // Need two-factor code to login
k_EResultItemDeleted = 86, // The thing we're trying to access has been deleted
k_EResultAccountLoginDeniedThrottle = 87, // login attempt failed, try to throttle response to possible attacker
k_EResultTwoFactorCodeMismatch = 88, // two factor code mismatch
k_EResultTwoFactorActivationCodeMismatch = 89, // activation code for two-factor didn't match
k_EResultAccountAssociatedToMultiplePartners = 90, // account has been associated with multiple partners
k_EResultNotModified = 91, // data not modified
k_EResultNoMobileDevice = 92, // the account does not have a mobile device associated with it
k_EResultTimeNotSynced = 93, // the time presented is out of range or tolerance
k_EResultSmsCodeFailed = 94, // SMS code failure (no match, none pending, etc.)
k_EResultAccountLimitExceeded = 95, // Too many accounts access this resource
k_EResultAccountActivityLimitExceeded = 96, // Too many changes to this account
k_EResultPhoneActivityLimitExceeded = 97, // Too many changes to this phone
k_EResultRefundToWallet = 98, // Cannot refund to payment method, must use wallet
k_EResultEmailSendFailure = 99, // Cannot send an email
k_EResultNotSettled = 100, // Can't perform operation till payment has settled
k_EResultNeedCaptcha = 101, // Needs to provide a valid captcha
k_EResultGSLTDenied = 102, // a game server login token owned by this token's owner has been banned
k_EResultGSOwnerDenied = 103, // game server owner is denied for other reason (account lock, community ban, vac ban, missing phone)
k_EResultInvalidItemType = 104 // the type of thing we were requested to act on is invalid
};
/* This enum is used in client API methods, do not re-number existing values. */
enum EHTTPMethod
{
k_EHTTPMethodInvalid = 0,
k_EHTTPMethodGET,
k_EHTTPMethodHEAD,
k_EHTTPMethodPOST,
k_EHTTPMethodPUT,
k_EHTTPMethodDELETE,
k_EHTTPMethodOPTIONS,
k_EHTTPMethodPATCH,
// The remaining HTTP methods are not yet supported, per rfc2616 section 5.1.1 only GET and HEAD are required for
// a compliant general purpose server. We'll likely add more as we find uses for them.
// k_EHTTPMethodTRACE,
// k_EHTTPMethodCONNECT
};
/* HTTP Status codes that the server can send in response to a request, see rfc2616 section 10.3 for descriptions
of each of these. */
enum EHTTPStatusCode
{
// Invalid status code (this isn't defined in HTTP, used to indicate unset in our code)
k_EHTTPStatusCodeInvalid = 0,
// Informational codes
k_EHTTPStatusCode100Continue = 100,
k_EHTTPStatusCode101SwitchingProtocols = 101,
// Success codes
k_EHTTPStatusCode200OK = 200,
k_EHTTPStatusCode201Created = 201,
k_EHTTPStatusCode202Accepted = 202,
k_EHTTPStatusCode203NonAuthoritative = 203,
k_EHTTPStatusCode204NoContent = 204,
k_EHTTPStatusCode205ResetContent = 205,
k_EHTTPStatusCode206PartialContent = 206,
// Redirection codes
k_EHTTPStatusCode300MultipleChoices = 300,
k_EHTTPStatusCode301MovedPermanently = 301,
k_EHTTPStatusCode302Found = 302,
k_EHTTPStatusCode303SeeOther = 303,
k_EHTTPStatusCode304NotModified = 304,
k_EHTTPStatusCode305UseProxy = 305,
//k_EHTTPStatusCode306Unused = 306, (used in old HTTP spec, now unused in 1.1)
k_EHTTPStatusCode307TemporaryRedirect = 307,
// Error codes
k_EHTTPStatusCode400BadRequest = 400,
k_EHTTPStatusCode401Unauthorized = 401, // You probably want 403 or something else. 401 implies you're sending a WWW-Authenticate header and the client can sent an Authorization header in response.
k_EHTTPStatusCode402PaymentRequired = 402, // This is reserved for future HTTP specs, not really supported by clients
k_EHTTPStatusCode403Forbidden = 403,
k_EHTTPStatusCode404NotFound = 404,
k_EHTTPStatusCode405MethodNotAllowed = 405,
k_EHTTPStatusCode406NotAcceptable = 406,
k_EHTTPStatusCode407ProxyAuthRequired = 407,
k_EHTTPStatusCode408RequestTimeout = 408,
k_EHTTPStatusCode409Conflict = 409,
k_EHTTPStatusCode410Gone = 410,
k_EHTTPStatusCode411LengthRequired = 411,
k_EHTTPStatusCode412PreconditionFailed = 412,
k_EHTTPStatusCode413RequestEntityTooLarge = 413,
k_EHTTPStatusCode414RequestURITooLong = 414,
k_EHTTPStatusCode415UnsupportedMediaType = 415,
k_EHTTPStatusCode416RequestedRangeNotSatisfiable = 416,
k_EHTTPStatusCode417ExpectationFailed = 417,
k_EHTTPStatusCode4xxUnknown = 418, // 418 is reserved, so we'll use it to mean unknown
k_EHTTPStatusCode429TooManyRequests = 429,
// Server error codes
k_EHTTPStatusCode500InternalServerError = 500,
k_EHTTPStatusCode501NotImplemented = 501,
k_EHTTPStatusCode502BadGateway = 502,
k_EHTTPStatusCode503ServiceUnavailable = 503,
k_EHTTPStatusCode504GatewayTimeout = 504,
k_EHTTPStatusCode505HTTPVersionNotSupported = 505,
k_EHTTPStatusCode5xxUnknown = 599,
};
/* list of possible return values from the ISteamGameCoordinator API */
enum EGCResults
{
k_EGCResultOK = 0,
k_EGCResultNoMessage = 1, // There is no message in the queue
k_EGCResultBufferTooSmall = 2, // The buffer is too small for the requested message
k_EGCResultNotLoggedOn = 3, // The client is not logged onto Steam
k_EGCResultInvalidMessage = 4, // Something was wrong with the message being sent with SendMessage
};
native bool SteamWorks_IsVACEnabled();
native bool SteamWorks_GetPublicIP(int ipaddr[4]);
native int SteamWorks_GetPublicIPCell();
native bool SteamWorks_IsLoaded();
native bool SteamWorks_SetGameData(const char[] sData);
native bool SteamWorks_SetGameDescription(const char[] sDesc);
native bool SteamWorks_SetMapName(const char[] sMapName);
native bool SteamWorks_IsConnected();
native bool SteamWorks_SetRule(const char[] sKey, const char[] sValue);
native bool SteamWorks_ClearRules();
native bool SteamWorks_GetUserGroupStatus(int client, int groupid);
native bool SteamWorks_GetUserGroupStatusAuthID(int authid, int groupid);
native EUserHasLicenseForAppResult SteamWorks_HasLicenseForApp(int client, int app);
native EUserHasLicenseForAppResult SteamWorks_HasLicenseForAppId(int authid, int app);
native int SteamWorks_GetClientSteamID(int client, char[] sSteamID, int length);
native bool SteamWorks_RequestStatsAuthID(int authid, int appid);
native bool SteamWorks_RequestStats(int client, int appid);
native bool SteamWorks_GetStatCell(int client, const char[] sKey, int &value);
native bool SteamWorks_GetStatAuthIDCell(int authid, const char[] sKey, int &value);
native bool SteamWorks_GetStatFloat(int client, const char[] sKey, float &value);
native bool SteamWorks_GetStatAuthIDFloat(int authid, const char[] sKey, float &value);
native Handle SteamWorks_CreateHTTPRequest(EHTTPMethod method, const char[] sURL);
native bool SteamWorks_SetHTTPRequestContextValue(Handle hHandle, any data1, any data2=0);
native bool SteamWorks_SetHTTPRequestNetworkActivityTimeout(Handle hHandle, int timeout);
native bool SteamWorks_SetHTTPRequestHeaderValue(Handle hHandle, const char[] sName, const char[] sValue);
native bool SteamWorks_SetHTTPRequestGetOrPostParameter(Handle hHandle, const char[] sName, const char[] sValue);
native bool SteamWorks_SetHTTPRequestUserAgentInfo(Handle hHandle, const char[] sUserAgentInfo);
native bool SteamWorks_SetHTTPRequestRequiresVerifiedCertificate(Handle hHandle, bool bRequireVerifiedCertificate);
native bool SteamWorks_SetHTTPRequestAbsoluteTimeoutMS(Handle hHandle, int unMilliseconds);
typeset SteamWorksHTTPRequestCompleted
{
function void (Handle hRequest, bool bFailure, bool bRequestSuccessful, EHTTPStatusCode eStatusCode);
function void (Handle hRequest, bool bFailure, bool bRequestSuccessful, EHTTPStatusCode eStatusCode, any data1);
function void (Handle hRequest, bool bFailure, bool bRequestSuccessful, EHTTPStatusCode eStatusCode, any data1, any data2);
};
typeset SteamWorksHTTPHeadersReceived
{
function void (Handle hRequest, bool bFailure);
function void (Handle hRequest, bool bFailure, any data1);
function void (Handle hRequest, bool bFailure, any data1, any data2);
};
typeset SteamWorksHTTPDataReceived
{
function void (Handle hRequest, bool bFailure, int offset, int bytesreceived);
function void (Handle hRequest, bool bFailure, int offset, int bytesreceived, any data1);
function void (Handle hRequest, bool bFailure, int offset, int bytesreceived, any data1, any data2);
};
typeset SteamWorksHTTPBodyCallback
{
function void (const char[] sData);
function void (const char[] sData, any value);
function void (const int[] data, any value, int datalen);
};
native bool SteamWorks_SetHTTPCallbacks(Handle hHandle, SteamWorksHTTPRequestCompleted fCompleted = INVALID_FUNCTION, SteamWorksHTTPHeadersReceived fHeaders = INVALID_FUNCTION, SteamWorksHTTPDataReceived fData = INVALID_FUNCTION, Handle hCalling = null);
native bool SteamWorks_SendHTTPRequest(Handle hRequest);
native bool SteamWorks_SendHTTPRequestAndStreamResponse(Handle hRequest);
native bool SteamWorks_DeferHTTPRequest(Handle hRequest);
native bool SteamWorks_PrioritizeHTTPRequest(Handle hRequest);
native bool SteamWorks_GetHTTPResponseHeaderSize(Handle hRequest, const char[] sHeader, int &size);
native bool SteamWorks_GetHTTPResponseHeaderValue(Handle hRequest, const char[] sHeader, char[] sValue, int size);
native bool SteamWorks_GetHTTPResponseBodySize(Handle hRequest, int &size);
native bool SteamWorks_GetHTTPResponseBodyData(Handle hRequest, char[] sBody, int length);
native bool SteamWorks_GetHTTPStreamingResponseBodyData(Handle hRequest, int cOffset, char[] sBody, int length);
native bool SteamWorks_GetHTTPDownloadProgressPct(Handle hRequest, float &percent);
native bool SteamWorks_GetHTTPRequestWasTimedOut(Handle hRequest, bool &bWasTimedOut);
native bool SteamWorks_SetHTTPRequestRawPostBody(Handle hRequest, const char[] sContentType, const char[] sBody, int bodylen);
native bool SteamWorks_SetHTTPRequestRawPostBodyFromFile(Handle hRequest, const char[] sContentType, const char[] sFileName);
native bool SteamWorks_GetHTTPResponseBodyCallback(Handle hRequest, SteamWorksHTTPBodyCallback fCallback, any data = 0, Handle hPlugin = null);
native bool SteamWorks_WriteHTTPResponseBodyToFile(Handle hRequest, const char[] sFileName);
forward void SW_OnValidateClient(int ownerauthid, int authid);
forward void SteamWorks_OnValidateClient(int ownerauthid, int authid);
forward void SteamWorks_SteamServersConnected();
forward void SteamWorks_SteamServersConnectFailure(EResult result);
forward void SteamWorks_SteamServersDisconnected(EResult result);
forward Action SteamWorks_RestartRequested();
forward void SteamWorks_TokenRequested(char[] sToken, int maxlen);
forward void SteamWorks_OnClientGroupStatus(int authid, int groupid, bool isMember, bool isOfficer);
forward EGCResults SteamWorks_GCSendMessage(int unMsgType, const char[] pubData, int cubData);
forward void SteamWorks_GCMsgAvailable(int cubData);
forward EGCResults SteamWorks_GCRetrieveMessage(int punMsgType, const char[] pubDest, int cubDest, int pcubMsgSize);
native EGCResults SteamWorks_SendMessageToGC(int unMsgType, const char[] pubData, int cubData);
public Extension __ext_SteamWorks =
{
name = "SteamWorks",
file = "SteamWorks.ext",
#if defined AUTOLOAD_EXTENSIONS
autoload = 1,
#else
autoload = 0,
#endif
#if defined REQUIRE_EXTENSIONS
required = 1,
#else
required = 0,
#endif
};
#if !defined REQUIRE_EXTENSIONS
public void __ext_SteamWorks_SetNTVOptional()
{
MarkNativeAsOptional("SteamWorks_IsVACEnabled");
MarkNativeAsOptional("SteamWorks_GetPublicIP");
MarkNativeAsOptional("SteamWorks_GetPublicIPCell");
MarkNativeAsOptional("SteamWorks_IsLoaded");
MarkNativeAsOptional("SteamWorks_SetGameData");
MarkNativeAsOptional("SteamWorks_SetGameDescription");
MarkNativeAsOptional("SteamWorks_IsConnected");
MarkNativeAsOptional("SteamWorks_SetRule");
MarkNativeAsOptional("SteamWorks_ClearRules");
MarkNativeAsOptional("SteamWorks_GetUserGroupStatus");
MarkNativeAsOptional("SteamWorks_GetUserGroupStatusAuthID");
MarkNativeAsOptional("SteamWorks_HasLicenseForApp");
MarkNativeAsOptional("SteamWorks_HasLicenseForAppId");
MarkNativeAsOptional("SteamWorks_GetClientSteamID");
MarkNativeAsOptional("SteamWorks_RequestStatsAuthID");
MarkNativeAsOptional("SteamWorks_RequestStats");
MarkNativeAsOptional("SteamWorks_GetStatCell");
MarkNativeAsOptional("SteamWorks_GetStatAuthIDCell");
MarkNativeAsOptional("SteamWorks_GetStatFloat");
MarkNativeAsOptional("SteamWorks_GetStatAuthIDFloat");
MarkNativeAsOptional("SteamWorks_SendMessageToGC");
MarkNativeAsOptional("SteamWorks_CreateHTTPRequest");
MarkNativeAsOptional("SteamWorks_SetHTTPRequestContextValue");
MarkNativeAsOptional("SteamWorks_SetHTTPRequestNetworkActivityTimeout");
MarkNativeAsOptional("SteamWorks_SetHTTPRequestHeaderValue");
MarkNativeAsOptional("SteamWorks_SetHTTPRequestGetOrPostParameter");
MarkNativeAsOptional("SteamWorks_SetHTTPRequestUserAgentInfo");
MarkNativeAsOptional("SteamWorks_SetHTTPRequestRequiresVerifiedCertificate");
MarkNativeAsOptional("SteamWorks_SetHTTPRequestAbsoluteTimeoutMS");
MarkNativeAsOptional("SteamWorks_SetHTTPCallbacks");
MarkNativeAsOptional("SteamWorks_SendHTTPRequest");
MarkNativeAsOptional("SteamWorks_SendHTTPRequestAndStreamResponse");
MarkNativeAsOptional("SteamWorks_DeferHTTPRequest");
MarkNativeAsOptional("SteamWorks_PrioritizeHTTPRequest");
MarkNativeAsOptional("SteamWorks_GetHTTPResponseHeaderSize");
MarkNativeAsOptional("SteamWorks_GetHTTPResponseHeaderValue");
MarkNativeAsOptional("SteamWorks_GetHTTPResponseBodySize");
MarkNativeAsOptional("SteamWorks_GetHTTPResponseBodyData");
MarkNativeAsOptional("SteamWorks_GetHTTPStreamingResponseBodyData");
MarkNativeAsOptional("SteamWorks_GetHTTPDownloadProgressPct");
MarkNativeAsOptional("SteamWorks_SetHTTPRequestRawPostBody");
MarkNativeAsOptional("SteamWorks_SetHTTPRequestRawPostBodyFromFile");
MarkNativeAsOptional("SteamWorks_GetHTTPResponseBodyCallback");
MarkNativeAsOptional("SteamWorks_WriteHTTPResponseBodyToFile");
}
#endif

View File

@@ -0,0 +1,376 @@
#if defined _SteamWorks_Included
#endinput
#endif
#define _SteamWorks_Included
/* results from UserHasLicenseForApp */
enum EUserHasLicenseForAppResult
{
k_EUserHasLicenseResultHasLicense = 0, // User has a license for specified app
k_EUserHasLicenseResultDoesNotHaveLicense = 1, // User does not have a license for the specified app
k_EUserHasLicenseResultNoAuth = 2, // User has not been authenticated
};
/* General result codes */
enum EResult
{
k_EResultOK = 1, // success
k_EResultFail = 2, // generic failure
k_EResultNoConnection = 3, // no/failed network connection
// k_EResultNoConnectionRetry = 4, // OBSOLETE - removed
k_EResultInvalidPassword = 5, // password/ticket is invalid
k_EResultLoggedInElsewhere = 6, // same user logged in elsewhere
k_EResultInvalidProtocolVer = 7, // protocol version is incorrect
k_EResultInvalidParam = 8, // a parameter is incorrect
k_EResultFileNotFound = 9, // file was not found
k_EResultBusy = 10, // called method busy - action not taken
k_EResultInvalidState = 11, // called object was in an invalid state
k_EResultInvalidName = 12, // name is invalid
k_EResultInvalidEmail = 13, // email is invalid
k_EResultDuplicateName = 14, // name is not unique
k_EResultAccessDenied = 15, // access is denied
k_EResultTimeout = 16, // operation timed out
k_EResultBanned = 17, // VAC2 banned
k_EResultAccountNotFound = 18, // account not found
k_EResultInvalidSteamID = 19, // steamID is invalid
k_EResultServiceUnavailable = 20, // The requested service is currently unavailable
k_EResultNotLoggedOn = 21, // The user is not logged on
k_EResultPending = 22, // Request is pending (may be in process, or waiting on third party)
k_EResultEncryptionFailure = 23, // Encryption or Decryption failed
k_EResultInsufficientPrivilege = 24, // Insufficient privilege
k_EResultLimitExceeded = 25, // Too much of a good thing
k_EResultRevoked = 26, // Access has been revoked (used for revoked guest passes)
k_EResultExpired = 27, // License/Guest pass the user is trying to access is expired
k_EResultAlreadyRedeemed = 28, // Guest pass has already been redeemed by account, cannot be acked again
k_EResultDuplicateRequest = 29, // The request is a duplicate and the action has already occurred in the past, ignored this time
k_EResultAlreadyOwned = 30, // All the games in this guest pass redemption request are already owned by the user
k_EResultIPNotFound = 31, // IP address not found
k_EResultPersistFailed = 32, // failed to write change to the data store
k_EResultLockingFailed = 33, // failed to acquire access lock for this operation
k_EResultLogonSessionReplaced = 34,
k_EResultConnectFailed = 35,
k_EResultHandshakeFailed = 36,
k_EResultIOFailure = 37,
k_EResultRemoteDisconnect = 38,
k_EResultShoppingCartNotFound = 39, // failed to find the shopping cart requested
k_EResultBlocked = 40, // a user didn't allow it
k_EResultIgnored = 41, // target is ignoring sender
k_EResultNoMatch = 42, // nothing matching the request found
k_EResultAccountDisabled = 43,
k_EResultServiceReadOnly = 44, // this service is not accepting content changes right now
k_EResultAccountNotFeatured = 45, // account doesn't have value, so this feature isn't available
k_EResultAdministratorOK = 46, // allowed to take this action, but only because requester is admin
k_EResultContentVersion = 47, // A Version mismatch in content transmitted within the Steam protocol.
k_EResultTryAnotherCM = 48, // The current CM can't service the user making a request, user should try another.
k_EResultPasswordRequiredToKickSession = 49,// You are already logged in elsewhere, this cached credential login has failed.
k_EResultAlreadyLoggedInElsewhere = 50, // You are already logged in elsewhere, you must wait
k_EResultSuspended = 51, // Long running operation (content download) suspended/paused
k_EResultCancelled = 52, // Operation canceled (typically by user: content download)
k_EResultDataCorruption = 53, // Operation canceled because data is ill formed or unrecoverable
k_EResultDiskFull = 54, // Operation canceled - not enough disk space.
k_EResultRemoteCallFailed = 55, // an remote call or IPC call failed
k_EResultPasswordUnset = 56, // Password could not be verified as it's unset server side
k_EResultExternalAccountUnlinked = 57, // External account (PSN, Facebook...) is not linked to a Steam account
k_EResultPSNTicketInvalid = 58, // PSN ticket was invalid
k_EResultExternalAccountAlreadyLinked = 59, // External account (PSN, Facebook...) is already linked to some other account, must explicitly request to replace/delete the link first
k_EResultRemoteFileConflict = 60, // The sync cannot resume due to a conflict between the local and remote files
k_EResultIllegalPassword = 61, // The requested new password is not legal
k_EResultSameAsPreviousValue = 62, // new value is the same as the old one ( secret question and answer )
k_EResultAccountLogonDenied = 63, // account login denied due to 2nd factor authentication failure
k_EResultCannotUseOldPassword = 64, // The requested new password is not legal
k_EResultInvalidLoginAuthCode = 65, // account login denied due to auth code invalid
k_EResultAccountLogonDeniedNoMail = 66, // account login denied due to 2nd factor auth failure - and no mail has been sent
k_EResultHardwareNotCapableOfIPT = 67, //
k_EResultIPTInitError = 68, //
k_EResultParentalControlRestricted = 69, // operation failed due to parental control restrictions for current user
k_EResultFacebookQueryError = 70, // Facebook query returned an error
k_EResultExpiredLoginAuthCode = 71, // account login denied due to auth code expired
k_EResultIPLoginRestrictionFailed = 72,
k_EResultAccountLockedDown = 73,
k_EResultAccountLogonDeniedVerifiedEmailRequired = 74,
k_EResultNoMatchingURL = 75,
k_EResultBadResponse = 76, // parse failure, missing field, etc.
k_EResultRequirePasswordReEntry = 77, // The user cannot complete the action until they re-enter their password
k_EResultValueOutOfRange = 78, // the value entered is outside the acceptable range
k_EResultUnexpectedError = 79, // something happened that we didn't expect to ever happen
k_EResultDisabled = 80, // The requested service has been configured to be unavailable
k_EResultInvalidCEGSubmission = 81, // The set of files submitted to the CEG server are not valid !
k_EResultRestrictedDevice = 82, // The device being used is not allowed to perform this action
k_EResultRegionLocked = 83, // The action could not be complete because it is region restricted
k_EResultRateLimitExceeded = 84, // Temporary rate limit exceeded, try again later, different from k_EResultLimitExceeded which may be permanent
k_EResultAccountLoginDeniedNeedTwoFactor = 85, // Need two-factor code to login
k_EResultItemDeleted = 86, // The thing we're trying to access has been deleted
k_EResultAccountLoginDeniedThrottle = 87, // login attempt failed, try to throttle response to possible attacker
k_EResultTwoFactorCodeMismatch = 88, // two factor code mismatch
k_EResultTwoFactorActivationCodeMismatch = 89, // activation code for two-factor didn't match
k_EResultAccountAssociatedToMultiplePartners = 90, // account has been associated with multiple partners
k_EResultNotModified = 91, // data not modified
k_EResultNoMobileDevice = 92, // the account does not have a mobile device associated with it
k_EResultTimeNotSynced = 93, // the time presented is out of range or tolerance
k_EResultSmsCodeFailed = 94, // SMS code failure (no match, none pending, etc.)
k_EResultAccountLimitExceeded = 95, // Too many accounts access this resource
k_EResultAccountActivityLimitExceeded = 96, // Too many changes to this account
k_EResultPhoneActivityLimitExceeded = 97, // Too many changes to this phone
k_EResultRefundToWallet = 98, // Cannot refund to payment method, must use wallet
k_EResultEmailSendFailure = 99, // Cannot send an email
k_EResultNotSettled = 100, // Can't perform operation till payment has settled
k_EResultNeedCaptcha = 101, // Needs to provide a valid captcha
k_EResultGSLTDenied = 102, // a game server login token owned by this token's owner has been banned
k_EResultGSOwnerDenied = 103, // game server owner is denied for other reason (account lock, community ban, vac ban, missing phone)
k_EResultInvalidItemType = 104 // the type of thing we were requested to act on is invalid
};
/* This enum is used in client API methods, do not re-number existing values. */
enum EHTTPMethod
{
k_EHTTPMethodInvalid = 0,
k_EHTTPMethodGET,
k_EHTTPMethodHEAD,
k_EHTTPMethodPOST,
k_EHTTPMethodPUT,
k_EHTTPMethodDELETE,
k_EHTTPMethodOPTIONS,
// The remaining HTTP methods are not yet supported, per rfc2616 section 5.1.1 only GET and HEAD are required for
// a compliant general purpose server. We'll likely add more as we find uses for them.
// k_EHTTPMethodTRACE,
// k_EHTTPMethodCONNECT
};
/* HTTP Status codes that the server can send in response to a request, see rfc2616 section 10.3 for descriptions
of each of these. */
enum EHTTPStatusCode
{
// Invalid status code (this isn't defined in HTTP, used to indicate unset in our code)
k_EHTTPStatusCodeInvalid = 0,
// Informational codes
k_EHTTPStatusCode100Continue = 100,
k_EHTTPStatusCode101SwitchingProtocols = 101,
// Success codes
k_EHTTPStatusCode200OK = 200,
k_EHTTPStatusCode201Created = 201,
k_EHTTPStatusCode202Accepted = 202,
k_EHTTPStatusCode203NonAuthoritative = 203,
k_EHTTPStatusCode204NoContent = 204,
k_EHTTPStatusCode205ResetContent = 205,
k_EHTTPStatusCode206PartialContent = 206,
// Redirection codes
k_EHTTPStatusCode300MultipleChoices = 300,
k_EHTTPStatusCode301MovedPermanently = 301,
k_EHTTPStatusCode302Found = 302,
k_EHTTPStatusCode303SeeOther = 303,
k_EHTTPStatusCode304NotModified = 304,
k_EHTTPStatusCode305UseProxy = 305,
//k_EHTTPStatusCode306Unused = 306, (used in old HTTP spec, now unused in 1.1)
k_EHTTPStatusCode307TemporaryRedirect = 307,
// Error codes
k_EHTTPStatusCode400BadRequest = 400,
k_EHTTPStatusCode401Unauthorized = 401, // You probably want 403 or something else. 401 implies you're sending a WWW-Authenticate header and the client can sent an Authorization header in response.
k_EHTTPStatusCode402PaymentRequired = 402, // This is reserved for future HTTP specs, not really supported by clients
k_EHTTPStatusCode403Forbidden = 403,
k_EHTTPStatusCode404NotFound = 404,
k_EHTTPStatusCode405MethodNotAllowed = 405,
k_EHTTPStatusCode406NotAcceptable = 406,
k_EHTTPStatusCode407ProxyAuthRequired = 407,
k_EHTTPStatusCode408RequestTimeout = 408,
k_EHTTPStatusCode409Conflict = 409,
k_EHTTPStatusCode410Gone = 410,
k_EHTTPStatusCode411LengthRequired = 411,
k_EHTTPStatusCode412PreconditionFailed = 412,
k_EHTTPStatusCode413RequestEntityTooLarge = 413,
k_EHTTPStatusCode414RequestURITooLong = 414,
k_EHTTPStatusCode415UnsupportedMediaType = 415,
k_EHTTPStatusCode416RequestedRangeNotSatisfiable = 416,
k_EHTTPStatusCode417ExpectationFailed = 417,
k_EHTTPStatusCode4xxUnknown = 418, // 418 is reserved, so we'll use it to mean unknown
k_EHTTPStatusCode429TooManyRequests = 429,
// Server error codes
k_EHTTPStatusCode500InternalServerError = 500,
k_EHTTPStatusCode501NotImplemented = 501,
k_EHTTPStatusCode502BadGateway = 502,
k_EHTTPStatusCode503ServiceUnavailable = 503,
k_EHTTPStatusCode504GatewayTimeout = 504,
k_EHTTPStatusCode505HTTPVersionNotSupported = 505,
k_EHTTPStatusCode5xxUnknown = 599,
};
/* list of possible return values from the ISteamGameCoordinator API */
enum EGCResults
{
k_EGCResultOK = 0,
k_EGCResultNoMessage = 1, // There is no message in the queue
k_EGCResultBufferTooSmall = 2, // The buffer is too small for the requested message
k_EGCResultNotLoggedOn = 3, // The client is not logged onto Steam
k_EGCResultInvalidMessage = 4, // Something was wrong with the message being sent with SendMessage
};
native bool:SteamWorks_IsVACEnabled();
native bool:SteamWorks_GetPublicIP(ipaddr[4]);
native SteamWorks_GetPublicIPCell();
native bool:SteamWorks_IsLoaded();
native bool:SteamWorks_SetGameDescription(const String:sDesc[]);
native bool:SteamWorks_SetMapName(const String:sMapName[]);
native bool:SteamWorks_IsConnected();
native bool:SteamWorks_SetRule(const String:sKey[], const String:sValue[]);
native bool:SteamWorks_ClearRules();
native bool:SteamWorks_ForceHeartbeat();
native bool:SteamWorks_GetUserGroupStatus(client, groupid);
native bool:SteamWorks_GetUserGroupStatusAuthID(authid, groupid);
native EUserHasLicenseForAppResult:SteamWorks_HasLicenseForApp(client, app);
native EUserHasLicenseForAppResult:SteamWorks_HasLicenseForAppId(authid, app);
native SteamWorks_GetClientSteamID(client, String:sSteamID[], length);
native bool:SteamWorks_RequestStatsAuthID(authid, appid);
native bool:SteamWorks_RequestStats(client, appid);
native bool:SteamWorks_GetStatCell(client, const String:sKey[], &value);
native bool:SteamWorks_GetStatAuthIDCell(authid, const String:sKey[], &value);
native bool:SteamWorks_GetStatFloat(client, const String:sKey[], &Float:value);
native bool:SteamWorks_GetStatAuthIDFloat(authid, const String:sKey[], &Float:value);
native Handle:SteamWorks_CreateHTTPRequest(EHTTPMethod:method, const String:sURL[]);
native bool:SteamWorks_SetHTTPRequestContextValue(Handle:hHandle, any:data1, any:data2=0);
native bool:SteamWorks_SetHTTPRequestNetworkActivityTimeout(Handle:hHandle, timeout);
native bool:SteamWorks_SetHTTPRequestHeaderValue(Handle:hHandle, const String:sName[], const String:sValue[]);
native bool:SteamWorks_SetHTTPRequestGetOrPostParameter(Handle:hHandle, const String:sName[], const String:sValue[]);
native bool:SteamWorks_SetHTTPRequestUserAgentInfo(Handle:hHandle, const String:sUserAgentInfo[]);
native bool:SteamWorks_SetHTTPRequestRequiresVerifiedCertificate(Handle:hHandle, bool:bRequireVerifiedCertificate);
native bool:SteamWorks_SetHTTPRequestAbsoluteTimeoutMS(Handle:hHandle, unMilliseconds);
funcenum SteamWorksHTTPRequestCompleted
{
public(Handle:hRequest, bool:bFailure, bool:bRequestSuccessful, EHTTPStatusCode:eStatusCode),
public(Handle:hRequest, bool:bFailure, bool:bRequestSuccessful, EHTTPStatusCode:eStatusCode, any:data1),
public(Handle:hRequest, bool:bFailure, bool:bRequestSuccessful, EHTTPStatusCode:eStatusCode, any:data1, any:data2)
};
funcenum SteamWorksHTTPHeadersReceived
{
public(Handle:hRequest, bool:bFailure),
public(Handle:hRequest, bool:bFailure, any:data1),
public(Handle:hRequest, bool:bFailure, any:data1, any:data2)
};
funcenum SteamWorksHTTPDataReceived
{
public(Handle:hRequest, bool:bFailure, offset, bytesreceived),
public(Handle:hRequest, bool:bFailure, offset, bytesreceived, any:data1),
public(Handle:hRequest, bool:bFailure, offset, bytesreceived, any:data1, any:data2)
};
native bool:SteamWorks_SetHTTPCallbacks(Handle:hHandle, SteamWorksHTTPRequestCompleted:fCompleted = INVALID_FUNCTION, SteamWorksHTTPHeadersReceived:fHeaders = INVALID_FUNCTION, SteamWorksHTTPDataReceived:fData = INVALID_FUNCTION, Handle:hCalling = INVALID_HANDLE);
native bool:SteamWorks_SendHTTPRequest(Handle:hRequest);
native bool:SteamWorks_SendHTTPRequestAndStreamResponse(Handle:hRequest);
native bool:SteamWorks_DeferHTTPRequest(Handle:hRequest);
native bool:SteamWorks_PrioritizeHTTPRequest(Handle:hRequest);
native bool:SteamWorks_GetHTTPResponseHeaderSize(Handle:hRequest, const String:sHeader[], &size);
native bool:SteamWorks_GetHTTPResponseHeaderValue(Handle:hRequest, const String:sHeader[], String:sValue[], size);
native bool:SteamWorks_GetHTTPResponseBodySize(Handle:hRequest, &size);
native bool:SteamWorks_GetHTTPResponseBodyData(Handle:hRequest, String:sBody[], length);
native bool:SteamWorks_GetHTTPStreamingResponseBodyData(Handle:hRequest, cOffset, String:sBody[], length);
native bool:SteamWorks_GetHTTPDownloadProgressPct(Handle:hRequest, &Float:percent);
native bool:SteamWorks_GetHTTPRequestWasTimedOut(Handle:hRequest, &bool:bWasTimedOut);
native bool:SteamWorks_SetHTTPRequestRawPostBody(Handle:hRequest, const String:sContentType[], const String:sBody[], bodylen);
funcenum SteamWorksHTTPBodyCallback
{
public(const String:sData[]),
public(const String:sData[], any:value),
public(const data[], any:value, datalen)
};
native bool:SteamWorks_GetHTTPResponseBodyCallback(Handle:hRequest, SteamWorksHTTPBodyCallback:fCallback, any:data = 0, Handle:hPlugin = INVALID_HANDLE);
native bool:SteamWorks_WriteHTTPResponseBodyToFile(Handle:hRequest, const String:sFileName[]);
forward SW_OnValidateClient(ownerauthid, authid);
forward SteamWorks_OnValidateClient(ownerauthid, authid);
forward SteamWorks_SteamServersConnected();
forward SteamWorks_SteamServersConnectFailure(EResult:result);
forward SteamWorks_SteamServersDisconnected(EResult:result);
forward Action:SteamWorks_RestartRequested();
forward SteamWorks_TokenRequested(String:sToken[], maxlen);
forward SteamWorks_OnClientGroupStatus(authid, groupid, bool:isMember, bool:isOfficer);
forward EGCResults:SteamWorks_GCSendMessage(unMsgType, const String:pubData[], cubData);
forward SteamWorks_GCMsgAvailable(cubData);
forward EGCResults:SteamWorks_GCRetrieveMessage(punMsgType, const String:pubDest[], cubDest, pcubMsgSize);
native EGCResults:SteamWorks_SendMessageToGC(unMsgType, const String:pubData[], cubData);
public Extension:__ext_SteamWorks =
{
name = "SteamWorks",
file = "SteamWorks.ext",
#if defined AUTOLOAD_EXTENSIONS
autoload = 1,
#else
autoload = 0,
#endif
#if defined REQUIRE_EXTENSIONS
required = 1,
#else
required = 0,
#endif
};
#if !defined REQUIRE_EXTENSIONS
public __ext_SteamWorks_SetNTVOptional()
{
MarkNativeAsOptional("SteamWorks_IsVACEnabled");
MarkNativeAsOptional("SteamWorks_GetPublicIP");
MarkNativeAsOptional("SteamWorks_GetPublicIPCell");
MarkNativeAsOptional("SteamWorks_IsLoaded");
MarkNativeAsOptional("SteamWorks_SetGameDescription");
MarkNativeAsOptional("SteamWorks_IsConnected");
MarkNativeAsOptional("SteamWorks_SetRule");
MarkNativeAsOptional("SteamWorks_ClearRules");
MarkNativeAsOptional("SteamWorks_ForceHeartbeat");
MarkNativeAsOptional("SteamWorks_GetUserGroupStatus");
MarkNativeAsOptional("SteamWorks_GetUserGroupStatusAuthID");
MarkNativeAsOptional("SteamWorks_HasLicenseForApp");
MarkNativeAsOptional("SteamWorks_HasLicenseForAppId");
MarkNativeAsOptional("SteamWorks_GetClientSteamID");
MarkNativeAsOptional("SteamWorks_RequestStatsAuthID");
MarkNativeAsOptional("SteamWorks_RequestStats");
MarkNativeAsOptional("SteamWorks_GetStatCell");
MarkNativeAsOptional("SteamWorks_GetStatAuthIDCell");
MarkNativeAsOptional("SteamWorks_GetStatFloat");
MarkNativeAsOptional("SteamWorks_GetStatAuthIDFloat");
MarkNativeAsOptional("SteamWorks_SendMessageToGC");
MarkNativeAsOptional("SteamWorks_CreateHTTPRequest");
MarkNativeAsOptional("SteamWorks_SetHTTPRequestContextValue");
MarkNativeAsOptional("SteamWorks_SetHTTPRequestNetworkActivityTimeout");
MarkNativeAsOptional("SteamWorks_SetHTTPRequestHeaderValue");
MarkNativeAsOptional("SteamWorks_SetHTTPRequestGetOrPostParameter");
MarkNativeAsOptional("SteamWorks_SetHTTPCallbacks");
MarkNativeAsOptional("SteamWorks_SendHTTPRequest");
MarkNativeAsOptional("SteamWorks_SendHTTPRequestAndStreamResponse");
MarkNativeAsOptional("SteamWorks_DeferHTTPRequest");
MarkNativeAsOptional("SteamWorks_PrioritizeHTTPRequest");
MarkNativeAsOptional("SteamWorks_GetHTTPResponseHeaderSize");
MarkNativeAsOptional("SteamWorks_GetHTTPResponseHeaderValue");
MarkNativeAsOptional("SteamWorks_GetHTTPResponseBodySize");
MarkNativeAsOptional("SteamWorks_GetHTTPResponseBodyData");
MarkNativeAsOptional("SteamWorks_GetHTTPStreamingResponseBodyData");
MarkNativeAsOptional("SteamWorks_GetHTTPDownloadProgressPct");
MarkNativeAsOptional("SteamWorks_SetHTTPRequestRawPostBody");
MarkNativeAsOptional("SteamWorks_GetHTTPResponseBodyCallback");
MarkNativeAsOptional("SteamWorks_WriteHTTPResponseBodyToFile");
}
#endif

832
scripting/include/admin.inc Normal file
View File

@@ -0,0 +1,832 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _admin_included
#endinput
#endif
#define _admin_included
/**
* Access levels (flags) for admins.
*/
enum AdminFlag
{
Admin_Reservation = 0, /**< Reserved slot */
Admin_Generic, /**< Generic admin abilities */
Admin_Kick, /**< Kick another user */
Admin_Ban, /**< Ban another user */
Admin_Unban, /**< Unban another user */
Admin_Slay, /**< Slay/kill/damage another user */
Admin_Changemap, /**< Change the map */
Admin_Convars, /**< Change basic convars */
Admin_Config, /**< Change configuration */
Admin_Chat, /**< Special chat privileges */
Admin_Vote, /**< Special vote privileges */
Admin_Password, /**< Set a server password */
Admin_RCON, /**< Use RCON */
Admin_Cheats, /**< Change sv_cheats and use its commands */
Admin_Root, /**< All access by default */
Admin_Custom1, /**< First custom flag type */
Admin_Custom2, /**< Second custom flag type */
Admin_Custom3, /**< Third custom flag type */
Admin_Custom4, /**< Fourth custom flag type */
Admin_Custom5, /**< Fifth custom flag type */
Admin_Custom6 /**< Sixth custom flag type */
};
#define AdminFlags_TOTAL 21 /**< Total number of admin flags */
/**
* @section Bitwise values definitions for admin flags.
*/
#define ADMFLAG_RESERVATION (1<<0) /**< Convenience macro for Admin_Reservation as a FlagBit */
#define ADMFLAG_GENERIC (1<<1) /**< Convenience macro for Admin_Generic as a FlagBit */
#define ADMFLAG_KICK (1<<2) /**< Convenience macro for Admin_Kick as a FlagBit */
#define ADMFLAG_BAN (1<<3) /**< Convenience macro for Admin_Ban as a FlagBit */
#define ADMFLAG_UNBAN (1<<4) /**< Convenience macro for Admin_Unban as a FlagBit */
#define ADMFLAG_SLAY (1<<5) /**< Convenience macro for Admin_Slay as a FlagBit */
#define ADMFLAG_CHANGEMAP (1<<6) /**< Convenience macro for Admin_Changemap as a FlagBit */
#define ADMFLAG_CONVARS (1<<7) /**< Convenience macro for Admin_Convars as a FlagBit */
#define ADMFLAG_CONFIG (1<<8) /**< Convenience macro for Admin_Config as a FlagBit */
#define ADMFLAG_CHAT (1<<9) /**< Convenience macro for Admin_Chat as a FlagBit */
#define ADMFLAG_VOTE (1<<10) /**< Convenience macro for Admin_Vote as a FlagBit */
#define ADMFLAG_PASSWORD (1<<11) /**< Convenience macro for Admin_Password as a FlagBit */
#define ADMFLAG_RCON (1<<12) /**< Convenience macro for Admin_RCON as a FlagBit */
#define ADMFLAG_CHEATS (1<<13) /**< Convenience macro for Admin_Cheats as a FlagBit */
#define ADMFLAG_ROOT (1<<14) /**< Convenience macro for Admin_Root as a FlagBit */
#define ADMFLAG_CUSTOM1 (1<<15) /**< Convenience macro for Admin_Custom1 as a FlagBit */
#define ADMFLAG_CUSTOM2 (1<<16) /**< Convenience macro for Admin_Custom2 as a FlagBit */
#define ADMFLAG_CUSTOM3 (1<<17) /**< Convenience macro for Admin_Custom3 as a FlagBit */
#define ADMFLAG_CUSTOM4 (1<<18) /**< Convenience macro for Admin_Custom4 as a FlagBit */
#define ADMFLAG_CUSTOM5 (1<<19) /**< Convenience macro for Admin_Custom5 as a FlagBit */
#define ADMFLAG_CUSTOM6 (1<<20) /**< Convenience macro for Admin_Custom6 as a FlagBit */
/**
* @endsection
*/
/**
* @section Hardcoded authentication methods
*/
#define AUTHMETHOD_STEAM "steam" /**< SteamID based authentication */
#define AUTHMETHOD_IP "ip" /**< IP based authentication */
#define AUTHMETHOD_NAME "name" /**< Name based authentication */
/**
* @endsection
*/
/**
* Access override types.
*/
enum OverrideType
{
Override_Command = 1, /**< Command */
Override_CommandGroup /**< Command group */
};
/**
* Access override rules.
*/
enum OverrideRule
{
Command_Deny = 0,
Command_Allow = 1
};
/**
* DEPRECATED, do not use.
*/
enum ImmunityType
{
Immunity_Default = 1, /**< Deprecated. */
Immunity_Global /**< Deprecated. */
};
/**
* Identifies a unique entry in the group permissions cache. These are not Handles.
*/
enum GroupId
{
INVALID_GROUP_ID = -1 /**< An invalid/non-existent group */
};
/**
* Identifies a unique entry in the admin permissions cache. These are not Handles.
*/
enum AdminId
{
INVALID_ADMIN_ID = -1 /**< An invalid/non-existent admin */
};
/**
* Methods of computing access permissions.
*/
enum AdmAccessMode
{
Access_Real, /**< Access the user has inherently */
Access_Effective /**< Access the user has from their groups */
};
/**
* Represents the various cache regions.
*/
enum AdminCachePart
{
AdminCache_Overrides = 0, /**< Global overrides */
AdminCache_Groups = 1, /**< All groups (automatically invalidates admins too) */
AdminCache_Admins = 2 /**< All admins */
};
methodmap AdminId {
// Retrieves an admin's user name as made with CreateAdmin().
//
// @note This function can return UTF-8 strings, and will safely chop UTF-8 strings.
//
// @param name String buffer to store name.
// @param maxlength Maximum size of string buffer.
// @return Number of bytes written.
public native void GetUsername(char[] name, int maxlength);
// Binds an admin to an identity for fast lookup later on. The bind must be unique.
//
// @param authMethod Auth method to use, predefined or from RegisterAuthIdentType().
// @param ident String containing the arbitrary, unique identity.
// @return True on success, false if the auth method was not found,
// ident was already taken, or ident invalid for auth method.
public native bool BindIdentity(const char[] authMethod, const char[] ident);
// Sets whether or not a flag is enabled on an admin.
//
// @param flag Admin flag to use.
// @param enabled True to enable, false to disable.
public native void SetFlag(AdminFlag flag, bool enabled);
// Sets multiple bitwise flags to be enabled/disabled on an admin.
//
// @param flags Bitwise admin flags (ADMFLAG_*).
// @param enabled True to set the flag, false to unset/disable.
public void SetBitFlags(int flags, bool enabled)
{
AdminFlag flagArray[AdminFlags_TOTAL];
int num = FlagBitsToArray(flags, flagArray, sizeof(flagArray));
for (int i = 0; i < num; i++)
{
this.SetFlag(flagArray[i], enabled);
}
}
// Returns whether or not a flag is enabled on an admin.
//
// @param flag Admin flag to use.
// @param mode Access mode to check.
// @return True if enabled, false otherwise.
public native bool HasFlag(AdminFlag flag, AdmAccessMode mode=Access_Effective);
// Returns the bitstring of access flags on an admin.
//
// @param mode Access mode to use.
// @return A bitstring containing which flags are enabled.
public native int GetFlags(AdmAccessMode mode);
// Adds a group to an admin's inherited group list. Any flags the group has
// will be added to the admin's effective flags.
//
// @param gid GroupId index of the group.
// @return True on success, false on invalid input or duplicate membership.
public native bool InheritGroup(GroupId gid);
// Returns group information from an admin.
//
// @param index Group number to retrieve, from 0 to N-1, where N
// is the value of the GroupCount property.
// @param name Buffer to store the group's name.
// Note: This will safely chop UTF-8 strings.
// @param maxlength Maximum size of the output name buffer.
// @return A GroupId index and a name pointer, or
// INVALID_GROUP_ID and NULL if an error occurred.
public native GroupId GetGroup(int index, char[] name, int maxlength);
// Sets a password on an admin.
//
// @param password String containing the password.
public native void SetPassword(const char[] password);
// Gets an admin's password.
//
// @param buffer Optional buffer to store the admin's password.
// @param maxlength Maximum size of the output name buffer.
// Note: This will safely chop UTF-8 strings.
// @return True if there was a password set, false otherwise.
public native bool GetPassword(char[] buffer="", int maxlength=0);
// Tests whether one admin can target another.
//
// The heuristics for this check are as follows:
// 0. If the targeting AdminId is INVALID_ADMIN_ID, targeting fails.
// 1. If the targeted AdminId is INVALID_ADMIN_ID, targeting succeeds.
// 2. If the targeted AdminId is the same as the targeting AdminId,
// (self) targeting succeeds.
// 3. If the targeting admin is root, targeting succeeds.
// 4. If the targeted admin has access higher (as interpreted by
// (sm_immunity_mode) than the targeting admin, then targeting fails.
// 5. If the targeted admin has specific immunity from the
// targeting admin via group immunities, targeting fails.
// 6. Targeting succeeds.
//
// @param target Target admin (may be INVALID_ADMIN_ID).
// @return True if targetable, false if immune.
public native bool CanTarget(AdminId other);
// The number of groups of which this admin is a member.
property int GroupCount {
public native get();
}
// Immunity level used for targetting.
property int ImmunityLevel {
public native get();
public native set(int level);
}
}
methodmap GroupId {
// Gets whether or not a flag is enabled on a group's flag set.
//
// @param flag Admin flag to retrieve.
// @return True if enabled, false otherwise,
public native bool HasFlag(AdminFlag flag);
// Adds or removes a flag from a group's flag set.
//
// @param flag Admin flag to toggle.
// @param enabled True to set the flag, false to unset/disable.
public native void SetFlag(AdminFlag flag, bool enabled);
// Adds or removes multiple bitwise flags from a group's flag set.
//
// @param flags Bitwise admin flags (ADMFLAG_*).
// @param enabled True to set the flag, false to unset/disable.
public void SetBitFlags(int flags, bool enabled)
{
AdminFlag flagArray[AdminFlags_TOTAL];
int num = FlagBitsToArray(flags, flagArray, sizeof(flagArray));
for (int i = 0; i < num; i++)
{
this.SetFlag(flagArray[i], enabled);
}
}
// Returns the flag set that is added to users from this group.
//
// @return Bitstring containing the flags enabled.
public native int GetFlags();
// Returns a group that this group is immune to given an index.
//
// @param number Index from 0 to N-1, from GroupImmunitiesCount.
// @return GroupId that this group is immune to, or INVALID_GROUP_ID on failure.
public native GroupId GetGroupImmunity(int index);
// Adds immunity to a specific group.
//
// @param other Group id to receive immunity to.
public native void AddGroupImmunity(GroupId other);
// Retrieves a group-specific command override.
//
// @param name String containing command name (case sensitive).
// @param type Override type (specific command or group).
// @param rule Optional pointer to store allow/deny setting.
// @return True if an override exists, false otherwise.
public native bool GetCommandOverride(const char[] name, OverrideType type, OverrideRule &rule);
// Adds a group-specific override type.
//
// @param name String containing command name (case sensitive).
// @param type Override type (specific command or group).
// @param rule Override allow/deny setting.
public native void AddCommandOverride(const char[] name, OverrideType type, OverrideRule rule);
// Number of specific group immunities
property int GroupImmunitiesCount {
public native get();
}
// Immunity level used for targetting.
property int ImmunityLevel {
public native get();
public native set(int level);
}
}
/**
* Called when part of the cache needs to be rebuilt.
*
* @param part Part of the admin cache to rebuild.
*/
forward void OnRebuildAdminCache(AdminCachePart part);
/**
* Tells the admin system to dump a portion of the cache.
*
* @param part Part of the cache to dump. Specifying groups also dumps admins.
* @param rebuild If true, the rebuild forwards will fire.
*/
native void DumpAdminCache(AdminCachePart part, bool rebuild);
/**
* Adds a global command flag override. Any command registered with this name
* will assume the new flag. This is applied retroactively as well.
*
* @param cmd String containing command name (case sensitive).
* @param type Override type (specific command or group).
* @param flags New admin flag.
*/
native void AddCommandOverride(const char[] cmd, OverrideType type, int flags);
/**
* Returns a command override.
*
* @param cmd String containing command name (case sensitive).
* @param type Override type (specific command or group).
* @param flags By-reference cell to store the flag (undefined if not found).
* @return True if there is an override, false otherwise.
*/
native bool GetCommandOverride(const char[] cmd, OverrideType type, int &flags);
/**
* Unsets a command override.
*
* @param cmd String containing command name (case sensitive).
* @param type Override type (specific command or group).
*/
native void UnsetCommandOverride(const char[] cmd, OverrideType type);
/**
* Adds a new group. Name must be unique.
*
* @param group_name String containing the group name.
* @return A new group id, INVALID_GROUP_ID if it already exists.
*/
native GroupId CreateAdmGroup(const char[] group_name);
/**
* Finds a group by name.
*
* @param group_name String containing the group name.
* @return A group id, or INVALID_GROUP_ID if not found.
*/
native GroupId FindAdmGroup(const char[] group_name);
/**
* Adds or removes a flag from a group's flag set.
* @note These are called "add flags" because they add to a user's flags.
*
* @param id Group id.
* @param flag Admin flag to toggle.
* @param enabled True to set the flag, false to unset/disable.
*/
native void SetAdmGroupAddFlag(GroupId id, AdminFlag flag, bool enabled);
/**
* Gets the set value of an add flag on a group's flag set.
* @note These are called "add flags" because they add to a user's flags.
*
* @param id Group id.
* @param flag Admin flag to retrieve.
* @return True if enabled, false otherwise,
*/
native bool GetAdmGroupAddFlag(GroupId id, AdminFlag flag);
/**
* Returns the flag set that is added to a user from their group.
* @note These are called "add flags" because they add to a user's flags.
*
* @param id GroupId of the group.
* @return Bitstring containing the flags enabled.
*/
native int GetAdmGroupAddFlags(GroupId id);
/**
* @deprecated Functionality removed.
*/
#pragma deprecated Use SetAdmGroupImmunityLevel() instead.
native void SetAdmGroupImmunity(GroupId id, ImmunityType type, bool enabled);
/**
* @deprecated Functionality removed.
*/
#pragma deprecated Use GetAdmGroupImmunityLevel() instead.
native bool GetAdmGroupImmunity(GroupId id, ImmunityType type);
/**
* Adds immunity to a specific group.
*
* @param id Group id.
* @param other_id Group id to receive immunity to.
*/
native void SetAdmGroupImmuneFrom(GroupId id, GroupId other_id);
/**
* Returns the number of specific group immunities.
*
* @param id Group id.
* @return Number of group immunities.
*/
native int GetAdmGroupImmuneCount(GroupId id);
/**
* Returns a group that this group is immune to given an index.
*
* @param id Group id.
* @param number Index from 0 to N-1, from GetAdmGroupImmuneCount().
* @return GroupId that this group is immune to, or INVALID_GROUP_ID on failure.
*/
native GroupId GetAdmGroupImmuneFrom(GroupId id, int number);
/**
* Adds a group-specific override type.
*
* @param id Group id.
* @param name String containing command name (case sensitive).
* @param type Override type (specific command or group).
* @param rule Override allow/deny setting.
*/
native void AddAdmGroupCmdOverride(GroupId id, const char[] name, OverrideType type, OverrideRule rule);
/**
* Retrieves a group-specific command override.
*
* @param id Group id.
* @param name String containing command name (case sensitive).
* @param type Override type (specific command or group).
* @param rule Optional pointer to store allow/deny setting.
* @return True if an override exists, false otherwise.
*/
native bool GetAdmGroupCmdOverride(GroupId id, const char[] name, OverrideType type, OverrideRule &rule);
/**
* Registers an authentication identity type. You normally never need to call this except for
* very specific systems.
*
* @param name Codename to use for your authentication type.
*/
native void RegisterAuthIdentType(const char[] name);
/**
* Creates a new admin entry in the permissions cache and returns the generated AdminId index.
*
* @param name Name for this entry (does not have to be unique).
* Specify an empty string for an anonymous admin.
* @return New AdminId index or INVALID_ADMIN_ID if name is empty
*/
native AdminId CreateAdmin(const char[] name="");
/**
* Retrieves an admin's user name as made with CreateAdmin().
*
* @note This function can return UTF-8 strings, and will safely chop UTF-8 strings.
*
* @param id AdminId of the admin.
* @param name String buffer to store name.
* @param maxlength Maximum size of string buffer.
* @return Number of bytes written.
*/
native int GetAdminUsername(AdminId id, char[] name, int maxlength);
/**
* Binds an admin to an identity for fast lookup later on. The bind must be unique.
*
* @param id AdminId of the admin.
* @param auth Auth method to use, predefined or from RegisterAuthIdentType().
* @param ident String containing the arbitrary, unique identity.
* @return True on success, false if the auth method was not found,
* ident was already taken, or ident invalid for auth method.
*/
native bool BindAdminIdentity(AdminId id, const char[] auth, const char[] ident);
/**
* Sets whether or not a flag is enabled on an admin.
*
* @param id AdminId index of the admin.
* @param flag Admin flag to use.
* @param enabled True to enable, false to disable.
*/
native void SetAdminFlag(AdminId id, AdminFlag flag, bool enabled);
/**
* Returns whether or not a flag is enabled on an admin.
*
* @param id AdminId index of the admin.
* @param flag Admin flag to use.
* @param mode Access mode to check.
* @return True if enabled, false otherwise.
*/
native bool GetAdminFlag(AdminId id, AdminFlag flag, AdmAccessMode mode=Access_Effective);
/**
* Returns the bitstring of access flags on an admin.
*
* @param id AdminId index of the admin.
* @param mode Access mode to use.
* @return A bitstring containing which flags are enabled.
*/
native int GetAdminFlags(AdminId id, AdmAccessMode mode);
/**
* Adds a group to an admin's inherited group list. Any flags the group has
* will be added to the admin's effective flags.
*
* @param id AdminId index of the admin.
* @param gid GroupId index of the group.
* @return True on success, false on invalid input or duplicate membership.
*/
native bool AdminInheritGroup(AdminId id, GroupId gid);
/**
* Returns the number of groups this admin is a member of.
*
* @param id AdminId index of the admin.
* @return Number of groups this admin is a member of.
*/
native int GetAdminGroupCount(AdminId id);
/**
* Returns group information from an admin.
*
* @param id AdminId index of the admin.
* @param index Group number to retrieve, from 0 to N-1, where N
* is the value of GetAdminGroupCount(id).
* @param name Buffer to store the group's name.
* Note: This will safely chop UTF-8 strings.
* @param maxlength Maximum size of the output name buffer.
* @return A GroupId index and a name pointer, or
* INVALID_GROUP_ID and NULL if an error occurred.
*/
native GroupId GetAdminGroup(AdminId id, int index, char[] name, int maxlength);
/**
* Sets a password on an admin.
*
* @param id AdminId index of the admin.
* @param password String containing the password.
*/
native void SetAdminPassword(AdminId id, const char[] password);
/**
* Gets an admin's password.
*
* @param id AdminId index of the admin.
* @param buffer Optional buffer to store the admin's password.
* @param maxlength Maximum size of the output name buffer.
* Note: This will safely chop UTF-8 strings.
* @return True if there was a password set, false otherwise.
*/
native bool GetAdminPassword(AdminId id, char[] buffer="", int maxlength=0);
/**
* Attempts to find an admin by an auth method and an identity.
*
* @param auth Auth method to try.
* @param identity Identity string to look up.
* @return An AdminId index if found, INVALID_ADMIN_ID otherwise.
*/
native AdminId FindAdminByIdentity(const char[] auth, const char[] identity);
/**
* Removes an admin entry from the cache.
*
* @note This will remove any bindings to a specific user.
*
* @param id AdminId index to remove/invalidate.
* @return True on success, false otherwise.
*/
native bool RemoveAdmin(AdminId id);
/**
* Converts a flag bit string to a bit array.
*
* @param bits Bit string containing the flags.
* @param array Array to write the flags to. Enabled flags will be 'true'.
* @param maxSize Maximum number of flags the array can store.
* @return Number of flags written.
*/
native int FlagBitsToBitArray(int bits, bool[] array, int maxSize);
/**
* Converts a flag array to a bit string.
*
* @param array Array containing true or false for each AdminFlag.
* @param maxSize Maximum size of the flag array.
* @return A bit string composed of the array bits.
*/
native int FlagBitArrayToBits(const bool[] array, int maxSize);
/**
* Converts an array of flags to bits.
*
* @param array Array containing flags that are enabled.
* @param numFlags Number of flags in the array.
* @return A bit string composed of the array flags.
*/
native int FlagArrayToBits(const AdminFlag[] array, int numFlags);
/**
* Converts a bit string to an array of flags.
*
* @param bits Bit string containing the flags.
* @param array Output array to write flags.
* @param maxSize Maximum size of the flag array.
* @return Number of flags written.
*/
native int FlagBitsToArray(int bits, AdminFlag[] array, int maxSize);
/**
* Finds a flag by its string name.
*
* @param name Flag name (like "kick"), case sensitive.
* @param flag Variable to store flag in.
* @return True on success, false if not found.
*/
native bool FindFlagByName(const char[] name, AdminFlag &flag);
/**
* Finds a flag by a given character.
*
* @param c Flag ASCII character/token.
* @param flag Variable to store flag in.
* @return True on success, false if not found.
*/
native bool FindFlagByChar(int c, AdminFlag &flag);
/**
* Finds the flag char for a given admin flag.
*
* @param flag Flag to look up.
* @param c Variable to store flag char.
* @return True on success, false if not found.
*/
native bool FindFlagChar(AdminFlag flag, int &c);
/**
* Converts a string of flag characters to a bit string.
*
* @param flags Flag ASCII string.
* @param numchars Optional variable to store the number of bytes read.
* @return Bit string of ADMFLAG values.
*/
native int ReadFlagString(const char[] flags, int &numchars=0);
/**
* Tests whether one admin can target another.
*
* The heuristics for this check are as follows:
* 0. If the targeting AdminId is INVALID_ADMIN_ID, targeting fails.
* 1. If the targeted AdminId is INVALID_ADMIN_ID, targeting succeeds.
* 2. If the targeted AdminId is the same as the targeting AdminId,
* (self) targeting succeeds.
* 3. If the targeting admin is root, targeting succeeds.
* 4. If the targeted admin has access higher (as interpreted by
* (sm_immunity_mode) than the targeting admin, then targeting fails.
* 5. If the targeted admin has specific immunity from the
* targeting admin via group immunities, targeting fails.
* 6. Targeting succeeds.
*
* @param admin Admin doing the targetting (may be INVALID_ADMIN_ID).
* @param target Target admin (may be INVALID_ADMIN_ID).
* @return True if targetable, false if immune.
*/
native bool CanAdminTarget(AdminId admin, AdminId target);
/**
* Creates an admin auth method. This does not need to be called more than once
* per method, ever.
*
* @param method Name of the authentication method.
* @return True on success, false on failure.
*/
native bool CreateAuthMethod(const char[] method);
/**
* Sets a group's immunity level.
*
* @param gid Group Id.
* @param level Immunity level value.
* @return Old immunity level value.
*/
native int SetAdmGroupImmunityLevel(GroupId gid, int level);
/**
* Gets a group's immunity level (defaults to 0).
*
* @param gid Group Id.
* @return Immunity level value.
*/
native int GetAdmGroupImmunityLevel(GroupId gid);
/**
* Sets an admin's immunity level.
*
* @param id Admin Id.
* @param level Immunity level value.
* @return Old immunity level value.
*/
native int SetAdminImmunityLevel(AdminId id, int level);
/**
* Gets an admin's immunity level.
*
* @param id Admin Id.
* @return Immunity level value.
*/
native int GetAdminImmunityLevel(AdminId id);
/**
* Converts a flag to its single bit.
*
* @param flag Flag to convert.
* @return Bit representation of the flag.
*/
stock int FlagToBit(AdminFlag flag)
{
return (1 << view_as<int>(flag));
}
/**
* Converts a bit to an AdminFlag.
*
* @param bit Bit to convert.
* @param flag Stores the converted flag by reference.
* @return True on success, false otherwise.
*/
stock bool BitToFlag(int bit, AdminFlag &flag)
{
AdminFlag array[1];
if (FlagBitsToArray(bit, array, 1))
{
flag = array[0];
return true;
}
return false;
}
/**
* Converts a bit string to a string of flag characters.
*
* @param bits Bit string containing the flags.
* @param flags Output array to write a string of flag characters.
* @param maxSize Maximum size of the string array.
* @return Number of flag characters written.
*/
stock int FlagBitsToString(const int bits, char[] flags, const int maxSize)
{
AdminFlag array[AdminFlags_TOTAL];
int numFlags = FlagBitsToArray(bits, array, AdminFlags_TOTAL);
if (numFlags > maxSize)
{
numFlags = maxSize;
}
int i, c, numId = 0;
for (i = 0; i < numFlags; ++i)
{
if(FindFlagChar(array[i], c))
{
flags[numId++] = c;
}
}
flags[numId] = '\0';
return numId;
}

View File

@@ -0,0 +1,152 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _adminmenu_included
#endinput
#endif
#define _adminmenu_included
/* Decide whether topmenus should be required */
#if !defined REQUIRE_PLUGIN
#if defined REQUIRE_EXTENSIONS
#define TEMP_REQUIRE_EXTENSIONS
#undef REQUIRE_EXTENSIONS
#endif
#endif
#include <topmenus>
/* Restore old REQUIRE_EXTENSIONS value if necessary */
#if defined TEMP_REQUIRE_EXTENSIONS
#define REQUIRE_EXTENSIONS
#undef TEMP_REQUIRE_EXTENSIONS
#endif
/** Category for player commands. */
#define ADMINMENU_PLAYERCOMMANDS "PlayerCommands"
/** Category for server commands. */
#define ADMINMENU_SERVERCOMMANDS "ServerCommands"
/** Category for voting commands. */
#define ADMINMENU_VOTINGCOMMANDS "VotingCommands"
/**
* Called when the admin menu is created and 3rd party plugins can grab
* the Handle or add categories.
*
* @param topmenu Handle to the admin menu's TopMenu.
*/
forward void OnAdminMenuCreated(Handle topmenu);
/**
* Called when the admin menu is ready to have items added.
*
* @param topmenu Handle to the admin menu's TopMenu.
*/
forward void OnAdminMenuReady(Handle topmenu);
/**
* Retrieves the Handle to the admin top menu.
*
* @return Handle to the admin menu's TopMenu,
* or INVALID_HANDLE if not created yet.
*/
native TopMenu GetAdminTopMenu();
/**
* Adds targets to an admin menu.
*
* Each client is displayed as: name (userid)
* Each item contains the userid as a string for its info.
*
* @param menu Menu Handle.
* @param source_client Source client, or 0 to ignore immunity.
* @param in_game_only True to only select in-game players.
* @param alive_only True to only select alive players.
* @return Number of clients added.
*/
native int AddTargetsToMenu(Handle menu,
int source_client,
bool in_game_only=true,
bool alive_only=false);
/**
* Adds targets to an admin menu.
*
* Each client is displayed as: name (userid)
* Each item contains the userid as a string for its info.
*
* @param menu Menu Handle.
* @param source_client Source client, or 0 to ignore immunity.
* @param flags COMMAND_FILTER flags from commandfilters.inc.
* @return Number of clients added.
*/
native int AddTargetsToMenu2(Handle menu, int source_client, int flags);
/**
* Re-displays the admin menu to a client after selecting an item.
* Auto-aborts if the Handle is invalid.
*
* @param topmenu TopMenu Handle.
* @param client Client index.
* @return True on success, false on failure.
*/
stock bool RedisplayAdminMenu(Handle topmenu, int client)
{
if (topmenu == INVALID_HANDLE)
{
return false;
}
return DisplayTopMenu(topmenu, client, TopMenuPosition_LastCategory);
}
/* DO NOT EDIT BELOW THIS LINE */
public SharedPlugin __pl_adminmenu =
{
name = "adminmenu",
file = "adminmenu.smx",
#if defined REQUIRE_PLUGIN
required = 1,
#else
required = 0,
#endif
};
#if !defined REQUIRE_PLUGIN
public void __pl_adminmenu_SetNTVOptional()
{
MarkNativeAsOptional("GetAdminTopMenu");
MarkNativeAsOptional("AddTargetsToMenu");
MarkNativeAsOptional("AddTargetsToMenu2");
}
#endif

40
scripting/include/adt.inc Normal file
View File

@@ -0,0 +1,40 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _adt_included
#endinput
#endif
#define _adt_included
#include <adt_array>
#include <adt_trie>
#include <adt_stack>

View File

@@ -0,0 +1,491 @@
/**
* vim: set ts=4 sw=4 tw=99 noet :
* =============================================================================
* SourceMod (C)2004-2014 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _adt_array_included
#endinput
#endif
#define _adt_array_included
/**
* Given a maximum string size (including the null terminator),
* returns the number of cells required to fit that string.
*
* @param size Number of bytes.
* @return Minimum number of cells required to fit the byte count.
*/
stock int ByteCountToCells(int size)
{
if (!size)
{
return 1;
}
return (size + 3) / 4;
}
methodmap ArrayList < Handle {
// Creates a dynamic global cell array. While slower than a normal array,
// it can be used globally AND dynamically, which is otherwise impossible.
//
// The contents of the array are uniform; i.e. storing a string at index X
// and then retrieving it as an integer is NOT the same as StringToInt()!
// The "blocksize" determines how many cells each array slot has; it cannot
// be changed after creation.
//
// @param blocksize The number of cells each member of the array can
// hold. For example, 32 cells is equivalent to:
// new Array[X][32]
// @param startsize Initial size of the array. Note that data will
// NOT be auto-initialized.
// @return New Handle to the array object.
public native ArrayList(int blocksize=1, int startsize=0);
// Clears an array of all entries. This is the same as Resize(0).
public native void Clear();
// Clones an array, returning a new handle with the same size and data.
// This should NOT be confused with CloneHandle. This is a completely new
// handle with the same data but no relation to the original. It should be
// closed when no longer needed.
//
// @return New handle to the cloned array object
public native ArrayList Clone();
// Resizes an array. If the size is smaller than the current size, the
// array is truncated. If the size is larger than the current size,
// the data at the additional indexes will not be initialized.
//
// @param newsize New size.
public native void Resize(int newsize);
// Pushes a value onto the end of an array, adding a new index.
//
// This may safely be used even if the array has a blocksize greater
// than 1.
//
// @param value Value to push.
// @return Index of the new entry.
// @error Invalid Handle or out of memory.
public native int Push(any value);
// Pushes a string onto the end of an array, truncating it if it is too big.
//
// @param value String to push.
// @return Index of the new entry.
public native int PushString(const char[] value);
// Pushes an array of cells onto the end of an array. The cells
// are pushed as a block (i.e. the entire array sits at the index),
// rather than pushing each cell individually.
//
// @param values Block of values to copy.
// @param size If not set, the number of elements copied from the array
// will be equal to the blocksize. If set higher than the
// blocksize, the operation will be truncated.
// @return Index of the new entry.
public native int PushArray(const any[] values, int size=-1);
// Retrieves a cell value from an array.
//
// @param index Index in the array.
// @param block Optionally specify which block to read from
// (useful if the blocksize > 0).
// @param asChar Optionally read as a byte instead of a cell.
// @return Value read.
// @error Invalid index.
public native any Get(int index, int block=0, bool asChar=false);
// Retrieves a string value from an array.
//
// @param index Index in the array.
// @param buffer Buffer to copy to.
// @param maxlength Maximum size of the buffer.
// @param block Optionally specify which block to read from
// (useful if the blocksize > 0).
// @return Number of characters copied.
// @error Invalid index.
public native int GetString(int index, char[] buffer, int maxlength, int block=0);
// Retrieves an array of cells from an array.
//
// @param index Index in the array.
// @param buffer Buffer to store the array in.
// @param size If not set, assumes the buffer size is equal to the
// blocksize. Otherwise, the size passed is used.
// @param block Optionally specify which block to read from
// (useful if the blocksize > 0).
// @return Number of cells copied.
// @error Invalid index.
public native int GetArray(int index, any[] buffer, int size=-1, int block=0);
// Sets a cell value in an array.
//
// @param index Index in the array.
// @param value Cell value to set.
// @param block Optionally specify which block to write to
// (useful if the blocksize > 0).
// @param asChar Optionally set as a byte instead of a cell.
// @error Invalid index, or invalid block.
public native void Set(int index, any value, int block=0, bool asChar=false);
// Sets a string value in an array.
//
// @param index Index in the array.
// @param value String value to set.
// @param size If not set, assumes the buffer size is equal to the
// blocksize. Otherwise, the size passed is used.
// @param block Optionally specify which block to write to
// (useful if the blocksize > 0).
// @return Number of characters copied.
// @error Invalid index.
public native int SetString(int index, const char[] value, int size=-1, int block=0);
// Sets an array of cells in an array.
//
// @param index Index in the array.
// @param values Array to copy.
// @param size If not set, assumes the buffer size is equal to the
// blocksize. Otherwise, the size passed is used.
// @param block Optionally specify which block to write to
// (useful if the blocksize > 0).
// @return Number of cells copied.
// @error Invalid index.
public native int SetArray(int index, const any[] values, int size=-1, int block=0);
// Shifts an array up. All array contents after and including the given
// index are shifted up by one, and the given index is then "free."
// After shifting, the contents of the given index is undefined.
//
// @param index Index in the array to shift up from.
// @error Invalid index.
public native void ShiftUp(int index);
// Removes an array index, shifting the entire array down from that position
// on. For example, if item 8 of 10 is removed, the last 3 items will then be
// (6,7,8) instead of (7,8,9), and all indexes before 8 will remain unchanged.
//
// @param index Index in the array to remove at.
// @error Invalid index.
public native void Erase(int index);
// Swaps two items in the array.
//
// @param index1 First index.
// @param index2 Second index.
// @error Invalid index.
public native void SwapAt(int index1, int index2);
// Returns the index for the first occurrence of the provided string. If
// the string cannot be located, -1 will be returned.
//
// @param item String to search for
// @param block Optionally which block to search in
// @return Array index, or -1 on failure
public native int FindString(const char[] item, int block=0);
// Returns the index for the first occurrence of the provided value. If the
// value cannot be located, -1 will be returned.
//
// @param item Value to search for
// @param block Optionally which block to search in
// @return Array index, or -1 on failure
// @error Invalid block index
public native int FindValue(any item, int block=0);
// Sort an ADT Array. Specify the type as Integer, Float, or String.
//
// @param order Sort order to use, same as other sorts.
// @param type Data type stored in the ADT Array
public native void Sort(SortOrder order, SortType type);
// Custom sorts an ADT Array. You must pass in a comparison function.
//
// @param sortfunc Sort comparison function to use
// @param hndl Optional Handle to pass through the comparison calls.
public native void SortCustom(SortFuncADTArray sortfunc, Handle hndl=INVALID_HANDLE);
// Retrieve the size of the array.
property int Length {
public native get();
}
// Retrieve the blocksize the array was created with.
property int BlockSize {
public native get();
}
};
/**
* Creates a dynamic global cell array. While slower than a normal array,
* it can be used globally AND dynamically, which is otherwise impossible.
*
* The contents of the array are uniform; i.e. storing a string at index X
* and then retrieving it as an integer is NOT the same as StringToInt()!
* The "blocksize" determines how many cells each array slot has; it cannot
* be changed after creation.
*
* @param blocksize The number of cells each member of the array can
* hold. For example, 32 cells is equivalent to:
* new Array[X][32]
* @param startsize Initial size of the array. Note that data will
* NOT be auto-initialized.
* @return New Handle to the array object.
*/
native ArrayList CreateArray(int blocksize=1, int startsize=0);
/**
* Clears an array of all entries. This is the same as ResizeArray(0).
*
* @param array Array Handle.
* @error Invalid Handle.
*/
native void ClearArray(Handle array);
/**
* Clones an array, returning a new handle with the same size and data. This should NOT
* be confused with CloneHandle. This is a completely new handle with the same data but
* no relation to the original. You MUST close it.
*
* @param array Array handle to be cloned
* @return New handle to the cloned array object
* @error Invalid Handle
*/
native Handle CloneArray(Handle array);
/**
* Resizes an array. If the size is smaller than the current size,
* the array is truncated. If the size is larger than the current size,
* the data at the additional indexes will not be initialized.
*
* @param array Array Handle.
* @param newsize New size.
* @error Invalid Handle or out of memory.
*/
native void ResizeArray(Handle array, int newsize);
/**
* Returns the array size.
*
* @param array Array Handle.
* @return Number of elements in the array.
* @error Invalid Handle.
*/
native int GetArraySize(Handle array);
/**
* Pushes a value onto the end of an array, adding a new index.
*
* This may safely be used even if the array has a blocksize
* greater than 1.
*
* @param array Array Handle.
* @param value Value to push.
* @return Index of the new entry.
* @error Invalid Handle or out of memory.
*/
native int PushArrayCell(Handle array, any value);
/**
* Pushes a string onto the end of an array, truncating it
* if it is too big.
*
* @param array Array Handle.
* @param value String to push.
* @return Index of the new entry.
* @error Invalid Handle or out of memory.
*/
native int PushArrayString(Handle array, const char[] value);
/**
* Pushes an array of cells onto the end of an array. The cells
* are pushed as a block (i.e. the entire array sits at the index),
* rather than pushing each cell individually.
*
* @param array Array Handle.
* @param values Block of values to copy.
* @param size If not set, the number of elements copied from the array
* will be equal to the blocksize. If set higher than the
* blocksize, the operation will be truncated.
* @return Index of the new entry.
* @error Invalid Handle or out of memory.
*/
native int PushArrayArray(Handle array, const any[] values, int size=-1);
/**
* Retrieves a cell value from an array.
*
* @param array Array Handle.
* @param index Index in the array.
* @param block Optionally specify which block to read from
* (useful if the blocksize > 0).
* @param asChar Optionally read as a byte instead of a cell.
* @return Value read.
* @error Invalid Handle, invalid index, or invalid block.
*/
native any GetArrayCell(Handle array, int index, int block=0, bool asChar=false);
/**
* Retrieves a string value from an array.
*
* @param array Array Handle.
* @param index Index in the array.
* @param buffer Buffer to copy to.
* @param maxlength Maximum size of the buffer.
* @param block Optionally specify which block to read from
* (useful if the blocksize > 0).
* @return Number of characters copied.
* @error Invalid Handle or invalid index.
*/
native int GetArrayString(Handle array, int index, char[] buffer, int maxlength, int block=0);
/**
* Retrieves an array of cells from an array.
*
* @param array Array Handle.
* @param index Index in the array.
* @param buffer Buffer to store the array in.
* @param size If not set, assumes the buffer size is equal to the
* blocksize. Otherwise, the size passed is used.
* @param block Optionally specify which block to read from
* (useful if the blocksize > 0).
* @return Number of cells copied.
* @error Invalid Handle or invalid index.
*/
native int GetArrayArray(Handle array, int index, any[] buffer, int size=-1, int block=0);
/**
* Sets a cell value in an array.
*
* @param array Array Handle.
* @param index Index in the array.
* @param value Cell value to set.
* @param block Optionally specify which block to write to
* (useful if the blocksize > 0).
* @param asChar Optionally set as a byte instead of a cell.
* @error Invalid Handle, invalid index, or invalid block.
*/
native void SetArrayCell(Handle array, int index, any value, int block=0, bool asChar=false);
/**
* Sets a string value in an array.
*
* @param array Array Handle.
* @param index Index in the array.
* @param value String value to set.
* @param size If not set, assumes the buffer size is equal to the
* blocksize. Otherwise, the size passed is used.
* @param block Optionally specify which block to write to
* (useful if the blocksize > 0).
* @return Number of characters copied.
* @error Invalid Handle or invalid index.
*/
native int SetArrayString(Handle array, int index, const char[] value, int size=-1, int block=0);
/**
* Sets an array of cells in an array.
*
* @param array Array Handle.
* @param index Index in the array.
* @param values Array to copy.
* @param size If not set, assumes the buffer size is equal to the
* blocksize. Otherwise, the size passed is used.
* @param block Optionally specify which block to write to
* (useful if the blocksize > 0).
* @return Number of cells copied.
* @error Invalid Handle or invalid index.
*/
native int SetArrayArray(Handle array, int index, const any[] values, int size=-1, int block=0);
/**
* Shifts an array up. All array contents after and including the given
* index are shifted up by one, and the given index is then "free."
* After shifting, the contents of the given index is undefined.
*
* @param array Array Handle.
* @param index Index in the array to shift up from.
* @error Invalid Handle or invalid index.
*/
native void ShiftArrayUp(Handle array, int index);
/**
* Removes an array index, shifting the entire array down from that position
* on. For example, if item 8 of 10 is removed, the last 3 items will then be
* (6,7,8) instead of (7,8,9), and all indexes before 8 will remain unchanged.
*
* @param array Array Handle.
* @param index Index in the array to remove at.
* @error Invalid Handle or invalid index.
*/
native void RemoveFromArray(Handle array, int index);
/**
* Swaps two items in the array.
*
* @param array Array Handle.
* @param index1 First index.
* @param index2 Second index.
* @error Invalid Handle or invalid index.
*/
native void SwapArrayItems(Handle array, int index1, int index2);
/**
* Returns the index for the first occurrence of the provided string. If the string
* cannot be located, -1 will be returned.
*
* @param array Array Handle.
* @param item String to search for
* @param block Optionally which block to search in
* @return Array index, or -1 on failure
* @error Invalid Handle
*/
native int FindStringInArray(Handle array, const char[] item, int block=0);
/**
* Returns the index for the first occurrence of the provided value. If the value
* cannot be located, -1 will be returned.
*
* @param array Array Handle.
* @param item Value to search for
* @param block Optionally which block to search in
* @return Array index, or -1 on failure
* @error Invalid Handle or invalid block
*/
native int FindValueInArray(Handle array, any item, int block=0);
/**
* Returns the blocksize the array was created with.
*
* @param array Array Handle.
* @return The blocksize of the array.
* @error Invalid Handle
*/
native int GetArrayBlockSize(Handle array);

View File

@@ -0,0 +1,281 @@
/**
* vim: set ts=4 sw=4 tw=99 noet :
* =============================================================================
* SourceMod (C)2004-2014 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _adt_stack_included
#endinput
#endif
#define _adt_stack_included
methodmap ArrayStack < Handle
{
// Creates a stack structure. A stack is a LIFO (last in, first out)
// vector (array) of items. It has O(1) insertion and O(1) removal.
//
// Stacks have two operations: Push (adding an item) and Pop (removes
// items in reverse-push order).
//
// The contents of the stack are uniform; i.e. storing a string and then
// retrieving it as an integer is NOT the same as StringToInt()!
//
// The "blocksize" determines how many cells each slot has; it cannot
// be changed after creation.
//
// @param blocksize The number of cells each entry in the stack can
// hold. For example, 32 cells is equivalent to:
// new Array[X][32]
public native ArrayStack(int blocksize=1);
// Clears a stack of all entries.
public native void Clear();
// Clones an stack, returning a new handle with the same size and data.
// This should NOT be confused with CloneHandle. This is a completely new
// handle with the same data but no relation to the original. It should
// closed when no longer needed.
//
// @return New handle to the cloned stack object
public native ArrayStack Clone();
// Pushes a value onto the end of the stack, adding a new index.
//
// This may safely be used even if the stack has a blocksize
// greater than 1.
//
// @param value Value to push.
public native void Push(any value);
// Pushes a copy of a string onto the end of a stack, truncating it if it
// is too big.
//
// @param value String to push.
public native void PushString(const char[] value);
// Pushes a copy of an array of cells onto the end of a stack. The cells
// are pushed as a block (i.e. the entire array takes up one stack slot),
// rather than pushing each cell individually.
//
// @param stack Stack Handle.
// @param values Block of values to copy.
// @param size If not set, the number of elements copied from the array
// will be equal to the blocksize. If set higher than the
// blocksize, the operation will be truncated.
public native void PushArray(const any[] values, int size=-1);
// Pops a cell value from a stack.
//
// @param block Optionally specify which block to read from
// (useful if the blocksize > 0).
// @param asChar Optionally read as a byte instead of a cell.
// @return Value popped from the stack.
// @error The stack is empty.
public native any Pop(int block=0, bool asChar=false);
// Reads a cell value from a stack without removing it.
//
// @param block Optionally specify which block to read from
// (useful if the blocksize > 0).
// @param asChar Optionally read as a byte instead of a cell.
// @return Value read from the stack.
// @error The stack is empty.
public native any Top(int block=0, bool asChar=false);
// Pops a string value from a stack.
//
// @param buffer Buffer to store string.
// @param maxlength Maximum size of the buffer.
// @param written Number of characters written to buffer, not including
// the null terminator.
// @error The stack is empty.
public native void PopString(char[] buffer, int maxlength, int &written = 0);
// Reads a string value from a stack without removing it.
//
// @param buffer Buffer to store string.
// @param maxlength Maximum size of the buffer.
// @param written Number of characters written to buffer, not including
// the null terminator.
// @error The stack is empty.
public native void TopString(char[] buffer, int maxlength, int &written = 0);
// Pops an array of cells from a stack.
//
// @param buffer Buffer to store the array in.
// @param size If not set, assumes the buffer size is equal to the
// blocksize. Otherwise, the size passed is used.
// @error The stack is empty.
public native void PopArray(any[] buffer, int size=-1);
// Reads an array of cells from a stack without removing it.
//
// @param buffer Buffer to store the array in.
// @param size If not set, assumes the buffer size is equal to the
// blocksize. Otherwise, the size passed is used.
// @error The stack is empty.
public native void TopArray(any[] buffer, int size=-1);
// Returns true if the stack is empty, false otherwise.
property bool Empty {
public native get();
}
// Retrieve the blocksize the stack was created with.
property int BlockSize {
public native get();
}
property int Length {
public native get();
}
};
/**
* Creates a stack structure. A stack is a LIFO (last in, first out)
* vector (array) of items. It has O(1) insertion and O(1) removal.
*
* Stacks have two operations: Push (adding an item) and Pop (removes
* items in reverse-push order).
*
* The contents of the stack are uniform; i.e. storing a string and then
* retrieving it as an integer is NOT the same as StringToInt()!
*
* The "blocksize" determines how many cells each slot has; it cannot
* be changed after creation.
*
* @param blocksize The number of cells each entry in the stack can
* hold. For example, 32 cells is equivalent to:
* new Array[X][32]
* @return New stack Handle.
*/
native ArrayStack CreateStack(int blocksize=1);
/**
* Pushes a value onto the end of the stack, adding a new index.
*
* This may safely be used even if the stack has a blocksize
* greater than 1.
*
* @param stack Stack Handle.
* @param value Value to push.
* @error Invalid Handle or out of memory.
*/
native void PushStackCell(Handle stack, any value);
/**
* Pushes a copy of a string onto the end of a stack, truncating it if it is
* too big.
*
* @param stack Stack Handle.
* @param value String to push.
* @error Invalid Handle or out of memory.
*/
native void PushStackString(Handle stack, const char[] value);
/**
* Pushes a copy of an array of cells onto the end of a stack. The cells
* are pushed as a block (i.e. the entire array takes up one stack slot),
* rather than pushing each cell individually.
*
* @param stack Stack Handle.
* @param values Block of values to copy.
* @param size If not set, the number of elements copied from the array
* will be equal to the blocksize. If set higher than the
* blocksize, the operation will be truncated.
* @error Invalid Handle or out of memory.
*/
native void PushStackArray(Handle stack, const any[] values, int size=-1);
/**
* Pops a cell value from a stack.
*
* @param stack Stack Handle.
* @param value Variable to store the value.
* @param block Optionally specify which block to read from
* (useful if the blocksize > 0).
* @param asChar Optionally read as a byte instead of a cell.
* @return True on success, false if the stack is empty.
* @error Invalid Handle.
*/
native bool PopStackCell(Handle stack, any &value, int block=0, bool asChar=false);
/**
* Pops a string value from a stack.
*
* @param stack Stack Handle.
* @param buffer Buffer to store string.
* @param maxlength Maximum size of the buffer.
* @return True on success, false if the stack is empty.
* @error Invalid Handle.
*/
native bool PopStackString(Handle stack, char[] buffer, int maxlength, int &written=0);
/**
* Pops an array of cells from a stack.
*
* @param stack Stack Handle.
* @param buffer Buffer to store the array in.
* @param size If not set, assumes the buffer size is equal to the
* blocksize. Otherwise, the size passed is used.
* @return True on success, false if the stack is empty.
* @error Invalid Handle.
*/
native bool PopStackArray(Handle stack, any[] buffer, int size=-1);
/**
* Checks if a stack is empty.
*
* @param stack Stack Handle.
* @return True if empty, false if not empty.
* @error Invalid Handle.
*/
native bool IsStackEmpty(Handle stack);
/**
* Pops a value off a stack, ignoring it completely.
*
* @param stack Stack Handle.
* @return True if something was popped, false otherwise.
* @error Invalid Handle.
*/
stock bool PopStack(Handle stack)
{
int value;
return PopStackCell(stack, value);
}
/**
* Returns the blocksize the stack was created with.
*
* @param stack Stack Handle.
* @return The blocksize of the stack.
* @error Invalid Handle
*/
native int GetStackBlockSize(Handle stack);

View File

@@ -0,0 +1,332 @@
/**
* vim: set ts=4 sw=4 tw=99 noet :
* =============================================================================
* SourceMod (C)2004-2014 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _adt_trie_included
#endinput
#endif
#define _adt_trie_included
/* Object-oriented wrapper for maps. */
methodmap StringMap < Handle
{
// Creates a hash map. A hash map is a container that can map strings (called
// "keys") to arbitrary values (cells, arrays, or strings). Keys in a hash map
// are unique. That is, there is at most one entry in the map for a given key.
//
// Insertion, deletion, and lookup in a hash map are all considered to be fast
// operations, amortized to O(1), or constant time.
//
// The word "Trie" in this API is historical. As of SourceMod 1.6, tries have
// been internally replaced with hash tables, which have O(1) insertion time
// instead of O(n).
//
// The StringMap must be freed via delete or CloseHandle().
public native StringMap();
// Clones a string map, returning a new handle with the same size and data.
// This should NOT be confused with CloneHandle. This is a completely new
// handle with the same data but no relation to the original. It should be
// closed when no longer needed with delete or CloseHandle().
//
// @return New handle to the cloned string map
public native StringMap Clone();
// Sets a value in a hash map, either inserting a new entry or replacing an old one.
//
// @param key Key string.
// @param value Value to store at this key.
// @param replace If false, operation will fail if the key is already set.
// @return True on success, false on failure.
public native bool SetValue(const char[] key, any value, bool replace=true);
// Sets an array value in a Map, either inserting a new entry or replacing an old one.
//
// @param key Key string.
// @param array Array to store.
// @param num_items Number of items in the array.
// @param replace If false, operation will fail if the key is already set.
// @return True on success, false on failure.
public native bool SetArray(const char[] key, const any[] array, int num_items, bool replace=true);
// Sets a string value in a Map, either inserting a new entry or replacing an old one.
//
// @param key Key string.
// @param value String to store.
// @param replace If false, operation will fail if the key is already set.
// @return True on success, false on failure.
public native bool SetString(const char[] key, const char[] value, bool replace=true);
// Retrieves a value in a Map.
//
// @param key Key string.
// @param value Variable to store value.
// @return True on success. False if the key is not set, or the key is set
// as an array or string (not a value).
public native bool GetValue(const char[] key, any &value);
// Retrieves an array in a Map.
//
// @param key Key string.
// @param array Buffer to store array.
// @param max_size Maximum size of array buffer.
// @param size Optional parameter to store the number of elements written to the buffer.
// @return True on success. False if the key is not set, or the key is set
// as a value or string (not an array).
public native bool GetArray(const char[] key, any[] array, int max_size, int &size=0);
// Retrieves a string in a Map.
//
// @param key Key string.
// @param value Buffer to store value.
// @param max_size Maximum size of string buffer.
// @param size Optional parameter to store the number of bytes written to the buffer.
// @return True on success. False if the key is not set, or the key is set
// as a value or array (not a string).
public native bool GetString(const char[] key, char[] value, int max_size, int &size=0);
// Checks whether a key is present in a Map.
//
// @param key Key string.
// @return True if the key has been found, else false.
public native bool ContainsKey(const char[] key);
// Removes a key entry from a Map.
//
// @param key Key string.
// @return True on success, false if the value was never set.
public native bool Remove(const char[] key);
// Clears all entries from a Map.
public native void Clear();
// Create a snapshot of the map's keys. See StringMapSnapshot.
public native StringMapSnapshot Snapshot();
// Retrieves the number of elements in a map.
property int Size {
public native get();
}
};
/**
* A StringMapSnapshot is created via StringMap.Snapshot(). It captures the
* keys on a map so they can be read. Snapshots must be freed with delete or
* CloseHandle().
*/
methodmap StringMapSnapshot < Handle
{
// Returns the number of keys in the map snapshot.
property int Length {
public native get();
}
// Returns the buffer size required to store a given key. That is, it
// returns the length of the key plus one.
//
// @param index Key index (starting from 0).
// @return Buffer size required to store the key string.
// @error Index out of range.
public native int KeyBufferSize(int index);
// Retrieves the key string of a given key in a map snapshot.
//
// @param index Key index (starting from 0).
// @param buffer String buffer.
// @param maxlength Maximum buffer length.
// @return Number of bytes written to the buffer.
// @error Index out of range.
public native int GetKey(int index, char[] buffer, int maxlength);
};
/**
* Creates a hash map. A hash map is a container that can map strings (called
* "keys") to arbitrary values (cells, arrays, or strings). Keys in a hash map
* are unique. That is, there is at most one entry in the map for a given key.
*
* Insertion, deletion, and lookup in a hash map are all considered to be fast
* operations, amortized to O(1), or constant time.
*
* The word "Trie" in this API is historical. As of SourceMod 1.6, tries have
* been internally replaced with hash tables, which have O(1) insertion time
* instead of O(n).
*
* @return New Map Handle, which must be freed via CloseHandle().
*/
native StringMap CreateTrie();
/**
* Sets a value in a hash map, either inserting a new entry or replacing an old one.
*
* @param map Map Handle.
* @param key Key string.
* @param value Value to store at this key.
* @param replace If false, operation will fail if the key is already set.
* @return True on success, false on failure.
* @error Invalid Handle.
*/
native bool SetTrieValue(Handle map, const char[] key, any value, bool replace=true);
/**
* Sets an array value in a Map, either inserting a new entry or replacing an old one.
*
* @param map Map Handle.
* @param key Key string.
* @param array Array to store.
* @param num_items Number of items in the array.
* @param replace If false, operation will fail if the key is already set.
* @return True on success, false on failure.
* @error Invalid Handle.
*/
native bool SetTrieArray(Handle map, const char[] key, const any[] array, int num_items, bool replace=true);
/**
* Sets a string value in a Map, either inserting a new entry or replacing an old one.
*
* @param map Map Handle.
* @param key Key string.
* @param value String to store.
* @param replace If false, operation will fail if the key is already set.
* @return True on success, false on failure.
* @error Invalid Handle.
*/
native bool SetTrieString(Handle map, const char[] key, const char[] value, bool replace=true);
/**
* Retrieves a value in a Map.
*
* @param map Map Handle.
* @param key Key string.
* @param value Variable to store value.
* @return True on success. False if the key is not set, or the key is set
* as an array or string (not a value).
* @error Invalid Handle.
*/
native bool GetTrieValue(Handle map, const char[] key, any &value);
/**
* Retrieves an array in a Map.
*
* @param map Map Handle.
* @param key Key string.
* @param array Buffer to store array.
* @param max_size Maximum size of array buffer.
* @param size Optional parameter to store the number of elements written to the buffer.
* @return True on success. False if the key is not set, or the key is set
* as a value or string (not an array).
* @error Invalid Handle.
*/
native bool GetTrieArray(Handle map, const char[] key, any[] array, int max_size, int &size=0);
/**
* Retrieves a string in a Map.
*
* @param map Map Handle.
* @param key Key string.
* @param value Buffer to store value.
* @param max_size Maximum size of string buffer.
* @param size Optional parameter to store the number of bytes written to the buffer.
* @return True on success. False if the key is not set, or the key is set
* as a value or array (not a string).
* @error Invalid Handle.
*/
native bool GetTrieString(Handle map, const char[] key, char[] value, int max_size, int &size=0);
/**
* Removes a key entry from a Map.
*
* @param map Map Handle.
* @param key Key string.
* @return True on success, false if the value was never set.
* @error Invalid Handle.
*/
native bool RemoveFromTrie(Handle map, const char[] key);
/**
* Clears all entries from a Map.
*
* @param map Map Handle.
* @error Invalid Handle.
*/
native void ClearTrie(Handle map);
/**
* Retrieves the number of elements in a map.
*
* @param map Map Handle.
* @return Number of elements in the trie.
* @error Invalid Handle.
*/
native int GetTrieSize(Handle map);
/**
* Creates a snapshot of all keys in the map. If the map is changed after this
* call, the changes are not reflected in the snapshot. Keys are not sorted.
*
* @param map Map Handle.
* @return New Map Snapshot Handle, which must be closed via CloseHandle().
* @error Invalid Handle.
*/
native Handle CreateTrieSnapshot(Handle map);
/**
* Returns the number of keys in a map snapshot. Note that this may be
* different from the size of the map, since the map can change after the
* snapshot of its keys was taken.
*
* @param snapshot Map snapshot.
* @return Number of keys.
* @error Invalid Handle.
*/
native int TrieSnapshotLength(Handle snapshot);
/**
* Returns the buffer size required to store a given key. That is, it returns
* the length of the key plus one.
*
* @param snapshot Map snapshot.
* @param index Key index (starting from 0).
* @return Buffer size required to store the key string.
* @error Invalid Handle or index out of range.
*/
native int TrieSnapshotKeyBufferSize(Handle snapshot, int index);
/**
* Retrieves the key string of a given key in a map snapshot.
*
* @param snapshot Map snapshot.
* @param index Key index (starting from 0).
* @param buffer String buffer.
* @param maxlength Maximum buffer length.
* @return Number of bytes written to the buffer.
* @error Invalid Handle or index out of range.
*/
native int GetTrieSnapshotKey(Handle snapshot, int index, char[] buffer, int maxlength);

View File

@@ -0,0 +1,91 @@
#if defined _advmotd_enabled
#endinput
#endif
#define _advmotd_enabled
enum MOTDFailureReason {
MOTDFailure_Unknown, // Failure reason unknown
MOTDFailure_Disabled, // Client has explicitly disabled HTML MOTDs
MOTDFailure_Matchmaking, // HTML MOTD is disabled by Quickplay/matchmaking (TF2 only)
MOTDFailure_QueryFailed // cl_disablehtmlmotd convar query failed
};
typedef MOTDFailure = function void (int client, MOTDFailureReason reason);
/**
* Displays an MOTD panel to a client with advanced options
*
* @param client Client index the panel should be shown to
* @param title Title of the MOTD panel (not displayed on all games)
* @param msg Content of the MOTD panel; could be a URL, plain text, or a stringtable index
* @param type Type of MOTD this is, one of MOTDPANEL_TYPE_TEXT, MOTDPANEL_TYPE_INDEX, MOTDPANEL_TYPE_URL, MOTDPANEL_TYPE_FILE
* @param visible Whether the panel should be shown to the client
* @param big true if this should be a big MOTD panel (TF2 only)
* @param verify true if we should check if the client can actually receive HTML MOTDs before sending it, false otherwise
* @param callback A callback to be called if we determine that the client can't receive HTML MOTDs
* @noreturn
*/
stock void AdvMOTD_ShowMOTDPanel(int client, const char[] title, const char[] msg, int type=MOTDPANEL_TYPE_INDEX, bool visible=true, bool big=false, bool verify=false, MOTDFailure callback=INVALID_FUNCTION) {
char connectmethod[32];
if(verify && GetClientInfo(client, "cl_connectmethod", connectmethod, sizeof(connectmethod))) {
if(StrContains(connectmethod, "quickplay", false) != -1 || StrContains(connectmethod, "matchmaking", false) != -1) {
if(callback != INVALID_FUNCTION) {
Call_StartFunction(null, callback);
Call_PushCell(client);
Call_PushCell(MOTDFailure_Matchmaking);
Call_Finish();
}
return;
}
}
KeyValues kv = new KeyValues("data");
kv.SetString("title", title);
kv.SetNum("type", type);
kv.SetString("msg", msg);
if(big) {
kv.SetNum("customsvr", 1);
}
if(verify) {
DataPack pack = new DataPack();
pack.WriteCell(kv);
pack.WriteCell(visible);
if(callback != INVALID_FUNCTION) {
Handle fwd = CreateForward(ET_Ignore, Param_Cell, Param_Cell);
AddToForward(fwd, null, callback);
pack.WriteCell(fwd);
} else {
pack.WriteCell(0);
}
QueryClientConVar(client, "cl_disablehtmlmotd", AdvMOTD_OnQueryFinished, pack);
} else {
ShowVGUIPanel(client, "info", kv, visible);
CloseHandle(kv);
}
}
public void AdvMOTD_OnQueryFinished(QueryCookie cookie, int client, ConVarQueryResult result, const char[] cvarName, const char[] cvarValue, DataPack pack) {
pack.Reset();
KeyValues kv = pack.ReadCell();
bool visible = pack.ReadCell();
Handle fwd = pack.ReadCell();
delete pack;
if(result != ConVarQuery_Okay || StringToInt(cvarValue)) {
delete kv;
if(fwd) {
Call_StartForward(fwd);
Call_PushCell(client);
Call_PushCell((result != ConVarQuery_Okay) ? MOTDFailure_QueryFailed : MOTDFailure_Disabled);
delete fwd;
}
return;
}
ShowVGUIPanel(client, "info", kv, visible);
delete kv;
}

View File

@@ -0,0 +1,26 @@
stock bool IsValidClient(int client) {
return (0 < client <= MaxClients && IsClientInGame(client));
}
void PrecacheAllFiles(){
for (int i = 0; i < (sizeof(MusicArray) - 1); i++){
PrintToServer("[CORE] Precaching music: %s in position %i", MusicArray[i], i);
PrecacheSound(MusicArray[i], true);
}
for (int i = 0; i < (sizeof(SFXArray) - 1); i++){
PrintToServer("[CORE] Precaching SFX: %s in position %i", SFXArray[i], i);
PrecacheSound(SFXArray[i], true);
}
}
void RegisterAllCommands(){
RegServerCmd("fb_operator", Command_Operator, "Serverside only. Does nothing when executed as client.");
RegAdminCmd("sm_music", Command_Music, ADMFLAG_RESERVATION, "Set music to be played for the next wave");
RegConsoleCmd("sm_bombstatus", Command_FBBombStatus, "Check bomb status");
RegConsoleCmd("sm_song", Command_GetCurrentSong, "Get current song name");
RegConsoleCmd("sm_stats", Command_MyStats, "Print current statistics");
RegConsoleCmd("sm_return", Command_Return, "Return to Spawn");
RegConsoleCmd("sm_sacpoints", Command_SacrificePointShop, "Fartsy's Annihilation Supply Shop");
RegConsoleCmd("sm_discord", Command_Discord, "Join our Discord server!");
RegConsoleCmd("sm_sounds", Command_Sounds, "Toggle sounds on or off via menu");
}

View File

@@ -0,0 +1,156 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _banning_included
#endinput
#endif
#define _banning_included
#define BANFLAG_AUTO (1<<0) /**< Auto-detects whether to ban by steamid or IP */
#define BANFLAG_IP (1<<1) /**< Always ban by IP address */
#define BANFLAG_AUTHID (1<<2) /**< Always ban by authstring (for BanIdentity) if possible */
#define BANFLAG_NOKICK (1<<3) /**< Does not kick the client */
/**
* Called for calls to BanClient() with a non-empty command.
*
* @param client Client being banned.
* @param time Time the client is being banned for (0 = permanent).
* @param flags One if AUTHID or IP will be enabled. If AUTO is also
* enabled, it means Core autodetected which to use.
* @param reason Reason passed via BanClient().
* @param kick_message Kick message passed via BanClient().
* @param command Command string to identify the ban source.
* @param source Source value passed via BanClient().
* @return Plugin_Handled to block the actual server banning.
* Kicking will still occur.
*/
forward Action OnBanClient(int client,
int time,
int flags,
const char[] reason,
const char[] kick_message,
const char[] command,
any source);
/**
* Called for calls to BanIdentity() with a non-empty command.
*
* @param identity Identity string being banned (authstring or ip).
* @param time Time the client is being banned for (0 = permanent).
* @param flags Ban flags (only IP or AUTHID are valid here).
* @param reason Reason passed via BanIdentity().
* @param command Command string to identify the ban source.
* @param source Source value passed via BanIdentity().
* @return Plugin_Handled to block the actual server banning.
*/
forward Action OnBanIdentity(const char[] identity,
int time,
int flags,
const char[] reason,
const char[] command,
any source);
/**
* Called for calls to RemoveBan() with a non-empty command.
*
* @param identity Identity string being banned (authstring or ip).
* @param flags Ban flags (only IP or AUTHID are valid here).
* @param command Command string to identify the ban source.
* @param source Source value passed via BanIdentity().
* @return Plugin_Handled to block the actual unbanning.
*/
forward Action OnRemoveBan(const char[] identity,
int flags,
const char[] command,
any source);
/**
* Bans a client.
*
* @param client Client being banned.
* @param time Time (in minutes) to ban (0 = permanent).
* @param flags Flags for controlling the ban mechanism. If AUTHID
* is set and no AUTHID is available, the ban will fail
* unless AUTO is also flagged.
* @param reason Reason to ban the client for.
* @param kick_message Message to display to the user when kicking.
* @param command Command string to identify the source. If this is left
* empty, then the OnBanClient forward will not be called.
* @param source A source value that could be interpreted as a player
* index of any sort (not actually checked by Core).
* @return True on success, false on failure.
* @error Invalid client index or client not in game.
*/
native bool BanClient(int client,
int time,
int flags,
const char[] reason,
const char[] kick_message="",
const char[] command="",
any source=0);
/**
* Bans an identity (either an IP address or auth string).
*
* @param identity String to ban (ip or authstring).
* @param time Time to ban for (0 = permanent).
* @param flags Flags (only IP and AUTHID are valid flags here).
* @param reason Ban reason string.
* @param command Command string to identify the source. If this is left
* empty, then the OnBanIdentity forward will not be called.
* @param source A source value that could be interpreted as a player
* index of any sort (not actually checked by Core).
* @return True on success, false on failure.
*/
native bool BanIdentity(const char[] identity,
int time,
int flags,
const char[] reason,
const char[] command="",
any source=0);
/**
* Removes a ban that was written to the server (either in memory or on disk).
*
* @param identity String to unban (ip or authstring).
* @param flags Flags (only IP and AUTHID are valid flags here).
* @param command Command string to identify the source. If this is left
* empty, then OnRemoveBan will not be called.
* @param source A source value that could be interpreted as a player
* index of any sort (not actually checked by Core).
* @return True on success, false on failure.
*/
native bool RemoveBan(const char[] identity,
int flags,
const char[] command="",
any source=0);

View File

@@ -0,0 +1,109 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2011 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _basecomm_included
#endinput
#endif
#define _basecomm_included
/**
* Called when a client is muted or unmuted
*
* @param client Client index
* @param muteState True if client was muted, false otherwise
*/
forward void BaseComm_OnClientMute(int client, bool muteState);
/**
* Called when a client is gagged or ungagged
*
* @param client Client index
* @param gagState True if client was gaged, false otherwise
*/
forward void BaseComm_OnClientGag(int client, bool gagState);
/**
* Returns whether or not a client is gagged
*
* @param client Client index.
* @return True if client is gagged, false otherwise.
*/
native bool BaseComm_IsClientGagged(int client);
/**
* Returns whether or not a client is muted
*
* @param client Client index.
* @return True if client is muted, false otherwise.
*/
native bool BaseComm_IsClientMuted(int client);
/**
* Sets a client's gag state
*
* @param client Client index.
* @param gagState True to gag client, false to ungag.
* @return True if this caused a change in gag state, false otherwise.
*/
native bool BaseComm_SetClientGag(int client, bool gagState);
/**
* Sets a client's mute state
*
* @param client Client index.
* @param muteState True to mute client, false to unmute.
* @return True if this caused a change in mute state, false otherwise.
*/
native bool BaseComm_SetClientMute(int client, bool muteState);
/* DO NOT EDIT BELOW THIS LINE */
public SharedPlugin __pl_basecomm =
{
name = "basecomm",
file = "basecomm.smx",
#if defined REQUIRE_PLUGIN
required = 1,
#else
required = 0,
#endif
};
#if !defined REQUIRE_PLUGIN
public void __pl_basecomm_SetNTVOptional()
{
MarkNativeAsOptional("BaseComm_IsClientGagged");
MarkNativeAsOptional("BaseComm_IsClientMuted");
MarkNativeAsOptional("BaseComm_SetClientGag");
MarkNativeAsOptional("BaseComm_SetClientMute");
}
#endif

View File

@@ -0,0 +1,55 @@
#if defined _betherobot_included_
#endinput
#endif
#define _betherobot_included_
enum RobotStatus {
RobotStatus_Human = 0, // Client is human
RobotStatus_WantsToBeRobot, // Client wants to be robot, but can't because of defined rules.
RobotStatus_Robot // Client is a robot. Beep boop.
}
/**
* Checks if a client is a robot.
*
* @param client Index of the client to check.
* @return RobotStatus value of the client; RobotStatus_Human if they're a human, RobotStatus_Robot if they're a robot, RobotStatus_WantsToBeRobot if they want to be a robot, but can't for some reason.
*/
native RobotStatus:BeTheRobot_GetRobotStatus(client);
/**
* Sets if a client should be robot or not.
*
* @param client Index of the client to set.
* @param toggle True to make the client a robot, false to change them back to a human. Skip this argument to toggle instead.
* @noreturn
*/
native BeTheRobot_SetRobot(client, bool:toggle = bool:2);
/**
* Uses Be the Robot's "CheckTheRules()" native to check if a client should be allowed to be a robot or not.
*
* @param client Index of the client to check.
* @return True if the client is allowed to be a robot (not dead, allowed class by server, etc.) false otherwise.
*/
native bool:BeTheRobot_CheckRules(client);
public SharedPlugin:__pl_betherobot =
{
name = "betherobot",
file = "betherobot.smx",
#if defined REQUIRE_PLUGIN
required = 1,
#else
required = 0,
#endif
};
#if !defined REQUIRE_PLUGIN
public __pl_betherobot_SetNTVOptional()
{
MarkNativeAsOptional("BeTheRobot_GetRobotStatus");
MarkNativeAsOptional("BeTheRobot_SetRobot");
MarkNativeAsOptional("BeTheRobot_CheckRules");
}
#endif

View File

@@ -0,0 +1,470 @@
/**
* vim: set ts=4 sw=4 tw=99 noet :
* =============================================================================
* SourceMod (C)2004-2014 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _bitbuffer_included
#endinput
#endif
#define _bitbuffer_included
methodmap BfWrite < Handle
{
// Writes a single bit to a writable bitbuffer (bf_write).
//
// @param bit Bit to write (true for 1, false for 0).
public native void WriteBool(bool bit);
// Writes a byte to a writable bitbuffer (bf_write).
//
// @param byte Byte to write (value will be written as 8bit).
public native void WriteByte(int byte);
// Writes a byte to a writable bitbuffer (bf_write).
//
// @param chr Character to write.
public native void WriteChar(int chr);
// Writes a 16bit integer to a writable bitbuffer (bf_write).
//
// @param num Integer to write (value will be written as 16bit).
public native void WriteShort(int num);
// Writes a 16bit unsigned integer to a writable bitbuffer (bf_write).
//
// @param num Integer to write (value will be written as 16bit).
public native void WriteWord(int num);
// Writes a normal integer to a writable bitbuffer (bf_write).
//
// @param num Integer to write (value will be written as 32bit).
public native void WriteNum(int num);
// Writes a floating point number to a writable bitbuffer (bf_write).
//
// @param num Number to write.
public native void WriteFloat(float num);
// Writes a string to a writable bitbuffer (bf_write).
//
// @param string Text string to write.
public native void WriteString(const char[] string);
// Writes an entity to a writable bitbuffer (bf_write).
//
// @param ent Entity index to write.
public native void WriteEntity(int ent);
// Writes a bit angle to a writable bitbuffer (bf_write).
//
// @param angle Angle to write.
// @param numBits Optional number of bits to use.
public native void WriteAngle(float angle, int numBits=8);
// Writes a coordinate to a writable bitbuffer (bf_write).
//
// @param coord Coordinate to write.
public native void WriteCoord(float coord);
// Writes a 3D vector of coordinates to a writable bitbuffer (bf_write).
//
// @param coord Coordinate array to write.
public native void WriteVecCoord(float coord[3]);
// Writes a 3D normal vector to a writable bitbuffer (bf_write).
//
// @param vec Vector to write.
public native void WriteVecNormal(float vec[3]);
// Writes a 3D angle vector to a writable bitbuffer (bf_write).
//
// @param angles Angle vector to write.
public native void WriteAngles(float angles[3]);
};
methodmap BfRead < Handle
{
// Reads a single bit from a readable bitbuffer (bf_read).
//
// @return Bit value read.
public native bool ReadBool();
// Reads a byte from a readable bitbuffer (bf_read).
//
// @return Byte value read (read as 8bit).
public native int ReadByte();
// Reads a character from a readable bitbuffer (bf_read).
//
// @return Character value read.
public native int ReadChar();
// Reads a 16bit integer from a readable bitbuffer (bf_read).
//
// @param bf bf_read handle to read from.
// @return Integer value read (read as 16bit).
public native int ReadShort();
// Reads a 16bit unsigned integer from a readable bitbuffer (bf_read).
//
// @param bf bf_read handle to read from.
// @return Integer value read (read as 16bit).
public native int ReadWord();
// Reads a normal integer to a readable bitbuffer (bf_read).
//
// @return Integer value read (read as 32bit).
public native int ReadNum();
// Reads a floating point number from a readable bitbuffer (bf_read).
//
// @return Floating point value read.
public native float ReadFloat();
// Reads a string from a readable bitbuffer (bf_read).
//
// @param buffer Destination string buffer.
// @param maxlength Maximum length of output string buffer.
// @param line If true the buffer will be copied until it reaches a '\n' or a null terminator.
// @return Number of bytes written to the buffer. If the bitbuffer stream overflowed,
// that is, had no terminator before the end of the stream, then a negative
// number will be returned equal to the number of characters written to the
// buffer minus 1. The buffer will be null terminated regardless of the
// return value.
public native int ReadString(char[] buffer, int maxlength, bool line=false);
// Reads an entity from a readable bitbuffer (bf_read).
//
// @return Entity index read.
public native int ReadEntity();
// Reads a bit angle from a readable bitbuffer (bf_read).
//
// @param numBits Optional number of bits to use.
// @return Angle read.
public native float ReadAngle(int numBits=8);
// Reads a coordinate from a readable bitbuffer (bf_read).
//
// @return Coordinate read.
public native float ReadCoord();
// Reads a 3D vector of coordinates from a readable bitbuffer (bf_read).
//
// @param coord Destination coordinate array.
public native void ReadVecCoord(float coord[3]);
// Reads a 3D normal vector from a readable bitbuffer (bf_read).
//
// @param vec Destination vector array.
public native void ReadVecNormal(float vec[3]);
// Reads a 3D angle vector from a readable bitbuffer (bf_read).
//
// @param angles Destination angle vector.
public native void ReadAngles(float angles[3]);
// Returns the number of bytes left in a readable bitbuffer (bf_read).
property int BytesLeft {
public native get();
}
};
/**
* Writes a single bit to a writable bitbuffer (bf_write).
*
* @param bf bf_write handle to write to.
* @param bit Bit to write (true for 1, false for 0).
* @error Invalid or incorrect Handle.
*/
native void BfWriteBool(Handle bf, bool bit);
/**
* Writes a byte to a writable bitbuffer (bf_write).
*
* @param bf bf_write handle to write to.
* @param byte Byte to write (value will be written as 8bit).
* @error Invalid or incorrect Handle.
*/
native void BfWriteByte(Handle bf, int byte);
/**
* Writes a byte to a writable bitbuffer (bf_write).
*
* @param bf bf_write handle to write to.
* @param chr Character to write.
* @error Invalid or incorrect Handle.
*/
native void BfWriteChar(Handle bf, int chr);
/**
* Writes a 16bit integer to a writable bitbuffer (bf_write).
*
* @param bf bf_write handle to write to.
* @param num Integer to write (value will be written as 16bit).
* @error Invalid or incorrect Handle.
*/
native void BfWriteShort(Handle bf, int num);
/**
* Writes a 16bit unsigned integer to a writable bitbuffer (bf_write).
*
* @param bf bf_write handle to write to.
* @param num Integer to write (value will be written as 16bit).
* @error Invalid or incorrect Handle.
*/
native void BfWriteWord(Handle bf, int num);
/**
* Writes a normal integer to a writable bitbuffer (bf_write).
*
* @param bf bf_write handle to write to.
* @param num Integer to write (value will be written as 32bit).
* @error Invalid or incorrect Handle.
*/
native void BfWriteNum(Handle bf, int num);
/**
* Writes a floating point number to a writable bitbuffer (bf_write).
*
* @param bf bf_write handle to write to.
* @param num Number to write.
* @error Invalid or incorrect Handle.
*/
native void BfWriteFloat(Handle bf, float num);
/**
* Writes a string to a writable bitbuffer (bf_write).
*
* @param bf bf_write handle to write to.
* @param string Text string to write.
* @error Invalid or incorrect Handle.
*/
native void BfWriteString(Handle bf, const char[] string);
/**
* Writes an entity to a writable bitbuffer (bf_write).
* @note This is a wrapper around BfWriteShort().
*
* @param bf bf_write handle to write to.
* @param ent Entity index to write.
* @error Invalid or incorrect Handle, or invalid entity.
*/
native void BfWriteEntity(Handle bf, int ent);
/**
* Writes a bit angle to a writable bitbuffer (bf_write).
*
* @param bf bf_write handle to write to.
* @param angle Angle to write.
* @param numBits Optional number of bits to use.
* @error Invalid or incorrect Handle.
*/
native void BfWriteAngle(Handle bf, float angle, int numBits=8);
/**
* Writes a coordinate to a writable bitbuffer (bf_write).
*
* @param bf bf_write handle to write to.
* @param coord Coordinate to write.
* @error Invalid or incorrect Handle.
*/
native void BfWriteCoord(Handle bf, float coord);
/**
* Writes a 3D vector of coordinates to a writable bitbuffer (bf_write).
*
* @param bf bf_write handle to write to.
* @param coord Coordinate array to write.
* @error Invalid or incorrect Handle.
*/
native void BfWriteVecCoord(Handle bf, float coord[3]);
/**
* Writes a 3D normal vector to a writable bitbuffer (bf_write).
*
* @param bf bf_write handle to write to.
* @param vec Vector to write.
* @error Invalid or incorrect Handle.
*/
native void BfWriteVecNormal(Handle bf, float vec[3]);
/**
* Writes a 3D angle vector to a writable bitbuffer (bf_write).
*
* @param bf bf_write handle to write to.
* @param angles Angle vector to write.
* @error Invalid or incorrect Handle.
*/
native void BfWriteAngles(Handle bf, float angles[3]);
/**
* Reads a single bit from a readable bitbuffer (bf_read).
*
* @param bf bf_read handle to read from.
* @return Bit value read.
* @error Invalid or incorrect Handle.
*/
native bool BfReadBool(Handle bf);
/**
* Reads a byte from a readable bitbuffer (bf_read).
*
* @param bf bf_read handle to read from.
* @return Byte value read (read as 8bit).
* @error Invalid or incorrect Handle.
*/
native int BfReadByte(Handle bf);
/**
* Reads a character from a readable bitbuffer (bf_read).
*
* @param bf bf_read handle to read from.
* @return Character value read.
* @error Invalid or incorrect Handle.
*/
native int BfReadChar(Handle bf);
/**
* Reads a 16bit integer from a readable bitbuffer (bf_read).
*
* @param bf bf_read handle to read from.
* @return Integer value read (read as 16bit).
* @error Invalid or incorrect Handle.
*/
native int BfReadShort(Handle bf);
/**
* Reads a 16bit unsigned integer from a readable bitbuffer (bf_read).
*
* @param bf bf_read handle to read from.
* @return Integer value read (read as 16bit).
* @error Invalid or incorrect Handle.
*/
native int BfReadWord(Handle bf);
/**
* Reads a normal integer to a readable bitbuffer (bf_read).
*
* @param bf bf_read handle to read from.
* @return Integer value read (read as 32bit).
* @error Invalid or incorrect Handle.
*/
native int BfReadNum(Handle bf);
/**
* Reads a floating point number from a readable bitbuffer (bf_read).
*
* @param bf bf_read handle to read from.
* @return Floating point value read.
* @error Invalid or incorrect Handle.
*/
native float BfReadFloat(Handle bf);
/**
* Reads a string from a readable bitbuffer (bf_read).
*
* @param bf bf_read handle to read from.
* @param buffer Destination string buffer.
* @param maxlength Maximum length of output string buffer.
* @param line If true the buffer will be copied until it reaches a '\n' or a null terminator.
* @return Number of bytes written to the buffer. If the bitbuffer stream overflowed,
* that is, had no terminator before the end of the stream, then a negative
* number will be returned equal to the number of characters written to the
* buffer minus 1. The buffer will be null terminated regardless of the
* return value.
* @error Invalid or incorrect Handle.
*/
native int BfReadString(Handle bf, char[] buffer, int maxlength, bool line=false);
/**
* Reads an entity from a readable bitbuffer (bf_read).
* @note This is a wrapper around BfReadShort().
*
* @param bf bf_read handle to read from.
* @return Entity index read.
* @error Invalid or incorrect Handle.
*/
native int BfReadEntity(Handle bf);
/**
* Reads a bit angle from a readable bitbuffer (bf_read).
*
* @param bf bf_read handle to read from.
* @param numBits Optional number of bits to use.
* @return Angle read.
* @error Invalid or incorrect Handle.
*/
native float BfReadAngle(Handle bf, int numBits=8);
/**
* Reads a coordinate from a readable bitbuffer (bf_read).
*
* @param bf bf_read handle to read from.
* @return Coordinate read.
* @error Invalid or incorrect Handle.
*/
native float BfReadCoord(Handle bf);
/**
* Reads a 3D vector of coordinates from a readable bitbuffer (bf_read).
*
* @param bf bf_read handle to read from.
* @param coord Destination coordinate array.
* @error Invalid or incorrect Handle.
*/
native void BfReadVecCoord(Handle bf, float coord[3]);
/**
* Reads a 3D normal vector from a readable bitbuffer (bf_read).
*
* @param bf bf_read handle to read from.
* @param vec Destination vector array.
* @error Invalid or incorrect Handle.
*/
native void BfReadVecNormal(Handle bf, float vec[3]);
/**
* Reads a 3D angle vector from a readable bitbuffer (bf_read).
*
* @param bf bf_read handle to read from.
* @param angles Destination angle vector.
* @error Invalid or incorrect Handle.
*/
native void BfReadAngles(Handle bf, float angles[3]);
/**
* Returns the number of bytes left in a readable bitbuffer (bf_read).
*
* @param bf bf_read handle to read from.
* @return Number of bytes left unread.
* @error Invalid or incorrect Handle.
*/
native int BfGetNumBytesLeft(Handle bf);

View File

@@ -0,0 +1,123 @@
#if defined _boss_spawns_included
#endinput
#endif
#define _boss_spawns_included
/**
* Spawns a Hatman on the map. (Horsemann)
*
* @param client Client spawning the boss. (0 = Console)
* @param X Float value for X parameter of spawn location.
* @param Y Float value for Y parameter of spawn location.
* @param Z Float value for Z parameter of spawn location.
* @param scale Float value for the scale of the boss.
* @param glow True if boss should glow, false if not.
* @param spew True if to log, reply & show activity, false otherwise.
*
* @return True if spawned successfully, false otherwise.
* @error Invalid client or fields.
*/
native bool:TF2_SpawnHatman(client, Float:X = 0.0, Float:Y = 0.0, Float:Z = 0.0, Float:scale = 1.0, bool:glow = false, bool:spew = true);
/**
* Spawns an Eyeboss on the map. (Monoculus)
*
* @param client Client spawning the boss. (0 = Console)
* @param X Float value for X parameter of spawn location.
* @param Y Float value for Y parameter of spawn location.
* @param Z Float value for Z parameter of spawn location.
* @param scale Float value for the scale of the boss.
* @param glow True if boss should glow, false if not.
* @param spew True if to log, reply & show activity, false otherwise.
* @param type Type of Eyeboss: (0 = Normal, 1 = Red, 2 = Blue)
*
* @return True if spawned successfully, false otherwise.
* @error Invalid client or fields.
*/
native bool:TF2_SpawnEyeboss(client, Float:X = 0.0, Float:Y = 0.0, Float:Z = 0.0, Float:scale = 1.0, bool:glow = false, bool:spew = true, type = 0);
/**
* Spawns Merasmus on the map.
*
* @param client Client spawning the boss. (0 = Console)
* @param X Float value for X parameter of spawn location.
* @param Y Float value for Y parameter of spawn location.
* @param Z Float value for Z parameter of spawn location.
* @param scale Float value for the scale of the boss.
* @param glow True if boss should glow, false if not.
* @param spew True if to log, reply & show activity, false otherwise.
*
* @return True if spawned successfully, false otherwise.
* @error Invalid client or fields.
*/
native bool:TF2_SpawnMerasmus(client, Float:X = 0.0, Float:Y = 0.0, Float:Z = 0.0, Float:scale = 1.0, bool:glow = false, bool:spew = true);
/**
* Spawns a Skeleton on the map.
*
* @param client Client spawning the boss. (0 = Console)
* @param X Float value for X parameter of spawn location.
* @param Y Float value for Y parameter of spawn location.
* @param Z Float value for Z parameter of spawn location.
* @param scale Float value for the scale of the boss.
* @param glow True if boss should glow, false if not.
* @param spew True if to log, reply & show activity, false otherwise.
* @param type Type of Skeleton: (0 = Green, 1 = Red, 2 = Blue)
*
* @return True if spawned successfully, false otherwise.
* @error Invalid client or fields.
*/
native bool:TF2_SpawnSkeleton(client, Float:X = 0.0, Float:Y = 0.0, Float:Z = 0.0, Float:scale = 1.0, bool:glow = false, bool:spew = true, type = 0);
/**
* Spawns the Skeleton King on the map.
*
* @param client Client spawning the boss. (0 = Console)
* @param X Float value for X parameter of spawn location.
* @param Y Float value for Y parameter of spawn location.
* @param Z Float value for Z parameter of spawn location.
* @param glow True if boss should glow, false if not.
* @param spew True if to log, reply & show activity, false otherwise.
*
* @return True if spawned successfully, false otherwise.
* @error Invalid client or fields.
*/
native bool:TF2_SpawnSkeletonKing(client, Float:X = 0.0, Float:Y = 0.0, Float:Z = 0.0, bool:glow = false, bool:spew = true);
/**
* Spawns the Ghost on the map.
*
* @param client Client spawning the boss. (0 = Console)
* @param X Float value for X parameter of spawn location.
* @param Y Float value for Y parameter of spawn location.
* @param Z Float value for Z parameter of spawn location.
* @param glow True if boss should glow, false if not.
* @param spew True if to log, reply & show activity, false otherwise.
*
* @return True if spawned successfully, false otherwise.
* @error Invalid client or fields.
*/
native bool:TF2_SpawnGhost(client, Float:X = 0.0, Float:Y = 0.0, Float:Z = 0.0, bool:glow = false, bool:spew = true);
public SharedPlugin:__pl_boss_spawns =
{
name = "BossSpawns",
file = "BossSpawns.smx",
#if defined REQUIRE_PLUGIN
required = 1,
#else
required = 0,
#endif
};
#if !defined REQUIRE_PLUGIN
public __pl_boss_spawns_SetNTVOptional()
{
MarkNativeAsOptional("TF2_SpawnHatman");
MarkNativeAsOptional("TF2_SpawnEyeboss");
MarkNativeAsOptional("TF2_SpawnMerasmus");
MarkNativeAsOptional("TF2_SpawnSkeleton");
MarkNativeAsOptional("TF2_SpawnSkeletonKing");
MarkNativeAsOptional("TF2_SpawnGhost");
}
#endif

View File

@@ -0,0 +1,79 @@
#if defined _chat_processor_included
#endinput
#endif
#define _chat_processor_included
//Globals
#define MAXLENGTH_FLAG 32
#define MAXLENGTH_NAME 128
#define MAXLENGTH_MESSAGE 128
#define MAXLENGTH_BUFFER 255
//Natives
/**
* Retrieves the current format string assigned from a flag string.
* Example: "Cstrike_Chat_All" = "{1} : {2}"
* You can find the config formats in either the translations or the configs.
*
* param sFlag Flag string to retrieve the format string from.
* param sBuffer Format string from the flag string.
* param iSize Size of the format string buffer.
*
* noreturn
**/
native void ChatProcessor_GetFlagFormatString(const char[] sFlag, char[] sBuffer, int iSize);
//Forwards
/**
* Called while sending a chat message before It's sent.
* Limits on the name and message strings can be found above.
*
* param author Author that created the message.
* param recipients Array of clients who will receive the message.
* param flagstring Flag string to determine the type of message.
* param name Name string of the author to be pushed.
* param message Message string from the author to be pushed.
* param processcolors Toggle to process colors in the buffer strings.
* param removecolors Toggle to remove colors in the buffer strings. (Requires bProcessColors = true)
*
* return types
* - Plugin_Continue Stops the message.
* - Plugin_Stop Stops the message.
* - Plugin_Changed Fires the post-forward below and prints out a message.
* - Plugin_Handled Fires the post-forward below but doesn't print a message.
**/
forward Action CP_OnChatMessage(int& author, ArrayList recipients, char[] flagstring, char[] name, char[] message, bool& processcolors, bool& removecolors);
/**
* Called after the chat message is sent to the designated clients by the author.
*
* param author Author that sent the message.
* param recipients Array of clients who received the message.
* param flagstring Flag string to determine the type of message.
* param formatstring Format string used in the message based on the flag string.
* param name Name string of the author.
* param message Message string from the author.
* param processcolors Check if colors were processed in the buffer strings.
* param removecolors Check if colors were removed from the buffer strings.
*
* noreturn
**/
forward void CP_OnChatMessagePost(int author, ArrayList recipients, const char[] flagstring, const char[] formatstring, const char[] name, const char[] message, bool processcolors, bool removecolors);
#if !defined REQUIRE_PLUGIN
public void __pl_chat_processor_SetNTVOptional()
{
MarkNativeAsOptional("ChatProcessor_GetFlagFormatString");
}
#endif
public SharedPlugin __pl_chat_processor =
{
name = "chat-processor",
file = "chat-processor.smx",
#if defined REQUIRE_PLUGIN
required = 1
#else
required = 0
#endif
};

View File

@@ -0,0 +1,170 @@
/*
* Simple Chat colors Include by PaxPlay
*
* Credits to shavit.
* Supported Games: CSGO, CSS
*/
#if defined _SCC_PAX_included
#endinput
#endif
#define _SCC_PAX_included
char gS_CSSRGBColorNames[][] =
{
"{RGB}", // this string must follow a hex color code (i.e. {RGB}00ff00 for green)
"{RGBA}" // same but with alpha channel
};
char gS_CSSRGBColors[][] =
{
"\x07", // this string must follow a hex color code (i.e. {RGB}00ff00 for green)
"\x08" // same but with alpha channel
};
char gS_GlobalColorNames[][] =
{
"{default}",
"{team}",
"{green}"
};
char gS_GlobalColors[][] =
{
"\x01",
"\x03",
"\x04"
};
char gS_CSGOColorNames[][] =
{
"{blue}",
"{bluegrey}",
"{darkblue}",
"{darkred}",
"{gold}",
"{grey}",
"{grey2}",
"{lightgreen}",
"{lightred}",
"{lime}",
"{orchid}",
"{palered}",
"{yellow}"
};
char gS_CSGOColors[][] =
{
"\x0B",
"\x0A",
"\x0C",
"\x02",
"\x10",
"\x08",
"\x0D",
"\x05",
"\x0F",
"\x06",
"\x0E",
"\x07",
"\x09"
};
/**
* Replaces chat color strings between "{}" with the color belonging to it.
*
* @param buffer Buffer String.
* @param maxlength Length of buffer.
*
*/
stock void SCC_ReplaceColors(char[] buffer, int maxlength)
{
EngineVersion gEV_Type = GetEngineVersion();
for(int i = 0; i < sizeof(gS_GlobalColorNames); i++)
{
ReplaceString(buffer, maxlength, gS_GlobalColorNames[i], gS_GlobalColors[i]);
}
if (gEV_Type == Engine_CSS)
{
for(int i = 0; i < sizeof(gS_CSSRGBColorNames); i++)
{
ReplaceString(buffer, maxlength, gS_CSSRGBColorNames[i], gS_CSSRGBColors[i]);
}
}
else // Remove Tags anyways
{
for(int i = 0; i < sizeof(gS_CSSRGBColorNames); i++)
{
if (ReplaceString(buffer, maxlength, gS_CSSRGBColorNames[i], "") > 0)
LogMessage("\"%s\" is not supported in this game.", gS_CSSRGBColorNames[i]);
}
}
if (gEV_Type == Engine_CSGO)
{
for(int i = 0; i < sizeof(gS_CSGOColorNames); i++)
{
ReplaceString(buffer, maxlength, gS_CSGOColorNames[i], gS_CSGOColors[i]);
}
}
else // Remove Tags anyways
{
for(int i = 0; i < sizeof(gS_CSGOColorNames); i++)
{
if (ReplaceString(buffer, maxlength, gS_CSGOColorNames[i], "") > 0)
LogMessage("\"%s\" is not supported in this game.", gS_CSGOColorNames[i]);
}
}
}
/**
* Removes any chat colors from a string.
*
* @param buffer Buffer String.
* @param maxlength Length of buffer.
*
*/
stock void SCC_RemoveColors(char[] buffer, int maxlength)
{
for(int i = 0; i < sizeof(gS_GlobalColors); i++) // no need to check Engine, just remove everything, no need to remove css, since \x07 and \x08 are in csgo aswell
{
ReplaceString(buffer, maxlength, gS_GlobalColors[i], "");
}
for(int i = 0; i < sizeof(gS_CSGOColors); i++)
{
ReplaceString(buffer, maxlength, gS_CSGOColors[i], "");
}
}
/**
* Prints a message to a specific client in the chat area. Replaces chat color strings between "{}" with the color belonging to it.
*
* @param client client index.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
*
*/
stock void SCC_PrintToChat(client, const char[] format, any ...)
{
char buffer[254];
VFormat(buffer, sizeof(buffer), format, 3);
SCC_ReplaceColors(buffer, sizeof(buffer));
PrintToChat(client, "%s", buffer);
}
/**
* Prints a message to all clients in the chat area.Replaces chat color strings between "{}" with the color belonging to it.
*
* @param format Formatting rules.
* @param ... Variable number of format parameters.
*
*/
stock void SCC_PrintToChatAll(const char[] format, any ...)
{
char buffer[254];
VFormat(buffer, sizeof(buffer), format, 3);
SCC_ReplaceColors(buffer, sizeof(buffer));
PrintToChatAll("%s", buffer);
}

View File

@@ -0,0 +1,75 @@
enum struct MENUARRAY {
char alias[64];
char hintText[256];
char title[64];
char url[64];
char item[256];
int size;
}
MENUARRAY DiscordMenu[8];
MENUARRAY RulesMenu[16];
//MENUARRAY VotesMenu[16];
int menuData = -1;
void RegisterAllMenus() {
Handle confMenuDiscord = OpenFile("addons/sourcemod/configs/ChillSkiesMenus/discord.ini", "rt", false);
Handle confMenuRules = OpenFile("addons/sourcemod/configs/ChillSkiesMenus/rules.ini", "rt", false);
Handle confMenuVotes = OpenFile("addons/sourcemod/configs/ChillSkiesMenus/votes.ini", "rt", false);
if (confMenuDiscord == INVALID_HANDLE || confMenuRules == INVALID_HANDLE || confMenuVotes == INVALID_HANDLE) return;
char buffer[256];
int x = -1;
int y = -1;
int z = -1;
LogMessage("Reading configs - discord.ini");
while (ReadFileLine(confMenuDiscord, buffer, sizeof(buffer))) {
TrimString(buffer);
if (!StrContains(buffer, "Title:")) {
ReplaceString(buffer, sizeof(buffer), "Title:", "", true);
Format(DiscordMenu[0].title, 64, buffer);
}
if (!StrContains(buffer, "Item:")) {
x++;
ReplaceString(buffer, sizeof(buffer), "Item:", "", true);
Format(DiscordMenu[x].item, 64, buffer);
}
if (!StrContains(buffer, "Alias:")) {
ReplaceString(buffer, sizeof(buffer), "Alias:", "", true);
Format(DiscordMenu[0].alias, 64, buffer);
}
if (!StrContains(buffer, "URL:")) {
ReplaceString(buffer, sizeof(buffer), "URL:", "", true);
Format(DiscordMenu[0].url, 64, buffer);
}
DiscordMenu[0].size = x + 1;
if (IsEndOfFile(confMenuDiscord)) break;
}
CloseHandle(confMenuDiscord);
LogMessage("Reading configs - rules.ini");
while (ReadFileLine(confMenuRules, buffer, sizeof(buffer))) {
TrimString(buffer);
if (!StrContains(buffer, "Title:")) {
ReplaceString(buffer, sizeof(buffer), "Title:", "", true);
Format(RulesMenu[0].title, 64, buffer);
}
if (!StrContains(buffer, "HintText:")) {
y++;
ReplaceString(buffer, sizeof(buffer), "HintText:", "", true);
Format(RulesMenu[y].hintText, 256, buffer);
PrintToServer("Setting RulesMenu[%i].hintText to %s", y, buffer);
}
if (!StrContains(buffer, "Rule:")) {
z++;
ReplaceString(buffer, sizeof(buffer), "Rule:", "", true);
Format(RulesMenu[z].item, 256, buffer);
PrintToServer("Setting RulesMenu[%i].item to %s", z, buffer);
}
RulesMenu[0].size = z + 1;
if (IsEndOfFile(confMenuRules)) break;
}
CloseHandle(confMenuRules);
}
//Check if the client is valid
stock bool IsValidClient(int client) {
return (0 < client <= MaxClients && IsClientInGame(client) && !IsFakeClient(client));
}

View File

@@ -0,0 +1,433 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2011 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _clientprefs_included
#endinput
#endif
#define _clientprefs_included
/**
* Cookie access types for client viewing
*/
enum CookieAccess
{
CookieAccess_Public, /**< Visible and Changeable by users */
CookieAccess_Protected, /**< Read only to users */
CookieAccess_Private /**< Completely hidden cookie */
};
/**
* Cookie Prefab menu types
*/
enum CookieMenu
{
CookieMenu_YesNo, /**< Yes/No menu with "yes"/"no" results saved into the cookie */
CookieMenu_YesNo_Int, /**< Yes/No menu with 1/0 saved into the cookie */
CookieMenu_OnOff, /**< On/Off menu with "on"/"off" results saved into the cookie */
CookieMenu_OnOff_Int /**< On/Off menu with 1/0 saved into the cookie */
};
enum CookieMenuAction
{
/**
* An option is being drawn for a menu.
*
* INPUT : Client index and data if available.
* OUTPUT: Buffer for rendering, maxlength of buffer.
*/
CookieMenuAction_DisplayOption = 0,
/**
* A menu option has been selected.
*
* INPUT : Client index and any data if available.
*/
CookieMenuAction_SelectOption = 1
};
#define COOKIE_MAX_NAME_LENGTH 30 /**< Maximum Cookie name length. */
#define COOKIE_MAX_DESCRIPTION_LENGTH 255 /**< Maximum Cookie description length. */
/**
* Cookie Menu Callback prototype
*
* @param client Client index.
* @param action CookieMenuAction being performed.
* @param info Info data passed.
* @param buffer Outbut buffer.
* @param maxlen Max length of the output buffer.
*/
typedef CookieMenuHandler = function void (
int client,
CookieMenuAction action,
any info,
char[] buffer,
int maxlen
);
/**
* Note:
*
* A successful return value/result on any client prefs native only guarantees that the local cache has been updated.
* Database connection problems can still prevent the data from being permanently saved. Connection problems will be logged as
* errors by the clientprefs extension.
*/
methodmap Cookie < Handle {
// Creates a new Client preference cookie.
//
// Handles returned can be closed via CloseHandle() when
// no longer needed.
//
// @param name Name of the new preference cookie.
// @param description Optional description of the preference cookie.
// @param access What CookieAccess level to assign to this cookie.
// @return A handle to the newly created cookie. If the cookie already
// exists, a handle to it will still be returned.
// @error Cookie name is blank.
public native Cookie(const char[] name, const char[] description, CookieAccess access);
// Searches for a Client preference cookie.
//
// Handles returned by Cookie.Find can be closed via CloseHandle() when
// no longer needed.
//
// @param name Name of cookie to find.
// @return A handle to the cookie if it is found, null otherwise.
public static native Cookie Find(const char[] name);
// Set the value of a Client preference cookie.
//
// @param client Client index.
// @param value String value to set.
// @error Invalid cookie handle or invalid client index.
public native void Set(int client, const char[] value);
// Set the integer value of a Client preference cookie.
//
// @param client Client index.
// @param value Integer value to set.
// @error Invalid cookie handle or invalid client index.
public void SetInt(int client, int value) {
char sValue[12];
IntToString(value, sValue, sizeof(sValue));
this.Set(client, sValue);
}
// Set the float value of a Client preference cookie.
//
// @param client Client index.
// @param value Float value to set.
// @error Invalid cookie handle or invalid client index.
public void SetFloat(int client, float value) {
char sValue[32];
FloatToString(value, sValue, sizeof(sValue));
this.Set(client, sValue);
}
// Retrieve the value of a Client preference cookie.
//
// @param client Client index.
// @param buffer Copyback buffer for value.
// @param maxlen Maximum length of the buffer.
// @error Invalid cookie handle or invalid client index.
public native void Get(int client, char[] buffer, int maxlen);
// Retrieve the integer value of a Client preference cookie.
//
// @param client Client index.
// @return Integer value of cookie
// @error Invalid cookie handle or invalid client index.
public int GetInt(int client, int defaultValue = 0)
{
char buffer[12];
this.Get(client, buffer, sizeof(buffer));
int value;
if (!StringToIntEx(buffer, value))
{
value = defaultValue;
}
return value;
}
// Retrieve the float value of a Client preference cookie.
//
// @param client Client index.
// @return Float value of cookie
// @error Invalid cookie handle or invalid client index.
public float GetFloat(int client, float defaultValue = 0.0)
{
char buffer[32];
this.Get(client, buffer, sizeof(buffer));
float value;
if (!StringToFloatEx(buffer, value))
{
value = defaultValue;
}
return value;
}
// Set the value of a Client preference cookie based on an authID string.
//
// @param authID String Auth/STEAM ID of player to set.
// @param value String value to set.
// @error Invalid cookie handle.
public native void SetByAuthId(const char[] authID, const char[] value);
// Add a new prefab item to the client cookie settings menu.
//
// Note: This handles everything automatically and does not require a callback
//
// @param type A CookieMenu prefab menu type.
// @param display Text to show on the menu.
// @param handler Optional handler callback for translations and output on selection
// @param info Info data to pass to the callback.
// @error Invalid cookie handle.
public native void SetPrefabMenu(CookieMenu type, const char[] display, CookieMenuHandler handler=INVALID_FUNCTION, any info=0);
// Returns the last updated timestamp for a client cookie
//
// @param client Client index.
// @return Last updated timestamp.
public native int GetClientTime(int client);
// Returns the access level of a cookie
//
// @return CookieAccess access level.
// @error Invalid cookie handle.
property CookieAccess AccessLevel {
public native get();
}
};
/**
* Creates a new Client preference cookie.
*
* Handles returned by RegClientCookie can be closed via CloseHandle() when
* no longer needed.
*
* @param name Name of the new preference cookie.
* @param description Optional description of the preference cookie.
* @param access What CookieAccess level to assign to this cookie.
* @return A handle to the newly created cookie. If the cookie already
* exists, a handle to it will still be returned.
* @error Cookie name is blank.
*/
native Cookie RegClientCookie(const char[] name, const char[] description, CookieAccess access);
/**
* Searches for a Client preference cookie.
*
* Handles returned by FindClientCookie can be closed via CloseHandle() when
* no longer needed.
*
* @param name Name of cookie to find.
* @return A handle to the cookie if it is found, null otherwise.
*/
native Cookie FindClientCookie(const char[] name);
/**
* Set the value of a Client preference cookie.
*
* @param client Client index.
* @param cookie Client preference cookie handle.
* @param value String value to set.
* @error Invalid cookie handle or invalid client index.
*/
native void SetClientCookie(int client, Handle cookie, const char[] value);
/**
* Retrieve the value of a Client preference cookie.
*
* @param client Client index.
* @param cookie Client preference cookie handle.
* @param buffer Copyback buffer for value.
* @param maxlen Maximum length of the buffer.
* @error Invalid cookie handle or invalid client index.
*/
native void GetClientCookie(int client, Handle cookie, char[] buffer, int maxlen);
/**
* Sets the value of a Client preference cookie based on an authID string.
*
* @param authID String Auth/STEAM ID of player to set.
* @param cookie Client preference cookie handle.
* @param value String value to set.
* @error Invalid cookie handle.
*/
native void SetAuthIdCookie(const char[] authID, Handle cookie, const char[] value);
/**
* Checks if a clients cookies have been loaded from the database.
*
* @param client Client index.
* @return True if loaded, false otherwise.
* @error Invalid client index.
*/
native bool AreClientCookiesCached(int client);
/**
* Called once a client's saved cookies have been loaded from the database.
*
* @param client Client index.
*/
forward void OnClientCookiesCached(int client);
/**
* Add a new prefab item to the client cookie settings menu.
*
* Note: This handles everything automatically and does not require a callback
*
* @param cookie Client preference cookie handle.
* @param type A CookieMenu prefab menu type.
* @param display Text to show on the menu.
* @param handler Optional handler callback for translations and output on selection
* @param info Info data to pass to the callback.
* @error Invalid cookie handle.
*/
native void SetCookiePrefabMenu(Handle cookie, CookieMenu type, const char[] display, CookieMenuHandler handler=INVALID_FUNCTION, any info=0);
/**
* Adds a new item to the client cookie settings menu.
*
* Note: This only adds the top level menu item. You need to handle any submenus from the callback.
*
* @param handler A MenuHandler callback function.
* @param info Data to pass to the callback.
* @param display Text to show on the menu.
* @error Invalid cookie handle.
*/
native void SetCookieMenuItem(CookieMenuHandler handler, any info, const char[] display);
/**
* Displays the settings menu to a client.
*
* @param client Client index.
*/
native void ShowCookieMenu(int client);
/**
* Gets a cookie iterator. Must be freed with CloseHandle().
*
* @return A new cookie iterator.
*/
native Handle GetCookieIterator();
/**
* Reads a cookie iterator, then advances to the next cookie if any.
*
* @param iter Cookie iterator Handle.
* @param name Name buffer.
* @param nameLen Name buffer size.
* @param access Access level of the cookie.
* @param desc Cookie description buffer.
* @param descLen Cookie description buffer size.
* @return True on success, false if there are no more commands.
*/
native bool ReadCookieIterator(Handle iter,
char[] name,
int nameLen,
CookieAccess &access,
char[] desc="",
int descLen=0);
/**
* Returns the access level of a cookie
*
* @param cookie Client preference cookie handle.
* @return CookieAccess access level.
* @error Invalid cookie handle.
*/
native CookieAccess GetCookieAccess(Handle cookie);
/**
* Returns the last updated timestamp for a client cookie
*
* @param client Client index.
* @param cookie Cookie handle.
* @return Last updated timestamp.
*/
native int GetClientCookieTime(int client, Handle cookie);
/**
* Do not edit below this line!
*/
public Extension __ext_cprefs =
{
name = "Client Preferences",
file = "clientprefs.ext",
#if defined AUTOLOAD_EXTENSIONS
autoload = 1,
#else
autoload = 0,
#endif
#if defined REQUIRE_EXTENSIONS
required = 1,
#else
required = 0,
#endif
};
#if !defined REQUIRE_EXTENSIONS
public void __ext_cprefs_SetNTVOptional()
{
MarkNativeAsOptional("RegClientCookie");
MarkNativeAsOptional("FindClientCookie");
MarkNativeAsOptional("SetClientCookie");
MarkNativeAsOptional("GetClientCookie");
MarkNativeAsOptional("SetAuthIdCookie");
MarkNativeAsOptional("AreClientCookiesCached");
MarkNativeAsOptional("SetCookiePrefabMenu");
MarkNativeAsOptional("SetCookieMenuItem");
MarkNativeAsOptional("ShowCookieMenu");
MarkNativeAsOptional("GetCookieIterator");
MarkNativeAsOptional("ReadCookieIterator");
MarkNativeAsOptional("GetCookieAccess");
MarkNativeAsOptional("GetClientCookieTime");
MarkNativeAsOptional("Cookie.Cookie");
MarkNativeAsOptional("Cookie.Find");
MarkNativeAsOptional("Cookie.Set");
MarkNativeAsOptional("Cookie.Get");
MarkNativeAsOptional("Cookie.SetByAuthId");
MarkNativeAsOptional("Cookie.SetPrefabMenu");
MarkNativeAsOptional("Cookie.GetClientTime");
MarkNativeAsOptional("Cookie.AccessLevel.get");
}
#endif

View File

@@ -0,0 +1,843 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _clients_included
#endinput
#endif
#define _clients_included
/**
* Network flow directions.
*/
enum NetFlow
{
NetFlow_Outgoing = 0, /**< Outgoing traffic */
NetFlow_Incoming, /**< Incoming traffic */
NetFlow_Both /**< Both values added together */
};
/**
* Auth string types.
*
* Note that for the Steam2 and Steam3 types, the following ids are
* also valid values:
* "STEAM_ID_PENDING" - Authentication is pending.
* "STEAM_ID_LAN" - Authentication is disabled because of being on a LAN server.
* "BOT" - The client is a bot.
*/
enum AuthIdType
{
AuthId_Engine = 0, /**< The game-specific auth string as returned from the engine */
// The following are only available on games that support Steam authentication.
AuthId_Steam2, /**< Steam2 rendered format, ex "STEAM_1:1:4153990" */
AuthId_Steam3, /**< Steam3 rendered format, ex "[U:1:8307981]" */
AuthId_SteamID64 /**< A SteamID64 (uint64) as a String, ex "76561197968573709" */
};
/**
* MAXPLAYERS is not the same as MaxClients.
* MAXPLAYERS is a hardcoded value as an upper limit. MaxClients changes based on the server.
*/
#define MAXPLAYERS 101 /**< Maximum number of players SourceMod supports */
#define MAX_NAME_LENGTH 128 /**< Maximum buffer required to store a client name */
#define MAX_AUTHID_LENGTH 64 /**< Maximum buffer required to store any AuthID type */
public const int MaxClients; /**< Maximum number of players the server supports (dynamic) */
/**
* Called on client connection. If you return true, the client will be allowed in the server.
* If you return false (or return nothing), the client will be rejected. If the client is
* rejected by this forward or any other, OnClientDisconnect will not be called.
*
* Note: Do not write to rejectmsg if you plan on returning true. If multiple plugins write
* to the string buffer, it is not defined which plugin's string will be shown to the client,
* but it is guaranteed one of them will.
*
* @param client Client index.
* @param rejectmsg Buffer to store the rejection message when the connection is refused.
* @param maxlen Maximum number of characters for rejection buffer.
* @return True to validate client's connection, false to refuse it.
*/
forward bool OnClientConnect(int client, char[] rejectmsg, int maxlen);
/**
* Called once a client successfully connects. This callback is paired with OnClientDisconnect.
*
* @param client Client index.
*/
forward void OnClientConnected(int client);
/**
* Called when a client is entering the game.
*
* Whether a client has a steamid is undefined until OnClientAuthorized
* is called, which may occur either before or after OnClientPutInServer.
* Similarly, use OnClientPostAdminCheck() if you need to verify whether
* connecting players are admins.
*
* GetClientCount() will include clients as they are passed through this
* function, as clients are already in game at this point.
*
* @param client Client index.
*/
forward void OnClientPutInServer(int client);
/**
* Called when a client is disconnecting from the server.
*
* @param client Client index.
*/
forward void OnClientDisconnect(int client);
/**
* Called when a client is disconnected from the server.
*
* @param client Client index.
*/
forward void OnClientDisconnect_Post(int client);
/**
* Called when a client is sending a command.
*
* As of SourceMod 1.3, the client is guaranteed to be in-game.
* Use command listeners (console.inc) for more advanced hooks.
*
* @param client Client index.
* @param args Number of arguments.
* @return Plugin_Handled blocks the command from being sent,
* and Plugin_Continue resumes normal functionality.
*/
forward Action OnClientCommand(int client, int args);
/**
* Called when a client is sending a KeyValues command.
*
* @param client Client index.
* @param kv Editable KeyValues data to be sent as the command.
* (This handle should not be stored and will be closed
* after this forward completes.)
* @return Plugin_Handled blocks the command from being sent,
* and Plugin_Continue resumes normal functionality.
*/
forward Action OnClientCommandKeyValues(int client, KeyValues kv);
/**
* Called after a client has sent a KeyValues command.
*
* @param client Client index.
* @param kv KeyValues data sent as the command.
* (This handle should not be stored and will be closed
* after this forward completes.)
*/
forward void OnClientCommandKeyValues_Post(int client, KeyValues kv);
/**
* Called whenever the client's settings are changed.
*
* @param client Client index.
*/
forward void OnClientSettingsChanged(int client);
/**
* Called when a client receives an auth ID. The state of a client's
* authorization as an admin is not guaranteed here. Use
* OnClientPostAdminCheck() if you need a client's admin status.
*
* This is called by bots, but the ID will be "BOT".
*
* @param client Client index.
* @param auth Client Steam2 id, if available, else engine auth id.
*/
forward void OnClientAuthorized(int client, const char[] auth);
/**
* Called once a client is authorized and fully in-game, but
* before admin checks are done. This can be used to override
* the default admin checks for a client. You should only use
* this for overriding; use OnClientPostAdminCheck() instead
* if you want notification.
*
* Note: If handled/blocked, PostAdminCheck must be signalled
* manually via NotifyPostAdminCheck().
*
* This callback is guaranteed to occur on all clients, and always
* after each OnClientPutInServer() call.
*
* @param client Client index.
* @return Plugin_Handled to block admin checks.
*/
forward Action OnClientPreAdminCheck(int client);
/**
* Called directly before OnClientPostAdminCheck() as a method to
* alter administrative permissions before plugins perform final
* post-connect operations.
*
* In general, do not use this function unless you are specifically
* attempting to change access permissions. Use OnClientPostAdminCheck()
* instead if you simply want to perform post-connect authorization
* routines.
*
* See OnClientPostAdminCheck() for more information.
*
* @param client Client index.
*/
forward void OnClientPostAdminFilter(int client);
/**
* Called directly before the server enters hibernation.
* This is your last chance to do anything in the plugin before
* hibernation occurs, as SV_Frame will no longer be called.
*/
forward void OnServerEnterHibernation();
/**
* Called directly before the server leaves hibernation.
*/
forward void OnServerExitHibernation();
/**
* Called once a client is authorized and fully in-game, and
* after all post-connection authorizations have been performed.
*
* This callback is guaranteed to occur on all clients, and always
* after each OnClientPutInServer() call.
*
* @param client Client index.
*/
forward void OnClientPostAdminCheck(int client);
/**
* Called when the language was received from the player.
*
* @param client Client index.
* @param language Language number.
*/
forward void OnClientLanguageChanged(int client, int language);
/**
* This function is deprecated. Use the MaxClients variable instead.
*
* Returns the maximum number of clients allowed on the server. This may
* return 0 if called before OnMapStart(), and thus should not be called
* in OnPluginStart().
*
* You should not globally cache the value to GetMaxClients() because it can change from
* SourceTV or TF2's arena mode. Use the "MaxClients" dynamic variable documented at the
* top of this file.
*
* @return Maximum number of clients allowed.
* @deprecated Use MaxClients variable instead.
*/
#pragma deprecated Use MaxClients variable instead.
native int GetMaxClients();
/**
* Returns the maximum number of human players allowed on the server. This is
* a game-specific function used on newer games to limit the number of humans
* that can join a game and can be lower than MaxClients. It is the number often
* reflected in the server browser or when viewing the output of the status command.
* On unsupported games or modes without overrides, it will return the same value
* as MaxClients.
*
* You should not globally cache the value to GetMaxHumanPlayers() because it can change across
* game modes. You may still cache it locally.
*
* @return Maximum number of humans allowed.
*/
native int GetMaxHumanPlayers();
/**
* Returns the client count put in the server.
*
* @param inGameOnly If false connecting players are also counted.
* @return Client count in the server.
*/
native int GetClientCount(bool inGameOnly=true);
/**
* Returns the client's name.
*
* @param client Player index.
* @param name Buffer to store the client's name.
* @param maxlen Maximum length of string buffer (includes NULL terminator).
* @return True on success, false otherwise.
* @error If the client is not connected an error will be thrown.
*/
native bool GetClientName(int client, char[] name, int maxlen);
/**
* Retrieves a client's IP address.
*
* @param client Player index.
* @param ip Buffer to store the client's ip address.
* @param maxlen Maximum length of string buffer (includes NULL terminator).
* @param remport Remove client's port from the ip string (true by default).
* @return True on success, false otherwise.
* @error If the client is not connected or the index is invalid.
*/
native bool GetClientIP(int client, char[] ip, int maxlen, bool remport=true);
/**
* Retrieves a client's authentication string (SteamID).
*
* @param client Player index.
* @param auth Buffer to store the client's auth string.
* @param maxlen Maximum length of string buffer (includes NULL terminator).
* @param validate Check backend validation status.
* DO NOT PASS FALSE UNLESS YOU UNDERSTAND THE CONSEQUENCES,
* You WILL KNOW if you need to use this, MOST WILL NOT.
* @return True on success, false otherwise.
* @error If the client is not connected or the index is invalid.
* @deprecated Use GetClientAuthId
*/
#pragma deprecated Use GetClientAuthId
native bool GetClientAuthString(int client, char[] auth, int maxlen, bool validate=true);
/**
* Retrieves a client's authentication string (SteamID).
*
* @param client Player index.
* @param authType Auth id type and format to use.
* @param auth Buffer to store the client's auth id.
* @param maxlen Maximum length of string buffer (includes NULL terminator).
* @param validate Check backend validation status.
* DO NOT PASS FALSE UNLESS YOU UNDERSTAND THE CONSEQUENCES,
* You WILL KNOW if you need to use this, MOST WILL NOT.
* @return True on success, false otherwise.
* @error If the client is not connected or the index is invalid.
*/
native bool GetClientAuthId(int client, AuthIdType authType, char[] auth, int maxlen, bool validate=true);
/**
* Returns the client's Steam account ID, a number uniquely identifying a given Steam account.
* This number is the basis for the various display SteamID forms, see the AuthIdType enum for examples.
*
* @param client Client Index.
* @param validate Check backend validation status.
* DO NOT PASS FALSE UNLESS YOU UNDERSTAND THE CONSEQUENCES,
* You WILL KNOW if you need to use this, MOST WILL NOT.
* @return Steam account ID or 0 if not available.
* @error If the client is not connected or the index is invalid.
*/
native int GetSteamAccountID(int client, bool validate=true);
/**
* Retrieves a client's user id, which is an index incremented for every client
* that joins the server.
*
* @param client Player index.
* @return User id of the client.
* @error If the client is not connected or the index is invalid.
*/
native int GetClientUserId(int client);
/**
* Returns if a certain player is connected.
*
* @param client Player index.
* @return True if player is connected to the server, false otherwise.
* @error Invalid client index.
*/
native bool IsClientConnected(int client);
/**
* Returns if a certain player has entered the game.
*
* @param client Player index (index does not have to be connected).
* @return True if player has entered the game, false otherwise.
* @error Invalid client index.
*/
native bool IsClientInGame(int client);
/**
* Returns if a client is in the "kick queue" (i.e. the client will be kicked
* shortly and thus they should not appear as valid).
*
* @param client Player index (must be connected).
* @return True if in the kick queue, false otherwise.
* @error Invalid client index.
*/
native bool IsClientInKickQueue(int client);
/**
* Backwards compatibility stock - use IsClientInGame
* @deprecated Renamed to IsClientInGame
*/
#pragma deprecated Use IsClientInGame() instead
stock bool IsPlayerInGame(int client)
{
return IsClientInGame(client);
}
/**
* Returns if a certain player has been authenticated.
*
* @param client Player index.
* @return True if player has been authenticated, false otherwise.
* @error Invalid client index.
*/
native bool IsClientAuthorized(int client);
/**
* Returns if a certain player is a fake client.
*
* @param client Player index.
* @return True if player is a fake client, false otherwise.
* @error Invalid client index, or client not connected.
*/
native bool IsFakeClient(int client);
/**
* Returns if a certain player is the SourceTV bot.
*
* @param client Player index.
* @return True if player is the SourceTV bot, false otherwise.
* @error Invalid client index, or client not connected.
*/
native bool IsClientSourceTV(int client);
/**
* Returns if a certain player is the Replay bot.
*
* @param client Player index.
* @return True if player is the Replay bot, false otherwise.
* @error Invalid client index, or client not connected.
*/
native bool IsClientReplay(int client);
/**
* Returns if a certain player is an observer/spectator.
*
* @param client Player index.
* @return True if player is an observer, false otherwise.
* @error Invalid client index, client not in game, or no mod support.
*/
native bool IsClientObserver(int client);
/**
* Returns if the client is alive or dead.
*
* Note: This function was originally in SDKTools and was moved to core.
*
* @param client Player's index.
* @return True if the client is alive, false otherwise.
* @error Invalid client index, client not in game, or no mod support.
*/
native bool IsPlayerAlive(int client);
/**
* Retrieves values from client replicated keys.
*
* @param client Player's index.
* @param key Key string.
* @param value Buffer to store value.
* @param maxlen Maximum length of valve (UTF-8 safe).
* @return True on success, false otherwise.
* @error Invalid client index, or client not connected.
*/
native bool GetClientInfo(int client, const char[] key, char[] value, int maxlen);
/**
* Retrieves a client's team index.
*
* @param client Player's index.
* @return Team index the client is on (mod specific).
* @error Invalid client index, client not in game, or no mod support.
*/
native int GetClientTeam(int client);
/**
* Sets a client's AdminId.
*
* @param client Player's index.
* @param id AdminId to set. INVALID_ADMIN_ID removes admin permissions.
* @param temp True if the id should be freed on disconnect.
* @error Invalid client index, client not connected, or bogus AdminId.
*/
native void SetUserAdmin(int client, AdminId id, bool temp=false);
/**
* Retrieves a client's AdminId.
*
* @param client Player's index.
* @return AdminId of the client, or INVALID_ADMIN_ID if none.
* @error Invalid client index, or client not connected.
*/
native AdminId GetUserAdmin(int client);
/**
* Sets access flags on a client. If the client is not an admin,
* a temporary, anonymous AdminId is given.
*
* @param client Player's index.
* @param ... Flags to set on the client.
* @error Invalid client index, or client not connected.
*/
native void AddUserFlags(int client, AdminFlag ...);
/**
* Removes flags from a client. If the client is not an admin,
* this has no effect.
*
* @param client Player's index.
* @param ... Flags to remove from the client.
* @error Invalid client index, or client not connected.
*/
native void RemoveUserFlags(int client, AdminFlag ...);
/**
* Sets access flags on a client using bits instead of flags. If the
* client is not an admin, and flags not 0, a temporary, anonymous AdminId is given.
*
* @param client Player's index.
* @param flags Bitstring of flags to set on client.
* @error Invalid client index, or client not connected.
*/
native void SetUserFlagBits(int client, int flags);
/**
* Returns client access flags. If the client is not an admin,
* the result is always 0.
*
* @param client Player's index.
* @return Flags
* @error Invalid client index, or client not connected.
*/
native int GetUserFlagBits(int client);
/**
* Returns whether a user can target another user.
* This is a helper function for CanAdminTarget.
*
* @param client Player's index.
* @param target Target player's index.
* @return True if target is targettable by the player, false otherwise.
* @error Invalid or unconnected player indexers.
*/
native bool CanUserTarget(int client, int target);
/**
* Runs through the Core-defined admin authorization checks on a player.
* Has no effect if the player is already an admin.
*
* Note: This function is based on the internal cache only.
*
* @param client Client index.
* @return True if access was changed, false if it did not.
* @error Invalid client index or client not in-game AND authorized.
*/
native bool RunAdminCacheChecks(int client);
/**
* Signals that a player has completed post-connection admin checks.
* Has no effect if the player has already had this event signalled.
*
* Note: This must be sent even if no admin id was assigned.
*
* @param client Client index.
* @error Invalid client index or client not in-game AND authorized.
*/
native void NotifyPostAdminCheck(int client);
/**
* Creates a fake client.
*
* @param name Name to use.
* @return Client index on success, 0 otherwise.
* @error No map is active.
*/
native int CreateFakeClient(const char[] name);
/**
* Sets a convar value on a fake client.
*
* @param client Client index.
* @param cvar ConVar name.
* @param value ConVar value.
* @error Invalid client index, client not connected,
* or client not a fake client.
*/
native void SetFakeClientConVar(int client, const char[] cvar, const char[] value);
/**
* Returns the client's health.
*
* @param client Player's index.
* @return Health value.
* @error Invalid client index, client not in game, or no mod support.
*/
native int GetClientHealth(int client);
/**
* Returns the client's model name.
*
* @param client Player's index.
* @param model Buffer to store the client's model name.
* @param maxlen Maximum length of string buffer (includes NULL terminator).
* @error Invalid client index, client not in game, or no mod support.
*/
native void GetClientModel(int client, char[] model, int maxlen);
/**
* Returns the client's weapon name.
*
* @param client Player's index.
* @param weapon Buffer to store the client's weapon name.
* @param maxlen Maximum length of string buffer (includes NULL terminator).
* @error Invalid client index, client not in game, or no mod support.
*/
native void GetClientWeapon(int client, char[] weapon, int maxlen);
/**
* Returns the client's max size vector.
*
* @param client Player's index.
* @param vec Destination vector to store the client's max size.
* @error Invalid client index, client not in game, or no mod support.
*/
native void GetClientMaxs(int client, float vec[3]);
/**
* Returns the client's min size vector.
*
* @param client Player's index.
* @param vec Destination vector to store the client's min size.
* @error Invalid client index, client not in game, or no mod support.
*/
native void GetClientMins(int client, float vec[3]);
/**
* Returns the client's position angle.
*
* @param client Player's index.
* @param ang Destination vector to store the client's position angle.
* @error Invalid client index, client not in game, or no mod support.
*/
native void GetClientAbsAngles(int client, float ang[3]);
/**
* Returns the client's origin vector.
*
* @param client Player's index.
* @param vec Destination vector to store the client's origin vector.
* @error Invalid client index, client not in game, or no mod support.
*/
native void GetClientAbsOrigin(int client, float vec[3]);
/**
* Returns the client's armor.
*
* @param client Player's index.
* @return Armor value.
* @error Invalid client index, client not in game, or no mod support.
*/
native int GetClientArmor(int client);
/**
* Returns the client's death count.
*
* @param client Player's index.
* @return Death count.
* @error Invalid client index, client not in game, or no mod support.
*/
native int GetClientDeaths(int client);
/**
* Returns the client's frag count.
*
* @param client Player's index.
* @return Frag count.
* @error Invalid client index, client not in game, or no mod support.
*/
native int GetClientFrags(int client);
/**
* Returns the client's send data rate in bytes/sec.
*
* @param client Player's index.
* @return Data rate.
* @error Invalid client index, client not connected, or fake client.
*/
native int GetClientDataRate(int client);
/**
* Returns if a client is timing out
*
* @param client Player's index.
* @return True if client is timing out, false otherwise.
* @error Invalid client index, client not connected, or fake client.
*/
native bool IsClientTimingOut(int client);
/**
* Returns the client's connection time in seconds.
*
* @param client Player's index.
* @return Connection time.
* @error Invalid client index, client not connected, or fake client.
*/
native float GetClientTime(int client);
/**
* Returns the client's current latency (RTT), more accurate than GetAvgLatency but jittering.
*
* @param client Player's index.
* @param flow Traffic flowing direction.
* @return Latency, or -1 if network info is not available.
* @error Invalid client index, client not connected, or fake client.
*/
native float GetClientLatency(int client, NetFlow flow);
/**
* Returns the client's average packet latency in seconds.
*
* @param client Player's index.
* @param flow Traffic flowing direction.
* @return Latency, or -1 if network info is not available.
* @error Invalid client index, client not connected, or fake client.
*/
native float GetClientAvgLatency(int client, NetFlow flow);
/**
* Returns the client's average packet loss, values go from 0 to 1 (for percentages).
*
* @param client Player's index.
* @param flow Traffic flowing direction.
* @return Average packet loss, or -1 if network info is not available.
* @error Invalid client index, client not connected, or fake client.
*/
native float GetClientAvgLoss(int client, NetFlow flow);
/**
* Returns the client's average packet choke, values go from 0 to 1 (for percentages).
*
* @param client Player's index.
* @param flow Traffic flowing direction.
* @return Average packet loss, or -1 if network info is not available.
* @error Invalid client index, client not connected, or fake client.
*/
native float GetClientAvgChoke(int client, NetFlow flow);
/**
* Returns the client's data flow in bytes/sec.
*
* @param client Player's index.
* @param flow Traffic flowing direction.
* @return Data flow.
* @error Invalid client index, client not connected, or fake client.
*/
native float GetClientAvgData(int client, NetFlow flow);
/**
* Returns the client's average packet frequency in packets/sec.
*
* @param client Player's index.
* @param flow Traffic flowing direction.
* @return Packet frequency.
* @error Invalid client index, client not connected, or fake client.
*/
native float GetClientAvgPackets(int client, NetFlow flow);
/**
* Translates an userid index to the real player index.
*
* @param userid Userid value.
* @return Client value.
* @error Returns 0 if invalid userid.
*/
native int GetClientOfUserId(int userid);
/**
* Disconnects a client from the server as soon as the next frame starts.
*
* Note: Originally, KickClient() was immediate. The delay was introduced
* because despite warnings, plugins were using it in ways that would crash.
* The new safe version can break cases that rely on immediate disconnects,
* but ensures that plugins do not accidentally cause crashes.
*
* If you need immediate disconnects, use KickClientEx().
*
* Note: IsClientInKickQueue() will return true before the kick occurs.
*
* @param client Client index.
* @param format Optional formatting rules for disconnect reason.
* Note that a period is automatically appended to the string by the engine.
* @param ... Variable number of format parameters.
* @error Invalid client index, or client not connected.
*/
native void KickClient(int client, const char[] format="", any ...);
/**
* Immediately disconnects a client from the server.
*
* Kicking clients from certain events or callbacks may cause crashes. If in
* doubt, create a short (0.1 second) timer to kick the client in the next
* available frame.
*
* @param client Client index.
* @param format Optional formatting rules for disconnect reason.
* Note that a period is automatically appended to the string by the engine.
* @param ... Variable number of format parameters.
* @error Invalid client index, or client not connected.
*/
native void KickClientEx(int client, const char[] format="", any ...);
/**
* Changes a client's team through the mod's generic team changing function.
* On CS:S, this will kill the player.
*
* @param client Client index.
* @param team Mod-specific team index.
* @error Invalid client index, client not in game, or lack of
* mod support.
*/
native void ChangeClientTeam(int client, int team);
/**
* Returns the clients unique serial identifier.
*
* @param client Client index.
* @return Serial number.
* @error Invalid client index, or client not connected.
*/
native int GetClientSerial(int client);
/**
* Returns the client index by its serial number.
*
* @param serial Serial number.
* @return Client index, or 0 for invalid serial.
*/
native int GetClientFromSerial(int serial);

View File

@@ -0,0 +1,508 @@
/**************************************************************************
* *
* Colored Chat Functions *
* Author: exvel, Editor: Popoklopsi *
* Version: 1.1 *
* *
**************************************************************************/
#if defined _colors_included
#endinput
#endif
#define _colors_included
#define MAX_MESSAGE_LENGTH 250
#define MAX_COLORS 9
#define SERVER_INDEX 0
#define NO_INDEX -1
#define NO_PLAYER -2
enum Colors
{
Color_Default = 0,
Color_Darkred,
Color_Green,
Color_Lightgreen,
Color_Red,
Color_Blue,
Color_Olive,
Color_Lime,
Color_Lightred
}
/* Colors' properties */
new String:CTag[][] = {"{default}", "{darkred}", "{green}", "{lightgreen}", "{red}", "{blue}", "{olive}", "{lime}", "{lightred}"};
new String:CTagCode[][] = {"\x01", "\x02", "\x04", "\x03", "\x03", "\x03", "\x05", "\x06", "\x07"};
new bool:CTagReqSayText2[] = {false, false, false, true, true, true, false, false, false};
new bool:CEventIsHooked = false;
new bool:CSkipList[MAXPLAYERS+1] = {false,...};
/* Game default profile */
new bool:CProfile_Colors[] = {true, false, true, false, false, false, false, false, false};
new CProfile_TeamIndex[] = {NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX};
new bool:CProfile_SayText2 = false;
/**
* Prints a message to a specific client in the chat area.
* Supports color tags.
*
* @param client Client index.
* @param szMessage Message (formatting rules).
* @return No return
*
* On error/Errors: If the client is not connected an error will be thrown.
*/
stock CPrintToChat(client, const String:szMessage[], any:...)
{
if (client <= 0 || client > MaxClients)
ThrowError("Invalid client index %d", client);
if (!IsClientInGame(client))
ThrowError("Client %d is not in game", client);
decl String:szBuffer[MAX_MESSAGE_LENGTH];
decl String:szCMessage[MAX_MESSAGE_LENGTH];
SetGlobalTransTarget(client);
Format(szBuffer, sizeof(szBuffer), "\x01%s", szMessage);
VFormat(szCMessage, sizeof(szCMessage), szBuffer, 3);
new index = CFormat(szCMessage, sizeof(szCMessage));
if (index == NO_INDEX)
PrintToChat(client, szCMessage);
else
CSayText2(client, index, szCMessage);
}
/**
* Prints a message to all clients in the chat area.
* Supports color tags.
*
* @param client Client index.
* @param szMessage Message (formatting rules)
* @return No return
*/
stock CPrintToChatAll(const String:szMessage[], any:...)
{
decl String:szBuffer[MAX_MESSAGE_LENGTH];
for (new i = 1; i <= MaxClients; i++)
{
if (IsClientInGame(i) && !IsFakeClient(i) && !CSkipList[i])
{
SetGlobalTransTarget(i);
VFormat(szBuffer, sizeof(szBuffer), szMessage, 2);
CPrintToChat(i, szBuffer);
}
CSkipList[i] = false;
}
}
/**
* Prints a message to a specific client in the chat area.
* Supports color tags and teamcolor tag.
*
* @param client Client index.
* @param author Author index whose color will be used for teamcolor tag.
* @param szMessage Message (formatting rules).
* @return No return
*
* On error/Errors: If the client or author are not connected an error will be thrown.
*/
stock CPrintToChatEx(client, author, const String:szMessage[], any:...)
{
if (client <= 0 || client > MaxClients)
ThrowError("Invalid client index %d", client);
if (!IsClientInGame(client))
ThrowError("Client %d is not in game", client);
if (author < 0 || author > MaxClients)
ThrowError("Invalid client index %d", author);
decl String:szBuffer[MAX_MESSAGE_LENGTH];
decl String:szCMessage[MAX_MESSAGE_LENGTH];
SetGlobalTransTarget(client);
Format(szBuffer, sizeof(szBuffer), "\x01%s", szMessage);
VFormat(szCMessage, sizeof(szCMessage), szBuffer, 4);
new index = CFormat(szCMessage, sizeof(szCMessage), author);
if (index == NO_INDEX)
PrintToChat(client, szCMessage);
else
CSayText2(client, author, szCMessage);
}
/**
* Prints a message to all clients in the chat area.
* Supports color tags and teamcolor tag.
*
* @param author Author index whos color will be used for teamcolor tag.
* @param szMessage Message (formatting rules).
* @return No return
*
* On error/Errors: If the author is not connected an error will be thrown.
*/
stock CPrintToChatAllEx(author, const String:szMessage[], any:...)
{
if (author < 0 || author > MaxClients)
ThrowError("Invalid client index %d", author);
if (!IsClientInGame(author))
ThrowError("Client %d is not in game", author);
decl String:szBuffer[MAX_MESSAGE_LENGTH];
for (new i = 1; i <= MaxClients; i++)
{
if (IsClientInGame(i) && !IsFakeClient(i) && !CSkipList[i])
{
SetGlobalTransTarget(i);
VFormat(szBuffer, sizeof(szBuffer), szMessage, 3);
CPrintToChatEx(i, author, szBuffer);
}
CSkipList[i] = false;
}
}
/**
* Removes color tags from the string.
*
* @param szMessage String.
* @return No return
*/
stock CRemoveTags(String:szMessage[], maxlength)
{
for (new i = 0; i < MAX_COLORS; i++)
ReplaceString(szMessage, maxlength, CTag[i], "", false);
ReplaceString(szMessage, maxlength, "{teamcolor}", "", false);
}
/**
* Checks whether a color is allowed or not
*
* @param tag Color Tag.
* @return True when color is supported, otherwise false
*/
stock CColorAllowed(Colors:color)
{
if (!CEventIsHooked)
{
CSetupProfile();
CEventIsHooked = true;
}
return CProfile_Colors[color];
}
/**
* Replace the color with another color
* Handle with care!
*
* @param color color to replace.
* @param newColor color to replace with.
* @noreturn
*/
stock CReplaceColor(Colors:color, Colors:newColor)
{
if (!CEventIsHooked)
{
CSetupProfile();
CEventIsHooked = true;
}
CProfile_Colors[color] = CProfile_Colors[newColor];
CProfile_TeamIndex[color] = CProfile_TeamIndex[newColor];
Format(CTagCode[color], sizeof(CTagCode[]), CTagCode[newColor])
}
/**
* This function should only be used right in front of
* CPrintToChatAll or CPrintToChatAllEx and it tells
* to those funcions to skip specified client when printing
* message to all clients. After message is printed client will
* no more be skipped.
*
* @param client Client index
* @return No return
*/
stock CSkipNextClient(client)
{
if (client <= 0 || client > MaxClients)
ThrowError("Invalid client index %d", client);
CSkipList[client] = true;
}
/**
* Replaces color tags in a string with color codes
*
* @param szMessage String.
* @param maxlength Maximum length of the string buffer.
* @return Client index that can be used for SayText2 author index
*
* On error/Errors: If there is more then one team color is used an error will be thrown.
*/
stock CFormat(String:szMessage[], maxlength, author=NO_INDEX)
{
decl String:szGameName[30];
GetGameFolderName(szGameName, sizeof(szGameName));
/* Hook event for auto profile setup on map start */
if (!CEventIsHooked)
{
CSetupProfile();
HookEvent("server_spawn", CEvent_MapStart, EventHookMode_PostNoCopy);
CEventIsHooked = true;
}
new iRandomPlayer = NO_INDEX;
// On CS:GO set invisible precolor
if (StrEqual(szGameName, "csgo", false))
Format(szMessage, maxlength, "\x01\x0B\x01%s", szMessage);
/* If author was specified replace {teamcolor} tag */
if (author != NO_INDEX)
{
if (CProfile_SayText2)
{
ReplaceString(szMessage, maxlength, "{teamcolor}", "\x03", false);
iRandomPlayer = author;
}
/* If saytext2 is not supported by game replace {teamcolor} with green tag */
else
ReplaceString(szMessage, maxlength, "{teamcolor}", CTagCode[Color_Green], false);
}
else
ReplaceString(szMessage, maxlength, "{teamcolor}", "", false);
/* For other color tags we need a loop */
for (new i = 0; i < MAX_COLORS; i++)
{
/* If tag not found - skip */
if (StrContains(szMessage, CTag[i], false) == -1)
continue;
/* If tag is not supported by game replace it with green tag */
else if (!CProfile_Colors[i])
ReplaceString(szMessage, maxlength, CTag[i], CTagCode[Color_Green], false);
/* If tag doesn't need saytext2 simply replace */
else if (!CTagReqSayText2[i])
ReplaceString(szMessage, maxlength, CTag[i], CTagCode[i], false);
/* Tag needs saytext2 */
else
{
/* If saytext2 is not supported by game replace tag with green tag */
if (!CProfile_SayText2)
ReplaceString(szMessage, maxlength, CTag[i], CTagCode[Color_Green], false);
/* Game supports saytext2 */
else
{
/* If random player for tag wasn't specified replace tag and find player */
if (iRandomPlayer == NO_INDEX)
{
/* Searching for valid client for tag */
iRandomPlayer = CFindRandomPlayerByTeam(CProfile_TeamIndex[i]);
/* If player not found replace tag with green color tag */
if (iRandomPlayer == NO_PLAYER)
ReplaceString(szMessage, maxlength, CTag[i], CTagCode[Color_Green], false);
/* If player was found simply replace */
else
ReplaceString(szMessage, maxlength, CTag[i], CTagCode[i], false);
}
/* If found another team color tag throw error */
else
{
//ReplaceString(szMessage, maxlength, CTag[i], "");
ThrowError("Using two team colors in one message is not allowed");
}
}
}
}
return iRandomPlayer;
}
/**
* Founds a random player with specified team
*
* @param color_team Client team.
* @return Client index or NO_PLAYER if no player found
*/
stock CFindRandomPlayerByTeam(color_team)
{
if (color_team == SERVER_INDEX)
return 0;
else
{
for (new i = 1; i <= MaxClients; i++)
{
if (IsClientInGame(i) && GetClientTeam(i) == color_team)
return i;
}
}
return NO_PLAYER;
}
/**
* Sends a SayText2 usermessage to a client
*
* @param szMessage Client index
* @param maxlength Author index
* @param szMessage Message
* @return No return.
*/
stock CSayText2(client, author, const String:szMessage[])
{
new Handle:hBuffer = StartMessageOne("SayText2", client, USERMSG_RELIABLE|USERMSG_BLOCKHOOKS);
if(GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && GetUserMessageType() == UM_Protobuf)
{
PbSetInt(hBuffer, "ent_idx", author);
PbSetBool(hBuffer, "chat", true);
PbSetString(hBuffer, "msg_name", szMessage);
PbAddString(hBuffer, "params", "");
PbAddString(hBuffer, "params", "");
PbAddString(hBuffer, "params", "");
PbAddString(hBuffer, "params", "");
}
else
{
BfWriteByte(hBuffer, author);
BfWriteByte(hBuffer, true);
BfWriteString(hBuffer, szMessage);
}
EndMessage();
}
/**
* Creates game color profile
* This function must be edited if you want to add more games support
*
* @return No return.
*/
stock CSetupProfile()
{
decl String:szGameName[30];
GetGameFolderName(szGameName, sizeof(szGameName));
if (StrEqual(szGameName, "cstrike", false))
{
CProfile_Colors[Color_Lightgreen] = true;
CProfile_Colors[Color_Red] = true;
CProfile_Colors[Color_Blue] = true;
CProfile_Colors[Color_Olive] = true;
CProfile_TeamIndex[Color_Lightgreen] = SERVER_INDEX;
CProfile_TeamIndex[Color_Red] = 2;
CProfile_TeamIndex[Color_Blue] = 3;
CProfile_SayText2 = true;
}
else if (StrEqual(szGameName, "csgo", false))
{
CProfile_Colors[Color_Red] = true;
CProfile_Colors[Color_Blue] = true;
CProfile_Colors[Color_Olive] = true;
CProfile_Colors[Color_Darkred] = true;
CProfile_Colors[Color_Lime] = true;
CProfile_Colors[Color_Lightred] = true;
CProfile_TeamIndex[Color_Red] = 2;
CProfile_TeamIndex[Color_Blue] = 3;
CProfile_SayText2 = true;
}
else if (StrEqual(szGameName, "tf", false))
{
CProfile_Colors[Color_Lightgreen] = true;
CProfile_Colors[Color_Red] = true;
CProfile_Colors[Color_Blue] = true;
CProfile_Colors[Color_Olive] = true;
CProfile_TeamIndex[Color_Lightgreen] = SERVER_INDEX;
CProfile_TeamIndex[Color_Red] = 2;
CProfile_TeamIndex[Color_Blue] = 3;
CProfile_SayText2 = true;
}
else if (StrEqual(szGameName, "left4dead", false) || StrEqual(szGameName, "left4dead2", false))
{
CProfile_Colors[Color_Lightgreen] = true;
CProfile_Colors[Color_Red] = true;
CProfile_Colors[Color_Blue] = true;
CProfile_Colors[Color_Olive] = true;
CProfile_TeamIndex[Color_Lightgreen] = SERVER_INDEX;
CProfile_TeamIndex[Color_Red] = 3;
CProfile_TeamIndex[Color_Blue] = 2;
CProfile_SayText2 = true;
}
else if (StrEqual(szGameName, "hl2mp", false))
{
/* hl2mp profile is based on mp_teamplay convar */
if (GetConVarBool(FindConVar("mp_teamplay")))
{
CProfile_Colors[Color_Red] = true;
CProfile_Colors[Color_Blue] = true;
CProfile_Colors[Color_Olive] = true;
CProfile_TeamIndex[Color_Red] = 3;
CProfile_TeamIndex[Color_Blue] = 2;
CProfile_SayText2 = true;
}
else
{
CProfile_SayText2 = false;
CProfile_Colors[Color_Olive] = true;
}
}
else if (StrEqual(szGameName, "dod", false))
{
CProfile_Colors[Color_Olive] = true;
CProfile_SayText2 = false;
}
/* Profile for other games */
else
{
if (GetUserMessageId("SayText2") == INVALID_MESSAGE_ID)
{
CProfile_SayText2 = false;
}
else
{
CProfile_Colors[Color_Red] = true;
CProfile_Colors[Color_Blue] = true;
CProfile_TeamIndex[Color_Red] = 2;
CProfile_TeamIndex[Color_Blue] = 3;
CProfile_SayText2 = true;
}
}
}
public Action:CEvent_MapStart(Handle:event, const String:name[], bool:dontBroadcast)
{
CSetupProfile();
for (new i = 1; i <= MaxClients; i++)
CSkipList[i] = false;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,171 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _commandfilters_included
#endinput
#endif
#define _commandfilters_included
#define MAX_TARGET_LENGTH 64
#define COMMAND_FILTER_ALIVE (1<<0) /**< Only allow alive players */
#define COMMAND_FILTER_DEAD (1<<1) /**< Only filter dead players */
#define COMMAND_FILTER_CONNECTED (1<<2) /**< Allow players not fully in-game */
#define COMMAND_FILTER_NO_IMMUNITY (1<<3) /**< Ignore immunity rules */
#define COMMAND_FILTER_NO_MULTI (1<<4) /**< Do not allow multiple target patterns */
#define COMMAND_FILTER_NO_BOTS (1<<5) /**< Do not allow bots to be targetted */
#define COMMAND_TARGET_NONE 0 /**< No target was found */
#define COMMAND_TARGET_NOT_ALIVE -1 /**< Single client is not alive */
#define COMMAND_TARGET_NOT_DEAD -2 /**< Single client is not dead */
#define COMMAND_TARGET_NOT_IN_GAME -3 /**< Single client is not in game */
#define COMMAND_TARGET_IMMUNE -4 /**< Single client is immune */
#define COMMAND_TARGET_EMPTY_FILTER -5 /**< A multi-filter (such as @all) had no targets */
#define COMMAND_TARGET_NOT_HUMAN -6 /**< Target was not human */
#define COMMAND_TARGET_AMBIGUOUS -7 /**< Partial name had too many targets */
/**
* Processes a generic command target string, and resolves it to a list
* of clients or one client, based on filtering rules and a pattern.
*
* Note that you should use LoadTranslations("common.phrases") in OnPluginStart(),
* as that file is guaranteed to contain all of the translatable phrases that
* ProcessTargetString() will return.
*
* @param pattern Pattern to find clients against.
* @param admin Admin performing the action, or 0 if the server.
* @param targets Array to hold targets.
* @param max_targets Maximum size of the targets array.
* @param filter_flags Filter flags.
* @param target_name Buffer to store the target name.
* @param tn_maxlength Maximum length of the target name buffer.
* @param tn_is_ml OUTPUT: Will be true if the target name buffer is an ML phrase,
* false if it is a normal string.
* @return If a multi-target pattern was used, the number of clients found
* is returned. If a single-target pattern was used, 1 is returned
* if one valid client is found. Otherwise, a COMMAND_TARGET reason
* for failure is returned.
*/
native int ProcessTargetString(const char[] pattern,
int admin,
int[] targets,
int max_targets,
int filter_flags,
char[] target_name,
int tn_maxlength,
bool &tn_is_ml);
/**
* Replies to a client with a given message describing a targetting
* failure reason.
*
* Note: The translation phrases are found in common.phrases.txt.
*
* @param client Client index, or 0 for server.
* @param reason COMMAND_TARGET reason.
*/
stock void ReplyToTargetError(int client, int reason)
{
switch (reason)
{
case COMMAND_TARGET_NONE:
{
ReplyToCommand(client, "[SM] %t", "No matching client");
}
case COMMAND_TARGET_NOT_ALIVE:
{
ReplyToCommand(client, "[SM] %t", "Target must be alive");
}
case COMMAND_TARGET_NOT_DEAD:
{
ReplyToCommand(client, "[SM] %t", "Target must be dead");
}
case COMMAND_TARGET_NOT_IN_GAME:
{
ReplyToCommand(client, "[SM] %t", "Target is not in game");
}
case COMMAND_TARGET_IMMUNE:
{
ReplyToCommand(client, "[SM] %t", "Unable to target");
}
case COMMAND_TARGET_EMPTY_FILTER:
{
ReplyToCommand(client, "[SM] %t", "No matching clients");
}
case COMMAND_TARGET_NOT_HUMAN:
{
ReplyToCommand(client, "[SM] %t", "Cannot target bot");
}
case COMMAND_TARGET_AMBIGUOUS:
{
ReplyToCommand(client, "[SM] %t", "More than one client matched");
}
}
}
#define FEATURECAP_MULTITARGETFILTER_CLIENTPARAM "SourceMod MultiTargetFilter ClientParam"
/**
* Adds clients to a multi-target filter.
*
* @param pattern Pattern name.
* @param clients Array to fill with unique, valid client indexes.
* @param client Client that triggered this filter.
* @return True if pattern was recognized, false otherwise.
*
* @note To see if the client param is available, use FeatureType_Capability and FEATURECAP_MULTITARGETFILTER_CLIENTPARAM.
*/
typeset MultiTargetFilter {
function bool (const char[] pattern, Handle clients);
function bool (const char[] pattern, ArrayList clients);
function bool (const char[] pattern, Handle clients, int client);
function bool (const char[] pattern, ArrayList clients, int client);
}
/**
* Adds a multi-target filter function for ProcessTargetString().
*
* @param pattern Pattern to match (case sensitive).
* @param filter Filter function.
* @param phrase Descriptive phrase to display on successful match.
* @param phraseIsML True if phrase is multi-lingual, false otherwise.
*/
native void AddMultiTargetFilter(const char[] pattern, MultiTargetFilter filter,
const char[] phrase, bool phraseIsML);
/**
* Removes a multi-target filter function from ProcessTargetString().
*
* @param pattern Pattern to match (case sensitive).
* @param filter Filter function.
*/
native void RemoveMultiTargetFilter(const char[] pattern, MultiTargetFilter filter);

View File

@@ -0,0 +1,86 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _commandline_included_
#endinput
#endif
#define _commandline_included_
/**
* Gets the full command line the server was launched with.
*
* @param commandLine Buffer to store the command line in.
* @param maxlen Maximum length of the command line buffer.
* @return True if the command line is valid; otherwise, false.
* @error No command line available, or no mod support.
*/
native bool GetCommandLine(char[] commandLine, int maxlen);
/**
* Gets the value of a command line parameter the server was launched with.
*
* @param param The command line parameter to get the value of.
* @param value Buffer to store the parameter value in.
* @param maxlen Maximum length of the value buffer.
* @param defValue The default value to return if the parameter wasn't specified.
* @error No command line available, or no mod support.
*/
native void GetCommandLineParam(const char[] param, char[] value, int maxlen, const char[] defValue="");
/**
* Gets the value of a command line parameter the server was launched with.
*
* @param param The command line parameter to get the value of.
* @param defValue The default value to return if the parameter wasn't specified.
* @return The integer value of the command line parameter value.
* @error No command line available, or no mod support.
*/
native int GetCommandLineParamInt(const char[] param, int defValue=0);
/**
* Gets the value of a command line parameter the server was launched with.
*
* @param param The command line parameter to get the value of.
* @param defValue The default value to return if the parameter wasn't specified.
* @return The floating point value of the command line parameter value.
* @error No command line available, or no mod support.
*/
native float GetCommandLineParamFloat(const char[] param, float defValue=0.0);
/**
* Determines if a specific command line parameter is present.
*
* @param param The command line parameter to test.
* @return True if the command line parameter is specified; otherwise, false.
* @error No command line available, or no mod support.
*/
native bool FindCommandLineParam(const char[] param);

View File

@@ -0,0 +1,815 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _console_included
#endinput
#endif
#define _console_included
#define INVALID_FCVAR_FLAGS (-1)
/**
* Console variable query helper values.
*/
enum QueryCookie
{
QUERYCOOKIE_FAILED = 0
};
/**
* Reply sources for commands.
*/
enum ReplySource
{
SM_REPLY_TO_CONSOLE = 0,
SM_REPLY_TO_CHAT = 1
};
/**
* @section Flags for console commands and console variables. The descriptions
* for each constant come directly from the Source SDK.
*/
#pragma deprecated No logic using this flag ever existed in a released game. It only ever appeared in the first hl2sdk.
#define FCVAR_PLUGIN 0 // Actual value is same as FCVAR_SS_ADDED in Left 4 Dead and later.
#pragma deprecated Did you mean FCVAR_DEVELOPMENTONLY? (No logic using this flag ever existed in a released game. It only ever appeared in the first hl2sdk.)
#define FCVAR_LAUNCHER (1<<1) // Same value as FCVAR_DEVELOPMENTONLY, which is what most usages of this were intending to use.
#define FCVAR_NONE 0 // The default, no flags at all
#define FCVAR_UNREGISTERED (1<<0) // If this is set, don't add to linked list, etc.
#define FCVAR_DEVELOPMENTONLY (1<<1) // Hidden in released products. Flag is removed automatically if ALLOW_DEVELOPMENT_CVARS is defined. (OB+)
#define FCVAR_GAMEDLL (1<<2) // Defined by the game DLL.
#define FCVAR_CLIENTDLL (1<<3) // Defined by the client DLL.
#define FCVAR_MATERIAL_SYSTEM (1<<4) // Defined by the material system. (EP1-only)
#define FCVAR_HIDDEN (1<<4) // Hidden. Doesn't appear in find or autocomplete. Like DEVELOPMENTONLY, but can't be compiled out.1 (OB+)
#define FCVAR_PROTECTED (1<<5) // It's a server cvar, but we don't send the data since it's a password, etc.
// Sends 1 if it's not bland/zero, 0 otherwise as value.
#define FCVAR_SPONLY (1<<6) // This cvar cannot be changed by clients connected to a multiplayer server.
#define FCVAR_ARCHIVE (1<<7) // Set to cause it to be saved to vars.rc
#define FCVAR_NOTIFY (1<<8) // Notifies players when changed.
#define FCVAR_USERINFO (1<<9) // Changes the client's info string.
#define FCVAR_PRINTABLEONLY (1<<10) // This cvar's string cannot contain unprintable characters (e.g., used for player name, etc.)
#define FCVAR_UNLOGGED (1<<11) // If this is a FCVAR_SERVER, don't log changes to the log file / console if we are creating a log
#define FCVAR_NEVER_AS_STRING (1<<12) // Never try to print that cvar.
#define FCVAR_REPLICATED (1<<13) // Server setting enforced on clients.
#define FCVAR_CHEAT (1<<14) // Only useable in singleplayer / debug / multiplayer & sv_cheats
#define FCVAR_SS (1<<15) // causes varnameN where N 2 through max splitscreen slots for mod to be autogenerated (L4D+)
#define FCVAR_DEMO (1<<16) // Record this cvar when starting a demo file.
#define FCVAR_DONTRECORD (1<<17) // Don't record these command in demo files.
#define FCVAR_SS_ADDED (1<<18) // This is one of the "added" FCVAR_SS variables for the splitscreen players (L4D+)
#define FCVAR_RELEASE (1<<19) // Cvars tagged with this are the only cvars available to customers (L4D+)
#define FCVAR_RELOAD_MATERIALS (1<<20) // If this cvar changes, it forces a material reload (OB+)
#define FCVAR_RELOAD_TEXTURES (1<<21) // If this cvar changes, if forces a texture reload (OB+)
#define FCVAR_NOT_CONNECTED (1<<22) // Cvar cannot be changed by a client that is connected to a server.
#define FCVAR_MATERIAL_SYSTEM_THREAD (1<<23) // Indicates this cvar is read from the material system thread (OB+)
#define FCVAR_ARCHIVE_XBOX (1<<24) // Cvar written to config.cfg on the Xbox.
#define FCVAR_ARCHIVE_GAMECONSOLE (1<<24) // Cvar written to config.cfg on the Xbox.
#define FCVAR_ACCESSIBLE_FROM_THREADS (1<<25) // used as a debugging tool necessary to check material system thread convars (OB+)
#define FCVAR_SERVER_CAN_EXECUTE (1<<28) // the server is allowed to execute this command on clients via
// ClientCommand/NET_StringCmd/CBaseClientState::ProcessStringCmd. (OB+)
#define FCVAR_SERVER_CANNOT_QUERY (1<<29) // If this is set, then the server is not allowed to query this cvar's value (via
// IServerPluginHelpers::StartQueryCvarValue).
#define FCVAR_CLIENTCMD_CAN_EXECUTE (1<<30) // IVEngineClient::ClientCmd is allowed to execute this command.
// Note: IVEngineClient::ClientCmd_Unrestricted can run any client command.
/**
* @endsection
*/
/**
* Executes a server command as if it were on the server console (or RCON)
*
* @param format Formatting rules.
* @param ... Variable number of format parameters.
*/
native void ServerCommand(const char[] format, any ...);
/**
* Executes a server command as if it were on the server console (or RCON)
* and stores the printed text into buffer.
*
* Warning: This calls ServerExecute internally and may have issues if
* certain commands are in the buffer, only use when you really need
* the response.
* Also, on L4D2 this will not print the command output to the server console.
*
* @param buffer String to store command result into.
* @param maxlen Length of buffer.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
*/
native void ServerCommandEx(char[] buffer, int maxlen, const char[] format, any ...);
/**
* Inserts a server command at the beginning of the server command buffer.
*
* @param format Formatting rules.
* @param ... Variable number of format parameters.
*/
native void InsertServerCommand(const char[] format, any ...);
/**
* Executes every command in the server's command buffer, rather than once per frame.
*/
native void ServerExecute();
/**
* Executes a client command. Note that this will not work on clients unless
* they have cl_restrict_server_commands set to 0.
*
* @param client Index of the client.
* @param fmt Format of the client command.
* @param ... Format parameters
* @error Invalid client index, or client not connected.
*/
native void ClientCommand(int client, const char[] fmt, any ...);
/**
* Executes a client command on the server without being networked.
*
* FakeClientCommand() overwrites the command tokenization buffer. This can
* cause undesired effects because future calls to GetCmdArg* will return
* data from the FakeClientCommand(), not the parent command. If you are in
* a hook where this matters (for example, a "say" hook), you should use
* FakeClientCommandEx() instead.
*
* @param client Index of the client.
* @param fmt Format of the client command.
* @param ... Format parameters
* @error Invalid client index, or client not connected.
*/
native void FakeClientCommand(int client, const char[] fmt, any ...);
/**
* Executes a client command on the server without being networked. The
* execution of the client command is delayed by one frame to prevent any
* re-entrancy issues that might surface with FakeClientCommand().
*
* @param client Index of the client.
* @param fmt Format of the client command.
* @param ... Format parameters
* @error Invalid client index, or client not connected.
*/
native void FakeClientCommandEx(int client, const char[] fmt, any ...);
/**
* Executes a KeyValues client command on the server without being networked.
*
* @param client Index of the client.
* @param kv KeyValues data to be sent.
* @error Invalid client index, client not connected,
* or unsupported on current game.
*/
native void FakeClientCommandKeyValues(int client, KeyValues kv);
/**
* Sends a message to the server console.
*
* @param format Formatting rules.
* @param ... Variable number of format parameters.
*/
native void PrintToServer(const char[] format, any ...);
/**
* Sends a message to a client's console.
*
* @param client Client index.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
* @error If the client is not connected an error will be thrown.
*/
native void PrintToConsole(int client, const char[] format, any ...);
/**
* Sends a message to every client's console.
*
* @param format Formatting rules.
* @param ... Variable number of format parameters.
*/
stock void PrintToConsoleAll(const char[] format, any ...)
{
char buffer[254];
for (int i = 1; i <= MaxClients; i++)
{
if (IsClientInGame(i))
{
SetGlobalTransTarget(i);
VFormat(buffer, sizeof(buffer), format, 2);
PrintToConsole(i, "%s", buffer);
}
}
}
/**
* Replies to a message in a command.
*
* A client index of 0 will use PrintToServer().
* If the command was from the console, PrintToConsole() is used.
* If the command was from chat, PrintToChat() is used.
*
* @param client Client index, or 0 for server.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
* @error If the client is not connected or invalid.
*/
native void ReplyToCommand(int client, const char[] format, any ...);
/**
* Returns the current reply source of a command.
*
* @return ReplySource value.
*/
native ReplySource GetCmdReplySource();
/**
* Sets the current reply source of a command.
*
* Only use this if you know what you are doing. You should save the old value
* and restore it once you are done.
*
* @param source New ReplySource value.
* @return Old ReplySource value.
*/
native ReplySource SetCmdReplySource(ReplySource source);
/**
* Returns whether the current say hook is a chat trigger.
*
* This function is only meaningful inside say or say_team hooks.
*
* @return True if a chat trigger, false otherwise.
*/
native bool IsChatTrigger();
/**
* Get the list of characters used for public chat triggers.
*
* @param buffer Buffer to use for storing the string.
* @param maxlength Maximum length of the buffer.
* @return Length of string written to buffer.
*/
native int GetPublicChatTriggers(char[] buffer, int maxlength);
/**
* Get the list of characters used for silent chat triggers.
*
* @param buffer Buffer to use for storing the string.
* @param maxlength Maximum length of the buffer.
* @return Length of string written to buffer.
*/
native int GetSilentChatTriggers(char[] buffer, int maxlength);
/**
* Displays usage of an admin command to users depending on the
* setting of the sm_show_activity cvar. All users receive a message
* in their chat text, except for the originating client, who receives
* the message based on the current ReplySource.
*
* @param client Client index doing the action, or 0 for server.
* @param tag Tag to prepend to the message.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
* @error
*/
native void ShowActivity2(int client, const char[] tag, const char[] format, any ...);
/**
* Displays usage of an admin command to users depending on the
* setting of the sm_show_activity cvar.
*
* This version does not display a message to the originating client
* if used from chat triggers or menus. If manual replies are used
* for these cases, then this function will suffice. Otherwise,
* ShowActivity2() is slightly more useful.
*
* @param client Client index doing the action, or 0 for server.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
* @error
*/
native void ShowActivity(int client, const char[] format, any ...);
/**
* Same as ShowActivity(), except the tag parameter is used instead of
* "[SM] " (note that you must supply any spacing).
*
* @param client Client index doing the action, or 0 for server.
* @param tag Tag to display with.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
* @error
*/
native void ShowActivityEx(int client, const char[] tag, const char[] format, any ...);
/**
* Given an originating client and a target client, returns the string
* that describes the originating client according to the sm_show_activity cvar.
*
* For example, "ADMIN", "PLAYER", or a player's name could be placed in this buffer.
*
* @param client Originating client; may be 0 for server console.
* @param target Targeted client.
* @param namebuf Name buffer.
* @param maxlength Maximum size of the name buffer.
* @return True if activity should be shown. False otherwise. In either
* case, the name buffer is filled. The return value can be used
* to broadcast a "safe" name to all players regardless of the
* sm_show_activity filters.
* @error Invalid client index or client not connected.
*/
native bool FormatActivitySource(int client, int target, const char[] namebuf, int maxlength);
/**
* Called when a server-only command is invoked.
*
* @param args Number of arguments that were in the argument string.
* @return An Action value. Not handling the command
* means that Source will report it as "not found."
*/
typedef SrvCmd = function Action (int args);
/**
* Creates a server-only console command, or hooks an already existing one.
*
* Server commands are case sensitive.
*
* @param cmd Name of the command to hook or create.
* @param callback A function to use as a callback for when the command is invoked.
* @param description Optional description to use for command creation.
* @param flags Optional flags to use for command creation.
* @error Command name is the same as an existing convar.
*/
native void RegServerCmd(const char[] cmd, SrvCmd callback, const char[] description="", int flags=0);
/**
* Called when a generic console command is invoked.
*
* @param client Index of the client, or 0 from the server.
* @param args Number of arguments that were in the argument string.
* @return An Action value. Not handling the command
* means that Source will report it as "not found."
*/
typedef ConCmd = function Action (int client, int args);
/**
* Creates a console command, or hooks an already existing one.
*
* Console commands are case sensitive. However, if the command already exists in the game,
* a client may enter the command in any case. SourceMod corrects for this automatically,
* and you should only hook the "real" version of the command.
*
* @param cmd Name of the command to hook or create.
* @param callback A function to use as a callback for when the command is invoked.
* @param description Optional description to use for command creation.
* @param flags Optional flags to use for command creation.
* @error Command name is the same as an existing convar.
*/
native void RegConsoleCmd(const char[] cmd, ConCmd callback, const char[] description="", int flags=0);
/**
* Creates a console command as an administrative command. If the command does not exist,
* it is created. When this command is invoked, the access rights of the player are
* automatically checked before allowing it to continue.
*
* Admin commands are case sensitive from both the client and server.
*
* @param cmd String containing command to register.
* @param callback A function to use as a callback for when the command is invoked.
* @param adminflags Administrative flags (bitstring) to use for permissions.
* @param description Optional description to use for help.
* @param group String containing the command group to use. If empty,
* the plugin's filename will be used instead.
* @param flags Optional console flags.
* @error Command name is the same as an existing convar.
*/
native void RegAdminCmd(const char[] cmd,
ConCmd callback,
int adminflags,
const char[] description="",
const char[] group="",
int flags=0);
/**
* Returns the number of arguments from the current console or server command.
* @note Unlike the HL2 engine call, this does not include the command itself.
*
* @return Number of arguments to the current command.
*/
native int GetCmdArgs();
/**
* Retrieves a command argument given its index, from the current console or
* server command.
* @note Argument indexes start at 1; 0 retrieves the command name.
*
* @param argnum Argument number to retrieve.
* @param buffer Buffer to use for storing the string.
* @param maxlength Maximum length of the buffer.
* @return Length of string written to buffer.
*/
native int GetCmdArg(int argnum, char[] buffer, int maxlength);
/**
* Retrieves a numeric command argument given its index, from the current
* console or server command. Will return 0 if the argument can not be
* parsed as a number. Use GetCmdArgIntEx to handle that explicitly.
*
* @param argnum Argument number to retrieve.
* @return Value of the command argument.
*/
stock int GetCmdArgInt(int argnum)
{
char str[12];
GetCmdArg(argnum, str, sizeof(str));
return StringToInt(str);
}
/**
* Retrieves a numeric command argument given its index, from the current
* console or server command. Returns false if the argument can not be
* completely parsed as an integer.
*
* @param argnum Argument number to retrieve.
* @param value Populated with the value of the command argument.
* @return Whether the argument was entirely a numeric value.
*/
stock bool GetCmdArgIntEx(int argnum, int &value)
{
char str[12];
int len = GetCmdArg(argnum, str, sizeof(str));
return StringToIntEx(str, value) == len && len > 0;
}
/**
* Retrieves a float command argument given its index, from the current
* console or server command. Will return 0.0 if the argument can not be
* parsed as a number. Use GetCmdArgFloatEx to handle that explicitly.
*
* @param argnum Argument number to retrieve.
* @return Value of the command argument.
*/
stock float GetCmdArgFloat(int argnum)
{
char str[18];
GetCmdArg(argnum, str, sizeof(str));
return StringToFloat(str);
}
/**
* Retrieves a float command argument given its index, from the current
* console or server command. Returns false if the argument can not be
* completely parsed as a floating point.
*
* @param argnum Argument number to retrieve.
* @param value Populated with the value of the command argument.
* @return Whether the argument was entirely a floating point value.
*/
stock bool GetCmdArgFloatEx(int argnum, float &value)
{
char str[18];
int len = GetCmdArg(argnum, str, sizeof(str));
return StringToFloatEx(str, value) == len && len > 0;
}
/**
* Retrieves the entire command argument string in one lump from the current
* console or server command.
*
* @param buffer Buffer to use for storing the string.
* @param maxlength Maximum length of the buffer.
* @return Length of string written to buffer.
*/
native int GetCmdArgString(char[] buffer, int maxlength);
methodmap CommandIterator < Handle {
// Creates a new CommandIterator. Must be freed with delete or
// CloseHandle().
//
// The CommandIterator can be used to iterate commands created by
// SourceMod plugins and allows inspection of properties associated
// with the command.
//
// @return New CommandIterator Handle.
public native CommandIterator();
// Determines if there is a next command. If one is found, the
// iterator is advanced to it.
//
// @return true if found and iterator is advanced.
public native bool Next();
// Retrieves the command's description.
//
// @param buffer Buffer to copy to.
// @param maxlen Maximum size of the buffer.
// @error Invalid iterator position.
public native void GetDescription(char[] buffer, int maxlen);
// Retrieves the command's name.
//
// @param buffer Buffer to copy to.
// @param maxlen Maximum size of the buffer.
// @error Invalid iterator position.
public native void GetName(char[] buffer, int maxlen);
// Retrieves the plugin handle of the command's creator
//
// @error Invalid iterator position.
property Handle Plugin {
public native get();
}
// This property is deprecated. Use .AdminFlags instead.
// Retrieves the command's effective admin flags.
//
// @error Invalid iterator position.
// @deprecated Use .AdminFlags instead.
#pragma deprecated Use .AdminFlags instead.
property int Flags {
public native get();
}
// Retrieves the command's effective admin flags.
//
// @error Invalid iterator position.
property int AdminFlags {
public native get();
}
// Retrieves the command's convar flags.
//
// @error Invalid iterator position.
property int ConVarFlags {
public native get();
}
}
/**
* Gets a command iterator. Must be freed with CloseHandle().
*
* @return A new command iterator.
*/
native Handle GetCommandIterator();
/**
* Reads a command iterator, then advances to the next command if any.
* Only SourceMod specific commands are returned.
*
* @param iter Command iterator Handle.
* @param name Name buffer.
* @param nameLen Name buffer size.
* @param eflags Effective default flags of a command.
* @param desc Command description buffer.
* @param descLen Command description buffer size.
* @return True on success, false if there are no more commands.
*/
native bool ReadCommandIterator(Handle iter,
char[] name,
int nameLen,
int &eflags=0,
char[] desc="",
int descLen=0);
/**
* Returns whether a client has access to a given command string. The string
* can be any override string, as overrides can be independent of
* commands. This feature essentially allows you to create custom
* flags using the override system.
*
* @param client Client index.
* @param command Command name. If the command is not found, the default
* flags are used.
* @param flags Flag string to use as a default, if the command or override
* is not found.
* @param override_only If true, SourceMod will not attempt to find a matching
* command, and it will only use the default flags specified.
* Otherwise, SourceMod will ignore the default flags if
* there is a matching admin command.
* @return True if the client has access, false otherwise.
*/
native bool CheckCommandAccess(int client,
const char[] command,
int flags,
bool override_only=false);
/**
* Returns whether an admin has access to a given command string. The string
* can be any override string, as overrides can be independent of
* commands. This feature essentially allows you to create custom flags
* using the override system.
*
* @param id AdminId of the admin.
* @param command Command name. If the command is not found, the default
* flags are used.
* @param flags Flag string to use as a default, if the command or override
* is not found.
* @param override_only If true, SourceMod will not attempt to find a matching
* command, and it will only use the default flags specified.
* Otherwise, SourceMod will ignore the default flags if
* there is a matching admin command.
* @return True if the admin has access, false otherwise.
*/
native bool CheckAccess(AdminId id,
const char[] command,
int flags,
bool override_only=false);
/**
* Returns the bitstring of flags of a command.
*
* @param name Name of the command.
* @return A bitstring containing the FCVAR_* flags that are enabled
* or INVALID_FCVAR_FLAGS if command not found.
*/
native int GetCommandFlags(const char[] name);
/**
* Sets the bitstring of flags of a command.
*
* @param name Name of the command.
* @param flags A bitstring containing the FCVAR_* flags to enable.
* @return True on success, otherwise false.
*/
native bool SetCommandFlags(const char[] name, int flags);
/**
* Starts a ConCommandBase search, traversing the list of ConVars and
* ConCommands. If a Handle is returned, the next entry must be read
* via FindNextConCommand(). The order of the list is undefined.
*
* @param buffer Buffer to store entry name.
* @param max_size Maximum size of the buffer.
* @param isCommand Variable to store whether the entry is a command.
* If it is not a command, it is a ConVar.
* @param flags Variable to store entry flags.
* @param description Buffer to store the description, empty if no description present.
* @param descrmax_size Maximum size of the description buffer.
* @return On success, a ConCmdIter Handle is returned, which
can be read via FindNextConCommand(), and must be
closed via CloseHandle(). Additionally, the output
parameters will be filled with information of the
first ConCommandBase entry.
On failure, INVALID_HANDLE is returned, and the
contents of outputs is undefined.
*/
native Handle FindFirstConCommand(char[] buffer, int max_size, bool &isCommand, int &flags=0, char[] description="", int descrmax_size=0);
/**
* Reads the next entry in a ConCommandBase iterator.
*
* @param search ConCmdIter Handle to search.
* @param buffer Buffer to store entry name.
* @param max_size Maximum size of the buffer.
* @param isCommand Variable to store whether the entry is a command.
If it is not a command, it is a ConVar.
* @param flags Variable to store entry flags.
* @param description Buffer to store the description, empty if no description present.
* @param descrmax_size Maximum size of the description buffer.
* @return On success, the outputs are filled, the iterator is
advanced to the next entry, and true is returned.
If no more entries exist, false is returned, and the
contents of outputs is undefined.
*/
native bool FindNextConCommand(Handle search, char[] buffer, int max_size, bool &isCommand, int &flags=0, char[] description="", int descrmax_size=0);
/**
* Adds an informational string to the server's public "tags".
* This string should be a short, unique identifier.
*
* Note: Tags are automatically removed when a plugin unloads.
* Note: Currently, this function does nothing because of bugs in the Valve master.
*
* @param tag Tag string to append.
*/
native void AddServerTag(const char[] tag);
/**
* Removes a tag previously added by the calling plugin.
*
* @param tag Tag string to remove.
*/
native void RemoveServerTag(const char[] tag);
/**
* Callback for command listeners. This is invoked whenever any command
* reaches the server, from the server console itself or a player.
*
* Clients may be in the process of connecting when they are executing commands
* IsClientConnected(client) is not guaranteed to return true. Other functions
* such as GetClientIP() may not work at this point either.
*
* Returning Plugin_Handled or Plugin_Stop will prevent the original,
* baseline code from running.
*
* -- TEXT BELOW IS IMPLEMENTATION, AND NOT GUARANTEED --
* Even if returning Plugin_Handled or Plugin_Stop, some callbacks will still
* trigger. These are:
* * C++ command dispatch hooks from Metamod:Source plugins
* * Reg*Cmd() hooks that did not create new commands.
*
* @param client Client, or 0 for server.
* Client may not be connected or in game.
* @param command Command name, lower case. To get name as typed, use
* GetCmdArg() and specify argument 0.
* @param argc Argument count.
* @return Action to take (see extended notes above).
*/
typedef CommandListener = function Action (int client, const char[] command, int argc);
#define FEATURECAP_COMMANDLISTENER "command listener"
/**
* Adds a callback that will fire when a command is sent to the server.
*
* Registering commands is designed to create a new command as part of the UI,
* whereas this is a lightweight hook on a command string, existing or not.
* Using Reg*Cmd to intercept is in poor practice, as it physically creates a
* new command and can slow down dispatch in general.
*
* To see if this feature is available, use FeatureType_Capability and
* FEATURECAP_COMMANDLISTENER.
*
* @param callback Callback.
* @param command Command, or if not specified, a global listener.
* The command is case insensitive.
* @return True if this feature is available on the current game,
* false otherwise.
*/
native bool AddCommandListener(CommandListener callback, const char[] command="");
/**
* Removes a previously added command listener, in reverse order of being added.
*
* @param callback Callback.
* @param command Command, or if not specified, a global listener.
* The command is case insensitive.
* @error Callback has no active listeners.
*/
native void RemoveCommandListener(CommandListener callback, const char[] command="");
/**
* Returns true if the supplied command exists.
*
* @param command Command to find.
* @return True if command is found, false otherwise.
*/
stock bool CommandExists(const char[] command)
{
return (GetCommandFlags(command) != INVALID_FCVAR_FLAGS);
}
/**
* Global listener for the chat commands.
*
* @param client Client index.
* @param command Command name.
* @param sArgs Chat argument string.
*
* @return An Action value. Returning Plugin_Handled bypasses the game function call.
* Returning Plugin_Stop bypasses the post hook as well as the game function.
*/
forward Action OnClientSayCommand(int client, const char[] command, const char[] sArgs);
/**
* Global post listener for the chat commands.
*
* @param client Client index.
* @param command Command name.
* @param sArgs Chat argument string.
*/
forward void OnClientSayCommand_Post(int client, const char[] command, const char[] sArgs);

View File

@@ -0,0 +1,514 @@
/**
* vim: set ts=4 sw=4 tw=99 noet :
* =============================================================================
* SourceMod (C)2004-2014 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _convars_included
#endinput
#endif
#define _convars_included
/**
* Console variable bound values used with Get/SetConVarBounds()
*/
enum ConVarBounds
{
ConVarBound_Upper = 0,
ConVarBound_Lower
};
/**
* Console variable query result values.
*/
enum ConVarQueryResult
{
ConVarQuery_Cancelled = -1, //< Client disconnected during query */
ConVarQuery_Okay = 0, //< Retrieval of client convar value was successful. */
ConVarQuery_NotFound, //< Client convar was not found. */
ConVarQuery_NotValid, //< A console command with the same name was found, but there is no convar. */
ConVarQuery_Protected //< Client convar was found, but it is protected. The server cannot retrieve its value. */
};
/**
* Called when a console variable's value is changed.
*
* @param convar Handle to the convar that was changed.
* @param oldValue String containing the value of the convar before it was changed.
* @param newValue String containing the new value of the convar.
*/
typedef ConVarChanged = function void (ConVar convar, const char[] oldValue, const char[] newValue);
/**
* Creates a new console variable.
*
* @param name Name of new convar.
* @param defaultValue String containing the default value of new convar.
* @param description Optional description of the convar.
* @param flags Optional bitstring of flags determining how the convar should be handled. See FCVAR_* constants for more details.
* @param hasMin Optional boolean that determines if the convar has a minimum value.
* @param min Minimum floating point value that the convar can have if hasMin is true.
* @param hasMax Optional boolean that determines if the convar has a maximum value.
* @param max Maximum floating point value that the convar can have if hasMax is true.
* @return A handle to the newly created convar. If the convar already exists, a handle to it will still be returned.
* @error Convar name is blank or is the same as an existing console command.
*/
native ConVar CreateConVar(
const char[] name,
const char[] defaultValue,
const char[] description="",
int flags=0,
bool hasMin=false, float min=0.0,
bool hasMax=false, float max=0.0);
/**
* Searches for a console variable.
*
* @param name Name of convar to find.
* @return A ConVar object if found; null otherwise.
*/
native ConVar FindConVar(const char[] name);
// A ConVar is a configurable, named setting in the srcds console.
methodmap ConVar < Handle
{
// Retrieves or sets a boolean value for the convar.
property bool BoolValue {
public native get();
public native set(bool b);
}
// Retrieves or sets an integer value for the convar.
property int IntValue {
public native get();
public native set(int value);
}
// Retrieves or sets a float value for the convar.
property float FloatValue {
public native get();
public native set(float value);
}
// Gets or sets the flag bits (FCVAR_*) on the convar.
property int Flags {
public native get();
public native set(int flags);
}
// Retrieves the plugin handle of the convar's creator
property Handle Plugin {
public native get();
}
// Sets the boolean value of a console variable.
//
// Note: The replicate and notify params are only relevant for the
// original, Dark Messiah, and Episode 1 engines. Newer engines
// automatically do these things when the convar value is changed.
//
// @param value New boolean value.
// @param replicate If set to true, the new convar value will be set on all clients.
// This will only work if the convar has the FCVAR_REPLICATED flag
// and actually exists on clients.
// @param notify If set to true, clients will be notified that the convar has changed.
// This will only work if the convar has the FCVAR_NOTIFY flag.
public native void SetBool(bool value, bool replicate=false, bool notify=false);
// Sets the integer value of a console variable.
//
// Note: The replicate and notify params are only relevant for the
// original, Dark Messiah, and Episode 1 engines. Newer engines
// automatically do these things when the convar value is changed.
//
// @param value New integer value.
// @param replicate If set to true, the new convar value will be set on all clients.
// This will only work if the convar has the FCVAR_REPLICATED flag
// and actually exists on clients.
// @param notify If set to true, clients will be notified that the convar has changed.
// This will only work if the convar has the FCVAR_NOTIFY flag.
public native void SetInt(int value, bool replicate=false, bool notify=false);
// Sets the floating point value of a console variable.
//
// Note: The replicate and notify params are only relevant for the
// original, Dark Messiah, and Episode 1 engines. Newer engines
// automatically do these things when the convar value is changed.
//
// @param value New floating point value.
// @param replicate If set to true, the new convar value will be set on all clients.
// This will only work if the convar has the FCVAR_REPLICATED flag
// and actually exists on clients.
// @param notify If set to true, clients will be notified that the convar has changed.
// This will only work if the convar has the FCVAR_NOTIFY flag.
public native void SetFloat(float value, bool replicate=false, bool notify=false);
// Retrieves the string value of a console variable.
//
// @param value Buffer to store the value of the convar.
// @param maxlength Maximum length of string buffer.
public native void GetString(char[] value, int maxlength);
// Sets the string value of a console variable.
//
// Note: The replicate and notify params are only relevant for the
// original, Dark Messiah, and Episode 1 engines. Newer engines
// automatically do these things when the convar value is changed.
//
// @param value New string value.
// @param replicate If set to true, the new convar value will be set on all clients.
// This will only work if the convar has the FCVAR_REPLICATED flag
// and actually exists on clients.
// @param notify If set to true, clients will be notified that the convar has changed.
// This will only work if the convar has the FCVAR_NOTIFY flag.
public native void SetString(const char[] value, bool replicate=false, bool notify=false);
// Resets the console variable to its default value.
//
// Note: The replicate and notify params are only relevant for the
// original, Dark Messiah, and Episode 1 engines. Newer engines
// automatically do these things when the convar value is changed.
//
// @param replicate If set to true, the new convar value will be set on all clients.
// This will only work if the convar has the FCVAR_REPLICATED flag
// and actually exists on clients.
// @param notify If set to true, clients will be notified that the convar has changed.
// This will only work if the convar has the FCVAR_NOTIFY flag.
public native void RestoreDefault(bool replicate=false, bool notify=false);
// Retrieves the default string value of a console variable.
//
// @param value Buffer to store the default value of the convar.
// @param maxlength Maximum length of string buffer.
// @return Number of bytes written to the buffer (UTF-8 safe).
public native int GetDefault(char[] value, int maxlength);
// Retrieves the specified bound of a console variable.
//
// @param type Type of bound to retrieve, ConVarBound_Lower or ConVarBound_Upper.
// @param value By-reference cell to store the specified floating point bound value.
// @return True if the convar has the specified bound set, false otherwise.
public native bool GetBounds(ConVarBounds type, float &value);
// Sets the specified bound of a console variable.
//
// @param type Type of bound to set, ConVarBound_Lower or ConVarBound_Upper
// @param set If set to true, convar will use specified bound. If false, bound will be removed.
// @param value Floating point value to use as the specified bound.
public native void SetBounds(ConVarBounds type, bool set, float value=0.0);
// Retrieves the name of a console variable.
//
// @param name Buffer to store the name of the convar.
// @param maxlength Maximum length of string buffer.
public native void GetName(char[] name, int maxlength);
// Retrieves the description of a console variable.
//
// @param buffer Buffer to store the description of the convar.
// @param maxlength Maximum length of string buffer.
public native void GetDescription(char[] buffer, int maxlength);
// Replicates a convar value to a specific client. This does not change the actual convar value.
//
// @param client Client index
// @param value String value to send
// @return True on success, false on failure
// @error Invalid client index, client not in game, or client is fake
public native bool ReplicateToClient(int client, const char[] value);
// Creates a hook for when a console variable's value is changed.
//
// @param callback An OnConVarChanged function pointer.
public native void AddChangeHook(ConVarChanged callback);
// Removes a hook for when a console variable's value is changed.
//
// @param callback An OnConVarChanged function pointer.
// @error No active hook on convar.
public native void RemoveChangeHook(ConVarChanged callback);
}
/**
* Creates a hook for when a console variable's value is changed.
*
* @param convar Handle to the convar.
* @param callback An OnConVarChanged function pointer.
* @error Invalid or corrupt Handle or invalid callback function.
*/
native void HookConVarChange(Handle convar, ConVarChanged callback);
/**
* Removes a hook for when a console variable's value is changed.
*
* @param convar Handle to the convar.
* @param callback An OnConVarChanged function pointer.
* @error Invalid or corrupt Handle, invalid callback function, or no active hook on convar.
*/
native void UnhookConVarChange(Handle convar, ConVarChanged callback);
/**
* Returns the boolean value of a console variable.
*
* @param convar Handle to the convar.
* @return The boolean value of the convar.
* @error Invalid or corrupt Handle.
*/
native bool GetConVarBool(Handle convar);
/**
* Sets the boolean value of a console variable.
*
* Note: The replicate and notify params are only relevant for the original, Dark Messiah, and
* Episode 1 engines. Newer engines automatically do these things when the convar value is changed.
*
* @param convar Handle to the convar.
* @param value New boolean value.
* @param replicate If set to true, the new convar value will be set on all clients.
* This will only work if the convar has the FCVAR_REPLICATED flag
* and actually exists on clients.
* @param notify If set to true, clients will be notified that the convar has changed.
* This will only work if the convar has the FCVAR_NOTIFY flag.
* @error Invalid or corrupt Handle.
*/
native void SetConVarBool(Handle convar, bool value, bool replicate=false, bool notify=false);
/**
* Returns the integer value of a console variable.
*
* @param convar Handle to the convar.
* @return The integer value of the convar.
* @error Invalid or corrupt Handle.
*/
native int GetConVarInt(Handle convar);
/**
* Sets the integer value of a console variable.
*
* Note: The replicate and notify params are only relevant for the original, Dark Messiah, and
* Episode 1 engines. Newer engines automatically do these things when the convar value is changed.
*
* @param convar Handle to the convar.
* @param value New integer value.
* @param replicate If set to true, the new convar value will be set on all clients.
* This will only work if the convar has the FCVAR_REPLICATED flag
* and actually exists on clients.
* @param notify If set to true, clients will be notified that the convar has changed.
* This will only work if the convar has the FCVAR_NOTIFY flag.
* @error Invalid or corrupt Handle.
*/
native void SetConVarInt(Handle convar, int value, bool replicate=false, bool notify=false);
/**
* Returns the floating point value of a console variable.
*
* @param convar Handle to the convar.
* @return The floating point value of the convar.
* @error Invalid or corrupt Handle.
*/
native float GetConVarFloat(Handle convar);
/**
* Sets the floating point value of a console variable.
*
* Note: The replicate and notify params are only relevant for the original, Dark Messiah, and
* Episode 1 engines. Newer engines automatically do these things when the convar value is changed.
*
* @param convar Handle to the convar.
* @param value New floating point value.
* @param replicate If set to true, the new convar value will be set on all clients.
* This will only work if the convar has the FCVAR_REPLICATED flag
* and actually exists on clients.
* @param notify If set to true, clients will be notified that the convar has changed.
* This will only work if the convar has the FCVAR_NOTIFY flag.
* @error Invalid or corrupt Handle.
*/
native void SetConVarFloat(Handle convar, float value, bool replicate=false, bool notify=false);
/**
* Retrieves the string value of a console variable.
*
* @param convar Handle to the convar.
* @param value Buffer to store the value of the convar.
* @param maxlength Maximum length of string buffer.
* @error Invalid or corrupt Handle.
*/
native void GetConVarString(Handle convar, char[] value, int maxlength);
/**
* Sets the string value of a console variable.
*
* Note: The replicate and notify params are only relevant for the original, Dark Messiah, and
* Episode 1 engines. Newer engines automatically do these things when the convar value is changed.
*
* @param convar Handle to the convar.
* @param value New string value.
* @param replicate If set to true, the new convar value will be set on all clients.
* This will only work if the convar has the FCVAR_REPLICATED flag
* and actually exists on clients.
* @param notify If set to true, clients will be notified that the convar has changed.
* This will only work if the convar has the FCVAR_NOTIFY flag.
* @error Invalid or corrupt Handle.
*/
native void SetConVarString(Handle convar, const char[] value, bool replicate=false, bool notify=false);
/**
* Resets the console variable to its default value.
*
* Note: The replicate and notify params are only relevant for the original, Dark Messiah, and
* Episode 1 engines. Newer engines automatically do these things when the convar value is changed.
*
* @param convar Handle to the convar.
* @param replicate If set to true, the new convar value will be set on all clients.
* This will only work if the convar has the FCVAR_REPLICATED flag
* and actually exists on clients.
* @param notify If set to true, clients will be notified that the convar has changed.
* This will only work if the convar has the FCVAR_NOTIFY flag.
* @error Invalid or corrupt Handle.
*/
native void ResetConVar(Handle convar, bool replicate=false, bool notify=false);
/**
* Retrieves the default string value of a console variable.
*
* @param convar Handle to the convar.
* @param value Buffer to store the default value of the convar.
* @param maxlength Maximum length of string buffer.
* @return Number of bytes written to the buffer (UTF-8 safe).
* @error Invalid or corrupt Handle.
*/
native int GetConVarDefault(Handle convar, char[] value, int maxlength);
/**
* Returns the bitstring of flags on a console variable.
*
* @param convar Handle to the convar.
* @return A bitstring containing the FCVAR_* flags that are enabled.
* @error Invalid or corrupt Handle.
*/
native int GetConVarFlags(Handle convar);
/**
* Sets the bitstring of flags on a console variable.
*
* @param convar Handle to the convar.
* @param flags A bitstring containing the FCVAR_* flags to enable.
* @error Invalid or corrupt Handle.
*/
native void SetConVarFlags(Handle convar, int flags);
/**
* Retrieves the specified bound of a console variable.
*
* @param convar Handle to the convar.
* @param type Type of bound to retrieve, ConVarBound_Lower or ConVarBound_Upper.
* @param value By-reference cell to store the specified floating point bound value.
* @return True if the convar has the specified bound set, false otherwise.
* @error Invalid or corrupt Handle.
*/
native bool GetConVarBounds(Handle convar, ConVarBounds type, float &value);
/**
* Sets the specified bound of a console variable.
*
* @param convar Handle to the convar.
* @param type Type of bound to set, ConVarBound_Lower or ConVarBound_Upper
* @param set If set to true, convar will use specified bound. If false, bound will be removed.
* @param value Floating point value to use as the specified bound.
* @error Invalid or corrupt Handle.
*/
native void SetConVarBounds(Handle convar, ConVarBounds type, bool set, float value=0.0);
/**
* Retrieves the name of a console variable.
*
* @param convar Handle to the convar.
* @param name Buffer to store the name of the convar.
* @param maxlength Maximum length of string buffer.
* @error Invalid or corrupt Handle.
*/
native void GetConVarName(Handle convar, char[] name, int maxlength);
/**
* Replicates a convar value to a specific client. This does not change the actual convar value.
*
* @param client Client index
* @param convar ConVar handle
* @param value String value to send
* @return True on success, false on failure
* @error Invalid client index, client not in game, or client is fake
*/
native bool SendConVarValue(int client, Handle convar, const char[] value);
typeset ConVarQueryFinished
{
// Called when a query to retrieve a client's console variable has finished.
//
// @param cookie Unique identifier of query.
// @param client Player index.
// @param result Result of query that tells one whether or not query was successful.
// See ConVarQueryResult enum for more details.
// @param convarName Name of client convar that was queried.
// @param convarValue Value of client convar that was queried if successful. This will be "" if it was not.
// @param value Value that was passed when query was started.
function void (QueryCookie cookie, int client, ConVarQueryResult result, const char[] cvarName, const char[] cvarValue, any value);
// Called when a query to retrieve a client's console variable has finished.
//
// @param cookie Unique identifier of query.
// @param client Player index.
// @param result Result of query that tells one whether or not query was successful.
// See ConVarQueryResult enum for more details.
// @param convarName Name of client convar that was queried.
// @param convarValue Value of client convar that was queried if successful. This will be "" if it was not.
function void (QueryCookie cookie, int client, ConVarQueryResult result, const char[] cvarName, const char[] cvarValue);
};
/**
* Starts a query to retrieve the value of a client's console variable.
*
* @param client Player index.
* @param cvarName Name of client convar to query.
* @param callback A function to use as a callback when the query has finished.
* @param value Optional value to pass to the callback function.
* @return A cookie that uniquely identifies the query.
* Returns QUERYCOOKIE_FAILED on failure, such as when used on a bot.
*/
native QueryCookie QueryClientConVar(int client, const char[] cvarName, ConVarQueryFinished callback, any value=0);
/**
* Returns true if the supplied character is valid in a ConVar name.
*
* @param c Character to validate.
* @return True is valid for ConVars, false otherwise
*/
stock bool IsValidConVarChar(int c)
{
return (c == '_' || IsCharAlpha(c) || IsCharNumeric(c));
}

320
scripting/include/core.inc Normal file
View File

@@ -0,0 +1,320 @@
/**
* vim: set ts=4 sw=4 tw=99 noet:
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _core_included
#endinput
#endif
#define _core_included
#include <version>
/** If this gets changed, you need to update Core's check. */
#define SOURCEMOD_PLUGINAPI_VERSION 7
struct PlVers
{
public int version;
public const char[] filevers;
public const char[] date;
public const char[] time;
};
/**
* Specifies what to do after a hook completes.
*/
enum Action
{
Plugin_Continue = 0, /**< Continue with the original action */
Plugin_Changed = 1, /**< Inputs or outputs have been overridden with new values */
Plugin_Handled = 3, /**< Handle the action at the end (don't call it) */
Plugin_Stop = 4 /**< Immediately stop the hook chain and handle the original */
};
/**
* Specifies identity types.
*/
enum Identity
{
Identity_Core = 0,
Identity_Extension = 1,
Identity_Plugin = 2
};
public PlVers __version =
{
version = SOURCEMOD_PLUGINAPI_VERSION,
filevers = SOURCEMOD_VERSION,
date = __DATE__,
time = __TIME__
};
/**
* Plugin status values.
*/
enum PluginStatus
{
Plugin_Running=0, /**< Plugin is running */
/* All states below are "temporarily" unexecutable */
Plugin_Paused, /**< Plugin is loaded but paused */
Plugin_Error, /**< Plugin is loaded but errored/locked */
/* All states below do not have all natives */
Plugin_Loaded, /**< Plugin has passed loading and can be finalized */
Plugin_Failed, /**< Plugin has a fatal failure */
Plugin_Created, /**< Plugin is created but not initialized */
Plugin_Uncompiled, /**< Plugin is not yet compiled by the JIT */
Plugin_BadLoad, /**< Plugin failed to load */
Plugin_Evicted /**< Plugin was unloaded due to an error */
};
/**
* Plugin information properties. Plugins can declare a global variable with
* their info. Example,
*
* public Plugin myinfo = {
* name = "Admin Help",
* author = "AlliedModders LLC",
* description = "Display command information",
* version = "1.0",
* url = "http://www.sourcemod.net/"
* };
*
* SourceMod will display this information when a user inspects plugins in the
* console.
*/
enum PluginInfo
{
PlInfo_Name, /**< Plugin name */
PlInfo_Author, /**< Plugin author */
PlInfo_Description, /**< Plugin description */
PlInfo_Version, /**< Plugin version */
PlInfo_URL /**< Plugin URL */
};
/**
* Defines how an extension must expose itself for autoloading.
*/
struct Extension
{
public const char[] name; /**< Short name */
public const char[] file; /**< Default file name */
public bool autoload; /**< Whether or not to auto-load */
public bool required; /**< Whether or not to require */
};
/**
* Defines how a plugin must expose itself for native requiring.
*/
struct SharedPlugin
{
public const char[] name; /**< Short name */
public const char[] file; /**< File name */
public bool required; /**< Whether or not to require */
};
public float NULL_VECTOR[3]; /**< Pass this into certain functions to act as a C++ NULL */
public const char NULL_STRING[1]; /**< pass this into certain functions to act as a C++ NULL */
/**
* Check if the given vector is the NULL_VECTOR.
*
* @param vec The vector to test.
* @return True if NULL_VECTOR, false otherwise.
*/
native bool IsNullVector(const float vec[3]);
/**
* Check if the given string is the NULL_STRING.
*
* @param str The string to test.
* @return True if NULL_STRING, false otherwise.
*/
native bool IsNullString(const char[] str);
/**
* Horrible compatibility shim.
*/
public Extension __ext_core =
{
name = "Core",
file = "core",
autoload = 0,
required = 0,
};
native int VerifyCoreVersion();
/**
* Sets a native as optional, such that if it is unloaded, removed,
* or otherwise non-existent, the plugin will still work. Calling
* removed natives results in a run-time error.
*
* @param name Native name.
*/
native void MarkNativeAsOptional(const char[] name);
public void __ext_core_SetNTVOptional()
{
MarkNativeAsOptional("GetFeatureStatus");
MarkNativeAsOptional("RequireFeature");
MarkNativeAsOptional("AddCommandListener");
MarkNativeAsOptional("RemoveCommandListener");
MarkNativeAsOptional("BfWriteBool");
MarkNativeAsOptional("BfWriteByte");
MarkNativeAsOptional("BfWriteChar");
MarkNativeAsOptional("BfWriteShort");
MarkNativeAsOptional("BfWriteWord");
MarkNativeAsOptional("BfWriteNum");
MarkNativeAsOptional("BfWriteFloat");
MarkNativeAsOptional("BfWriteString");
MarkNativeAsOptional("BfWriteEntity");
MarkNativeAsOptional("BfWriteAngle");
MarkNativeAsOptional("BfWriteCoord");
MarkNativeAsOptional("BfWriteVecCoord");
MarkNativeAsOptional("BfWriteVecNormal");
MarkNativeAsOptional("BfWriteAngles");
MarkNativeAsOptional("BfReadBool");
MarkNativeAsOptional("BfReadByte");
MarkNativeAsOptional("BfReadChar");
MarkNativeAsOptional("BfReadShort");
MarkNativeAsOptional("BfReadWord");
MarkNativeAsOptional("BfReadNum");
MarkNativeAsOptional("BfReadFloat");
MarkNativeAsOptional("BfReadString");
MarkNativeAsOptional("BfReadEntity");
MarkNativeAsOptional("BfReadAngle");
MarkNativeAsOptional("BfReadCoord");
MarkNativeAsOptional("BfReadVecCoord");
MarkNativeAsOptional("BfReadVecNormal");
MarkNativeAsOptional("BfReadAngles");
MarkNativeAsOptional("BfGetNumBytesLeft");
MarkNativeAsOptional("BfWrite.WriteBool");
MarkNativeAsOptional("BfWrite.WriteByte");
MarkNativeAsOptional("BfWrite.WriteChar");
MarkNativeAsOptional("BfWrite.WriteShort");
MarkNativeAsOptional("BfWrite.WriteWord");
MarkNativeAsOptional("BfWrite.WriteNum");
MarkNativeAsOptional("BfWrite.WriteFloat");
MarkNativeAsOptional("BfWrite.WriteString");
MarkNativeAsOptional("BfWrite.WriteEntity");
MarkNativeAsOptional("BfWrite.WriteAngle");
MarkNativeAsOptional("BfWrite.WriteCoord");
MarkNativeAsOptional("BfWrite.WriteVecCoord");
MarkNativeAsOptional("BfWrite.WriteVecNormal");
MarkNativeAsOptional("BfWrite.WriteAngles");
MarkNativeAsOptional("BfRead.ReadBool");
MarkNativeAsOptional("BfRead.ReadByte");
MarkNativeAsOptional("BfRead.ReadChar");
MarkNativeAsOptional("BfRead.ReadShort");
MarkNativeAsOptional("BfRead.ReadWord");
MarkNativeAsOptional("BfRead.ReadNum");
MarkNativeAsOptional("BfRead.ReadFloat");
MarkNativeAsOptional("BfRead.ReadString");
MarkNativeAsOptional("BfRead.ReadEntity");
MarkNativeAsOptional("BfRead.ReadAngle");
MarkNativeAsOptional("BfRead.ReadCoord");
MarkNativeAsOptional("BfRead.ReadVecCoord");
MarkNativeAsOptional("BfRead.ReadVecNormal");
MarkNativeAsOptional("BfRead.ReadAngles");
MarkNativeAsOptional("BfRead.BytesLeft.get");
MarkNativeAsOptional("PbReadInt");
MarkNativeAsOptional("PbReadFloat");
MarkNativeAsOptional("PbReadBool");
MarkNativeAsOptional("PbReadString");
MarkNativeAsOptional("PbReadColor");
MarkNativeAsOptional("PbReadAngle");
MarkNativeAsOptional("PbReadVector");
MarkNativeAsOptional("PbReadVector2D");
MarkNativeAsOptional("PbGetRepeatedFieldCount");
MarkNativeAsOptional("PbSetInt");
MarkNativeAsOptional("PbSetFloat");
MarkNativeAsOptional("PbSetBool");
MarkNativeAsOptional("PbSetString");
MarkNativeAsOptional("PbSetColor");
MarkNativeAsOptional("PbSetAngle");
MarkNativeAsOptional("PbSetVector");
MarkNativeAsOptional("PbSetVector2D");
MarkNativeAsOptional("PbAddInt");
MarkNativeAsOptional("PbAddFloat");
MarkNativeAsOptional("PbAddBool");
MarkNativeAsOptional("PbAddString");
MarkNativeAsOptional("PbAddColor");
MarkNativeAsOptional("PbAddAngle");
MarkNativeAsOptional("PbAddVector");
MarkNativeAsOptional("PbAddVector2D");
MarkNativeAsOptional("PbRemoveRepeatedFieldValue");
MarkNativeAsOptional("PbReadMessage");
MarkNativeAsOptional("PbReadRepeatedMessage");
MarkNativeAsOptional("PbAddMessage");
MarkNativeAsOptional("Protobuf.ReadInt");
MarkNativeAsOptional("Protobuf.ReadInt64");
MarkNativeAsOptional("Protobuf.ReadFloat");
MarkNativeAsOptional("Protobuf.ReadBool");
MarkNativeAsOptional("Protobuf.ReadString");
MarkNativeAsOptional("Protobuf.ReadColor");
MarkNativeAsOptional("Protobuf.ReadAngle");
MarkNativeAsOptional("Protobuf.ReadVector");
MarkNativeAsOptional("Protobuf.ReadVector2D");
MarkNativeAsOptional("Protobuf.GetRepeatedFieldCount");
MarkNativeAsOptional("Protobuf.SetInt");
MarkNativeAsOptional("Protobuf.SetInt64");
MarkNativeAsOptional("Protobuf.SetFloat");
MarkNativeAsOptional("Protobuf.SetBool");
MarkNativeAsOptional("Protobuf.SetString");
MarkNativeAsOptional("Protobuf.SetColor");
MarkNativeAsOptional("Protobuf.SetAngle");
MarkNativeAsOptional("Protobuf.SetVector");
MarkNativeAsOptional("Protobuf.SetVector2D");
MarkNativeAsOptional("Protobuf.AddInt");
MarkNativeAsOptional("Protobuf.AddInt64");
MarkNativeAsOptional("Protobuf.AddFloat");
MarkNativeAsOptional("Protobuf.AddBool");
MarkNativeAsOptional("Protobuf.AddString");
MarkNativeAsOptional("Protobuf.AddColor");
MarkNativeAsOptional("Protobuf.AddAngle");
MarkNativeAsOptional("Protobuf.AddVector");
MarkNativeAsOptional("Protobuf.AddVector2D");
MarkNativeAsOptional("Protobuf.RemoveRepeatedFieldValue");
MarkNativeAsOptional("Protobuf.ReadMessage");
MarkNativeAsOptional("Protobuf.ReadRepeatedMessage");
MarkNativeAsOptional("Protobuf.AddMessage");
VerifyCoreVersion();
}
#define AUTOLOAD_EXTENSIONS
#define REQUIRE_EXTENSIONS
#define REQUIRE_PLUGIN

View File

@@ -0,0 +1,559 @@
/**************************************************************************
* *
* Colored Chat Functions *
* Author: exvel, Editor: Popoklopsi, Powerlord, Bara *
* Version: 1.1.3 *
* *
**************************************************************************/
#if defined _colors_included
#endinput
#endif
#define _colors_included
#define MAX_MESSAGE_LENGTH 250
#define MAX_COLORS 16
#define SERVER_INDEX 0
#define NO_INDEX -1
#define NO_PLAYER -2
enum Colors
{
Color_Default = 0,
Color_Darkred,
Color_Pink,
Color_Green,
Color_Lightgreen,
Color_Lime,
Color_Red,
Color_Grey,
Color_Olive,
Color_A,
Color_Lightblue,
Color_Blue,
Color_D,
Color_Purple,
Color_Darkrange,
Color_Orange
}
/* Colors' properties */
new String:CTag[][] = {"{normal}", "{darkred}", "{pink}", "{green}", "{lightgreen}", "{lime}", "{red}", "{grey}", "{olive}", "{a}", "{lightblue}", "{blue}", "{d}", "{purple}", "{darkorange}", "{orange}"};
new String:CTagCode[][] = {"\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07", "\x08", "\x09", "\x0A", "\x0B", "\x0C", "\x0D", "\x0E", "\x0F", "\x10"};
new bool:CTagReqSayText2[] = {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false};
new bool:CEventIsHooked = false;
new bool:CSkipList[MAXPLAYERS+1] = {false,...};
/* Game default profile */
new bool:CProfile_Colors[] = {true, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false};
new CProfile_TeamIndex[] = {NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX};
new bool:CProfile_SayText2 = false;
/**
* Prints a message to a specific client in the chat area.
* Supports color tags.
*
* @param client Client index.
* @param szMessage Message (formatting rules).
* @return No return
*
* On error/Errors: If the client is not connected an error will be thrown.
*/
stock CPrintToChat(client, const String:szMessage[], any:...)
{
if (client <= 0 || client > MaxClients)
ThrowError("Invalid client index %d", client);
if (!IsClientInGame(client))
ThrowError("Client %d is not in game", client);
decl String:szBuffer[MAX_MESSAGE_LENGTH];
decl String:szCMessage[MAX_MESSAGE_LENGTH];
SetGlobalTransTarget(client);
Format(szBuffer, sizeof(szBuffer), "\x01%s", szMessage);
VFormat(szCMessage, sizeof(szCMessage), szBuffer, 3);
new index = CFormat(szCMessage, sizeof(szCMessage));
if (index == NO_INDEX)
PrintToChat(client, "%s", szCMessage);
else
CSayText2(client, index, szCMessage);
}
stock CReplyToCommand(client, const String:szMessage[], any:...)
{
decl String:szCMessage[MAX_MESSAGE_LENGTH];
VFormat(szCMessage, sizeof(szCMessage), szMessage, 3);
if (client == 0)
{
CRemoveTags(szCMessage, sizeof(szCMessage));
PrintToServer("%s", szCMessage);
}
else if (GetCmdReplySource() == SM_REPLY_TO_CONSOLE)
{
CRemoveTags(szCMessage, sizeof(szCMessage));
PrintToConsole(client, "%s", szCMessage);
}
else
{
CPrintToChat(client, "%s", szCMessage);
}
}
/**
* Prints a message to all clients in the chat area.
* Supports color tags.
*
* @param client Client index.
* @param szMessage Message (formatting rules)
* @return No return
*/
stock CPrintToChatAll(const String:szMessage[], any:...)
{
decl String:szBuffer[MAX_MESSAGE_LENGTH];
for (new i = 1; i <= MaxClients; i++)
{
if (IsClientInGame(i) && !IsFakeClient(i) && !CSkipList[i])
{
SetGlobalTransTarget(i);
VFormat(szBuffer, sizeof(szBuffer), szMessage, 2);
CPrintToChat(i, "%s", szBuffer);
}
CSkipList[i] = false;
}
}
/**
* Prints a message to a specific client in the chat area.
* Supports color tags and teamcolor tag.
*
* @param client Client index.
* @param author Author index whose color will be used for teamcolor tag.
* @param szMessage Message (formatting rules).
* @return No return
*
* On error/Errors: If the client or author are not connected an error will be thrown.
*/
stock CPrintToChatEx(client, author, const String:szMessage[], any:...)
{
if (client <= 0 || client > MaxClients)
ThrowError("Invalid client index %d", client);
if (!IsClientInGame(client))
ThrowError("Client %d is not in game", client);
if (author < 0 || author > MaxClients)
ThrowError("Invalid client index %d", author);
decl String:szBuffer[MAX_MESSAGE_LENGTH];
decl String:szCMessage[MAX_MESSAGE_LENGTH];
SetGlobalTransTarget(client);
Format(szBuffer, sizeof(szBuffer), "\x01%s", szMessage);
VFormat(szCMessage, sizeof(szCMessage), szBuffer, 4);
new index = CFormat(szCMessage, sizeof(szCMessage), author);
if (index == NO_INDEX)
PrintToChat(client, "%s", szCMessage);
else
CSayText2(client, author, szCMessage);
}
/**
* Prints a message to all clients in the chat area.
* Supports color tags and teamcolor tag.
*
* @param author Author index whos color will be used for teamcolor tag.
* @param szMessage Message (formatting rules).
* @return No return
*
* On error/Errors: If the author is not connected an error will be thrown.
*/
stock CPrintToChatAllEx(author, const String:szMessage[], any:...)
{
if (author < 0 || author > MaxClients)
ThrowError("Invalid client index %d", author);
if (!IsClientInGame(author))
ThrowError("Client %d is not in game", author);
decl String:szBuffer[MAX_MESSAGE_LENGTH];
for (new i = 1; i <= MaxClients; i++)
{
if (IsClientInGame(i) && !IsFakeClient(i) && !CSkipList[i])
{
SetGlobalTransTarget(i);
VFormat(szBuffer, sizeof(szBuffer), szMessage, 3);
CPrintToChatEx(i, author, "%s", szBuffer);
}
CSkipList[i] = false;
}
}
/**
* Removes color tags from the string.
*
* @param szMessage String.
* @return No return
*/
stock CRemoveTags(String:szMessage[], maxlength)
{
for (new i = 0; i < MAX_COLORS; i++)
ReplaceString(szMessage, maxlength, CTag[i], "", false);
ReplaceString(szMessage, maxlength, "{teamcolor}", "", false);
}
/**
* Checks whether a color is allowed or not
*
* @param tag Color Tag.
* @return True when color is supported, otherwise false
*/
stock CColorAllowed(Colors:color)
{
if (!CEventIsHooked)
{
CSetupProfile();
CEventIsHooked = true;
}
return CProfile_Colors[color];
}
/**
* Replace the color with another color
* Handle with care!
*
* @param color color to replace.
* @param newColor color to replace with.
* @noreturn
*/
stock CReplaceColor(Colors:color, Colors:newColor)
{
if (!CEventIsHooked)
{
CSetupProfile();
CEventIsHooked = true;
}
CProfile_Colors[color] = CProfile_Colors[newColor];
CProfile_TeamIndex[color] = CProfile_TeamIndex[newColor];
CTagReqSayText2[color] = CTagReqSayText2[newColor];
Format(CTagCode[color], sizeof(CTagCode[]), CTagCode[newColor])
}
/**
* This function should only be used right in front of
* CPrintToChatAll or CPrintToChatAllEx and it tells
* to those funcions to skip specified client when printing
* message to all clients. After message is printed client will
* no more be skipped.
*
* @param client Client index
* @return No return
*/
stock CSkipNextClient(client)
{
if (client <= 0 || client > MaxClients)
ThrowError("Invalid client index %d", client);
CSkipList[client] = true;
}
/**
* Replaces color tags in a string with color codes
*
* @param szMessage String.
* @param maxlength Maximum length of the string buffer.
* @return Client index that can be used for SayText2 author index
*
* On error/Errors: If there is more then one team color is used an error will be thrown.
*/
stock CFormat(String:szMessage[], maxlength, author=NO_INDEX)
{
decl String:szGameName[30];
GetGameFolderName(szGameName, sizeof(szGameName));
/* Hook event for auto profile setup on map start */
if (!CEventIsHooked)
{
CSetupProfile();
HookEvent("server_spawn", CEvent_MapStart, EventHookMode_PostNoCopy);
CEventIsHooked = true;
}
new iRandomPlayer = NO_INDEX;
// On CS:GO set invisible precolor
if (StrEqual(szGameName, "csgo", false))
Format(szMessage, maxlength, " \x01\x0B\x01%s", szMessage);
/* If author was specified replace {teamcolor} tag */
if (author != NO_INDEX)
{
if (CProfile_SayText2)
{
ReplaceString(szMessage, maxlength, "{teamcolor}", "\x03", false);
iRandomPlayer = author;
}
/* If saytext2 is not supported by game replace {teamcolor} with green tag */
else
ReplaceString(szMessage, maxlength, "{teamcolor}", CTagCode[Color_Green], false);
}
else
ReplaceString(szMessage, maxlength, "{teamcolor}", "", false);
/* For other color tags we need a loop */
for (new i = 0; i < MAX_COLORS; i++)
{
/* If tag not found - skip */
if (StrContains(szMessage, CTag[i], false) == -1)
continue;
/* If tag is not supported by game replace it with green tag */
else if (!CProfile_Colors[i])
ReplaceString(szMessage, maxlength, CTag[i], CTagCode[Color_Green], false);
/* If tag doesn't need saytext2 simply replace */
else if (!CTagReqSayText2[i])
ReplaceString(szMessage, maxlength, CTag[i], CTagCode[i], false);
/* Tag needs saytext2 */
else
{
/* If saytext2 is not supported by game replace tag with green tag */
if (!CProfile_SayText2)
ReplaceString(szMessage, maxlength, CTag[i], CTagCode[Color_Green], false);
/* Game supports saytext2 */
else
{
/* If random player for tag wasn't specified replace tag and find player */
if (iRandomPlayer == NO_INDEX)
{
/* Searching for valid client for tag */
iRandomPlayer = CFindRandomPlayerByTeam(CProfile_TeamIndex[i]);
/* If player not found replace tag with green color tag */
if (iRandomPlayer == NO_PLAYER)
ReplaceString(szMessage, maxlength, CTag[i], CTagCode[Color_Green], false);
/* If player was found simply replace */
else
ReplaceString(szMessage, maxlength, CTag[i], CTagCode[i], false);
}
/* If found another team color tag throw error */
else
{
//ReplaceString(szMessage, maxlength, CTag[i], "");
ThrowError("Using two team colors in one message is not allowed");
}
}
}
}
return iRandomPlayer;
}
/**
* Founds a random player with specified team
*
* @param color_team Client team.
* @return Client index or NO_PLAYER if no player found
*/
stock CFindRandomPlayerByTeam(color_team)
{
if (color_team == SERVER_INDEX)
return 0;
else
{
for (new i = 1; i <= MaxClients; i++)
{
if (IsClientInGame(i) && GetClientTeam(i) == color_team)
return i;
}
}
return NO_PLAYER;
}
/**
* Sends a SayText2 usermessage to a client
*
* @param szMessage Client index
* @param maxlength Author index
* @param szMessage Message
* @return No return.
*/
stock CSayText2(client, author, const String:szMessage[])
{
new Handle:hBuffer = StartMessageOne("SayText2", client, USERMSG_RELIABLE|USERMSG_BLOCKHOOKS);
if(GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && GetUserMessageType() == UM_Protobuf)
{
PbSetInt(hBuffer, "ent_idx", author);
PbSetBool(hBuffer, "chat", true);
PbSetString(hBuffer, "msg_name", szMessage);
PbAddString(hBuffer, "params", "");
PbAddString(hBuffer, "params", "");
PbAddString(hBuffer, "params", "");
PbAddString(hBuffer, "params", "");
}
else
{
BfWriteByte(hBuffer, author);
BfWriteByte(hBuffer, true);
BfWriteString(hBuffer, szMessage);
}
EndMessage();
}
/**
* Creates game color profile
* This function must be edited if you want to add more games support
*
* @return No return.
*/
stock CSetupProfile()
{
decl String:szGameName[30];
GetGameFolderName(szGameName, sizeof(szGameName));
if (StrEqual(szGameName, "cstrike", false))
{
CProfile_Colors[Color_Lightgreen] = true;
CProfile_Colors[Color_Red] = true;
CProfile_Colors[Color_Blue] = true;
CProfile_Colors[Color_Olive] = true;
CProfile_TeamIndex[Color_Lightgreen] = SERVER_INDEX;
CProfile_TeamIndex[Color_Red] = 2;
CProfile_TeamIndex[Color_Blue] = 3;
CProfile_SayText2 = true;
}
else if (StrEqual(szGameName, "csgo", false))
{
CProfile_Colors[Color_Default] = true;
CProfile_Colors[Color_Darkred] = true;
CProfile_Colors[Color_Pink] = true;
CProfile_Colors[Color_Green] = true;
CProfile_Colors[Color_Lightgreen] = true;
CProfile_Colors[Color_Lime] = true;
CProfile_Colors[Color_Red] = true;
CProfile_Colors[Color_Grey] = true;
CProfile_Colors[Color_Olive] = true;
CProfile_Colors[Color_A] = true;
CProfile_Colors[Color_Lightblue] = true;
CProfile_Colors[Color_Blue] = true;
CProfile_Colors[Color_D] = true;
CProfile_Colors[Color_Purple] = true;
CProfile_Colors[Color_Darkrange] = true;
CProfile_Colors[Color_Orange] = true;
CProfile_Colors[Color_Red] = true;
CProfile_Colors[Color_Blue] = true;
CProfile_Colors[Color_Olive] = true;
CProfile_Colors[Color_Darkred] = true;
CProfile_Colors[Color_Lime] = true;
CProfile_Colors[Color_Purple] = true;
CProfile_Colors[Color_Grey] = true;
CProfile_Colors[Color_Orange] = true;
CProfile_TeamIndex[Color_Red] = 2;
CProfile_TeamIndex[Color_Blue] = 3;
CProfile_SayText2 = true;
}
else if (StrEqual(szGameName, "tf", false))
{
CProfile_Colors[Color_Lightgreen] = true;
CProfile_Colors[Color_Red] = true;
CProfile_Colors[Color_Blue] = true;
CProfile_Colors[Color_Olive] = true;
CProfile_TeamIndex[Color_Lightgreen] = SERVER_INDEX;
CProfile_TeamIndex[Color_Red] = 2;
CProfile_TeamIndex[Color_Blue] = 3;
CProfile_SayText2 = true;
}
else if (StrEqual(szGameName, "left4dead", false) || StrEqual(szGameName, "left4dead2", false))
{
CProfile_Colors[Color_Lightgreen] = true;
CProfile_Colors[Color_Red] = true;
CProfile_Colors[Color_Blue] = true;
CProfile_Colors[Color_Olive] = true;
CProfile_TeamIndex[Color_Lightgreen] = SERVER_INDEX;
CProfile_TeamIndex[Color_Red] = 3;
CProfile_TeamIndex[Color_Blue] = 2;
CProfile_SayText2 = true;
}
else if (StrEqual(szGameName, "hl2mp", false))
{
/* hl2mp profile is based on mp_teamplay convar */
if (GetConVarBool(FindConVar("mp_teamplay")))
{
CProfile_Colors[Color_Red] = true;
CProfile_Colors[Color_Blue] = true;
CProfile_Colors[Color_Olive] = true;
CProfile_TeamIndex[Color_Red] = 3;
CProfile_TeamIndex[Color_Blue] = 2;
CProfile_SayText2 = true;
}
else
{
CProfile_SayText2 = false;
CProfile_Colors[Color_Olive] = true;
}
}
else if (StrEqual(szGameName, "dod", false))
{
CProfile_Colors[Color_Olive] = true;
CProfile_SayText2 = false;
}
/* Profile for other games */
else
{
if (GetUserMessageId("SayText2") == INVALID_MESSAGE_ID)
{
CProfile_SayText2 = false;
}
else
{
CProfile_Colors[Color_Red] = true;
CProfile_Colors[Color_Blue] = true;
CProfile_TeamIndex[Color_Red] = 2;
CProfile_TeamIndex[Color_Blue] = 3;
CProfile_SayText2 = true;
}
}
}
public Action:CEvent_MapStart(Handle:event, const String:name[], bool:dontBroadcast)
{
CSetupProfile();
for (new i = 1; i <= MaxClients; i++)
CSkipList[i] = false;
}

View File

@@ -0,0 +1,498 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _cstrike_included
#endinput
#endif
#define _cstrike_included
#define CS_TEAM_NONE 0 /**< No team yet. */
#define CS_TEAM_SPECTATOR 1 /**< Spectators. */
#define CS_TEAM_T 2 /**< Terrorists. */
#define CS_TEAM_CT 3 /**< Counter-Terrorists. */
#define CS_SLOT_PRIMARY 0 /**< Primary weapon slot. */
#define CS_SLOT_SECONDARY 1 /**< Secondary weapon slot. */
#define CS_SLOT_KNIFE 2 /**< Knife slot. */
#define CS_SLOT_GRENADE 3 /**< Grenade slot (will only return one grenade). */
#define CS_SLOT_C4 4 /**< C4 slot. */
#define CS_SLOT_BOOST 11 /**< Slot for healthshot and shield (will only return one weapon/item). */
#define CS_SLOT_UTILITY 12 /**< Slot for tablet. */
#define CS_DMG_HEADSHOT (1 << 30) /**< Headshot */
enum CSRoundEndReason
{
CSRoundEnd_TargetBombed = 0, /**< Target Successfully Bombed! */
CSRoundEnd_VIPEscaped, /**< The VIP has escaped! - Doesn't exist on CS:GO */
CSRoundEnd_VIPKilled, /**< VIP has been assassinated! - Doesn't exist on CS:GO */
CSRoundEnd_TerroristsEscaped, /**< The terrorists have escaped! */
CSRoundEnd_CTStoppedEscape, /**< The CTs have prevented most of the terrorists from escaping! */
CSRoundEnd_TerroristsStopped, /**< Escaping terrorists have all been neutralized! */
CSRoundEnd_BombDefused, /**< The bomb has been defused! */
CSRoundEnd_CTWin, /**< Counter-Terrorists Win! */
CSRoundEnd_TerroristWin, /**< Terrorists Win! */
CSRoundEnd_Draw, /**< Round Draw! */
CSRoundEnd_HostagesRescued, /**< All Hostages have been rescued! */
CSRoundEnd_TargetSaved, /**< Target has been saved! */
CSRoundEnd_HostagesNotRescued, /**< Hostages have not been rescued! */
CSRoundEnd_TerroristsNotEscaped, /**< Terrorists have not escaped! */
CSRoundEnd_VIPNotEscaped, /**< VIP has not escaped! - Doesn't exist on CS:GO */
CSRoundEnd_GameStart, /**< Game Commencing! */
// The below only exist on CS:GO
CSRoundEnd_TerroristsSurrender, /**< Terrorists Surrender */
CSRoundEnd_CTSurrender, /**< CTs Surrender */
CSRoundEnd_TerroristsPlanted, /**< Terrorists Planted the bomb */
CSRoundEnd_CTsReachedHostage /**< CTs Reached the hostage */
};
enum CSWeaponID
{
CSWeapon_NONE = 0,
CSWeapon_P228,
CSWeapon_GLOCK,
CSWeapon_SCOUT,
CSWeapon_HEGRENADE,
CSWeapon_XM1014,
CSWeapon_C4,
CSWeapon_MAC10,
CSWeapon_AUG,
CSWeapon_SMOKEGRENADE,
CSWeapon_ELITE,
CSWeapon_FIVESEVEN,
CSWeapon_UMP45,
CSWeapon_SG550,
CSWeapon_GALIL,
CSWeapon_FAMAS,
CSWeapon_USP,
CSWeapon_AWP,
CSWeapon_MP5NAVY,
CSWeapon_M249,
CSWeapon_M3,
CSWeapon_M4A1,
CSWeapon_TMP,
CSWeapon_G3SG1,
CSWeapon_FLASHBANG,
CSWeapon_DEAGLE,
CSWeapon_SG552,
CSWeapon_AK47,
CSWeapon_KNIFE,
CSWeapon_P90,
CSWeapon_SHIELD,
CSWeapon_KEVLAR,
CSWeapon_ASSAULTSUIT,
CSWeapon_NIGHTVISION, //Anything below is CS:GO ONLY
CSWeapon_GALILAR,
CSWeapon_BIZON,
CSWeapon_MAG7,
CSWeapon_NEGEV,
CSWeapon_SAWEDOFF,
CSWeapon_TEC9,
CSWeapon_TASER,
CSWeapon_HKP2000,
CSWeapon_MP7,
CSWeapon_MP9,
CSWeapon_NOVA,
CSWeapon_P250,
CSWeapon_SCAR17,
CSWeapon_SCAR20,
CSWeapon_SG556,
CSWeapon_SSG08,
CSWeapon_KNIFE_GG,
CSWeapon_MOLOTOV,
CSWeapon_DECOY,
CSWeapon_INCGRENADE,
CSWeapon_DEFUSER,
CSWeapon_HEAVYASSAULTSUIT,
//The rest are actual item definition indexes for CS:GO
CSWeapon_CUTTERS = 56,
CSWeapon_HEALTHSHOT = 57,
CSWeapon_KNIFE_T = 59,
CSWeapon_M4A1_SILENCER = 60,
CSWeapon_USP_SILENCER = 61,
CSWeapon_CZ75A = 63,
CSWeapon_REVOLVER = 64,
CSWeapon_TAGGRENADE = 68,
CSWeapon_FISTS = 69,
CSWeapon_BREACHCHARGE = 70,
CSWeapon_TABLET = 72,
CSWeapon_MELEE = 74,
CSWeapon_AXE = 75,
CSWeapon_HAMMER = 76,
CSWeapon_SPANNER = 78,
CSWeapon_KNIFE_GHOST = 80,
CSWeapon_FIREBOMB = 81,
CSWeapon_DIVERSION = 82,
CSWeapon_FRAGGRENADE = 83,
CSWeapon_SNOWBALL = 84,
CSWeapon_BUMPMINE = 85,
CSWeapon_MAX_WEAPONS_NO_KNIFES, // Max without the knife item defs, useful when treating all knives as a regular knife.
CSWeapon_BAYONET = 500,
CSWeapon_KNIFE_CLASSIC = 503,
CSWeapon_KNIFE_FLIP = 505,
CSWeapon_KNIFE_GUT = 506,
CSWeapon_KNIFE_KARAMBIT = 507,
CSWeapon_KNIFE_M9_BAYONET = 508,
CSWeapon_KNIFE_TATICAL = 509,
CSWeapon_KNIFE_FALCHION = 512,
CSWeapon_KNIFE_SURVIVAL_BOWIE = 514,
CSWeapon_KNIFE_BUTTERFLY = 515,
CSWeapon_KNIFE_PUSH = 516,
CSWeapon_KNIFE_CORD = 517,
CSWeapon_KNIFE_CANIS = 518,
CSWeapon_KNIFE_URSUS = 519,
CSWeapon_KNIFE_GYPSY_JACKKNIFE = 520,
CSWeapon_KNIFE_OUTDOOR = 521,
CSWeapon_KNIFE_STILETTO = 522,
CSWeapon_KNIFE_WIDOWMAKER = 523,
CSWeapon_KNIFE_SKELETON = 525,
CSWeapon_MAX_WEAPONS //THIS MUST BE LAST, EASY WAY TO CREATE LOOPS. When looping, do CS_IsValidWeaponID(i), to check.
};
/**
* Called when a player attempts to purchase an item.
* Return Plugin_Continue to allow the purchase or return a
* higher action to deny.
*
* @param client Client index
* @param weapon User input for weapon name
*/
forward Action CS_OnBuyCommand(int client, const char[] weapon);
/**
* Called when CSWeaponDrop is called
* Return Plugin_Continue to allow the call or return a
* higher action to block.
*
* @param client Client index
* @param weaponIndex Weapon index
* @param donated Was weapon donated (Bought from a buy menu while ctrl was pressed)
* (Note: This param is for CS:GO only, will be false on other games)
*/
forward Action CS_OnCSWeaponDrop(int client, int weaponIndex, bool donated);
/**
* Called when game retrieves a weapon's price for a player.
* Return Plugin_Continue to use default value or return a higher
* action to use a newly-set price.
*
* @note This can be called multiple times per weapon purchase
*
* @param client Client index
* @param weapon Weapon classname
* @param price Buffer param for the price of the weapon
*
* @note Not all "weapons" call GetWeaponPrice. Example: c4, knife, vest, vest helmet, night vision.
*/
forward Action CS_OnGetWeaponPrice(int client, const char[] weapon, int &price);
/**
* Called when TerminateRound is called.
* Return Plugin_Continue to ignore, return Plugin_Changed to continue,
* using the given delay and reason, or return Plugin_Handled or a higher
* action to block TerminateRound from firing.
*
* @param delay Time (in seconds) until new round starts
* @param reason Reason for round end
*/
forward Action CS_OnTerminateRound(float &delay, CSRoundEndReason &reason);
/**
* Respawns a player.
*
* @param client Player's index.
* @error Invalid client index, client not in game.
*/
native void CS_RespawnPlayer(int client);
/**
* Switches the player's team.
*
* @param client Player's index.
* @param team Team index.
* @error Invalid client index, client not in game.
*/
native void CS_SwitchTeam(int client, int team);
/**
* Forces a player to drop or toss their weapon
*
* @param client Player's index.
* @param weaponIndex Index of weapon to drop.
* @param toss True to toss weapon (with velocity) or false to just drop weapon
* @param blockhook Set to true to stop the corresponding CS_OnCSWeaponDrop
* @error Invalid client index, client not in game, or invalid weapon index.
*/
native void CS_DropWeapon(int client, int weaponIndex, bool toss, bool blockhook = false);
/**
* Forces round to end with a reason
*
* @param delay Time (in seconds) to delay before new round starts
* @param reason Reason for the round ending
* @param blockhook Set to true to stop the corresponding CS_OnTerminateRound
* forward from being called.
*/
native void CS_TerminateRound(float delay, CSRoundEndReason reason, bool blockhook = false);
/**
* Gets a weapon name from a weapon alias
*
* @param alias Weapons alias to get weapon name for.
* @param weapon Buffer to store weapons name
* @param size Size of buffer to store the weapons name.
*
* @note Will set the buffer to the original alias if it is not an alias to a weapon.
*/
native void CS_GetTranslatedWeaponAlias(const char[] alias, char[] weapon, int size);
/**
* Gets a weapon's price
*
* @param client Client to check weapon price for.
* @param id Weapon id for the weapon to check
* @param defaultprice Set to true to get defaultprice.
* @return Returns price of the weapon (even if modified)
* @error Invalid client, failing to get weapon info, or failing to get price offset.
*
* @note c4, knife and shield will always return 0. vest, vest helmet and night vision will always return default price.
*/
native int CS_GetWeaponPrice(int client, CSWeaponID id, bool defaultprice = false);
/**
* Gets a clients clan tag
*
* @param client Client index to get clan tag for.
* @param buffer Buffer to store clients clan tag in.
* @param size Size of the buffer.
* @return Number of non-null bytes written.
* @error Invalid client.
*/
native int CS_GetClientClanTag(int client, char[] buffer, int size);
/**
* Sets a clients clan tag
*
* @param client Client index to set clan tag for.
* @param tag Tag to set clients clan tag as.
* @error Invalid client.
*/
native void CS_SetClientClanTag(int client, const char[] tag);
/**
* Gets a team's score
*
* @param team Team index to get score for.
* @return Returns the internal team score.
* @error Invalid team index.
*/
native int CS_GetTeamScore(int team);
/**
* Sets a team's score
*
* @param team Team index to set score for.
* @param value Value to set teams score as.
* @error Invalid team index.
*
* @note This will update the scoreboard only after the scoreboard update function is called.
* Use SetTeamScore plus this to update the scoreboard instantly and save values correctly.
*/
native void CS_SetTeamScore(int team, int value);
/**
* Gets a client's mvp count
*
* @param client Client index to get mvp count of.
* @return Returns the client's internal MVP count.
* @error Invalid client.
*/
native int CS_GetMVPCount(int client);
/**
* Sets a client's mvp count
*
* @param client Client index to set mvp count for.
* @param value Value to set client's mvp count as.
* @error Invalid client.
*/
native void CS_SetMVPCount(int client, int value);
/**
* Gets a client's contribution score (CS:GO only)
*
* @param client Client index to get score of.
* @return Returns the client's score.
* @error Invalid client.
*/
native int CS_GetClientContributionScore(int client);
/**
* Sets a client's contribution score (CS:GO only)
*
* @param client Client index to set score for.
* @param value Value to set client's score as.
* @error Invalid client.
*/
native void CS_SetClientContributionScore(int client, int value);
/**
* Gets a client's assists (CS:GO only)
*
* @param client Client index to get assists of.
* @return Returns the client's assists.
* @error Invalid client.
*/
native int CS_GetClientAssists(int client);
/**
* Sets a client's assists (CS:GO only)
*
* @param client Client index to set assists for.
* @param value Value to set client's assists as.
* @error Invalid client.
*/
native void CS_SetClientAssists(int client, int value);
/**
* Gets a weaponID from a alias
*
* @param alias Weapon alias to attempt to get an id for.
* @return Returns a weapon id or 0 if failed to find a match.
*
* @note For best results use CS_GetTranslatedWeaponAlias on the weapon name before passing it.
*/
native CSWeaponID CS_AliasToWeaponID(const char[] alias);
/**
* Gets a alias from a weaponID
*
* @param weaponID WeaponID to get alias for.
* @param destination Destination string to hold the weapon alias.
* @param len Length of the destination array.
* @return Returns number of cells written.
*/
native int CS_WeaponIDToAlias(CSWeaponID weaponID, char[] destination, int len);
/**
* Returns weather a WeaponID is valid on the current mod (css or csgo)
*
* @param weaponID WeaponID to check
* @return Returns true if its a valid WeaponID false otherwise.
*
* @note This will return false always for CSWeapon_NONE. Should only be called after OnMapStart since weapon info isnt intialized before.
*/
native bool CS_IsValidWeaponID(CSWeaponID id);
/**
* Sets a player's model based on their current class
*
* @param client Player's index.
* @error Invalid client index, client not in game.
*/
native void CS_UpdateClientModel(int client);
/**
* Returns a CSWeaponID equivalent based on the item definition index.
*
* @param iDefIndex Definition index to get the CSWeaponID value for.
* @return Returns CSWeaponID value for the definition index.
* @error Invalid definition index.
*
* @note In most cases the id will be the item definition index. Works for CS:GO ONLY.
*/
native CSWeaponID CS_ItemDefIndexToID(int iDefIndex);
/**
* Returns a item definition index equivalent based on the CSWeaponID.
*
* @param id CSWeaponID to get the item definition for.
* @return Returns item definition index value for the weapon id.
* @error Invalid weapon id.
*
* @note In most cases the item definition index will be the id. Works for CS:GO ONLY.
*/
native int CS_WeaponIDToItemDefIndex(CSWeaponID id);
/**
* Returns the loadout slot based on the CSWeaponID. (CS:GO only)
*
* @param id CSWeaponID to get the loadout slot for.
* @return Returns loadout slot value for the weapon id.
* @error Invalid weapon id.
*/
native int CS_WeaponIDToLoadoutSlot(CSWeaponID id);
/**
* Do not edit below this line!
*/
public Extension __ext_cstrike =
{
name = "cstrike",
file = "games/game.cstrike.ext",
autoload = 0,
#if defined REQUIRE_EXTENSIONS
required = 1,
#else
required = 0,
#endif
};
#if !defined REQUIRE_EXTENSIONS
public void __ext_cstrike_SetNTVOptional()
{
MarkNativeAsOptional("CS_RespawnPlayer");
MarkNativeAsOptional("CS_SwitchTeam");
MarkNativeAsOptional("CS_DropWeapon");
MarkNativeAsOptional("CS_TerminateRound");
MarkNativeAsOptional("CS_GetTranslatedWeaponAlias");
MarkNativeAsOptional("CS_GetWeaponPrice");
MarkNativeAsOptional("CS_GetClientClanTag");
MarkNativeAsOptional("CS_SetClientClanTag");
MarkNativeAsOptional("CS_GetTeamScore");
MarkNativeAsOptional("CS_SetTeamScore");
MarkNativeAsOptional("CS_GetMVPCount");
MarkNativeAsOptional("CS_SetMVPCount");
MarkNativeAsOptional("CS_GetClientContributionScore");
MarkNativeAsOptional("CS_SetClientContributionScore");
MarkNativeAsOptional("CS_GetClientAssists");
MarkNativeAsOptional("CS_SetClientAssists");
MarkNativeAsOptional("CS_AliasToWeaponID");
MarkNativeAsOptional("CS_WeaponIDToAlias");
MarkNativeAsOptional("CS_IsValidWeaponID");
MarkNativeAsOptional("CS_UpdateClientModel");
MarkNativeAsOptional("CS_ItemDefIndexToID");
MarkNativeAsOptional("CS_WeaponIDToItemDefIndex");
MarkNativeAsOptional("CS_WeaponIDToLoadoutSlot");
}
#endif

View File

@@ -0,0 +1,255 @@
/**
* vim: set ts=4 sw=4 tw=99 noet :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _datapack_included
#endinput
#endif
#define _datapack_included
/**
* Opaque handle to a datapack position.
*/
enum DataPackPos: {};
// A DataPack allows serializing multiple variables into a single stream.
methodmap DataPack < Handle
{
// Creates a new data pack.
public native DataPack();
// Packs a normal cell into a data pack.
//
// @param cell Cell to add.
// @param insert Determines whether mid-pack writes will insert instead of overwrite.
public native void WriteCell(any cell, bool insert = false);
// Packs a float into a data pack.
//
// @param val Float to add.
// @param insert Determines whether mid-pack writes will insert instead of overwrite.
public native void WriteFloat(float val, bool insert = false);
// Packs a string into a data pack.
//
// @param str String to add.
// @param insert Determines whether mid-pack writes will insert instead of overwrite.
public native void WriteString(const char[] str, bool insert = false);
// Packs a function pointer into a data pack.
//
// @param fktptr Function pointer to add.
// @param insert Determines whether mid-pack writes will insert instead of overwrite.
public native void WriteFunction(Function fktptr, bool insert = false);
// Packs an array of cells into a data pack.
//
// @param array Array to add.
// @param count Number of elements
// @param insert Determines whether mid-pack writes will insert instead of overwrite.
public native void WriteCellArray(const any[] array, int count, bool insert = false);
// Packs an array of floats into a data pack.
//
// @param array Array to add.
// @param count Number of elements
// @param insert Determines whether mid-pack writes will insert instead of overwrite.
public native void WriteFloatArray(const float[] array, int count, bool insert = false);
// Reads a cell from a data pack.
//
// @return A cell at this position
public native any ReadCell();
// Reads a float from a data pack.
//
// @return Float at this position
public native float ReadFloat();
// Reads a string from a data pack.
//
// @param buffer Destination string buffer.
// @param maxlen Maximum length of output string buffer.
public native void ReadString(char[] buffer, int maxlen);
// Reads a function pointer from a data pack.
//
// @return Function pointer.
public native Function ReadFunction();
// Reads an array of cells a data pack.
//
// @param buffer Destination buffer.
// @param count Maximum length of output buffer.
public native void ReadCellArray(any[] buffer, int count);
// Reads an array of floats from a data pack.
//
// @param buffer Destination buffer.
// @param count Maximum length of output buffer.
public native void ReadFloatArray(float[] buffer, int count);
// Resets the position in a data pack.
//
// @param clear If true, clears the contained data.
public native void Reset(bool clear=false);
// Returns whether or not a specified number of bytes from the data pack
// position to the end can be read.
//
// @param unused Unused variable. Exists for backwards compatability.
public native bool IsReadable(int unused = 0);
// The read or write position in a data pack.
property DataPackPos Position {
public native get();
public native set(DataPackPos pos);
}
};
/**
* Creates a new data pack.
*
* @return A Handle to the data pack. Must be closed with CloseHandle().
*/
native DataPack CreateDataPack();
/**
* Packs a normal cell into a data pack.
*
* @param pack Handle to the data pack.
* @param cell Cell to add.
* @error Invalid handle.
*/
native void WritePackCell(Handle pack, any cell);
/**
* Packs a float into a data pack.
*
* @param pack Handle to the data pack.
* @param val Float to add.
* @error Invalid handle.
*/
native void WritePackFloat(Handle pack, float val);
/**
* Packs a string into a data pack.
*
* @param pack Handle to the data pack.
* @param str String to add.
* @error Invalid handle.
*/
native void WritePackString(Handle pack, const char[] str);
/**
* Packs a function pointer into a data pack.
*
* @param pack Handle to the data pack.
* @param fktptr Function pointer to add.
* @error Invalid handle.
*/
native void WritePackFunction(Handle pack, Function fktptr);
/**
* Reads a cell from a data pack.
*
* @param pack Handle to the data pack.
* @return Cell value.
* @error Invalid handle, or bounds error.
*/
native any ReadPackCell(Handle pack);
/**
* Reads a float from a data pack.
*
* @param pack Handle to the data pack.
* @return Float value.
* @error Invalid handle, or bounds error.
*/
native float ReadPackFloat(Handle pack);
/**
* Reads a string from a data pack.
*
* @param pack Handle to the data pack.
* @param buffer Destination string buffer.
* @param maxlen Maximum length of output string buffer.
* @error Invalid handle, or bounds error.
*/
native void ReadPackString(Handle pack, char[] buffer, int maxlen);
/**
* Reads a function pointer from a data pack.
*
* @param pack Handle to the data pack.
* @return Function pointer.
* @error Invalid handle, or bounds error.
*/
native Function ReadPackFunction(Handle pack);
/**
* Resets the position in a data pack.
*
* @param pack Handle to the data pack.
* @param clear If true, clears the contained data.
* @error Invalid handle.
*/
native void ResetPack(Handle pack, bool clear=false);
/**
* Returns the read or write position in a data pack.
*
* @param pack Handle to the data pack.
* @return Position in the data pack, only usable with calls to SetPackPosition.
* @error Invalid handle.
*/
native DataPackPos GetPackPosition(Handle pack);
/**
* Sets the read/write position in a data pack.
*
* @param pack Handle to the data pack.
* @param position New position to set. Must have been previously retrieved from a call to GetPackPosition.
* @error Invalid handle, or position is beyond the pack bounds.
*/
native void SetPackPosition(Handle pack, DataPackPos position);
/**
* Returns whether or not a specified number of bytes from the data pack
* position to the end can be read.
*
* @param pack Handle to the data pack.
* @param bytes Number of bytes to simulate reading.
* @return True if can be read, false otherwise.
* @error Invalid handle.
*/
native bool IsPackReadable(Handle pack, int bytes);

1077
scripting/include/dbi.inc Normal file

File diff suppressed because it is too large Load Diff

1100
scripting/include/dhooks.inc Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,141 @@
#if defined _discord_included
#endinput
#endif
#define _discord_included
#include <smjansson>
#include <discord/stocks>
typedef DiscordGuildsRetrieve = function void (DiscordBot bot, char[] id, char[] name, char[] icon, bool owner, int permissions, any data);
typedef DiscordGuildsRetrievedAll = function void (DiscordBot bot, ArrayList id, ArrayList name, ArrayList icon, ArrayList owner, ArrayList permissions, any data);
//Channel are Handles that are closed immediately after forwards called. To keep, clone. Or store id if thats what you want
typedef DiscordGuildChannelsRetrieve = function void (DiscordBot bot, char[] guild, DiscordChannel Channel, any data);
typedef DiscordGuildChannelsRetrieveAll = function void (DiscordBot bot, char[] guild, ArrayList Channels, any data);
typedef DiscordGuildGetRoles = function void (DiscordBot bot, char[] guild, RoleList Roles, any data);
/**
* Called when message is received
* bot/channel/message are all destroyed after callback is sent.
* You can clone it if need to keep.
*/
typeset OnChannelMessage {
function void(DiscordBot bot, DiscordChannel channel, DiscordMessage message);
};
typedef OnGetReactions = function void (DiscordBot bot, ArrayList Users, char[] channelID, const char[] messageID, const char[] emoji, any data);
typedef OnMessageSent = function void(DiscordBot bot, char[] channel, DiscordMessage message, any data);
typedef OnMessageDeleted = function void(DiscordBot bot, any data);
//hMemberList is JSON array containing guild members
typedef OnGetMembers = function void(DiscordBot bot, char[] guild, Handle hMemberList);
methodmap Role < Handle {
public void GetID(char[] buffer, int maxlength) {
JsonObjectGetString(this, "id", buffer, maxlength);
}
public void GetName(char[] buffer, int maxlength) {
JsonObjectGetString(this, "name", buffer, maxlength);
}
public int GetColor() {
return JsonObjectGetInt(this, "color");
}
public int GetPosition() {
return JsonObjectGetInt(this, "position");
}
public int GetPermissions() {
return JsonObjectGetInt(this, "permissions");
}
public bool Hoist() {
return JsonObjectGetBool(this, "hoist");
}
public bool Managed() {
return JsonObjectGetBool(this, "managed");
}
public bool Mentionable() {
return JsonObjectGetBool(this, "mentionable");
}
}
methodmap RoleList < Handle {
property int Size {
public get() {
return json_array_size(this);
}
}
public Role GetRole(int i) {
return view_as<Role>(
json_array_get(this, i)
);
}
public Role Get(int i) {
return this.GetRole(i);
}
}
/*
{
"id": "80351110224678912",
"username": "Nelly",
"discriminator": "1337",
"avatar": "8342729096ea3675442027381ff50dfe",
"verified": true,
"email": "nelly@discordapp.com"
}
*/
//It's a JSON Handle with the above info TODO stop using natives!
methodmap DiscordUser < Handle {
public native void GetID(char[] buffer, int maxlength);
public native void GetUsername(char[] buffer, int maxlength);
public native void GetDiscriminator(char[] buffer, int maxlength);
public int GetDiscriminatorInt() {
char buffer[16];
this.GetDiscriminator(buffer, sizeof(buffer));
return StringToInt(buffer);
}
public native void GetAvatar(char[] buffer, int maxlength);
public native bool IsVerified();
public native void GetEmail(char[] buffer, int maxlength);
public native bool IsBot();
}
/*
{"timestamp": "2017-01-15T20:26:35.353000+00:00", "mention_everyone": false, "id": "270287641155469313", "pinned": false, "edited_timestamp": null, "author": {"username": "DK-Bot", "discriminator": "6274", "bot": true, "id": "186256454863290369", "avatar": null}, "mention_roles": [], "content": "ab", "channel_id": "229677130483499008", "mentions": [], "type": 0}
*/
methodmap DiscordMessage < Handle {
public native void GetID(char[] buffer, int maxlength);
public native bool IsPinned();
public native DiscordUser GetAuthor();
public native void GetContent(char[] buffer, int maxlength);
public native void GetChannelID(char[] buffer, int maxlength);
}
#include <discord/channel>
#include <discord/message_embed>
#include <discord/webhook>
#include <discord/bot>
#include <discord/GuildMember>

View File

@@ -0,0 +1,29 @@
methodmap DiscordGuildUser < Handle {
//Returns User Object
public DiscordUser GetUser() {
return view_as<DiscordUser>(json_object_get(this, "user"));
}
//Returns player's nick
public void GetNickname(char[] buffer, int maxlength) {
JsonObjectGetString(this, "nick", buffer, maxlength);
}
//Returns JSON array list of roles. You can manually loop through them for now.
public Handle GetRoles() {
return json_object_get(this, "roles");
}
//Returns the date the user joined the guild in format: "2015-04-26T06:26:56.936000+00:00"
public void GetJoinedAt(char[] buffer, int maxlength) {
JsonObjectGetString(this, "joined_at", buffer, maxlength);
}
public bool IsDeaf() {
return JsonObjectGetBool(this, "deaf");
}
public bool IsMute() {
return JsonObjectGetBool(this, "mute");
}
}

View File

@@ -0,0 +1,231 @@
methodmap DiscordBot < StringMap {
public DiscordBot(const char[] token) {
Handle json = json_object();
json_object_set_new(json, "token", json_string(token));
return view_as<DiscordBot>(json);
}
public void StopListening() {
json_object_del(this, "listeningChannels");
}
property float MessageCheckInterval {
public get() {
return JsonObjectGetFloat(this, "messageInterval", 3.0);
}
public set(float value) {
json_object_set_new(this, "messageInterval", json_real(value));
}
}
public native void StartTimer(DiscordChannel Channel, OnChannelMessage fCallback);
/**
* Retrieves a list of Channels the bot is listening to for messages
*/
public Handle GetListeningChannels() {
return json_object_get(this, "listeningChannels");
}
/**
* Checks if the bot is listening to channel for messages
* @param DiscordChannel Channel
*/
public bool IsListeningToChannel(DiscordChannel Channel) {
char id[32];
Channel.GetID(id, sizeof(id));
Handle hChannels = this.GetListeningChannels();
if(hChannels == null) return false;
for(int i = 0; i < json_array_size(hChannels); i++) {
DiscordChannel tempChannel = view_as<DiscordChannel>(json_array_get(hChannels, i));
static char tempID[32];
tempChannel.GetID(tempID, sizeof(tempID));
if(StrEqual(id, tempID, false)) {
delete tempChannel;
delete hChannels;
return true;
}
delete tempChannel;
}
delete hChannels;
return false;
}
/**
* Checks if the bot is listening to channel for messages
* @param DiscordChannel Channel
*/
public bool IsListeningToChannelID(char[] id) {
Handle hChannels = this.GetListeningChannels();
if(hChannels == null) return false;
for(int i = 0; i < json_array_size(hChannels); i++) {
DiscordChannel tempChannel = view_as<DiscordChannel>(json_array_get(hChannels, i));
static char tempID[32];
tempChannel.GetID(tempID, sizeof(tempID));
if(StrEqual(id, tempID, false)) {
delete tempChannel;
delete hChannels;
return true;
}
delete tempChannel;
}
delete hChannels;
return false;
}
/**
* Stops the bot from listening to that channel for messages
* @param DiscordChannel Channel
*/
public void StopListeningToChannel(DiscordChannel Channel) {
char id[32];
Channel.GetID(id, sizeof(id));
Handle channels = this.GetListeningChannels();
if(channels == null) return;
for(int i = 0; i < json_array_size(channels); i++) {
DiscordChannel tempChannel = view_as<DiscordChannel>(json_array_get(channels, i));
static char tempID[32];
tempChannel.GetID(tempID, sizeof(tempID));
if(StrEqual(id, tempID, false)) {
json_array_remove(channels, i);
i--;
delete tempChannel;
}
}
delete channels;
}
/**
* Stops the bot from listening to that channel id for messages
* @param DiscordChannel Channel
*/
public void StopListeningToChannelID(char[] id) {
Handle channels = this.GetListeningChannels();
if(channels == null) return;
for(int i = 0; i < json_array_size(channels); i++) {
DiscordChannel tempChannel = view_as<DiscordChannel>(json_array_get(channels, i));
static char tempID[32];
tempChannel.GetID(tempID, sizeof(tempID));
if(StrEqual(id, tempID, false)) {
json_array_remove(channels, i);
i--;
delete tempChannel;
}
}
delete channels;
}
public DiscordChannel GetListeningChannelByID(char[] id) {
Handle channels = this.GetListeningChannels();
if(channels == null) return null;
for(int i = 0; i < json_array_size(channels); i++) {
DiscordChannel tempChannel = view_as<DiscordChannel>(json_array_get(channels, i));
static char tempID[32];
tempChannel.GetID(tempID, sizeof(tempID));
if(StrEqual(id, tempID, false)) {
delete channels;
return tempChannel;
}
}
delete channels;
return null;
}
/**
* Start listening to the channel for messages.
* The Channel handle is duplicated. Feel free to close yours.
* @param DiscordChannel Channel
*/
public void StartListeningToChannel(DiscordChannel Channel, OnChannelMessage fCallback) {
if(this.IsListeningToChannel(Channel)) return;
Handle channels = this.GetListeningChannels();
if(channels == null) {
channels = json_array();
json_object_set(this, "listeningChannels", channels);
}
json_array_append(channels, Channel);
//Handle fForward = CreateForward(ET_Ignore, Param_Cell, Param_Cell, Param_String, Param_String, Param_String, Param_String, Param_String, Param_Cell);
//AddToForward(fForward, GetMyHandle(), callback);
this.StartTimer(Channel, fCallback);
}
public native void AddReactionID(char[] channel, char[] messageid, char[] emoji);
public void AddReaction(DiscordChannel channel, char[] messageid, char[] emoji) {
char channelid[64];
channel.GetID(channelid, sizeof(channelid));
this.AddReactionID(channelid, messageid, emoji);
}
public native void DeleteReactionID(char[] channel, char[] messageid, char[] emoji, char[] user);
public void DeleteReaction(DiscordChannel channel, char[] messageid, char[] emoji, char[] user) {
char chid[64];
channel.GetID(chid, sizeof(chid));
this.DeleteReactionID(chid, messageid, emoji, user);
}
public void DeleteReactionSelf(DiscordChannel channel, char[] messageid, char[] emoji) {
this.DeleteReaction(channel, messageid, emoji, "@me");
}
public void DeleteReactionAll(DiscordChannel channel, char[] messageid, char[] emoji) {
this.DeleteReaction(channel, messageid, emoji, "@all");
}
public void DeleteReactionSelfID(char[] channel, char[] messageid, char[] emoji) {
this.DeleteReactionID(channel, messageid, emoji, "@me");
}
public void DeleteReactionAllID(char[] channel, char[] messageid, char[] emoji) {
this.DeleteReactionID(channel, messageid, emoji, "@all");
}
public native void GetReactionID(char[] channel, char[] messageid, char[] emoji, OnGetReactions fCallback=INVALID_FUNCTION, any data=0);
public void GetReaction(DiscordChannel channel, char[] messageid, char[] emoji, OnGetReactions fCallback=INVALID_FUNCTION, any data=0) {
char id[64];
channel.GetID(id, sizeof(id));
this.GetReactionID(id, messageid, emoji, fCallback, data);
}
public native void GetToken(char[] token, int maxlength);
public native void SendMessage(DiscordChannel channel, char[] message, OnMessageSent fCallback=INVALID_FUNCTION, any data=0);
public native void SendMessageToChannelID(char[] channel, char[] message, OnMessageSent fCallback=INVALID_FUNCTION, any data=0);
public native void DeleteMessageID(char[] channel, char[] message, OnMessageDeleted fCallback=INVALID_FUNCTION, any data=0);
public native void DeleteMessage(DiscordChannel channel, DiscordMessage message, OnMessageDeleted fCallback=INVALID_FUNCTION, any data=0);
public native void GetGuilds(DiscordGuildsRetrieve fCallback = INVALID_FUNCTION, DiscordGuildsRetrievedAll fCallbackAll = INVALID_FUNCTION, any data=0);
public native void GetGuildChannels(char[] guild, DiscordGuildChannelsRetrieve fCallback = INVALID_FUNCTION, DiscordGuildChannelsRetrieveAll fCallbackAll = INVALID_FUNCTION, any data=0);
/**
* ATM takes guild id, hopefully later on i will implement guild objects.
* Limit is from 1-1000
*/
public native void GetGuildMembers(char[] guild, OnGetMembers fCallback, int limit=250, char[] afterUserID="");
/**
* Same as above but displays ALL members, paginating automatically.
* perPage is how many it should display per callback. 1-1000
*/
public native void GetGuildMembersAll(char[] guild, OnGetMembers fCallback, int perPage=250, char[] afterUserID="");
public native void GetGuildRoles(char[] guild, DiscordGuildGetRoles fCallback, any data);
}

View File

@@ -0,0 +1,69 @@
methodmap DiscordChannel < StringMap {
public DiscordChannel() {
Handle hObj = json_object();
return view_as<DiscordChannel>(hObj);
}
public native void SendMessage(DiscordBot Bot, char[] message, OnMessageSent fCallback=INVALID_FUNCTION, any data=0);
public void GetGuildID(char[] buffer, int maxlength) {
JsonObjectGetString(this, "guild_id", buffer, maxlength);
}
public void GetID(char[] buffer, int maxlength) {
JsonObjectGetString(this, "id", buffer, maxlength);
}
public void GetName(char[] buffer, int maxlength) {
JsonObjectGetString(this, "name", buffer, maxlength);
}
public void GetType(char[] buffer, int maxlength) {
JsonObjectGetString(this, "type", buffer, maxlength);
}
property int Position {
public get() {
return JsonObjectGetInt(this, "position");
}
}
property bool IsPrivate {
public get() {
return JsonObjectGetBool(this, "is_private");
}
}
public void GetTopic(char[] buffer, int maxlength) {
JsonObjectGetString(this, "topic", buffer, maxlength);
}
public void GetLastMessageID(char[] buffer, int maxlength) {
JsonObjectGetString(this, "last_message_id", buffer, maxlength);
}
public void SetLastMessageID(char[] id) {
json_object_set_new(this, "last_message_id", json_string(id));
}
property int Bitrate {
public get() {
return JsonObjectGetInt(this, "bitrate");
}
}
property int UserLimit {
public get() {
return JsonObjectGetInt(this, "user_limit");
}
}
property bool IsText {
public get() {
char type[8];
this.GetType(type, sizeof(type));
if(StrEqual(type, "text", false)) return true;
return false;
}
}
}

View File

@@ -0,0 +1,128 @@
methodmap MessageEmbed < Handle {
public MessageEmbed() {
Handle hObj = json_object();
return view_as<MessageEmbed>(hObj);
}
public bool GetColor(char[] buffer, int maxlength) {
return JsonObjectGetString(this, "color", buffer, maxlength);
}
public void SetColor(char[] color) {
json_object_set_new(this, "color", json_string(color));
}
public bool GetTitle(char[] buffer, int maxlength) {
return JsonObjectGetString(this, "title", buffer, maxlength);
}
public void SetTitle(char[] title) {
json_object_set_new(this, "title", json_string(title));
}
public bool GetTitleLink(char[] buffer, int maxlength) {
return JsonObjectGetString(this, "title_link", buffer, maxlength);
}
public void SetImageLink(char[] title_link) {
json_object_set_new(this, "title_link", json_string(title_link));
}
public bool GetImage(char[] buffer, int maxlength) {
return JsonObjectGetString(this, "image_url", buffer, maxlength);
}
public void SetImage(char[] image_url) {
json_object_set_new(this, "image_url", json_string(image_url));
}
public bool GetAuthor(char[] buffer, int maxlength) {
return JsonObjectGetString(this, "author_name", buffer, maxlength);
}
public void SetAuthor(char[] author_name) {
json_object_set_new(this, "author_name", json_string(author_name));
}
public bool GetAuthorLink(char[] buffer, int maxlength) {
return JsonObjectGetString(this, "author_link", buffer, maxlength);
}
public void SetAuthorLink(char[] author_link) {
json_object_set_new(this, "author_link", json_string(author_link));
}
public bool GetAuthorIcon(char[] buffer, int maxlength) {
return JsonObjectGetString(this, "author_icon", buffer, maxlength);
}
public void SetAuthorIcon(char[] author_icon) {
json_object_set_new(this, "author_icon", json_string(author_icon));
}
public bool GetThumb(char[] buffer, int maxlength) {
return JsonObjectGetString(this, "thumb_url", buffer, maxlength);
}
public void SetThumb(char[] thumb_url) {
json_object_set_new(this, "thumb_url", json_string(thumb_url));
}
public bool GetFooter(char[] buffer, int maxlength) {
return JsonObjectGetString(this, "footer", buffer, maxlength);
}
public void SetFooter(char[] footer) {
json_object_set_new(this, "footer", json_string(footer));
}
public bool GetFooterIcon(char[] buffer, int maxlength) {
return JsonObjectGetString(this, "footer_icon", buffer, maxlength);
}
public void SetFooterIcon(char[] footer_icon) {
json_object_set_new(this, "footer_icon", json_string(footer_icon));
}
/**
* Note: Setting Fields will delete the handle!
*/
property Handle Fields {
public get() {
return json_object_get(this, "fields");
}
public set(Handle value) {
json_object_set_new(this, "fields", value);
}
}
public void AddField(char[] name, char[] value, bool inline) {
Handle hObj = json_object();
json_object_set_new(hObj, "name", json_string(name));
json_object_set_new(hObj, "value", json_string(value));
json_object_set_new(hObj, "inline", json_boolean(inline));
Handle hArray = this.Fields;
if(this.Fields == null) {
hArray = json_array();
}
json_array_append_new(hArray, hObj);
this.Fields = hArray;
}
//Below don't support Slack Mode
public bool GetDescription(char[] buffer, int maxlength) {
return JsonObjectGetString(this, "description", buffer, maxlength);
}
public void SetDescription(char[] description) {
json_object_set_new(this, "description", json_string(description));
}
public bool GetURL(char[] buffer, int maxlength) {
return JsonObjectGetString(this, "url", buffer, maxlength);
}
public void SetURL(char[] url) {
json_object_set_new(this, "url", json_string(url));
}
}

View File

@@ -0,0 +1,82 @@
stock int JsonObjectGetInt(Handle hElement, char[] key) {
Handle hObject = json_object_get(hElement, key);
if(hObject == INVALID_HANDLE) return 0;
int value;
if(json_is_integer(hObject)) {
value = json_integer_value(hObject);
}else if(json_is_string(hObject)) {
char buffer[12];
json_string_value(hObject, buffer, sizeof(buffer));
value = StringToInt(buffer);
}
CloseHandle(hObject);
return value;
}
stock bool JsonObjectGetString(Handle hElement, char[] key, char[] buffer, maxlength) {
Handle hObject = json_object_get(hElement, key);
if(hObject == INVALID_HANDLE) return false;
if(json_is_integer(hObject)) {
IntToString(json_integer_value(hObject), buffer, maxlength);
}else if(json_is_string(hObject)) {
json_string_value(hObject, buffer, maxlength);
}else if(json_is_real(hObject)) {
FloatToString(json_real_value(hObject), buffer, maxlength);
}else if(json_is_true(hObject)) {
FormatEx(buffer, maxlength, "true");
}else if(json_is_false(hObject)) {
FormatEx(buffer, maxlength, "false");
}
CloseHandle(hObject);
return true;
}
stock bool JsonObjectGetBool(Handle hElement, char[] key, bool defaultvalue=false) {
Handle hObject = json_object_get(hElement, key);
if(hObject == INVALID_HANDLE) return defaultvalue;
bool ObjectBool = defaultvalue;
if(json_is_integer(hObject)) {
ObjectBool = view_as<bool>(json_integer_value(hObject));
}else if(json_is_string(hObject)) {
char buffer[11];
json_string_value(hObject, buffer, sizeof(buffer));
if(StrEqual(buffer, "true", false)) {
ObjectBool = true;
}else if(StrEqual(buffer, "false", false)) {
ObjectBool = false;
}else {
int x = StringToInt(buffer);
ObjectBool = view_as<bool>(x);
}
}else if(json_is_real(hObject)) {
ObjectBool = view_as<bool>(RoundToFloor(json_real_value(hObject)));
}else if(json_is_true(hObject)) {
ObjectBool = true;
}else if(json_is_false(hObject)) {
ObjectBool = false;
}
CloseHandle(hObject);
return ObjectBool;
}
stock float JsonObjectGetFloat(Handle hJson, char[] key, float defaultValue=0.0) {
Handle hObject = json_object_get(hJson, key);
if(hObject == INVALID_HANDLE) return defaultValue;
float value = defaultValue;
if(json_is_integer(hObject)) {
value = float(json_integer_value(hObject));
}else if(json_is_real(hObject)) {
value = json_real_value(hObject);
}else if(json_is_string(hObject)) {
char buffer[12];
json_string_value(hObject, buffer, sizeof(buffer));
value = StringToFloat(buffer);
}
CloseHandle(hObject);
return value;
}

View File

@@ -0,0 +1,142 @@
methodmap DiscordWebHook < Handle {
public DiscordWebHook(char[] url) {
Handle mp = json_object();
json_object_set_new(mp, "__url", json_string(url));
Handle data = json_object();
json_object_set_new(mp, "__data", data);
return view_as<DiscordWebHook>(mp);
}
public void GetUrl(char[] buffer, int maxlength) {
JsonObjectGetString(this, "__url", buffer, maxlength);
}
/**
* Gets/Sets if the hook should be sent as Slack.
* Note: color is different for slack than discord msg.
*
* @return True if Slack, otherwise false.
*/
property bool SlackMode {
public get() {
return JsonObjectGetBool(this, "__slack", false);
}
public set(bool value) {
json_object_set_new(this, "__slack", (value) ? json_true() : json_false());
}
}
property Handle Data {
public get() {
return json_object_get(this, "__data");
}
public set(Handle value) {
json_object_set_new(this, "__data", value);
}
}
public void UpdateDataObject(char[] key, Handle hObject) {
Handle data = this.Data;
json_object_set_new(data, key, hObject);
delete data;
}
public bool GetDataBool(char[] key, bool defaultValue=false) {
Handle data = this.Data;
bool value = JsonObjectGetBool(data, key, defaultValue);
delete data;
return value;
}
public bool GetDataString(char[] key, char[] buffer, int maxlength) {
Handle data = this.Data;
bool success = JsonObjectGetString(data, key, buffer, maxlength);
delete data;
return success;
}
/**
* Note: Deletes the MessageEmbed Object!
*/
public void Embed(MessageEmbed Object) {
//this.UpdateDataObject("embeds", Object);
Handle data = this.Data;
Handle hArray = json_object_get(data, "embeds");
if(hArray == null) {
hArray = json_array();
json_object_set(data, "embeds", hArray);
}
json_array_append_new(hArray, Object);
delete hArray;
delete data;
}
property bool tts {
public get() {
return this.GetDataBool("tts", false);
}
public set(bool value) {
this.UpdateDataObject("tts", json_boolean(value));
}
}
public bool GetUsername(char[] buffer, int maxlength) {
return this.GetDataString("username", buffer, maxlength);
}
public void SetUsername(char[] name) {
this.UpdateDataObject("username", json_string(name));
}
public bool GetAvatar(char[] buffer, int maxlength) {
return this.GetDataString("icon_url", buffer, maxlength);
}
public void SetAvatar(char[] icon_url) {
this.UpdateDataObject("icon_url", json_string(icon_url));
}
public bool GetContent(char[] buffer, int maxlength) {
return this.GetDataString("content", buffer, maxlength);
}
public void SetContent(char[] content) {
this.UpdateDataObject("content", json_string(content));
}
/*property Handle OnComplete {
public get() {
Handle fForward = null;
if(!GetTrieValue(this, "callback", fForward)) {
return null;
}
return fForward;
}
public set(Handle value) {
SetTrieValue(this, "callback", value);
SetTrieValue(this, "plugin", GetMyHandle());
}
}
property Handle CallbackPlugin {
public get() {
Handle value = null;
if(!GetTrieValue(this, "plugin", value)) {
return null;
}
return value;
}
}*/
public native void Send();
}

View File

@@ -0,0 +1,785 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2011 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _entity_included
#endinput
#endif
#define _entity_included
/**
* Property types for entities.
*/
enum PropType
{
Prop_Send = 0, /**< This property is networked. */
Prop_Data = 1 /**< This property is for save game data fields. */
};
/**
* @section For more information on these, see the HL2SDK (public/edict.h)
*/
#define FL_EDICT_CHANGED (1<<0) /**< Game DLL sets this when the entity state changes
Mutually exclusive with FL_EDICT_PARTIAL_CHANGE. */
#define FL_EDICT_FREE (1<<1) /**< this edict if free for reuse */
#define FL_EDICT_FULL (1<<2) /**< this is a full server entity */
#define FL_EDICT_FULLCHECK (0<<0) /**< call ShouldTransmit() each time, this is a fake flag */
#define FL_EDICT_ALWAYS (1<<3) /**< always transmit this entity */
#define FL_EDICT_DONTSEND (1<<4) /**< don't transmit this entity */
#define FL_EDICT_PVSCHECK (1<<5) /**< always transmit entity, but cull against PVS */
#define FL_EDICT_PENDING_DORMANT_CHECK (1<<6)
#define FL_EDICT_DIRTY_PVS_INFORMATION (1<<7)
#define FL_FULL_EDICT_CHANGED (1<<8)
enum PropFieldType
{
PropField_Unsupported, /**< The type is unsupported. */
PropField_Integer, /**< Valid for SendProp and Data fields */
PropField_Float, /**< Valid for SendProp and Data fields */
PropField_Entity, /**< Valid for Data fields only (SendProp shows as int) */
PropField_Vector, /**< Valid for SendProp and Data fields */
PropField_String, /**< Valid for SendProp and Data fields */
PropField_String_T, /**< Valid for Data fields. Read only.
Note that the size of a string_t is dynamic, and
thus FindDataMapOffs() will return the constant size
of the string_t container (which is 32 bits right now). */
PropField_Variant /**< Valid for Data fields only Type is not known at the field level,
(for this call), but dependent on current field value. */
};
/**
* @endsection
*/
/**
* Returns the maximum number of networked entities.
*
* Note: For legacy reasons, this only returns the maximum
* networked entities (maximum edicts), rather than total
* maximum entities.
*
* @return Maximum number of networked entities.
*/
native int GetMaxEntities();
/**
* Returns the number of networked entities in the server.
*
* Note: For legacy reasons, this only returns the current count
* of networked entities (current edicts), rather than total
* count of current entities.
*
* @return Number of entities in the server.
*/
native int GetEntityCount();
/**
* Returns whether or not an entity is valid. Returns false
* if there is no matching CBaseEntity for this entity index.
*
* @param entity Index of the entity.
* @return True if valid, false otherwise.
*/
native bool IsValidEntity(int entity);
/**
* Returns whether or not an edict index is valid.
*
* @param edict Index of the edict.
* @return True if valid, false otherwise.
*/
native bool IsValidEdict(int edict);
/**
* Returns whether or not an entity has a valid networkable edict.
*
* @param entity Index of the entity.
* @return True if networkable, false if invalid or not networkable.
*/
native bool IsEntNetworkable(int entity);
/**
* Creates a new edict (the basis of a networkable entity)
*
* @return Index of the edict, 0 on failure.
*/
native int CreateEdict();
/**
* Removes an edict from the world.
*
* @param edict Index of the edict.
* @error Invalid edict index.
*/
native void RemoveEdict(int edict);
/**
* Marks an entity for deletion.
*
* @param entity Index of the entity.
* @error Invalid entity index.
*/
native void RemoveEntity(int entity);
/**
* Returns the flags on an edict. These are not the same as entity flags.
*
* @param edict Index of the entity.
* @return Edict flags.
* @error Invalid edict index.
*/
native int GetEdictFlags(int edict);
/**
* Sets the flags on an edict. These are not the same as entity flags.
*
* @param edict Index of the entity.
* @param flags Flags to set.
* @error Invalid edict index.
*/
native void SetEdictFlags(int edict, int flags);
/**
* Retrieves an edict classname.
*
* @param edict Index of the entity.
* @param clsname Buffer to store the classname.
* @param maxlength Maximum length of the buffer.
* @return True on success, false if there is no classname set.
*/
native bool GetEdictClassname(int edict, char[] clsname, int maxlength);
/**
* Retrieves an entity's networkable serverclass name.
* This is not the same as the classname and is used for networkable state changes.
*
* @param edict Index of the entity.
* @param clsname Buffer to store the serverclass name.
* @param maxlength Maximum length of the buffer.
* @return True on success, false if the edict is not networkable.
* @error Invalid edict index.
*/
native bool GetEntityNetClass(int edict, char[] clsname, int maxlength);
/**
* @section Entity offset functions
*
* Offsets should be specified in byte distance from the CBaseEntity
* structure, not short (double byte) or integer (four byte) multiples.
* It is somewhat common practice to use offsets aligned to their final
* type, and thus make sure you are not falling to this error in SourceMod.
* For example, if your "integer-aligned" offset was 119, your byte-aligned
* offset is 119*4, or 476.
* Specifying incorrect offsets or the incorrect data type for an offset
* can have fatal consequences. If you are hardcoding offsets, and the
* layout of CBaseEntity does not match, you can easily crash the server.
*
* The reasonable bounds for offsets is greater than or equal to 0 and
* below 32768. Offsets out of these bounds will throw an error. However,
* this does not represent any real range, it is simply a sanity check for
* illegal values. Any range outside of the CBaseEntity structure's private
* size will cause undefined behavior or even crash.
*/
/**
* Marks an entity as state changed. This can be useful if you set an offset
* and wish for it to be immediately changed over the network. By default this
* is not done for offset setting functions.
*
* @param edict Index to the edict.
* @param offset Offset to mark as changed. If 0,
* the entire edict is marked as changed.
* @error Invalid entity or offset out of bounds.
*/
native void ChangeEdictState(int edict, int offset = 0);
/**
* Peeks into an entity's object data and retrieves the integer value at
* the given offset.
*
* @param entity Edict index.
* @param offset Offset to use.
* @param size Number of bytes to read (valid values are 1, 2, or 4).
* @return Value at the given memory location.
* @error Invalid entity or offset out of reasonable bounds.
*/
native int GetEntData(int entity, int offset, int size=4);
/**
* Peeks into an entity's object data and sets the integer value at
* the given offset.
*
* @param entity Edict index.
* @param offset Offset to use.
* @param value Value to set.
* @param size Number of bytes to write (valid values are 1, 2, or 4).
* @param changeState If true, change will be sent over the network.
* @error Invalid entity or offset out of reasonable bounds.
*/
native void SetEntData(int entity, int offset, any value, int size=4, bool changeState=false);
/**
* Peeks into an entity's object data and retrieves the float value at
* the given offset.
*
* @param entity Edict index.
* @param offset Offset to use.
* @return Value at the given memory location.
* @error Invalid entity or offset out of reasonable bounds.
*/
native float GetEntDataFloat(int entity, int offset);
/**
* Peeks into an entity's object data and sets the float value at
* the given offset.
*
* @param entity Edict index.
* @param offset Offset to use.
* @param value Value to set.
* @param changeState If true, change will be sent over the network.
* @error Invalid entity or offset out of reasonable bounds.
*/
native void SetEntDataFloat(int entity, int offset, float value, bool changeState=false);
/**
* This function is deprecated. Use GetEntDataEnt2 instead, for
* reasons explained in the notes.
*
* Note: This function returns 0 on failure, which may be misleading,
* as the number 0 is also used for the world entity index.
*
* Note: This function makes no attempt to validate the returned
* entity, and in fact, it could be garbage or completely unexpected.
*
* @param entity Edict index.
* @param offset Offset to use.
* @return Entity index at the given location, or 0 if none.
* @error Invalid entity or offset out of reasonable bounds.
* @deprecated Use GetEntDataEnt2() instead.
*/
#pragma deprecated Use GetEntDataEnt2() instead.
native int GetEntDataEnt(int entity, int offset);
/**
* This function is deprecated. Use SetEntDataEnt2 instead, for
* reasons explained in the notes.
*
* Note: This function uses 0 as an indicator to unset data, but
* 0 is also the world entity index. Thus, a property cannot
* be set to the world entity using this native.
*
* @param entity Edict index.
* @param offset Offset to use.
* @param other Entity index to set, or 0 to clear.
* @param changeState If true, change will be sent over the network.
* @error Invalid entity or offset out of reasonable bounds.
* @deprecated Use SetEntDataEnt2() instead.
*/
#pragma deprecated Use SetEntDataEnt2() instead.
native void SetEntDataEnt(int entity, int offset, int other, bool changeState=false);
/**
* Peeks into an entity's object data and retrieves the entity index
* at the given offset.
*
* Note: This will only work on offsets that are stored as "entity
* handles" (which usually looks like m_h* in properties). These
* are not SourceMod Handles, but internal Source structures.
*
* @param entity Edict index.
* @param offset Offset to use.
* @return Entity index at the given location. If there is no entity,
* or the stored entity is invalid, then -1 is returned.
* @error Invalid input entity, or offset out of reasonable bounds.
*/
native int GetEntDataEnt2(int entity, int offset);
/**
* Peeks into an entity's object data and sets the entity index at the
* given offset.
*
* Note: This will only work on offsets that are stored as "entity
* handles" (which usually looks like m_h* in properties). These
* are not SourceMod Handles, but internal Source structures.
*
* @param entity Edict index.
* @param offset Offset to use.
* @param other Entity index to set, or -1 to clear.
* @param changeState If true, change will be sent over the network.
* @error Invalid input entity, or offset out of reasonable bounds.
*/
native void SetEntDataEnt2(int entity, int offset, int other, bool changeState=false);
/**
* Peeks into an entity's object data and retrieves the vector at the
* given offset.
* @note Both a Vector and a QAngle are three floats. This is a
* convenience function and will work with both types.
*
* @param entity Edict index.
* @param offset Offset to use.
* @param vec Vector buffer to store data in.
* @error Invalid entity or offset out of reasonable bounds.
*/
native void GetEntDataVector(int entity, int offset, float vec[3]);
/**
* Peeks into an entity's object data and sets the vector at the given
* offset.
* @note Both a Vector and a QAngle are three floats. This is a
* convenience function and will work with both types.
*
* @param entity Edict index.
* @param offset Offset to use.
* @param vec Vector to set.
* @param changeState If true, change will be sent over the network.
* @error Invalid entity or offset out of reasonable bounds.
*/
native void SetEntDataVector(int entity, int offset, const float vec[3], bool changeState=false);
/**
* Peeks into an entity's object data and retrieves the string at
* the given offset.
*
* @param entity Edict index.
* @param offset Offset to use.
* @param buffer Destination string buffer.
* @param maxlen Maximum length of output string buffer.
* @return Number of non-null bytes written.
* @error Invalid entity or offset out of reasonable bounds.
*/
native int GetEntDataString(int entity, int offset, char[] buffer, int maxlen);
/**
* Peeks into an entity's object data and sets the string at
* the given offset.
*
* @param entity Edict index.
* @param offset Offset to use.
* @param buffer String to set.
* @param maxlen Maximum length of bytes to write.
* @param changeState If true, change will be sent over the network.
* @return Number of non-null bytes written.
* @error Invalid entity or offset out of reasonable bounds.
*/
native int SetEntDataString(int entity, int offset, const char[] buffer, int maxlen, bool changeState=false);
/**
* @endsection
*/
/**
* Given a ServerClass name, finds a networkable send property offset.
* This information is cached for future calls.
*
* Note, this function may return offsets that do not work!
* If a property is nested beneath a parent object, the resulting offset
* will be invalid for direct use with data functions. Therefore, you
* should use FindSendPropInfo() instead. An example of such a property is
* CTFPlayer::DT_LocalPlayer.m_nDisguiseClass on Team Fortress.
*
* @param cls Classname.
* @param prop Property name.
* @return An offset, or -1 on failure.
* @deprecated Use FindSendPropInfo instead, or HasEntProp if you just want to check for existence.
*/
#pragma deprecated Use FindSendPropInfo instead, or HasEntProp if you just want to check for existence.
native int FindSendPropOffs(const char[] cls, const char[] prop);
/**
* Given a ServerClass name, finds a networkable send property offset.
* This information is cached for future calls.
*
* @param cls Classname.
* @param prop Property name.
* @param type Optional parameter to store the type.
* @param num_bits Optional parameter to store the number of bits the field
* uses, if applicable (otherwise 0 is stored). The number
* of bits varies for integers and floats, and is always 0
* for strings.
* @param local_offset Optional parameter to store the local offset, as
* FindSendPropOffs() would return.
* @param array_size Optional parameter to store array size, 0 if not an array.
* @return On success, returns an absolutely computed offset.
* If no offset is available, 0 is returned.
* If the property is not found, -1 is returned.
*/
native int FindSendPropInfo(const char[] cls,
const char[] prop,
PropFieldType &type=view_as<PropFieldType>(0),
int &num_bits=0,
int &local_offset=0,
int &array_size=0);
/**
* Given an entity, finds a datamap property offset.
* This information is cached for future calls.
*
* @param entity Entity index.
* @param prop Property name.
* @param type Optional parameter to store the type.
* @param num_bits Optional parameter to store the number of bits the field
* uses. The bit count will either be 1 (for boolean) or
* divisible by 8 (including 0 if unknown).
* @return An offset, or -1 on failure.
* @deprecated Use FindDataMapInfo instead, or HasEntProp if you just want to check for existence.
*/
#pragma deprecated Use FindDataMapInfo instead, or HasEntProp if you just want to check for existence.
native int FindDataMapOffs(int entity,
const char[] prop,
PropFieldType &type=view_as<PropFieldType>(0),
int &num_bits=0);
/**
* Given an entity, finds a nested datamap property offset.
* This information is cached for future calls.
*
* @param entity Entity index.
* @param prop Property name.
* @param type Optional parameter to store the type.
* @param num_bits Optional parameter to store the number of bits the field
* uses. The bit count will either be 1 (for boolean) or
* divisible by 8 (including 0 if unknown).
* @param local_offset Optional parameter to store the local offset, as
* FindDataMapOffs() would return.
* @return An offset, or -1 on failure.
*/
native int FindDataMapInfo(int entity,
const char[] prop,
PropFieldType &type=view_as<PropFieldType>(0),
int &num_bits=0,
int &local_offset=0);
/**
* Wrapper function for finding a send property for a particular entity.
*
* @param ent Entity index.
* @param prop Property name.
* @param actual Defaults to false for backwards compatibility.
* If true, the newer FindSendPropInfo() function
* is used instead.
* @return An offset, or -1 on failure.
*/
stock int GetEntSendPropOffs(int ent, const char[] prop, bool actual=false)
{
char cls[64];
if (!GetEntityNetClass(ent, cls, sizeof(cls)))
{
return -1;
}
int local = -1;
int offset = FindSendPropInfo(cls, prop, _, _, local);
if (actual)
{
return offset;
}
return local;
}
/**
* Checks if an entity property exists on an entity.
*
* @param entity Entity/edict index.
* @param type Property type.
* @param prop Property name.
* @return Whether the property exists on the entity.
* @error Invalid entity.
*/
stock bool HasEntProp(int entity, PropType type, const char[] prop)
{
if (type == Prop_Data)
{
return (FindDataMapInfo(entity, prop) != -1);
}
if (type != Prop_Send)
{
return false;
}
char cls[64];
if (!GetEntityNetClass(entity, cls, sizeof(cls)))
{
return false;
}
return (FindSendPropInfo(cls, prop) != -1);
}
/**
* Retrieves an integer value from an entity's property.
*
* This function is considered safer and more robust over GetEntData,
* because it performs strict offset checking and typing rules.
*
* @param entity Entity/edict index.
* @param type Property type.
* @param prop Property name.
* @param size Number of bytes to write (valid values are 1, 2, or 4).
* This value is auto-detected, and the size parameter is
* only used as a fallback in case detection fails.
* @param element Element # (starting from 0) if property is an array.
* @return Value at the given property offset.
* @error Invalid entity or property not found.
*/
native int GetEntProp(int entity, PropType type, const char[] prop, int size=4, int element=0);
/**
* Sets an integer value in an entity's property.
*
* This function is considered safer and more robust over SetEntData,
* because it performs strict offset checking and typing rules.
*
* @param entity Entity/edict index.
* @param type Property type.
* @param prop Property name.
* @param value Value to set.
* @param size Number of bytes to write (valid values are 1, 2, or 4).
* This value is auto-detected, and the size parameter is
* only used as a fallback in case detection fails.
* @param element Element # (starting from 0) if property is an array.
* @error Invalid entity or offset out of reasonable bounds.
*/
native void SetEntProp(int entity, PropType type, const char[] prop, any value, int size=4, int element=0);
/**
* Retrieves a float value from an entity's property.
*
* This function is considered safer and more robust over GetEntDataFloat,
* because it performs strict offset checking and typing rules.
*
* @param entity Entity/edict index.
* @param type Property type.
* @param prop Property name.
* @param element Element # (starting from 0) if property is an array.
* @return Value at the given property offset.
* @error Invalid entity or offset out of reasonable bounds.
*/
native float GetEntPropFloat(int entity, PropType type, const char[] prop, int element=0);
/**
* Sets a float value in an entity's property.
*
* This function is considered safer and more robust over SetEntDataFloat,
* because it performs strict offset checking and typing rules.
*
* @param entity Entity/edict index.
* @param type Property type.
* @param prop Property name.
* @param value Value to set.
* @param element Element # (starting from 0) if property is an array.
* @error Invalid entity or offset out of reasonable bounds.
*/
native void SetEntPropFloat(int entity, PropType type, const char[] prop, float value, int element=0);
/**
* Retrieves an entity index from an entity's property.
*
* This function is considered safer and more robust over GetEntDataEnt*,
* because it performs strict offset checking and typing rules.
*
* @param entity Entity/edict index.
* @param type Property type.
* @param prop Property name.
* @param element Element # (starting from 0) if property is an array.
* @return Entity index at the given property.
* If there is no entity, or the entity is not valid,
* then -1 is returned.
* @error Invalid entity or offset out of reasonable bounds.
*/
native int GetEntPropEnt(int entity, PropType type, const char[] prop, int element=0);
/**
* Sets an entity index in an entity's property.
*
* This function is considered safer and more robust over SetEntDataEnt*,
* because it performs strict offset checking and typing rules.
*
* @param entity Entity/edict index.
* @param type Property type.
* @param prop Property name.
* @param other Entity index to set, or -1 to unset.
* @param element Element # (starting from 0) if property is an array.
* @error Invalid entity or offset out of reasonable bounds.
*/
native void SetEntPropEnt(int entity, PropType type, const char[] prop, int other, int element=0);
/**
* Retrieves a vector of floats from an entity, given a named network property.
*
* This function is considered safer and more robust over GetEntDataVector,
* because it performs strict offset checking and typing rules.
*
* @param entity Entity/edict index.
* @param type Property type.
* @param prop Property name.
* @param vec Vector buffer to store data in.
* @param element Element # (starting from 0) if property is an array.
* @error Invalid entity, property not found, or property not
* actually a vector data type.
*/
native void GetEntPropVector(int entity, PropType type, const char[] prop, float vec[3], int element=0);
/**
* Sets a vector of floats in an entity, given a named network property.
*
* This function is considered safer and more robust over SetEntDataVector,
* because it performs strict offset checking and typing rules.
*
* @param entity Entity/edict index.
* @param type Property type.
* @param prop Property name.
* @param vec Vector to set.
* @param element Element # (starting from 0) if property is an array.
* @error Invalid entity, property not found, or property not
* actually a vector data type.
*/
native void SetEntPropVector(int entity, PropType type, const char[] prop, const float vec[3], int element=0);
/**
* Gets a network property as a string.
*
* @param entity Edict index.
* @param type Property type.
* @param prop Property to use.
* @param buffer Destination string buffer.
* @param maxlen Maximum length of output string buffer.
* @param element Element # (starting from 0) if property is an array.
* @return Number of non-null bytes written.
* @error Invalid entity, offset out of reasonable bounds, or property is not a valid string.
*/
native int GetEntPropString(int entity, PropType type, const char[] prop, char[] buffer, int maxlen, int element=0);
/**
* Sets a network property as a string.
*
* @param entity Edict index.
* @param type Property type.
* @param prop Property to use.
* @param buffer String to set.
* @param element Element # (starting from 0) if property is an array.
* @return Number of non-null bytes written.
* @error Invalid entity, offset out of reasonable bounds, or property is not a valid string.
*/
native int SetEntPropString(int entity, PropType type, const char[] prop, const char[] buffer, int element=0);
/**
* Retrieves the count of values that an entity property's array can store.
*
* @param entity Entity/edict index.
* @param type Property type.
* @param prop Property name.
* @return Size of array (in elements) or 0 if property is not an array.
* @error Invalid entity or property not found.
*/
native int GetEntPropArraySize(int entity, PropType type, const char[] prop);
/**
* Copies an array of cells from an entity at a given offset.
*
* @param entity Entity index.
* @param offset Offset to use.
* @param array Array to read into.
* @param arraySize Number of values to read.
* @param dataSize Size of each value in bytes (1, 2, or 4).
* @error Invalid entity or offset out of reasonable bounds.
*/
stock void GetEntDataArray(int entity, int offset, any[] array, int arraySize, int dataSize=4)
{
for (int i = 0; i < arraySize; i++)
{
array[i] = GetEntData(entity, offset + i*dataSize, dataSize);
}
}
/**
* Copies an array of cells to an entity at a given offset.
*
* @param entity Entity index.
* @param offset Offset to use.
* @param array Array of values to copy.
* @param arraySize Number of values to copy.
* @param dataSize Size of each value in bytes (1, 2, or 4).
* @param changeState True to set the network state as changed; false otherwise.
* @error Invalid entity or offset out of reasonable bounds.
*/
stock void SetEntDataArray(int entity, int offset, const any[] array, int arraySize, int dataSize=4, bool changeState=false)
{
for (int i = 0; i < arraySize; i++)
{
SetEntData(entity, offset + i*dataSize, array[i], dataSize, changeState);
}
}
/**
* Gets the memory address of an entity.
*
* @param entity Entity index.
* @return Address of the entity.
* @error Invalid entity.
*/
native Address GetEntityAddress(int entity);
/**
* Retrieves the classname of an entity.
* This is like GetEdictClassname(), except it works for ALL
* entities, not just edicts.
*
* @param entity Index of the entity.
* @param clsname Buffer to store the classname.
* @param maxlength Maximum length of the buffer.
* @return True on success, false if there is no classname set.
*/
stock bool GetEntityClassname(int entity, char[] clsname, int maxlength)
{
return !!GetEntPropString(entity, Prop_Data, "m_iClassname", clsname, maxlength);
}
/**
* Interprets the address as an entity handle and returns the associated entity.
*
* @param addr Address to a memory location.
* @return Entity index at the given location. If there is no entity, or the stored entity is invalid, then -1 is returned.
*/
native int LoadEntityFromHandleAddress(Address addr);
/**
* Interprets the address as an entity handle and sets the entity.
*
* @param addr Address to a memory location.
* @param entity Entity index to set, or -1 to clear.
*/
native void StoreEntityToHandleAddress(Address addr, int entity);

View File

@@ -0,0 +1,590 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _entity_prop_stocks_included
#endinput
#endif
#define _entity_prop_stocks_included
enum MoveType
{
MOVETYPE_NONE = 0, /**< never moves */
MOVETYPE_ISOMETRIC, /**< For players */
MOVETYPE_WALK, /**< Player only - moving on the ground */
MOVETYPE_STEP, /**< gravity, special edge handling -- monsters use this */
MOVETYPE_FLY, /**< No gravity, but still collides with stuff */
MOVETYPE_FLYGRAVITY, /**< flies through the air + is affected by gravity */
MOVETYPE_VPHYSICS, /**< uses VPHYSICS for simulation */
MOVETYPE_PUSH, /**< no clip to world, push and crush */
MOVETYPE_NOCLIP, /**< No gravity, no collisions, still do velocity/avelocity */
MOVETYPE_LADDER, /**< Used by players only when going onto a ladder */
MOVETYPE_OBSERVER, /**< Observer movement, depends on player's observer mode */
MOVETYPE_CUSTOM /**< Allows the entity to describe its own physics */
};
enum RenderMode
{
RENDER_NORMAL, /**< src */
RENDER_TRANSCOLOR, /**< c*a+dest*(1-a) */
RENDER_TRANSTEXTURE, /**< src*a+dest*(1-a) */
RENDER_GLOW, /**< src*a+dest -- No Z buffer checks -- Fixed size in screen space */
RENDER_TRANSALPHA, /**< src*srca+dest*(1-srca) */
RENDER_TRANSADD, /**< src*a+dest */
RENDER_ENVIRONMENTAL, /**< not drawn, used for environmental effects */
RENDER_TRANSADDFRAMEBLEND, /**< use a fractional frame value to blend between animation frames */
RENDER_TRANSALPHAADD, /**< src + dest*(1-a) */
RENDER_WORLDGLOW, /**< Same as kRenderGlow but not fixed size in screen space */
RENDER_NONE /**< Don't render. */
};
enum RenderFx
{
RENDERFX_NONE = 0,
RENDERFX_PULSE_SLOW,
RENDERFX_PULSE_FAST,
RENDERFX_PULSE_SLOW_WIDE,
RENDERFX_PULSE_FAST_WIDE,
RENDERFX_FADE_SLOW,
RENDERFX_FADE_FAST,
RENDERFX_SOLID_SLOW,
RENDERFX_SOLID_FAST,
RENDERFX_STROBE_SLOW,
RENDERFX_STROBE_FAST,
RENDERFX_STROBE_FASTER,
RENDERFX_FLICKER_SLOW,
RENDERFX_FLICKER_FAST,
RENDERFX_NO_DISSIPATION,
RENDERFX_DISTORT, /**< Distort/scale/translate flicker */
RENDERFX_HOLOGRAM, /**< kRenderFxDistort + distance fade */
RENDERFX_EXPLODE, /**< Scale up really big! */
RENDERFX_GLOWSHELL, /**< Glowing Shell */
RENDERFX_CLAMP_MIN_SCALE, /**< Keep this sprite from getting very small (SPRITES only!) */
RENDERFX_ENV_RAIN, /**< for environmental rendermode, make rain */
RENDERFX_ENV_SNOW, /**< " " " , make snow */
RENDERFX_SPOTLIGHT, /**< TEST CODE for experimental spotlight */
RENDERFX_RAGDOLL, /**< HACKHACK: TEST CODE for signalling death of a ragdoll character */
RENDERFX_PULSE_FAST_WIDER,
RENDERFX_MAX
};
// These defines are for client button presses.
#define IN_ATTACK (1 << 0)
#define IN_JUMP (1 << 1)
#define IN_DUCK (1 << 2)
#define IN_FORWARD (1 << 3)
#define IN_BACK (1 << 4)
#define IN_USE (1 << 5)
#define IN_CANCEL (1 << 6)
#define IN_LEFT (1 << 7)
#define IN_RIGHT (1 << 8)
#define IN_MOVELEFT (1 << 9)
#define IN_MOVERIGHT (1 << 10)
#define IN_ATTACK2 (1 << 11)
#define IN_RUN (1 << 12)
#define IN_RELOAD (1 << 13)
#define IN_ALT1 (1 << 14)
#define IN_ALT2 (1 << 15)
#define IN_SCORE (1 << 16) /**< Used by client.dll for when scoreboard is held down */
#define IN_SPEED (1 << 17) /**< Player is holding the speed key */
#define IN_WALK (1 << 18) /**< Player holding walk key */
#define IN_ZOOM (1 << 19) /**< Zoom key for HUD zoom */
#define IN_WEAPON1 (1 << 20) /**< weapon defines these bits */
#define IN_WEAPON2 (1 << 21) /**< weapon defines these bits */
#define IN_BULLRUSH (1 << 22)
#define IN_GRENADE1 (1 << 23) /**< grenade 1 */
#define IN_GRENADE2 (1 << 24) /**< grenade 2 */
#define IN_ATTACK3 (1 << 25)
// Note: these are only for use with GetEntityFlags and SetEntityFlags
// and may not match the game's actual, internal m_fFlags values.
// PLAYER SPECIFIC FLAGS FIRST BECAUSE WE USE ONLY A FEW BITS OF NETWORK PRECISION
#define FL_ONGROUND (1 << 0) /**< At rest / on the ground */
#define FL_DUCKING (1 << 1) /**< Player flag -- Player is fully crouched */
#define FL_WATERJUMP (1 << 2) /**< player jumping out of water */
#define FL_ONTRAIN (1 << 3) /**< Player is _controlling_ a train, so movement commands should be ignored on client during prediction. */
#define FL_INRAIN (1 << 4) /**< Indicates the entity is standing in rain */
#define FL_FROZEN (1 << 5) /**< Player is frozen for 3rd person camera */
#define FL_ATCONTROLS (1 << 6) /**< Player can't move, but keeps key inputs for controlling another entity */
#define FL_CLIENT (1 << 7) /**< Is a player */
#define FL_FAKECLIENT (1 << 8) /**< Fake client, simulated server side; don't send network messages to them */
// NOTE if you move things up, make sure to change this value
#define PLAYER_FLAG_BITS 9
// NON-PLAYER SPECIFIC (i.e., not used by GameMovement or the client .dll ) -- Can still be applied to players, though
#define FL_INWATER (1 << 9) /**< In water */
#define FL_FLY (1 << 10) /**< Changes the SV_Movestep() behavior to not need to be on ground */
#define FL_SWIM (1 << 11) /**< Changes the SV_Movestep() behavior to not need to be on ground (but stay in water) */
#define FL_CONVEYOR (1 << 12)
#define FL_NPC (1 << 13)
#define FL_GODMODE (1 << 14)
#define FL_NOTARGET (1 << 15)
#define FL_AIMTARGET (1 << 16) /**< set if the crosshair needs to aim onto the entity */
#define FL_PARTIALGROUND (1 << 17) /**< not all corners are valid */
#define FL_STATICPROP (1 << 18) /**< Eetsa static prop! */
#define FL_GRAPHED (1 << 19) /**< worldgraph has this ent listed as something that blocks a connection */
#define FL_GRENADE (1 << 20)
#define FL_STEPMOVEMENT (1 << 21) /**< Changes the SV_Movestep() behavior to not do any processing */
#define FL_DONTTOUCH (1 << 22) /**< Doesn't generate touch functions, generates Untouch() for anything it was touching when this flag was set */
#define FL_BASEVELOCITY (1 << 23) /**< Base velocity has been applied this frame (used to convert base velocity into momentum) */
#define FL_WORLDBRUSH (1 << 24) /**< Not moveable/removeable brush entity (really part of the world, but represented as an entity for transparency or something) */
#define FL_OBJECT (1 << 25) /**< Terrible name. This is an object that NPCs should see. Missiles, for example. */
#define FL_KILLME (1 << 26) /**< This entity is marked for death -- will be freed by game DLL */
#define FL_ONFIRE (1 << 27) /**< You know... */
#define FL_DISSOLVING (1 << 28) /**< We're dissolving! */
#define FL_TRANSRAGDOLL (1 << 29) /**< In the process of turning into a client side ragdoll. */
#define FL_UNBLOCKABLE_BY_PLAYER (1 << 30) /**< pusher that can't be blocked by the player */
#define FL_FREEZING (1 << 31) /**< We're becoming frozen! */
#define FL_EP2V_UNKNOWN1 (1 << 31) /**< Unknown */
// END entity flag #defines
/**
* Get an entity's flags.
*
* @note The game's actual flags are internally translated by SM
* to match the entity flags defined above as the actual values
* can differ per engine.
*
* @param entity Entity index.
* @return Entity's flags, see entity flag defines above.
* @error Invalid entity index, or lack of mod compliance.
*/
native int GetEntityFlags(int entity);
/**
* Sets an entity's flags.
*
* @note The entity flags as defined above are internally translated by SM
* to match the current game's expected value for the flags as
* the actual values can differ per engine.
*
* @param entity Entity index.
* @param flags Entity flags, see entity flag defines above.
* @error Invalid entity index, or lack of mod compliance.
*/
native void SetEntityFlags(int entity, int flags);
/**
* Gets an entity's movetype.
*
* @param entity Entity index.
* @return Movetype, see enum above.
* @error Invalid entity index, or lack of mod compliance.
*/
stock MoveType GetEntityMoveType(int entity)
{
static bool gotconfig = false;
static char datamap[32];
if (!gotconfig)
{
GameData gc = new GameData("core.games");
bool exists = gc.GetKeyValue("m_MoveType", datamap, sizeof(datamap));
delete gc;
if (!exists)
{
strcopy(datamap, sizeof(datamap), "m_MoveType");
}
gotconfig = true;
}
return view_as<MoveType>(GetEntProp(entity, Prop_Data, datamap));
}
/**
* Sets an entity's movetype.
*
* @param entity Entity index.
* @param mt Movetype, see enum above.
* @error Invalid entity index, or lack of mod compliance.
*/
stock void SetEntityMoveType(int entity, MoveType mt)
{
static bool gotconfig = false;
static char datamap[32];
if (!gotconfig)
{
GameData gc = new GameData("core.games");
bool exists = gc.GetKeyValue("m_MoveType", datamap, sizeof(datamap));
delete gc;
if (!exists)
{
strcopy(datamap, sizeof(datamap), "m_MoveType");
}
gotconfig = true;
}
SetEntProp(entity, Prop_Data, datamap, mt);
}
/**
* Gets an entity's render mode.
*
* @param entity Entity index.
* @return RenderMode value.
* @error Invalid entity index, or lack of mod compliance.
*/
stock RenderMode GetEntityRenderMode(int entity)
{
static bool gotconfig = false;
static char prop[32];
if (!gotconfig)
{
GameData gc = new GameData("core.games");
bool exists = gc.GetKeyValue("m_nRenderMode", prop, sizeof(prop));
delete gc;
if (!exists)
{
strcopy(prop, sizeof(prop), "m_nRenderMode");
}
gotconfig = true;
}
return view_as<RenderMode>(GetEntProp(entity, Prop_Send, prop, 1));
}
/**
* Sets an entity's render mode.
*
* @param entity Entity index.
* @param mode RenderMode value.
* @error Invalid entity index, or lack of mod compliance.
*/
stock void SetEntityRenderMode(int entity, RenderMode mode)
{
static bool gotconfig = false;
static char prop[32];
if (!gotconfig)
{
GameData gc = new GameData("core.games");
bool exists = gc.GetKeyValue("m_nRenderMode", prop, sizeof(prop));
delete gc;
if (!exists)
{
strcopy(prop, sizeof(prop), "m_nRenderMode");
}
gotconfig = true;
}
SetEntProp(entity, Prop_Send, prop, mode, 1);
}
/**
* Gets an entity's render Fx.
*
* @param entity Entity index.
* @return RenderFx value.
* @error Invalid entity index, or lack of mod compliance.
*/
stock RenderFx GetEntityRenderFx(int entity)
{
static bool gotconfig = false;
static char prop[32];
if (!gotconfig)
{
GameData gc = new GameData("core.games");
bool exists = gc.GetKeyValue("m_nRenderFX", prop, sizeof(prop));
delete gc;
if (!exists)
{
strcopy(prop, sizeof(prop), "m_nRenderFX");
}
gotconfig = true;
}
return view_as<RenderFx>(GetEntProp(entity, Prop_Send, prop, 1));
}
/**
* Sets an entity's render Fx.
*
* @param entity Entity index.
* @param fx RenderFx value.
* @error Invalid entity index, or lack of mod compliance.
*/
stock void SetEntityRenderFx(int entity, RenderFx fx)
{
static bool gotconfig = false;
static char prop[32];
if (!gotconfig)
{
GameData gc = new GameData("core.games");
bool exists = gc.GetKeyValue("m_nRenderFX", prop, sizeof(prop));
delete gc;
if (!exists)
{
strcopy(prop, sizeof(prop), "m_nRenderFX");
}
gotconfig = true;
}
SetEntProp(entity, Prop_Send, prop, fx, 1);
}
/**
* Gets an entity's color.
*
* @param entity Entity index.
* @param r Amount of red (0-255)
* @param g Amount of green (0-255)
* @param b Amount of blue (0-255)
* @param a Amount of alpha (0-255)
* @error Invalid entity index, or lack of mod compliance.
*/
stock void GetEntityRenderColor(int entity, int &r, int &g, int &b, int &a)
{
static bool gotconfig = false;
static char prop[32];
if (!gotconfig)
{
GameData gc = new GameData("core.games");
bool exists = gc.GetKeyValue("m_clrRender", prop, sizeof(prop));
delete gc;
if (!exists)
{
strcopy(prop, sizeof(prop), "m_clrRender");
}
gotconfig = true;
}
int offset = GetEntSendPropOffs(entity, prop);
if (offset <= 0)
{
ThrowError("GetEntityRenderColor not supported by this mod");
}
r = GetEntData(entity, offset, 1);
g = GetEntData(entity, offset + 1, 1);
b = GetEntData(entity, offset + 2, 1);
a = GetEntData(entity, offset + 3, 1);
}
/**
* Sets an entity's color.
*
* @param entity Entity index
* @param r Amount of red (0-255)
* @param g Amount of green (0-255)
* @param b Amount of blue (0-255)
* @param a Amount of alpha (0-255)
* @error Invalid entity index, or lack of mod compliance.
*/
stock void SetEntityRenderColor(int entity, int r=255, int g=255, int b=255, int a=255)
{
static bool gotconfig = false;
static char prop[32];
if (!gotconfig)
{
GameData gc = new GameData("core.games");
bool exists = gc.GetKeyValue("m_clrRender", prop, sizeof(prop));
delete gc;
if (!exists)
{
strcopy(prop, sizeof(prop), "m_clrRender");
}
gotconfig = true;
}
int offset = GetEntSendPropOffs(entity, prop);
if (offset <= 0)
{
ThrowError("SetEntityRenderColor not supported by this mod");
}
SetEntData(entity, offset, r, 1, true);
SetEntData(entity, offset + 1, g, 1, true);
SetEntData(entity, offset + 2, b, 1, true);
SetEntData(entity, offset + 3, a, 1, true);
}
/**
* Gets an entity's gravity.
*
* @param entity Entity index.
* @return Entity's m_flGravity value.
* @error Invalid entity index, or lack of mod compliance.
*/
stock float GetEntityGravity(int entity)
{
static bool gotconfig = false;
static char datamap[32];
if (!gotconfig)
{
GameData gc = new GameData("core.games");
bool exists = gc.GetKeyValue("m_flGravity", datamap, sizeof(datamap));
delete gc;
if (!exists)
{
strcopy(datamap, sizeof(datamap), "m_flGravity");
}
gotconfig = true;
}
return GetEntPropFloat(entity, Prop_Data, datamap);
}
/**
* Sets an entity's gravity.
*
* @param entity Entity index.
* @param amount Gravity to set (default = 1.0, half = 0.5, double = 2.0).
* @error Invalid entity index, or lack of mod compliance.
*/
stock void SetEntityGravity(int entity, float amount)
{
static bool gotconfig = false;
static char datamap[32];
if (!gotconfig)
{
GameData gc = new GameData("core.games");
bool exists = gc.GetKeyValue("m_flGravity", datamap, sizeof(datamap));
delete gc;
if (!exists)
{
strcopy(datamap, sizeof(datamap), "m_flGravity");
}
gotconfig = true;
}
SetEntPropFloat(entity, Prop_Data, datamap, amount);
}
/**
* Sets an entity's health
*
* @param entity Entity index.
* @param amount Health amount.
* @error Invalid entity index, or lack of mod compliance.
*/
stock void SetEntityHealth(int entity, int amount)
{
static bool gotconfig = false;
static char prop[32];
if (!gotconfig)
{
GameData gc = new GameData("core.games");
bool exists = gc.GetKeyValue("m_iHealth", prop, sizeof(prop));
delete gc;
if (!exists)
{
strcopy(prop, sizeof(prop), "m_iHealth");
}
gotconfig = true;
}
PropFieldType type;
int offset;
if ((offset = FindDataMapInfo(entity, prop, type)) == -1)
{
ThrowError("SetEntityHealth not supported by this mod");
return;
}
/* Dark Messiah uses a float for the health instead an integer */
if (type == PropField_Float)
{
SetEntDataFloat(entity, offset, float(amount));
}
else
{
SetEntData(entity, offset, amount);
}
if (IsValidEdict(entity))
{
ChangeEdictState(entity);
}
}
/**
* Get's a users current pressed buttons
*
* @param client Client index
* @return Bitsum of buttons
* @error Invalid client index, client not in game,
* or lack of mod compliance.
*/
stock int GetClientButtons(int client)
{
static bool gotconfig = false;
static char datamap[32];
if (!gotconfig)
{
GameData gc = new GameData("core.games");
bool exists = gc.GetKeyValue("m_nButtons", datamap, sizeof(datamap));
delete gc;
if (!exists)
{
strcopy(datamap, sizeof(datamap), "m_nButtons");
}
gotconfig = true;
}
return GetEntProp(client, Prop_Data, datamap);
}

View File

@@ -0,0 +1,157 @@
#if defined _entitylump_included
#endinput
#endif
#define _entitylump_included
/**
* An ordered list of key / value pairs for a map entity.
* If the entry in the EntityLump is removed, the handle will error on all operations.
* (The handle will remain valid on the scripting side, and will still need to be deleted.)
*
* Write operations (update, insert, erase, append) are only allowed during OnMapInit.
*/
methodmap EntityLumpEntry < Handle {
/**
* Copies the key / value at the given index into buffers.
*
* @param index Position, starting from 0.
* @param keybuf Key name buffer.
* @param keylen Maximum length of the key name buffer.
* @param valbuf Value buffer.
* @param vallen Maximum length of the value buffer.
* @error Index is out of bounds.
*/
public native void Get(int index, char[] keybuf = "", int keylen = 0, char[] valbuf = "", int vallen = 0);
/**
* Updates the key / value pair at the given index.
*
* @param index Position, starting from 0.
* @param key New key name, or NULL_STRING to preserve the existing key name.
* @param value New value, or NULL_STRING to preserve the existing value.
* @error Index is out of bounds or entity lump is read-only.
*/
public native void Update(int index, const char[] key = NULL_STRING, const char[] value = NULL_STRING);
/**
* Inserts a new key / value pair at the given index, shifting the pair at that index and beyond up.
* If EntityLumpEntry.Length is passed in, this is an append operation.
*
* @param index Position, starting from 0.
* @param key New key name.
* @param value New value.
* @error Index is out of bounds or entity lump is read-only.
*/
public native void Insert(int index, const char[] key, const char[] value);
/**
* Removes the key / value pair at the given index, shifting all entries past it down.
*
* @param index Position, starting from 0.
* @error Index is out of bounds or entity lump is read-only.
*/
public native void Erase(int index);
/**
* Inserts a new key / value pair at the end of the entry's list.
*
* @param key New key name.
* @param value New value.
* @error Index is out of bounds or entity lump is read-only.
*/
public native void Append(const char[] key, const char[] value);
/**
* Searches the entry list for an index matching a key starting from a position.
*
* @param key Key name to search.
* @param start A position after which to begin searching from. Use -1 to start from the
* first entry.
* @return Position after start with an entry matching the given key, or -1 if no
* match was found.
* @error Invalid start position; must be a value between -1 and one less than the
* length of the entry.
*/
public native int FindKey(const char[] key, int start = -1);
/**
* Searches the entry list for an index matching a key starting from a position.
* This also copies the value from that index into the given buffer.
*
* This can be used to find the first / only value matching a key, or to iterate over all
* the values that match said key.
*
* @param key Key name to search.
* @param buffer Value buffer. This will contain the result of the next match, or empty
* if no match was found.
* @param maxlen Maximum length of the value buffer.
* @param start An index after which to begin searching from. Use -1 to start from the
* first entry.
* @return Position after start with an entry matching the given key, or -1 if no
* match was found.
* @error Invalid start position; must be a value between -1 and one less than the
* length of the entry.
*/
public int GetNextKey(const char[] key, char[] buffer, int maxlen, int start = -1) {
int result = this.FindKey(key, start);
if (result != -1) {
this.Get(result, .valbuf = buffer, .vallen = maxlen);
} else {
buffer[0] = '\0';
}
return result;
}
/**
* Retrieves the number of key / value pairs in the entry.
*/
property int Length {
public native get();
}
};
/**
* A group of natives for a singleton entity lump, representing all the entities defined in the map.
*
* Write operations (insert, erase, append) are only allowed during OnMapInit.
*/
methodmap EntityLump {
/**
* Returns the EntityLumpEntry at the given index.
* This handle should be freed by the calling plugin.
*
* @param index Position, starting from 0.
* @error Index is out of bounds.
*/
public static native EntityLumpEntry Get(int index);
/**
* Erases an EntityLumpEntry at the given index, shifting all entries past it down.
* Any handles referencing the erased EntityLumpEntry will throw on any operations aside from delete.
*
* @param index Position, starting from 0.
* @error Index is out of bounds or entity lump is read-only.
*/
public static native void Erase(int index);
/**
* Inserts an empty EntityLumpEntry at the given index, shifting the existing entry and ones past it up.
*
* @param index Position, starting from 0.
* @error Index is out of bounds or entity lump is read-only.
*/
public static native void Insert(int index);
/**
* Creates an empty EntityLumpEntry, returning its index.
*
* @error Entity lump is read-only.
*/
public static native int Append();
/**
* Returns the number of entities currently in the lump.
*/
public static native int Length();
};

View File

@@ -0,0 +1,343 @@
/**
* vim: set ts=4 sw=4 tw=99 noet :
* =============================================================================
* SourceMod (C)2004-2014 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _events_included
#endinput
#endif
#define _events_included
/**
* Event hook modes determining how hooking should be handled
*/
enum EventHookMode
{
EventHookMode_Pre, //< Hook callback fired before event is fired */
EventHookMode_Post, //< Hook callback fired after event is fired */
EventHookMode_PostNoCopy //< Hook callback fired after event is fired, but event data won't be copied */
};
/**
* Hook function types for events.
*/
typeset EventHook
{
// Called when a game event is fired.
//
// @param event Handle to event. This could be INVALID_HANDLE if every plugin hooking
// this event has set the hook mode EventHookMode_PostNoCopy.
// @param name String containing the name of the event.
// @param dontBroadcast True if event was not broadcast to clients, false otherwise.
// May not correspond to the real value. Use the property BroadcastDisabled.
// @return Ignored for post hooks. Plugin_Handled will block event if hooked as pre.
///
function Action (Event event, const char[] name, bool dontBroadcast);
//
// Called when a game event is fired.
//
// @param event Handle to event. This could be INVALID_HANDLE if every plugin hooking
// this event has set the hook mode EventHookMode_PostNoCopy.
// @param name String containing the name of the event.
// @param dontBroadcast True if event was not broadcast to clients, false otherwise.
///
function void (Event event, const char[] name, bool dontBroadcast);
};
methodmap Event < Handle
{
// Fires a game event.
//
// This function closes the event Handle after completing.
//
// @param dontBroadcast Optional boolean that determines if event should be broadcast to clients.
public native void Fire(bool dontBroadcast=false);
// Fires a game event to only the specified client.
//
// Unlike Fire, this function DOES NOT close the event Handle.
//
// @param client Index of client to receive the event..
public native void FireToClient(int client);
// Cancels a previously created game event that has not been fired. This
// is necessary to avoid leaking memory when an event isn't fired.
public native void Cancel();
// Returns the boolean value of a game event's key.
//
// @param key Name of event key.
// @param defValue Optional default value to use if the key is not found.
// @return The boolean value of the specified event key.
public native bool GetBool(const char[] key, bool defValue=false);
// Sets the boolean value of a game event's key.
//
// @param key Name of event key.
// @param value New boolean value.
public native void SetBool(const char[] key, bool value);
// Returns the integer value of a game event's key.
//
// @param key Name of event key.
// @param defValue Optional default value to use if the key is not found.
// @return The integer value of the specified event key.
public native int GetInt(const char[] key, int defValue=0);
// Sets the integer value of a game event's key.
//
// Integer value refers to anything that can be reduced to an integer.
// The various size specifiers, such as "byte" and "short" are still
// integers, and only refer to how much data will actually be sent
// over the network (if applicable).
//
// @param key Name of event key.
// @param value New integer value.
public native void SetInt(const char[] key, int value);
// Returns the floating point value of a game event's key.
//
// @param key Name of event key.
// @param defValue Optional default value to use if the key is not found.
// @return The floating point value of the specified event key.
public native float GetFloat(const char[] key, float defValue=0.0);
// Sets the floating point value of a game event's key.
//
// @param key Name of event key.
// @param value New floating point value.
public native void SetFloat(const char[] key, float value);
// Retrieves the string value of a game event's key.
//
// @param key Name of event key.
// @param value Buffer to store the value of the specified event key.
// @param maxlength Maximum length of string buffer.
// @param defValue Optional default value to use if the key is not found.
public native void GetString(const char[] key, char[] value, int maxlength, const char[] defvalue="");
// Sets the string value of a game event's key.
//
// @param key Name of event key.
// @param value New string value.
public native void SetString(const char[] key, const char[] value);
// Retrieves the name of a game event.
//
// @param name Buffer to store the name of the event.
// @param maxlength Maximum length of string buffer.
public native void GetName(char[] name, int maxlength);
// Sets whether an event's broadcasting will be disabled or not.
//
// This has no effect on events Handles that are not from HookEvent
// or HookEventEx callbacks.
property bool BroadcastDisabled {
public native set(bool dontBroadcast);
public native get();
}
}
/**
* Creates a hook for when a game event is fired.
*
* @param name Name of event.
* @param callback An EventHook function pointer.
* @param mode Optional EventHookMode determining the type of hook.
* @error Invalid event name or invalid callback function.
*/
native void HookEvent(const char[] name, EventHook callback, EventHookMode mode=EventHookMode_Post);
/**
* Creates a hook for when a game event is fired.
*
* @param name Name of event.
* @param callback An EventHook function pointer.
* @param mode Optional EventHookMode determining the type of hook.
* @return True if event exists and was hooked successfully, false otherwise.
* @error Invalid callback function.
*/
native bool HookEventEx(const char[] name, EventHook callback, EventHookMode mode=EventHookMode_Post);
/**
* Removes a hook for when a game event is fired.
*
* @param name Name of event.
* @param callback An EventHook function pointer.
* @param mode Optional EventHookMode determining the type of hook.
* @error Invalid callback function or no active hook for specified event.
*/
native void UnhookEvent(const char[] name, EventHook callback, EventHookMode mode=EventHookMode_Post);
/**
* Creates a game event to be fired later.
*
* The Handle should not be closed via CloseHandle(). It must be closed via
* event.Fire() or event.Cancel().
*
* @param name Name of event.
* @param force If set to true, this forces the event to be created even if it's not being hooked.
* Note that this will not force it if the event doesn't exist at all.
* @return Handle to event. INVALID_HANDLE is returned if the event doesn't exist or isn't
* being hooked (unless force is true).
*/
native Event CreateEvent(const char[] name, bool force=false);
/**
* Fires a game event.
*
* This function closes the event Handle after completing.
*
* @param event Handle to the event.
* @param dontBroadcast Optional boolean that determines if event should be broadcast to clients.
* @error Invalid or corrupt Handle.
*/
native void FireEvent(Handle event, bool dontBroadcast=false);
/**
* Cancels a previously created game event that has not been fired.
*
* @param event Handled to the event.
* @error Invalid or corrupt Handle.
*/
native void CancelCreatedEvent(Handle event);
/**
* Returns the boolean value of a game event's key.
*
* @param event Handle to the event.
* @param key Name of event key.
* @param defValue Optional default value to use if the key is not found.
* @return The boolean value of the specified event key.
* @error Invalid or corrupt Handle.
*/
native bool GetEventBool(Handle event, const char[] key, bool defValue=false);
/**
* Sets the boolean value of a game event's key.
*
* @param event Handle to the event.
* @param key Name of event key.
* @param value New boolean value.
* @error Invalid or corrupt Handle.
*/
native void SetEventBool(Handle event, const char[] key, bool value);
/**
* Returns the integer value of a game event's key.
*
* @param event Handle to the event.
* @param key Name of event key.
* @param defValue Optional default value to use if the key is not found.
* @return The integer value of the specified event key.
* @error Invalid or corrupt Handle.
*/
native int GetEventInt(Handle event, const char[] key, int defValue=0);
/**
* Sets the integer value of a game event's key.
*
* Integer value refers to anything that can be reduced to an integer.
* The various size specifiers, such as "byte" and "short" are still
* integers, and only refer to how much data will actually be sent
* over the network (if applicable).
*
* @param event Handle to the event.
* @param key Name of event key.
* @param value New integer value.
* @error Invalid or corrupt Handle.
*/
native void SetEventInt(Handle event, const char[] key, int value);
/**
* Returns the floating point value of a game event's key.
*
* @param event Handle to the event.
* @param key Name of event key.
* @param defValue Optional default value to use if the key is not found.
* @return The floating point value of the specified event key.
* @error Invalid or corrupt Handle.
*/
native float GetEventFloat(Handle event, const char[] key, float defValue=0.0);
/**
* Sets the floating point value of a game event's key.
*
* @param event Handle to the event.
* @param key Name of event key.
* @param value New floating point value.
* @error Invalid or corrupt Handle.
*/
native void SetEventFloat(Handle event, const char[] key, float value);
/**
* Retrieves the string value of a game event's key.
*
* @param event Handle to the event.
* @param key Name of event key.
* @param value Buffer to store the value of the specified event key.
* @param maxlength Maximum length of string buffer.
* @param defValue Optional default value to use if the key is not found.
* @error Invalid or corrupt Handle.
*/
native void GetEventString(Handle event, const char[] key, char[] value, int maxlength, const char[] defvalue="");
/**
* Sets the string value of a game event's key.
*
* @param event Handle to the event.
* @param key Name of event key.
* @param value New string value.
* @error Invalid or corrupt Handle.
*/
native void SetEventString(Handle event, const char[] key, const char[] value);
/**
* Retrieves the name of a game event.
*
* @param event Handle to the event.
* @param name Buffer to store the name of the event.
* @param maxlength Maximum length of string buffer.
* @error Invalid or corrupt Handle.
*/
native void GetEventName(Handle event, char[] name, int maxlength);
/**
* Sets whether an event's broadcasting will be disabled or not.
*
* This has no effect on events Handles that are not from HookEvent
* or HookEventEx callbacks.
*
* @param event Handle to an event from an event hook.
* @param dontBroadcast True to disable broadcasting, false otherwise.
* @error Invalid Handle.
*/
native void SetEventBroadcast(Handle event, bool dontBroadcast);

View File

@@ -0,0 +1,522 @@
// Fartsy's Boss Handler v1.0.0
enum struct BOSSHANDLER {
int bossID;
bool bTargetInRange[MAXPLAYERS+1];
bool bDoTankBuster;
bool isAlive;
bool shouldTick;
bool shouldTickBGM;
bool tickBuster;
float fAng[3];
float fPos[3];
int bustTarget;
int iBossEnt;
int iBossEntHealth;
int iBossEntMaxHealth;
int iBossEntTarget;
int iBossPhase;
int iBossPhaseTmp;
void EmitSpawnSound(int boss){
switch(boss){
//Onslaughter
case 0:{
//Onslaughter has no spawn sound for now.... maybe when brute justice happens c:
}
//Sephiroth (wip)
case 1:{
}
//Metallizer (wip) To Do: Only change to Inferno if we're in boss attack range. Use a trigger_multiple for this. To Do, delay this by like 1 second so the DJMM sound can play properly.
case 2:{
sudo(1001);
AudioManager.Stop();
AudioManager.indexBGM = 20;
CustomSoundEmitter(SFXArray[106].realPath, 65, false, 0, 1.0, 100); //DJMM SFX
CreateTimer(1.5, DelayedMetalFace);
}
}
}
//For tracking model and skipping player ready check if boss is alive
void Tick(){
//PrintToServer("Boss %i, hp %i/%i", this.bossID, this.iBossEntHealth, this.iBossEntMaxHealth);
if (this.shouldTickBGM) (this.TickBGM());
if(this.isAlive && !core.isWave){
PrintToChatAll("PLACEHOLDER -- FORCE PLAYERS TO BE READY IF NOT IN WAVE.");
}
if(this.tickBuster) this.TickBuster();
switch(this.bossID){
case 0:{
}
case 1:{
}
case 2:{
this.iBossEnt = FindEntityByTargetname("FB.MetalBase", "base_boss");
if (!IsValidEntity(this.iBossEnt)) this.iBossPhase = 4;
else {
this.iBossEntHealth = GetEntProp(this.iBossEnt, Prop_Data, "m_iHealth");
this.iBossEntMaxHealth = GetEntProp(this.iBossEnt, Prop_Data, "m_iMaxHealth");
this.iBossEntTarget = FindEntityByTargetname("FB.MetalFace.Train", "func_tracktrain");
GetEntPropVector(this.iBossEntTarget, Prop_Send, "m_vecOrigin", this.fPos);
GetEntPropVector(this.iBossEntTarget, Prop_Data, "m_angRotation", this.fAng);
float vel[3];
float newPos[3];
vel[0] = 0.0;
vel[1] = 0.0;
vel[2] = 0.0;
newPos[0] = this.fPos[0];
newPos[1] = this.fPos[1];
newPos[2] = this.fPos[2] - 50.0;
TeleportEntity(this.iBossEnt, newPos, this.fAng, vel);
}
//Also need to set entity angles to its target... we can use this.bustTarget for the index of the client to get the angles...
//Do phase changes
switch(RoundToFloor((this.iBossEntHealth * 1.0/this.iBossEntMaxHealth * 1.0) * 10.0)){
case 10:{
this.iBossPhase = 1;
}
case 7:{
this.iBossPhase = 2;
}
case 4:{
this.iBossPhase = 3;
}
case 1:{
this.iBossPhase = 4;
}
}
if(this.iBossPhase != this.iBossPhaseTmp){
PrintToChatAll("PHASE CHANGED, %i to %i", this.iBossPhaseTmp, this.iBossPhase);
this.iBossPhaseTmp = this.iBossPhase;
if(this.iBossPhase > 1){
FastFire2("mfTelefect", "Start", "", 0.0, false);
FastFire2("FB.MetalFace.ReturnSND", "PlaySound", "", 0.0, false);
FastFire2("FB.MetalFace.Train", "TeleportToPathTrack", "MFTHOME", 0.25, false);
FastFire2("FB.MetalFace.Invuln", "Enable", "", 3.0, false);
}
//Phase changing, these only ever happen once per phase.
switch(this.iBossPhase){
case 0:{
PrintToChatAll("Phase 0 happened, boss must must be dead /shrug");
}
case 1:{
//PrintToChatAll("Recognized 0 -> 1, the boss must have just spawned!");
FastFire2("FB.MetalBase", "SetHealth", "320000", 0.0, false);
FastFire2("FB.MetalBase", "SetMaxHealth", "320000", 0.0, false);
FastFire2("FB.MetalBase", "AddOutput", "health 320000", 0.0, false);
}
case 2:{
//PrintToChatAll("Recognized 1 -> 2, things are heating up!");
AudioManager.ChangeBGM(22);
FastFire2("FB.MetalFace.Train", "TeleportToPathTrack", "MFT1x0", 3.00, false);
FastFire2("FB.MetalFace.SkeleSpawner", "Enable", "", 0.0, false);
FastFire2("FB.MetalFace.SkeleSpawner", "Disable", "", 120.0, false);
FastFire2("mfTelefect", "Start", "", 120.0, false);
FastFire2("FB.MetalFace.ReturnSND", "PlaySound", "", 120.0, false);
FastFire2("FB.MetalFace.Train", "TeleportToPathTrack", "MFTHOME", 120.25, false);
FastFire2("FB.MetalFace.Invuln", "Disable", "", 123.0, false);
FastFire2("FB.MetalFace.Train", "TeleportToPathTrack", "tank_path_a_100", 126.85, false);
FastFire2("mfTelefect", "Start", "", 127.0, false);
FastFire2("FB.MetalFace.ReturnSND", "PlaySound", "", 127.0, false);
}
case 3:{
//PrintToChatAll("Recognized 2 -> 3, oh boi");
AudioManager.ChangeBGM(24);
FastFire2("FB.MetalFace.Train", "TeleportToPathTrack", "MFT2x0", 3.00, false);
FastFire2("FB.MetalFace.MerasmusSpawner", "ForceSpawn", "", 5.0, false); //Spawn halloween bosses at MetalFace's location
FastFire2("FB.MetalFace.MonoculusSpawner", "ForceSpawn", "", 7.0, false); //Spawn halloween bosses at MetalFace's location
FastFire2("FB.MetalFace.HHHSpawner", "ForceSpawn", "", 9.0, false); //Spawn halloween bosses at MetalFace's location
FastFire2("FB.MetalFace.Invuln", "Disable", "", 123.0, false);
FastFire2("FB.MetalFace.Train", "TeleportToPathTrack", "tank_path_a_250", 126.85, false);
FastFire2("mfTelefect", "Start", "", 127.0, false);
FastFire2("FB.MetalFace.ReturnSND", "PlaySound", "", 127.0, false);
}
case 4:{
//PrintToChatAll("Recognized 3 -> 4, OHSHITOHFUCKOHNO");
AudioManager.ChangeBGM(26);
FastFire2("FB.MetalFace.Train", "TeleportToPathTrack", "MFT3x0", 3.00, false);
FastFire2("FB.MetalFace.GigaBuster", "ForceSpawn", "", 10.0, false);
}
}
}
}
}
}
//For tracking bgm and updating bgm based on player emnity
void TickBGM(){
if (this.shouldTickBGM){
int iBGM0;
int iBGM1;
switch(this.iBossPhase){
case 1:{
iBGM0 = 20;
iBGM1 = 21;
}
case 2:{
iBGM0 = 22;
iBGM1 = 23;
}
case 3:{
iBGM0 = 24;
iBGM1 = 25;
}
case 4:{
iBGM0 = 26;
iBGM1 = 27;
}
}
for (int i = 0; i < MaxClients; i++){
if (EmnityManager[i].IsAboveEmnityThreshold(SuggestEmnityThreshold())) {
CSEClient(i, BGMArray[iBGM1].realPath, BGMArray[iBGM1].SNDLVL, true, 1, 1.0, 100);
CSEClient(i, BGMArray[iBGM0].realPath, BGMArray[iBGM0].SNDLVL, true, 1, 0.05, 100);
}
else {
CSEClient(i, BGMArray[iBGM1].realPath, BGMArray[iBGM1].SNDLVL, true, 1, 0.05, 100);
CSEClient(i, BGMArray[iBGM0].realPath, BGMArray[iBGM0].SNDLVL, true, 1, 1.0, 100);
}
}
AudioManager.indexBGM = iBGM0;
}
}
//Tank buster thing
void TickBuster(){
float cPos[3]; //Client's Position
float pPos[3]; //Ground Particle Target Position
float sPos[3]; //Sign/Arrow's Target Position
float rPos[3];
float fVelocity[3]; //Velocity for teleporting entities, used for angles as well so we don't need two vectors.
int iAirParticle = FindEntityByTargetname("FB.TankBuster.AirParticle", "func_brush");
int iBuster = FindEntityByTargetname("FB.TankBuster", "trigger_hurt");
int iExploParticle = FindEntityByTargetname("FB.TankBuster.ExplodeParticle", "info_particle_system");
int iParticle = FindEntityByTargetname("FB.TankBuster.GroundParticle", "info_particle_system");
int iSign = FindEntityByTargetname("FB.TankBuster.Sign", "func_rotating");
int iSpin = FindEntityByTargetname("FB.TankBuster.Spinner", "func_rotating");
GetClientAbsOrigin(this.bustTarget, cPos);
rPos[0] = cPos[0];
rPos[1] = cPos[1];
rPos[2] = cPos[2] + 50.0;
pPos[0] = cPos[0];
pPos[1] = cPos[1];
pPos[2] = cPos[2] + 25.0;
sPos[0] = cPos[0];
sPos[1] = cPos[1];
sPos[2] = cPos[2] + 150.0;
TeleportEntity(iAirParticle, rPos, fVelocity, fVelocity);
TeleportEntity(iParticle, pPos, fVelocity, fVelocity);
TeleportEntity(iExploParticle, pPos, fVelocity, fVelocity);
TeleportEntity(iBuster, cPos, fVelocity, fVelocity);
TeleportEntity(iSign, sPos, fVelocity, fVelocity);
TeleportEntity(iSpin, pPos, fVelocity, fVelocity);
}
//Tick client post
void TickForClient(int client){
float cPos[3];
GetClientAbsOrigin(client, cPos);
if(GetVectorDistance(cPos, this.fPos) < 500 && client == GetEmnityMax() && this.bDoTankBuster){
char sDamage[32];
this.bustTarget = client;
this.bDoTankBuster = false;
int iHealth = GetClientHealth(this.bustTarget);
Format(sDamage, sizeof(sDamage), "damage %i", RoundToFloor(iHealth * 0.65));
FastFire2("FB.TankBuster", "AddOutput", sDamage, 0.0, false);
FastFire2("FB.TankBusterSND", "PlaySound", "", 1.25, false);
FastFire2("FB.TankBuster.GroundParticle", "Start", "", 0.0, false);
FastFire2("FB.TankBuster.ExplodeSND", "PlaySound", "", 5.50, false);
FastFire2("FB.TankBuster.ExplodeParticle", "Start", "", 5.75, false);
FastFire2("FB.TankBuster.ExplodeParticle", "Stop", "", 9.0, false);
FastFire2("FB.TankBuster", "Enable", "", 5.75, false);
FastFire2("FB.TankBuster", "Disable", "", 6.0, false);
CreateTimer(1.0, StartTickBuster);
PrintToServer("Dropping a tank buster on %N, they have %i HP, the tank buster will do %s.", this.bustTarget, iHealth, sDamage);
CreateTimer(7.0, ResetTickBuster);
}
}
//Boss was slain
void TriggerDeath(){
this.shouldTick = false;
this.tickBuster = false;
this.iBossPhase = 0;
switch(this.bossID){
//Onslaughter lost
case 0: {
}
//Sephiroth lost
case 1:{
}
//Metal Face lost
case 2:{
FastFire2("FB.MetalFace.Train", "TeleportToPathTrack", "MFTHOME", 0.0, false);
}
}
}
//Boss reached bomb hatch
void TriggerVictory(){
this.shouldTick = false;
this.tickBuster = false;
float bossOrigin[3];
float targetOrigin[3];
int targetEnt = FindEntityByTargetname("capturezone_blue", "func_capturezone");
GetEntPropVector(targetEnt, Prop_Send, "m_vecOrigin", targetOrigin);
switch(this.bossID){
//Onslaughter Won
case 0:{
int bossEnt = FindEntityByTargetname("FB.MetalBase", "base_boss");
if(bossEnt == -1) return;
GetEntPropVector(bossEnt, Prop_Send, "m_vecOrigin", bossOrigin);
if (GetVectorDistance(bossOrigin, targetOrigin) < 2200){
//Do something here because Onslaughter is at the pit, victory for boss.
}
}
//Sephiroth Won
case 1:{
}
//Metallizer Won
case 2:{
int bossEnt = FindEntityByTargetname("FB.MetalBase", "base_boss");
if(bossEnt == -1) return;
GetEntPropVector(bossEnt, Prop_Send, "m_vecOrigin", bossOrigin);
if (GetVectorDistance(bossOrigin, targetOrigin) < 2200){
//Do something here because Metal Face is at the pit, victory for boss.
}
}
}
}
//Spawn the boi
void TriggerSpawn(int boss){
this.bossID = boss;
this.shouldTick = true;
switch(boss){
case 0:{
}
case 1:{
}
case 2:{
this.EmitSpawnSound(2);
FastFire2("FB.MetalFace.Train", "TeleportToPathTrack", "MFT0x0", 1.0, false);
FastFire2("FB.MetalFace.SpawnParticle", "Start", "", 1.0, false);
FastFire2("FB.MetalFace.Train", "SetSpeedReal", "1024", 1.0, false);
//switch(GetClientCount(true))
FastFire2("FB.MetalBase", "AddOutput", "health 320000", 0.0, false);
}
}
}
}
BOSSHANDLER BossHandler;
//Player specific async tick process
public Action OnPlayerRunCmd(int client, int &buttons, int &impulse, float vel[3], float angles[3], int &weapon){
if (BossHandler.shouldTick) BossHandler.TickForClient(client);
return Plugin_Continue;
}
stock int SuggestEmnityThreshold(){
switch(GetClientCount(true)){
case 1:{
return 75;
}
case 2:{
return 60;
}
case 3:{
return 50;
}
case 4:{
return 35;
}
case 5:{
return 25;
}
case 6:{
return 20;
}
case 7:{
return 15;
}
case 8,9,10:{
return 10;
}
}
return -1;
}
//Used for emitting boss sounds
public Action QueueBossSound(Handle timer, int sound){
AssLogger(LOGLVL_DEBUG, "QueueBossSound played %i", sound);
switch(sound){
case 2:{
}
case 10:{
CustomSoundEmitter(SFXArray[71].realPath, 65, false, 0, 1.0, 100); //Interrupting
CreateTimer(3.1, QueueBossSound, GetRandomInt(16,22));
}
case 11:{
CustomSoundEmitter(SFXArray[69].realPath, 65, false, 0, 1.0, 100); //FunnyLooking
CreateTimer(3.0, QueueBossSound, GetRandomInt(18, 21));
}
case 12:{
CustomSoundEmitter(SFXArray[75].realPath, 65, false, 0, 1.0, 100); //Racket
CreateTimer(3.2, QueueBossSound, GetRandomInt(16, 22));
}
case 13:{
CustomSoundEmitter(SFXArray[78].realPath, 65, false, 0, 1.0, 100); //WhatDoing
}
case 14:{
CustomSoundEmitter(SFXArray[79].realPath, 65, false, 0, 1.0, 100); //WhateverDoing
CreateTimer(4.3, QueueBossSound, GetRandomInt(16,17));
}
case 15:{
CustomSoundEmitter(SFXArray[72].realPath, 65, false, 0, 1.0, 100); //Join In
CreateTimer(3.2, QueueBossSound, 16);
}
//pt 2
case 16:{
CustomSoundEmitter(SFXArray[70].realPath, 65, false, 0, 1.0, 100); //Good show
}
case 17:{
CustomSoundEmitter(SFXArray[67].realPath, 65, false, 0, 1.0, 100); //Carryon
}
case 18:{
CustomSoundEmitter(SFXArray[66].realPath, 65, false, 0, 1.0, 100); //Carnage
}
case 19:{
CustomSoundEmitter(SFXArray[73].realPath, 65, false, 0, 1.0, 100); //Lets Start
}
case 20:{
CustomSoundEmitter(SFXArray[74].realPath, 65, false, 0, 1.0, 100); //Make Way
}
//Attack sounds, but also shared with spawn sounds
case 21:{
CustomSoundEmitter(SFXArray[76].realPath, 65, false, 0, 1.0, 100); //SliceYou
}
case 22:{
CustomSoundEmitter(SFXArray[77].realPath, 65, false, 0, 1.0, 100); //Stroll
}
//Attack sounds, used for random grunts
case 23:{
CustomSoundEmitter(SFXArray[80].realPath, 65, false, 0, 1.0, 100); //gah
}
case 24:{
CustomSoundEmitter(SFXArray[81].realPath, 65, false, 0, 1.0, 100); //guh
}
case 25:{
CustomSoundEmitter(SFXArray[82].realPath, 65, false, 0, 1.0, 100); //hah
}
//Defeats
case 26:{
CustomSoundEmitter(SFXArray[83].realPath, 65, false, 0, 1.0, 100); //BadSide
}
case 27:{
CustomSoundEmitter(SFXArray[84].realPath, 65, false, 0, 1.0, 100); //NotFair
}
case 28:{
CustomSoundEmitter(SFXArray[85].realPath, 65, false, 0, 1.0, 100); //Nothing
}
case 29:{
CustomSoundEmitter(SFXArray[86].realPath, 65, false, 0, 1.0, 100); //Scream
}
case 30:{
CustomSoundEmitter(SFXArray[87].realPath, 65, false, 0, 1.0, 100); //ToGo
}
//Special attack sounds like phase changes
case 31:{
CustomSoundEmitter(SFXArray[88].realPath, 65, false, 0, 1.0, 100); //Clever
}
case 32:{
CustomSoundEmitter(SFXArray[89].realPath, 65, false, 0, 1.0, 100); //Cmon
}
case 33:{
CustomSoundEmitter(SFXArray[90].realPath, 65, false, 0, 1.0, 100); //Die
}
case 34:{
CustomSoundEmitter(SFXArray[91].realPath, 65, false, 0, 1.0, 100); //GetOff
}
case 35:{
CustomSoundEmitter(SFXArray[92].realPath, 65, false, 0, 1.0, 100); //HearYouScream
}
case 36:{
CustomSoundEmitter(SFXArray[93].realPath, 65, false, 0, 1.0, 100); //IsntOver
}
case 37:{
CustomSoundEmitter(SFXArray[94].realPath, 65, false, 0, 1.0, 100); //Like
}
case 38:{
CustomSoundEmitter(SFXArray[95].realPath, 65, false, 0, 1.0, 100); //Little
}
case 39:{
CustomSoundEmitter(SFXArray[96].realPath, 65, false, 0, 1.0, 100); //Pay
}
case 40:{
CustomSoundEmitter(SFXArray[97].realPath, 65, false, 0, 1.0, 100); //Pointers
}
case 41:{
CustomSoundEmitter(SFXArray[98].realPath, 65, false, 0, 1.0, 100); //Seat
}
case 42:{
CustomSoundEmitter(SFXArray[99].realPath, 65, false, 0, 1.0, 100); //Size
}
case 43:{
CustomSoundEmitter(SFXArray[100].realPath, 65, false, 0, 1.0, 100); //There
}
case 44:{
CustomSoundEmitter(SFXArray[101].realPath, 65, false, 0, 1.0, 100); //TimeToDie
}
case 45:{
CustomSoundEmitter(SFXArray[102].realPath, 65, false, 0, 1.0, 100); //Way
}
//Ultimates
case 46:{
CustomSoundEmitter(SFXArray[103].realPath, 65, false, 0, 1.0, 100); //FinalWords
}
case 47:{
CustomSoundEmitter(SFXArray[104].realPath, 65, false, 0, 1.0, 100); //PartingGift
}
case 48:{
CustomSoundEmitter(SFXArray[105].realPath, 65, false, 0, 1.0, 100); //WatchAndLearn
}
}
return Plugin_Stop;
}
//Teleport all entities to the client every frame
public Action StartTickBuster(Handle timer){
BossHandler.tickBuster = true;
return Plugin_Stop;
}
//Used for stopping tank busters from ticking
public Action ResetTickBuster(Handle time){
BossHandler.tickBuster = false;
float fAirPart[3] = {
-1437.270019,
-3906.739990,
-1334.989990
};
float fVelocity[3];
int iAirParticle = FindEntityByTargetname("FB.TankBuster.AirParticle", "func_brush");
int iBuster = FindEntityByTargetname("FB.TankBuster", "trigger_hurt");
int iExploParticle = FindEntityByTargetname("FB.TankBuster.ExplodeParticle", "info_particle_system");
int iParticle = FindEntityByTargetname("FB.TankBuster.GroundParticle", "info_particle_system");
int iSign = FindEntityByTargetname("FB.TankBuster.Sign", "func_rotating");
int iSpin = FindEntityByTargetname("FB.TankBuster.Spinner", "func_rotating");
TeleportEntity(iAirParticle, fAirPart, fVelocity, fVelocity);
TeleportEntity(iParticle, fAirPart, fVelocity, fVelocity);
TeleportEntity(iExploParticle, fAirPart, fVelocity, fVelocity);
TeleportEntity(iBuster, fAirPart, fVelocity, fVelocity);
TeleportEntity(iSign, fAirPart, fVelocity, fVelocity);
TeleportEntity(iSpin, fAirPart, fVelocity, fVelocity);
return Plugin_Stop;
}
//Spawn metal face
public Action DelayedMetalFace(Handle timer){
AudioManager.indexBGM = 20;
AudioManager.stopBGM = true;
CustomSoundEmitter(SFXArray[68].realPath, 65, false, 0, 1.0, 100); //Evil Laugh
CreateTimer(3.2, QueueBossSound, GetRandomInt(10,14));
sudo(1000);
BossHandler.shouldTickBGM = true;
return Plugin_Stop;
}

View File

@@ -0,0 +1,165 @@
#include <sourcemod>
public Action Command_AOE(int client, int args){
float pos[3];
pos[0] = GetCmdArgFloat(1);
pos[1] = GetCmdArgFloat(2);
pos[2] = GetCmdArgFloat(3);
PrintToChat(client, "pos %f %f %f", pos[0], pos[1], pos[2]);
DispatchCircleAOE(pos);
return Plugin_Handled;
}
public Action Command_SetFogDensity(int client, int args){
tickOnslaughter = true;
char arg1[5];
GetCmdArg(1, arg1, sizeof(arg1));
WeatherManager.fogTarget = StringToFloat(arg1);
PrintToChatAll("Changing fog density to %s", arg1);
return Plugin_Handled;
}
public Action Command_SetFogSEU(int client, int args){
char arg01[5];
char arg02[5];
char arg03[5];
GetCmdArg(1, arg01, sizeof(arg01));
GetCmdArg(2, arg02, sizeof(arg02));
GetCmdArg(3, arg03, sizeof(arg03));
WeatherManager.SetFogStartQueued(arg01);
WeatherManager.SetFogEndQueued(arg02);
if (StringToInt(arg03) == 1) WeatherManager.StartFogTransition();
PrintToChatAll("Received fog start: %s, fog end: %s, begin transition: %s", arg01, arg02, arg03);
return Plugin_Handled;
}
//Get client's stats via command
public Action Command_MyStats(int client, int args) {
int steamID = GetSteamAccountID(client);
if (!Get_Ass_Database() || !steamID || steamID <= 10000) return Plugin_Stop;
char queryID[256];
Format(queryID, sizeof(queryID), "SELECT * from ass_activity WHERE steamid = %i;", steamID);
Get_Ass_Database().Query(MyStats, queryID, client);
return Plugin_Continue;
}
public void MyStats(Database db, DBResultSet results, const char[] error, int client) {
if (!results) {
LogError("Failed to query database: %s", error);
return;
}
char name[64];
char class [64];
int health, healthMax, steamID, damagedealt, damagedealtsession, kills, killssession, deaths, deathssession, bombsreset, bombsresetsession, sacrifices, sacrificessession;
char lastkilledname[128];
char lastusedweapon[128];
char killedbyname[128];
char killedbyweapon[128];
if (results.FetchRow()) {
results.FetchString(0, name, 64); //name
steamID = results.FetchInt(1); //steamid
results.FetchString(4, class, 64); //class
health = results.FetchInt(5); //health
healthMax = results.FetchInt(6); //health
damagedealt = results.FetchInt(7); //damage dealt
damagedealtsession = results.FetchInt(8); //damage dealt session
kills = results.FetchInt(9); //kills
killssession = results.FetchInt(10); //kills session
deaths = results.FetchInt(11); //deaths
deathssession = results.FetchInt(12); //deaths session
bombsreset = results.FetchInt(13); //bombs reset
bombsresetsession = results.FetchInt(14); //bombs reset session
sacrifices = results.FetchInt(15); //sacrifices
sacrificessession = results.FetchInt(16); //sacrifices session
results.FetchString(17, lastkilledname, sizeof(lastkilledname)); //last client killed
results.FetchString(18, lastusedweapon, sizeof(lastusedweapon)); //using weapon
results.FetchString(19, killedbyname, sizeof(killedbyname)); //last client that killed
results.FetchString(20, killedbyweapon, sizeof(killedbyweapon)); //using weapon
CPrintToChat(client, "\x07AAAAAA[CORE] Showing stats of %s [%s, %i/%i hp] || SteamID: %i ", name, class, health, healthMax, steamID);
CPrintToChat(client, "{white}Damage Dealt: %i (Session: %i) || Kills: %i (Session: %i) || Deaths: %i (Session: %i) || Bombs Reset: %i (Session: %i)", damagedealt, damagedealtsession, kills, killssession, deaths, deathssession, bombsreset, bombsresetsession);
CPrintToChat(client, "Sacrifices: %i(Session:%i) || Killed %s (using %s) || Last killed by: %s (using %s)", sacrifices, sacrificessession, lastkilledname, lastusedweapon, killedbyname, killedbyweapon);
}
return;
}
//Fartsy's A.S.S
public Action Command_SacrificePointShop(int client, int args) {
ShowFartsysAss(client);
return Plugin_Handled;
}
//Fartsy's A.S.S
public void ShowFartsysAss(int client) {
CPrintToChat(client, (!core.isWave ? "{darkviolet}[{forestgreen}CORE{darkviolet}] {forestgreen}The sacrificial points counter is currently at %i of %i maximum for this wave." : core.sacPoints <= 9 ? "{darkviolet}[{forestgreen}CORE{darkviolet}] {red}You do not have enough sacrifice points to use this shop. You have %i / 10 required." : ""), core.sacPoints, core.sacPointsMax);
if (!core.isWave || core.sacPoints < 10) return;
Menu menu = new Menu(MenuHandlerFartsysAss, MENU_ACTIONS_DEFAULT);
char buffer[100];
menu.SetTitle("Fartsy's Annihilation Supply Shop");
menu.ExitButton = true;
for (int i = 0; i < RoundToFloor(core.sacPoints / 10.0); i++) menu.AddItem(buffer, ass[i].name);
menu.Display(client, 20);
}
//Also Fartsy's A.S.S
public int MenuHandlerFartsysAss(Menu menu, MenuAction action, int client, int item) {
if (action == MenuAction_Select) {
if (core.sacPoints < ass[item].price) return 0;
if(WeatherManager.TornadoWarning && item == 5){
CPrintToChatAll("{darkred}[Fartsy's Operator] {limegreen}-> {red}%N {darkred}I'm sorry, it is too late for that.. You are doomed...", client);
}
else sudo(ass[item].purchase);
AssLogger(LOGLVL_INFO, "%N opted for %s via the A.S.S.", client, ass[item].name);
} else if (action == MenuAction_End) CloseHandle(menu);
return 0;
}
//Command action definitions
//Get current song
public Action Command_GetCurrentSong(int client, int args) {
char buffer[16];
char tbuffer[16];
int sPos = RoundToFloor(AudioManager.ticksBGM / 66.6666666666);
int tPos = RoundToFloor(AudioManager.refireBGM / 66.6666666666);
Format(buffer, 16, "%02d:%02d", sPos / 60, sPos % 60);
Format(tbuffer, 16, "%02d:%02d", tPos / 60, tPos % 60);
CPrintToChat(client, "The current song is: {limegreen}%s {orange}(%s / %s)", AudioManager.songName, buffer, tbuffer);
return Plugin_Handled;
}
//Determine which bomb has been recently pushed and tell the client if a bomb is ready or not.
public Action Command_FBBombStatus(int client, int args) {
char bombStatusMsg[256];
Format(bombStatusMsg, sizeof(bombStatusMsg), (bombState[0].isMoving ? "{darkviolet}[{forestgreen}CORE{darkviolet}] {white}(%i/%i) Your team is currently pushing a %s!" : bombState[0].isReady ? "{darkviolet}[{forestgreen}CORE{darkviolet}] {white}(%i/%i) Your team's %s is ready!" : "{darkviolet}[{forestgreen}CORE{darkviolet}] {white}(%i/%i) Your team recently deployed a %s! Please wait for the next bomb."), bombState[0].state, bombState[0].stateMax, bombState[RoundToFloor(bombState[0].state / 8.0)].name);
CPrintToChat(client, bombStatusMsg);
return Plugin_Handled;
}
//Return the client to spawn
public Action Command_Return(int client, int args) {
if (!IsPlayerAlive(client)) {
CPrintToChat(client, "{red}[Core] You must be alive to use this command...");
return Plugin_Handled;
}
char name[128];
GetClientName(client, name, sizeof(name));
CPrintToChatAll("{darkviolet}[{forestgreen}CORE{darkviolet}] {white}Client {red}%s {white}began casting {darkviolet}/return{white}.", name);
CustomSoundEmitter(SFXArray[41].realPath, 65, false, 0, 1.0, 100);
CreateTimer(5.0, ReturnClient, client);
return Plugin_Handled;
}
//Return the client to spawn
public Action ReturnClient(Handle timer, int clientID) {
TeleportEntity(clientID, Return, NULL_VECTOR, NULL_VECTOR);
CSEClient(clientID, SFXArray[42].realPath, 65, false, 0, 1.0, 100);
return Plugin_Handled;
}
//Join us on Discord!
public Action Command_Discord(int client, int args) {
CPrintToChat(client, "{darkviolet}[{forestgreen}CORE{darkviolet}] {white}Our Discord server URL is {darkviolet}https://discord.com/invite/ZfUUQWxCmw{white}.");
ShowMOTDPanel(client, "FireHostRedux Discord", "https://discord.com/invite/ZfUUQWxCmw", MOTDPANEL_TYPE_URL);
return Plugin_Handled;
}
//Operator, core of the entire map
public Action Command_Operator(int args) {
char arg1[16];
GetCmdArg(1, arg1, sizeof(arg1));
sudo(StringToInt(arg1));
return Plugin_Continue;
}

View File

@@ -0,0 +1,773 @@
//Fartsy's Scene Enhancer v1.0.0 (Inspired by Mrbt0907/Weather2Remastered)
bool Enhancer_IsWave;
//All background music
enum struct BGM {
char realPath[64];
char songName[64];
int refireTime;
int ticksOffset;
int SNDLVL;
}
BGM BGMArray[32];
//All sound effects
enum struct SFXARRAY {
char realPath[64];
int SNDLVL;
}
SFXARRAY SFXArray[127];
//Sound preference menu
char sndPrefs[][128] = {
"Sounds are currently DISABLED.",
"Sounds are currently MUSIC ONLY.",
"Sounds are currently SOUND EFFECTS ONLY.",
"Sounds are currently ALL ON.",
"Somehow your sound preference was stored as non-existent 5... Please configure your sounds."
};
Handle cvarSNDDefault = INVALID_HANDLE;
int soundPreference[MAXPLAYERS + 1];
//Get client sound prefs
public void SQL_SNDPrefs(Database db, DBResultSet results, const char[] error, int client) {
if (!results) {
LogError("Failed to query database: %s", error);
return;
}
if (!IsValidClient(client)) return;
if (results.FetchRow()) soundPreference[client] = results.FetchInt(0);
}
//Music system rewrite for the 6th time. I will never make a change. My code will never mend. Still everything's the same and it all just fades to math.
enum struct AUDIOMANAGER {
bool bgmPlaying;
bool shouldTick;
bool stopBGM;
bool tickBGMOffset;
char cachedPath[128];
char songName[128];
int indexBGM;
int refireBGM;
int chanBGM;
int ticksBGM;
int VIPBGM;
void ChangeBGM(int bgm){
this.indexBGM = (this.VIPBGM >= 0 ? this.VIPBGM : bgm);
this.ticksBGM = -2;
this.refireBGM = 2;
this.shouldTick = true;
this.tickBGMOffset = BGMArray[this.indexBGM].ticksOffset > 0 ? true : false;
this.stopBGM = (!StrEqual(this.cachedPath, BGMArray[this.indexBGM].realPath) ? true : false);
this.bgmPlaying = true;
if (this.indexBGM >= 20) for (int i = 0; i < MaxClients; i++) for (int s = 19; s < bgm; s++) StopSound(i, this.chanBGM, BGMArray[s].realPath); //Very quick, very dirty, very suboptimal, but gets the job done... This stops all boss music.
}
void Reset() {
this.stopBGM = true;
this.indexBGM = GetRandomInt(1, 4);
this.ticksBGM = -2;
this.refireBGM = 2;
for (int i = 0; i < MaxClients; i++) for (int s = this.indexBGM; s < sizeof(BGMArray); s++) StopSound(i, this.chanBGM, BGMArray[s].realPath); //Very quick, very dirty, very suboptimal, but gets the job done... This stops all boss music.
AssLogger(LOGLVL_DEBUG, "AudioManager has been reset!");
}
void Stop() {
this.bgmPlaying = false;
this.stopBGM = true;
this.ticksBGM = -2;
this.refireBGM = 2;
this.shouldTick = false;
}
void TickBGM() {
this.ticksBGM++;
if (this.ticksBGM >= this.refireBGM) {
if (this.stopBGM){
for (int i = 0; i < MaxClients; ++i) {
StopSound(i, this.chanBGM, this.cachedPath);
this.stopBGM = false;
}
}
if (GetClientCount(true) == 0) {
AssLogger(LOGLVL_INFO, "Server is empty. Music queue stopped.");
this.indexBGM = GetRandomInt(1, 4);
this.Stop();
}
strcopy(this.songName, sizeof(this.songName), BGMArray[this.indexBGM].songName);
this.refireBGM = BGMArray[this.indexBGM].refireTime;
this.ticksBGM = (this.tickBGMOffset ? BGMArray[this.indexBGM].ticksOffset : 0);
CustomSoundEmitter(BGMArray[this.indexBGM].realPath, BGMArray[this.indexBGM].SNDLVL, true, 1, 1.0, 100);
CreateTimer(1.0, SyncMusic, this.indexBGM);
}
}
}
AUDIOMANAGER AudioManager;
//Custom sound emitter, I don't know how many fucking times I've rewritten this! See potato.sp
//int flags:
// SND_NOFLAGS= 0, /**< Nothing */
// SND_CHANGEVOL = 1, /**< Change sound volume */
// SND_CHANGEPITCH = 2, /**< Change sound pitch */
// SND_STOP = 3, /**< Stop the sound */
// SND_SPAWNING = 4, /**< Used in some cases for ambients */
// SND_DELAY = 5, /**< Sound has an initial delay */
// SND_STOPLOOPING = 6, /**< Stop looping all sounds on the entity */
// SND_SPEAKER = 7, /**< Being played by a mic through a speaker */
// SND_SHOULDPAUSE = 8 /**< Pause if game is paused */
void CustomSoundEmitter(char[] sndName, int TSNDLVL, bool isBGM, int flags, float vol, int pitch) {
for (int i = 1; i <= MaxClients; i++) {
if (!IsValidClient(i)) continue;
if (isBGM && (soundPreference[i] == 1 || soundPreference[i] == 3) || !isBGM && soundPreference[i] >= 2) EmitSoundToClient(i, sndName, _, AudioManager.chanBGM, TSNDLVL, flags, vol, pitch, _, _, _, _, _);
}
}
//Play sound to client. Ripped straight from potato. Allows us to play sounds directly to people when they join.
void CSEClient(int client, char[] sndName, int TSNDLVL, bool isBGM, int flags, float vol, int pitch) {
if (!IsValidClient(client)) return;
if (isBGM && (soundPreference[client] == 1 || soundPreference[client] == 3) || !isBGM && soundPreference[client] >= 2) EmitSoundToClient(client, sndName, _, AudioManager.chanBGM, TSNDLVL, flags, vol, pitch, _, _, _, _, _);
}
//VIP Music Menu
public Action Command_Music(int client, int args) {
int steamID = GetSteamAccountID(client);
if (!steamID || steamID <= 10000) return Plugin_Handled;
else ShowFartsyMusicMenu(client);
return Plugin_Handled;
}
//VIP Music Menu
public void ShowFartsyMusicMenu(int client) {
Menu menu = new Menu(MenuHandlerFartsyMusic, MENU_ACTIONS_DEFAULT);
char buffer[100];
menu.SetTitle("FartsysAss Music Menu");
for (int i = 0; i < sizeof(BGMArray); i++) menu.AddItem(buffer, BGMArray[i].songName);
menu.Display(client, 20);
menu.ExitButton = true;
}
//Set Fartsy Sound menu
public void FartsysSNDSelected(int client, CookieMenuAction action, any info, char[] buffer, int maxlen) {
if (action == CookieMenuAction_SelectOption) ShowFartsyMenu(client);
}
// Get clients sound preferences then send them the menu
public Action Command_Sounds(int client, int args) {
int steamID = GetSteamAccountID(client);
if (!steamID || steamID <= 10000) return Plugin_Handled;
else {
char queryID[256];
Format(queryID, sizeof(queryID), "SELECT soundprefs from ass_activity WHERE steamid = '%d';", steamID);
Get_Ass_Database().Query(SQL_SNDPrefs, queryID, client);
ShowFartsyMenu(client);
PrintToChat(client, sndPrefs[soundPreference[client]]);
return Plugin_Handled;
}
}
//Send client sound menu
public void ShowFartsyMenu(int client) {
Menu menu = new Menu(MenuHandlerFartsy, MENU_ACTIONS_DEFAULT);
char buffer[100];
menu.SetTitle("FartsysAss Sound Menu");
menu.AddItem(buffer, "Disable ALL");
menu.AddItem(buffer, "Music Only");
menu.AddItem(buffer, "Sound Effects Only");
menu.AddItem(buffer, "Enable ALL");
menu.Display(client, 20);
menu.ExitButton = true;
}
// Handle client choices for sound preference
public int MenuHandlerFartsy(Menu menu, MenuAction action, int param1, int param2) {
if (action == MenuAction_Select) {
char query[256];
int steamID = GetSteamAccountID(param1);
if (!Get_Ass_Database() || !steamID) return 0;
else {
Format(query, sizeof(query), "UPDATE ass_activity SET soundprefs = '%i' WHERE steamid = '%d';", param2, steamID);
Get_Ass_Database().Query(Database_FastQuery, query);
soundPreference[param1] = param2;
Command_Sounds(param1, 0);
}
} else if (action == MenuAction_End) CloseHandle(menu);
return 0;
}
//Restart music for the new client
public Action RefireMusicForClient(Handle timer, int client) {
if (IsValidClient(client)) {
if (GetClientTeam(client) == 0) CreateTimer(1.0, RefireMusicForClient, client);
else if (GetClientTeam(client) == 2) CSEClient(client, BGMArray[AudioManager.indexBGM].realPath, BGMArray[AudioManager.indexBGM].SNDLVL, true, 1, 1.0, 100);
}
return Plugin_Stop;
}
//Light Entities
bool g_PowerOutage;
enum struct MAPLIGHTING {
bool hasCustomPattern;
bool isBroken;
char arcs[32];
char beam[32];
char buzz[32];
char explosion[35];
char light[32];
char status[32];
char stun[32];
char zap[32];
void Explode(){
if(this.isBroken) return;
this.isBroken = true;
FastFire2(this.arcs, "StartSpark", "", 0.0, false);
FastFire2(this.arcs, "StartSpark", "", 0.1, false);
FastFire2(this.beam, "LightOff", "", 0.0, false);
FastFire2(this.buzz, "PlaySound", "", 0.0, false);
FastFire2(this.explosion, "Explode", "", 0.0, false);
FastFire2(this.light, "TurnOff", "", 0.0, false);
FastFire2(this.status, "Color", "255 0 0", 0.0, false);
FastFire2(this.stun, "Enable", "", 0.0, false);
FastFire2(this.zap, "Enable", "", 0.0, false);
}
void Repair(){
this.isBroken = false;
FastFire2(this.arcs, "StopSpark", "", 0.0, false);
FastFire2(this.buzz, "StopSound", "", 0.25, false);
FastFire2(this.status, "Color", "0 255 0", 0.0, false);
FastFire2(this.stun, "Disable", "", 0.0, false);
FastFire2(this.zap, "Disable", "", 0.0, false);
if(!g_PowerOutage) {
FastFire2(this.light, "SetPattern", "", 0.0, false);
FastFire2(this.light, "TurnOff", "", 0.0, false);
FastFire2(this.light, "TurnOn", "", 0.1, false);
FastFire2(this.light, "SetPattern", "", 0.1, false);
FastFire2(this.beam, "LightOff", "", 0.1, false);
FastFire2(this.beam, "LightOn", "", 0.2, false);
}
}
void RestorePower(){
if(!this.isBroken || strcmp(this.light, "MapLighting.StreetLamp0C.light") == 0){
FastFire2(this.light, "TurnOn", "", 0.0, false);
FastFire2(this.beam, "LightOn", "", 0.0, false);
FastFire2(this.beam, "LightOn", "", 1.0, false);
FastFire2(this.beam, "LightOn", "", 3.0, false);
FastFire2(this.light, "SetPattern", "", 0.0, false);
this.hasCustomPattern = false;
}
}
}
MAPLIGHTING MapLighting[15];
//Weather Manager
BULKFIRE lightningStrike[16];
BULKFIRE lightningFlash[13];
enum struct WEATHERMANAGER {
bool canTornado;
bool hasTornado;
bool powerSurging;
bool sirenExplode;
bool sirenExploded;
bool tickWeather;
bool TornadoTimerActive;
bool TornadoWarning;
char defFogStartDist[5];
char defFogEndDist[5];
char defRainDensity;
char rainDensity;
float fogDensity;
float defFogDensity;
float fogTarget;
float fogChangeRate;
float sirenPitch;
float sirenPitchRate;
float sirenPitchTarget;
int intensity;
int mIntensity;
void Activate(){
this.Reset();
sudo(1001); //Stop any BGM
FastFire2("Weather.Sky", "Enable", "", 0.0, false);
this.tickWeather = true;
this.PerformRandomWeather(); //Start weather system
}
void doLightning(){
sudo(1003);
FastFire2(lightningStrike[GetRandomInt(0, sizeof(lightningStrike)-1)].fireStr, "", "", 0.0, true);
FastFire2("Weather.LightningHurt*", "Disable", "", 0.07, false);
CustomSoundEmitter(SFXArray[GetRandomInt(27, 34)].realPath, 65, false, 0, 1.0, 100);
//Affect lights
int i = GetRandomInt(this.intensity, 15);
AssLogger(LOGLVL_DEBUG, "Doing light interactions with %i", i);
switch(i){
case 2,3,5:{
int index = GetRandomInt(0, 12);
float f = GetRandomFloat(0.5, 3.0);
FastFire2(MapLighting[index].light, "TurnOff", "", 0.0, false);
FastFire2(MapLighting[index].beam, "LightOff", "", 0.0, false);
FastFire2(MapLighting[index].light, "TurnOn", "", f, false);
FastFire2(MapLighting[index].beam, "LightOn", "", f, false);
}
case 11,15:{
g_PowerOutage = true;
if(!this.hasTornado) CreateTimer(GetRandomFloat(5.0, 30.0), RestorePower, GetRandomInt(0, 3));
FastFire2("MapLighting.*", "LightOff", "", 0.0, false);
FastFire2("MapLighting.*", "TurnOff", "", 0.0, false);
FastFire2("MapLighting.*", "LightOff", "", 1.0, false);
FastFire2("MapLighting.*", "LightOff", "", 2.0, false);
FastFire2("MapLighting.*", "LightOff", "", 3.0, false);
FastFire2("MapLighting.*", "LightOff", "", 4.0, false);
FastFire2("MapLighting.*", "LightOff", "", 5.0, false);
}
}
}
void Dissipate(){
this.sirenPitchTarget = 0.0;
this.sirenPitchRate = 0.25;
this.fogTarget = this.defFogDensity;
g_PowerOutage = false;
this.hasTornado = false;
if(Enhancer_IsWave){
this.mIntensity = 5;
this.intensity = 7;
} else {
this.mIntensity = 0;
this.intensity = 0;
}
if (this.sirenExploded) {
this.sirenPitch = 0.0;
this.sirenExploded = false;
}
this.TornadoWarning = false;
CreateTimer(GetRandomFloat(45.0, 135.0), ResetTornado);
for (int i = 0; i < sizeof(MapLighting); i++) if (!MapLighting[i].isBroken) FastFire2(MapLighting[i].light, "TurnOn", "", 0.0, false);
FastFire2("Weather.FogOutdoor", "SetStartDistLerp", this.defFogStartDist, 0.0, false);
FastFire2("Weather.FogOutdoor", "SetEndDistLerp", this.defFogEndDist, 0.0, false);
FastFire2("Weather.FogOutdoor", "StartFogTransition", "", 0.0, false);
FastFire2("tornadof1", "Stop", "", 0.0, false);
FastFire2("TornadoKill", "Disable", "", 0.0, false);
FastFire2("tornadof1wind", "Disable", "", 0.0, false);
FastFire2("tornadowindf1", "StopSound", "", 0.0, false);
FastFire2("shaketriggerf1", "Disable", "", 0.0, false);
FastFire2("tornadobutton", "Unlock", "", 30.0, false);
FastFire2("FB.FakeTankTank01", "Kill", "", 0.0, false);
FastFire2("FB.FakeTankPhys01", "Kill", "", 0.0, false);
FastFire2("Weather.EASScreen", "Disable", "", 0.0, false);
FastFire2("Weather.Siren.ExplodeParticle", "Stop", "", 0.0, false);
FastFire2("Weather.Siren", "StopSound", "", 5.0, false);
}
void FormTornado(){
this.hasTornado = true;
this.mIntensity = 15;
this.intensity = 15;
CreateTimer(1.5, TornadoShaker);
FastFire2("TornadoKill", "Enable", "", 0.0, false);
FastFire2("tornadobutton", "Lock", "", 0.0, false);
FastFire2("tornadof1", "Start", "", 20.0, false);
FastFire2("shaketriggerf1", "Enable", "", 20.0, false);
FastFire2("tornadowindf1", "PlaySound", "", 20.0, false);
FastFire2("tornadof1wind", "Enable", "", 21.50, false);
float f = GetRandomFloat(60.0, 120.0);
CreateTimer(f, TimedOperator, 42);
}
void IssueTornadoWarning(){
this.TornadoWarning = true;
this.sirenPitchTarget = 100.0;
this.sirenPitchRate = 0.1;
FastFire2("Weather.EASScreen", "Enable", "", 0.0, false);
FastFire2("Weather.EAS", "PlaySound", "", 0.0, false);
CreateTimer(GetRandomFloat(1.0, 3.0), ModulateSiren);
}
void PerformRandomWeather(){
if (!this.tickWeather) return;
AssLogger(LOGLVL_DEBUG, "[Fartsy's Enhancer] Storm Intensity @ %f% (%i)", (this.intensity / 15.0), this.intensity);
this.doLightning();
float flStormMin;
float flStormMax;
switch(GetRandomInt(this.mIntensity, this.intensity)){
case 0:{
this.SetFogStartQueued("500");
this.SetFogEndQueued("3000");
this.StartFogTransition();
flStormMin = 15.0;
flStormMax = 35.0;
this.fogTarget = 0.55;
FastFire2("rain", "Alpha", "15", 0.0, false);
CustomSoundEmitter(SFXArray[108].realPath, 65, false, 1, 0.1, 100); //Rain, no wind, reduced volume
}
case 1:{
this.SetFogStartQueued("500");
this.SetFogEndQueued("2700");
this.StartFogTransition();
flStormMin = 12.0;
flStormMax = 32.0;
this.fogTarget = 0.60;
FastFire2("rain", "Alpha", "30", 0.0, false);
CustomSoundEmitter(SFXArray[108].realPath, 65, false, 1, 0.1, 100); //Rain, no wind, reduced volume
}
case 2:{
this.SetFogStartQueued("500");
this.SetFogEndQueued("2500");
this.StartFogTransition();
this.mIntensity = 1;
flStormMin = 12.0;
flStormMax = 30.0;
FastFire2("rain", "Alpha", "50", 0.0, false);
CustomSoundEmitter(SFXArray[108].realPath, 65, false, 1, 0.1, 100); //Rain, no wind, increased volume
}
case 3:{
this.SetFogStartQueued("500");
this.SetFogEndQueued("2500");
this.StartFogTransition();
flStormMin = 10.0;
flStormMax = 28.5;
this.fogTarget = 0.70;
FastFire2("rain", "Alpha", "65", 0.0, false);
CustomSoundEmitter(SFXArray[108].realPath, 65, false, 1, 0.1, 100); //Rain, no wind, increased volume
}
case 4:{
flStormMin = 9.0;
flStormMax = 26.5;
FastFire2("rain", "Alpha", "75", 0.0, false);
CustomSoundEmitter(SFXArray[108].realPath, 65, false, 1, 1.0, 100); //Rain, no wind, increased volume
CustomSoundEmitter(SFXArray[107].realPath, 65, false, 1, 0.1, 100); //Rain, wind, decreased volume
CustomSoundEmitter(SFXArray[109].realPath, 65, false, 1, 0.01, 100); //Extra wind
}
case 5:{
this.SetFogStartQueued("500");
this.SetFogEndQueued("2100");
this.StartFogTransition();
this.mIntensity = 3;
flStormMin = 7.0;
flStormMax = 25.0;
this.fogTarget = 0.75;
FastFire2("rain", "Alpha", "95", 0.0, false);
CustomSoundEmitter(SFXArray[108].realPath, 65, false, 1, 0.1, 100); //Rain, no wind, decreased volume
CustomSoundEmitter(SFXArray[107].realPath, 65, false, 1, 0.15, 100); //Rain, wind
CustomSoundEmitter(SFXArray[109].realPath, 65, false, 1, 0.05, 100); //Extra wind
}
case 6:{
this.mIntensity = 4;
flStormMin = 7.0;
flStormMax = 23.5;
FastFire2("rain", "Alpha", "125", 0.0, false);
CustomSoundEmitter(SFXArray[108].realPath, 65, false, 1, 0.05, 100); //Rain, no wind, decreased volume
CustomSoundEmitter(SFXArray[107].realPath, 65, false, 1, 0.21, 100); //Rain, wind, increased volume
CustomSoundEmitter(SFXArray[109].realPath, 65, false, 1, 0.125, 100); //Extra wind
}
case 7:{
this.SetFogStartQueued("500");
this.SetFogEndQueued("2000");
this.StartFogTransition();
flStormMin = 6.0;
flStormMax = 21.0;
this.fogTarget = 0.80;
FastFire2("rain", "Alpha", "155", 0.0, false);
CreateTimer(GetRandomFloat(0.1, 1.25), GetRandomWind, 0);
CustomSoundEmitter(SFXArray[108].realPath, 65, false, 1, 0.05, 100); //Rain, no wind, decreased volume
CustomSoundEmitter(SFXArray[107].realPath, 65, false, 1, 0.26, 100); //Rain, wind, increased volume
CustomSoundEmitter(SFXArray[109].realPath, 65, false, 1, 0.25, 100); //Extra wind
}
case 8:{
this.mIntensity = 6;
this.SetFogStartQueued("470");
this.SetFogEndQueued("2000");
this.StartFogTransition();
flStormMin = 5.0;
flStormMax = 20.0;
this.fogTarget = 0.875;
FastFire2("rain", "Alpha", "175", 0.0, false);
CreateTimer(GetRandomFloat(0.1, 1.25), GetRandomWind, 1);
CustomSoundEmitter(SFXArray[107].realPath, 65, false, 1, 0.37, 100); //Rain, wind, increased volume
CustomSoundEmitter(SFXArray[109].realPath, 65, false, 1, 0.35, 100); //Extra wind
}
case 9:{
this.SetFogStartQueued("425");
this.SetFogEndQueued("1500");
this.StartFogTransition();
this.mIntensity = 7;
flStormMin = 5.0;
flStormMax = 19.0;
FastFire2("rain", "Alpha", "200", 0.0, false);
CreateTimer(GetRandomFloat(0.1, 1.25), GetRandomWind, 2);
CustomSoundEmitter(SFXArray[107].realPath, 65, false, 1, 0.41, 100); //Rain, wind, increased volume
CustomSoundEmitter(SFXArray[109].realPath, 65, false, 1, 0.42, 100); //Extra wind
}
case 10:{
this.SetFogStartQueued("375");
this.SetFogEndQueued("1500");
this.StartFogTransition();
flStormMin = 5.0;
flStormMax = 18.0;
this.fogTarget = 0.925;
FastFire2("rain", "Alpha", "215", 0.0, false);
CreateTimer(GetRandomFloat(0.1, 1.25), GetRandomWind, 3);
CustomSoundEmitter(SFXArray[107].realPath, 65, false, 1, 0.45, 100); //Rain, wind, increased volume
CustomSoundEmitter(SFXArray[109].realPath, 65, false, 1, 0.56, 100); //Extra wind
}
case 11:{
this.mIntensity = 9;
flStormMin = 5.0;
flStormMax = 17.0;
FastFire2("rain", "Alpha", "235", 0.0, false);
CreateTimer(GetRandomFloat(0.1, 1.25), GetRandomWind, 4);
CustomSoundEmitter(SFXArray[107].realPath, 65, false, 1, 0.63, 100); //Rain, wind, increased volume
CustomSoundEmitter(SFXArray[109].realPath, 65, false, 1, 0.69, 100); //Extra wind
}
case 12:{
this.mIntensity = 10;
flStormMin = 5.0;
flStormMax = 15.0;
this.fogTarget = 1.0;
this.SetFogStartQueued("225");
this.SetFogEndQueued("700");
this.StartFogTransition();
FastFire2("rain", "Alpha", "255", 0.0, false);
CreateTimer(GetRandomFloat(0.1, 1.25), GetRandomWind, 5);
CustomSoundEmitter(SFXArray[107].realPath, 65, false, 1, 0.72, 100); //Rain, wind, increased volume
CustomSoundEmitter(SFXArray[109].realPath, 65, false, 1, 0.76, 100); //Extra wind
if (!this.TornadoTimerActive) sudo(1004);
}
case 13:{
this.SetFogStartQueued("200");
this.SetFogEndQueued("700");
this.StartFogTransition();
this.mIntensity = 12;
flStormMin = 5.0;
flStormMax = 14.0;
this.fogTarget = 1.0;
FastFire2("rain", "Alpha", "255", 0.0, false);
CreateTimer(GetRandomFloat(0.1, 1.25), GetRandomWind, 6);
CustomSoundEmitter(SFXArray[107].realPath, 65, false, 1, 0.85, 100); //Rain, wind, increased volume
CustomSoundEmitter(SFXArray[109].realPath, 65, false, 1, 0.83, 100); //Extra wind
if (!this.TornadoTimerActive) sudo(1004);
}
case 14:{
this.mIntensity = 13;
this.SetFogStartQueued("100");
this.SetFogEndQueued("700");
this.StartFogTransition();
flStormMin = 5.0;
flStormMax = 13.0;
this.fogTarget = 1.0;
FastFire2("rain", "Alpha", "255", 0.0, false);
CreateTimer(GetRandomFloat(0.1, 1.25), GetRandomWind, 7);
CustomSoundEmitter(SFXArray[107].realPath, 65, false, 1, 0.9, 100); //Rain, wind, increased volume
CustomSoundEmitter(SFXArray[109].realPath, 65, false, 1, 0.92, 100); //Extra wind
if (!this.TornadoTimerActive) sudo(1004);
}
case 15:{
this.mIntensity = 14;
this.SetFogStartQueued("50");
this.SetFogEndQueued("500");
this.StartFogTransition();
flStormMin = 5.0;
flStormMax = 12.0;
this.fogTarget = 1.0;
FastFire2("rain", "Alpha", "255", 0.0, false);
CreateTimer(GetRandomFloat(0.1, 1.25), GetRandomWind, 7);
CustomSoundEmitter(SFXArray[107].realPath, 65, false, 1, 1.0, 100); //Rain, wind, increased volume
CustomSoundEmitter(SFXArray[109].realPath, 65, false, 1, 1.0, 100); //Extra wind
if (!this.TornadoTimerActive) sudo(1004);
}
default:{
}
}
CreateTimer(GetRandomFloat(flStormMin, flStormMax), GetRandomWeather);
}
void Reset(){
AssLogger(LOGLVL_DEBUG, "[Fartsy's Enhancer] WeatherManager has been reset!");
this.fogDensity = 0.50;
this.Dissipate();
this.tickWeather = false;
FastFire2("rain", "Alpha", "0", 0.0, false);
}
void SetFogStartQueued(const char[] fsq){
FastFire2("Weather.FogOutdoor", "SetStartDistLerpTo", fsq, 0.0, false);
}
void SetFogEndQueued(const char[] feq){
FastFire2("Weather.FogOutdoor", "SetEndDistLerpTo", feq, 0.0, false);
}
void StartFogTransition(){
FastFire2("Weather.FogOutdoor", "StartFogTransition", "", 0.0, false);
}
void TickFogDensity(){
if(this.fogDensity != this.fogTarget){
char targetDensity[24];
this.fogDensity = (this.fogDensity < this.fogTarget) ? FloatMin(this.fogDensity+=this.fogChangeRate, this.fogTarget) : FloatMax(this.fogDensity-=this.fogChangeRate, this.fogTarget);
FloatToString(this.fogDensity, targetDensity, sizeof(targetDensity));
FastFire2("Weather.FogOutdoor", "SetMaxDensity", targetDensity, 0.0, false);
}
}
void TickSiren(){
if(this.TornadoWarning){
if(!this.sirenExploded && (this.sirenPitch > 165.0)){
FastFire2("Weather.Siren", "Pitch", "50", 0.0, false);
FastFire2("Weather.Siren", "Pitch", "40", 0.1, false);
FastFire2("Weather.Siren", "Pitch", "30", 0.2, false);
FastFire2("Weather.Siren", "Pitch", "20", 0.3, false);
FastFire2("Weather.Siren", "Pitch", "10", 0.4, false);
FastFire2("Weather.Siren", "Pitch", "0", 0.5, false);
FastFire2("Weather.Siren.ExplodeParticle", "Start", "", 0.0, false);
FastFire2("Weather.Siren.ExplodeSND", "PlaySound", "", 0.0, false);
FastFire2("Weather.Siren", "StopSound", "", 5.0, false);
FastFire2("Weather.Siren.ExplodeParticle", "Stop", "", 5.0, false);
FastFire2("Weather.Siren.ExplodeParticle", "Start", "", 5.1, false);
this.sirenExploded = true;
}
if(this.sirenPitch != this.sirenPitchTarget && !this.sirenExploded){
char targetPitch[24];
this.sirenPitch = (this.sirenPitch < this.sirenPitchTarget) ? FloatMin(this.sirenPitch+=this.sirenPitchRate, this.sirenPitchTarget) : FloatMax(this.sirenPitch-=this.sirenPitchRate, this.sirenPitchTarget);
FloatToString(this.sirenPitch, targetPitch, sizeof(targetPitch));
FastFire2("Weather.Siren", "Pitch", targetPitch, 0.0, false);
PrintToServer("SirenPitch = %s", targetPitch);
}
}
}
}
WEATHERMANAGER WeatherManager;
//Ghosties
enum struct GHOSTHANDLER {
bool placeholder;
void SpawnRandom(){
switch(GetRandomInt(0,3)){
case 0:{
FastFire2("gTrain", "TeleportToPathTrack", "gPath00_0", 0.0, false);
}
case 1:{
FastFire2("gTrain", "TeleportToPathTrack", "gPath01_0", 0.0, false);
}
case 2:{
FastFire2("gTrain", "TeleportToPathTrack", "gPath02_0", 0.0, false);
}
case 3:{
FastFire2("gTrain", "TeleportToPathTrack", "gPath03_0", 0.0, false);
}
}
}
}
GHOSTHANDLER GhostHandler;
//Timers
public Action GetRandomWeather(Handle timer){
if(WeatherManager.tickWeather){
switch(GetRandomInt (0, 10)){
case 0,4,8:{
if(WeatherManager.intensity > 9) GhostHandler.SpawnRandom();
if (WeatherManager.intensity > 0 && (WeatherManager.intensity-1 > WeatherManager.mIntensity)) WeatherManager.intensity--;
}
case 1,2,3,5,6,7,9,10:{
if (WeatherManager.intensity < 15) WeatherManager.intensity++;
}
}
WeatherManager.PerformRandomWeather();
}
return Plugin_Stop;
}
public Action GetRandomWind(Handle timer, int intensity){
switch(intensity){
case 0:{
CustomSoundEmitter(SFXArray[GetRandomInt(113, 114)].realPath, 65, true, 1, 0.125, 100);
}
case 1:{
CustomSoundEmitter(SFXArray[GetRandomInt(113, 114)].realPath, 65, true, 1, 0.20, 100);
}
case 2:{
CustomSoundEmitter(SFXArray[GetRandomInt(113, 114)].realPath, 65, true, 1, 0.30, 100);
}
case 3:{
CustomSoundEmitter(SFXArray[GetRandomInt(113, 115)].realPath, 65, true, 1, 0.45, 100);
}
case 4:{
CustomSoundEmitter(SFXArray[GetRandomInt(113, 115)].realPath, 65, true, 1, 0.55, 100);
}
case 5:{
CustomSoundEmitter(SFXArray[GetRandomInt(113, 115)].realPath, 65, true, 1, 0.65, 100);
}
case 6:{
CustomSoundEmitter(SFXArray[GetRandomInt(113, 116)].realPath, 65, true, 1, 0.80, 100);
}
case 7:{
CustomSoundEmitter(SFXArray[GetRandomInt(113, 116)].realPath, 65, true, 1, 1.0, 100);
}
}
return Plugin_Stop;
}
public Action ModulateSiren(Handle timer){
if(WeatherManager.TornadoWarning && !WeatherManager.sirenExplode){
WeatherManager.sirenPitchTarget = WeatherManager.powerSurging ? GetRandomFloat(95.0, 210.0) : GetRandomFloat(85.0, 125.0);
WeatherManager.sirenPitchRate = WeatherManager.powerSurging ? GetRandomFloat(0.0525, 0.20) : GetRandomFloat(0.01, 0.125);
CreateTimer(GetRandomFloat(1.0, 3.0), ModulateSiren);
}
return Plugin_Stop;
}
public Action ResetTornado(Handle timer){
WeatherManager.canTornado = true;
WeatherManager.TornadoTimerActive = false;
return Plugin_Stop;
}
public Action RestorePower(Handle timer, int surge){
g_PowerOutage = false;
WeatherManager.powerSurging = ((surge == 1) ? true : false);
if (surge == 1){
CreateTimer(1.0, SurgePower);
}
for (int i = 0; i < sizeof(MapLighting); i++) MapLighting[i].RestorePower();
FastFire2("MapLighting.Indoor*", "TurnOn", "", 0.0, false);
FastFire2("MapLighting.Indoor*", "LightOn", "", 0.0, false);
return Plugin_Stop;
}
char LightingPatterns[][25] = {
/////Allistor/////
"sduehrjkihwerte",
"ihqopeiruhiqwer",
"sadnpiudghsfiod",
"kjahbfihkabweoi",
"djfohoaeiufgawt",
"ewrtyvghbvfczfr",
"aesrergtafdcgvz",
"aeradyjdghnyjxc",
"oihaecpnefijanle",
"oaihbewrpoijnae",
//////Jeffy///////
"gewsaadgfhgtfsr",
"kuyijyterytdfsadfvgzs",
"bvcxfgtertyaetr",
"gyukkjtyasde",
"bxcvmvbnhkgfj",
"ewrhrtmhgjf",
"bfgmghntjy",
"afsdgdsfayrwte",
"hfgjgfdiyet",
"fsdbvxfgkytestry"
};
public Action SurgePower(Handle timer){
if (WeatherManager.powerSurging){
int target = GetRandomInt(0, 12);
if (MapLighting[target].isBroken) target = GetRandomInt(0, 12);
if(!MapLighting[target].isBroken){
if (GetRandomInt(0, 7) == 5) MapLighting[target].Explode();
FastFire2(MapLighting[target].light, "SetPattern", LightingPatterns[GetRandomInt(0, 19)], 0.0, false);
FastFire2(MapLighting[target].light, "TurnOn", "", 0.0, false);
FastFire2(MapLighting[target].beam, "LightOn", "", 0.0, false);
CreateTimer(GetRandomFloat(7.5, 15.0), RestorePower, 0);
CreateTimer(GetRandomFloat(0.1, 3.0), SurgePower);
CreateTimer(GetRandomFloat(1.5, 2.0), SurgePowerFX);
}
}
return Plugin_Stop;
}
public Action SurgePowerFX(Handle timer){
for (int i = 0; i < sizeof(MapLighting); i++){
if(WeatherManager.powerSurging && !MapLighting[i].isBroken){
FastFire2(MapLighting[i].light, "SetPattern", LightingPatterns[GetRandomInt(0, 19)], 0.0, false);
FastFire2(MapLighting[i].beam, "LightOff", "", 0.0, false);
FastFire2(MapLighting[i].beam, "LightOn", "", GetRandomFloat(0.1, 0.35), false);
FastFire2(MapLighting[i].beam, "LightOff", "", GetRandomFloat(0.4, 0.75), false);
FastFire2(MapLighting[i].beam, "LightOn", "", GetRandomFloat(1.0, 1.35), false);
}
}
return Plugin_Stop;
}
public Action TornadoShaker(Handle timer){
if(WeatherManager.hasTornado){
FastFire2("tornadoshake_f1", "StartShake", "", 0.0, false);
CreateTimer(1.5, TornadoShaker);
}
return Plugin_Stop;
}

View File

@@ -0,0 +1,250 @@
//Sync client stats when they leave
public void OnClientDisconnect(int client) {
//Database Ass_Database = Get_Ass_Database();
int steamID = GetSteamAccountID(client);
if (steamID) {
iDmgHealingTotal -= EmnityManager[client].iDamage;
iDmgHealingTotal -= EmnityManager[client].iHealing;
}
if (!Ass_Database || !steamID || steamID <= 10000) return;
char query[256];
char clientName[128];
GetClientInfo(client, "name", clientName, 128);
Format(query, sizeof(query), "INSERT INTO ass_activity (name, steamid, date, seconds) VALUES ('%s', %d, CURRENT_DATE, %d) ON DUPLICATE KEY UPDATE name = '%s', seconds = seconds + VALUES(seconds);", clientName, steamID, GetClientMapTime(client), clientName);
Ass_Database.Query(Database_FastQuery, query);
}
//Check who spawned and log their class
public Action EventSpawn(Event Spawn_Event, const char[] Spawn_Name, bool Spawn_Broadcast) {
int client = GetClientOfUserId(Spawn_Event.GetInt("userid"));
if (IsValidClient(client)) {
int class = Spawn_Event.GetInt("class");
int steamID = GetSteamAccountID(client);
if (!Ass_Database || !steamID || !class) return Plugin_Handled;
char strClass[32];
char query[256];
strClass = ClassDefinitions[class - 1];
Format(query, sizeof(query), "UPDATE ass_activity SET class = '%s' WHERE steamid = %i;", strClass, steamID);
Ass_Database.Query(Database_FastQuery, query);
}
return Plugin_Handled;
}
//Log Damage!
public void Event_PlayerHurt(Handle event, const char[] name, bool dontBroadcast) {
int client = GetClientOfUserId(GetEventInt(event, "userid"));
int attacker = GetClientOfUserId(GetEventInt(event, "attacker"));
int damage = GetEventInt(event, "damageamount");
if (IsValidClient(attacker) && attacker != client) {
int steamID = GetSteamAccountID(attacker);
if (!Ass_Database || !steamID) return;
PrintToServer("Adding Damage %i dealt by %N, with index %i", damage, attacker, attacker);
int healer = GetHealerOfClient(attacker);
if (healer != -1){
EmnityManager[healer].iDamage += RoundToFloor(damage * 0.35);
iDmgHealingTotal += RoundToFloor(damage * 0.35);
}
EmnityManager[attacker].iDamage += damage;
iDmgHealingTotal += damage;
char query[256];
Format(query, sizeof(query), "UPDATE ass_activity SET damagedealt = damagedealt + %i, damagedealtsession = damagedealtsession + %i WHERE steamid = %i;", damage, damage, steamID);
Ass_Database.Query(Database_FastQuery, query);
}
}
//Check who died by what and announce it to chat.
public Action EventDeath(Event Spawn_Event, const char[] Spawn_Name, bool Spawn_Broadcast) {
int client = GetClientOfUserId(Spawn_Event.GetInt("userid"));
int attacker = GetClientOfUserId(Spawn_Event.GetInt("attacker"));
int steamid = GetSteamAccountID(client);
if(steamid){
iDmgHealingTotal -= EmnityManager[client].iDamage;
iDmgHealingTotal -= EmnityManager[client].iHealing;
EmnityManager[client].iBossDamage = 0;
EmnityManager[client].iDamage = 0;
EmnityManager[client].iHealing = 0;
}
char name[64];
char weapon[32];
Format(name, sizeof(name), attacker == 0 ? "[INTENTIONAL GAME DESIGN]" : "%N", IsValidClient(attacker) ? client : attacker);
Spawn_Event.GetString("weapon", weapon, sizeof(weapon));
if (0 < client <= MaxClients && IsClientInGame(client)) {
int damagebits = Spawn_Event.GetInt("damagebits");
if (IsValidClient(attacker) && core.sacrificedByClient) SacrificeClient(client, attacker, core.bombReset);
if (!attacker) {
switch (damagebits) {
case 1: { //CRUSH
CPrintToChatAll("{darkviolet}[{red}CORE{darkviolet}] {white}Client %N was crushed by a {red}FALLING ROCK FROM OUTER SPACE{white}!", client);
weapon = "Meteor to the Face";
}
case 8: { //BURN
CPrintToChatAll("{darkviolet}[{red}CORE{darkviolet}] {white}Client %N was {red}MELTED{white}.", client);
weapon = "Melted by Sharts or Ass Gas";
}
case 16: { //FREEZE
CPrintToChatAll("{darkviolet}[{red}CORE{darkviolet}] {white}Client %N was flattened out by a {red}TRAIN{white}!", client);
weapon = "Attempted Train Robbery";
}
case 32: { //FALL
if (WeatherManager.hasTornado) {
switch (GetClientTeam(client)) {
case 2: {
CPrintToChatAll("{darkviolet}[{red}CORE{darkviolet}] {white}Client %N was {red}%s{white}!", client, DeathMessage[GetRandomInt(0, 5)]);
weapon = "Yeeted into Orbit via Tornado";
}
case 3: {
CPrintToChatAll("{darkviolet}[{red}CORE{darkviolet}] {white}Client %N was {red}%s{white}! ({limegreen}+1 pt{white})", client, DeathMessage[GetRandomInt(0, 5)]);
core.sacPoints++;
CustomSoundEmitter(SFXArray[GetRandomInt(11, 26)].realPath, 65, false, 0, 1.0, 100);
}
}
} else {
CPrintToChatAll("{darkviolet}[{red}CORE{darkviolet}] {white}Client %N fell to a {red}CLUMSY PAINFUL DEATH{white}!", client);
weapon = "Tripped on a LEGO";
}
}
case 64: { //BLAST
CPrintToChatAll("{darkviolet}[{red}CORE{darkviolet}] {white}Client %N went {red} KABOOM{white}!", client);
weapon = "Gone Kaboom!";
}
case 128: { //CLUB
if (core.canHindenburg) {
CPrintToChatAll("{darkviolet}[{red}CORE{darkviolet}] {white}Client %N is {red}CRASHING THE HINDENBURG{white}!!!", client);
weapon = "Crashing the Hindenburg";
}
}
case 256: { //SHOCK
if(core.CodeEntry > 0){
CPrintToChatAll("{darkviolet}[{red}EXTERMINATUS{darkviolet}] {white}Client %N has humliated themselves with an {red}incorrect {white}key entry!", client);
weapon = "Failed FB Code Entry";
int i = GetRandomInt(1, 16);
switch (i) {
case 1, 3, 10: {
FastFire2("BG.Meteorites1", "ForceSpawn", "", 0.0, false);
CPrintToChatAll("{darkviolet}[{red}WARN{darkviolet}] {white}Uh oh, a {red}METEOR{white}has been spotted coming towards Dovah's Ass!!!");
FastFire2("bg.meteorite1", "StartForward", "", 0.1, false);
}
case 2, 5, 16: {
CreateTimer(0.5, TimedOperator, 71);
FastFire2("FB.TankTrain", "TeleportToPathTrack", "Tank01", 0.0, false);
FastFire2("FB.TankTrain", "StartForward", "", 0.25, false);
FastFire2("FB.TankTrain", "SetSpeed", "1", 0.35, false);
FastFire2("FB.Tank", "Enable", "", 1.0, false);
}
case 4, 8, 14: {
CustomSoundEmitter("ambient/alarms/train_horn_distant1.wav", 65, false, 0, 1.0, 100);
FastFire2("TrainSND","PlaySound", "", 0.0, false);
FastFire2("TrainDamage", "Enable", "", 0.0, false);
FastFire2("Train01", "Enable", "", 0.0, false);
CPrintToChatAll("{darkviolet}[{red}WARN{darkviolet}] {orange}KISSONE'S TRAIN{white}is {red}INCOMING{white}. Look out!");
FastFire2("TrainTrain", "TeleportToPathTrack", "TrainTrack01", 0.0, false);
FastFire2("TrainTrain", "StartForward", "", 0.1, false);
}
case 6, 9: {
WeatherManager.canTornado = true;
CreateTimer(1.0, TimedOperator, 41);
}
case 7, 13: {
CPrintToChatAll("{darkviolet}[{red}WARN{darkviolet}] {white}Uh oh, it appears to have started raining a {red}METEOR SHOWER{white}!!!");
core.canSENTMeteors = true;
CreateTimer(1.0, SENTMeteorTimer);
CreateTimer(30.0, TimedOperator, 12);
}
case 11: {
FastFire2("FB.Slice", "Enable", "", 0.0, false);
CustomSoundEmitter("ambient/sawblade_impact1.wav", 65, false, 0, 1.0, 100);
FastFire2("FB.Slice", "Disable", "", 1.0, false);
}
}
}
}
case 512: { //SONIC
CPrintToChatAll("{darkviolet}[{red}EXTERMINATUS{darkviolet}] {white}Client %N has sacrificed themselves with a {forestgreen}correct {white}key entry! Prepare your anus!", client);
sudo(1006);
weapon = "Correct FB Code Entry";
}
case 1024: { //ENERGYBEAM
char EnergyDeath[32];
Format(EnergyDeath, sizeof(EnergyDeath), (core.crusader ? "THE CRUSADER" : core.waveFlags == 1 ? "ONSLAUGHTER" : "LIGHTNING"));
weapon = (core.crusader ? "Crusader" : core.waveFlags == 1 ? "Onslaughter" : "Lightning");
CPrintToChatAll("{darkviolet}[{red}CORE{darkviolet}] {white}Client %N has been %s by {red}%s{white}!", client, (core.crusader ? "nuked" : core.waveFlags == 1 ? "deleted" : "struck"), EnergyDeath);
}
case 16384: { //DROWN
CPrintToChatAll("{darkviolet}[{red}CORE{darkviolet}] {white}Client %N {red}DROWNED{white}.", client);
weapon = "Darwin Award for Drowning";
}
case 32768: { //PARALYZE
CPrintToChatAll("{darkviolet}[{red}CORE{darkviolet}] {white}Client %N has been crushed by a {darkviolet}MYSTERIOUS BLUE BALL{white}!", client);
weapon = "Mysterious Blue Ball";
}
case 65536: { //NERVEGAS
CPrintToChatAll("{darkviolet}[{red}CORE{darkviolet}] {white}Client %N has been {red}SLICED TO RIBBONS{white}!", client);
weapon = "FB Code Entry Failed";
}
case 131072: { //POISON
CPrintToChat(client, "{darkviolet}[{red}CORE{darkviolet}] {white}Please don't sit {red}IDLE {white}in the FC Tavern.");
CPrintToChatAll("{darkviolet}[{red}CORE{darkviolet}] {white}Client %N was killed for standing in the Tavern instead of helping their team!", client);
weapon = "Idle in FC Tavern..?";
}
case 262144: { //RADIATION
CPrintToChatAll("{darkviolet}[{red}CORE{darkviolet}] {white}Client %N was blown away by a {red}NUCLEAR EXPLOSION{white}!", client);
weapon = "Nuclear Explosion";
}
case 524288: { //DROWNRECOVER
CPrintToChatAll("{darkviolet}[{red}CORE{darkviolet}] {white}Client %N experienced {red}TACO BELL{white}!", client);
weapon = "Taco Bell";
}
case 1048576: { //ACID
CPrintToChatAll( isGoobbue ? "{darkviolet}[{red}CORE{darkviolet}] {white}Client %N has been crushed by a {forestgreen}FALLING GOOBBUE FROM OUTER SPACE{white}!" : "{darkviolet}[{red}CORE{darkviolet}] {white}Client %N was deleted by {orange}AN AREA OF EFFECT{white}!", client);
weapon = isGoobbue ? "Falling Goobbue" : "AREA_EFFECT";
}
}
}
//Log if a player killed someone or was killed by a robot
if (attacker != client) {
if (!Ass_Database) return Plugin_Handled;
char query[256];
int steamID = (IsValidClient(attacker) ? GetSteamAccountID(attacker) : GetSteamAccountID(client));
Format(query, sizeof(query), IsValidClient(attacker) && !StrEqual(weapon, "world") ? "UPDATE ass_activity SET kills = kills +1, killssession = killssession + 1, lastkilledname = '%s', lastweaponused = '%s' WHERE steamid = %i;" : !StrEqual(weapon, "world") && !IsValidClient(attacker) ? "UPDATE ass_activity SET deaths = deaths + 1, deathssession = deathssession + 1, killedbyname = '%s', killedbyweapon = '%s' WHERE steamid = %i;" : "RETURN", name, weapon, steamID);
if (StrEqual(query, "RETURN")) return Plugin_Handled;
Ass_Database.Query(Database_FastQuery, query);
}
}
return Plugin_Handled;
}
//When we win
public Action EventWaveComplete(Event Spawn_Event, const char[] Spawn_Name, bool Spawn_Broadcast) {
sudo(300);
CPrintToChatAll("{darkviolet}[{forestgreen}CORE{darkviolet}] {white}You've defeated the wave!");
return Plugin_Handled;
}
//Announce when we are in danger.
public Action EventWarning(Event Spawn_Event,
const char[] Spawn_Name, bool Spawn_Broadcast) {
if (core.doFailsafe) {
core.failsafeCount++;
CPrintToChatAll("%s Counter: %i", failsafe[GetRandomInt(0, sizeof(failsafe) - 1)], core.failsafeCount);
EmitSoundToAll(SFXArray[55].realPath);
PerformWaveFailsafe(GetRandomInt(0,1));
core.doFailsafe = false;
} else CPrintToChatAll("{darkviolet}[{red}WARN{darkviolet}] {darkred}PROFESSOR'S ASS IS ABOUT TO BE DEPLOYED!!!");
return Plugin_Handled;
}
//When the wave fails
public Action EventWaveFailed(Event Spawn_Event, const char[] Spawn_Name, bool Spawn_Broadcast) {
CPrintToChatAll("{darkviolet}[{forestgreen}CORE{darkviolet}] {white}Wave {red}failed {white}successfully!");
sudo(300);
return Plugin_Handled;
}
//Sacrifice target and grant bonus points
public Action SacrificeClient(int client, int attacker, bool wasBombReset) {
if (attacker <= MaxClients && IsClientInGame(attacker)) {
core.bombReset = false;
core.sacPoints += wasBombReset ? 5 : 1;
core.sacrificedByClient = false;
int steamID = GetSteamAccountID(attacker);
if (!Ass_Database || !steamID) return Plugin_Handled;
char query[256];
CPrintToChatAll(wasBombReset ? "{darkviolet}[{forestgreen}CORE{darkviolet}] {white}Client {red}%N {white}has reset the ass! ({limegreen}+5 pts{white})" : "{darkviolet}[{forestgreen}CORE{darkviolet}] {white}Client {red}%N {white}has sacrificed {blue}%N {white}for the ass! ({limegreen}+1 pt{white})", attacker, client);
Format(query, sizeof(query), wasBombReset ? "UPDATE ass_activity SET bombsreset = bombsreset + 1, bombsresetsession = bombsresetsession + 1 WHERE steamid = %i;" : "UPDATE ass_activity SET sacrifices = sacrifices + 1, sacrificessession = sacrificessession + 1 WHERE steamid = %i;", steamID);
Ass_Database.Query(Database_FastQuery, query);
}
return Plugin_Handled;
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,32 @@
//Fartsy's FastFire2
int ff2Ref;
//Inject entity IO logic
public void OnMapStart() {
InjectFastFire2();
}
void InjectFastFire2(){
int ff2 = FindEntityByTargetname("FastFire2", "info_target");
AssLogger(LOGLVL_INFO, "Injecting FastFire2!");
if (!IsValidEntity(ff2)){
ff2 = CreateEntityByName("info_target");
if (!IsValidEdict(ff2)) SetFailState("Could not inject FastFire2, aborting!!!");
DispatchSpawn(ff2);
DispatchKeyValue(ff2, "targetname", "FastFire2");
ActivateEntity(ff2);
AssLogger(LOGLVL_INFO, "Injected info_target FastFire2 to map!")
}
ff2Ref = EntIndexToEntRef(ff2);
OnFastFire2Ready();
}
//Execute inputs - EXPERT MODE
public void FastFire2(const char[] target, const char[] input, const char[] param, const float delay, bool isLegacy) {
int ff2 = EntRefToEntIndex(ff2Ref);
char FireStr[128];
FormatEx(FireStr, sizeof(FireStr), (isLegacy ? target : "OnUser1 %s,%s,%s,%f,1"), target, input, param, delay);
SetVariantString(FireStr);
AcceptEntityInput(ff2, "AddOutput");
AcceptEntityInput(ff2, "FireUser1");
}

View File

@@ -0,0 +1,264 @@
//Helper for Fartsy's Clockwork Chaos
bool BLC = false; //Blu captured intermediate point, set by OnOwnerChangedToTeam3
bool REC = false; //Red captured intermediate point, set by OnOwnerChangeToTeam2
bool isMatch = false; //Is it a match?
bool RECEDE = false; //PL receding
bool PLM; //Payload is moving
char LoggerDbg[512];
char LoggerInfo[256];
char PLT[16] = "N/A"; //Team that is currently pushing the payload
int PLB = 0; //Payload blu progress
int PLL = 0; //Payload location. 0 = neutral, 1 = red, 2 = blu
int PLR = 0; //Payload red progress
int PLRL = 20; //Payload real location, 40 = red base, 20 = neutral, 0 = blu base
Handle RecedeTimer = INVALID_HANDLE; //Recede timer, restart it by killing it and starting a new one.
//PL Hud
enum struct CCHUD {
char RED[128];
char BLU[128];
char IDLE[128];
char NEUTRAL[128];
}
CCHUD CCH[42];
//Reference lookup for payload position
int PLPOS[] = {
100,
95,
90,
85,
80,
75,
70,
65,
60,
55,
50,
45,
40,
35,
30,
25,
20,
15,
10,
5,
0,
5,
10,
15,
20,
25,
30,
35,
40,
45,
50,
55,
60,
65,
70,
75,
80,
85,
90,
95,
100,
100
};
//Register and precache all sounds
void RegisterAndPrecacheAllFiles(){
LogMessage("[ERROR] RegisterAndPRecacheAllFiles is not implemented!");
}
//Register all commands
void RegisterAllCommands(){
FccLogger(1, "Registering commands...");
RegServerCmd("fcc_operator", Command_Operator, "Serverside only. Does nothing when executed as client.");
}
//Setup core map data
void SetupCoreData(){
FccLogger(1, "Setting up core data...");
CCH[0].BLU = "hud/cconflict/cc_bluFF"; // Blu payload at their spawn being pushed by blu
CCH[1].BLU = "hud/cconflict/cc_bluFE";
CCH[2].BLU = "hud/cconflict/cc_bluFD";
CCH[3].BLU = "hud/cconflict/cc_bluFC";
CCH[4].BLU = "hud/cconflict/cc_bluFB";
CCH[5].BLU = "hud/cconflict/cc_bluFA";
CCH[6].BLU = "hud/cconflict/cc_bluF9";
CCH[7].BLU = "hud/cconflict/cc_bluF8";
CCH[8].BLU = "hud/cconflict/cc_bluF7";
CCH[9].BLU = "hud/cconflict/cc_bluF6";
CCH[10].BLU = "hud/cconflict/cc_bluF5";
CCH[11].BLU = "hud/cconflict/cc_bluF4";
CCH[12].BLU = "hud/cconflict/cc_bluF3";
CCH[13].BLU = "hud/cconflict/cc_bluF2";
CCH[14].BLU = "hud/cconflict/cc_bluF1";
CCH[15].BLU = "hud/cconflict/cc_bluF0";
CCH[16].BLU = "hud/cconflict/cc_bluEF";
CCH[17].BLU = "hud/cconflict/cc_bluEE";
CCH[18].BLU = "hud/cconflict/cc_bluED";
CCH[19].BLU = "hud/cconflict/cc_bluEC";
CCH[20].BLU = "hud/cconflict/cc_blu00";
CCH[21].BLU = "hud/cconflict/cc_blu01";
CCH[22].BLU = "hud/cconflict/cc_blu02";
CCH[23].BLU = "hud/cconflict/cc_blu03";
CCH[24].BLU = "hud/cconflict/cc_blu04";
CCH[25].BLU = "hud/cconflict/cc_blu05";
CCH[26].BLU = "hud/cconflict/cc_blu06";
CCH[27].BLU = "hud/cconflict/cc_blu07";
CCH[28].BLU = "hud/cconflict/cc_blu08";
CCH[29].BLU = "hud/cconflict/cc_blu09";
CCH[30].BLU = "hud/cconflict/cc_blu0A";
CCH[31].BLU = "hud/cconflict/cc_blu0C";
CCH[32].BLU = "hud/cconflict/cc_blu0D";
CCH[33].BLU = "hud/cconflict/cc_blu0E";
CCH[34].BLU = "hud/cconflict/cc_blu0F";
CCH[35].BLU = "hud/cconflict/cc_blu10";
CCH[36].BLU = "hud/cconflict/cc_blu11";
CCH[37].BLU = "hud/cconflict/cc_blu12";
CCH[38].BLU = "hud/cconflict/cc_blu13";
CCH[39].BLU = "hud/cconflict/cc_blu14";
CCH[40].BLU = "hud/cconflict/cc_blu15";
CCH[0].RED = "hud/cconflict/cc_red2A"; // Red payload at Blu spawn
CCH[1].RED = "hud/cconflict/cc_red29";
CCH[2].RED = "hud/cconflict/cc_red28";
CCH[3].RED = "hud/cconflict/cc_red27";
CCH[4].RED = "hud/cconflict/cc_red26";
CCH[5].RED = "hud/cconflict/cc_red25";
CCH[6].RED = "hud/cconflict/cc_red24";
CCH[7].RED = "hud/cconflict/cc_red23";
CCH[8].RED = "hud/cconflict/cc_red22";
CCH[9].RED = "hud/cconflict/cc_red21";
CCH[10].RED = "hud/cconflict/cc_red1F";
CCH[11].RED = "hud/cconflict/cc_red1E";
CCH[12].RED = "hud/cconflict/cc_red1D";
CCH[13].RED = "hud/cconflict/cc_red1C";
CCH[14].RED = "hud/cconflict/cc_red1B";
CCH[15].RED = "hud/cconflict/cc_red1A";
CCH[16].RED = "hud/cconflict/cc_red19";
CCH[17].RED = "hud/cconflict/cc_red18";
CCH[18].RED = "hud/cconflict/cc_red17";
CCH[19].RED = "hud/cconflict/cc_red16";
CCH[20].RED = "hud/cconflict/cc_red15";
CCH[21].RED = "hud/cconflict/cc_redEC";
CCH[22].RED = "hud/cconflict/cc_redED";
CCH[23].RED = "hud/cconflict/cc_redEE";
CCH[24].RED = "hud/cconflict/cc_redEF";
CCH[25].RED = "hud/cconflict/cc_redF0";
CCH[26].RED = "hud/cconflict/cc_redF1";
CCH[27].RED = "hud/cconflict/cc_redF2";
CCH[28].RED = "hud/cconflict/cc_redF3";
CCH[29].RED = "hud/cconflict/cc_redF4";
CCH[30].RED = "hud/cconflict/cc_redF5";
CCH[31].RED = "hud/cconflict/cc_redF6";
CCH[32].RED = "hud/cconflict/cc_redF7";
CCH[33].RED = "hud/cconflict/cc_redF8";
CCH[34].RED = "hud/cconflict/cc_redF9";
CCH[35].RED = "hud/cconflict/cc_redFA";
CCH[36].RED = "hud/cconflict/cc_redFB";
CCH[37].RED = "hud/cconflict/cc_redFC";
CCH[38].RED = "hud/cconflict/cc_redFD";
CCH[39].RED = "hud/cconflict/cc_redFE";
CCH[40].RED = "hud/cconflict/cc_redFF";
CCH[0].NEUTRAL = "hud/cconflict/cc_neutralFF"; // Receding payload at their spawn
CCH[1].NEUTRAL = "hud/cconflict/cc_neutralFE";
CCH[2].NEUTRAL = "hud/cconflict/cc_neutralFD";
CCH[3].NEUTRAL = "hud/cconflict/cc_neutralFC";
CCH[4].NEUTRAL = "hud/cconflict/cc_neutralFB";
CCH[5].NEUTRAL = "hud/cconflict/cc_neutralFA";
CCH[6].NEUTRAL = "hud/cconflict/cc_neutralF9";
CCH[7].NEUTRAL = "hud/cconflict/cc_neutralF8";
CCH[8].NEUTRAL = "hud/cconflict/cc_neutralF7";
CCH[9].NEUTRAL = "hud/cconflict/cc_neutralF6";
CCH[10].NEUTRAL = "hud/cconflict/cc_neutralF5";
CCH[11].NEUTRAL = "hud/cconflict/cc_neutralF4";
CCH[12].NEUTRAL = "hud/cconflict/cc_neutralF3";
CCH[13].NEUTRAL = "hud/cconflict/cc_neutralF2";
CCH[14].NEUTRAL = "hud/cconflict/cc_neutralF1";
CCH[15].NEUTRAL = "hud/cconflict/cc_neutralF0";
CCH[16].NEUTRAL = "hud/cconflict/cc_neutralEF";
CCH[17].NEUTRAL = "hud/cconflict/cc_neutralEE";
CCH[18].NEUTRAL = "hud/cconflict/cc_neutralED";
CCH[19].NEUTRAL = "hud/cconflict/cc_neutralEC";
CCH[20].NEUTRAL = "hud/cconflict/cc_neutral00";
CCH[21].NEUTRAL = "hud/cconflict/cc_neutral01";
CCH[22].NEUTRAL = "hud/cconflict/cc_neutral02";
CCH[23].NEUTRAL = "hud/cconflict/cc_neutral03";
CCH[24].NEUTRAL = "hud/cconflict/cc_neutral04";
CCH[25].NEUTRAL = "hud/cconflict/cc_neutral05";
CCH[26].NEUTRAL = "hud/cconflict/cc_neutral06";
CCH[27].NEUTRAL = "hud/cconflict/cc_neutral07";
CCH[28].NEUTRAL = "hud/cconflict/cc_neutral08";
CCH[29].NEUTRAL = "hud/cconflict/cc_neutral09";
CCH[30].NEUTRAL = "hud/cconflict/cc_neutral0A";
CCH[31].NEUTRAL = "hud/cconflict/cc_neutral0C";
CCH[32].NEUTRAL = "hud/cconflict/cc_neutral0D";
CCH[33].NEUTRAL = "hud/cconflict/cc_neutral0E";
CCH[34].NEUTRAL = "hud/cconflict/cc_neutral0F";
CCH[35].NEUTRAL = "hud/cconflict/cc_neutral10";
CCH[36].NEUTRAL = "hud/cconflict/cc_neutral11";
CCH[37].NEUTRAL = "hud/cconflict/cc_neutral12";
CCH[38].NEUTRAL = "hud/cconflict/cc_neutral13";
CCH[39].NEUTRAL = "hud/cconflict/cc_neutral14";
CCH[40].NEUTRAL = "hud/cconflict/cc_neutral15";
CCH[0].IDLE = "hud/cconflict/cc_idleFF";
CCH[1].IDLE = "hud/cconflict/cc_idleFE";
CCH[2].IDLE = "hud/cconflict/cc_idleFD";
CCH[3].IDLE = "hud/cconflict/cc_idleFC";
CCH[4].IDLE = "hud/cconflict/cc_idleFB";
CCH[5].IDLE = "hud/cconflict/cc_idleFA";
CCH[6].IDLE = "hud/cconflict/cc_idleF9";
CCH[7].IDLE = "hud/cconflict/cc_idleF8";
CCH[8].IDLE = "hud/cconflict/cc_idleF7";
CCH[9].IDLE = "hud/cconflict/cc_idleF6";
CCH[10].IDLE = "hud/cconflict/cc_idleF5";
CCH[11].IDLE = "hud/cconflict/cc_idleF4";
CCH[12].IDLE = "hud/cconflict/cc_idleF3";
CCH[13].IDLE = "hud/cconflict/cc_idleF2";
CCH[14].IDLE = "hud/cconflict/cc_idleF1";
CCH[15].IDLE = "hud/cconflict/cc_idleF0";
CCH[16].IDLE = "hud/cconflict/cc_idleEF";
CCH[17].IDLE = "hud/cconflict/cc_idleEE";
CCH[18].IDLE = "hud/cconflict/cc_idleED";
CCH[19].IDLE = "hud/cconflict/cc_idleEC";
CCH[20].IDLE = "hud/cconflict/cc_idle00";
CCH[21].IDLE = "hud/cconflict/cc_idle01";
CCH[22].IDLE = "hud/cconflict/cc_idle02";
CCH[23].IDLE = "hud/cconflict/cc_idle03";
CCH[24].IDLE = "hud/cconflict/cc_idle04";
CCH[25].IDLE = "hud/cconflict/cc_idle05";
CCH[26].IDLE = "hud/cconflict/cc_idle06";
CCH[27].IDLE = "hud/cconflict/cc_idle07";
CCH[28].IDLE = "hud/cconflict/cc_idle08";
CCH[29].IDLE = "hud/cconflict/cc_idle09";
CCH[30].IDLE = "hud/cconflict/cc_idle0A";
CCH[31].IDLE = "hud/cconflict/cc_idle0C";
CCH[32].IDLE = "hud/cconflict/cc_idle0D";
CCH[33].IDLE = "hud/cconflict/cc_idle0E";
CCH[34].IDLE = "hud/cconflict/cc_idle0F";
CCH[35].IDLE = "hud/cconflict/cc_idle10";
CCH[36].IDLE = "hud/cconflict/cc_idle11";
CCH[37].IDLE = "hud/cconflict/cc_idle12";
CCH[38].IDLE = "hud/cconflict/cc_idle13";
CCH[39].IDLE = "hud/cconflict/cc_idle14";
CCH[40].IDLE = "hud/cconflict/cc_idle15";
}
//Check if the client is valid
stock bool IsValidClient(int client) {
return (0 < client <= MaxClients && IsClientInGame(client) && !IsFakeClient(client));
}
// Show overlay to all clients with lifetime | 0.0 = no auto remove
stock void ShowOverlayAll(char[] path)
{
for (int i = 1; i <= MaxClients; i++)
{
if (!IsClientInGame(i) || IsFakeClient(i) || IsClientSourceTV(i) || IsClientReplay(i))
continue;
ClientCommand(i, "r_screenoverlay \"%s.vtf\"", path);
}
}

642
scripting/include/files.inc Normal file
View File

@@ -0,0 +1,642 @@
/**
* vim: set ts=4 sw=4 tw=99 noet :
* =============================================================================
* SourceMod (C)2004-2014 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _files_included
#endinput
#endif
#define _files_included
/**
* @global All paths in SourceMod natives are relative to the mod folder
* unless otherwise noted.
*
* Most functions in SourceMod (at least, ones that deal with direct
* file manipulation) will support an alternate path specification.
*
* If the path starts with the string "file://" and the PathType is
* not relative, then the "file://" portion is stripped off, and the
* rest of the path is used without any modification (except for
* correcting slashes). This can be used to override the path
* builder to supply alternate absolute paths. Examples:
*
* file://C:/Temp/file.txt
* file:///tmp/file.txt
*/
/**
* File inode types.
*/
enum FileType
{
FileType_Unknown = 0, /* Unknown file type (device/socket) */
FileType_Directory = 1, /* File is a directory */
FileType_File = 2 /* File is a file */
};
/**
* File time modes.
*/
enum FileTimeMode
{
FileTime_LastAccess = 0, /* Last access (does not work on FAT) */
FileTime_Created = 1, /* Creation (does not work on FAT) */
FileTime_LastChange = 2 /* Last modification */
};
#define PLATFORM_MAX_PATH 256 /**< Maximum path length. */
#define SEEK_SET 0 /**< Seek from start. */
#define SEEK_CUR 1 /**< Seek from current position. */
#define SEEK_END 2 /**< Seek from end position. */
/**
* Path types.
*/
enum PathType
{
Path_SM, /**< SourceMod root folder */
};
// A DirectoryListing iterates over the contents of a directory. To obtain a
// DirectoryListing handle, call OpenDirectory().
methodmap DirectoryListing < Handle
{
// Reads the current directory entry as a local filename, then moves to the
// next file.
//
// Note: Both the '.' and '..' automatic directory entries will be retrieved.
//
// @param buffer String buffer to hold directory name.
// @param maxlength Maximum size of string buffer.
// @param type Optional variable to store the file type.
// @return True on success, false if there are no more files to read.
public native bool GetNext(char[] buffer, int maxlength, FileType &type=FileType_Unknown);
};
// A File object can be obtained by calling OpenFile(). File objects should be
// closed with delete or Close(). Note that, "delete file" does not
// actually delete the file, it just closes the handle.
methodmap File < Handle
{
// Close the file handle. This is the same as using CloseHandle() or delete.
public void Close() {
CloseHandle(this);
}
// Get the file size in bytes.
//
// @return File size in bytes, -1 on error.
public native int Size();
// Reads a line of text from a file.
//
// @param buffer String buffer to hold the line.
// @param maxlength Maximum size of string buffer.
// @return True on success, false otherwise.
public native bool ReadLine(char[] buffer, int maxlength);
// Reads binary data from a file.
//
// @param items Array to store each item read.
// @param num_items Number of items to read into the array.
// @param size Size of each element, in bytes, to be read.
// Valid sizes are 1, 2, or 4.
// @return Number of elements read, or -1 on error.
public native int Read(any[] items, int num_items, int size);
// Reads a UTF8 or ANSI string from a file.
//
// @param buffer Buffer to store the string.
// @param max_size Maximum size of the string buffer.
// @param read_count If -1, reads until a null terminator is encountered in
// the file. Otherwise, read_count bytes are read
// into the buffer provided. In this case the buffer
// is not explicitly null terminated, and the buffer
// will contain any null terminators read from the file.
// @return Number of characters written to the buffer, or -1
// if an error was encountered.
// @error read_count > max_size.
public native int ReadString(char[] buffer, int max_size, int read_count=-1);
// Writes binary data to a file.
//
// @param items Array of items to write. The data is read directly.
// That is, in 1 or 2-byte mode, the lower byte(s) in
// each cell are used directly, rather than performing
// any casts from a 4-byte number to a smaller number.
// @param num_items Number of items in the array.
// @param size Size of each item in the array in bytes.
// Valid sizes are 1, 2, or 4.
// @return True on success, false on error.
public native bool Write(const any[] items, int num_items, int size);
// Writes a binary string to a file.
//
// @param buffer String to write.
// @param term True to append NUL terminator, false otherwise.
// @return True on success, false on error.
public native bool WriteString(const char[] buffer, bool term);
// Writes a line of text to a text file. A newline is automatically appended.
//
// @param hndl Handle to the file.
// @param format Formatting rules.
// @param ... Variable number of format parameters.
// @return True on success, false otherwise.
public native bool WriteLine(const char[] format, any ...);
// Reads a single int8 (byte) from a file. The returned value is sign-
// extended to an int32.
//
// @param data Variable to store the data read.
// @return True on success, false on failure.
public native bool ReadInt8(int &data);
// Reads a single uint8 (unsigned byte) from a file. The returned value is
// zero-extended to an int32.
//
// @param data Variable to store the data read.
// @return True on success, false on failure.
public native bool ReadUint8(int &data);
// Reads a single int16 (short) from a file. The value is sign-extended to
// an int32.
//
// @param data Variable to store the data read.
// @return True on success, false on failure.
public native bool ReadInt16(int &data);
// Reads a single unt16 (unsigned short) from a file. The value is zero-
// extended to an int32.
//
// @param data Variable to store the data read.
// @return True on success, false on failure.
public native bool ReadUint16(int &data);
// Reads a single int32 (int/cell) from a file.
//
// @param data Variable to store the data read.
// @return True on success, false on failure.
public native bool ReadInt32(int &data);
// Writes a single int8 (byte) to a file.
//
// @param data Data to write (truncated to an int8).
// @return True on success, false on failure.
public native bool WriteInt8(int data);
// Writes a single int16 (short) to a file.
//
// @param data Data to write (truncated to an int16).
// @return True on success, false on failure.
public native bool WriteInt16(int data);
// Writes a single int32 (int/cell) to a file.
//
// @param data Data to write.
// @return True on success, false on failure.
public native bool WriteInt32(int data);
// Tests if the end of file has been reached.
//
// @return True if end of file has been reached, false otherwise.
public native bool EndOfFile();
// Sets the file position indicator.
//
// @param position Position relative to what is specified in whence.
// @param where SEEK_ constant value of where to see from.
// @return True on success, false otherwise.
public native bool Seek(int position, int where);
// Flushes a file's buffered output; any buffered output
// is immediately written to the file.
//
// @return True on success or use_valve_fs specified with OpenFile,
// otherwise false on failure.
public native bool Flush();
// Get the current position in the file; returns -1 on failure.
property int Position {
public native get();
}
}
/**
* Builds a path relative to the SourceMod folder. This should be used instead of
* directly referencing addons/sourcemod, in case users change the name of their
* folder layout.
*
* @param type Type of path to build as the base.
* @param buffer Buffer to store the path.
* @param maxlength Maximum length of buffer.
* @param fmt Format string.
* @param ... Format arguments.
* @return Number of bytes written to buffer (not including null terminator).
*/
native int BuildPath(PathType type, char[] buffer, int maxlength, const char[] fmt, any ...);
/**
* Opens a directory/folder for contents enumeration.
*
* @note Directories are closed with CloseHandle() or delete.
* @note Directories Handles can be cloned.
* @note OpenDirectory() supports the "file://" notation.
*
* @param path Path to open.
* @param use_valve_fs If true, the Valve file system will be used instead.
* This can be used to find files existing in any of
* the Valve search paths, rather than solely files
* existing directly in the gamedir.
* @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths.
* @return A Handle to the directory, null on error.
*/
native DirectoryListing OpenDirectory(const char[] path, bool use_valve_fs=false, const char[] valve_path_id="GAME");
/**
* Reads the current directory entry as a local filename, then moves to the next file.
*
* @note Contents of buffers are undefined when returning false.
* @note Both the '.' and '..' automatic directory entries will be retrieved for Windows and Linux.
*
* @param dir Handle to a directory.
* @param buffer String buffer to hold directory name.
* @param maxlength Maximum size of string buffer.
* @param type Optional variable to store the file type.
* @return True on success, false if there are no more files to read.
* @error Invalid or corrupt Handle.
*/
native bool ReadDirEntry(Handle dir, char[] buffer, int maxlength, FileType &type=FileType_Unknown);
/**
* Opens or creates a file, returning a File handle on success. File handles
* should be closed with delete or CloseHandle().
*
* The open mode may be one of the following strings:
* "r": Open an existing file for reading.
* "w": Create a file for writing, or truncate (delete the contents of) an
* existing file and then open it for writing.
* "a": Create a file for writing, or open an existing file such that writes
* will be appended to the end.
* "r+": Open an existing file for both reading and writing.
* "w+": Create a file for reading and writing, or truncate an existing file
* and then open it for reading and writing.
* "a+": Create a file for both reading and writing, or open an existing file
* such that writes will be appended to the end.
*
* The open mode may also contain an additional character after "r", "w", or "a",
* but before any "+" sign. This character may be "b" (indicating binary mode) or
* "t" (indicating text mode). By default, "text" mode is implied. On Linux and
* Mac, this has no distinction from binary mode. On Windows, it causes the '\n'
* character (0xA) to be written as "\r\n" (0xD, 0xA).
*
* Example: "rb" opens a binary file for reading; "at" opens a text file for
* appending.
*
* @param file File to open.
* @param mode Open mode.
* @param use_valve_fs If true, the Valve file system will be used instead.
* This can be used to find files existing in valve
* search paths, rather than solely files existing directly
* in the gamedir.
* @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths.
* @return A File handle, or null if the file could not be opened.
*/
native File OpenFile(const char[] file, const char[] mode, bool use_valve_fs=false, const char[] valve_path_id="GAME");
/**
* Deletes a file.
*
* @param path Path of the file to delete.
* @param use_valve_fs If true, the Valve file system will be used instead.
* This can be used to delete files existing in the Valve
* search path, rather than solely files existing directly
* in the gamedir.
* @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths.
* @return True on success, false on failure or if file not immediately removed.
*/
native bool DeleteFile(const char[] path, bool use_valve_fs=false, const char[] valve_path_id="DEFAULT_WRITE_PATH");
/**
* Reads a line from a text file.
*
* @param hndl Handle to the file.
* @param buffer String buffer to hold the line.
* @param maxlength Maximum size of string buffer.
* @return True on success, false otherwise.
*/
native bool ReadFileLine(Handle hndl, char[] buffer, int maxlength);
/**
* Reads binary data from a file.
*
* @param hndl Handle to the file.
* @param items Array to store each item read.
* @param num_items Number of items to read into the array.
* @param size Size of each element, in bytes, to be read.
* Valid sizes are 1, 2, or 4.
* @return Number of elements read, or -1 on error.
*/
native int ReadFile(Handle hndl, any[] items, int num_items, int size);
/**
* Reads a UTF8 or ANSI string from a file.
*
* @param hndl Handle to the file.
* @param buffer Buffer to store the string.
* @param max_size Maximum size of the string buffer.
* @param read_count If -1, reads until a null terminator is encountered in
* the file. Otherwise, read_count bytes are read
* into the buffer provided. In this case the buffer
* is not explicitly null terminated, and the buffer
* will contain any null terminators read from the file.
* @return Number of characters written to the buffer, or -1
* if an error was encountered.
* @error Invalid Handle, or read_count > max_size.
*/
native int ReadFileString(Handle hndl, char[] buffer, int max_size, int read_count=-1);
/**
* Writes binary data to a file.
*
* @param hndl Handle to the file.
* @param items Array of items to write. The data is read directly.
* That is, in 1 or 2-byte mode, the lower byte(s) in
* each cell are used directly, rather than performing
* any casts from a 4-byte number to a smaller number.
* @param num_items Number of items in the array.
* @param size Size of each item in the array in bytes.
* Valid sizes are 1, 2, or 4.
* @return True on success, false on error.
* @error Invalid Handle.
*/
native bool WriteFile(Handle hndl, const any[] items, int num_items, int size);
/**
* Writes a binary string to a file.
*
* @param hndl Handle to the file.
* @param buffer String to write.
* @param term True to append NUL terminator, false otherwise.
* @return True on success, false on error.
* @error Invalid Handle.
*/
native bool WriteFileString(Handle hndl, const char[] buffer, bool term);
/**
* Writes a line of text to a text file. A newline is automatically appended.
*
* @param hndl Handle to the file.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
* @return True on success, false otherwise.
* @error Invalid Handle.
*/
native bool WriteFileLine(Handle hndl, const char[] format, any ...);
/**
* Reads a single binary cell from a file.
*
* @param hndl Handle to the file.
* @param data Variable to store the data read.
* @param size Size of the data to read in bytes. Valid
* sizes are 1, 2, or 4 bytes.
* @return Number of elements read (max 1), or -1 on error.
* @error Invalid Handle.
*/
stock int ReadFileCell(Handle hndl, int &data, int size)
{
int ret;
int array[1];
if ((ret = ReadFile(hndl, array, 1, size)) == 1)
{
data = array[0];
}
return ret;
}
/**
* Writes a single binary cell to a file.
*
* @param hndl Handle to the file.
* @param data Cell to write to the file.
* @param size Size of the data to read in bytes. Valid
* sizes are 1, 2, or 4 bytes. If the size
* is less than 4 bytes, the data is truncated
* rather than casted. That is, only the lower
* bits will be read.
* @return True on success, false on error.
* @error Invalid Handle.
*/
stock bool WriteFileCell(Handle hndl, int data, int size)
{
int array[1];
array[0] = data;
return WriteFile(hndl, array, 1, size);
}
/**
* Tests if the end of file has been reached.
*
* @param file Handle to the file.
* @return True if end of file has been reached, false otherwise.
* @error Invalid Handle.
*/
native bool IsEndOfFile(Handle file);
/**
* Sets the file position indicator.
*
* @param file Handle to the file.
* @param position Position relative to what is specified in whence.
* @param where SEEK_ constant value of where to see from.
* @return True on success, false otherwise.
* @error Invalid Handle.
*/
native bool FileSeek(Handle file, int position, int where);
/**
* Get current position in the file.
*
* @param file Handle to the file.
* @return Value for the file position indicator.
* @error Invalid Handle.
*/
native int FilePosition(Handle file);
/**
* Checks if a file exists.
*
* @param path Path to the file.
* @param use_valve_fs If true, the Valve file system will be used instead.
* This can be used to find files existing in any of
* the Valve search paths, rather than solely files
* existing directly in the gamedir.
* @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths.
* @return True if the file exists, false otherwise.
*/
native bool FileExists(const char[] path, bool use_valve_fs=false, const char[] valve_path_id="GAME");
/**
* Renames a file.
*
* @param newpath New path to the file.
* @param oldpath Path to the existing file.
* @param use_valve_fs If true, the Valve file system will be used instead.
* This can be used to rename files in the game's
* Valve search paths, rather than directly in the gamedir.
* @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths.
* @return True on success or use_valve_fs specified, false otherwise.
*/
native bool RenameFile(const char[] newpath, const char[] oldpath, bool use_valve_fs=false, const char[] valve_path_id="DEFAULT_WRITE_PATH");
/**
* Checks if a directory exists.
*
* @param path Path to the directory.
* @param use_valve_fs If true, the Valve file system will be used instead.
* This can be used to find files existing in any of
* the Valve search paths, rather than solely files
* existing directly in the gamedir.
* @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths.
* @return True if the directory exists, false otherwise.
*/
native bool DirExists(const char[] path, bool use_valve_fs=false, const char[] valve_path_id="GAME");
/**
* Get the file size in bytes.
*
* @param path Path to the file.
* @param use_valve_fs If true, the Valve file system will be used instead.
* This can be used to find files existing in any of
* the Valve search paths, rather than solely files
* existing directly in the gamedir.
* @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths.
* @return File size in bytes, -1 if file not found.
*/
native int FileSize(const char[] path, bool use_valve_fs=false, const char[] valve_path_id="GAME");
/**
* Flushes a file's buffered output; any buffered output
* is immediately written to the file.
*
* @param file Handle to the file.
* @return True on success or use_valve_fs specified with OpenFile,
* otherwise false on failure.
*/
native bool FlushFile(Handle file);
/**
* Removes a directory.
* @note On most Operating Systems you cannot remove a directory which has files inside it.
*
* @param path Path to the directory.
* @return True on success, false otherwise.
*/
native bool RemoveDir(const char[] path);
#define FPERM_U_READ 0x0100 /* User can read. */
#define FPERM_U_WRITE 0x0080 /* User can write. */
#define FPERM_U_EXEC 0x0040 /* User can exec. */
#define FPERM_G_READ 0x0020 /* Group can read. */
#define FPERM_G_WRITE 0x0010 /* Group can write. */
#define FPERM_G_EXEC 0x0008 /* Group can exec. */
#define FPERM_O_READ 0x0004 /* Anyone can read. */
#define FPERM_O_WRITE 0x0002 /* Anyone can write. */
#define FPERM_O_EXEC 0x0001 /* Anyone can exec. */
/**
* Creates a directory.
*
* @param path Path to create. Note that directories are not created recursively unless use_valve_fs is used.
* @param mode Permissions (default is o=rx,g=rx,u=rwx). Note that folders must have
* the execute bit set on Linux. On Windows, the mode is ignored.
* @param use_valve_fs If true, the Valve file system will be used instead.
* This can be used to create folders in the game's
* Valve search paths, rather than directly in the gamedir.
* @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for default.
* In this case, mode is ignored.
* @return True on success, false otherwise.
*/
native bool CreateDirectory(const char[] path, int mode=FPERM_O_READ|FPERM_O_EXEC|FPERM_G_READ|FPERM_G_EXEC|FPERM_U_READ|FPERM_U_WRITE|FPERM_U_EXEC, bool use_valve_fs=false, const char[] valve_path_id="DEFAULT_WRITE_PATH");
/**
* Changes a file or directories permissions.
*
* @param path Path to the file.
* @param mode Permissions to set.
* @return True on success, false otherwise.
*/
native bool SetFilePermissions(const char[] path, int mode);
/**
* Retrieves a file or directories permissions.
*
* @param path Path to the file.
* @param mode Variable to store the permissions in.
* @return True on success, false otherwise.
*/
native bool GetFilePermissions(const char[] path, int &mode);
/**
* Returns a file timestamp as a unix timestamp.
*
* @param file File name.
* @param tmode Time mode.
* @return Time value, or -1 on failure.
*/
native int GetFileTime(const char[] file, FileTimeMode tmode);
/**
* Same as LogToFile(), except uses an open file Handle. The file must
* be opened in text appending mode.
*
* @param hndl Handle to the file.
* @param message Message format.
* @param ... Message format parameters.
* @error Invalid Handle.
*/
native void LogToOpenFile(Handle hndl, const char[] message, any ...);
/**
* Same as LogToFileEx(), except uses an open file Handle. The file must
* be opened in text appending mode.
*
* @param hndl Handle to the file.
* @param message Message format.
* @param ... Message format parameters.
* @error Invalid Handle.
*/
native void LogToOpenFileEx(Handle hndl, const char[] message, any ...);

477
scripting/include/float.inc Normal file
View File

@@ -0,0 +1,477 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _float_included
#endinput
#endif
#define _float_included
#if !defined __sourcepawn2__
/**
* Converts an integer into a floating point value.
*
* @param value Integer to convert.
* @return Floating point value.
*/
native float float(int value);
#endif
/**
* Multiplies two floats together.
*
* Note: This native is internal implementation. For multiplication use the '*' operator.
*
* @param oper1 First value.
* @param oper2 Second value.
* @return oper1*oper2.
* @deprecated This native is internal implementation. For multiplication use the '*' operator.
*/
#pragma deprecated This native is internal implementation. For multiplication use the '*' operator.
native float FloatMul(float oper1, float oper2);
/**
* Divides the dividend by the divisor.
*
* Note: This native is internal implementation. For division use the '/' operator.
*
* @param dividend First value.
* @param divisor Second value.
* @return dividend/divisor.
* @deprecated This native is internal implementation. For division use the '/' operator.
*/
#pragma deprecated This native is internal implementation. For division use the '/' operator.
native float FloatDiv(float dividend, float divisor);
/**
* Adds two floats together.
*
* Note: This native is internal implementation. For addition use the '+' operator.
*
* @param oper1 First value.
* @param oper2 Second value.
* @return oper1+oper2.
* @deprecated This native is internal implementation. For addition use the '+' operator.
*/
#pragma deprecated This native is internal implementation. For addition use the '+' operator.
native float FloatAdd(float oper1, float oper2);
/**
* Subtracts oper2 from oper1.
*
* Note: This native is internal implementation. For subtraction use the '-' operator.
*
* @param oper1 First value.
* @param oper2 Second value.
* @return oper1-oper2.
* @deprecated This native is internal implementation. For subtraction use the '-' operator.
*/
#pragma deprecated This native is internal implementation. For subtraction use the '-' operator.
native float FloatSub(float oper1, float oper2);
/**
* Returns the modulus of oper1 and oper2.
*
* Note: This native is internal implementation. For modulo use the '%' operator.
*
* @param oper1 First value.
* @param oper2 Second value.
* @return oper1%oper2.
* @deprecated This native is internal implementation. For modulo use the '%' operator.
*/
#pragma deprecated This native is internal implementation. For modulo use the '%' operator.
native float FloatMod(float oper1, float oper2);
/**
* Returns the decimal part of a float.
*
* @param value Input value.
* @return Decimal part.
*/
native float FloatFraction(float value);
/**
* Rounds a float to the closest integer to zero.
*
* @param value Input value to be rounded.
* @return Rounded value.
*/
native int RoundToZero(float value);
/**
* Rounds a float to the next highest integer value.
*
* @param value Input value to be rounded.
* @return Rounded value.
*/
native int RoundToCeil(float value);
/**
* Rounds a float to the next lowest integer value.
*
* @param value Input value to be rounded.
* @return Rounded value.
*/
native int RoundToFloor(float value);
/**
* Standard IEEE rounding.
*
* @param value Input value to be rounded.
* @return Rounded value.
*/
native int RoundToNearest(float value);
/**
* Compares two floats.
*
* @param fOne First value.
* @param fTwo Second value.
* @return Returns 1 if the first argument is greater than the second argument.
* Returns -1 if the first argument is smaller than the second argument.
* Returns 0 if both arguments are equal.
*/
native int FloatCompare(float fOne, float fTwo);
/**
* Returns the square root of the input value, equivalent to floatpower(value, 0.5).
*
* @param value Input value.
* @return Square root of the value.
*/
native float SquareRoot(float value);
/**
* Returns the value raised to the power of the exponent.
*
* @param value Value to be raised.
* @param exponent Value to raise the base.
* @return value^exponent.
*/
native float Pow(float value, float exponent);
/**
* Returns the value of raising the input by e.
*
* @param value Input value.
* @return exp(value).
*/
native float Exponential(float value);
/**
* Returns the logarithm of any base specified.
*
* @param value Input value.
* @param base Logarithm base to use, default is 10.
* @return log(value)/log(base).
*/
native float Logarithm(float value, float base=10.0);
/**
* Returns the sine of the argument.
*
* @param value Input value in radians.
* @return sin(value).
*/
native float Sine(float value);
/**
* Returns the cosine of the argument.
*
* @param value Input value in radians.
* @return cos(value).
*/
native float Cosine(float value);
/**
* Returns the tangent of the argument.
*
* @param value Input value in radians.
* @return tan(value).
*/
native float Tangent(float value);
/**
* Returns an absolute value.
*
* @param value Input value.
* @return Absolute value of the input.
*/
native float FloatAbs(float value);
/**
* Returns the arctangent of the input value.
*
* @param angle Input value.
* @return atan(value) in radians.
*/
native float ArcTangent(float angle);
/**
* Returns the arccosine of the input value.
*
* @param angle Input value.
* @return acos(value) in radians.
*/
native float ArcCosine(float angle);
/**
* Returns the arcsine of the input value.
*
* @param angle Input value.
* @return asin(value) in radians.
*/
native float ArcSine(float angle);
/**
* Returns the arctangent2 of the input values.
*
* @param x Horizontal value.
* @param y Vertical value.
* @return atan2(value) in radians.
*/
native float ArcTangent2(float x, float y);
/**
* Rounds a floating point number using the "round to nearest" algorithm.
*
* @param value Floating point value to round.
* @return The value rounded to the nearest integer.
*/
stock int RoundFloat(float value)
{
return RoundToNearest(value);
}
/**
* User defined operators.
*/
#if !defined __sourcepawn2__
// Internal aliases for backwards compatibility.
native float __FLOAT_MUL__(float a, float b);
native float __FLOAT_DIV__(float a, float b);
native float __FLOAT_ADD__(float a, float b);
native float __FLOAT_SUB__(float a, float b);
native float __FLOAT_MOD__(float a, float b);
native bool __FLOAT_GT__(float a, float b);
native bool __FLOAT_GE__(float a, float b);
native bool __FLOAT_LT__(float a, float b);
native bool __FLOAT_LE__(float a, float b);
native bool __FLOAT_EQ__(float a, float b);
native bool __FLOAT_NE__(float a, float b);
native bool __FLOAT_NOT__(float a);
stock float operator*(float oper1, float oper2) { return __FLOAT_MUL__(oper1, oper2); }
stock float operator/(float oper1, float oper2) { return __FLOAT_DIV__(oper1, oper2); }
stock float operator+(float oper1, float oper2) { return __FLOAT_ADD__(oper1, oper2); }
stock float operator-(float oper1, float oper2) { return __FLOAT_SUB__(oper1, oper2); }
stock float operator%(float oper1, float oper2) { return __FLOAT_MOD__(oper1, oper2); }
stock bool operator!(float oper1) { return __FLOAT_NOT__(oper1); }
stock bool operator>(float oper1, float oper2) { return __FLOAT_GT__(oper1, oper2); }
stock bool operator>=(float oper1, float oper2) { return __FLOAT_GE__(oper1, oper2); }
stock bool operator<(float oper1, float oper2) { return __FLOAT_LT__(oper1, oper2); }
stock bool operator<=(float oper1, float oper2) { return __FLOAT_LE__(oper1, oper2); }
stock bool operator!=(float oper1, float oper2) { return __FLOAT_NE__(oper1, oper2); }
stock bool operator==(float oper1, float oper2) { return __FLOAT_EQ__(oper1, oper2); }
stock float operator++(float oper)
{
return oper+1.0;
}
stock float operator--(float oper)
{
return oper-1.0;
}
stock float operator-(float oper)
{
return oper^view_as<float>(cellmin); /* IEEE values are sign/magnitude */
}
// The stocks below are int->float converting versions of the above natives.
stock float operator*(float oper1, int oper2)
{
return __FLOAT_MUL__(oper1, float(oper2)); /* "*" is commutative */
}
stock float operator/(float oper1, int oper2)
{
return __FLOAT_DIV__(oper1, float(oper2));
}
stock float operator/(int oper1, float oper2)
{
return __FLOAT_DIV__(float(oper1), oper2);
}
stock float operator+(float oper1, int oper2)
{
return __FLOAT_ADD__(oper1, float(oper2)); /* "+" is commutative */
}
stock float operator-(float oper1, int oper2)
{
return __FLOAT_SUB__(oper1, float(oper2));
}
stock float operator-(int oper1, float oper2)
{
return __FLOAT_SUB__(float(oper1), oper2);
}
stock bool operator==(float oper1, int oper2)
{
return __FLOAT_EQ__(oper1, float(oper2));
}
stock bool operator!=(float oper1, int oper2)
{
return __FLOAT_NE__(oper1, float(oper2));
}
stock bool operator>(float oper1, int oper2)
{
return __FLOAT_GT__(oper1, float(oper2));
}
stock bool operator>(int oper1, float oper2)
{
return __FLOAT_GT__(float(oper1), oper2);
}
stock bool operator>=(float oper1, int oper2)
{
return __FLOAT_GE__(oper1, float(oper2));
}
stock bool operator>=(int oper1, float oper2)
{
return __FLOAT_GE__(float(oper1), oper2);
}
stock bool operator<(float oper1, int oper2)
{
return __FLOAT_LT__(oper1, float(oper2));
}
stock bool operator<(int oper1, float oper2)
{
return __FLOAT_LT__(float(oper1), oper2);
}
stock bool operator<=(float oper1, int oper2)
{
return __FLOAT_LE__(oper1, float(oper2));
}
stock bool operator<=(int oper1, float oper2)
{
return __FLOAT_LE__(float(oper1), oper2);
}
stock float operator%(float oper1, int oper2)
{
return __FLOAT_MOD__(oper1, float(oper2));
}
stock float operator%(int oper1, float oper2)
{
return __FLOAT_MOD__(float(oper1), oper2);
}
#endif // __sourcepawn2__
#define FLOAT_PI 3.1415926535897932384626433832795
/**
* Converts degrees to radians.
*
* @param angle Degrees.
* @return Radians.
*/
stock float DegToRad(float angle)
{
return (angle*FLOAT_PI)/180;
}
/**
* Converts radians to degrees.
*
* @param angle Radians.
* @return Degrees.
*/
stock float RadToDeg(float angle)
{
return (angle*180)/FLOAT_PI;
}
/**
* Returns a random integer in the range [0, 2^31-1].
*
* Note: Uniform random number streams are seeded automatically per-plugin.
*
* @return Random integer.
*/
native int GetURandomInt();
/**
* Returns a uniform random float in the range [0, 1).
*
* Note: Uniform random number streams are seeded automatically per-plugin.
*
* @return Uniform random floating-point number.
*/
native float GetURandomFloat();
/**
* Seeds a plugin's uniform random number stream. This is done automatically,
* so normally it is totally unnecessary to call this.
*
* @param seeds Array of numbers to use as seeding data.
* @param numSeeds Number of seeds in the seeds array.
*/
native void SetURandomSeed(const int[] seeds, int numSeeds);
/**
* Seeds a plugin's uniform random number stream. This is done automatically,
* so normally it is totally unnecessary to call this.
*
* @param seed Single seed value.
*/
stock void SetURandomSeedSimple(int seed)
{
int seeds[1];
seeds[0] = seed;
SetURandomSeed(seeds, 1);
}

View File

@@ -0,0 +1,633 @@
//Freak Fortress 2 include file.
#include <morecolors>
#include <sdktools>
#define FF2FLAG_UBERREADY (1<<1) //Used when medic says "I'm charged!"
#define FF2FLAG_ISBUFFED (1<<2) //Used when soldier uses the Battalion's Backup
#define FF2FLAG_CLASSTIMERDISABLED (1<<3) //Used to prevent clients' timer
#define FF2FLAG_HUDDISABLED (1<<4) //Used to prevent custom hud from clients' timer
#define FF2FLAG_BOTRAGE (1<<5) //Used by bots to use Boss's rage
#define FF2FLAG_TALKING (1<<6) //Used by Bosses with "sound_block_vo" to disable block for some lines
#define FF2FLAG_ALLOWSPAWNINBOSSTEAM (1<<7) //Used to allow spawn players in Boss's team
#define FF2FLAG_USEBOSSTIMER (1<<8) //Used to prevent Boss's timer
#define FF2FLAG_USINGABILITY (1<<9) //Used to prevent Boss's hints about abilities buttons
#define FF2FLAG_CLASSHELPED (1<<10)
#define FF2FLAG_HASONGIVED (1<<11)
#define FF2FLAG_CHANGECVAR (1<<12) //Used to prevent SMAC from kicking bosses who are using certain rages (NYI)
#define FF2FLAG_ALLOW_HEALTH_PICKUPS (1<<13) //Used to prevent bosses from picking up health
#define FF2FLAG_ALLOW_AMMO_PICKUPS (1<<14) //Used to prevent bosses from picking up ammo
#define FF2FLAG_ROCKET_JUMPING (1<<15) //Used when a soldier is rocket jumping
#define FF2FLAGS_SPAWN ~FF2FLAG_UBERREADY & ~FF2FLAG_ISBUFFED & ~FF2FLAG_TALKING & ~FF2FLAG_ALLOWSPAWNINBOSSTEAM & ~FF2FLAG_CHANGECVAR & ~FF2FLAG_ROCKET_JUMPING & FF2FLAG_USEBOSSTIMER & FF2FLAG_USINGABILITY
#if defined _FF2_included
#endinput
#endif
#define _FF2_included
/**
* Is Freak Fortress enabled?
*
* @return False if FF2 is disabled
* True if FF2 is enabled
*/
native bool:FF2_IsFF2Enabled();
/**
* Gets the version of FF2 running on the server
*
* @param version An array of size 3 that will contain the major, minor, and stable version numbers respectively
* @return True if the server is running a dev version of FF2, false otherwise
*/
native FF2_GetFF2Version(version[]=0);
/**
* Gets current round state
*
* @return 0 - in setup
* 1 - round is in progress (due to a bug in arena mode, stalemate will also return 1)
* 2 - someone wins
*/
native FF2_GetRoundState();
/**
* Gets UserID of current Boss
*
* @param boss Boss's index
* @return Userid of boss (-1 if Boss does not exist)
*/
native FF2_GetBossUserId(boss=0);
/**
* Gets the boss index of a client
*
* @param client The client used to search for the boss index
* @return Boss index of that client. If client is not boss, returns -1
*/
native FF2_GetBossIndex(client);
/**
* Gets current team of Boss
* @return Number of boss's team
*/
native FF2_GetBossTeam();
/**
* Gets the character name of the Boss
*
* @param boss Boss's index
* @param buffer Buffer for boss' character name
* @param bufferLength Length of buffer string
* @param bossMeaning 0 - "boss" parameter means index of current Boss
* 1 - "boss" parameter means number of Boss in characters.cfg-1
* @return True if boss exists, false if not
*/
native bool:FF2_GetBossSpecial(boss=0, String:buffer[], bufferLength, bossMeaning=0);
/**
* Gets the current health value of the Boss
*
* @param boss Boss's index
* @return Current health of the Boss
*/
native FF2_GetBossHealth(boss=0);
/**
* Sets the health of the Boss
*
* @param boss Boss's index
* @param health New health value
* @noreturn
*/
native FF2_SetBossHealth(boss, health);
/**
* Gets the max health of the Boss
*
* @param boss Boss's index
* @return Max health of the Boss
*/
native FF2_GetBossMaxHealth(boss=0);
/**
* Sets the max health of the Boss
*
* @param boss Boss's index
* @param health New max health value
* @noreturn
*/
native FF2_SetBossMaxHealth(boss, health);
/**
* Gets the current number of lives of the Boss
*
* @param boss Boss's index
* @return Number of lives the boss has remaining
*/
native FF2_GetBossLives(boss);
/**
* Sets the current number of lives of the Boss
*
* @param boss Boss's index
* @param lives New number of lives
* @noreturn
*/
native FF2_SetBossLives(boss, lives);
/**
* Gets the max number of lives of the Boss
*
* @param boss Boss's index
* @return Max number of lives of the Boss
*/
native FF2_GetBossMaxLives(boss);
/**
* Sets the max number of lives of the Boss
*
* @param boss Boss's index
* @param lives New max number of lives
* @noreturn
*/
native FF2_SetBossMaxLives(boss, lives);
/**
* Gets the charge meter value of the Boss
*
* @param boss Boss's index
* @param slot Slot of charge meter
* 0 - rage
* 1 - as usual, used for brave jump or teleport
* 2 - other charged abilities
* @return Charge value of the Boss
*/
native Float:FF2_GetBossCharge(boss, slot);
/**
* Sets the charge meter value of the Boss
*
* @param boss Boss's index
* @param slot Slot of charge meter
* 0 - rage
* 1 - as usual, used for brave jump or teleport
* 2 - other charged abilities
* @param value New value of charge
* @noreturn
*/
native FF2_SetBossCharge(boss, slot, Float:value);
/**
* Gets how much damage is needed in order to activate the rage of the current boss
*
* @param boss Boss index
* @return Total damage needed
*/
native FF2_GetBossRageDamage(boss);
/**
* Sets how much damage is needed in order to activate the rage of the current boss
*
* @param boss Boss index
* @param damage New damage value
* @noreturn
*/
native FF2_SetBossRageDamage(boss, damage);
/**
* Gets damage dealt by this client
*
* @param client Client's index
* @return Damage dealt
*/
native FF2_GetClientDamage(client);
/**
* Gets an ability's rage distance
*
* @param boss Boss's index
* @param pluginName Name of plugin with this ability
* @param abilityName Name of ability (use null string if you want get boss's global "ragedist" value)
* @return Ability's rage distance
*/
native Float:FF2_GetRageDist(boss=0, const String:pluginName[]="", const String:abilityName[]="");
/**
* Finds if a Boss has a certain ability
*
* @param boss Boss's index
* @param pluginName Name of plugin with this ability
* @param abilityName Name of ability
* @return True if the boss has this ability, false if it doesn't
*/
native bool:FF2_HasAbility(boss, const String:pluginName[], const String:abilityName[]);
/**
* Determines how the Boss should use a certain ability
*
* @param boss Boss's index
* @param pluginName Name of plugin with this ability
* @param abilityName Name of ability
* @param slot Slot of charge meter
* 0 - rage
* 1 - as usual, used for brave jump or teleport
* 2 - other charged abilities
* @param buttonMode How to activate the ability
* 0 - by taunt
* 1 - by right mouse button or duck
* 2 - by reload button
* @noreturn
*/
native FF2_DoAbility(boss, const String:pluginName[], const String:abilityName[], slot, buttonMode=0);
/**
* Gets the integer value of an ability argument
*
* @param boss Boss's index
* @param pluginName Name of plugin with this ability
* @param abilityName Name of ability
* @param argument Number of argument
* @param defValue Returns if argument is not defined
* @return Value of argument
*/
native FF2_GetAbilityArgument(boss, const String:pluginName[], const String:abilityName[], argument, defValue=0);
/**
* Gets the float value of an ability argument
*
* @param boss Boss's index
* @param pluginName Name of plugin with this ability
* @param abilityName Name of ability
* @param argument Number of argument
* @param defValue Returns if argument is not defined
* @return Value of argument
*/
native Float:FF2_GetAbilityArgumentFloat(boss, const String:plugin_name[], const String:ability_name[], argument, Float:defValue=0.0);
/**
* Gets the string value of an ability argument
*
* @param boss Boss's index
* @param pluginName Name of plugin with this ability
* @param abilityName Name of ability
* @param argument Number of argument
* @param buffer Buffer for value of argument
* @param bufferLength Length of buffer string
* @noreturn
*/
native FF2_GetAbilityArgumentString(boss, const String:pluginName[], const String:abilityName[], argument, String:buffer[], bufferLength);
/**
* Starts a random Boss sound from its config file
*
* @param keyvalue Name of sound container
* @param buffer Buffer for result sound path
* @param bufferLength Length of buffer
* @param boss Boss's index
* @param slot Only for "sound_ability" - slot of ability
* @return True if sound has been found, false otherwise
*/
native bool:FF2_RandomSound(const String:keyvalue[], String:buffer[], bufferLength, boss=0, slot=0);
/**
* Starts the Boss's music for the specified clients
*
* @param client Client's index (0 for all clients)
* @noreturn
*/
native FF2_StartMusic(client=0);
/**
* Stops the Boss's music for the specified clients
*
* @param client Client's index (0 for all clients)
* @noreturn
*/
native FF2_StopMusic(client=0);
/**
* Gets a Boss's KV handle
*
* @param boss Boss's index
* @param specialIndex 0 - 'boss' parameter refers to the index of the boss
* 1 - 'boss' parameter refers to the index of the boss in characters.cfg-1
* @return Handle of Boss's keyvalues
*/
native Handle:FF2_GetSpecialKV(boss, specialIndex=0);
/**
* Gets a client's flags for FF2
*
* @param client Client's index
* @return Client's FF2 flags
*/
native FF2_GetFF2flags(client);
/**
* Sets a client's flags for FF2
*
* @param client Client's index
* @param flags New flag values
* @noreturn
*/
native FF2_SetFF2flags(client, flags);
/**
* Gets a client's queue points
*
* @param client Client's index
* @return Client's queue points
*/
native FF2_GetQueuePoints(client);
/**
* Sets a client's queue points
*
* @param client Client's index
* @param value New value of client's queue points
* @noreturn
*/
native FF2_SetQueuePoints(client, value);
/**
* Gets a client's glow timer
*
* @param client Client's index
* @return Number of seconds left until client glow disappears (-1 if invalid client)
*/
native Float:FF2_GetClientGlow(client);
/**
* Sets a client's glow timer
*
* @param client Client's index
* @param time1 Number of seconds to add to the glow timer (can be negative)
* @param time2 New value of glow timer
* @noreturn
*/
native FF2_SetClientGlow(client, Float:time1, Float:time2=-1.0);
/**
* Retrieves the number of alive players left (not including bosses)
*
* @return Number of non-boss players left alive
*/
#pragma deprecated Use FF2_OnAlivePlayersChanged
native FF2_GetAlivePlayers();
/**
* Retrieves the number of boss players left (including minions)
*
* @return Number of boss players left alive
*/
#pragma deprecated Use FF2_OnAlivePlayersChanged
native FF2_GetBossPlayers();
/**
* Returns whether or not debug is enabled
* @return True if enabled, false otherwise
*/
native bool:FF2_Debug();
/**
* FF2_ONABILITY IS KNOWN TO BE BUGGED AND WILL NOT BE FIXED TO PRESERVE BACKWARDS COMPATABILITY. DO NOT USE IT.
* Called when a Boss uses an ability (Rage, jump, teleport, etc)
* Called every 0.2 seconds for charge abilities
*
* Use FF2_PreAbility with enabled=false ONLY to prevent FF2_OnAbility!
*
* @param boss Boss's index
* @param pluginName Name of plugin with this ability
* @param abilityName Name of ability
* @param slot Slot of ability (THIS DOES NOT RETURN WHAT YOU THINK IT RETURNS FOR FF2_ONABILITY-if you insist on using this, refer to freak_fortress_2.sp to see what it actually does)
* 0 - Rage or life-loss
* 1 - Jump or teleport
* 2 - Other
* @param status Status of ability (DO NOT ACCESS THIS. IT DOES NOT EXIST AND MIGHT CRASH YOUR SERVER)
* @return Plugin_Stop can not prevent the ability. Use FF2_PreAbility with enabled=false
*/
forward FF2_PreAbility(boss, const String:pluginName[], const String:abilityName[], slot, &bool:enabled);
forward Action:FF2_OnAbility(boss, const String:pluginName[], const String:abilityName[], slot, status);
/**
* Called when a Boss gets hurt by environmental damage
*
* @param boss Boss's index
* @param triggerHurt Entity index of "trigger_hurt"
* @param damage Damage by "trigger_hurt". Cutomizable.
* @return Plugin_Stop will prevent forward, Plugin_Changed will change damage.
*/
forward Action:FF2_OnTriggerHurt(boss, triggerHurt, &Float:damage);
/**
* Called when a Boss's music begins
*
* @param path Path to music sound file
* @param time Length of music
* @return Plugin_Stop will prevent music, Plugin_Changed will change it.
*/
forward Action:FF2_OnMusic(String:path[], &Float:time);
/**
* Called when FF2 picks a character for a Boss
*
* @param boss Boss index
* @param character Character index
* @param characterName Character name
* @param preset True if the boss was set using a command such as ff2_special
* @return You can NOT use Plugin_Stop to prevent this, but you can change characterName and use Plugin_Changed to change the boss. If you want to change 'character', then make 'characterName' null.
*/
forward Action:FF2_OnSpecialSelected(boss, &character, String:characterName[], bool:preset);
/**
* Called when FF2 adds queue points
*
* @param add_points Array that contains each player's queue points
*
* @return Plugin_Stop will prevent this, Plugin_Changed will change it.
*/
forward Action:FF2_OnAddQueuePoints(add_points[MAXPLAYERS+1]);
/**
* Called when FF2 picks a character set for the map
*
* @param charSetNum Number of character set
* @param charSetName Name of character set
* @return You can NOT use Plugin_Stop to prevent this, but you can change charSetName and use Plugin_Changed to change the character set. If you want to change charSetNum, then make charSetName null.
*/
forward Action:FF2_OnLoadCharacterSet(&charSetNum, String:charSetName[]);
/**
* Called when a Boss loses a life
*
* @param boss Boss's index
* @param lives Number of lives left
* @param maxLives Max number of lives
* @return Plugin_Stop or Plugin_Handled to prevent damage that would remove a life, Plugin_Changed if you want to change the number of lives left.
*/
forward Action:FF2_OnLoseLife(boss, &lives, maxLives);
/**
* Called when the number of alive players changes. Note that this will never be 0 as FF2 does not re-calculate the number of players once the round ends.
*
* @param players Number of alive players left on the non-boss team
* @param bosses Number of alive players left on the boss team (this includes minions as well)
* @noreturn
*/
forward Action:FF2_OnAlivePlayersChanged(players, bosses);
/**
*
* Gives ammo to a weapon
*
* @param client Client's index
* @param weapon Weapon
* @param ammo Ammo (set to 1 for clipless weapons, then set the actual ammo using clip)
* @param clip Clip
* @noreturn
*/
stock FF2_SetAmmo(client, weapon, ammo=-1, clip=-1)
{
if(IsValidEntity(weapon))
{
if(clip>-1)
{
SetEntProp(weapon, Prop_Data, "m_iClip1", clip);
}
new ammoType=(ammo>-1 ? GetEntProp(weapon, Prop_Send, "m_iPrimaryAmmoType") : -1);
if(ammoType!=-1)
{
SetEntProp(client, Prop_Data, "m_iAmmo", ammo, _, ammoType);
}
else if(ammo>-1) //Only complain if we're trying to set ammo
{
decl String:classname[64], String:bossName[32];
GetEdictClassname(weapon, classname, sizeof(classname));
FF2_GetBossSpecial(FF2_GetBossIndex(client), bossName, sizeof(bossName));
LogError("[FF2] Cannot give ammo to weapon %s (boss %s)-check your config!", classname, bossName);
}
}
}
/**
* Sends a synced HUD message according to FF2's rules
* Will only send if the client hasn't disabled their HUD and isn't checking the scoreboard
*
* Uses the same params and return values as ShowSyncHudText
*/
stock FF2_ShowSyncHudText(client, Handle:sync, const String:buffer[], any:...)
{
if(!(FF2_GetFF2flags(client) & FF2FLAG_HUDDISABLED) && !(GetClientButtons(client) & IN_SCORE))
{
decl String:message[256];
VFormat(message, sizeof(message), buffer, 4);
ShowSyncHudText(client, sync, message);
}
}
/**
* Sends a HUD message according to FF2's rules
* Will only send if the client hasn't disabled their HUD and isn't checking the scoreboard
*
* Uses the same params and return values as ShowHudText
*/
stock FF2_ShowHudText(client, channel, const String:buffer[], any:...)
{
if(!(FF2_GetFF2flags(client) & FF2FLAG_HUDDISABLED) && !(GetClientButtons(client) & IN_SCORE))
{
decl String:message[256];
VFormat(message, sizeof(message), buffer, 4);
ShowHudText(client, channel, message);
}
}
/**
* Used to consolidate debug messages
*
* @param buffer Debug string to display
* @param any:... Formatting rules
* @noreturn
*/
stock Debug(String:buffer[], any:...)
{
if(FF2_Debug())
{
decl String:message[192];
VFormat(message, sizeof(message), buffer, 2);
CPrintToChatAll("{olive}[FF2 {darkorange}DEBUG{olive}]{default} %s", message);
PrintToServer("[FF2 DEBUG] %s", message);
}
}
// These exist for compatibility reasons (<1.10.1)
#pragma deprecated Use TF2_RemoveWeaponSlot
stock TF2_RemoveWeaponSlot2(client, slot)
{
TF2_RemoveWeaponSlot(client, slot);
}
#pragma deprecated Use TF2_RemoveAllWeapons
stock TF2_RemoveAllWeapons2(client)
{
for(new slot=0; slot<=5; slot++)
{
TF2_RemoveWeaponSlot(client, slot);
}
}
public SharedPlugin:__pl_FF2=
{
name="freak_fortress_2",
file="freak_fortress_2.smx",
#if defined REQUIRE_PLUGIN
required=1,
#else
required=0,
#endif
};
#if !defined REQUIRE_PLUGIN
public __pl_FF2_SetNTVOptional()
{
MarkNativeAsOptional("FF2_IsFF2Enabled");
MarkNativeAsOptional("FF2_GetFF2Version");
MarkNativeAsOptional("FF2_GetBossUserId");
MarkNativeAsOptional("FF2_GetBossIndex");
MarkNativeAsOptional("FF2_GetBossTeam");
MarkNativeAsOptional("FF2_GetBossSpecial");
MarkNativeAsOptional("FF2_GetBossHealth");
MarkNativeAsOptional("FF2_SetBossHealth");
MarkNativeAsOptional("FF2_GetBossMaxHealth");
MarkNativeAsOptional("FF2_SetBossMaxHealth");
MarkNativeAsOptional("FF2_GetBossLives");
MarkNativeAsOptional("FF2_SetBossLives");
MarkNativeAsOptional("FF2_GetBossMaxLives");
MarkNativeAsOptional("FF2_SetBossMaxLives");
MarkNativeAsOptional("FF2_GetBossCharge");
MarkNativeAsOptional("FF2_SetBossCharge");
MarkNativeAsOptional("FF2_GetBossRageDamage");
MarkNativeAsOptional("FF2_SetBossRageDamage");
MarkNativeAsOptional("FF2_GetClientDamage");
MarkNativeAsOptional("FF2_GetRoundState");
MarkNativeAsOptional("FF2_GetRageDist");
MarkNativeAsOptional("FF2_HasAbility");
MarkNativeAsOptional("FF2_GetAbilityArgument");
MarkNativeAsOptional("FF2_GetAbilityArgumentFloat");
MarkNativeAsOptional("FF2_GetAbilityArgumentString");
MarkNativeAsOptional("FF2_RandomSound");
MarkNativeAsOptional("FF2_StartMusic");
MarkNativeAsOptional("FF2_StopMusic");
MarkNativeAsOptional("FF2_GetSpecialKV");
MarkNativeAsOptional("FF2_GetQueuePoints");
MarkNativeAsOptional("FF2_SetQueuePoints");
MarkNativeAsOptional("FF2_GetFF2flags");
MarkNativeAsOptional("FF2_SetFF2flags");
MarkNativeAsOptional("FF2_DoAbility");
MarkNativeAsOptional("FF2_GetClientGlow");
MarkNativeAsOptional("FF2_SetClientGlow");
MarkNativeAsOptional("FF2_GetAlivePlayers");
MarkNativeAsOptional("FF2_GetBossPlayers");
MarkNativeAsOptional("FF2_Debug");
}
#endif

View File

@@ -0,0 +1,633 @@
//Freak Fortress 2 include file.
#include <morecolors>
#include <sdktools>
#define FF2FLAG_UBERREADY (1<<1) //Used when medic says "I'm charged!"
#define FF2FLAG_ISBUFFED (1<<2) //Used when soldier uses the Battalion's Backup
#define FF2FLAG_CLASSTIMERDISABLED (1<<3) //Used to prevent clients' timer
#define FF2FLAG_HUDDISABLED (1<<4) //Used to prevent custom hud from clients' timer
#define FF2FLAG_BOTRAGE (1<<5) //Used by bots to use Boss's rage
#define FF2FLAG_TALKING (1<<6) //Used by Bosses with "sound_block_vo" to disable block for some lines
#define FF2FLAG_ALLOWSPAWNINBOSSTEAM (1<<7) //Used to allow spawn players in Boss's team
#define FF2FLAG_USEBOSSTIMER (1<<8) //Used to prevent Boss's timer
#define FF2FLAG_USINGABILITY (1<<9) //Used to prevent Boss's hints about abilities buttons
#define FF2FLAG_CLASSHELPED (1<<10)
#define FF2FLAG_HASONGIVED (1<<11)
#define FF2FLAG_CHANGECVAR (1<<12) //Used to prevent SMAC from kicking bosses who are using certain rages (NYI)
#define FF2FLAG_ALLOW_HEALTH_PICKUPS (1<<13) //Used to prevent bosses from picking up health
#define FF2FLAG_ALLOW_AMMO_PICKUPS (1<<14) //Used to prevent bosses from picking up ammo
#define FF2FLAG_ROCKET_JUMPING (1<<15) //Used when a soldier is rocket jumping
#define FF2FLAGS_SPAWN ~FF2FLAG_UBERREADY & ~FF2FLAG_ISBUFFED & ~FF2FLAG_TALKING & ~FF2FLAG_ALLOWSPAWNINBOSSTEAM & ~FF2FLAG_CHANGECVAR & ~FF2FLAG_ROCKET_JUMPING & FF2FLAG_USEBOSSTIMER & FF2FLAG_USINGABILITY
#if defined _FF2_included
#endinput
#endif
#define _FF2_included
/**
* Is Freak Fortress enabled?
*
* @return False if FF2 is disabled
* True if FF2 is enabled
*/
native bool:FF2_IsFF2Enabled();
/**
* Gets the version of FF2 running on the server
*
* @param version An array of size 3 that will contain the major, minor, and stable version numbers respectively
* @return True if the server is running a dev version of FF2, false otherwise
*/
native FF2_GetFF2Version(version[]=0);
/**
* Gets current round state
*
* @return 0 - in setup
* 1 - round is in progress (due to a bug in arena mode, stalemate will also return 1)
* 2 - someone wins
*/
native FF2_GetRoundState();
/**
* Gets UserID of current Boss
*
* @param boss Boss's index
* @return Userid of boss (-1 if Boss does not exist)
*/
native FF2_GetBossUserId(boss=0);
/**
* Gets the boss index of a client
*
* @param client The client used to search for the boss index
* @return Boss index of that client. If client is not boss, returns -1
*/
native FF2_GetBossIndex(client);
/**
* Gets current team of Boss
* @return Number of boss's team
*/
native FF2_GetBossTeam();
/**
* Gets the character name of the Boss
*
* @param boss Boss's index
* @param buffer Buffer for boss' character name
* @param bufferLength Length of buffer string
* @param bossMeaning 0 - "boss" parameter means index of current Boss
* 1 - "boss" parameter means number of Boss in characters.cfg-1
* @return True if boss exists, false if not
*/
native bool:FF2_GetBossSpecial(boss=0, String:buffer[], bufferLength, bossMeaning=0);
/**
* Gets the current health value of the Boss
*
* @param boss Boss's index
* @return Current health of the Boss
*/
native FF2_GetBossHealth(boss=0);
/**
* Sets the health of the Boss
*
* @param boss Boss's index
* @param health New health value
* @noreturn
*/
native FF2_SetBossHealth(boss, health);
/**
* Gets the max health of the Boss
*
* @param boss Boss's index
* @return Max health of the Boss
*/
native FF2_GetBossMaxHealth(boss=0);
/**
* Sets the max health of the Boss
*
* @param boss Boss's index
* @param health New max health value
* @noreturn
*/
native FF2_SetBossMaxHealth(boss, health);
/**
* Gets the current number of lives of the Boss
*
* @param boss Boss's index
* @return Number of lives the boss has remaining
*/
native FF2_GetBossLives(boss);
/**
* Sets the current number of lives of the Boss
*
* @param boss Boss's index
* @param lives New number of lives
* @noreturn
*/
native FF2_SetBossLives(boss, lives);
/**
* Gets the max number of lives of the Boss
*
* @param boss Boss's index
* @return Max number of lives of the Boss
*/
native FF2_GetBossMaxLives(boss);
/**
* Sets the max number of lives of the Boss
*
* @param boss Boss's index
* @param lives New max number of lives
* @noreturn
*/
native FF2_SetBossMaxLives(boss, lives);
/**
* Gets the charge meter value of the Boss
*
* @param boss Boss's index
* @param slot Slot of charge meter
* 0 - rage
* 1 - as usual, used for brave jump or teleport
* 2 - other charged abilities
* @return Charge value of the Boss
*/
native Float:FF2_GetBossCharge(boss, slot);
/**
* Sets the charge meter value of the Boss
*
* @param boss Boss's index
* @param slot Slot of charge meter
* 0 - rage
* 1 - as usual, used for brave jump or teleport
* 2 - other charged abilities
* @param value New value of charge
* @noreturn
*/
native FF2_SetBossCharge(boss, slot, Float:value);
/**
* Gets how much damage is needed in order to activate the rage of the current boss
*
* @param boss Boss index
* @return Total damage needed
*/
native FF2_GetBossRageDamage(boss);
/**
* Sets how much damage is needed in order to activate the rage of the current boss
*
* @param boss Boss index
* @param damage New damage value
* @noreturn
*/
native FF2_SetBossRageDamage(boss, damage);
/**
* Gets damage dealt by this client
*
* @param client Client's index
* @return Damage dealt
*/
native FF2_GetClientDamage(client);
/**
* Gets an ability's rage distance
*
* @param boss Boss's index
* @param pluginName Name of plugin with this ability
* @param abilityName Name of ability (use null string if you want get boss's global "ragedist" value)
* @return Ability's rage distance
*/
native Float:FF2_GetRageDist(boss=0, const String:pluginName[]="", const String:abilityName[]="");
/**
* Finds if a Boss has a certain ability
*
* @param boss Boss's index
* @param pluginName Name of plugin with this ability
* @param abilityName Name of ability
* @return True if the boss has this ability, false if it doesn't
*/
native bool:FF2_HasAbility(boss, const String:pluginName[], const String:abilityName[]);
/**
* Determines how the Boss should use a certain ability
*
* @param boss Boss's index
* @param pluginName Name of plugin with this ability
* @param abilityName Name of ability
* @param slot Slot of charge meter
* 0 - rage
* 1 - as usual, used for brave jump or teleport
* 2 - other charged abilities
* @param buttonMode How to activate the ability
* 0 - by taunt
* 1 - by right mouse button or duck
* 2 - by reload button
* @noreturn
*/
native FF2_DoAbility(boss, const String:pluginName[], const String:abilityName[], slot, buttonMode=0);
/**
* Gets the integer value of an ability argument
*
* @param boss Boss's index
* @param pluginName Name of plugin with this ability
* @param abilityName Name of ability
* @param argument Number of argument
* @param defValue Returns if argument is not defined
* @return Value of argument
*/
native FF2_GetAbilityArgument(boss, const String:pluginName[], const String:abilityName[], argument, defValue=0);
/**
* Gets the float value of an ability argument
*
* @param boss Boss's index
* @param pluginName Name of plugin with this ability
* @param abilityName Name of ability
* @param argument Number of argument
* @param defValue Returns if argument is not defined
* @return Value of argument
*/
native Float:FF2_GetAbilityArgumentFloat(boss, const String:plugin_name[], const String:ability_name[], argument, Float:defValue=0.0);
/**
* Gets the string value of an ability argument
*
* @param boss Boss's index
* @param pluginName Name of plugin with this ability
* @param abilityName Name of ability
* @param argument Number of argument
* @param buffer Buffer for value of argument
* @param bufferLength Length of buffer string
* @noreturn
*/
native FF2_GetAbilityArgumentString(boss, const String:pluginName[], const String:abilityName[], argument, String:buffer[], bufferLength);
/**
* Starts a random Boss sound from its config file
*
* @param keyvalue Name of sound container
* @param buffer Buffer for result sound path
* @param bufferLength Length of buffer
* @param boss Boss's index
* @param slot Only for "sound_ability" - slot of ability
* @return True if sound has been found, false otherwise
*/
native bool:FF2_RandomSound(const String:keyvalue[], String:buffer[], bufferLength, boss=0, slot=0);
/**
* Starts the Boss's music for the specified clients
*
* @param client Client's index (0 for all clients)
* @noreturn
*/
native FF2_StartMusic(client=0);
/**
* Stops the Boss's music for the specified clients
*
* @param client Client's index (0 for all clients)
* @noreturn
*/
native FF2_StopMusic(client=0);
/**
* Gets a Boss's KV handle
*
* @param boss Boss's index
* @param specialIndex 0 - 'boss' parameter refers to the index of the boss
* 1 - 'boss' parameter refers to the index of the boss in characters.cfg-1
* @return Handle of Boss's keyvalues
*/
native Handle:FF2_GetSpecialKV(boss, specialIndex=0);
/**
* Gets a client's flags for FF2
*
* @param client Client's index
* @return Client's FF2 flags
*/
native FF2_GetFF2flags(client);
/**
* Sets a client's flags for FF2
*
* @param client Client's index
* @param flags New flag values
* @noreturn
*/
native FF2_SetFF2flags(client, flags);
/**
* Gets a client's queue points
*
* @param client Client's index
* @return Client's queue points
*/
native FF2_GetQueuePoints(client);
/**
* Sets a client's queue points
*
* @param client Client's index
* @param value New value of client's queue points
* @noreturn
*/
native FF2_SetQueuePoints(client, value);
/**
* Gets a client's glow timer
*
* @param client Client's index
* @return Number of seconds left until client glow disappears (-1 if invalid client)
*/
native Float:FF2_GetClientGlow(client);
/**
* Sets a client's glow timer
*
* @param client Client's index
* @param time1 Number of seconds to add to the glow timer (can be negative)
* @param time2 New value of glow timer
* @noreturn
*/
native FF2_SetClientGlow(client, Float:time1, Float:time2=-1.0);
/**
* Retrieves the number of alive players left (not including bosses)
*
* @return Number of non-boss players left alive
*/
#pragma deprecated Use FF2_OnAlivePlayersChanged
native FF2_GetAlivePlayers();
/**
* Retrieves the number of boss players left (including minions)
*
* @return Number of boss players left alive
*/
#pragma deprecated Use FF2_OnAlivePlayersChanged
native FF2_GetBossPlayers();
/**
* Returns whether or not debug is enabled
* @return True if enabled, false otherwise
*/
native bool:FF2_Debug();
/**
* FF2_ONABILITY IS KNOWN TO BE BUGGED AND WILL NOT BE FIXED TO PRESERVE BACKWARDS COMPATABILITY. DO NOT USE IT.
* Called when a Boss uses an ability (Rage, jump, teleport, etc)
* Called every 0.2 seconds for charge abilities
*
* Use FF2_PreAbility with enabled=false ONLY to prevent FF2_OnAbility!
*
* @param boss Boss's index
* @param pluginName Name of plugin with this ability
* @param abilityName Name of ability
* @param slot Slot of ability (THIS DOES NOT RETURN WHAT YOU THINK IT RETURNS FOR FF2_ONABILITY-if you insist on using this, refer to freak_fortress_2.sp to see what it actually does)
* 0 - Rage or life-loss
* 1 - Jump or teleport
* 2 - Other
* @param status Status of ability (DO NOT ACCESS THIS. IT DOES NOT EXIST AND MIGHT CRASH YOUR SERVER)
* @return Plugin_Stop can not prevent the ability. Use FF2_PreAbility with enabled=false
*/
forward FF2_PreAbility(boss, const String:pluginName[], const String:abilityName[], slot, &bool:enabled);
forward Action:FF2_OnAbility(boss, const String:pluginName[], const String:abilityName[], slot, status);
/**
* Called when a Boss gets hurt by environmental damage
*
* @param boss Boss's index
* @param triggerHurt Entity index of "trigger_hurt"
* @param damage Damage by "trigger_hurt". Cutomizable.
* @return Plugin_Stop will prevent forward, Plugin_Changed will change damage.
*/
forward Action:FF2_OnTriggerHurt(boss, triggerHurt, &Float:damage);
/**
* Called when a Boss's music begins
*
* @param path Path to music sound file
* @param time Length of music
* @return Plugin_Stop will prevent music, Plugin_Changed will change it.
*/
forward Action:FF2_OnMusic(String:path[], &Float:time);
/**
* Called when FF2 picks a character for a Boss
*
* @param boss Boss index
* @param character Character index
* @param characterName Character name
* @param preset True if the boss was set using a command such as ff2_special
* @return You can NOT use Plugin_Stop to prevent this, but you can change characterName and use Plugin_Changed to change the boss. If you want to change 'character', then make 'characterName' null.
*/
forward Action:FF2_OnSpecialSelected(boss, &character, String:characterName[], bool:preset);
/**
* Called when FF2 adds queue points
*
* @param add_points Array that contains each player's queue points
*
* @return Plugin_Stop will prevent this, Plugin_Changed will change it.
*/
forward Action:FF2_OnAddQueuePoints(add_points[MAXPLAYERS+1]);
/**
* Called when FF2 picks a character set for the map
*
* @param charSetNum Number of character set
* @param charSetName Name of character set
* @return You can NOT use Plugin_Stop to prevent this, but you can change charSetName and use Plugin_Changed to change the character set. If you want to change charSetNum, then make charSetName null.
*/
forward Action:FF2_OnLoadCharacterSet(&charSetNum, String:charSetName[]);
/**
* Called when a Boss loses a life
*
* @param boss Boss's index
* @param lives Number of lives left
* @param maxLives Max number of lives
* @return Plugin_Stop or Plugin_Handled to prevent damage that would remove a life, Plugin_Changed if you want to change the number of lives left.
*/
forward Action:FF2_OnLoseLife(boss, &lives, maxLives);
/**
* Called when the number of alive players changes. Note that this will never be 0 as FF2 does not re-calculate the number of players once the round ends.
*
* @param players Number of alive players left on the non-boss team
* @param bosses Number of alive players left on the boss team (this includes minions as well)
* @noreturn
*/
forward Action:FF2_OnAlivePlayersChanged(players, bosses);
/**
*
* Gives ammo to a weapon
*
* @param client Client's index
* @param weapon Weapon
* @param ammo Ammo (set to 1 for clipless weapons, then set the actual ammo using clip)
* @param clip Clip
* @noreturn
*/
stock FF2_SetAmmo(client, weapon, ammo=-1, clip=-1)
{
if(IsValidEntity(weapon))
{
if(clip>-1)
{
SetEntProp(weapon, Prop_Data, "m_iClip1", clip);
}
new ammoType=(ammo>-1 ? GetEntProp(weapon, Prop_Send, "m_iPrimaryAmmoType") : -1);
if(ammoType!=-1)
{
SetEntProp(client, Prop_Data, "m_iAmmo", ammo, _, ammoType);
}
else if(ammo>-1) //Only complain if we're trying to set ammo
{
decl String:classname[64], String:bossName[32];
GetEdictClassname(weapon, classname, sizeof(classname));
FF2_GetBossSpecial(FF2_GetBossIndex(client), bossName, sizeof(bossName));
LogError("[FF2] Cannot give ammo to weapon %s (boss %s)-check your config!", classname, bossName);
}
}
}
/**
* Sends a synced HUD message according to FF2's rules
* Will only send if the client hasn't disabled their HUD and isn't checking the scoreboard
*
* Uses the same params and return values as ShowSyncHudText
*/
stock FF2_ShowSyncHudText(client, Handle:sync, const String:buffer[], any:...)
{
if(!(FF2_GetFF2flags(client) & FF2FLAG_HUDDISABLED) && !(GetClientButtons(client) & IN_SCORE))
{
decl String:message[256];
VFormat(message, sizeof(message), buffer, 4);
ShowSyncHudText(client, sync, message);
}
}
/**
* Sends a HUD message according to FF2's rules
* Will only send if the client hasn't disabled their HUD and isn't checking the scoreboard
*
* Uses the same params and return values as ShowHudText
*/
stock FF2_ShowHudText(client, channel, const String:buffer[], any:...)
{
if(!(FF2_GetFF2flags(client) & FF2FLAG_HUDDISABLED) && !(GetClientButtons(client) & IN_SCORE))
{
decl String:message[256];
VFormat(message, sizeof(message), buffer, 4);
ShowHudText(client, channel, message);
}
}
/**
* Used to consolidate debug messages
*
* @param buffer Debug string to display
* @param any:... Formatting rules
* @noreturn
*/
stock Debug(String:buffer[], any:...)
{
if(FF2_Debug())
{
decl String:message[192];
VFormat(message, sizeof(message), buffer, 2);
CPrintToChatAll("{olive}[FF2 {darkorange}DEBUG{olive}]{default} %s", message);
PrintToServer("[FF2 DEBUG] %s", message);
}
}
// These exist for compatibility reasons (<1.10.1)
#pragma deprecated Use TF2_RemoveWeaponSlot
stock TF2_RemoveWeaponSlot2(client, slot)
{
TF2_RemoveWeaponSlot(client, slot);
}
#pragma deprecated Use TF2_RemoveAllWeapons
stock TF2_RemoveAllWeapons2(client)
{
for(new slot=0; slot<=5; slot++)
{
TF2_RemoveWeaponSlot(client, slot);
}
}
public SharedPlugin:__pl_FF2=
{
name="freak_fortress_2",
file="freak_fortress_2.smx",
#if defined REQUIRE_PLUGIN
required=1,
#else
required=0,
#endif
};
#if !defined REQUIRE_PLUGIN
public __pl_FF2_SetNTVOptional()
{
MarkNativeAsOptional("FF2_IsFF2Enabled");
MarkNativeAsOptional("FF2_GetFF2Version");
MarkNativeAsOptional("FF2_GetBossUserId");
MarkNativeAsOptional("FF2_GetBossIndex");
MarkNativeAsOptional("FF2_GetBossTeam");
MarkNativeAsOptional("FF2_GetBossSpecial");
MarkNativeAsOptional("FF2_GetBossHealth");
MarkNativeAsOptional("FF2_SetBossHealth");
MarkNativeAsOptional("FF2_GetBossMaxHealth");
MarkNativeAsOptional("FF2_SetBossMaxHealth");
MarkNativeAsOptional("FF2_GetBossLives");
MarkNativeAsOptional("FF2_SetBossLives");
MarkNativeAsOptional("FF2_GetBossMaxLives");
MarkNativeAsOptional("FF2_SetBossMaxLives");
MarkNativeAsOptional("FF2_GetBossCharge");
MarkNativeAsOptional("FF2_SetBossCharge");
MarkNativeAsOptional("FF2_GetBossRageDamage");
MarkNativeAsOptional("FF2_SetBossRageDamage");
MarkNativeAsOptional("FF2_GetClientDamage");
MarkNativeAsOptional("FF2_GetRoundState");
MarkNativeAsOptional("FF2_GetRageDist");
MarkNativeAsOptional("FF2_HasAbility");
MarkNativeAsOptional("FF2_GetAbilityArgument");
MarkNativeAsOptional("FF2_GetAbilityArgumentFloat");
MarkNativeAsOptional("FF2_GetAbilityArgumentString");
MarkNativeAsOptional("FF2_RandomSound");
MarkNativeAsOptional("FF2_StartMusic");
MarkNativeAsOptional("FF2_StopMusic");
MarkNativeAsOptional("FF2_GetSpecialKV");
MarkNativeAsOptional("FF2_GetQueuePoints");
MarkNativeAsOptional("FF2_SetQueuePoints");
MarkNativeAsOptional("FF2_GetFF2flags");
MarkNativeAsOptional("FF2_SetFF2flags");
MarkNativeAsOptional("FF2_DoAbility");
MarkNativeAsOptional("FF2_GetClientGlow");
MarkNativeAsOptional("FF2_SetClientGlow");
MarkNativeAsOptional("FF2_GetAlivePlayers");
MarkNativeAsOptional("FF2_GetBossPlayers");
MarkNativeAsOptional("FF2_Debug");
}
#endif

View File

@@ -0,0 +1,641 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _functions_included
#endinput
#endif
#define _functions_included
#define SP_PARAMFLAG_BYREF (1<<0) /**< Internal use only. */
/**
* Describes the various ways to pass parameters to functions or forwards.
*/
enum ParamType
{
Param_Any = 0, /**< Any data type can be pushed */
Param_Cell = (1<<1), /**< Only basic cells can be pushed */
Param_Float = (2<<1), /**< Only floats can be pushed */
Param_String = (3<<1)|SP_PARAMFLAG_BYREF, /**< Only strings can be pushed */
Param_Array = (4<<1)|SP_PARAMFLAG_BYREF, /**< Only arrays can be pushed */
Param_VarArgs = (5<<1), /**< Same as "..." in plugins, anything can be pushed, but it will always be byref */
Param_CellByRef = (1<<1)|SP_PARAMFLAG_BYREF, /**< Only a cell by reference can be pushed */
Param_FloatByRef = (2<<1)|SP_PARAMFLAG_BYREF /**< Only a float by reference can be pushed */
};
/**
* Defines how a forward iterates through plugin functions.
*/
enum ExecType
{
ET_Ignore = 0, /**< Ignore all return values, return 0 */
ET_Single = 1, /**< Only return the last exec, ignore all others */
ET_Event = 2, /**< Acts as an event with the Actions defined in core.inc, no mid-Stops allowed, returns highest */
ET_Hook = 3 /**< Acts as a hook with the Actions defined in core.inc, mid-Stops allowed, returns highest */
};
/**
* @section Flags that are used with Call_PushArrayEx() and Call_PushStringEx()
*/
#define SM_PARAM_COPYBACK (1<<0) /**< Copy an array/reference back after call */
#define SM_PARAM_STRING_UTF8 (1<<0) /**< String should be UTF-8 handled */
#define SM_PARAM_STRING_COPY (1<<1) /**< String should be copied into the plugin */
#define SM_PARAM_STRING_BINARY (1<<2) /**< Treat the string as a binary string */
/**
* @endsection
*/
/**
* @section Error codes
*/
#define SP_ERROR_NONE 0 /**< No error occurred */
#define SP_ERROR_FILE_FORMAT 1 /**< File format unrecognized */
#define SP_ERROR_DECOMPRESSOR 2 /**< A decompressor was not found */
#define SP_ERROR_HEAPLOW 3 /**< Not enough space left on the heap */
#define SP_ERROR_PARAM 4 /**< Invalid parameter or parameter type */
#define SP_ERROR_INVALID_ADDRESS 5 /**< A memory address was not valid */
#define SP_ERROR_NOT_FOUND 6 /**< The object in question was not found */
#define SP_ERROR_INDEX 7 /**< Invalid index parameter */
#define SP_ERROR_STACKLOW 8 /**< Not enough space left on the stack */
#define SP_ERROR_NOTDEBUGGING 9 /**< Debug mode was not on or debug section not found */
#define SP_ERROR_INVALID_INSTRUCTION 10 /**< Invalid instruction was encountered */
#define SP_ERROR_MEMACCESS 11 /**< Invalid memory access */
#define SP_ERROR_STACKMIN 12 /**< Stack went beyond its minimum value */
#define SP_ERROR_HEAPMIN 13 /**< Heap went beyond its minimum value */
#define SP_ERROR_DIVIDE_BY_ZERO 14 /**< Division by zero */
#define SP_ERROR_ARRAY_BOUNDS 15 /**< Array index is out of bounds */
#define SP_ERROR_INSTRUCTION_PARAM 16 /**< Instruction had an invalid parameter */
#define SP_ERROR_STACKLEAK 17 /**< A native leaked an item on the stack */
#define SP_ERROR_HEAPLEAK 18 /**< A native leaked an item on the heap */
#define SP_ERROR_ARRAY_TOO_BIG 19 /**< A dynamic array is too big */
#define SP_ERROR_TRACKER_BOUNDS 20 /**< Tracker stack is out of bounds */
#define SP_ERROR_INVALID_NATIVE 21 /**< Native was pending or invalid */
#define SP_ERROR_PARAMS_MAX 22 /**< Maximum number of parameters reached */
#define SP_ERROR_NATIVE 23 /**< Error originates from a native */
#define SP_ERROR_NOT_RUNNABLE 24 /**< Function or plugin is not runnable */
#define SP_ERROR_ABORTED 25 /**< Function call was aborted */
/**
* @endsection
*/
methodmap GlobalForward < Handle {
// Creates a global forward.
//
// @note The name used to create the forward is used as its public function in all target plugins.
// @note This is ideal for global, static forwards that are never changed.
// @note Global forwards cannot be cloned.
// @note Use CloseHandle() to destroy these.
//
// @param name Name of public function to use in forward.
// @param type Execution type to be used.
// @param ... Variable number of parameter types (up to 32).
// @return Handle to new global forward.
// @error More than 32 parameter types passed.
public native GlobalForward(const char[] name, ExecType type, ParamType ...);
// Returns the number of functions in a global or private forward's call list.
property int FunctionCount {
public native get();
}
};
methodmap PrivateForward < GlobalForward {
// Creates a private forward.
//
// @note No functions are automatically added. Use AddToForward() to do this.
// @note Private forwards can be cloned.
// @note Use CloseHandle() to destroy these.
//
// @param type Execution type to be used.
// @param ... Variable number of parameter types (up to 32).
// @return Handle to new private forward.
// @error More than 32 parameter types passed.
public native PrivateForward(ExecType type, ParamType ...);
// Adds a function to a private forward's call list.
//
// @note Cannot be used during an incomplete call.
//
// @param plugin Handle of the plugin that contains the function.
// Pass INVALID_HANDLE to specify the calling plugin.
// @param func Function to add to forward.
// @return True on success, false otherwise.
// @error Invalid or corrupt private forward handle, invalid or corrupt plugin handle, or invalid function.
public native bool AddFunction(Handle plugin, Function func);
// Removes a function from a private forward's call list.
//
// @note Only removes one instance.
// @note Functions will be removed automatically if their parent plugin is unloaded.
//
// @param plugin Handle of the plugin that contains the function.
// Pass INVALID_HANDLE to specify the calling plugin.
// @param func Function to remove from forward.
// @return True on success, false otherwise.
// @error Invalid or corrupt private forward handle, invalid or corrupt plugin handle, or invalid function.
public native bool RemoveFunction(Handle plugin, Function func);
// Removes all instances of a plugin from a private forward's call list.
//
// @note Functions will be removed automatically if their parent plugin is unloaded.
//
// @param plugin Handle of the plugin to remove instances of.
// Pass INVALID_HANDLE to specify the calling plugin.
// @return Number of functions removed from forward.
// @error Invalid or corrupt private forward handle or invalid or corrupt plugin handle.
public native int RemoveAllFunctions(Handle plugin);
};
/**
* Gets a function id from a function name.
*
* @param plugin Handle of the plugin that contains the function.
* Pass INVALID_HANDLE to search in the calling plugin.
* @param name Name of the function.
* @return Function id or INVALID_FUNCTION if not found.
* @error Invalid or corrupt plugin handle.
*/
native Function GetFunctionByName(Handle plugin, const char[] name);
/**
* Creates a global forward.
*
* @note The name used to create the forward is used as its public function in all target plugins.
* @note This is ideal for global, static forwards that are never changed.
* @note Global forwards cannot be cloned.
* @note Use CloseHandle() to destroy these.
*
* @param name Name of public function to use in forward.
* @param type Execution type to be used.
* @param ... Variable number of parameter types (up to 32).
* @return Handle to new global forward.
* @error More than 32 parameter types passed.
*/
native GlobalForward CreateGlobalForward(const char[] name, ExecType type, ParamType ...);
/**
* Creates a private forward.
*
* @note No functions are automatically added. Use AddToForward() to do this.
* @note Private forwards can be cloned.
* @note Use CloseHandle() to destroy these.
*
* @param type Execution type to be used.
* @param ... Variable number of parameter types (up to 32).
* @return Handle to new private forward.
* @error More than 32 parameter types passed.
*/
native PrivateForward CreateForward(ExecType type, ParamType ...);
/**
* Returns the number of functions in a global or private forward's call list.
*
* @param fwd Handle to global or private forward.
* @return Number of functions in forward.
* @error Invalid or corrupt forward handle.
*/
native int GetForwardFunctionCount(Handle fwd);
/**
* Adds a function to a private forward's call list.
*
* @note Cannot be used during an incomplete call.
*
* @param fwd Handle to private forward.
* @param plugin Handle of the plugin that contains the function.
* Pass INVALID_HANDLE to specify the calling plugin.
* @param func Function to add to forward.
* @return True on success, false otherwise.
* @error Invalid or corrupt private forward handle, invalid or corrupt plugin handle, or invalid function.
*/
native bool AddToForward(Handle fwd, Handle plugin, Function func);
/**
* Removes a function from a private forward's call list.
*
* @note Only removes one instance.
* @note Functions will be removed automatically if their parent plugin is unloaded.
*
* @param fwd Handle to private forward.
* @param plugin Handle of the plugin that contains the function.
* Pass INVALID_HANDLE to specify the calling plugin.
* @param func Function to remove from forward.
* @return True on success, false otherwise.
* @error Invalid or corrupt private forward handle, invalid or corrupt plugin handle, or invalid function.
*/
native bool RemoveFromForward(Handle fwd, Handle plugin, Function func);
/**
* Removes all instances of a plugin from a private forward's call list.
*
* @note Functions will be removed automatically if their parent plugin is unloaded.
*
* @param fwd Handle to private forward.
* @param plugin Handle of the plugin to remove instances of.
* Pass INVALID_HANDLE to specify the calling plugin.
* @return Number of functions removed from forward.
* @error Invalid or corrupt private forward handle or invalid or corrupt plugin handle.
*/
native int RemoveAllFromForward(Handle fwd, Handle plugin);
/**
* Starts a call to functions in a forward's call list.
*
* @note Cannot be used during an incomplete call.
*
* @param fwd Handle to global or private forward.
* @error Invalid or corrupt forward handle or called before another call has completed.
*/
native void Call_StartForward(Handle fwd);
/**
* Starts a call to a function.
*
* @note Cannot be used during an incomplete call.
*
* @param plugin Handle of the plugin that contains the function.
* Pass INVALID_HANDLE to specify the calling plugin.
* @param func Function to call.
* @error Invalid or corrupt plugin handle, invalid function, or called before another call has completed.
*/
native void Call_StartFunction(Handle plugin, Function func);
/**
* Pushes a cell onto the current call.
*
* @note Cannot be used before a call has been started.
*
* @param value Cell value to push.
* @error Called before a call has been started.
*/
native void Call_PushCell(any value);
/**
* Pushes a cell by reference onto the current call.
*
* @note Cannot be used before a call has been started.
*
* @param value Cell reference to push.
* @error Called before a call has been started.
*/
native void Call_PushCellRef(any &value);
/**
* Pushes a float onto the current call.
*
* @note Cannot be used before a call has been started.
*
* @param value Floating point value to push.
* @error Called before a call has been started.
*/
native void Call_PushFloat(float value);
/**
* Pushes a float by reference onto the current call.
*
* @note Cannot be used before a call has been started.
*
* @param value Floating point reference to push.
* @error Called before a call has been started.
*/
native void Call_PushFloatRef(float &value);
/**
* Pushes an array onto the current call.
*
* @note Changes to array are not copied back to caller. Use PushArrayEx() to do this.
* @note Cannot be used before a call has been started.
*
* @param value Array to push.
* @param size Size of array.
* @error Called before a call has been started.
*/
native void Call_PushArray(const any[] value, int size);
/**
* Pushes an array onto the current call.
*
* @note Cannot be used before a call has been started.
*
* @param value Array to push.
* @param size Size of array.
* @param cpflags Whether or not changes should be copied back to the input array.
* See SM_PARAM_* constants for details.
* @error Called before a call has been started.
*/
native void Call_PushArrayEx(any[] value, int size, int cpflags);
/**
* Pushes the NULL_VECTOR onto the current call.
* @see IsNullVector
*
* @note Cannot be used before a call has been started.
*
* @error Called before a call has been started.
*/
native void Call_PushNullVector();
/**
* Pushes a string onto the current call.
*
* @note Changes to string are not copied back to caller. Use PushStringEx() to do this.
* @note Cannot be used before a call has been started.
*
* @param value String to push.
* @error Called before a call has been started.
*/
native void Call_PushString(const char[] value);
/**
* Pushes a string onto the current call.
*
* @note Cannot be used before a call has been started.
*
* @param value String to push.
* @param length Length of string buffer.
* @param szflags Flags determining how string should be handled.
* See SM_PARAM_STRING_* constants for details.
* The default (0) is to push ASCII.
* @param cpflags Whether or not changes should be copied back to the input array.
* See SM_PARAM_* constants for details.
* @error Called before a call has been started.
*/
native void Call_PushStringEx(char[] value, int length, int szflags, int cpflags);
/**
* Pushes the NULL_STRING onto the current call.
* @see IsNullString
*
* @note Cannot be used before a call has been started.
*
* @error Called before a call has been started.
*/
native void Call_PushNullString();
/**
* Completes a call to a function or forward's call list.
*
* @note Cannot be used before a call has been started.
*
* @param result Return value of function or forward's call list.
* @return SP_ERROR_NONE on success, any other integer on failure.
* @error Called before a call has been started.
*/
native int Call_Finish(any &result=0);
/**
* Cancels a call to a function or forward's call list.
*
* @note Cannot be used before a call has been started.
*
* @error Called before a call has been started.
*/
native void Call_Cancel();
typeset NativeCall
{
/**
* Defines a native function.
*
* It is not necessary to validate the parameter count
*
* @param plugin Handle of the calling plugin.
* @param numParams Number of parameters passed to the native.
* @return Value for the native call to return.
*/
function int (Handle plugin, int numParams);
/**
* Defines a native function.
*
* It is not necessary to validate the parameter count
*
* @param plugin Handle of the calling plugin.
* @param numParams Number of parameters passed to the native.
* @return Value for the native call to return.
*/
function any (Handle plugin, int numParams);
/**
* Defines a native function.
*
* It is not necessary to validate the parameter count
*
* @param plugin Handle of the calling plugin.
* @param numParams Number of parameters passed to the native.
*/
function void (Handle plugin, int numParams);
}
/**
* Creates a dynamic native. This should only be called in AskPluginLoad(), or
* else you risk not having your native shared with other plugins.
*
* @param name Name of the dynamic native; must be unique among
* all other registered dynamic natives.
* @param func Function to use as the dynamic native.
*/
native void CreateNative(const char[] name, NativeCall func);
/**
* Throws an error in the calling plugin of a native, instead of your own plugin.
*
* @param error Error code to use.
* @param fmt Error message format.
* @param ... Format arguments.
* @noreturn
* @error Always!
*/
native int ThrowNativeError(int error, const char[] fmt, any ...);
/**
* Retrieves the string length from a native parameter string. This is useful for
* fetching the entire string using dynamic arrays.
*
* @note If this function succeeds, Get/SetNativeString will also succeed.
*
* @param param Parameter number, starting from 1.
* @param length Stores the length of the string.
* @return SP_ERROR_NONE on success, any other integer on failure.
* @error Invalid parameter number or calling from a non-native function.
*/
native int GetNativeStringLength(int param, int &length);
/**
* Retrieves a string from a native parameter.
*
* @note Output conditions are undefined on failure.
*
* @param param Parameter number, starting from 1.
* @param buffer Buffer to store the string in.
* @param maxlength Maximum length of the buffer.
* @param bytes Optionally store the number of bytes written.
* @return SP_ERROR_NONE on success, any other integer on failure.
* @error Invalid parameter number or calling from a non-native function.
*/
native int GetNativeString(int param, char[] buffer, int maxlength, int &bytes=0);
/**
* Sets a string in a native parameter.
*
* @note Output conditions are undefined on failure.
*
* @param param Parameter number, starting from 1.
* @param source Source string to use.
* @param maxlength Maximum number of bytes to write.
* @param utf8 If false, string will not be written
* with UTF8 safety.
* @param bytes Optionally store the number of bytes written.
* @return SP_ERROR_NONE on success, any other integer on failure.
* @error Invalid parameter number or calling from a non-native function.
*/
native int SetNativeString(int param, const char[] source, int maxlength, bool utf8=true, int &bytes=0);
/**
* Gets a cell from a native parameter.
*
* @param param Parameter number, starting from 1.
* @return Cell value at the parameter number.
* @error Invalid parameter number or calling from a non-native function.
*/
native any GetNativeCell(int param);
/**
* Gets a function pointer from a native parameter.
*
* @param param Parameter number, starting from 1.
* @return Function pointer at the given parameter number.
* @error Invalid parameter number, or calling from a non-native function.
*/
native Function GetNativeFunction(int param);
/**
* Gets a cell from a native parameter, by reference.
*
* @param param Parameter number, starting from 1.
* @return Cell value at the parameter number.
* @error Invalid parameter number or calling from a non-native function.
*/
native any GetNativeCellRef(int param);
/**
* Sets a cell from a native parameter, by reference.
*
* @param param Parameter number, starting from 1.
* @param value Cell value at the parameter number to set by reference.
* @error Invalid parameter number or calling from a non-native function.
*/
native void SetNativeCellRef(int param, any value);
/**
* Gets an array from a native parameter (always by reference).
*
* @param param Parameter number, starting from 1.
* @param local Local array to copy into.
* @param size Maximum size of local array.
* @return SP_ERROR_NONE on success, anything else on failure.
* @error Invalid parameter number or calling from a non-native function.
*/
native int GetNativeArray(int param, any[] local, int size);
/**
* Copies a local array into a native parameter array (always by reference).
*
* @param param Parameter number, starting from 1.
* @param local Local array to copy from.
* @param size Size of the local array to copy.
* @return SP_ERROR_NONE on success, anything else on failure.
* @error Invalid parameter number or calling from a non-native function.
*/
native int SetNativeArray(int param, const any[] local, int size);
/**
* Check if the native parameter is the NULL_VECTOR.
*
* @param param Parameter number, starting from 1.
* @return True if NULL_VECTOR, false otherwise.
*/
native bool IsNativeParamNullVector(int param);
/**
* Check if the native parameter is the NULL_STRING.
*
* @param param Parameter number, starting from 1.
* @return True if NULL_STRING, false otherwise.
*/
native bool IsNativeParamNullString(int param);
/**
* Formats a string using parameters from a native.
*
* @note All parameter indexes start at 1.
* @note If the input and output buffers overlap, the contents
* of the output buffer at the end is undefined.
*
* @param out_param Output parameter number to write to. If 0, out_string is used.
* @param fmt_param Format parameter number. If 0, fmt_string is used.
* @param vararg_param First variable parameter number.
* @param out_len Output string buffer maximum length (always required).
* @param written Optionally stores the number of bytes written.
* @param out_string Output string buffer to use if out_param is not used.
* @param fmt_string Format string to use if fmt_param is not used.
* @return SP_ERROR_NONE on success, anything else on failure.
*/
native int FormatNativeString(int out_param,
int fmt_param,
int vararg_param,
int out_len,
int &written=0,
char[] out_string="",
const char[] fmt_string="");
/**
* Defines a RequestFrame Callback.
*
* @param data Data passed to the RequestFrame native.
*/
typeset RequestFrameCallback {
function void ();
function void (any data);
}
/**
* Creates a single use Next Frame hook.
*
* @param Function Function to call on the next frame.
* @param data Value to be passed on the invocation of the Function.
*/
native void RequestFrame(RequestFrameCallback Function, any data=0);

241
scripting/include/geoip.inc Normal file
View File

@@ -0,0 +1,241 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _geoip_included
#endinput
#endif
#define _geoip_included
enum Continent
{
CONTINENT_UNKNOWN = 0,
CONTINENT_AFRICA,
CONTINENT_ANTARCTICA,
CONTINENT_ASIA,
CONTINENT_EUROPE,
CONTINENT_NORTH_AMERICA,
CONTINENT_OCEANIA,
CONTINENT_SOUTH_AMERICA,
};
// The system of measurement for calculate the distance between geographical coordinates
#define SYSTEM_METRIC 0 // kilometers
#define SYSTEM_IMPERIAL 1 // statute miles
#include <core>
/**
* @section IP addresses can contain ports, the ports will be stripped out.
*/
/**
* Gets the two character country code from an IP address. (US, CA, etc)
*
* @param ip Ip to determine the country code.
* @param ccode Destination string buffer to store the code.
* @return True on success, false otherwise.
*/
native bool GeoipCode2(const char[] ip, char ccode[3]);
/**
* Gets the three character country code from an IP address. (USA, CAN, etc)
*
* @param ip Ip to determine the country code.
* @param ccode Destination string buffer to store the code.
* @return True on success, false otherwise.
*/
native bool GeoipCode3(const char[] ip, char ccode[4]);
/**
* Gets the region code with country code from an IP address. (US-IL, CH-CHE, etc)
*
* @param ip Ip to determine the region code.
* @param ccode Destination string buffer to store the code.
* @return True on success, false otherwise.
*/
native bool GeoipRegionCode(const char[] ip, char ccode[12]);
/**
* Gets the two character continent code from an IP address. (EU, AS, etc)
*
* @param ip Ip to determine the continent code.
* @param ccode Destination string buffer to store the code.
* @return The continent id on success, 0 otherwise.
*/
native Continent GeoipContinentCode(const char[] ip, char ccode[3]);
/**
* Gets the full country name.
*
* @param ip Ip to determine the country code.
* @param name Destination string buffer to store the country name.
* @param maxlength Maximum length of output string buffer.
* @return True on success, false otherwise.
*/
native bool GeoipCountry(const char[] ip, char[] name, int maxlength);
/**
* Gets the full country name.
*
* @param ip Ip to determine the country code.
* @param name Destination string buffer to store the country name.
* @param maxlength Maximum length of output string buffer.
* @param client Client index in order to return the result in the player's language
* -1: the default language, which is english.
* 0: the server language. You can use LANG_SERVER define.
* >=1: the player's language.
* @return True on success, false otherwise.
*/
native bool GeoipCountryEx(const char[] ip, char[] name, int maxlength, int client = -1);
/**
* Gets the full continent name.
*
* @param ip Ip to determine the continent code.
* @param name Destination string buffer to store the continent name.
* @param maxlength Maximum length of output string buffer.
* @param client Client index in order to return the result in the player's language
* -1: the default language, which is english.
* 0: the server language. You can use LANG_SERVER define.
* >=1: the player's language.
* @return True on success, false otherwise.
*/
native bool GeoipContinent(const char[] ip, char[] name, int maxlength, int client = -1);
/**
* Gets the full region name.
*
* @param ip Ip to determine the region code.
* @param name Destination string buffer to store the region name.
* @param maxlength Maximum length of output string buffer.
* @param client Client index in order to return the result in the player's language
* -1: the default language, which is english.
* 0: the server language. You can use LANG_SERVER define.
* >=1: the player's language.
* @return True on success, false otherwise.
*/
native bool GeoipRegion(const char[] ip, char[] name, int maxlength, int client = -1);
/**
* Gets the city name.
*
* @param ip Ip to determine the city code.
* @param name Destination string buffer to store the city name.
* @param maxlength Maximum length of output string buffer.
* @param client Client index in order to return the result in the player's language
* -1: the default language, which is english.
* 0: the server language. You can use LANG_SERVER define.
* >=1: the player's language.
* @return True on success, false otherwise.
*/
native bool GeoipCity(const char[] ip, char[] name, int maxlength, int client = -1);
/**
* Gets the timezone.
*
* @param ip Ip to determine the timezone.
* @param name Destination string buffer to store the timezone.
* @param maxlength Maximum length of output string buffer.
* @return True on success, false otherwise.
*/
native bool GeoipTimezone(const char[] ip, char[] name, int maxlength);
/**
* Gets the city's latitude
*
* @param ip Ip to determine the city latitude.
* @return The result of the latitude, 0 if latitude is not found
*/
native float GeoipLatitude(const char[] ip);
/**
* Gets the city's longitude
*
* @param ip Ip to determine the city longitude.
* @return The result of the longitude, 0 if longitude is not found
*/
native float GeoipLongitude(const char[] ip);
/*
* Calculate the distance between geographical coordinates, latitude and longitude.
*
* @param lat1 The first IP latitude.
* @param lon1 The first IP longitude.
* @param lat2 The second IP latitude.
* @param lon2 The second IP longitude.
* @param system The system of measurement, 0 = Metric(kilometers) or 1 = English(miles).
*
* @return The distance as result in specified system of measurement.
*/
native float GeoipDistance(float lat1, float lon1, float lat2, float lon2, int system = SYSTEM_METRIC);
/**
* @endsection
*/
/**
* Do not edit below this line!
*/
public Extension __ext_geoip =
{
name = "GeoIP",
file = "geoip.ext",
#if defined AUTOLOAD_EXTENSIONS
autoload = 1,
#else
autoload = 0,
#endif
#if defined REQUIRE_EXTENSIONS
required = 1,
#else
required = 0,
#endif
};
#if !defined REQUIRE_EXTENSIONS
public void __ext_geoip_SetNTVOptional()
{
MarkNativeAsOptional("GeoipCode2");
MarkNativeAsOptional("GeoipCode3");
MarkNativeAsOptional("GeoipRegionCode");
MarkNativeAsOptional("GeoipContinentCode");
MarkNativeAsOptional("GeoipCountry");
MarkNativeAsOptional("GeoipCountryEx");
MarkNativeAsOptional("GeoipContinent");
MarkNativeAsOptional("GeoipRegion");
MarkNativeAsOptional("GeoipCity");
MarkNativeAsOptional("GeoipTimezone");
MarkNativeAsOptional("GeoipLatitude");
MarkNativeAsOptional("GeoipLongitude");
MarkNativeAsOptional("GeoipDistance");
}
#endif

View File

@@ -0,0 +1,95 @@
#if defined _goomba_included_
#endinput
#endif
#define _goomba_included_
public SharedPlugin:__pl_goomba =
{
name = "goomba",
file = "goomba.smx",
#if defined REQUIRE_PLUGIN
required = 1,
#else
required = 0,
#endif
};
public __pl_ircrelay_SetNTVOptional()
{
MarkNativeAsOptional("GoombaStomp");
MarkNativeAsOptional("CheckStompImmunity");
MarkNativeAsOptional("PlayStompSound");
MarkNativeAsOptional("PlayStompReboundSound");
MarkNativeAsOptional("EmitStompParticles");
}
/**
* @brief Called right before the stomp
*
* @param attacker Player doing the stomp
* @param victim Player being stomped
* @param damageMultiplier Damage multiplier based on the actual victim's life
* @param damageBonus Damage bonus
* @param JumpPower Rebound jump power
* @return Plugin_Handled to block the stomp, Plugin_Changed to modify the damage
*/
forward Action:OnStomp(attacker, victim, &Float:damageMultiplier, &Float:damageBonus, &Float:JumpPower);
/**
* @brief Called after the stomp if it was successful
*
* @param attacker Player doing the stomp
* @param victim Player being stomped
* @param damageMultiplier Damage multiplier based on the actual victim's life
* @param damageBonus Damage bonus
* @param JumpPower Rebound jump power
* @noreturn
*/
forward OnStompPost(attacker, victim, Float:damageMultiplier, Float:damageBonus, Float:jumpPower);
/**
* @brief Stomp
*
* @param attacker Player doing the stomp
* @param victim Player being stomped
* @param damageMultiplier Damage inflicted based on the victim's health (default: goomba_dmg_lifemultiplier)
* @param damageBonus Damage bonus after damageMultiplier calculation (default: goomba_dmg_add)
* @param jumpPower Jump power of the rebound (default: goomba_rebound_power)
* @return True if the stomp was successful, false otherwise.
*/
native bool:GoombaStomp(attacker, victim, ...);
/**
* @param attacker Player doing the stomp
* @param victim Player being stomped
* @return Bit flags combination based on the attacker and victim's immunity preferences
*/
native CheckStompImmunity(attacker, victim);
/**
* @brief Play the stomped sound to the specified client
*
* @param client Client to play the stomped sound to.
* @noreturn
*/
native PlayStompSound(client);
/**
* @brief Play the rebound sound from the specified client to everyone
*
* @param client Player to play the rebound sound from.
* @noreturn
*/
native PlayStompReboundSound(client);
/**
* @brief Attach the rebound particles on the specified player
*
* @param client Player to attach the particles on
* @noreturn
*/
native EmitStompParticles(client);
#define GOOMBA_IMMUNFLAG_NONE 0
#define GOOMBA_IMMUNFLAG_ATTACKER (1 << 0)
#define GOOMBA_IMMUNFLAG_VICTIM (1 << 1)

View File

@@ -0,0 +1,722 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2016 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _halflife_included
#endinput
#endif
#define _halflife_included
#define SOURCE_SDK_UNKNOWN 0 /**< Could not determine the engine version */
#define SOURCE_SDK_ORIGINAL 10 /**< Original Source engine (still used by "The Ship") */
#define SOURCE_SDK_DARKMESSIAH 15 /**< Modified version of original engine used by Dark Messiah (no SDK) */
#define SOURCE_SDK_EPISODE1 20 /**< SDK+Engine released after Episode 1 */
#define SOURCE_SDK_EPISODE2 30 /**< SDK+Engine released after Episode 2/Orange Box */
#define SOURCE_SDK_BLOODYGOODTIME 32 /**< Modified version of ep2 engine used by Bloody Good Time (no SDK) */
#define SOURCE_SDK_EYE 33 /**< Modified version of ep2 engine used by E.Y.E Divine Cybermancy (no SDK) */
#define SOURCE_SDK_CSS 34 /**< Sometime-older version of Source 2009 SDK+Engine, used for Counter-Strike: Source */
#define SOURCE_SDK_EPISODE2VALVE 35 /**< SDK+Engine released after Episode 2/Orange Box, "Source 2009" or "Source MP" */
#define SOURCE_SDK_LEFT4DEAD 40 /**< Engine released after Left 4 Dead (no SDK yet) */
#define SOURCE_SDK_LEFT4DEAD2 50 /**< Engine released after Left 4 Dead 2 (no SDK yet) */
#define SOURCE_SDK_ALIENSWARM 60 /**< SDK+Engine released after Alien Swarm */
#define SOURCE_SDK_CSGO 80 /**< Engine released after CS:GO (no SDK yet) */
#define SOURCE_SDK_DOTA 90 /**< Engine released after Dota 2 (no SDK) */
#define MOTDPANEL_TYPE_TEXT 0 /**< Treat msg as plain text */
#define MOTDPANEL_TYPE_INDEX 1 /**< Msg is auto determined by the engine */
#define MOTDPANEL_TYPE_URL 2 /**< Treat msg as an URL link */
#define MOTDPANEL_TYPE_FILE 3 /**< Treat msg as a filename to be opened */
enum DialogType
{
DialogType_Msg = 0, /**< just an on screen message */
DialogType_Menu, /**< an options menu */
DialogType_Text, /**< a richtext dialog */
DialogType_Entry, /**< an entry box */
DialogType_AskConnect /**< ask the client to connect to a specified IP */
};
enum EngineVersion
{
Engine_Unknown, /**< Could not determine the engine version */
Engine_Original, /**< Original Source Engine (used by The Ship) */
Engine_SourceSDK2006, /**< Episode 1 Source Engine (second major SDK) */
Engine_SourceSDK2007, /**< Orange Box Source Engine (third major SDK) */
Engine_Left4Dead, /**< Left 4 Dead */
Engine_DarkMessiah, /**< Dark Messiah Multiplayer (based on original engine) */
Engine_Left4Dead2 = 7, /**< Left 4 Dead 2 */
Engine_AlienSwarm, /**< Alien Swarm (and Alien Swarm SDK) */
Engine_BloodyGoodTime, /**< Bloody Good Time */
Engine_EYE, /**< E.Y.E Divine Cybermancy */
Engine_Portal2, /**< Portal 2 */
Engine_CSGO, /**< Counter-Strike: Global Offensive */
Engine_CSS, /**< Counter-Strike: Source */
Engine_DOTA, /**< Dota 2 */
Engine_HL2DM, /**< Half-Life 2 Deathmatch */
Engine_DODS, /**< Day of Defeat: Source */
Engine_TF2, /**< Team Fortress 2 */
Engine_NuclearDawn, /**< Nuclear Dawn */
Engine_SDK2013, /**< Source SDK 2013 */
Engine_Blade, /**< Blade Symphony */
Engine_Insurgency, /**< Insurgency (2013 Retail version)*/
Engine_Contagion, /**< Contagion */
Engine_BlackMesa, /**< Black Mesa Multiplayer */
Engine_DOI, /**< Day of Infamy */
Engine_PVKII = 26, /**< Pirates, Vikings, and Knights II */
Engine_MCV, /**< Military Conflict: Vietnam */
};
enum FindMapResult
{
// A direct match for this name was found
FindMap_Found,
// No match for this map name could be found.
FindMap_NotFound,
// A fuzzy match for this map name was found.
// Ex: cp_dust -> cp_dustbowl, c1m1 -> c1m1_hotel
// Only supported for maps that the engine knows about. (This excludes workshop maps on Orangebox).
FindMap_FuzzyMatch,
// A non-canonical match for this map name was found.
// Ex: workshop/1234 -> workshop/cp_qualified_name.ugc1234
// Only supported on "Orangebox" games with workshop support.
FindMap_NonCanonical,
// No currently available match for this map name could be found, but it may be possible to load
// Only supported on "Orangebox" games with workshop support.
FindMap_PossiblyAvailable
};
#define INVALID_ENT_REFERENCE 0xFFFFFFFF
/**
* Logs a generic message to the HL2 logs.
*
* @param format String format.
* @param ... Format arguments.
*/
native void LogToGame(const char[] format, any ...);
/**
* Sets the seed value for the global Half-Life 2 Random Stream.
*
* @param seed Seed value.
*/
native void SetRandomSeed(int seed);
/**
* Returns a random floating point number from the Half-Life 2 Random Stream.
*
* @param fMin Minimum random bound.
* @param fMax Maximum random bound.
* @return A random number between (inclusive) fMin and fMax.
*/
native float GetRandomFloat(float fMin=0.0, float fMax=1.0);
/**
* Returns a random number from the Half-Life 2 Random Stream.
*
* @param nmin Minimum random bound.
* @param nmax Maximum random bound.
* @return A random number between (inclusive) nmin and nmax.
*/
native int GetRandomInt(int nmin, int nmax);
/**
* Returns whether a map is valid or not.
*
* @param map Map name, excluding .bsp extension.
* @return True if valid, false otherwise.
*/
native bool IsMapValid(const char[] map);
/**
* Returns whether a full or partial map name is found or can be resolved
*
* @param map Map name (usually same as map path relative to maps/ dir,
* excluding .bsp extension).
* @param foundmap Resolved map name. If the return is FindMap_FuzzyMatch
* or FindMap_NonCanonical the buffer will be the full path.
* @param maxlen Maximum length to write to map var.
* @return Result of the find operation. Not all result types are supported on all games.
*/
native FindMapResult FindMap(const char[] map, char[] foundmap, int maxlen);
/**
* Get the display name of a workshop map.
*
* Note: You do not need to call FindMap first. This native will call FindMap internally.
*
* @param map Map name (usually same as map path relative to maps/ dir,
* excluding .bsp extension).
* @param displayName Map's display name, i.e. cp_mymapname or de_mymapname.
* If FindMap returns FindMap_PossiblyAvailable or FindMap_NotFound,
* the map cannot be resolved and this native will return false,
* but displayName will be a copy of map.
* @param maxlen Maximum length to write to displayName var.
* @return true if FindMap returns FindMap_Found, FindMap_FuzzyMatch, or
* FindMap_NonCanonical.
* false if FindMap returns FindMap_PossiblyAvailable or FindMap_NotFound.
*/
native bool GetMapDisplayName(const char[] map, char[] displayName, int maxlen);
/**
* Returns whether the server is dedicated.
*
* @return True if dedicated, false otherwise.
*/
native bool IsDedicatedServer();
/**
* Returns a high-precision time value for profiling the engine.
*
* @return A floating point time value.
*/
native float GetEngineTime();
/**
* Returns the game time based on the game tick.
*
* @return Game tick time.
*/
native float GetGameTime();
/**
* Returns the game's internal tick count.
*
* @return Game tick count.
*/
native int GetGameTickCount();
/**
* Returns the time the Game took processing the last frame.
*
* @return Game frame time.
*/
native float GetGameFrameTime();
/**
* Returns the game description from the mod.
*
* @param buffer Buffer to store the description.
* @param maxlength Maximum size of the buffer.
* @param original If true, retrieves the original game description,
* ignoring any potential hooks from plugins.
* @return Number of bytes written to the buffer (UTF-8 safe).
*/
native int GetGameDescription(char[] buffer, int maxlength, bool original=false);
/**
* Returns the name of the game's directory.
*
* @param buffer Buffer to store the directory name.
* @param maxlength Maximum size of the buffer.
* @return Number of bytes written to the buffer (UTF-8 safe).
*/
native int GetGameFolderName(char[] buffer, int maxlength);
/**
* Returns the current map name.
*
* @param buffer Buffer to store map name.
* @param maxlength Maximum length of buffer.
* @return Number of bytes written (UTF-8 safe).
*/
native int GetCurrentMap(char[] buffer, int maxlength);
/**
* Precaches a given model.
*
* @param model Name of the model to precache.
* @param preload If preload is true the file will be precached before level startup.
* @return Returns the model index, 0 for error.
*/
native int PrecacheModel(const char[] model, bool preload=false);
/**
* Precaches a given sentence file.
*
* @param file Name of the sentence file to precache.
* @param preload If preload is true the file will be precached before level startup.
* @return Returns a sentence file index.
*/
native int PrecacheSentenceFile(const char[] file, bool preload=false);
/**
* Precaches a given decal.
*
* @param decal Name of the decal to precache.
* @param preload If preload is true the file will be precached before level startup.
* @return Returns a decal index.
*/
native int PrecacheDecal(const char[] decal, bool preload=false);
/**
* Precaches a given generic file.
*
* @param generic Name of the generic file to precache.
* @param preload If preload is true the file will be precached before level startup.
* @return Returns a generic file index.
*/
native int PrecacheGeneric(const char[] generic, bool preload=false);
/**
* Returns if a given model is precached.
*
* @param model Name of the model to check.
* @return True if precached, false otherwise.
*/
native bool IsModelPrecached(const char[] model);
/**
* Returns if a given decal is precached.
*
* @param decal Name of the decal to check.
* @return True if precached, false otherwise.
*/
native bool IsDecalPrecached(const char[] decal);
/**
* Returns if a given generic file is precached.
*
* @param generic Name of the generic file to check.
* @return True if precached, false otherwise.
*/
native bool IsGenericPrecached(const char[] generic);
/**
* Precaches a given sound.
*
* @param sound Name of the sound to precache.
* @param preload If preload is true the file will be precached before level startup.
* @return True if successfully precached, false otherwise.
*/
native bool PrecacheSound(const char[] sound, bool preload=false);
/**
* Returns if a given sound is precached.
*
* @param sound Name of the sound to check.
* @return True if precached, false otherwise.
* @deprecated Doesn't work correctly, always returns true.
*/
#pragma deprecated Doesn't work correctly, always returns true.
native bool IsSoundPrecached(const char[] sound);
/**
* Creates different types of ingame messages.
*
* Note: On many newer games (Left 4 Dead/2008+), the display of this to clients is broken.
* Additionally, as of 2018, some games also require the client to have cl_showpluginmessages
* set to 1, a non-default value, for this to function.
*
* @param client Index of the client.
* @param kv KeyValues handle to set the menu keys and options. (Check iserverplugin.h for more information).
* @param type Message type to display ingame.
* @error Invalid client index, or client not in game.
*/
native void CreateDialog(int client, Handle kv, DialogType type);
/**
* Guesses the SDK version a mod was compiled against. If nothing
* specific is known about the game, the engine version is used instead.
*
* The return values are guaranteed to increase chronologically (that is,
* a later release will have a higher value).
*
* @return SOURCE_SDK version code.
* @deprecated See GetEngineVersion()
*/
#pragma deprecated See GetEngineVersion()
native int GuessSDKVersion();
/**
* Gets the engine version that the currently-loaded SM core was compiled against.
*
* The engine version values are not guaranteed to be in any particular order,
* and should only be compared by (in)equality.
*
* @return An EngineVersion value.
*/
native EngineVersion GetEngineVersion();
/**
* Prints a message to a specific client in the chat area.
*
* @param client Client index.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
* @error Invalid client index, or client not in game.
*/
native void PrintToChat(int client, const char[] format, any ...);
/**
* Prints a message to all clients in the chat area.
*
* @param format Formatting rules.
* @param ... Variable number of format parameters.
*/
stock void PrintToChatAll(const char[] format, any ...)
{
char buffer[254];
for (int i = 1; i <= MaxClients; i++)
{
if (IsClientInGame(i))
{
SetGlobalTransTarget(i);
VFormat(buffer, sizeof(buffer), format, 2);
PrintToChat(i, "%s", buffer);
}
}
}
/**
* Prints a message to a specific client in the center of the screen.
*
* @param client Client index.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
* @error Invalid client index, or client not in game.
*/
native void PrintCenterText(int client, const char[] format, any ...);
/**
* Prints a message to all clients in the center of the screen.
*
* @param format Formatting rules.
* @param ... Variable number of format parameters.
*/
stock void PrintCenterTextAll(const char[] format, any ...)
{
char buffer[254];
for (int i = 1; i <= MaxClients; i++)
{
if (IsClientInGame(i))
{
SetGlobalTransTarget(i);
VFormat(buffer, sizeof(buffer), format, 2);
PrintCenterText(i, "%s", buffer);
}
}
}
/**
* Prints a message to a specific client with a hint box.
*
* @param client Client index.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
* @error Invalid client index, or client not in game.
*/
native void PrintHintText(int client, const char[] format, any ...);
/**
* Prints a message to all clients with a hint box.
*
* @param format Formatting rules.
* @param ... Variable number of format parameters.
*/
stock void PrintHintTextToAll(const char[] format, any ...)
{
char buffer[254];
for (int i = 1; i <= MaxClients; i++)
{
if (IsClientInGame(i))
{
SetGlobalTransTarget(i);
VFormat(buffer, sizeof(buffer), format, 2);
PrintHintText(i, "%s", buffer);
}
}
}
/**
* Shows a VGUI panel to a specific client.
*
* @param client Client index.
* @param name Panel type name (Check viewport_panel_names.h to see a list of
* some panel names).
* @param Kv KeyValues handle with all the data for the panel setup (Depends
* on the panel type and may be unused).
* @param show True to show the panel, or false to remove it from the client screen.
* @error Invalid client index, or client not in game.
*/
native void ShowVGUIPanel(int client, const char[] name, Handle Kv=INVALID_HANDLE, bool show=true);
/**
* Creates a HUD synchronization object. This object is used to automatically assign and
* re-use channels for a set of messages.
*
* The HUD has a hardcoded number of channels (usually 6) for displaying
* text. You can use any channel for any area of the screen. Text on
* different channels can overlap, but text on the same channel will
* erase the old text first. This overlapping and overwriting gets problematic.
*
* A HUD synchronization object automatically selects channels for you based on
* the following heuristics:
* - If channel X was last used by the object, and hasn't been modified again,
* channel X gets re-used.
* - Otherwise, a new channel is chosen based on the least-recently-used channel.
*
* This ensures that if you display text on a sync object, that the previous text
* displayed on it will always be cleared first. This is because your new text
* will either overwrite the old text on the same channel, or because another
* channel has already erased your text.
*
* Note that messages can still overlap if they are on different synchronization
* objects, or they are displayed to manual channels.
*
* These are particularly useful for displaying repeating or refreshing HUD text, in
* addition to displaying multiple message sets in one area of the screen (for example,
* center-say messages that may pop up randomly that you don't want to overlap each
* other).
*
* @return New HUD synchronization object.
* The Handle can be closed with CloseHandle().
* If HUD text is not supported on this mod, then
* INVALID_HANDLE is returned.
*/
native Handle CreateHudSynchronizer();
/**
* Sets the HUD parameters for drawing text. These parameters are stored
* globally, although nothing other than this function and SetHudTextParamsEx
* modify them.
*
* You must call this function before drawing text. If you are drawing
* text to multiple clients, you can set the parameters once, since
* they won't be modified. However, as soon as you pass control back
* to other plugins, you must reset the parameters next time you draw.
*
* @param x x coordinate, from 0 to 1. -1.0 is the center.
* @param y y coordinate, from 0 to 1. -1.0 is the center.
* @param holdTime Number of seconds to hold the text.
* @param r Red color value.
* @param g Green color value.
* @param b Blue color value.
* @param a Alpha transparency value.
* @param effect 0/1 causes the text to fade in and fade out.
* 2 causes the text to flash[?].
* @param fxTime Duration of chosen effect (may not apply to all effects).
* @param fadeIn Number of seconds to spend fading in.
* @param fadeOut Number of seconds to spend fading out.
*/
native void SetHudTextParams(float x, float y, float holdTime, int r, int g, int b, int a, int effect = 0,
float fxTime=6.0, float fadeIn=0.1, float fadeOut=0.2);
/**
* Sets the HUD parameters for drawing text. These parameters are stored
* globally, although nothing other than this function and SetHudTextParams
* modify them.
*
* This is the same as SetHudTextParams(), except it lets you set the alternate
* color for when effects require it.
*
* @param x x coordinate, from 0 to 1. -1.0 is the center.
* @param y y coordinate, from 0 to 1. -1.0 is the center.
* @param holdTime Number of seconds to hold the text.
* @param color1 First color set, array values being [red, green, blue, alpha]
* @param color2 Second color set, array values being [red, green, blue, alpha]
* @param effect 0/1 causes the text to fade in and fade out.
* 2 causes the text to flash[?].
* @param fxTime Duration of chosen effect (may not apply to all effects).
* @param fadeIn Number of seconds to spend fading in.
* @param fadeOut Number of seconds to spend fading out.
*/
native void SetHudTextParamsEx(float x, float y, float holdTime, int color1[4],
int color2[4]={255,255,255,0}, int effect = 0, float fxTime=6.0,
float fadeIn=0.1, float fadeOut=0.2);
/**
* Shows a synchronized HUD message to a client.
*
* As of this writing, only TF, HL2MP, and SourceForts support HUD Text.
*
* @param client Client index to send the message to.
* @param sync Synchronization object.
* @param message Message text or formatting rules.
* @param ... Message formatting parameters.
* @return -1 on failure, anything else on success.
* This function fails if the mod does not support it.
* @error Invalid client index, client not in game, or sync object not valid.
*/
native int ShowSyncHudText(int client, Handle sync, const char[] message, any ...);
/**
* Clears the text on a synchronized HUD channel.
*
* This is not the same as sending "" because it guarantees that it won't
* overwrite text on another channel. For example, consider the scenario:
*
* 1. Your synchronized message goes to channel 3.
* 2. Someone else's non-synchronized message goes to channel 3.
*
* If you were to simply send "" on your synchronized message,
* then someone else's text could be overwritten.
*
* @param client Client index to send the message to.
* @param sync Synchronization object.
* @error Invalid client index, client not in game, or sync object not valid.
*/
native void ClearSyncHud(int client, Handle sync);
/**
* Shows a HUD message to a client on the given channel.
*
* Note: while many games support HUD Text, not all do.
*
* @param client Client index to send the message to.
* @param channel A channel number.
* If -1, then a channel will automatically be selected
* based on the least-recently-used channel. If the
* channel is any other number, it will be modulo'd with
* the channel count to get a final channel number.
* @param message Message text or formatting rules.
* @param ... Message formatting parameters.
* @return -1 on failure (lack of mod support).
* Any other return value is the channel number that was
* used to render the text.
* @error Invalid client index, or client not in game.
*/
native int ShowHudText(int client, int channel, const char[] message, any ...);
/**
* Shows a MOTD panel to a specific client.
*
* @param client Client index.
* @param title Title of the panel (printed on the top border of the window).
* @param msg Contents of the panel, it can be treated as an url, filename or plain text
* depending on the type parameter (WARNING: msg has to be 192 bytes maximum!)
* @param type Determines the way to treat the message body of the panel.
* @error Invalid client index, or client not in game.
*/
stock void ShowMOTDPanel(int client, const char[] title, const char[] msg, int type=MOTDPANEL_TYPE_INDEX)
{
char num[3];
IntToString(type, num, sizeof(num));
KeyValues kv = new KeyValues("data");
kv.SetString("title", title);
kv.SetString("type", num);
kv.SetString("msg", msg);
ShowVGUIPanel(client, "info", kv);
delete kv;
}
/**
* Displays a panel asking the client to connect to a specified IP.
*
* Note: On many newer games (Left 4 Dead/2008+), the display of this to clients is broken.
* Additionally, as of 2018, some games also require the client to have cl_showpluginmessages
* set to 1, a non-default value, for this to function.
*
* @param client Client index.
* @param time Duration to hold the panel on the client's screen.
* @param ip Destination IP.
* @param password Password to connect to the destination IP. The client will be able to see this.
* @error Invalid client index, or client not in game.
*/
stock void DisplayAskConnectBox(int client, float time, const char[] ip, const char[] password = "")
{
char destination[288];
FormatEx(destination, sizeof(destination), "%s/%s", ip, password);
KeyValues kv = new KeyValues("data");
kv.SetFloat("time", time);
kv.SetString("title", destination);
CreateDialog(client, kv, DialogType_AskConnect);
delete kv;
}
/**
* Converts an entity index into a serial encoded entity reference.
*
* @param entity Entity index.
* @return Entity reference or -1 on invalid entity.
* @error Entity index >= GetMaxEntities() or < 0
*/
native int EntIndexToEntRef(int entity);
/**
* Retrieves the entity index from a reference or validates an entity index.
* The input ref is checked that it is still valid and refers to the same entity.
*
* @param ref Entity reference or index.
* @return Entity index or returns INVALID_ENT_REFERENCE if ref is invalid.
*/
native int EntRefToEntIndex(int ref);
/**
* Converts a reference into a backwards compatible version.
*
* @param ref Entity reference.
* @return Bcompat reference.
*/
native int MakeCompatEntRef(int ref);
enum ClientRangeType
{
RangeType_Visibility = 0,
RangeType_Audibility
}
/**
* Find clients that are potentially in range of a position.
*
* @param origin Coordinates from which to test range.
* @param rangeType Range type to use for filtering clients.
* @param clients Array to which found client indexes will be written.
* @param size Maximum size of clients array.
* @return Number of client indexes written to clients array.
*/
native int GetClientsInRange(const float origin[3], ClientRangeType rangeType, int[] clients, int size);
/**
* Retrieves the server's authentication string (SteamID).
*
* Note: If called before server is connected to Steam, auth id
* will be invalid ([I:0:1], 1, etc.)
*
* @param authType Auth id type and format to use.
* (Only AuthId_Steam3 and AuthId_SteamID64 are supported)
* @param auth Buffer to store the server's auth id.
* @param maxlen Maximum length of string buffer (includes NULL terminator).
* @error Invalid AuthIdType given.
*/
native void GetServerAuthId(AuthIdType authType, char[] auth, int maxlen);
/**
* Returns the server's Steam account ID.
*
* @return Steam account ID or 0 if not available.
*/
native int GetServerSteamAccountId();

View File

@@ -0,0 +1,129 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _handles_included
#endinput
#endif
#define _handles_included
/**
* Preset Handle values.
*/
enum Handle // Tag disables introducing "Handle" as a symbol.
{
INVALID_HANDLE = 0
};
/**
* Closes a Handle. If the handle has multiple copies open,
* it is not destroyed unless all copies are closed.
*
* @note Closing a Handle has a different meaning for each Handle type. Make
* sure you read the documentation on whatever provided the Handle.
*
* @param hndl Handle to close.
* @error Invalid handles will cause a run time error.
*/
native void CloseHandle(Handle hndl);
/**
* Clones a Handle. When passing handles in between plugins, caching handles
* can result in accidental invalidation when one plugin releases the Handle, or is its owner
* is unloaded from memory. To prevent this, the Handle may be "cloned" with a new owner.
*
* @note Usually, you will be cloning Handles for other plugins. This means that if you clone
* the Handle without specifying the new owner, it will assume the identity of your original
* calling plugin, which is not very useful. You should either specify that the receiving
* plugin should clone the handle on its own, or you should explicitly clone the Handle
* using the receiving plugin's identity Handle.
*
* @param hndl Handle to clone/duplicate.
* @param plugin Optional Handle to another plugin to mark as the new owner.
* If no owner is passed, the owner becomes the calling plugin.
* @return Handle on success, INVALID_HANDLE if not cloneable.
* @error Invalid handles will cause a run time error.
*/
native Handle CloneHandle(Handle hndl, Handle plugin=INVALID_HANDLE);
methodmap Handle __nullable__ {
public native ~Handle();
/**
* Closes a Handle. If the handle has multiple copies open,
* it is not destroyed unless all copies are closed.
*
* @note Closing a Handle has a different meaning for each Handle type. Make
* sure you read the documentation on whatever provided the Handle.
*
* @error Invalid handles will cause a run time error.
*/
public native void Close();
/**
* Clones a Handle. When passing handles in between plugins, caching handles
* can result in accidental invalidation when one plugin releases the Handle, or is its owner
* is unloaded from memory. To prevent this, the Handle may be "cloned" with a new owner.
*
* @note Usually, you will be cloning Handles for other plugins. This means that if you clone
* the Handle without specifying the new owner, it will assume the identity of your original
* calling plugin, which is not very useful. You should either specify that the receiving
* plugin should clone the handle on its own, or you should explicitly clone the Handle
* using the receiving plugin's identity Handle.
*
* @param plugin Optional Handle to another plugin to mark as the new owner.
* If no owner is passed, the owner becomes the calling plugin.
* @return Handle on success, INVALID_HANDLE if not cloneable.
* @error Invalid handles will cause a run time error.
*/
public native Handle Clone(Handle plugin=INVALID_HANDLE);
};
/**
* Do not use this function. Returns if a Handle and its contents
* are readable, whereas INVALID_HANDLE only checks for the absence
* of a Handle.
*
* This function is intended only for tests where the validity of a
* Handle can absolutely not be known.
*
* Do not use this to check the return values of functions, or to
* check if timers should be closed (except in very rare cases).
* This function is for very specific usage and using it for general
* purpose routines can and will hide very subtle bugs.
*
* @param hndl Handle to test for validity.
* @return True if handle is valid, false otherwise.
* @deprecated Do not use this function.
*/
#pragma deprecated Do not use this function.
native bool IsValidHandle(Handle hndl);

View File

@@ -0,0 +1,287 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _helpers_included
#endinput
#endif
#define _helpers_included
/**
* This function is deprecated. Use the %L format specifier instead.
*
* Formats a user's info as log text.
*
* @param client Client index.
* @param buffer Buffer for text.
* @param maxlength Maximum length of text.
* @deprecated Use the %L format specifier instead.
*/
#pragma deprecated Use the %L format specifier instead.
stock void FormatUserLogText(int client, char[] buffer, int maxlength)
{
FormatEx(buffer, maxlength, "\"%L\"", client);
}
/**
* Returns plugin handle from plugin filename.
*
* @param filename Filename of the plugin to search for.
* @return Handle to plugin if found, INVALID_HANDLE otherwise.
*/
stock Handle FindPluginByFile(const char[] filename)
{
char buffer[256];
Handle iter = GetPluginIterator();
Handle pl;
while (MorePlugins(iter))
{
pl = ReadPlugin(iter);
GetPluginFilename(pl, buffer, sizeof(buffer));
if (strcmp(buffer, filename, false) == 0)
{
CloseHandle(iter);
return pl;
}
}
CloseHandle(iter);
return INVALID_HANDLE;
}
/**
* @deprecated Use FindTarget() or ProcessTargetString().
*/
#pragma deprecated Use FindTarget() or ProcessTargetString()
stock int SearchForClients(const char[] pattern, int[] clients, int maxClients)
{
int total = 0;
if (maxClients == 0)
{
return 0;
}
if (pattern[0] == '#')
{
int input = StringToInt(pattern[1]);
if (!input) {
char name[MAX_NAME_LENGTH];
for (int i=1; i<=MaxClients; i++)
{
if (!IsClientInGame(i))
{
continue;
}
GetClientName(i, name, sizeof(name));
if (strcmp(name, pattern, false) == 0)
{
clients[0] = i;
return 1;
}
}
}
else
{
int client = GetClientOfUserId(input);
if (client)
{
clients[0] = client;
return 1;
}
}
}
char name[MAX_NAME_LENGTH];
for (int i=1; i<=MaxClients; i++)
{
if (!IsClientInGame(i))
{
continue;
}
GetClientName(i, name, sizeof(name));
if (StrContains(name, pattern, false) != -1)
{
clients[total++] = i;
if (total >= maxClients)
{
break;
}
}
}
return total;
}
/**
* Wraps ProcessTargetString() and handles producing error messages for
* bad targets.
*
* Note that you should use LoadTranslations("common.phrases") in OnPluginStart().
* "common.phrases" contains all of the translatable phrases that FindTarget() will
* reply with in the event a target is not found (error).
*
* @param client Client who issued command
* @param target Client's target argument
* @param nobots Optional. Set to true if bots should NOT be targetted
* @param immunity Optional. Set to false to ignore target immunity.
* @return Index of target client, or -1 on error.
*/
stock int FindTarget(int client, const char[] target, bool nobots = false, bool immunity = true)
{
char target_name[MAX_TARGET_LENGTH];
int target_list[1], target_count;
bool tn_is_ml;
int flags = COMMAND_FILTER_NO_MULTI;
if (nobots)
{
flags |= COMMAND_FILTER_NO_BOTS;
}
if (!immunity)
{
flags |= COMMAND_FILTER_NO_IMMUNITY;
}
if ((target_count = ProcessTargetString(
target,
client,
target_list,
1,
flags,
target_name,
sizeof(target_name),
tn_is_ml)) > 0)
{
return target_list[0];
}
ReplyToTargetError(client, target_count);
return -1;
}
/**
* This function is no longer supported. It has been replaced with ReadMapList(),
* which uses a more unified caching and configuration mechanism. This function also
* has a bug where if the cvar contents changes, the fileTime change won't be recognized.
*
* Loads a specified array with maps. The maps will be either loaded from mapcyclefile, or if supplied
* a cvar containing a file name. If the file in the cvar is bad, it will use mapcyclefile. The fileTime
* parameter is used to store a timestamp of the file. If specified, the file will only be reloaded if it
* has changed.
*
* @param array Valid array handle, should be created with CreateArray(33) or larger.
* @param fileTime Variable containing the "last changed" time of the file. Used to avoid needless reloading.
* @param fileCvar CVAR set to the file to be loaded. Optional.
* @return Number of maps loaded or 0 if in error.
* @deprecated Use ReadMapList() instead.
*/
#pragma deprecated Use ReadMapList() instead.
stock int LoadMaps(Handle array, int &fileTime = 0, Handle fileCvar = INVALID_HANDLE)
{
char mapPath[256], mapFile[64];
bool fileFound = false;
if (fileCvar != INVALID_HANDLE)
{
GetConVarString(fileCvar, mapFile, 64);
BuildPath(Path_SM, mapPath, sizeof(mapPath), mapFile);
fileFound = FileExists(mapPath);
}
if (!fileFound)
{
Handle mapCycleFile = FindConVar("mapcyclefile");
GetConVarString(mapCycleFile, mapPath, sizeof(mapPath));
fileFound = FileExists(mapPath);
}
if (!fileFound)
{
LogError("Failed to find a file to load maps from. No maps loaded.");
ClearArray(array);
return 0;
}
// If the file hasn't changed, there's no reason to reload
// all of the maps.
int newTime = GetFileTime(mapPath, FileTime_LastChange);
if (fileTime == newTime)
{
return GetArraySize(array);
}
fileTime = newTime;
ClearArray(array);
File file = OpenFile(mapPath, "rt");
if (!file) {
LogError("Could not open file: %s", mapPath);
return 0;
}
LogMessage("Loading maps from file: %s", mapPath);
int len;
char buffer[64];
while (!file.EndOfFile() && file.ReadLine(buffer, sizeof(buffer)))
{
TrimString(buffer);
if ((len = StrContains(buffer, ".bsp", false)) != -1)
{
buffer[len] = '\0';
}
if (buffer[0] == '\0' || !IsValidConVarChar(buffer[0]) || !IsMapValid(buffer))
{
continue;
}
if (FindStringInArray(array, buffer) != -1)
{
continue;
}
PushArrayString(array, buffer);
}
file.Close();
return GetArraySize(array);
}

View File

@@ -0,0 +1,711 @@
/**
* vim: set ts=4 sw=4 tw=99 noet :
* =============================================================================
* SourceMod (C)2004-2014 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _keyvalues_included
#endinput
#endif
#define _keyvalues_included
/**
* KeyValue data value types
*/
enum KvDataTypes
{
KvData_None = 0, /**< Type could not be identified, or no type */
KvData_String, /**< String value */
KvData_Int, /**< Integer value */
KvData_Float, /**< Floating point value */
KvData_Ptr, /**< Pointer value (sometimes called "long") */
KvData_WString, /**< Wide string value */
KvData_Color, /**< Color value */
KvData_UInt64, /**< Large integer value */
/* --- */
KvData_NUMTYPES
};
methodmap KeyValues < Handle
{
// Creates a new KeyValues structure. The Handle must be closed with
// CloseHandle() or delete.
//
// @param name Name of the root section.
// @param firstKey If non-empty, specifies the first key value.
// @param firstValue If firstKey is non-empty, specifies the first key's value.
public native KeyValues(const char[] name, const char[] firstKey="", const char[] firstValue="");
// Exports a KeyValues tree to a file. The tree is dumped from the current position.
//
// @param file File to dump write to.
// @return True on success, false otherwise.
public native bool ExportToFile(const char[] file);
// Exports a KeyValues tree to a string. The string is dumped from the current position.
//
// @param buffer Buffer to write to.
// @param maxlength Max length of buffer.
// @return Number of bytes that can be written to buffer.
public native int ExportToString(char[] buffer, int maxlength);
// Amount of bytes written by ExportToFile & ExportToString.
property int ExportLength {
public native get();
}
// Imports a file in KeyValues format. The file is read into the current
// position of the tree.
//
// @param file File to read from.
// @return True on success, false otherwise.
public native bool ImportFromFile(const char[] file);
// Converts a given string to a KeyValues tree. The string is read into
// the current postion of the tree.
//
// @param buffer String buffer to load into the KeyValues.
// @param resourceName The resource name of the KeyValues, used for error tracking purposes.
// @return True on success, false otherwise.
public native bool ImportFromString(const char[] buffer, const char[] resourceName="StringToKeyValues");
// Imports subkeys in the given KeyValues, at the current position in that
// KeyValues, into the current position in this KeyValues. Note that this
// copies keys; it does not embed a reference to them.
//
// @param other Origin KeyValues Handle.
public native void Import(KeyValues other);
// Sets a string value of a KeyValues key.
//
// @param kv KeyValues Handle.
// @param key Name of the key, or NULL_STRING.
// @param value String value.
public native void SetString(const char[] key, const char[] value);
// Sets an integer value of a KeyValues key.
//
// @param key Name of the key, or NULL_STRING.
// @param value Value number.
public native void SetNum(const char[] key, int value);
// Sets a large integer value of a KeyValues key.
//
// @param key Name of the key, or NULL_STRING.
// @param value Large integer value (0=High bits, 1=Low bits)
public native void SetUInt64(const char[] key, const int value[2]);
// Sets a floating point value of a KeyValues key.
//
// @param key Name of the key, or NULL_STRING.
// @param value Floating point value.
public native void SetFloat(const char[] key, float value);
// Sets a set of color values of a KeyValues key.
//
// @param key Name of the key, or NULL_STRING.
// @param r Red value.
// @param g Green value.
// @param b Blue value.
// @param a Alpha value.
public native void SetColor(const char[] key, int r, int g, int b, int a=0);
// Sets a set of color values of a KeyValues key.
//
// @param key Name of the key, or NULL_STRING.
// @param color Red, green, blue and alpha channels.
public void SetColor4(const char[] key, const int color[4]) {
this.SetColor(key, color[0], color[1], color[2], color[3]);
}
// Sets a vector value of a KeyValues key.
//
// @param key Name of the key, or NULL_STRING.
// @param vec Vector value.
public native void SetVector(const char[] key, const float vec[3]);
// Retrieves a string value from a KeyValues key.
//
// @param key Name of the key, or NULL_STRING.
// @param value Buffer to store key value in.
// @param maxlength Maximum length of the value buffer.
// @param defvalue Optional default value to use if the key is not found.
public native void GetString(const char[] key, char[] value, int maxlength, const char[] defvalue="");
// Retrieves an integer value from a KeyValues key.
//
// @param key Name of the key, or NULL_STRING.
// @param defvalue Optional default value to use if the key is not found.
// @return Integer value of the key.
public native int GetNum(const char[] key, int defvalue=0);
// Retrieves a floating point value from a KeyValues key.
//
// @param key Name of the key, or NULL_STRING.
// @param defvalue Optional default value to use if the key is not found.
// @return Floating point value of the key.
public native float GetFloat(const char[] key, float defvalue=0.0);
// Retrieves a set of color values from a KeyValues key.
//
// @param key Name of the key, or NULL_STRING.
// @param r Red value, set by reference.
// @param g Green value, set by reference.
// @param b Blue value, set by reference.
// @param a Alpha value, set by reference.
public native void GetColor(const char[] key, int &r, int &g, int &b, int &a);
// Retrieves a set of color values from a KeyValues key.
//
// @param key Name of the key, or NULL_STRING.
// @param color Red, green, blue, and alpha channels.
public void GetColor4(const char[] key, int color[4]) {
int r, g, b, a;
this.GetColor(key, r, g, b, a);
color[0] = r;
color[1] = g;
color[2] = b;
color[3] = a;
}
// Retrieves a large integer value from a KeyValues key.
//
// @param key Name of the key, or NULL_STRING.
// @param value Array to represent the large integer.
// @param defvalue Optional default value to use if the key is not found.
public native void GetUInt64(const char[] key, int value[2], int defvalue[2]={0,0});
// Retrieves a vector value from a KeyValues key.
//
// @param key Name of the key, or NULL_STRING.
// @param vec Destination vector to store the value in.
// @param defvalue Optional default value to use if the key is not found.
public native void GetVector(const char[] key, float vec[3], const float defvalue[3]={0.0, 0.0, 0.0});
// Sets the current position in the KeyValues tree to the given key.
//
// @param key Name of the key.
// @param create If true, and the key does not exist, it will be created.
// @return True if the key exists, false if it does not and was not created.
public native bool JumpToKey(const char[] key, bool create=false);
// Sets the current position in the KeyValues tree to the given key.
//
// @param id KeyValues id.
// @return True if the key exists, false if it does not.
public native bool JumpToKeySymbol(int id);
// Sets the current position in the KeyValues tree to the first sub key.
// This native adds to the internal traversal stack.
//
// @param keyOnly If false, non-keys will be traversed (values).
// @return True on success, false if there was no first sub key.
public native bool GotoFirstSubKey(bool keyOnly=true);
// Sets the current position in the KeyValues tree to the next sub key.
// This native does NOT add to the internal traversal stack, and thus
// GoBack() is not needed for each successive call to this function.
//
// @param keyOnly If false, non-keys will be traversed (values).
// @return True on success, false if there was no next sub key.
public native bool GotoNextKey(bool keyOnly=true);
// Saves the current position in the traversal stack onto the traversal
// stack. This can be useful if you wish to use KvGotoNextKey() and
// have the previous key saved for backwards traversal.
//
// @param kv KeyValues Handle.
// @return True on success, false if there is no higher node.
public native bool SavePosition();
// Jumps back to the previous position. Returns false if there are no
// previous positions (i.e., at the root node with an empty traversal stack).
// This should be called once for each successful Jump call, in order to return
// to the top node. This function pops one node off the internal traversal stack.
//
// @return True on success, false if there is no higher node.
public native bool GoBack();
// Removes the given key from the current position.
//
// @param key Name of the key.
// @return True on success, false if key did not exist.
public native bool DeleteKey(const char[] key);
// Removes the current sub-key and attempts to set the position
// to the sub-key after the removed one. If no such sub-key exists,
// the position will be the parent key in the traversal stack.
// Given the sub-key having position "N" in the traversal stack, the
// removal will always take place from position "N-1."
//
// @param kv KeyValues Handle.
// @return 1 if removal succeeded and there was another key.
// 0 if the current node was not contained in the
// previous node, or no previous node exists.
// -1 if removal succeeded and there were no more keys,
// thus the state is as if KvGoBack() was called.
public native int DeleteThis();
// Sets the position back to the top node and clears the entire
// node traversal history (by default). This can be used instead of looping
// KvGoBack() if recursive iteration is not important.
//
// @param kv KeyValues Handle.
// @param clearHistory If true, the entire node traversal stack is cleared.
// If false, this will add to the traversal stack.
public native void Rewind(bool clearHistory=true);
// Retrieves the current section name.
//
// @param section Buffer to store the section name.
// @param maxlength Maximum length of the name buffer.
// @return True on success, false on failure.
public native bool GetSectionName(char[] section, int maxlength);
// Sets the current section name.
//
// @param section Section name.
public native void SetSectionName(const char[] section);
// Returns the data type at a key.
//
// @param key Key name.
// @return KvDataType value of the key.
public native KvDataTypes GetDataType(const char[] key);
// Sets whether or not the KeyValues parser will read escape sequences.
// For example, \n would be read as a literal newline. This defaults
// to false for new KeyValues structures.
//
// @param useEscapes Whether or not to read escape sequences.
public native void SetEscapeSequences(bool useEscapes);
// Returns the position in the jump stack; I.e. the number of calls
// required for KvGoBack to return to the root node. If at the root node,
// and the traversal stack is empty, 0 is returned.
//
// @return Number of non-root nodes in the jump stack.
public native int NodesInStack();
// Finds a KeyValues name by id.
//
// @param id KeyValues id.
// @param name Buffer to store the name.
// @param maxlength Maximum length of the value buffer.
// @return True on success, false if id not found.
public native bool FindKeyById(int id, char[] name, int maxlength);
// Finds a KeyValues id inside a KeyValues tree.
//
// @param key Key name.
// @param id Id of the found KeyValue.
// @return True on success, false if key not found.
public native bool GetNameSymbol(const char[] key, int &id);
// Retrieves the current section id.
//
// @param kv KeyValues Handle.
// @param id Id of the current section.
// @return True on success, false on failure.
public native bool GetSectionSymbol(int &id);
};
/**
* Creates a new KeyValues structure. The Handle must always be closed.
*
* @param name Name of the root section.
* @param firstKey If non-empty, specifies the first key value.
* @param firstValue If firstKey is non-empty, specifies the first key's value.
* @return A Handle to a new KeyValues structure.
*/
native KeyValues CreateKeyValues(const char[] name, const char[] firstKey="", const char[] firstValue="");
/**
* Sets a string value of a KeyValues key.
*
* @param kv KeyValues Handle.
* @param key Name of the key, or NULL_STRING.
* @param value String value.
* @error Invalid Handle.
*/
native void KvSetString(Handle kv, const char[] key, const char[] value);
/**
* Sets an integer value of a KeyValues key.
*
* @param kv KeyValues Handle.
* @param key Name of the key, or NULL_STRING.
* @param value Value number.
* @error Invalid Handle.
*/
native void KvSetNum(Handle kv, const char[] key, int value);
/**
* Sets a large integer value of a KeyValues key.
*
* @param kv KeyValues Handle.
* @param key Name of the key, or NULL_STRING.
* @param value Large integer value (0=High bits, 1=Low bits)
* @error Invalid Handle.
*/
native void KvSetUInt64(Handle kv, const char[] key, const int value[2]);
/**
* Sets a floating point value of a KeyValues key.
*
* @param kv KeyValues Handle.
* @param key Name of the key, or NULL_STRING.
* @param value Floating point value.
* @error Invalid Handle.
*/
native void KvSetFloat(Handle kv, const char[] key, float value);
/**
* Sets a set of color values of a KeyValues key.
*
* @param kv KeyValues Handle.
* @param key Name of the key, or NULL_STRING.
* @param r Red value.
* @param g Green value.
* @param b Blue value.
* @param a Alpha value.
* @error Invalid Handle.
*/
native void KvSetColor(Handle kv, const char[] key, int r, int g, int b, int a=0);
/**
* Sets a vector value of a KeyValues key.
*
* @param kv KeyValues Handle.
* @param key Name of the key, or NULL_STRING.
* @param vec Vector value.
* @error Invalid Handle.
*/
native void KvSetVector(Handle kv, const char[] key, const float vec[3]);
/**
* Retrieves a string value from a KeyValues key.
*
* @param kv KeyValues Handle.
* @param key Name of the key, or NULL_STRING.
* @param value Buffer to store key value in.
* @param maxlength Maximum length of the value buffer.
* @param defvalue Optional default value to use if the key is not found.
* @error Invalid Handle.
*/
native void KvGetString(Handle kv, const char[] key, char[] value, int maxlength, const char[] defvalue="");
/**
* Retrieves an integer value from a KeyValues key.
*
* @param kv KeyValues Handle.
* @param key Name of the key, or NULL_STRING.
* @param defvalue Optional default value to use if the key is not found.
* @return Integer value of the key.
* @error Invalid Handle.
*/
native int KvGetNum(Handle kv, const char[] key, int defvalue=0);
/**
* Retrieves a floating point value from a KeyValues key.
*
* @param kv KeyValues Handle.
* @param key Name of the key, or NULL_STRING.
* @param defvalue Optional default value to use if the key is not found.
* @return Floating point value of the key.
* @error Invalid Handle.
*/
native float KvGetFloat(Handle kv, const char[] key, float defvalue=0.0);
/**
* Retrieves a set of color values from a KeyValues key.
*
* @param kv KeyValues Handle.
* @param key Name of the key, or NULL_STRING.
* @param r Red value, set by reference.
* @param g Green value, set by reference.
* @param b Blue value, set by reference.
* @param a Alpha value, set by reference.
* @error Invalid Handle.
*/
native void KvGetColor(Handle kv, const char[] key, int &r, int &g, int &b, int &a);
/**
* Retrieves a large integer value from a KeyValues key.
*
* @param kv KeyValues Handle.
* @param key Name of the key, or NULL_STRING.
* @param value Array to represent the large integer.
* @param defvalue Optional default value to use if the key is not found.
* @error Invalid Handle.
*/
native void KvGetUInt64(Handle kv, const char[] key, int value[2], int defvalue[2]={0,0});
/**
* Retrieves a vector value from a KeyValues key.
*
* @param kv KeyValues Handle.
* @param key Name of the key, or NULL_STRING.
* @param vec Destination vector to store the value in.
* @param defvalue Optional default value to use if the key is not found.
* @error Invalid Handle.
*/
native void KvGetVector(Handle kv, const char[] key, float vec[3], const float defvalue[3]={0.0, 0.0, 0.0});
/**
* Sets the current position in the KeyValues tree to the given key.
*
* @param kv KeyValues Handle.
* @param key Name of the key.
* @param create If true, and the key does not exist, it will be created.
* @return True if the key exists, false if it does not and was not created.
*/
native bool KvJumpToKey(Handle kv, const char[] key, bool create=false);
/**
* Sets the current position in the KeyValues tree to the given key.
*
* @param kv KeyValues Handle.
* @param id KeyValues id.
* @return True if the key exists, false if it does not.
*/
native bool KvJumpToKeySymbol(Handle kv, int id);
/**
* Sets the current position in the KeyValues tree to the first sub key.
* This native adds to the internal traversal stack.
*
* @param kv KeyValues Handle.
* @param keyOnly If false, non-keys will be traversed (values).
* @return True on success, false if there was no first sub key.
* @error Invalid Handle.
*/
native bool KvGotoFirstSubKey(Handle kv, bool keyOnly=true);
/**
* Sets the current position in the KeyValues tree to the next sub key.
* This native does NOT add to the internal traversal stack, and thus
* KvGoBack() is not needed for each successive call to this function.
*
* @param kv KeyValues Handle.
* @param keyOnly If false, non-keys will be traversed (values).
* @return True on success, false if there was no next sub key.
* @error Invalid Handle.
*/
native bool KvGotoNextKey(Handle kv, bool keyOnly=true);
/**
* Saves the current position in the traversal stack onto the traversal
* stack. This can be useful if you wish to use KvGotoNextKey() and
* have the previous key saved for backwards traversal.
*
* @param kv KeyValues Handle.
* @return True on success, false if there is no higher node.
* @error Invalid Handle.
*/
native bool KvSavePosition(Handle kv);
/**
* Removes the given key from the current position.
*
* @param kv KeyValues Handle.
* @param key Name of the key.
* @return True on success, false if key did not exist.
* @error Invalid Handle.
*/
native bool KvDeleteKey(Handle kv, const char[] key);
/**
* Removes the current sub-key and attempts to set the position
* to the sub-key after the removed one. If no such sub-key exists,
* the position will be the parent key in the traversal stack.
* Given the sub-key having position "N" in the traversal stack, the
* removal will always take place from position "N-1."
*
* @param kv KeyValues Handle.
* @return 1 if removal succeeded and there was another key.
* 0 if the current node was not contained in the
* previous node, or no previous node exists.
* -1 if removal succeeded and there were no more keys,
* thus the state is as if KvGoBack() was called.
* @error Invalid Handle.
*/
native int KvDeleteThis(Handle kv);
/**
* Jumps back to the previous position. Returns false if there are no
* previous positions (i.e., at the root node with an empty traversal stack).
* This should be called once for each successful Jump call, in order to return
* to the top node. This function pops one node off the internal traversal stack.
*
* @param kv KeyValues Handle.
* @return True on success, false if there is no higher node.
* @error Invalid Handle.
*/
native bool KvGoBack(Handle kv);
/**
* Sets the position back to the top node, emptying the entire node
* traversal history. This can be used instead of looping KvGoBack()
* if recursive iteration is not important.
*
* @param kv KeyValues Handle.
* @error Invalid Handle.
*/
native void KvRewind(Handle kv);
/**
* Retrieves the current section name.
*
* @param kv KeyValues Handle.
* @param section Buffer to store the section name.
* @param maxlength Maximum length of the name buffer.
* @return True on success, false on failure.
* @error Invalid Handle.
*/
native bool KvGetSectionName(Handle kv, char[] section, int maxlength);
/**
* Sets the current section name.
*
* @param kv KeyValues Handle.
* @param section Section name.
* @error Invalid Handle.
*/
native void KvSetSectionName(Handle kv, const char[] section);
/**
* Returns the data type at a key.
*
* @param kv KeyValues Handle.
* @param key Key name.
* @return KvDataType value of the key.
* @error Invalid Handle.
*/
native KvDataTypes KvGetDataType(Handle kv, const char[] key);
/**
* Converts a KeyValues tree to a file. The tree is dumped
* from the current position.
*
* @param kv KeyValues Handle.
* @param file File to dump write to.
* @return True on success, false otherwise.
* @error Invalid Handle.
*/
native bool KeyValuesToFile(Handle kv, const char[] file);
/**
* Converts a file to a KeyValues tree. The file is read into
* the current position of the tree.
*
* @param kv KeyValues Handle.
* @param file File to read from.
* @return True on success, false otherwise.
* @error Invalid Handle.
*/
native bool FileToKeyValues(Handle kv, const char[] file);
/**
* Converts a given string to a KeyValues tree. The string is read into
* the current postion of the tree.
*
* @param kv KeyValues Handle.
* @param buffer String buffer to load into the KeyValues.
* @param resourceName The resource name of the KeyValues, used for error tracking purposes.
* @return True on success, false otherwise.
* @error Invalid Handle.
*/
native bool StringToKeyValues(Handle kv, const char[] buffer, const char[] resourceName="StringToKeyValues");
/**
* Sets whether or not the KeyValues parser will read escape sequences.
* For example, \n would be read as a literal newline. This defaults
* to false for new KeyValues structures.
*
* @param kv KeyValues Handle.
* @param useEscapes Whether or not to read escape sequences.
* @error Invalid Handle.
*/
native void KvSetEscapeSequences(Handle kv, bool useEscapes);
/**
* Returns the position in the jump stack; I.e. the number of calls
* required for KvGoBack to return to the root node. If at the root node,
* 0 is returned.
*
* @param kv KeyValues Handle.
* @return Number of non-root nodes in the jump stack.
* @error Invalid Handle.
*/
native int KvNodesInStack(Handle kv);
/**
* Makes a new copy of all subkeys in the origin KeyValues to
* the destination KeyValues.
* NOTE: All KeyValues are processed from the current location not the root one.
*
* @param origin Origin KeyValues Handle.
* @param dest Destination KeyValues Handle.
* @error Invalid Handle.
*/
native void KvCopySubkeys(Handle origin, Handle dest);
/**
* Finds a KeyValues name by id.
*
* @param kv KeyValues Handle.
* @param id KeyValues id.
* @param name Buffer to store the name.
* @param maxlength Maximum length of the value buffer.
* @return True on success, false if id not found.
* @error Invalid Handle.
*/
native bool KvFindKeyById(Handle kv, int id, char[] name, int maxlength);
/**
* Finds a KeyValues id inside a KeyValues tree.
*
* @param kv KeyValues Handle.
* @param key Key name.
* @param id Id of the found KeyValue.
* @return True on success, false if key not found.
* @error Invalid Handle.
*/
native bool KvGetNameSymbol(Handle kv, const char[] key, int &id);
/**
* Retrieves the current section id.
*
* @param kv KeyValues Handle.
* @param id Id of the current section.
* @return True on success, false on failure.
* @error Invalid Handle.
*/
native bool KvGetSectionSymbol(Handle kv, int &id);

143
scripting/include/lang.inc Normal file
View File

@@ -0,0 +1,143 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _lang_included
#endinput
#endif
#define _lang_included
#define LANG_SERVER 0 /**< Translate using the server's language */
/**
* Loads a translation file for the plugin calling this native.
* If no extension is specified, .txt is assumed.
*
* @param file Translation file.
*/
native void LoadTranslations(const char[] file);
/**
* Sets the global language target. This is useful for creating functions
* that will be compatible with the %t format specifier. Note that invalid
* indexes can be specified but the error will occur during translation,
* not during this function call.
*
* @param client Client index or LANG_SERVER.
*/
native void SetGlobalTransTarget(int client);
/**
* Retrieves the language number of a client.
*
* @param client Client index.
* @return Language number client is using.
* @error Invalid client index or client not connected.
*/
native int GetClientLanguage(int client);
/**
* Retrieves the server's language.
*
* @return Language number server is using.
*/
native int GetServerLanguage();
/**
* Returns the number of languages known in languages.cfg.
*
* @return Language count.
*/
native int GetLanguageCount();
/**
* Retrieves info about a given language number.
*
* @param language Language number.
* @param code Language code buffer (2-3 characters usually).
* @param codeLen Maximum length of the language code buffer.
* @param name Language name buffer.
* @param nameLen Maximum length of the language name buffer.
* @error Invalid language number.
*/
native void GetLanguageInfo(int language, char[] code="", int codeLen=0, char[] name="", int nameLen=0);
/**
* Sets the language number of a client.
*
* @param client Client index.
* @param language Language number.
* @error Invalid client index or client not connected.
*/
native void SetClientLanguage(int client, int language);
/**
* Retrieves the language number a client had when they connected.
*
* @param client Client index.
* @return Language number client originally had.
* @error Invalid client index or client not connected.
*/
native int GetClientOriginalLanguage(int client);
/**
* Retrieves the language number from a language code.
*
* @param code Language code (2-3 characters usually).
* @return Language number. -1 if not found.
*/
native int GetLanguageByCode(const char[] code);
/**
* Retrieves the language number from a language name.
*
* @param name Language name (case insensitive).
* @return Language number. -1 if not found.
*/
native int GetLanguageByName(const char[] name);
/**
* Determines if the specified phrase exists within the plugin's
* translation cache.
*
* @param phrase Phrase to look for.
* @return True if phrase exists.
*/
native bool TranslationPhraseExists(const char[] phrase);
/**
* Determines if there is a translation for the specified language.
*
* @param phrase Phrase to check.
* @param language Language number.
* @return True if translation exists.
*/
native bool IsTranslatedForLanguage(const char[] phrase, int language);

View File

@@ -0,0 +1,135 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _sm_logging_included
#endinput
#endif
#define _sm_logging_included
/**
* Logs a plugin message to the SourceMod logs. The log message will be
* prefixed by the plugin's logtag (filename).
*
* @param format String format.
* @param ... Format arguments.
*/
native void LogMessage(const char[] format, any ...);
/**
* Logs a message to any file. The log message will be in the normal
* SourceMod format, with the plugin logtag prepended.
*
* @param file File to write the log message in.
* @param format String format.
* @param ... Format arguments.
* @error File could not be opened/written.
*/
native void LogToFile(const char[] file, const char[] format, any ...);
/**
* Same as LogToFile(), except no plugin logtag is prepended.
*
* @param file File to write the log message in.
* @param format String format.
* @param ... Format arguments.
* @error File could not be opened/written.
*/
native void LogToFileEx(const char[] file, const char[] format, any ...);
/**
* Logs an action from a command or event whereby interception and routing may
* be important. This is intended to be a logging version of ShowActivity().
*
* @param client Client performing the action, 0 for server, or -1 if not
* applicable.
* @param target Client being targetted, or -1 if not applicable.
* @param message Message format.
* @param ... Message formatting parameters.
*/
native void LogAction(int client, int target, const char[] message, any ...);
/**
* Logs a plugin error message to the SourceMod logs.
*
* @param format String format.
* @param ... Format arguments.
*/
native void LogError(const char[] format, any ...);
/**
* Called when an action is going to be logged.
*
* @param source Handle to the object logging the action, or INVALID_HANDLE
* if Core is logging the action.
* @param ident Type of object logging the action (plugin, ext, or core).
* @param client Client the action is from; 0 for server, -1 if not applicable.
* @param target Client the action is targetting, or -1 if not applicable.
* @param message Message that is being logged.
* @return Plugin_Continue will perform the default logging behavior.
* Plugin_Handled will stop Core from logging the message.
* Plugin_Stop is the same as Handled, but prevents any other
* plugins from handling the message.
*/
forward Action OnLogAction(Handle source,
Identity ident,
int client,
int target,
const char[] message);
/**
* Called when a game log message is received.
*
* Any Log*() functions called within this callback will not recursively
* pass through. That is, they will log directly, bypassing this callback.
*
* Note that this does not capture log messages from the engine. It only
* captures log messages being sent from the game/mod itself.
*
* @param message Message contents.
* @return Plugin_Handled or Plugin_Stop will prevent the message
* from being written to the log file.
*/
typedef GameLogHook = function Action (const char[] message);
/**
* Adds a game log hook.
*
* @param hook Hook function.
*/
native void AddGameLogHook(GameLogHook hook);
/**
* Removes a game log hook.
*
* @param hook Hook function.
*/
native void RemoveGameLogHook(GameLogHook hook);

View File

@@ -0,0 +1,164 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2014 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _mapchooser_included_
#endinput
#endif
#define _mapchooser_included_
enum NominateResult
{
Nominate_Added, /** The map was added to the nominate list */
Nominate_Replaced, /** A clients existing nomination was replaced */
Nominate_AlreadyInVote, /** Specified map was already in the vote */
Nominate_InvalidMap, /** Mapname specified wasn't a valid map */
Nominate_VoteFull /** This will only occur if force was set to false */
};
enum MapChange
{
MapChange_Instant, /** Change map as soon as the voting results have come in */
MapChange_RoundEnd, /** Change map at the end of the round */
MapChange_MapEnd /** Change the sm_nextmap cvar */
};
/**
* Attempt to add a map to the mapchooser map list.
*
* @param map Map to add.
* @param force Should we force the map in even if it requires overwriting an existing nomination?
* @param owner Client index of the nominator. If the client disconnects the nomination will be removed.
* Use 0 for constant nominations
* @return Nominate Result of the outcome
*/
native NominateResult NominateMap(const char[] map, bool force, int owner);
/**
* Attempt to remove a map from the mapchooser map list.
*
* @param map Map to remove.
* @return True if the nomination was found and removed, or false if the nomination was not found.
*/
native bool RemoveNominationByMap(const char[] map);
/**
* Attempt to remove a map from the mapchooser map list.
*
* @param owner Client index of the nominator.
* @return True if the nomination was found and removed, or false if the nomination was not found.
*/
native bool RemoveNominationByOwner(int owner);
/**
* Gets the current list of excluded maps.
*
* @param array An ADT array handle to add the map strings to.
*/
native void GetExcludeMapList(ArrayList array);
/**
* Gets the current list of nominated maps.
*
* @param maparray An ADT array handle to add the map strings to.
* @param ownerarray An optional ADT array handle to add the nominator client indexes to.
*/
native void GetNominatedMapList(ArrayList maparray, ArrayList ownerarray = null);
/**
* Checks if MapChooser will allow a vote
*
* @return True if a vote can be held, or false if mapchooser is already holding a vote.
*/
native bool CanMapChooserStartVote();
/**
* Initiates a MapChooser map vote
*
* Note: If no input array is specified mapchooser will use its internal list. This includes
* any nominations and excluded maps (as per mapchoosers convars).
*
* @param when MapChange consant of when the resulting mapchange should occur.
* @param inputarray ADT array list of maps to add to the vote.
*/
native void InitiateMapChooserVote(MapChange when, ArrayList inputarray=null);
/**
* Checks if MapChooser's end of map vote has completed.
*
* @return True if complete, false otherwise.
*/
native bool HasEndOfMapVoteFinished();
/**
* Checks if MapChooser is set to run an end of map vote.
*
* @return True if enabled, false otherwise.
*/
native bool EndOfMapVoteEnabled();
/**
* Called when mapchooser removes a nomination from its list.
* Nominations cleared on map start will not trigger this forward
*/
forward void OnNominationRemoved(const char[] map, int owner);
/**
* Called when mapchooser starts a Map Vote.
*/
forward void OnMapVoteStarted();
/* DO NOT EDIT BELOW THIS LINE */
public SharedPlugin __pl_mapchooser =
{
name = "mapchooser",
file = "mapchooser.smx",
#if defined REQUIRE_PLUGIN
required = 1,
#else
required = 0,
#endif
};
#if !defined REQUIRE_PLUGIN
public void __pl_mapchooser_SetNTVOptional()
{
MarkNativeAsOptional("NominateMap");
MarkNativeAsOptional("RemoveNominationByMap");
MarkNativeAsOptional("RemoveNominationByOwner");
MarkNativeAsOptional("GetExcludeMapList");
MarkNativeAsOptional("GetNominatedMapList");
MarkNativeAsOptional("CanMapChooserStartVote");
MarkNativeAsOptional("InitiateMapChooserVote");
MarkNativeAsOptional("HasEndOfMapVoteFinished");
MarkNativeAsOptional("EndOfMapVoteEnabled");
}
#endif

1161
scripting/include/menus.inc Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,674 @@
// MOAR COLORS
// By Dr. McKay
// Inspired by: https://forums.alliedmods.net/showthread.php?t=96831
#if defined _colors_included
#endinput
#endif
#define _colors_included
#include <regex>
#define MORE_COLORS_VERSION "1.9.1"
#define MAX_MESSAGE_LENGTH 256
#define MAX_BUFFER_LENGTH (MAX_MESSAGE_LENGTH * 4)
#define COLOR_RED 0xFF4040
#define COLOR_BLUE 0x99CCFF
#define COLOR_GRAY 0xCCCCCC
#define COLOR_GREEN 0x3EFF3E
#define GAME_DODS 0
new bool:CSkipList[MAXPLAYERS + 1];
new Handle:CTrie;
new CTeamColors[][] = {{0xCCCCCC, 0x4D7942, 0xFF4040}}; // Multi-dimensional array for games that don't support SayText2. First index is the game index (as defined by the GAME_ defines), second index is team. 0 = spectator, 1 = team1, 2 = team2
/**
* Prints a message to a specific client in the chat area.
* Supports color tags.
*
* @param client Client index.
* @param message Message (formatting rules).
* @noreturn
*
* On error/Errors: If the client is not connected an error will be thrown.
*/
stock CPrintToChat(client, const String:message[], any:...) {
CCheckTrie();
if(client <= 0 || client > MaxClients) {
ThrowError("Invalid client index %i", client);
}
if(!IsClientInGame(client)) {
ThrowError("Client %i is not in game", client);
}
decl String:buffer[MAX_BUFFER_LENGTH], String:buffer2[MAX_BUFFER_LENGTH];
SetGlobalTransTarget(client);
Format(buffer, sizeof(buffer), "\x01%s", message);
VFormat(buffer2, sizeof(buffer2), buffer, 3);
CReplaceColorCodes(buffer2);
CSendMessage(client, buffer2);
}
/**
* Prints a message to all clients in the chat area.
* Supports color tags.
*
* @param client Client index.
* @param message Message (formatting rules).
* @noreturn
*/
stock CPrintToChatAll(const String:message[], any:...) {
CCheckTrie();
decl String:buffer[MAX_BUFFER_LENGTH], String:buffer2[MAX_BUFFER_LENGTH];
for(new i = 1; i <= MaxClients; i++) {
if(!IsClientInGame(i) || CSkipList[i]) {
CSkipList[i] = false;
continue;
}
SetGlobalTransTarget(i);
Format(buffer, sizeof(buffer), "\x01%s", message);
VFormat(buffer2, sizeof(buffer2), buffer, 2);
CReplaceColorCodes(buffer2);
CSendMessage(i, buffer2);
}
}
/**
* Prints a message to a specific client in the chat area.
* Supports color tags and teamcolor tag.
*
* @param client Client index.
* @param author Author index whose color will be used for teamcolor tag.
* @param message Message (formatting rules).
* @noreturn
*
* On error/Errors: If the client or author are not connected an error will be thrown
*/
stock CPrintToChatEx(client, author, const String:message[], any:...) {
CCheckTrie();
if(client <= 0 || client > MaxClients) {
ThrowError("Invalid client index %i", client);
}
if(!IsClientInGame(client)) {
ThrowError("Client %i is not in game", client);
}
if(author <= 0 || author > MaxClients) {
ThrowError("Invalid client index %i", author);
}
if(!IsClientInGame(author)) {
ThrowError("Client %i is not in game", author);
}
decl String:buffer[MAX_BUFFER_LENGTH], String:buffer2[MAX_BUFFER_LENGTH];
SetGlobalTransTarget(client);
Format(buffer, sizeof(buffer), "\x01%s", message);
VFormat(buffer2, sizeof(buffer2), buffer, 4);
CReplaceColorCodes(buffer2, author);
CSendMessage(client, buffer2, author);
}
/**
* Prints a message to all clients in the chat area.
* Supports color tags and teamcolor tag.
*
* @param author Author index whose color will be used for teamcolor tag.
* @param message Message (formatting rules).
* @noreturn
*
* On error/Errors: If the author is not connected an error will be thrown.
*/
stock CPrintToChatAllEx(author, const String:message[], any:...) {
CCheckTrie();
if(author <= 0 || author > MaxClients) {
ThrowError("Invalid client index %i", author);
}
if(!IsClientInGame(author)) {
ThrowError("Client %i is not in game", author);
}
decl String:buffer[MAX_BUFFER_LENGTH], String:buffer2[MAX_BUFFER_LENGTH];
for(new i = 1; i <= MaxClients; i++) {
if(!IsClientInGame(i) || CSkipList[i]) {
CSkipList[i] = false;
continue;
}
SetGlobalTransTarget(i);
Format(buffer, sizeof(buffer), "\x01%s", message);
VFormat(buffer2, sizeof(buffer2), buffer, 3);
CReplaceColorCodes(buffer2, author);
CSendMessage(i, buffer2, author);
}
}
/**
* Sends a SayText2 usermessage
*
* @param client Client to send usermessage to
* @param message Message to send
* @noreturn
*/
stock CSendMessage(client, const String:message[], author=0) {
if(author == 0) {
author = client;
}
decl String:buffer[MAX_MESSAGE_LENGTH], String:game[16];
GetGameFolderName(game, sizeof(game));
strcopy(buffer, sizeof(buffer), message);
new UserMsg:index = GetUserMessageId("SayText2");
if(index == INVALID_MESSAGE_ID) {
if(StrEqual(game, "dod")) {
new team = GetClientTeam(author);
if(team == 0) {
ReplaceString(buffer, sizeof(buffer), "\x03", "\x04", false); // Unassigned gets green
} else {
decl String:temp[16];
Format(temp, sizeof(temp), "\x07%06X", CTeamColors[GAME_DODS][team - 1]);
ReplaceString(buffer, sizeof(buffer), "\x03", temp, false);
}
}
PrintToChat(client, "%s", buffer);
return;
}
new Handle:buf = StartMessageOne("SayText2", client, USERMSG_RELIABLE|USERMSG_BLOCKHOOKS);
if(GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && GetUserMessageType() == UM_Protobuf) {
PbSetInt(buf, "ent_idx", author);
PbSetBool(buf, "chat", true);
PbSetString(buf, "msg_name", buffer);
PbAddString(buf, "params", "");
PbAddString(buf, "params", "");
PbAddString(buf, "params", "");
PbAddString(buf, "params", "");
} else {
BfWriteByte(buf, author); // Message author
BfWriteByte(buf, true); // Chat message
BfWriteString(buf, buffer); // Message text
}
EndMessage();
}
/**
* This function should only be used right in front of
* CPrintToChatAll or CPrintToChatAllEx. It causes those functions
* to skip the specified client when printing the message.
* After printing the message, the client will no longer be skipped.
*
* @param client Client index
* @noreturn
*/
stock CSkipNextClient(client) {
if(client <= 0 || client > MaxClients) {
ThrowError("Invalid client index %i", client);
}
CSkipList[client] = true;
}
/**
* Checks if the colors trie is initialized and initializes it if it's not (used internally)
*
* @return No return
*/
stock CCheckTrie() {
if(CTrie == INVALID_HANDLE) {
CTrie = InitColorTrie();
}
}
/**
* Replaces color tags in a string with color codes (used internally by CPrintToChat, CPrintToChatAll, CPrintToChatEx, and CPrintToChatAllEx
*
* @param buffer String.
* @param author Optional client index to use for {teamcolor} tags, or 0 for none
* @param removeTags Optional boolean value to determine whether we're replacing tags with colors, or just removing tags, used by CRemoveTags
* @param maxlen Optional value for max buffer length, used by CRemoveTags
* @noreturn
*
* On error/Errors: If the client index passed for author is invalid or not in game.
*/
stock CReplaceColorCodes(String:buffer[], author=0, bool:removeTags=false, maxlen=MAX_BUFFER_LENGTH) {
CCheckTrie();
if(!removeTags) {
ReplaceString(buffer, maxlen, "{default}", "\x01", false);
} else {
ReplaceString(buffer, maxlen, "{default}", "", false);
ReplaceString(buffer, maxlen, "{teamcolor}", "", false);
}
if(author != 0 && !removeTags) {
if(author < 0 || author > MaxClients) {
ThrowError("Invalid client index %i", author);
}
if(!IsClientInGame(author)) {
ThrowError("Client %i is not in game", author);
}
ReplaceString(buffer, maxlen, "{teamcolor}", "\x03", false);
}
new cursor = 0;
new value;
decl String:tag[32], String:buff[32], String:output[maxlen];
strcopy(output, maxlen, buffer);
// Since the string's size is going to be changing, output will hold the replaced string and we'll search buffer
new Handle:regex = CompileRegex("{[a-zA-Z0-9]+}");
for(new i = 0; i < 1000; i++) { // The RegEx extension is quite flaky, so we have to loop here :/. This loop is supposed to be infinite and broken by return, but conditions have been added to be safe.
if(MatchRegex(regex, buffer[cursor]) < 1) {
CloseHandle(regex);
strcopy(buffer, maxlen, output);
return;
}
GetRegexSubString(regex, 0, tag, sizeof(tag));
CStrToLower(tag);
cursor = StrContains(buffer[cursor], tag, false) + cursor + 1;
strcopy(buff, sizeof(buff), tag);
ReplaceString(buff, sizeof(buff), "{", "");
ReplaceString(buff, sizeof(buff), "}", "");
if(!GetTrieValue(CTrie, buff, value)) {
continue;
}
if(removeTags) {
ReplaceString(output, maxlen, tag, "", false);
} else {
Format(buff, sizeof(buff), "\x07%06X", value);
ReplaceString(output, maxlen, tag, buff, false);
}
}
LogError("[MORE COLORS] Infinite loop broken.");
}
/**
* Gets a part of a string
*
* @param input String to get the part from
* @param output Buffer to write to
* @param maxlen Max length of output buffer
* @param start Position to start at
* @param numChars Number of characters to return, or 0 for the end of the string
* @noreturn
*/
stock CSubString(const String:input[], String:output[], maxlen, start, numChars=0) {
new i = 0;
for(;;) {
if(i == maxlen - 1 || i >= numChars || input[start + i] == '\0') {
output[i] = '\0';
return;
}
output[i] = input[start + i];
i++;
}
}
/**
* Converts a string to lowercase
*
* @param buffer String to convert
* @noreturn
*/
stock CStrToLower(String:buffer[]) {
new len = strlen(buffer);
for(new i = 0; i < len; i++) {
buffer[i] = CharToLower(buffer[i]);
}
}
/**
* Adds a color to the colors trie
*
* @param name Color name, without braces
* @param color Hexadecimal representation of the color (0xRRGGBB)
* @return True if color was added successfully, false if a color already exists with that name
*/
stock bool:CAddColor(const String:name[], color) {
CCheckTrie();
new value;
if(GetTrieValue(CTrie, name, value)) {
return false;
}
decl String:newName[64];
strcopy(newName, sizeof(newName), name);
CStrToLower(newName);
SetTrieValue(CTrie, newName, color);
return true;
}
/**
* Removes color tags from a message
*
* @param message Message to remove tags from
* @param maxlen Maximum buffer length
* @noreturn
*/
stock CRemoveTags(String:message[], maxlen) {
CReplaceColorCodes(message, 0, true, maxlen);
}
/**
* Replies to a command with colors
*
* @param client Client to reply to
* @param message Message (formatting rules)
* @noreturn
*/
stock CReplyToCommand(client, const String:message[], any:...) {
decl String:buffer[MAX_BUFFER_LENGTH];
SetGlobalTransTarget(client);
VFormat(buffer, sizeof(buffer), message, 3);
if(GetCmdReplySource() == SM_REPLY_TO_CONSOLE) {
CRemoveTags(buffer, sizeof(buffer));
PrintToConsole(client, "%s", buffer);
} else {
CPrintToChat(client, "%s", buffer);
}
}
/**
* Replies to a command with colors
*
* @param client Client to reply to
* @param author Client to use for {teamcolor}
* @param message Message (formatting rules)
* @noreturn
*/
stock CReplyToCommandEx(client, author, const String:message[], any:...) {
decl String:buffer[MAX_BUFFER_LENGTH];
SetGlobalTransTarget(client);
VFormat(buffer, sizeof(buffer), message, 4);
if(GetCmdReplySource() == SM_REPLY_TO_CONSOLE) {
CRemoveTags(buffer, sizeof(buffer));
PrintToConsole(client, "%s", buffer);
} else {
CPrintToChatEx(client, author, "%s", buffer);
}
}
/**
* Shows admin activity with colors
*
* @param client Client performing an action
* @param message Message (formatting rules)
* @noreturn
*/
stock CShowActivity(client, const String:message[], any:...) {
CCheckTrie();
if(client < 0 || client > MaxClients) {
ThrowError("Invalid client index %d", client);
}
if(client != 0 && !IsClientInGame(client)) {
ThrowError("Client %d is not in game", client);
}
decl String:buffer[MAX_BUFFER_LENGTH], String:buffer2[MAX_BUFFER_LENGTH];
Format(buffer, sizeof(buffer), "\x01%s", message);
VFormat(buffer2, sizeof(buffer2), buffer, 3);
CReplaceColorCodes(buffer2);
ShowActivity(client, "%s", buffer2);
}
/**
* Shows admin activity with colors
*
* @param client Client performing an action
* @param tag Tag to prepend to the message (color tags supported)
* @param message Message (formatting rules)
* @noreturn
*/
stock CShowActivityEx(client, const String:tag[], const String:message[], any:...) {
CCheckTrie();
if(client < 0 || client > MaxClients) {
ThrowError("Invalid client index %d", client);
}
if(client != 0 && !IsClientInGame(client)) {
ThrowError("Client %d is not in game", client);
}
decl String:buffer[MAX_BUFFER_LENGTH], String:buffer2[MAX_BUFFER_LENGTH];
Format(buffer, sizeof(buffer), "\x01%s", message);
VFormat(buffer2, sizeof(buffer2), buffer, 4);
CReplaceColorCodes(buffer2);
strcopy(buffer, sizeof(buffer), tag);
CReplaceColorCodes(buffer);
ShowActivityEx(client, tag, "%s", buffer2);
}
/**
* Shows admin activity with colors
*
* @param client Client performing an action
* @param tag Tag to prepend to the message (color tags supported)
* @param message Message (formatting rules)
* @noreturn
*/
stock CShowActivity2(client, const String:tag[], const String:message[], any:...) {
CCheckTrie();
if(client < 0 || client > MaxClients) {
ThrowError("Invalid client index %d", client);
}
if(client != 0 && !IsClientInGame(client)) {
ThrowError("Client %d is not in game", client);
}
decl String:buffer[MAX_BUFFER_LENGTH], String:buffer2[MAX_BUFFER_LENGTH];
Format(buffer, sizeof(buffer), "\x01%s", message);
VFormat(buffer2, sizeof(buffer2), buffer, 4);
CReplaceColorCodes(buffer2);
strcopy(buffer, sizeof(buffer), tag);
CReplaceColorCodes(buffer);
ShowActivity2(client, buffer, "%s", buffer2);
}
/**
* Determines whether a color name exists
*
* @param color The color name to check
* @return True if the color exists, false otherwise
*/
stock bool:CColorExists(const String:color[]) {
CCheckTrie();
new temp;
return GetTrieValue(CTrie, color, temp);
}
/**
* Returns the hexadecimal representation of a client's team color (will NOT initialize the trie)
*
* @param client Client to get the team color for
* @return Client's team color in hexadecimal, or green if unknown
* On error/Errors: If the client index passed is invalid or not in game.
*/
stock CGetTeamColor(client) {
if(client <= 0 || client > MaxClients) {
ThrowError("Invalid client index %i", client);
}
if(!IsClientInGame(client)) {
ThrowError("Client %i is not in game", client);
}
new value;
switch(GetClientTeam(client)) {
case 1: {
value = COLOR_GRAY;
}
case 2: {
value = COLOR_RED;
}
case 3: {
value = COLOR_BLUE;
}
default: {
value = COLOR_GREEN;
}
}
return value;
}
stock Handle:InitColorTrie() {
new Handle:hTrie = CreateTrie();
SetTrieValue(hTrie, "aliceblue", 0xF0F8FF);
SetTrieValue(hTrie, "allies", 0x4D7942); // same as Allies team in DoD:S
SetTrieValue(hTrie, "ancient", 0xEB4B4B); // same as Ancient item rarity in Dota 2
SetTrieValue(hTrie, "antiquewhite", 0xFAEBD7);
SetTrieValue(hTrie, "aqua", 0x00FFFF);
SetTrieValue(hTrie, "aquamarine", 0x7FFFD4);
SetTrieValue(hTrie, "arcana", 0xADE55C); // same as Arcana item rarity in Dota 2
SetTrieValue(hTrie, "axis", 0xFF4040); // same as Axis team in DoD:S
SetTrieValue(hTrie, "azure", 0x007FFF);
SetTrieValue(hTrie, "beige", 0xF5F5DC);
SetTrieValue(hTrie, "bisque", 0xFFE4C4);
SetTrieValue(hTrie, "black", 0x000000);
SetTrieValue(hTrie, "blanchedalmond", 0xFFEBCD);
SetTrieValue(hTrie, "blue", 0x99CCFF); // same as BLU/Counter-Terrorist team color
SetTrieValue(hTrie, "blueviolet", 0x8A2BE2);
SetTrieValue(hTrie, "brown", 0xA52A2A);
SetTrieValue(hTrie, "burlywood", 0xDEB887);
SetTrieValue(hTrie, "cadetblue", 0x5F9EA0);
SetTrieValue(hTrie, "chartreuse", 0x7FFF00);
SetTrieValue(hTrie, "chocolate", 0xD2691E);
SetTrieValue(hTrie, "collectors", 0xAA0000); // same as Collector's item quality in TF2
SetTrieValue(hTrie, "common", 0xB0C3D9); // same as Common item rarity in Dota 2
SetTrieValue(hTrie, "community", 0x70B04A); // same as Community item quality in TF2
SetTrieValue(hTrie, "coral", 0xFF7F50);
SetTrieValue(hTrie, "cornflowerblue", 0x6495ED);
SetTrieValue(hTrie, "cornsilk", 0xFFF8DC);
SetTrieValue(hTrie, "corrupted", 0xA32C2E); // same as Corrupted item quality in Dota 2
SetTrieValue(hTrie, "crimson", 0xDC143C);
SetTrieValue(hTrie, "cyan", 0x00FFFF);
SetTrieValue(hTrie, "darkblue", 0x00008B);
SetTrieValue(hTrie, "darkcyan", 0x008B8B);
SetTrieValue(hTrie, "darkgoldenrod", 0xB8860B);
SetTrieValue(hTrie, "darkgray", 0xA9A9A9);
SetTrieValue(hTrie, "darkgrey", 0xA9A9A9);
SetTrieValue(hTrie, "darkgreen", 0x006400);
SetTrieValue(hTrie, "darkkhaki", 0xBDB76B);
SetTrieValue(hTrie, "darkmagenta", 0x8B008B);
SetTrieValue(hTrie, "darkolivegreen", 0x556B2F);
SetTrieValue(hTrie, "darkorange", 0xFF8C00);
SetTrieValue(hTrie, "darkorchid", 0x9932CC);
SetTrieValue(hTrie, "darkred", 0x8B0000);
SetTrieValue(hTrie, "darksalmon", 0xE9967A);
SetTrieValue(hTrie, "darkseagreen", 0x8FBC8F);
SetTrieValue(hTrie, "darkslateblue", 0x483D8B);
SetTrieValue(hTrie, "darkslategray", 0x2F4F4F);
SetTrieValue(hTrie, "darkslategrey", 0x2F4F4F);
SetTrieValue(hTrie, "darkturquoise", 0x00CED1);
SetTrieValue(hTrie, "darkviolet", 0x9400D3);
SetTrieValue(hTrie, "deeppink", 0xFF1493);
SetTrieValue(hTrie, "deepskyblue", 0x00BFFF);
SetTrieValue(hTrie, "dimgray", 0x696969);
SetTrieValue(hTrie, "dimgrey", 0x696969);
SetTrieValue(hTrie, "dodgerblue", 0x1E90FF);
SetTrieValue(hTrie, "exalted", 0xCCCCCD); // same as Exalted item quality in Dota 2
SetTrieValue(hTrie, "firebrick", 0xB22222);
SetTrieValue(hTrie, "floralwhite", 0xFFFAF0);
SetTrieValue(hTrie, "forestgreen", 0x228B22);
SetTrieValue(hTrie, "frozen", 0x4983B3); // same as Frozen item quality in Dota 2
SetTrieValue(hTrie, "fuchsia", 0xFF00FF);
SetTrieValue(hTrie, "fullblue", 0x0000FF);
SetTrieValue(hTrie, "fullred", 0xFF0000);
SetTrieValue(hTrie, "gainsboro", 0xDCDCDC);
SetTrieValue(hTrie, "genuine", 0x4D7455); // same as Genuine item quality in TF2
SetTrieValue(hTrie, "ghostwhite", 0xF8F8FF);
SetTrieValue(hTrie, "gold", 0xFFD700);
SetTrieValue(hTrie, "goldenrod", 0xDAA520);
SetTrieValue(hTrie, "gray", 0xCCCCCC); // same as spectator team color
SetTrieValue(hTrie, "grey", 0xCCCCCC);
SetTrieValue(hTrie, "green", 0x3EFF3E);
SetTrieValue(hTrie, "greenyellow", 0xADFF2F);
SetTrieValue(hTrie, "haunted", 0x38F3AB); // same as Haunted item quality in TF2
SetTrieValue(hTrie, "honeydew", 0xF0FFF0);
SetTrieValue(hTrie, "hotpink", 0xFF69B4);
SetTrieValue(hTrie, "immortal", 0xE4AE33); // same as Immortal item rarity in Dota 2
SetTrieValue(hTrie, "indianred", 0xCD5C5C);
SetTrieValue(hTrie, "indigo", 0x4B0082);
SetTrieValue(hTrie, "ivory", 0xFFFFF0);
SetTrieValue(hTrie, "khaki", 0xF0E68C);
SetTrieValue(hTrie, "lavender", 0xE6E6FA);
SetTrieValue(hTrie, "lavenderblush", 0xFFF0F5);
SetTrieValue(hTrie, "lawngreen", 0x7CFC00);
SetTrieValue(hTrie, "legendary", 0xD32CE6); // same as Legendary item rarity in Dota 2
SetTrieValue(hTrie, "lemonchiffon", 0xFFFACD);
SetTrieValue(hTrie, "lightblue", 0xADD8E6);
SetTrieValue(hTrie, "lightcoral", 0xF08080);
SetTrieValue(hTrie, "lightcyan", 0xE0FFFF);
SetTrieValue(hTrie, "lightgoldenrodyellow", 0xFAFAD2);
SetTrieValue(hTrie, "lightgray", 0xD3D3D3);
SetTrieValue(hTrie, "lightgrey", 0xD3D3D3);
SetTrieValue(hTrie, "lightgreen", 0x99FF99);
SetTrieValue(hTrie, "lightpink", 0xFFB6C1);
SetTrieValue(hTrie, "lightsalmon", 0xFFA07A);
SetTrieValue(hTrie, "lightseagreen", 0x20B2AA);
SetTrieValue(hTrie, "lightskyblue", 0x87CEFA);
SetTrieValue(hTrie, "lightslategray", 0x778899);
SetTrieValue(hTrie, "lightslategrey", 0x778899);
SetTrieValue(hTrie, "lightsteelblue", 0xB0C4DE);
SetTrieValue(hTrie, "lightyellow", 0xFFFFE0);
SetTrieValue(hTrie, "lime", 0x00FF00);
SetTrieValue(hTrie, "limegreen", 0x32CD32);
SetTrieValue(hTrie, "linen", 0xFAF0E6);
SetTrieValue(hTrie, "magenta", 0xFF00FF);
SetTrieValue(hTrie, "maroon", 0x800000);
SetTrieValue(hTrie, "mediumaquamarine", 0x66CDAA);
SetTrieValue(hTrie, "mediumblue", 0x0000CD);
SetTrieValue(hTrie, "mediumorchid", 0xBA55D3);
SetTrieValue(hTrie, "mediumpurple", 0x9370D8);
SetTrieValue(hTrie, "mediumseagreen", 0x3CB371);
SetTrieValue(hTrie, "mediumslateblue", 0x7B68EE);
SetTrieValue(hTrie, "mediumspringgreen", 0x00FA9A);
SetTrieValue(hTrie, "mediumturquoise", 0x48D1CC);
SetTrieValue(hTrie, "mediumvioletred", 0xC71585);
SetTrieValue(hTrie, "midnightblue", 0x191970);
SetTrieValue(hTrie, "mintcream", 0xF5FFFA);
SetTrieValue(hTrie, "mistyrose", 0xFFE4E1);
SetTrieValue(hTrie, "moccasin", 0xFFE4B5);
SetTrieValue(hTrie, "mythical", 0x8847FF); // same as Mythical item rarity in Dota 2
SetTrieValue(hTrie, "navajowhite", 0xFFDEAD);
SetTrieValue(hTrie, "navy", 0x000080);
SetTrieValue(hTrie, "normal", 0xB2B2B2); // same as Normal item quality in TF2
SetTrieValue(hTrie, "oldlace", 0xFDF5E6);
SetTrieValue(hTrie, "olive", 0x9EC34F);
SetTrieValue(hTrie, "olivedrab", 0x6B8E23);
SetTrieValue(hTrie, "orange", 0xFFA500);
SetTrieValue(hTrie, "orangered", 0xFF4500);
SetTrieValue(hTrie, "orchid", 0xDA70D6);
SetTrieValue(hTrie, "palegoldenrod", 0xEEE8AA);
SetTrieValue(hTrie, "palegreen", 0x98FB98);
SetTrieValue(hTrie, "paleturquoise", 0xAFEEEE);
SetTrieValue(hTrie, "palevioletred", 0xD87093);
SetTrieValue(hTrie, "papayawhip", 0xFFEFD5);
SetTrieValue(hTrie, "peachpuff", 0xFFDAB9);
SetTrieValue(hTrie, "peru", 0xCD853F);
SetTrieValue(hTrie, "pink", 0xFFC0CB);
SetTrieValue(hTrie, "plum", 0xDDA0DD);
SetTrieValue(hTrie, "powderblue", 0xB0E0E6);
SetTrieValue(hTrie, "purple", 0x800080);
SetTrieValue(hTrie, "rare", 0x4B69FF); // same as Rare item rarity in Dota 2
SetTrieValue(hTrie, "red", 0xFF4040); // same as RED/Terrorist team color
SetTrieValue(hTrie, "rosybrown", 0xBC8F8F);
SetTrieValue(hTrie, "royalblue", 0x4169E1);
SetTrieValue(hTrie, "saddlebrown", 0x8B4513);
SetTrieValue(hTrie, "salmon", 0xFA8072);
SetTrieValue(hTrie, "sandybrown", 0xF4A460);
SetTrieValue(hTrie, "seagreen", 0x2E8B57);
SetTrieValue(hTrie, "seashell", 0xFFF5EE);
SetTrieValue(hTrie, "selfmade", 0x70B04A); // same as Self-Made item quality in TF2
SetTrieValue(hTrie, "sienna", 0xA0522D);
SetTrieValue(hTrie, "silver", 0xC0C0C0);
SetTrieValue(hTrie, "skyblue", 0x87CEEB);
SetTrieValue(hTrie, "slateblue", 0x6A5ACD);
SetTrieValue(hTrie, "slategray", 0x708090);
SetTrieValue(hTrie, "slategrey", 0x708090);
SetTrieValue(hTrie, "snow", 0xFFFAFA);
SetTrieValue(hTrie, "springgreen", 0x00FF7F);
SetTrieValue(hTrie, "steelblue", 0x4682B4);
SetTrieValue(hTrie, "strange", 0xCF6A32); // same as Strange item quality in TF2
SetTrieValue(hTrie, "tan", 0xD2B48C);
SetTrieValue(hTrie, "teal", 0x008080);
SetTrieValue(hTrie, "thistle", 0xD8BFD8);
SetTrieValue(hTrie, "tomato", 0xFF6347);
SetTrieValue(hTrie, "turquoise", 0x40E0D0);
SetTrieValue(hTrie, "uncommon", 0xB0C3D9); // same as Uncommon item rarity in Dota 2
SetTrieValue(hTrie, "unique", 0xFFD700); // same as Unique item quality in TF2
SetTrieValue(hTrie, "unusual", 0x8650AC); // same as Unusual item quality in TF2
SetTrieValue(hTrie, "valve", 0xA50F79); // same as Valve item quality in TF2
SetTrieValue(hTrie, "vintage", 0x476291); // same as Vintage item quality in TF2
SetTrieValue(hTrie, "violet", 0xEE82EE);
SetTrieValue(hTrie, "wheat", 0xF5DEB3);
SetTrieValue(hTrie, "white", 0xFFFFFF);
SetTrieValue(hTrie, "whitesmoke", 0xF5F5F5);
SetTrieValue(hTrie, "yellow", 0xFFFF00);
SetTrieValue(hTrie, "yellowgreen", 0x9ACD32);
return hTrie;
}

View File

@@ -0,0 +1,575 @@
// MOAR COLORS
// By Dr. McKay
// Inspired by: https://forums.alliedmods.net/showthread.php?t=96831
#if defined _morecolors_included
#endinput
#endif
#define _morecolors_included
#include <regex>
#define MORE_COLORS_VERSION "1.6.2"
#define MORE_COLORS_MAX_MESSAGE_LENGTH 256
#define COLOR_RED 0xFF4040
#define COLOR_BLUE 0x99CCFF
#define COLOR_GRAY 0xCCCCCC
#define COLOR_GREEN 0x3EFF3E
new bool:MoreColors_CSkipList[MAXPLAYERS + 1] = {false, ...};
new Handle:MoreColors_CTrie = INVALID_HANDLE;
/**
* Prints a message to a specific client in the chat area.
* Supports color tags.
*
* @param client Client index.
* @param message Message (formatting rules).
* @noreturn
*
* On error/Errors: If the client is not connected an error will be thrown.
*/
stock MoreColors_CPrintToChat(client, const String:message[], any:...) {
MoreColors_CCheckTrie();
if(client <= 0 || client > MaxClients) {
ThrowError("Invalid client index %i", client);
}
if(!IsClientInGame(client)) {
ThrowError("Client %i is not in game", client);
}
decl String:buffer[MORE_COLORS_MAX_MESSAGE_LENGTH], String:buffer2[MORE_COLORS_MAX_MESSAGE_LENGTH];
SetGlobalTransTarget(client);
Format(buffer, sizeof(buffer), "\x01%s", message);
VFormat(buffer2, sizeof(buffer2), buffer, 3);
MoreColors_CReplaceColorCodes(buffer2);
MoreColors_CSendMessage(client, buffer2);
}
/**
* Prints a message to all clients in the chat area.
* Supports color tags.
*
* @param client Client index.
* @param message Message (formatting rules).
* @noreturn
*/
stock MoreColors_CPrintToChatAll(const String:message[], any:...) {
MoreColors_CCheckTrie();
decl String:buffer[MORE_COLORS_MAX_MESSAGE_LENGTH], String:buffer2[MORE_COLORS_MAX_MESSAGE_LENGTH];
for(new i = 1; i <= MaxClients; i++) {
if(!IsClientInGame(i) || IsFakeClient(i) || MoreColors_CSkipList[i]) {
MoreColors_CSkipList[i] = false;
continue;
}
SetGlobalTransTarget(i);
Format(buffer, sizeof(buffer), "\x01%s", message);
VFormat(buffer2, sizeof(buffer2), buffer, 2);
MoreColors_CReplaceColorCodes(buffer2);
MoreColors_CSendMessage(i, buffer2);
}
}
/**
* Prints a message to a specific client in the chat area.
* Supports color tags and teamcolor tag.
*
* @param client Client index.
* @param author Author index whose color will be used for teamcolor tag.
* @param message Message (formatting rules).
* @noreturn
*
* On error/Errors: If the client or author are not connected an error will be thrown
*/
stock MoreColors_CPrintToChatEx(client, author, const String:message[], any:...) {
MoreColors_CCheckTrie();
if(client <= 0 || client > MaxClients) {
ThrowError("Invalid client index %i", client);
}
if(!IsClientInGame(client)) {
ThrowError("Client %i is not in game", client);
}
if(author <= 0 || author > MaxClients) {
ThrowError("Invalid client index %i", author);
}
if(!IsClientInGame(author)) {
ThrowError("Client %i is not in game", author);
}
decl String:buffer[MORE_COLORS_MAX_MESSAGE_LENGTH], String:buffer2[MORE_COLORS_MAX_MESSAGE_LENGTH];
SetGlobalTransTarget(client);
Format(buffer, sizeof(buffer), "\x01%s", message);
VFormat(buffer2, sizeof(buffer2), buffer, 4);
MoreColors_CReplaceColorCodes(buffer2, author);
MoreColors_CSendMessage(client, buffer2, author);
}
/**
* Prints a message to all clients in the chat area.
* Supports color tags and teamcolor tag.
*
* @param author Author index whos color will be used for teamcolor tag.
* @param message Message (formatting rules).
* @noreturn
*
* On error/Errors: If the author is not connected an error will be thrown.
*/
stock MoreColors_CPrintToChatAllEx(author, const String:message[], any:...) {
MoreColors_CCheckTrie();
if(author <= 0 || author > MaxClients) {
ThrowError("Invalid client index %i", author);
}
if(!IsClientInGame(author)) {
ThrowError("Client %i is not in game", author);
}
decl String:buffer[MORE_COLORS_MAX_MESSAGE_LENGTH], String:buffer2[MORE_COLORS_MAX_MESSAGE_LENGTH];
for(new i = 1; i <= MaxClients; i++) {
if(!IsClientInGame(i) || IsFakeClient(i) || MoreColors_CSkipList[i]) {
MoreColors_CSkipList[i] = false;
continue;
}
SetGlobalTransTarget(i);
Format(buffer, sizeof(buffer), "\x01%s", message);
VFormat(buffer2, sizeof(buffer2), buffer, 3);
MoreColors_CReplaceColorCodes(buffer2, author);
MoreColors_CSendMessage(i, buffer2, author);
}
}
/**
* Sends a SayText2 usermessage
*
* @param client Client to send usermessage to
* @param message Message to send
* @noreturn
*/
stock MoreColors_CSendMessage(client, const String:message[], author=0) {
if(author == 0) {
author = client;
}
new UserMsg:index = GetUserMessageId("SayText2");
if(index == INVALID_MESSAGE_ID) {
PrintToChat(client, "%s", message);
return;
}
new Handle:bf = StartMessageOne("SayText2", client, USERMSG_RELIABLE|USERMSG_BLOCKHOOKS);
BfWriteByte(bf, author); // Message author
BfWriteByte(bf, true);
BfWriteString(bf, message);
EndMessage();
}
/**
* This function should only be used right in front of
* CPrintToChatAll or CPrintToChatAllEx. It causes those functions
* to skip the specified client when printing the message.
* After printing the message, the client will no longer be skipped.
*
* @param client Client index
* @noreturn
*/
stock MoreColors_CSkipNextClient(client) {
if(client <= 0 || client > MaxClients) {
ThrowError("Invalid client index %i", client);
}
MoreColors_CSkipList[client] = true;
}
/**
* Checks if the colors trie is initialized and initializes it if it's not (used internally)
*
* @return No return
*/
stock MoreColors_CCheckTrie() {
if(MoreColors_CTrie == INVALID_HANDLE) {
MoreColors_CTrie = InitColorTrie();
}
}
/**
* Replaces color tags in a string with color codes (used internally by CPrintToChat, CPrintToChatAll, CPrintToChatEx, and CPrintToChatAllEx
*
* @param buffer String.
* @param author Optional client index to use for {teamcolor} tags, or 0 for none
* @param removeTags Optional boolean value to determine whether we're replacing tags with colors, or just removing tags, used by CRemoveTags
* @param maxlen Optional value for max buffer length, used by CRemoveTags
* @noreturn
*
* On error/Errors: If the client index passed for author is invalid or not in game.
*/
stock MoreColors_CReplaceColorCodes(String:buffer[], author=0, bool:removeTags=false, maxlen=MORE_COLORS_MAX_MESSAGE_LENGTH) {
MoreColors_CCheckTrie();
if(!removeTags) {
ReplaceString(buffer, maxlen, "{default}", "\x01", false);
} else {
ReplaceString(buffer, maxlen, "{default}", "", false);
ReplaceString(buffer, maxlen, "{teamcolor}", "", false);
}
if(author != 0 && !removeTags) {
if(author < 0 || author > MaxClients) {
ThrowError("Invalid client index %i", author);
}
if(!IsClientInGame(author)) {
ThrowError("Client %i is not in game", author);
}
decl String:game[32];
GetGameFolderName(game, sizeof(game));
if(StrEqual(game, "dod")) {
switch(GetClientTeam(author)) {
case 1: ReplaceString(buffer, maxlen, "{teamcolor}", "\x07CCCCCC", false);
case 2: ReplaceString(buffer, maxlen, "{teamcolor}", "\x074D7942", false);
case 3: ReplaceString(buffer, maxlen, "{teamcolor}", "\x07FF4040", false);
default: ReplaceString(buffer, maxlen, "{teamcolor}", "\x04", false);
}
} else {
ReplaceString(buffer, maxlen, "{teamcolor}", "\x03", false);
}
}
new cursor = 0;
new value, Handle:regex;
decl String:tag[32], String:buff[32], String:output[maxlen];
strcopy(output, maxlen, buffer);
// Since the string's size is going to be changing, output will hold the replaced string and we'll search buffer
for(new i = 0; i < 1000; i++) { // The RegEx extension is quite flaky, so we have to loop here :/. This loop is supposed to be infinite and broken by return, but conditions have been added to be safe.
regex = CompileRegex("{[a-zA-Z]+}");
if(MatchRegex(regex, buffer[cursor]) < 1) {
CloseHandle(regex);
strcopy(buffer, maxlen, output);
return;
}
GetRegexSubString(regex, 0, tag, sizeof(tag));
MoreColors_CStrToLower(tag);
cursor = StrContains(buffer[cursor], tag, false) + cursor + 1;
strcopy(buff, sizeof(buff), tag);
ReplaceString(buff, sizeof(buff), "{", "");
ReplaceString(buff, sizeof(buff), "}", "");
if(!GetTrieValue(MoreColors_CTrie, buff, value)) {
CloseHandle(regex);
continue;
}
if(removeTags) {
ReplaceString(output, maxlen, tag, "", false);
} else {
Format(buff, sizeof(buff), "\x07%06X", value);
ReplaceString(output, maxlen, tag, buff, false);
}
CloseHandle(regex);
}
LogError("[MORE COLORS] Infinite loop broken.");
}
/**
* Gets a part of a string
*
* @param input String to get the part from
* @param output Buffer to write to
* @param maxlen Max length of output buffer
* @param start Position to start at
* @param numChars Number of characters to return, or 0 for the end of the string
* @noreturn
*/
stock MoreColors_CSubString(const String:input[], String:output[], maxlen, start, numChars=0) {
new i = 0;
for(;;) {
if(i == maxlen - 1 || i >= numChars || input[start + i] == '\0') {
output[i] = '\0';
return;
}
output[i] = input[start + i];
i++;
}
}
/**
* Converts a string to lowercase
*
* @param buffer String to convert
* @noreturn
*/
stock MoreColors_CStrToLower(String:buffer[]) {
new len = strlen(buffer);
for(new i = 0; i < len; i++) {
buffer[i] = CharToLower(buffer[i]);
}
}
/**
* Adds a color to the colors trie
*
* @param name Color name, without braces
* @param color Hexadecimal representation of the color (0xRRGGBB)
* @return True if color was added successfully, false if a color already exists with that name
*/
stock bool:MoreColors_CAddColor(const String:name[], color) {
MoreColors_CCheckTrie();
new value;
if(GetTrieValue(MoreColors_CTrie, name, value)) {
return false;
}
decl String:newName[64];
strcopy(newName, sizeof(newName), name);
StrToLower(newName);
SetTrieValue(MoreColors_CTrie, newName, color);
return true;
}
/**
* Removes color tags from a message
*
* @param message Message to remove tags from
* @param maxlen Maximum buffer length
* @noreturn
*/
stock MoreColors_CRemoveTags(String:message[], maxlen) {
MoreColors_CReplaceColorCodes(message, 0, true, maxlen);
}
/**
* Replies to a command with colors
*
* @param client Client to reply to
* @param message Message (formatting rules)
* @noreturn
*/
stock CReplyToCommand(client, const String:message[], any:...) {
decl String:buffer[MORE_COLORS_MAX_MESSAGE_LENGTH * 2];
SetGlobalTransTarget(client);
VFormat(buffer, sizeof(buffer), message, 3);
if(GetCmdReplySource() == SM_REPLY_TO_CONSOLE) {
CRemoveTags(buffer, sizeof(buffer));
PrintToConsole(client, buffer);
} else {
MoreColors_CPrintToChat(client, buffer);
}
}
/**
* Replies to a command with colors
*
* @param client Client to reply to
* @param author Client to use for {teamcolor}
* @param message Message (formatting rules)
* @noreturn
*/
stock MoreColors_CReplyToCommandEx(client, author, const String:message[], any:...) {
decl String:buffer[MORE_COLORS_MAX_MESSAGE_LENGTH * 2];
SetGlobalTransTarget(client);
VFormat(buffer, sizeof(buffer), message, 3);
if(GetCmdReplySource() == SM_REPLY_TO_CONSOLE) {
CRemoveTags(buffer, sizeof(buffer));
PrintToConsole(client, buffer);
} else {
MoreColors_CPrintToChatEx(client, author, buffer);
}
}
/**
* Determines whether a color name exists
*
* @param color The color name to check
* @return True if the color exists, false otherwise
*/
stock bool:MoreColors_CColorExists(const String:color[]) {
MoreColors_CCheckTrie();
return GetTrieValue(MoreColors_CTrie, color, 0);
}
/**
* Returns the hexadecimal representation of a client's team color (will NOT initialize the trie)
*
* @param client Client to get the team color for
* @return Client's team color in hexadecimal, or green if unknown
* On error/Errors: If the client index passed is invalid or not in game.
*/
stock MoreColors_CGetTeamColor(client) {
if(client <= 0 || client > MaxClients) {
ThrowError("Invalid client index %i", client);
}
if(!IsClientInGame(client)) {
ThrowError("Client %i is not in game", client);
}
new value;
switch(GetClientTeam(client)) {
case 1: {
value = COLOR_GRAY;
}
case 2: {
value = COLOR_RED;
}
case 3: {
value = COLOR_BLUE;
}
default: {
value = COLOR_GREEN;
}
}
return value;
}
stock Handle:InitColorTrie() {
new Handle:hTrie = CreateTrie();
SetTrieValue(hTrie, "aliceblue", 0xF0F8FF);
SetTrieValue(hTrie, "allies", 0x4D7942); // same as Allies team in DoD:S
SetTrieValue(hTrie, "antiquewhite", 0xFAEBD7);
SetTrieValue(hTrie, "aqua", 0x00FFFF);
SetTrieValue(hTrie, "aquamarine", 0x7FFFD4);
SetTrieValue(hTrie, "axis", 0xFF4040); // same as Axis team in DoD:S
SetTrieValue(hTrie, "azure", 0x007FFF);
SetTrieValue(hTrie, "beige", 0xF5F5DC);
SetTrieValue(hTrie, "bisque", 0xFFE4C4);
SetTrieValue(hTrie, "black", 0x000000);
SetTrieValue(hTrie, "blanchedalmond", 0xFFEBCD);
SetTrieValue(hTrie, "blue", 0x99CCFF); // same as BLU/Counter-Terrorist team color
SetTrieValue(hTrie, "blueviolet", 0x8A2BE2);
SetTrieValue(hTrie, "brown", 0xA52A2A);
SetTrieValue(hTrie, "burlywood", 0xDEB887);
SetTrieValue(hTrie, "cadetblue", 0x5F9EA0);
SetTrieValue(hTrie, "chartreuse", 0x7FFF00);
SetTrieValue(hTrie, "chocolate", 0xD2691E);
SetTrieValue(hTrie, "community", 0x70B04A); // same as Community item quality in TF2
SetTrieValue(hTrie, "coral", 0xFF7F50);
SetTrieValue(hTrie, "cornflowerblue", 0x6495ED);
SetTrieValue(hTrie, "cornsilk", 0xFFF8DC);
SetTrieValue(hTrie, "crimson", 0xDC143C);
SetTrieValue(hTrie, "cyan", 0x00FFFF);
SetTrieValue(hTrie, "darkblue", 0x00008B);
SetTrieValue(hTrie, "darkcyan", 0x008B8B);
SetTrieValue(hTrie, "darkgoldenrod", 0xB8860B);
SetTrieValue(hTrie, "darkgray", 0xA9A9A9);
SetTrieValue(hTrie, "darkgrey", 0xA9A9A9);
SetTrieValue(hTrie, "darkgreen", 0x006400);
SetTrieValue(hTrie, "darkkhaki", 0xBDB76B);
SetTrieValue(hTrie, "darkmagenta", 0x8B008B);
SetTrieValue(hTrie, "darkolivegreen", 0x556B2F);
SetTrieValue(hTrie, "darkorange", 0xFF8C00);
SetTrieValue(hTrie, "darkorchid", 0x9932CC);
SetTrieValue(hTrie, "darkred", 0x8B0000);
SetTrieValue(hTrie, "darksalmon", 0xE9967A);
SetTrieValue(hTrie, "darkseagreen", 0x8FBC8F);
SetTrieValue(hTrie, "darkslateblue", 0x483D8B);
SetTrieValue(hTrie, "darkslategray", 0x2F4F4F);
SetTrieValue(hTrie, "darkslategrey", 0x2F4F4F);
SetTrieValue(hTrie, "darkturquoise", 0x00CED1);
SetTrieValue(hTrie, "darkviolet", 0x9400D3);
SetTrieValue(hTrie, "deeppink", 0xFF1493);
SetTrieValue(hTrie, "deepskyblue", 0x00BFFF);
SetTrieValue(hTrie, "dimgray", 0x696969);
SetTrieValue(hTrie, "dimgrey", 0x696969);
SetTrieValue(hTrie, "dodgerblue", 0x1E90FF);
SetTrieValue(hTrie, "firebrick", 0xB22222);
SetTrieValue(hTrie, "floralwhite", 0xFFFAF0);
SetTrieValue(hTrie, "forestgreen", 0x228B22);
SetTrieValue(hTrie, "fuchsia", 0xFF00FF);
SetTrieValue(hTrie, "fullblue", 0x0000FF);
SetTrieValue(hTrie, "fullred", 0xFF0000);
SetTrieValue(hTrie, "gainsboro", 0xDCDCDC);
SetTrieValue(hTrie, "genuine", 0x4D7455); // same as Genuine item quality in TF2
SetTrieValue(hTrie, "ghostwhite", 0xF8F8FF);
SetTrieValue(hTrie, "gold", 0xFFD700);
SetTrieValue(hTrie, "goldenrod", 0xDAA520);
SetTrieValue(hTrie, "gray", 0xCCCCCC); // same as spectator team color
SetTrieValue(hTrie, "grey", 0xCCCCCC);
SetTrieValue(hTrie, "green", 0x3EFF3E);
SetTrieValue(hTrie, "greenyellow", 0xADFF2F);
SetTrieValue(hTrie, "haunted", 0x38F3AB); // same as Haunted item quality in TF2
SetTrieValue(hTrie, "honeydew", 0xF0FFF0);
SetTrieValue(hTrie, "hotpink", 0xFF69B4);
SetTrieValue(hTrie, "indianred", 0xCD5C5C);
SetTrieValue(hTrie, "indigo", 0x4B0082);
SetTrieValue(hTrie, "ivory", 0xFFFFF0);
SetTrieValue(hTrie, "khaki", 0xF0E68C);
SetTrieValue(hTrie, "lavender", 0xE6E6FA);
SetTrieValue(hTrie, "lavenderblush", 0xFFF0F5);
SetTrieValue(hTrie, "lawngreen", 0x7CFC00);
SetTrieValue(hTrie, "lemonchiffon", 0xFFFACD);
SetTrieValue(hTrie, "lightblue", 0xADD8E6);
SetTrieValue(hTrie, "lightcoral", 0xF08080);
SetTrieValue(hTrie, "lightcyan", 0xE0FFFF);
SetTrieValue(hTrie, "lightgoldenrodyellow", 0xFAFAD2);
SetTrieValue(hTrie, "lightgray", 0xD3D3D3);
SetTrieValue(hTrie, "lightgrey", 0xD3D3D3);
SetTrieValue(hTrie, "lightgreen", 0x99FF99);
SetTrieValue(hTrie, "lightpink", 0xFFB6C1);
SetTrieValue(hTrie, "lightsalmon", 0xFFA07A);
SetTrieValue(hTrie, "lightseagreen", 0x20B2AA);
SetTrieValue(hTrie, "lightskyblue", 0x87CEFA);
SetTrieValue(hTrie, "lightslategray", 0x778899);
SetTrieValue(hTrie, "lightslategrey", 0x778899);
SetTrieValue(hTrie, "lightsteelblue", 0xB0C4DE);
SetTrieValue(hTrie, "lightyellow", 0xFFFFE0);
SetTrieValue(hTrie, "lime", 0x00FF00);
SetTrieValue(hTrie, "limegreen", 0x32CD32);
SetTrieValue(hTrie, "linen", 0xFAF0E6);
SetTrieValue(hTrie, "magenta", 0xFF00FF);
SetTrieValue(hTrie, "maroon", 0x800000);
SetTrieValue(hTrie, "mediumaquamarine", 0x66CDAA);
SetTrieValue(hTrie, "mediumblue", 0x0000CD);
SetTrieValue(hTrie, "mediumorchid", 0xBA55D3);
SetTrieValue(hTrie, "mediumpurple", 0x9370D8);
SetTrieValue(hTrie, "mediumseagreen", 0x3CB371);
SetTrieValue(hTrie, "mediumslateblue", 0x7B68EE);
SetTrieValue(hTrie, "mediumspringgreen", 0x00FA9A);
SetTrieValue(hTrie, "mediumturquoise", 0x48D1CC);
SetTrieValue(hTrie, "mediumvioletred", 0xC71585);
SetTrieValue(hTrie, "midnightblue", 0x191970);
SetTrieValue(hTrie, "mintcream", 0xF5FFFA);
SetTrieValue(hTrie, "mistyrose", 0xFFE4E1);
SetTrieValue(hTrie, "moccasin", 0xFFE4B5);
SetTrieValue(hTrie, "navajowhite", 0xFFDEAD);
SetTrieValue(hTrie, "navy", 0x000080);
SetTrieValue(hTrie, "normal", 0xB2B2B2); // same as Normal item quality in TF2
SetTrieValue(hTrie, "oldlace", 0xFDF5E6);
SetTrieValue(hTrie, "olive", 0x9EC34F);
SetTrieValue(hTrie, "olivedrab", 0x6B8E23);
SetTrieValue(hTrie, "orange", 0xFFA500);
SetTrieValue(hTrie, "orangered", 0xFF4500);
SetTrieValue(hTrie, "orchid", 0xDA70D6);
SetTrieValue(hTrie, "palegoldenrod", 0xEEE8AA);
SetTrieValue(hTrie, "palegreen", 0x98FB98);
SetTrieValue(hTrie, "paleturquoise", 0xAFEEEE);
SetTrieValue(hTrie, "palevioletred", 0xD87093);
SetTrieValue(hTrie, "papayawhip", 0xFFEFD5);
SetTrieValue(hTrie, "peachpuff", 0xFFDAB9);
SetTrieValue(hTrie, "peru", 0xCD853F);
SetTrieValue(hTrie, "pink", 0xFFC0CB);
SetTrieValue(hTrie, "plum", 0xDDA0DD);
SetTrieValue(hTrie, "powderblue", 0xB0E0E6);
SetTrieValue(hTrie, "purple", 0x800080);
SetTrieValue(hTrie, "red", 0xFF4040); // same as RED/Terrorist team color
SetTrieValue(hTrie, "rosybrown", 0xBC8F8F);
SetTrieValue(hTrie, "royalblue", 0x4169E1);
SetTrieValue(hTrie, "saddlebrown", 0x8B4513);
SetTrieValue(hTrie, "salmon", 0xFA8072);
SetTrieValue(hTrie, "sandybrown", 0xF4A460);
SetTrieValue(hTrie, "seagreen", 0x2E8B57);
SetTrieValue(hTrie, "seashell", 0xFFF5EE);
SetTrieValue(hTrie, "selfmade", 0x70B04A); // same as Self-Made item quality in TF2
SetTrieValue(hTrie, "sienna", 0xA0522D);
SetTrieValue(hTrie, "silver", 0xC0C0C0);
SetTrieValue(hTrie, "skyblue", 0x87CEEB);
SetTrieValue(hTrie, "slateblue", 0x6A5ACD);
SetTrieValue(hTrie, "slategray", 0x708090);
SetTrieValue(hTrie, "slategrey", 0x708090);
SetTrieValue(hTrie, "snow", 0xFFFAFA);
SetTrieValue(hTrie, "springgreen", 0x00FF7F);
SetTrieValue(hTrie, "steelblue", 0x4682B4);
SetTrieValue(hTrie, "strange", 0xCF6A32); // same as Strange item quality in TF2
SetTrieValue(hTrie, "tan", 0xD2B48C);
SetTrieValue(hTrie, "teal", 0x008080);
SetTrieValue(hTrie, "thistle", 0xD8BFD8);
SetTrieValue(hTrie, "tomato", 0xFF6347);
SetTrieValue(hTrie, "turquoise", 0x40E0D0);
SetTrieValue(hTrie, "unique", 0xFFD700); // same as Unique item quality in TF2
SetTrieValue(hTrie, "unusual", 0x8650AC); // same as Unusual item quality in TF2
SetTrieValue(hTrie, "valve", 0xA50F79); // same as Valve item quality in TF2
SetTrieValue(hTrie, "vintage", 0x476291); // same as Vintage item quality in TF2
SetTrieValue(hTrie, "violet", 0xEE82EE);
SetTrieValue(hTrie, "wheat", 0xF5DEB3);
SetTrieValue(hTrie, "white", 0xFFFFFF);
SetTrieValue(hTrie, "whitesmoke", 0xF5F5F5);
SetTrieValue(hTrie, "yellow", 0xFFFF00);
SetTrieValue(hTrie, "yellowgreen", 0x9ACD32);
return hTrie;
}

View File

@@ -0,0 +1,419 @@
#if defined _mutlicolors_included
#endinput
#endif
#define _mutlicolors_included
#include <multicolors/colors>
#include <multicolors/morecolors>
#define MuCo_VERSION "1.0.1"
/*
*
* Credits:
* - Popoklopsi
* - Powerlord
* - exvel
* - Dr. McKay
*
* Based on stamm-colors
* - https://github.com/popoklopsi/Stamm/blob/master/include/stamm/stamm-colors.inc
*
*/
/* Global var to check whether colors are fixed or not */
new bool:g_bCFixColors = false;
/**
* Writes a message to a client with the correct stock for the game.
*
* @param client Client index.
* @param message Message (formatting rules).
*
* @noreturn
* @error If the client is not connected an error will be thrown.
*/
stock CPrintToChat(client, const String:message[], any:...)
{
decl String:buffer[MAX_MESSAGE_LENGTH];
VFormat(buffer, sizeof(buffer), message, 3);
if (!g_bCFixColors)
{
CFixColors();
}
if (!IsSource2009())
{
C_PrintToChat(client, buffer);
}
else
{
MC_PrintToChat(client, buffer);
}
}
/**
* Prints a message to all clients in the chat area.
* Supports color tags.
*
* @param client Client index.
* @param message Message (formatting rules)
* @return No return
*/
stock CPrintToChatAll(const String:message[], any:...)
{
decl String:buffer[MAX_MESSAGE_LENGTH];
VFormat(buffer, sizeof(buffer), message, 2);
if (!g_bCFixColors)
{
CFixColors();
}
if (!IsSource2009())
{
C_PrintToChatAll(buffer);
}
else
{
MC_PrintToChatAll(buffer);
}
}
/**
* Writes a message to a client with the correct stock for the game.
*
* @param client Client index.
* @param author Author index.
* @param message Message (formatting rules).
*
* @noreturn
* @error If the client is not connected an error will be thrown.
*/
stock CPrintToChatEx(client, author, const String:message[], any:...)
{
decl String:buffer[MAX_MESSAGE_LENGTH];
VFormat(buffer, sizeof(buffer), message, 4);
if (!g_bCFixColors)
{
CFixColors();
}
if (!IsSource2009())
{
C_PrintToChatEx(client, author, buffer);
}
else
{
MC_PrintToChatEx(client, author, buffer);
}
}
/**
* Writes a message to all clients with the correct stock for the game.
*
* @param author Author index.
* @param message Message (formatting rules).
*
* @noreturn
*/
stock CPrintToChatAllEx(author, const String:message[], any:...)
{
decl String:buffer[MAX_MESSAGE_LENGTH];
VFormat(buffer, sizeof(buffer), message, 3);
if (!g_bCFixColors)
{
CFixColors();
}
if (!IsSource2009())
{
C_PrintToChatAllEx(author, buffer);
}
else
{
MC_PrintToChatAllEx(author, buffer);
}
}
/**
* Replies to a command with colors
*
* @param client Client to reply to
* @param message Message (formatting rules)
* @noreturn
*/
stock CReplyToCommand(author, const String:message[], any:...)
{
decl String:buffer[MAX_MESSAGE_LENGTH];
VFormat(buffer, sizeof(buffer), message, 3);
if (!g_bCFixColors)
{
CFixColors();
}
if (!IsSource2009())
{
C_ReplyToCommand(author, buffer);
}
else
{
MC_ReplyToCommand(author, buffer);
}
}
/**
* Replies to a command with colors
*
* @param client Client to reply to
* @param author Client to use for {teamcolor}
* @param message Message (formatting rules)
* @noreturn
*/
stock CReplyToCommandEx(client, author, const String:message[], any:...)
{
decl String:buffer[MAX_MESSAGE_LENGTH];
VFormat(buffer, sizeof(buffer), message, 4);
if (!g_bCFixColors)
{
CFixColors();
}
if (!IsSource2009())
{
C_ReplyToCommandEx(client, author, buffer);
}
else
{
MC_ReplyToCommandEx(client, author, buffer);
}
}
/**
* Displays usage of an admin command to users depending on the
* setting of the sm_show_activity cvar.
*
* This version does not display a message to the originating client
* if used from chat triggers or menus. If manual replies are used
* for these cases, then this function will suffice. Otherwise,
* CShowActivity2() is slightly more useful.
* Supports color tags.
*
* @param client Client index doing the action, or 0 for server.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
* @noreturn
* @error
*/
stock CShowActivity(author, const String:message[], any:...)
{
decl String:buffer[MAX_MESSAGE_LENGTH];
VFormat(buffer, sizeof(buffer), message, 3);
if (!g_bCFixColors)
{
CFixColors();
}
if (!IsSource2009())
{
C_ShowActivity(author, buffer);
}
else
{
MC_ShowActivity(author, buffer);
}
}
/**
* Same as C_ShowActivity(), except the tag parameter is used instead of "[SM] " (note that you must supply any spacing).
* Supports color tags.
*
* @param client Client index doing the action, or 0 for server.
* @param tags Tag to display with.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
* @noreturn
* @error
*/
stock CShowActivityEx(author, const String:tag[], const String:message[], any:...)
{
decl String:buffer[MAX_MESSAGE_LENGTH];
VFormat(buffer, sizeof(buffer), message, 4);
if (!g_bCFixColors)
{
CFixColors();
}
if (!IsSource2009())
{
C_ShowActivityEx(author, tag, buffer);
}
else
{
MC_ShowActivityEx(author, tag, buffer);
}
}
/**
* Displays usage of an admin command to users depending on the setting of the sm_show_activity cvar.
* All users receive a message in their chat text, except for the originating client,
* who receives the message based on the current ReplySource.
* Supports color tags.
*
* @param client Client index doing the action, or 0 for server.
* @param tags Tag to prepend to the message.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
* @noreturn
* @error
*/
stock CShowActivity2(author, const String:tag[], const String:message[], any:...)
{
decl String:buffer[MAX_MESSAGE_LENGTH];
VFormat(buffer, sizeof(buffer), message, 4);
if (!g_bCFixColors)
{
CFixColors();
}
if (!IsSource2009())
{
C_ShowActivity2(author, tag, buffer);
}
else
{
MC_ShowActivity2(author, tag, buffer);
}
}
/**
* Replaces color tags in a string with color codes
*
* @param message String.
* @param maxlength Maximum length of the string buffer.
*
* @noreturn
*/
stock CFormatColor(String:message[], maxlength, author=-1)
{
if (!g_bCFixColors)
{
CFixColors();
}
if (!IsSource2009())
{
if (author == 0)
{
author = -1;
}
C_Format(message, maxlength, author);
}
else
{
if (author == -1)
{
author = 0;
}
MC_ReplaceColorCodes(message, author, false, maxlength);
}
}
/**
* Fixes missing Lightgreen color.
*
* @noreturn
*/
stock CFixColors()
{
g_bCFixColors = true;
// Replace lightgreen if not exists
if (!C_ColorAllowed(Color_Lightgreen))
{
if (C_ColorAllowed(Color_Lime))
{
C_ReplaceColor(Color_Lightgreen, Color_Lime);
}
else if (C_ColorAllowed(Color_Olive))
{
C_ReplaceColor(Color_Lightgreen, Color_Olive);
}
}
}
stock IsSource2009()
{
if(GetEngineVersion() == Engine_CSS || GetEngineVersion() == Engine_HL2DM || GetEngineVersion() == Engine_DODS || GetEngineVersion() == Engine_TF2)
{
return true;
}
else
{
return false;
}
}

View File

@@ -0,0 +1,941 @@
/**************************************************************************
* *
* Colored Chat Functions *
* Author: exvel, Editor: Popoklopsi, Powerlord, Bara *
* Version: 1.2.4 *
* *
**************************************************************************/
#if defined _colors_included
#endinput
#endif
#define _colors_included
#define MAX_MESSAGE_LENGTH 250
#define MAX_COLORS 18
#define SERVER_INDEX 0
#define NO_INDEX -1
#define NO_PLAYER -2
enum C_Colors
{
Color_Default = 0,
Color_Darkred,
Color_Green,
Color_Lightgreen,
Color_Red,
Color_Blue,
Color_Olive,
Color_Lime,
Color_Lightred,
Color_Purple,
Color_Grey,
Color_Orange,
Color_Bluegrey,
Color_Lightblue,
Color_Darkblue,
Color_Grey2,
Color_Orchid,
Color_Lightred2
}
/* C_Colors' properties */
new String:C_Tag[][] = {"{default}", "{darkred}", "{green}", "{lightgreen}", "{red}", "{blue}", "{olive}", "{lime}", "{lightred}", "{purple}", "{grey}", "{orange}", "{bluegrey}", "{lightblue}", "{darkblue}", "{grey2}", "{orchid}", "{lightred2}"};
new String:C_TagCode[][] = {"\x01", "\x02", "\x04", "\x03", "\x03", "\x03", "\x05", "\x06", "\x07", "\x03", "\x08", "\x09", "\x0A", "\x0B", "\x0C", "\x0D", "\x0E", "\x0F"};
new bool:C_TagReqSayText2[] = {false, false, false, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false};
new bool:C_EventIsHooked = false;
new bool:C_SkipList[MAXPLAYERS+1] = {false,...};
/* Game default profile */
new bool:C_Profile_Colors[] = {true, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false};
new C_Profile_TeamIndex[] = {NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX};
new bool:C_Profile_SayText2 = false;
static Handle:sm_show_activity = INVALID_HANDLE;
/**
* Prints a message to a specific client in the chat area.
* Supports color tags.
*
* @param client Client index.
* @param szMessage Message (formatting rules).
* @return No return
*
* On error/Errors: If the client is not connected an error will be thrown.
*/
stock C_PrintToChat(client, const String:szMessage[], any:...)
{
if (client <= 0 || client > MaxClients)
ThrowError("Invalid client index %d", client);
if (!IsClientInGame(client))
ThrowError("Client %d is not in game", client);
decl String:szBuffer[MAX_MESSAGE_LENGTH];
decl String:szCMessage[MAX_MESSAGE_LENGTH];
SetGlobalTransTarget(client);
Format(szBuffer, sizeof(szBuffer), "\x01%s", szMessage);
VFormat(szCMessage, sizeof(szCMessage), szBuffer, 3);
new index = C_Format(szCMessage, sizeof(szCMessage));
if (index == NO_INDEX)
PrintToChat(client, "%s", szCMessage);
else
C_SayText2(client, index, szCMessage);
}
/**
* Reples to a message in a command. A client index of 0 will use PrintToServer().
* If the command was from the console, PrintToConsole() is used. If the command was from chat, C_PrintToChat() is used.
* Supports color tags.
*
* @param client Client index, or 0 for server.
* @param szMessage Formatting rules.
* @param ... Variable number of format parameters.
* @return No return
*
* On error/Errors: If the client is not connected or invalid.
*/
stock C_ReplyToCommand(client, const String:szMessage[], any:...)
{
decl String:szCMessage[MAX_MESSAGE_LENGTH];
SetGlobalTransTarget(client);
VFormat(szCMessage, sizeof(szCMessage), szMessage, 3);
if (client == 0)
{
C_RemoveTags(szCMessage, sizeof(szCMessage));
PrintToServer("%s", szCMessage);
}
else if (GetCmdReplySource() == SM_REPLY_TO_CONSOLE)
{
C_RemoveTags(szCMessage, sizeof(szCMessage));
PrintToConsole(client, "%s", szCMessage);
}
else
{
C_PrintToChat(client, "%s", szCMessage);
}
}
/**
* Reples to a message in a command. A client index of 0 will use PrintToServer().
* If the command was from the console, PrintToConsole() is used. If the command was from chat, C_PrintToChat() is used.
* Supports color tags.
*
* @param client Client index, or 0 for server.
* @param author Author index whose color will be used for teamcolor tag.
* @param szMessage Formatting rules.
* @param ... Variable number of format parameters.
* @return No return
*
* On error/Errors: If the client is not connected or invalid.
*/
stock C_ReplyToCommandEx(client, author, const String:szMessage[], any:...)
{
decl String:szCMessage[MAX_MESSAGE_LENGTH];
SetGlobalTransTarget(client);
VFormat(szCMessage, sizeof(szCMessage), szMessage, 4);
if (client == 0)
{
C_RemoveTags(szCMessage, sizeof(szCMessage));
PrintToServer("%s", szCMessage);
}
else if (GetCmdReplySource() == SM_REPLY_TO_CONSOLE)
{
C_RemoveTags(szCMessage, sizeof(szCMessage));
PrintToConsole(client, "%s", szCMessage);
}
else
{
C_PrintToChatEx(client, author, "%s", szCMessage);
}
}
/**
* Prints a message to all clients in the chat area.
* Supports color tags.
*
* @param client Client index.
* @param szMessage Message (formatting rules)
* @return No return
*/
stock C_PrintToChatAll(const String:szMessage[], any:...)
{
decl String:szBuffer[MAX_MESSAGE_LENGTH];
for (new i = 1; i <= MaxClients; i++)
{
if (IsClientInGame(i) && !IsFakeClient(i) && !C_SkipList[i])
{
SetGlobalTransTarget(i);
VFormat(szBuffer, sizeof(szBuffer), szMessage, 2);
C_PrintToChat(i, "%s", szBuffer);
}
C_SkipList[i] = false;
}
}
/**
* Prints a message to a specific client in the chat area.
* Supports color tags and teamcolor tag.
*
* @param client Client index.
* @param author Author index whose color will be used for teamcolor tag.
* @param szMessage Message (formatting rules).
* @return No return
*
* On error/Errors: If the client or author are not connected an error will be thrown.
*/
stock C_PrintToChatEx(client, author, const String:szMessage[], any:...)
{
if (client <= 0 || client > MaxClients)
ThrowError("Invalid client index %d", client);
if (!IsClientInGame(client))
ThrowError("Client %d is not in game", client);
if (author < 0 || author > MaxClients)
ThrowError("Invalid client index %d", author);
decl String:szBuffer[MAX_MESSAGE_LENGTH];
decl String:szCMessage[MAX_MESSAGE_LENGTH];
SetGlobalTransTarget(client);
Format(szBuffer, sizeof(szBuffer), "\x01%s", szMessage);
VFormat(szCMessage, sizeof(szCMessage), szBuffer, 4);
new index = C_Format(szCMessage, sizeof(szCMessage), author);
if (index == NO_INDEX)
PrintToChat(client, "%s", szCMessage);
else
C_SayText2(client, author, szCMessage);
}
/**
* Prints a message to all clients in the chat area.
* Supports color tags and teamcolor tag.
*
* @param author Author index whos color will be used for teamcolor tag.
* @param szMessage Message (formatting rules).
* @return No return
*
* On error/Errors: If the author is not connected an error will be thrown.
*/
stock C_PrintToChatAllEx(author, const String:szMessage[], any:...)
{
if (author < 0 || author > MaxClients)
ThrowError("Invalid client index %d", author);
if (!IsClientInGame(author))
ThrowError("Client %d is not in game", author);
decl String:szBuffer[MAX_MESSAGE_LENGTH];
for (new i = 1; i <= MaxClients; i++)
{
if (IsClientInGame(i) && !IsFakeClient(i) && !C_SkipList[i])
{
SetGlobalTransTarget(i);
VFormat(szBuffer, sizeof(szBuffer), szMessage, 3);
C_PrintToChatEx(i, author, "%s", szBuffer);
}
C_SkipList[i] = false;
}
}
/**
* Removes color tags from the string.
*
* @param szMessage String.
* @return No return
*/
stock C_RemoveTags(String:szMessage[], maxlength)
{
for (new i = 0; i < MAX_COLORS; i++)
ReplaceString(szMessage, maxlength, C_Tag[i], "", false);
ReplaceString(szMessage, maxlength, "{teamcolor}", "", false);
}
/**
* Checks whether a color is allowed or not
*
* @param tag Color Tag.
* @return True when color is supported, otherwise false
*/
stock C_ColorAllowed(C_Colors:color)
{
if (!C_EventIsHooked)
{
C_SetupProfile();
C_EventIsHooked = true;
}
return C_Profile_Colors[color];
}
/**
* Replace the color with another color
* Handle with care!
*
* @param color color to replace.
* @param newColor color to replace with.
* @noreturn
*/
stock C_ReplaceColor(C_Colors:color, C_Colors:newColor)
{
if (!C_EventIsHooked)
{
C_SetupProfile();
C_EventIsHooked = true;
}
C_Profile_Colors[color] = C_Profile_Colors[newColor];
C_Profile_TeamIndex[color] = C_Profile_TeamIndex[newColor];
C_TagReqSayText2[color] = C_TagReqSayText2[newColor];
Format(C_TagCode[color], sizeof(C_TagCode[]), C_TagCode[newColor]);
}
/**
* This function should only be used right in front of
* C_PrintToChatAll or C_PrintToChatAllEx and it tells
* to those funcions to skip specified client when printing
* message to all clients. After message is printed client will
* no more be skipped.
*
* @param client Client index
* @return No return
*/
stock C_SkipNextClient(client)
{
if (client <= 0 || client > MaxClients)
ThrowError("Invalid client index %d", client);
C_SkipList[client] = true;
}
/**
* Replaces color tags in a string with color codes
*
* @param szMessage String.
* @param maxlength Maximum length of the string buffer.
* @return Client index that can be used for SayText2 author index
*
* On error/Errors: If there is more then one team color is used an error will be thrown.
*/
stock C_Format(String:szMessage[], maxlength, author=NO_INDEX)
{
/* Hook event for auto profile setup on map start */
if (!C_EventIsHooked)
{
C_SetupProfile();
HookEvent("server_spawn", C_Event_MapStart, EventHookMode_PostNoCopy);
C_EventIsHooked = true;
}
new iRandomPlayer = NO_INDEX;
// On CS:GO set invisible precolor
if (GetEngineVersion() == Engine_CSGO)
{
Format(szMessage, maxlength, " %s", szMessage);
}
/* If author was specified replace {teamcolor} tag */
if (author != NO_INDEX)
{
if (C_Profile_SayText2)
{
ReplaceString(szMessage, maxlength, "{teamcolor}", "\x03", false);
iRandomPlayer = author;
}
/* If saytext2 is not supported by game replace {teamcolor} with green tag */
else
ReplaceString(szMessage, maxlength, "{teamcolor}", C_TagCode[Color_Green], false);
}
else
ReplaceString(szMessage, maxlength, "{teamcolor}", "", false);
/* For other color tags we need a loop */
for (new i = 0; i < MAX_COLORS; i++)
{
/* If tag not found - skip */
if (StrContains(szMessage, C_Tag[i], false) == -1)
continue;
/* If tag is not supported by game replace it with green tag */
else if (!C_Profile_Colors[i])
ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[Color_Green], false);
/* If tag doesn't need saytext2 simply replace */
else if (!C_TagReqSayText2[i])
ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[i], false);
/* Tag needs saytext2 */
else
{
/* If saytext2 is not supported by game replace tag with green tag */
if (!C_Profile_SayText2)
ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[Color_Green], false);
/* Game supports saytext2 */
else
{
/* If random player for tag wasn't specified replace tag and find player */
if (iRandomPlayer == NO_INDEX)
{
/* Searching for valid client for tag */
iRandomPlayer = C_FindRandomPlayerByTeam(C_Profile_TeamIndex[i]);
/* If player not found replace tag with green color tag */
if (iRandomPlayer == NO_PLAYER)
ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[Color_Green], false);
/* If player was found simply replace */
else
ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[i], false);
}
/* If found another team color tag throw error */
else
{
//ReplaceString(szMessage, maxlength, C_Tag[i], "");
ThrowError("Using two team colors in one message is not allowed");
}
}
}
}
return iRandomPlayer;
}
/**
* Founds a random player with specified team
*
* @param color_team Client team.
* @return Client index or NO_PLAYER if no player found
*/
stock C_FindRandomPlayerByTeam(color_team)
{
if (color_team == SERVER_INDEX)
return 0;
else
{
for (new i = 1; i <= MaxClients; i++)
{
if (IsClientInGame(i) && GetClientTeam(i) == color_team)
return i;
}
}
return NO_PLAYER;
}
/**
* Sends a SayText2 usermessage to a client
*
* @param szMessage Client index
* @param maxlength Author index
* @param szMessage Message
* @return No return.
*/
stock C_SayText2(client, author, const String:szMessage[])
{
new Handle:hBuffer = StartMessageOne("SayText2", client, USERMSG_RELIABLE|USERMSG_BLOCKHOOKS);
if(GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && GetUserMessageType() == UM_Protobuf)
{
PbSetInt(hBuffer, "ent_idx", author);
PbSetBool(hBuffer, "chat", true);
PbSetString(hBuffer, "msg_name", szMessage);
PbAddString(hBuffer, "params", "");
PbAddString(hBuffer, "params", "");
PbAddString(hBuffer, "params", "");
PbAddString(hBuffer, "params", "");
}
else
{
BfWriteByte(hBuffer, author);
BfWriteByte(hBuffer, true);
BfWriteString(hBuffer, szMessage);
}
EndMessage();
}
/**
* Creates game color profile
* This function must be edited if you want to add more games support
*
* @return No return.
*/
stock C_SetupProfile()
{
new EngineVersion:engine = GetEngineVersion();
if (engine == Engine_CSS)
{
C_Profile_Colors[Color_Lightgreen] = true;
C_Profile_Colors[Color_Red] = true;
C_Profile_Colors[Color_Blue] = true;
C_Profile_Colors[Color_Olive] = true;
C_Profile_TeamIndex[Color_Lightgreen] = SERVER_INDEX;
C_Profile_TeamIndex[Color_Red] = 2;
C_Profile_TeamIndex[Color_Blue] = 3;
C_Profile_SayText2 = true;
}
else if (engine == Engine_CSGO)
{
C_Profile_Colors[Color_Red] = true;
C_Profile_Colors[Color_Blue] = true;
C_Profile_Colors[Color_Olive] = true;
C_Profile_Colors[Color_Darkred] = true;
C_Profile_Colors[Color_Lime] = true;
C_Profile_Colors[Color_Lightred] = true;
C_Profile_Colors[Color_Purple] = true;
C_Profile_Colors[Color_Grey] = true;
C_Profile_Colors[Color_Orange] = true;
C_Profile_Colors[Color_Bluegrey] = true;
C_Profile_Colors[Color_Lightblue] = true;
C_Profile_Colors[Color_Darkblue] = true;
C_Profile_Colors[Color_Grey2] = true;
C_Profile_Colors[Color_Orchid] = true;
C_Profile_Colors[Color_Lightred2] = true;
C_Profile_TeamIndex[Color_Red] = 2;
C_Profile_TeamIndex[Color_Blue] = 3;
C_Profile_SayText2 = true;
}
else if (engine == Engine_TF2)
{
C_Profile_Colors[Color_Lightgreen] = true;
C_Profile_Colors[Color_Red] = true;
C_Profile_Colors[Color_Blue] = true;
C_Profile_Colors[Color_Olive] = true;
C_Profile_TeamIndex[Color_Lightgreen] = SERVER_INDEX;
C_Profile_TeamIndex[Color_Red] = 2;
C_Profile_TeamIndex[Color_Blue] = 3;
C_Profile_SayText2 = true;
}
else if (engine == Engine_Left4Dead || engine == Engine_Left4Dead2)
{
C_Profile_Colors[Color_Lightgreen] = true;
C_Profile_Colors[Color_Red] = true;
C_Profile_Colors[Color_Blue] = true;
C_Profile_Colors[Color_Olive] = true;
C_Profile_TeamIndex[Color_Lightgreen] = SERVER_INDEX;
C_Profile_TeamIndex[Color_Red] = 3;
C_Profile_TeamIndex[Color_Blue] = 2;
C_Profile_SayText2 = true;
}
else if (engine == Engine_HL2DM)
{
/* hl2mp profile is based on mp_teamplay convar */
if (GetConVarBool(FindConVar("mp_teamplay")))
{
C_Profile_Colors[Color_Red] = true;
C_Profile_Colors[Color_Blue] = true;
C_Profile_Colors[Color_Olive] = true;
C_Profile_TeamIndex[Color_Red] = 3;
C_Profile_TeamIndex[Color_Blue] = 2;
C_Profile_SayText2 = true;
}
else
{
C_Profile_SayText2 = false;
C_Profile_Colors[Color_Olive] = true;
}
}
else if (engine == Engine_DODS)
{
C_Profile_Colors[Color_Olive] = true;
C_Profile_SayText2 = false;
}
/* Profile for other games */
else
{
if (GetUserMessageId("SayText2") == INVALID_MESSAGE_ID)
{
C_Profile_SayText2 = false;
}
else
{
C_Profile_Colors[Color_Red] = true;
C_Profile_Colors[Color_Blue] = true;
C_Profile_TeamIndex[Color_Red] = 2;
C_Profile_TeamIndex[Color_Blue] = 3;
C_Profile_SayText2 = true;
}
}
}
public Action:C_Event_MapStart(Handle:event, const String:name[], bool:dontBroadcast)
{
C_SetupProfile();
for (new i = 1; i <= MaxClients; i++)
C_SkipList[i] = false;
}
/**
* Displays usage of an admin command to users depending on the
* setting of the sm_show_activity cvar.
*
* This version does not display a message to the originating client
* if used from chat triggers or menus. If manual replies are used
* for these cases, then this function will suffice. Otherwise,
* C_ShowActivity2() is slightly more useful.
* Supports color tags.
*
* @param client Client index doing the action, or 0 for server.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
* @noreturn
* @error
*/
stock C_ShowActivity(client, const String:format[], any:...)
{
if (sm_show_activity == INVALID_HANDLE)
sm_show_activity = FindConVar("sm_show_activity");
new String:tag[] = "[SM] ";
decl String:szBuffer[MAX_MESSAGE_LENGTH];
//decl String:szCMessage[MAX_MESSAGE_LENGTH];
new value = GetConVarInt(sm_show_activity);
new ReplySource:replyto = GetCmdReplySource();
new String:name[MAX_NAME_LENGTH] = "Console";
new String:sign[MAX_NAME_LENGTH] = "ADMIN";
new bool:display_in_chat = false;
if (client != 0)
{
if (client < 0 || client > MaxClients || !IsClientConnected(client))
ThrowError("Client index %d is invalid", client);
GetClientName(client, name, sizeof(name));
new AdminId:id = GetUserAdmin(client);
if (id == INVALID_ADMIN_ID
|| !GetAdminFlag(id, Admin_Generic, Access_Effective))
{
sign = "PLAYER";
}
/* Display the message to the client? */
if (replyto == SM_REPLY_TO_CONSOLE)
{
SetGlobalTransTarget(client);
VFormat(szBuffer, sizeof(szBuffer), format, 3);
C_RemoveTags(szBuffer, sizeof(szBuffer));
PrintToConsole(client, "%s%s\n", tag, szBuffer);
display_in_chat = true;
}
}
else
{
SetGlobalTransTarget(LANG_SERVER);
VFormat(szBuffer, sizeof(szBuffer), format, 3);
C_RemoveTags(szBuffer, sizeof(szBuffer));
PrintToServer("%s%s\n", tag, szBuffer);
}
if (!value)
{
return 1;
}
for (new i = 1; i <= MaxClients; i++)
{
if (!IsClientInGame(i)
|| IsFakeClient(i)
|| (display_in_chat && i == client))
{
continue;
}
new AdminId:id = GetUserAdmin(i);
SetGlobalTransTarget(i);
if (id == INVALID_ADMIN_ID
|| !GetAdminFlag(id, Admin_Generic, Access_Effective))
{
/* Treat this as a normal user. */
if ((value & 1) | (value & 2))
{
new String:newsign[MAX_NAME_LENGTH];
newsign = sign;
if ((value & 2) || (i == client))
{
newsign = name;
}
VFormat(szBuffer, sizeof(szBuffer), format, 3);
C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
}
}
else
{
/* Treat this as an admin user */
new bool:is_root = GetAdminFlag(id, Admin_Root, Access_Effective);
if ((value & 4)
|| (value & 8)
|| ((value & 16) && is_root))
{
new String:newsign[MAX_NAME_LENGTH];
newsign = sign;
if ((value & 8) || ((value & 16) && is_root) || (i == client))
{
newsign = name;
}
VFormat(szBuffer, sizeof(szBuffer), format, 3);
C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
}
}
}
return 1;
}
/**
* Same as C_ShowActivity(), except the tag parameter is used instead of "[SM] " (note that you must supply any spacing).
* Supports color tags.
*
* @param client Client index doing the action, or 0 for server.
* @param tags Tag to display with.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
* @noreturn
* @error
*/
stock C_ShowActivityEx(client, const String:tag[], const String:format[], any:...)
{
if (sm_show_activity == INVALID_HANDLE)
sm_show_activity = FindConVar("sm_show_activity");
decl String:szBuffer[MAX_MESSAGE_LENGTH];
//decl String:szCMessage[MAX_MESSAGE_LENGTH];
new value = GetConVarInt(sm_show_activity);
new ReplySource:replyto = GetCmdReplySource();
new String:name[MAX_NAME_LENGTH] = "Console";
new String:sign[MAX_NAME_LENGTH] = "ADMIN";
new bool:display_in_chat = false;
if (client != 0)
{
if (client < 0 || client > MaxClients || !IsClientConnected(client))
ThrowError("Client index %d is invalid", client);
GetClientName(client, name, sizeof(name));
new AdminId:id = GetUserAdmin(client);
if (id == INVALID_ADMIN_ID
|| !GetAdminFlag(id, Admin_Generic, Access_Effective))
{
sign = "PLAYER";
}
/* Display the message to the client? */
if (replyto == SM_REPLY_TO_CONSOLE)
{
SetGlobalTransTarget(client);
VFormat(szBuffer, sizeof(szBuffer), format, 4);
C_RemoveTags(szBuffer, sizeof(szBuffer));
PrintToConsole(client, "%s%s\n", tag, szBuffer);
display_in_chat = true;
}
}
else
{
SetGlobalTransTarget(LANG_SERVER);
VFormat(szBuffer, sizeof(szBuffer), format, 4);
C_RemoveTags(szBuffer, sizeof(szBuffer));
PrintToServer("%s%s\n", tag, szBuffer);
}
if (!value)
{
return 1;
}
for (new i = 1; i <= MaxClients; i++)
{
if (!IsClientInGame(i)
|| IsFakeClient(i)
|| (display_in_chat && i == client))
{
continue;
}
new AdminId:id = GetUserAdmin(i);
SetGlobalTransTarget(i);
if (id == INVALID_ADMIN_ID
|| !GetAdminFlag(id, Admin_Generic, Access_Effective))
{
/* Treat this as a normal user. */
if ((value & 1) | (value & 2))
{
new String:newsign[MAX_NAME_LENGTH];
newsign = sign;
if ((value & 2) || (i == client))
{
newsign = name;
}
VFormat(szBuffer, sizeof(szBuffer), format, 4);
C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
}
}
else
{
/* Treat this as an admin user */
new bool:is_root = GetAdminFlag(id, Admin_Root, Access_Effective);
if ((value & 4)
|| (value & 8)
|| ((value & 16) && is_root))
{
new String:newsign[MAX_NAME_LENGTH];
newsign = sign;
if ((value & 8) || ((value & 16) && is_root) || (i == client))
{
newsign = name;
}
VFormat(szBuffer, sizeof(szBuffer), format, 4);
C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
}
}
}
return 1;
}
/**
* Displays usage of an admin command to users depending on the setting of the sm_show_activity cvar.
* All users receive a message in their chat text, except for the originating client,
* who receives the message based on the current ReplySource.
* Supports color tags.
*
* @param client Client index doing the action, or 0 for server.
* @param tags Tag to prepend to the message.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
* @noreturn
* @error
*/
stock C_ShowActivity2(client, const String:tag[], const String:format[], any:...)
{
if (sm_show_activity == INVALID_HANDLE)
sm_show_activity = FindConVar("sm_show_activity");
decl String:szBuffer[MAX_MESSAGE_LENGTH];
//decl String:szCMessage[MAX_MESSAGE_LENGTH];
new value = GetConVarInt(sm_show_activity);
// new ReplySource:replyto = GetCmdReplySource();
new String:name[MAX_NAME_LENGTH] = "Console";
new String:sign[MAX_NAME_LENGTH] = "ADMIN";
if (client != 0)
{
if (client < 0 || client > MaxClients || !IsClientConnected(client))
ThrowError("Client index %d is invalid", client);
GetClientName(client, name, sizeof(name));
new AdminId:id = GetUserAdmin(client);
if (id == INVALID_ADMIN_ID
|| !GetAdminFlag(id, Admin_Generic, Access_Effective))
{
sign = "PLAYER";
}
SetGlobalTransTarget(client);
VFormat(szBuffer, sizeof(szBuffer), format, 4);
/* We don't display directly to the console because the chat text
* simply gets added to the console, so we don't want it to print
* twice.
*/
C_PrintToChatEx(client, client, "%s%s", tag, szBuffer);
}
else
{
SetGlobalTransTarget(LANG_SERVER);
VFormat(szBuffer, sizeof(szBuffer), format, 4);
C_RemoveTags(szBuffer, sizeof(szBuffer));
PrintToServer("%s%s\n", tag, szBuffer);
}
if (!value)
{
return 1;
}
for (new i = 1; i <= MaxClients; i++)
{
if (!IsClientInGame(i)
|| IsFakeClient(i)
|| i == client)
{
continue;
}
new AdminId:id = GetUserAdmin(i);
SetGlobalTransTarget(i);
if (id == INVALID_ADMIN_ID
|| !GetAdminFlag(id, Admin_Generic, Access_Effective))
{
/* Treat this as a normal user. */
if ((value & 1) | (value & 2))
{
new String:newsign[MAX_NAME_LENGTH];
newsign = sign;
if ((value & 2))
{
newsign = name;
}
VFormat(szBuffer, sizeof(szBuffer), format, 4);
C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
}
}
else
{
/* Treat this as an admin user */
new bool:is_root = GetAdminFlag(id, Admin_Root, Access_Effective);
if ((value & 4)
|| (value & 8)
|| ((value & 16) && is_root))
{
new String:newsign[MAX_NAME_LENGTH];
newsign = sign;
if ((value & 8) || ((value & 16) && is_root))
{
newsign = name;
}
VFormat(szBuffer, sizeof(szBuffer), format, 4);
C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
}
}
}
return 1;
}

View File

@@ -0,0 +1,948 @@
// MOAR COLORS
// By Dr. McKay
// Inspired by: https://forums.alliedmods.net/showthread.php?t=96831
#if defined _more_colors_included
#endinput
#endif
#define _more_colors_included
#include <regex>
#define MORE_COLORS_VERSION "1.9.1pl2"
#define MC_MAX_MESSAGE_LENGTH 256
#define MAX_BUFFER_LENGTH (MC_MAX_MESSAGE_LENGTH * 4)
#define MCOLOR_RED 0xFF4040
#define MCOLOR_BLUE 0x99CCFF
#define MCOLOR_GRAY 0xCCCCCC
#define MCOLOR_GREEN 0x3EFF3E
#define MC_GAME_DODS 0
new bool:MC_SkipList[MAXPLAYERS + 1];
new Handle:MC_Trie;
new MC_TeamColors[][] = {{0xCCCCCC, 0x4D7942, 0xFF4040}}; // Multi-dimensional array for games that don't support SayText2. First index is the game index (as defined by the GAME_ defines), second index is team. 0 = spectator, 1 = team1, 2 = team2
static Handle:sm_show_activity = INVALID_HANDLE;
/**
* Prints a message to a specific client in the chat area.
* Supports color tags.
*
* @param client Client index.
* @param message Message (formatting rules).
* @noreturn
*
* On error/Errors: If the client is not connected an error will be thrown.
*/
stock MC_PrintToChat(client, const String:message[], any:...) {
MC_CheckTrie();
if(client <= 0 || client > MaxClients) {
ThrowError("Invalid client index %i", client);
}
if(!IsClientInGame(client)) {
ThrowError("Client %i is not in game", client);
}
decl String:buffer[MAX_BUFFER_LENGTH], String:buffer2[MAX_BUFFER_LENGTH];
SetGlobalTransTarget(client);
Format(buffer, sizeof(buffer), "\x01%s", message);
VFormat(buffer2, sizeof(buffer2), buffer, 3);
MC_ReplaceColorCodes(buffer2);
MC_SendMessage(client, buffer2);
}
/**
* Prints a message to all clients in the chat area.
* Supports color tags.
*
* @param client Client index.
* @param message Message (formatting rules).
* @noreturn
*/
stock MC_PrintToChatAll(const String:message[], any:...) {
MC_CheckTrie();
decl String:buffer[MAX_BUFFER_LENGTH], String:buffer2[MAX_BUFFER_LENGTH];
for(new i = 1; i <= MaxClients; i++) {
if(!IsClientInGame(i) || MC_SkipList[i]) {
MC_SkipList[i] = false;
continue;
}
SetGlobalTransTarget(i);
Format(buffer, sizeof(buffer), "\x01%s", message);
VFormat(buffer2, sizeof(buffer2), buffer, 2);
MC_ReplaceColorCodes(buffer2);
MC_SendMessage(i, buffer2);
}
}
/**
* Prints a message to a specific client in the chat area.
* Supports color tags and teamcolor tag.
*
* @param client Client index.
* @param author Author index whose color will be used for teamcolor tag.
* @param message Message (formatting rules).
* @noreturn
*
* On error/Errors: If the client or author are not connected an error will be thrown
*/
stock MC_PrintToChatEx(client, author, const String:message[], any:...) {
MC_CheckTrie();
if(client <= 0 || client > MaxClients) {
ThrowError("Invalid client index %i", client);
}
if(!IsClientInGame(client)) {
ThrowError("Client %i is not in game", client);
}
if(author <= 0 || author > MaxClients) {
ThrowError("Invalid client index %i", author);
}
if(!IsClientInGame(author)) {
ThrowError("Client %i is not in game", author);
}
decl String:buffer[MAX_BUFFER_LENGTH], String:buffer2[MAX_BUFFER_LENGTH];
SetGlobalTransTarget(client);
Format(buffer, sizeof(buffer), "\x01%s", message);
VFormat(buffer2, sizeof(buffer2), buffer, 4);
MC_ReplaceColorCodes(buffer2, author);
MC_SendMessage(client, buffer2, author);
}
/**
* Prints a message to all clients in the chat area.
* Supports color tags and teamcolor tag.
*
* @param author Author index whose color will be used for teamcolor tag.
* @param message Message (formatting rules).
* @noreturn
*
* On error/Errors: If the author is not connected an error will be thrown.
*/
stock MC_PrintToChatAllEx(author, const String:message[], any:...) {
MC_CheckTrie();
if(author <= 0 || author > MaxClients) {
ThrowError("Invalid client index %i", author);
}
if(!IsClientInGame(author)) {
ThrowError("Client %i is not in game", author);
}
decl String:buffer[MAX_BUFFER_LENGTH], String:buffer2[MAX_BUFFER_LENGTH];
for(new i = 1; i <= MaxClients; i++) {
if(!IsClientInGame(i) || MC_SkipList[i]) {
MC_SkipList[i] = false;
continue;
}
SetGlobalTransTarget(i);
Format(buffer, sizeof(buffer), "\x01%s", message);
VFormat(buffer2, sizeof(buffer2), buffer, 3);
MC_ReplaceColorCodes(buffer2, author);
MC_SendMessage(i, buffer2, author);
}
}
/**
* Sends a SayText2 usermessage
*
* @param client Client to send usermessage to
* @param message Message to send
* @noreturn
*/
stock MC_SendMessage(client, const String:message[], author=0) {
if(author == 0) {
author = client;
}
decl String:buffer[MC_MAX_MESSAGE_LENGTH];
strcopy(buffer, sizeof(buffer), message);
new UserMsg:index = GetUserMessageId("SayText2");
if(index == INVALID_MESSAGE_ID) {
if(GetEngineVersion() == Engine_DODS) {
new team = GetClientTeam(author);
if(team == 0) {
ReplaceString(buffer, sizeof(buffer), "\x03", "\x04", false); // Unassigned gets green
} else {
decl String:temp[16];
Format(temp, sizeof(temp), "\x07%06X", MC_TeamColors[MC_GAME_DODS][team - 1]);
ReplaceString(buffer, sizeof(buffer), "\x03", temp, false);
}
}
PrintToChat(client, "%s", buffer);
return;
}
new Handle:buf = StartMessageOne("SayText2", client, USERMSG_RELIABLE|USERMSG_BLOCKHOOKS);
if(GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && GetUserMessageType() == UM_Protobuf) {
PbSetInt(buf, "ent_idx", author);
PbSetBool(buf, "chat", true);
PbSetString(buf, "msg_name", buffer);
PbAddString(buf, "params", "");
PbAddString(buf, "params", "");
PbAddString(buf, "params", "");
PbAddString(buf, "params", "");
} else {
BfWriteByte(buf, author); // Message author
BfWriteByte(buf, true); // Chat message
BfWriteString(buf, buffer); // Message text
}
EndMessage();
}
/**
* This function should only be used right in front of
* MC_PrintToChatAll or MC_PrintToChatAllEx. It causes those functions
* to skip the specified client when printing the message.
* After printing the message, the client will no longer be skipped.
*
* @param client Client index
* @noreturn
*/
stock MC_SkipNextClient(client) {
if(client <= 0 || client > MaxClients) {
ThrowError("Invalid client index %i", client);
}
MC_SkipList[client] = true;
}
/**
* Checks if the colors trie is initialized and initializes it if it's not (used internally)
*
* @return No return
*/
stock MC_CheckTrie() {
if(MC_Trie == INVALID_HANDLE) {
MC_Trie = MC_InitColorTrie();
}
}
/**
* Replaces color tags in a string with color codes (used internally by MC_PrintToChat, MC_PrintToChatAll, MC_PrintToChatEx, and MC_PrintToChatAllEx
*
* @param buffer String.
* @param author Optional client index to use for {teamcolor} tags, or 0 for none
* @param removeTags Optional boolean value to determine whether we're replacing tags with colors, or just removing tags, used by MC_RemoveTags
* @param maxlen Optional value for max buffer length, used by MC_RemoveTags
* @noreturn
*
* On error/Errors: If the client index passed for author is invalid or not in game.
*/
stock MC_ReplaceColorCodes(String:buffer[], author=0, bool:removeTags=false, maxlen=MAX_BUFFER_LENGTH) {
MC_CheckTrie();
if(!removeTags) {
ReplaceString(buffer, maxlen, "{default}", "\x01", false);
} else {
ReplaceString(buffer, maxlen, "{default}", "", false);
ReplaceString(buffer, maxlen, "{teamcolor}", "", false);
}
if(author != 0 && !removeTags) {
if(author < 0 || author > MaxClients) {
ThrowError("Invalid client index %i", author);
}
if(!IsClientInGame(author)) {
ThrowError("Client %i is not in game", author);
}
ReplaceString(buffer, maxlen, "{teamcolor}", "\x03", false);
}
new cursor = 0;
new value;
decl String:tag[32], String:buff[32], String:output[maxlen];
strcopy(output, maxlen, buffer);
// Since the string's size is going to be changing, output will hold the replaced string and we'll search buffer
new Handle:regex = CompileRegex("{[a-zA-Z0-9]+}");
for(new i = 0; i < 1000; i++) { // The RegEx extension is quite flaky, so we have to loop here :/. This loop is supposed to be infinite and broken by return, but conditions have been added to be safe.
if(MatchRegex(regex, buffer[cursor]) < 1) {
CloseHandle(regex);
strcopy(buffer, maxlen, output);
return;
}
GetRegexSubString(regex, 0, tag, sizeof(tag));
MC_StrToLower(tag);
cursor = StrContains(buffer[cursor], tag, false) + cursor + 1;
strcopy(buff, sizeof(buff), tag);
ReplaceString(buff, sizeof(buff), "{", "");
ReplaceString(buff, sizeof(buff), "}", "");
if(!GetTrieValue(MC_Trie, buff, value)) {
continue;
}
if(removeTags) {
ReplaceString(output, maxlen, tag, "", false);
} else {
Format(buff, sizeof(buff), "\x07%06X", value);
ReplaceString(output, maxlen, tag, buff, false);
}
}
LogError("[MORE COLORS] Infinite loop broken.");
}
/**
* Gets a part of a string
*
* @param input String to get the part from
* @param output Buffer to write to
* @param maxlen Max length of output buffer
* @param start Position to start at
* @param numChars Number of characters to return, or 0 for the end of the string
* @noreturn
*/
stock CSubString(const String:input[], String:output[], maxlen, start, numChars=0) {
new i = 0;
for(;;) {
if(i == maxlen - 1 || i >= numChars || input[start + i] == '\0') {
output[i] = '\0';
return;
}
output[i] = input[start + i];
i++;
}
}
/**
* Converts a string to lowercase
*
* @param buffer String to convert
* @noreturn
*/
stock MC_StrToLower(String:buffer[]) {
new len = strlen(buffer);
for(new i = 0; i < len; i++) {
buffer[i] = CharToLower(buffer[i]);
}
}
/**
* Adds a color to the colors trie
*
* @param name Color name, without braces
* @param color Hexadecimal representation of the color (0xRRGGBB)
* @return True if color was added successfully, false if a color already exists with that name
*/
stock bool:MC_AddColor(const String:name[], color) {
MC_CheckTrie();
new value;
if(GetTrieValue(MC_Trie, name, value)) {
return false;
}
decl String:newName[64];
strcopy(newName, sizeof(newName), name);
MC_StrToLower(newName);
SetTrieValue(MC_Trie, newName, color);
return true;
}
/**
* Removes color tags from a message
*
* @param message Message to remove tags from
* @param maxlen Maximum buffer length
* @noreturn
*/
stock MC_RemoveTags(String:message[], maxlen) {
MC_ReplaceColorCodes(message, 0, true, maxlen);
}
/**
* Replies to a command with colors
*
* @param client Client to reply to
* @param message Message (formatting rules)
* @noreturn
*/
stock MC_ReplyToCommand(client, const String:message[], any:...) {
decl String:buffer[MAX_BUFFER_LENGTH];
SetGlobalTransTarget(client);
VFormat(buffer, sizeof(buffer), message, 3);
if(GetCmdReplySource() == SM_REPLY_TO_CONSOLE) {
MC_RemoveTags(buffer, sizeof(buffer));
PrintToConsole(client, "%s", buffer);
} else {
MC_PrintToChat(client, "%s", buffer);
}
}
/**
* Replies to a command with colors
*
* @param client Client to reply to
* @param author Client to use for {teamcolor}
* @param message Message (formatting rules)
* @noreturn
*/
stock MC_ReplyToCommandEx(client, author, const String:message[], any:...) {
decl String:buffer[MAX_BUFFER_LENGTH];
SetGlobalTransTarget(client);
VFormat(buffer, sizeof(buffer), message, 4);
if(GetCmdReplySource() == SM_REPLY_TO_CONSOLE) {
MC_RemoveTags(buffer, sizeof(buffer));
PrintToConsole(client, "%s", buffer);
} else {
MC_PrintToChatEx(client, author, "%s", buffer);
}
}
/**
* Displays usage of an admin command to users depending on the
* setting of the sm_show_activity cvar.
*
* This version does not display a message to the originating client
* if used from chat triggers or menus. If manual replies are used
* for these cases, then this function will suffice. Otherwise,
* MC_ShowActivity2() is slightly more useful.
* Supports color tags.
*
* @param client Client index doing the action, or 0 for server.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
* @noreturn
* @error
*/
stock MC_ShowActivity(client, const String:format[], any:...)
{
if (sm_show_activity == INVALID_HANDLE)
sm_show_activity = FindConVar("sm_show_activity");
new String:tag[] = "[SM] ";
decl String:szBuffer[MC_MAX_MESSAGE_LENGTH];
//decl String:szCMessage[MC_MAX_MESSAGE_LENGTH];
new value = GetConVarInt(sm_show_activity);
new ReplySource:replyto = GetCmdReplySource();
new String:name[MAX_NAME_LENGTH] = "Console";
new String:sign[MAX_NAME_LENGTH] = "ADMIN";
new bool:display_in_chat = false;
if (client != 0)
{
if (client < 0 || client > MaxClients || !IsClientConnected(client))
ThrowError("Client index %d is invalid", client);
GetClientName(client, name, sizeof(name));
new AdminId:id = GetUserAdmin(client);
if (id == INVALID_ADMIN_ID
|| !GetAdminFlag(id, Admin_Generic, Access_Effective))
{
sign = "PLAYER";
}
/* Display the message to the client? */
if (replyto == SM_REPLY_TO_CONSOLE)
{
SetGlobalTransTarget(client);
VFormat(szBuffer, sizeof(szBuffer), format, 3);
MC_RemoveTags(szBuffer, sizeof(szBuffer));
PrintToConsole(client, "%s%s\n", tag, szBuffer);
display_in_chat = true;
}
}
else
{
SetGlobalTransTarget(LANG_SERVER);
VFormat(szBuffer, sizeof(szBuffer), format, 3);
MC_RemoveTags(szBuffer, sizeof(szBuffer));
PrintToServer("%s%s\n", tag, szBuffer);
}
if (!value)
{
return 1;
}
for (new i = 1; i <= MaxClients; i++)
{
if (!IsClientInGame(i)
|| IsFakeClient(i)
|| (display_in_chat && i == client))
{
continue;
}
new AdminId:id = GetUserAdmin(i);
SetGlobalTransTarget(i);
if (id == INVALID_ADMIN_ID
|| !GetAdminFlag(id, Admin_Generic, Access_Effective))
{
/* Treat this as a normal user. */
if ((value & 1) | (value & 2))
{
new String:newsign[MAX_NAME_LENGTH];
newsign = sign;
if ((value & 2) || (i == client))
{
newsign = name;
}
VFormat(szBuffer, sizeof(szBuffer), format, 3);
MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
}
}
else
{
/* Treat this as an admin user */
new bool:is_root = GetAdminFlag(id, Admin_Root, Access_Effective);
if ((value & 4)
|| (value & 8)
|| ((value & 16) && is_root))
{
new String:newsign[MAX_NAME_LENGTH];
newsign = sign;
if ((value & 8) || ((value & 16) && is_root) || (i == client))
{
newsign = name;
}
VFormat(szBuffer, sizeof(szBuffer), format, 3);
MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
}
}
}
return 1;
}
/**
* Same as MC_ShowActivity(), except the tag parameter is used instead of "[SM] " (note that you must supply any spacing).
* Supports color tags.
*
* @param client Client index doing the action, or 0 for server.
* @param tags Tag to display with.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
* @noreturn
* @error
*/
stock MC_ShowActivityEx(client, const String:tag[], const String:format[], any:...)
{
if (sm_show_activity == INVALID_HANDLE)
sm_show_activity = FindConVar("sm_show_activity");
decl String:szBuffer[MC_MAX_MESSAGE_LENGTH];
//decl String:szCMessage[MC_MAX_MESSAGE_LENGTH];
new value = GetConVarInt(sm_show_activity);
new ReplySource:replyto = GetCmdReplySource();
new String:name[MAX_NAME_LENGTH] = "Console";
new String:sign[MAX_NAME_LENGTH] = "ADMIN";
new bool:display_in_chat = false;
if (client != 0)
{
if (client < 0 || client > MaxClients || !IsClientConnected(client))
ThrowError("Client index %d is invalid", client);
GetClientName(client, name, sizeof(name));
new AdminId:id = GetUserAdmin(client);
if (id == INVALID_ADMIN_ID
|| !GetAdminFlag(id, Admin_Generic, Access_Effective))
{
sign = "PLAYER";
}
/* Display the message to the client? */
if (replyto == SM_REPLY_TO_CONSOLE)
{
SetGlobalTransTarget(client);
VFormat(szBuffer, sizeof(szBuffer), format, 4);
MC_RemoveTags(szBuffer, sizeof(szBuffer));
PrintToConsole(client, "%s%s\n", tag, szBuffer);
display_in_chat = true;
}
}
else
{
SetGlobalTransTarget(LANG_SERVER);
VFormat(szBuffer, sizeof(szBuffer), format, 4);
MC_RemoveTags(szBuffer, sizeof(szBuffer));
PrintToServer("%s%s\n", tag, szBuffer);
}
if (!value)
{
return 1;
}
for (new i = 1; i <= MaxClients; i++)
{
if (!IsClientInGame(i)
|| IsFakeClient(i)
|| (display_in_chat && i == client))
{
continue;
}
new AdminId:id = GetUserAdmin(i);
SetGlobalTransTarget(i);
if (id == INVALID_ADMIN_ID
|| !GetAdminFlag(id, Admin_Generic, Access_Effective))
{
/* Treat this as a normal user. */
if ((value & 1) | (value & 2))
{
new String:newsign[MAX_NAME_LENGTH];
newsign = sign;
if ((value & 2) || (i == client))
{
newsign = name;
}
VFormat(szBuffer, sizeof(szBuffer), format, 4);
MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
}
}
else
{
/* Treat this as an admin user */
new bool:is_root = GetAdminFlag(id, Admin_Root, Access_Effective);
if ((value & 4)
|| (value & 8)
|| ((value & 16) && is_root))
{
new String:newsign[MAX_NAME_LENGTH];
newsign = sign;
if ((value & 8) || ((value & 16) && is_root) || (i == client))
{
newsign = name;
}
VFormat(szBuffer, sizeof(szBuffer), format, 4);
MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
}
}
}
return 1;
}
/**
* Displays usage of an admin command to users depending on the setting of the sm_show_activity cvar.
* All users receive a message in their chat text, except for the originating client,
* who receives the message based on the current ReplySource.
* Supports color tags.
*
* @param client Client index doing the action, or 0 for server.
* @param tags Tag to prepend to the message.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
* @noreturn
* @error
*/
stock MC_ShowActivity2(client, const String:tag[], const String:format[], any:...)
{
if (sm_show_activity == INVALID_HANDLE)
sm_show_activity = FindConVar("sm_show_activity");
decl String:szBuffer[MC_MAX_MESSAGE_LENGTH];
//decl String:szCMessage[MC_MAX_MESSAGE_LENGTH];
new value = GetConVarInt(sm_show_activity);
// new ReplySource:replyto = GetCmdReplySource();
new String:name[MAX_NAME_LENGTH] = "Console";
new String:sign[MAX_NAME_LENGTH] = "ADMIN";
if (client != 0)
{
if (client < 0 || client > MaxClients || !IsClientConnected(client))
ThrowError("Client index %d is invalid", client);
GetClientName(client, name, sizeof(name));
new AdminId:id = GetUserAdmin(client);
if (id == INVALID_ADMIN_ID
|| !GetAdminFlag(id, Admin_Generic, Access_Effective))
{
sign = "PLAYER";
}
SetGlobalTransTarget(client);
VFormat(szBuffer, sizeof(szBuffer), format, 4);
/* We don't display directly to the console because the chat text
* simply gets added to the console, so we don't want it to print
* twice.
*/
MC_PrintToChatEx(client, client, "%s%s", tag, szBuffer);
}
else
{
SetGlobalTransTarget(LANG_SERVER);
VFormat(szBuffer, sizeof(szBuffer), format, 4);
MC_RemoveTags(szBuffer, sizeof(szBuffer));
PrintToServer("%s%s\n", tag, szBuffer);
}
if (!value)
{
return 1;
}
for (new i = 1; i <= MaxClients; i++)
{
if (!IsClientInGame(i)
|| IsFakeClient(i)
|| i == client)
{
continue;
}
new AdminId:id = GetUserAdmin(i);
SetGlobalTransTarget(i);
if (id == INVALID_ADMIN_ID
|| !GetAdminFlag(id, Admin_Generic, Access_Effective))
{
/* Treat this as a normal user. */
if ((value & 1) | (value & 2))
{
new String:newsign[MAX_NAME_LENGTH];
newsign = sign;
if ((value & 2))
{
newsign = name;
}
VFormat(szBuffer, sizeof(szBuffer), format, 4);
MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
}
}
else
{
/* Treat this as an admin user */
new bool:is_root = GetAdminFlag(id, Admin_Root, Access_Effective);
if ((value & 4)
|| (value & 8)
|| ((value & 16) && is_root))
{
new String:newsign[MAX_NAME_LENGTH];
newsign = sign;
if ((value & 8) || ((value & 16) && is_root))
{
newsign = name;
}
VFormat(szBuffer, sizeof(szBuffer), format, 4);
MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
}
}
}
return 1;
}
/**
* Determines whether a color name exists
*
* @param color The color name to check
* @return True if the color exists, false otherwise
*/
stock bool:CColorExists(const String:color[]) {
MC_CheckTrie();
new temp;
return GetTrieValue(MC_Trie, color, temp);
}
/**
* Returns the hexadecimal representation of a client's team color (will NOT initialize the trie)
*
* @param client Client to get the team color for
* @return Client's team color in hexadecimal, or green if unknown
* On error/Errors: If the client index passed is invalid or not in game.
*/
stock CGetTeamColor(client) {
if(client <= 0 || client > MaxClients) {
ThrowError("Invalid client index %i", client);
}
if(!IsClientInGame(client)) {
ThrowError("Client %i is not in game", client);
}
new value;
switch(GetClientTeam(client)) {
case 1: {
value = MCOLOR_GRAY;
}
case 2: {
value = MCOLOR_RED;
}
case 3: {
value = MCOLOR_BLUE;
}
default: {
value = MCOLOR_GREEN;
}
}
return value;
}
stock Handle:MC_InitColorTrie() {
new Handle:hTrie = CreateTrie();
SetTrieValue(hTrie, "aliceblue", 0xF0F8FF);
SetTrieValue(hTrie, "allies", 0x4D7942); // same as Allies team in DoD:S
SetTrieValue(hTrie, "ancient", 0xEB4B4B); // same as Ancient item rarity in Dota 2
SetTrieValue(hTrie, "antiquewhite", 0xFAEBD7);
SetTrieValue(hTrie, "aqua", 0x00FFFF);
SetTrieValue(hTrie, "aquamarine", 0x7FFFD4);
SetTrieValue(hTrie, "arcana", 0xADE55C); // same as Arcana item rarity in Dota 2
SetTrieValue(hTrie, "axis", 0xFF4040); // same as Axis team in DoD:S
SetTrieValue(hTrie, "azure", 0x007FFF);
SetTrieValue(hTrie, "beige", 0xF5F5DC);
SetTrieValue(hTrie, "bisque", 0xFFE4C4);
SetTrieValue(hTrie, "black", 0x000000);
SetTrieValue(hTrie, "blanchedalmond", 0xFFEBCD);
SetTrieValue(hTrie, "blue", 0x99CCFF); // same as BLU/Counter-Terrorist team color
SetTrieValue(hTrie, "blueviolet", 0x8A2BE2);
SetTrieValue(hTrie, "brown", 0xA52A2A);
SetTrieValue(hTrie, "burlywood", 0xDEB887);
SetTrieValue(hTrie, "cadetblue", 0x5F9EA0);
SetTrieValue(hTrie, "chartreuse", 0x7FFF00);
SetTrieValue(hTrie, "chocolate", 0xD2691E);
SetTrieValue(hTrie, "collectors", 0xAA0000); // same as Collector's item quality in TF2
SetTrieValue(hTrie, "common", 0xB0C3D9); // same as Common item rarity in Dota 2
SetTrieValue(hTrie, "community", 0x70B04A); // same as Community item quality in TF2
SetTrieValue(hTrie, "coral", 0xFF7F50);
SetTrieValue(hTrie, "cornflowerblue", 0x6495ED);
SetTrieValue(hTrie, "cornsilk", 0xFFF8DC);
SetTrieValue(hTrie, "corrupted", 0xA32C2E); // same as Corrupted item quality in Dota 2
SetTrieValue(hTrie, "crimson", 0xDC143C);
SetTrieValue(hTrie, "cyan", 0x00FFFF);
SetTrieValue(hTrie, "darkblue", 0x00008B);
SetTrieValue(hTrie, "darkcyan", 0x008B8B);
SetTrieValue(hTrie, "darkgoldenrod", 0xB8860B);
SetTrieValue(hTrie, "darkgray", 0xA9A9A9);
SetTrieValue(hTrie, "darkgrey", 0xA9A9A9);
SetTrieValue(hTrie, "darkgreen", 0x006400);
SetTrieValue(hTrie, "darkkhaki", 0xBDB76B);
SetTrieValue(hTrie, "darkmagenta", 0x8B008B);
SetTrieValue(hTrie, "darkolivegreen", 0x556B2F);
SetTrieValue(hTrie, "darkorange", 0xFF8C00);
SetTrieValue(hTrie, "darkorchid", 0x9932CC);
SetTrieValue(hTrie, "darkred", 0x8B0000);
SetTrieValue(hTrie, "darksalmon", 0xE9967A);
SetTrieValue(hTrie, "darkseagreen", 0x8FBC8F);
SetTrieValue(hTrie, "darkslateblue", 0x483D8B);
SetTrieValue(hTrie, "darkslategray", 0x2F4F4F);
SetTrieValue(hTrie, "darkslategrey", 0x2F4F4F);
SetTrieValue(hTrie, "darkturquoise", 0x00CED1);
SetTrieValue(hTrie, "darkviolet", 0x9400D3);
SetTrieValue(hTrie, "deeppink", 0xFF1493);
SetTrieValue(hTrie, "deepskyblue", 0x00BFFF);
SetTrieValue(hTrie, "dimgray", 0x696969);
SetTrieValue(hTrie, "dimgrey", 0x696969);
SetTrieValue(hTrie, "dodgerblue", 0x1E90FF);
SetTrieValue(hTrie, "exalted", 0xCCCCCD); // same as Exalted item quality in Dota 2
SetTrieValue(hTrie, "firebrick", 0xB22222);
SetTrieValue(hTrie, "floralwhite", 0xFFFAF0);
SetTrieValue(hTrie, "forestgreen", 0x228B22);
SetTrieValue(hTrie, "frozen", 0x4983B3); // same as Frozen item quality in Dota 2
SetTrieValue(hTrie, "fuchsia", 0xFF00FF);
SetTrieValue(hTrie, "fullblue", 0x0000FF);
SetTrieValue(hTrie, "fullred", 0xFF0000);
SetTrieValue(hTrie, "gainsboro", 0xDCDCDC);
SetTrieValue(hTrie, "genuine", 0x4D7455); // same as Genuine item quality in TF2
SetTrieValue(hTrie, "ghostwhite", 0xF8F8FF);
SetTrieValue(hTrie, "gold", 0xFFD700);
SetTrieValue(hTrie, "goldenrod", 0xDAA520);
SetTrieValue(hTrie, "gray", 0xCCCCCC); // same as spectator team color
SetTrieValue(hTrie, "grey", 0xCCCCCC);
SetTrieValue(hTrie, "green", 0x3EFF3E);
SetTrieValue(hTrie, "greenyellow", 0xADFF2F);
SetTrieValue(hTrie, "haunted", 0x38F3AB); // same as Haunted item quality in TF2
SetTrieValue(hTrie, "honeydew", 0xF0FFF0);
SetTrieValue(hTrie, "hotpink", 0xFF69B4);
SetTrieValue(hTrie, "immortal", 0xE4AE33); // same as Immortal item rarity in Dota 2
SetTrieValue(hTrie, "indianred", 0xCD5C5C);
SetTrieValue(hTrie, "indigo", 0x4B0082);
SetTrieValue(hTrie, "ivory", 0xFFFFF0);
SetTrieValue(hTrie, "khaki", 0xF0E68C);
SetTrieValue(hTrie, "lavender", 0xE6E6FA);
SetTrieValue(hTrie, "lavenderblush", 0xFFF0F5);
SetTrieValue(hTrie, "lawngreen", 0x7CFC00);
SetTrieValue(hTrie, "legendary", 0xD32CE6); // same as Legendary item rarity in Dota 2
SetTrieValue(hTrie, "lemonchiffon", 0xFFFACD);
SetTrieValue(hTrie, "lightblue", 0xADD8E6);
SetTrieValue(hTrie, "lightcoral", 0xF08080);
SetTrieValue(hTrie, "lightcyan", 0xE0FFFF);
SetTrieValue(hTrie, "lightgoldenrodyellow", 0xFAFAD2);
SetTrieValue(hTrie, "lightgray", 0xD3D3D3);
SetTrieValue(hTrie, "lightgrey", 0xD3D3D3);
SetTrieValue(hTrie, "lightgreen", 0x99FF99);
SetTrieValue(hTrie, "lightpink", 0xFFB6C1);
SetTrieValue(hTrie, "lightsalmon", 0xFFA07A);
SetTrieValue(hTrie, "lightseagreen", 0x20B2AA);
SetTrieValue(hTrie, "lightskyblue", 0x87CEFA);
SetTrieValue(hTrie, "lightslategray", 0x778899);
SetTrieValue(hTrie, "lightslategrey", 0x778899);
SetTrieValue(hTrie, "lightsteelblue", 0xB0C4DE);
SetTrieValue(hTrie, "lightyellow", 0xFFFFE0);
SetTrieValue(hTrie, "lime", 0x00FF00);
SetTrieValue(hTrie, "limegreen", 0x32CD32);
SetTrieValue(hTrie, "linen", 0xFAF0E6);
SetTrieValue(hTrie, "magenta", 0xFF00FF);
SetTrieValue(hTrie, "maroon", 0x800000);
SetTrieValue(hTrie, "mediumaquamarine", 0x66CDAA);
SetTrieValue(hTrie, "mediumblue", 0x0000CD);
SetTrieValue(hTrie, "mediumorchid", 0xBA55D3);
SetTrieValue(hTrie, "mediumpurple", 0x9370D8);
SetTrieValue(hTrie, "mediumseagreen", 0x3CB371);
SetTrieValue(hTrie, "mediumslateblue", 0x7B68EE);
SetTrieValue(hTrie, "mediumspringgreen", 0x00FA9A);
SetTrieValue(hTrie, "mediumturquoise", 0x48D1CC);
SetTrieValue(hTrie, "mediumvioletred", 0xC71585);
SetTrieValue(hTrie, "midnightblue", 0x191970);
SetTrieValue(hTrie, "mintcream", 0xF5FFFA);
SetTrieValue(hTrie, "mistyrose", 0xFFE4E1);
SetTrieValue(hTrie, "moccasin", 0xFFE4B5);
SetTrieValue(hTrie, "mythical", 0x8847FF); // same as Mythical item rarity in Dota 2
SetTrieValue(hTrie, "navajowhite", 0xFFDEAD);
SetTrieValue(hTrie, "navy", 0x000080);
SetTrieValue(hTrie, "normal", 0xB2B2B2); // same as Normal item quality in TF2
SetTrieValue(hTrie, "oldlace", 0xFDF5E6);
SetTrieValue(hTrie, "olive", 0x9EC34F);
SetTrieValue(hTrie, "olivedrab", 0x6B8E23);
SetTrieValue(hTrie, "orange", 0xFFA500);
SetTrieValue(hTrie, "orangered", 0xFF4500);
SetTrieValue(hTrie, "orchid", 0xDA70D6);
SetTrieValue(hTrie, "palegoldenrod", 0xEEE8AA);
SetTrieValue(hTrie, "palegreen", 0x98FB98);
SetTrieValue(hTrie, "paleturquoise", 0xAFEEEE);
SetTrieValue(hTrie, "palevioletred", 0xD87093);
SetTrieValue(hTrie, "papayawhip", 0xFFEFD5);
SetTrieValue(hTrie, "peachpuff", 0xFFDAB9);
SetTrieValue(hTrie, "peru", 0xCD853F);
SetTrieValue(hTrie, "pink", 0xFFC0CB);
SetTrieValue(hTrie, "plum", 0xDDA0DD);
SetTrieValue(hTrie, "powderblue", 0xB0E0E6);
SetTrieValue(hTrie, "purple", 0x800080);
SetTrieValue(hTrie, "rare", 0x4B69FF); // same as Rare item rarity in Dota 2
SetTrieValue(hTrie, "red", 0xFF4040); // same as RED/Terrorist team color
SetTrieValue(hTrie, "rosybrown", 0xBC8F8F);
SetTrieValue(hTrie, "royalblue", 0x4169E1);
SetTrieValue(hTrie, "saddlebrown", 0x8B4513);
SetTrieValue(hTrie, "salmon", 0xFA8072);
SetTrieValue(hTrie, "sandybrown", 0xF4A460);
SetTrieValue(hTrie, "seagreen", 0x2E8B57);
SetTrieValue(hTrie, "seashell", 0xFFF5EE);
SetTrieValue(hTrie, "selfmade", 0x70B04A); // same as Self-Made item quality in TF2
SetTrieValue(hTrie, "sienna", 0xA0522D);
SetTrieValue(hTrie, "silver", 0xC0C0C0);
SetTrieValue(hTrie, "skyblue", 0x87CEEB);
SetTrieValue(hTrie, "slateblue", 0x6A5ACD);
SetTrieValue(hTrie, "slategray", 0x708090);
SetTrieValue(hTrie, "slategrey", 0x708090);
SetTrieValue(hTrie, "snow", 0xFFFAFA);
SetTrieValue(hTrie, "springgreen", 0x00FF7F);
SetTrieValue(hTrie, "steelblue", 0x4682B4);
SetTrieValue(hTrie, "strange", 0xCF6A32); // same as Strange item quality in TF2
SetTrieValue(hTrie, "tan", 0xD2B48C);
SetTrieValue(hTrie, "teal", 0x008080);
SetTrieValue(hTrie, "thistle", 0xD8BFD8);
SetTrieValue(hTrie, "tomato", 0xFF6347);
SetTrieValue(hTrie, "turquoise", 0x40E0D0);
SetTrieValue(hTrie, "uncommon", 0xB0C3D9); // same as Uncommon item rarity in Dota 2
SetTrieValue(hTrie, "unique", 0xFFD700); // same as Unique item quality in TF2
SetTrieValue(hTrie, "unusual", 0x8650AC); // same as Unusual item quality in TF2
SetTrieValue(hTrie, "valve", 0xA50F79); // same as Valve item quality in TF2
SetTrieValue(hTrie, "vintage", 0x476291); // same as Vintage item quality in TF2
SetTrieValue(hTrie, "violet", 0xEE82EE);
SetTrieValue(hTrie, "wheat", 0xF5DEB3);
SetTrieValue(hTrie, "white", 0xFFFFFF);
SetTrieValue(hTrie, "whitesmoke", 0xF5F5F5);
SetTrieValue(hTrie, "yellow", 0xFFFF00);
SetTrieValue(hTrie, "yellowgreen", 0x9ACD32);
return hTrie;
}

View File

@@ -0,0 +1,82 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2014 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _nextmap_included_
#endinput
#endif
#define _nextmap_included_
/**
* Sets SourceMod's internal nextmap.
* Equivalent to changing sm_nextmap but with an added validity check.
*
* @param map Next map to set.
* @return True if the nextmap was set, false if map was invalid.
*/
native bool SetNextMap(const char[] map);
/**
* Returns SourceMod's internal nextmap.
*
* @param map Buffer to store the nextmap name.
* @param maxlen Maximum length of the map buffer.
* @return True if a Map was found and copied, false if no nextmap is set (map will be unchanged).
*/
native bool GetNextMap(char[] map, int maxlen);
/**
* Changes the current map and records the reason for the change with maphistory
*
* @param map Map to change to.
* @param reason Reason for change.
*/
native void ForceChangeLevel(const char[] map, const char[] reason);
/**
* Gets the current number of maps in the map history
*
* @return Number of maps.
*/
native int GetMapHistorySize();
/**
* Retrieves a map from the map history list.
*
* @param item Item number. Must be 0 or greater and less than GetMapHistorySize().
* @param map Buffer to store the map name.
* @param mapLen Length of map buffer.
* @param reason Buffer to store the change reason.
* @param reasonLen Length of the reason buffer.
* @param startTime Time the map started.
* @error Invalid item number.
*/
native void GetMapHistory(int item, char[] map, int mapLen, char[] reason, int reasonLen, int &startTime);

View File

@@ -0,0 +1,123 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2018 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _profiler_included
#endinput
#endif
#define _profiler_included
/**
* ONLY AVAILABLE ON WINDOWS RIGHT NOW K.
*/
methodmap Profiler < Handle
{
// Creates a new profile object. The Handle must be freed
// using delete or CloseHandle().
//
// @return A new Profiler Handle.
public native Profiler();
// Starts a cycle for profiling.
public native void Start();
// Stops a cycle for profiling.
//
// @error Profiler was never started.
public native void Stop();
// Returns the amount of high-precision time in seconds
// that passed during the profiler's last start/stop
// cycle.
//
// @return Time elapsed in seconds.
property float Time {
public native get();
}
};
/**
* Creates a new profile object. The Handle must be freed
* using delete or CloseHandle().
*
* @return Handle to the profiler object.
*/
native Profiler CreateProfiler();
/**
* Starts profiling.
*
* @param prof Profiling object.
* @error Invalid Handle.
*/
native void StartProfiling(Handle prof);
/**
* Stops profiling.
*
* @param prof Profiling object.
* @error Invalid Handle or profiling was never started.
*/
native void StopProfiling(Handle prof);
/**
* Returns the amount of high-precision time in seconds
* that passed during the profiler's last start/stop
* cycle.
*
* @param prof Profiling object.
* @return Time elapsed in seconds.
* @error Invalid Handle.
*/
native float GetProfilerTime(Handle prof);
/**
* Mark the start of a profiling event.
*
* @param group Budget group. This can be "all" for a default, or a short
* description like "Timers" or "Events".
* @param name A name to attribute to this profiling event.
*/
native void EnterProfilingEvent(const char[] group, const char[] name);
/**
* Mark the end of the last profiling event. This must be called in the same
* stack frame as StartProfilingEvent(). Not doing so, or throwing errors,
* will make the resulting profile very wrong.
*/
native void LeaveProfilingEvent();
/**
* Returns true if the global profiler is enabled; false otherwise. It is
* not necessary to call this before Enter/LeaveProfilingEvent.
*/
native bool IsProfilingActive();

View File

@@ -0,0 +1,602 @@
/**
* vim: set ts=4 sw=4 tw=99 noet :
* =============================================================================
* SourceMod (C)2013 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _protobuf_included
#endinput
#endif
#define _protobuf_included
#define PB_FIELD_NOT_REPEATED -1
methodmap Protobuf < Handle
{
// Reads an int32, uint32, sint32, fixed32, sfixed32, or enum value from a protobuf message.
//
// @param field Field name.
// @param index Index into repeated field.
// @return Integer value read.
// @error Non-existent field, or incorrect field type.
public native int ReadInt(const char[] field, int index = PB_FIELD_NOT_REPEATED);
// Reads an int64, uint64, sint64, fixed64, sfixed64 from a protobuf message.
//
// @param field Field name.
// @param value Array to represent the large integer (0=High bits, 1=Low bits).
// @param index Index into repeated field.
// @error Non-existent field, or incorrect field type.
public native void ReadInt64(const char[] field, int value[2], int index = PB_FIELD_NOT_REPEATED);
// Reads a float or downcasted double from a protobuf message.
//
// @param field Field name.
// @param index Index into repeated field.
// @return Float value read.
// @error Non-existent field, or incorrect field type.
public native float ReadFloat(const char[] field, int index = PB_FIELD_NOT_REPEATED);
// Reads a bool from a protobuf message.
//
// @param field Field name.
// @param index Index into repeated field.
// @return Boolean value read.
// @error Non-existent field, or incorrect field type.
public native bool ReadBool(const char[] field, int index = PB_FIELD_NOT_REPEATED);
// Reads a string from a protobuf message.
//
// @param field Field name.
// @param buffer Destination string buffer.
// @param maxlength Maximum length of output string buffer.
// @param index Index into repeated field.
// @error Non-existent field, or incorrect field type.
public native void ReadString(const char[] field, char[] buffer, int maxlength, int index = PB_FIELD_NOT_REPEATED);
// Reads an RGBA color value from a protobuf message.
//
// @param field Field name.
// @param buffer Destination color buffer.
// @param index Index into repeated field.
// @error Non-existent field, or incorrect field type.
public native void ReadColor(const char[] field, int buffer[4], int index = PB_FIELD_NOT_REPEATED);
// Reads an XYZ angle value from a protobuf message.
//
// @param field Field name.
// @param buffer Destination angle buffer.
// @param index Index into repeated field.
// @error Non-existent field, or incorrect field type.
public native void ReadAngle(const char[] field, float buffer[3], int index = PB_FIELD_NOT_REPEATED);
// Reads an XYZ vector value from a protobuf message.
//
// @param pb protobuf handle.
// @param field Field name.
// @param buffer Destination vector buffer.
// @param index Index into repeated field.
// @error Non-existent field, or incorrect field type.
public native void ReadVector(const char[] field, float buffer[3], int index = PB_FIELD_NOT_REPEATED);
// Reads an XY vector value from a protobuf message.
//
// @param field Field name.
// @param buffer Destination vector buffer.
// @param index Index into repeated field.
// @error Non-existent field, or incorrect field type.
public native void ReadVector2D(const char[] field, float buffer[2], int index = PB_FIELD_NOT_REPEATED);
// Gets the number of elements in a repeated field of a protobuf message.
//
// @param field Field name.
// @return Number of elements in the field.
// @error Non-existent field, or non-repeated field.
public native int GetRepeatedFieldCount(const char[] field);
// Returns whether or not the named, non-repeated field has a value set.
//
// @param field Field name.
// @return True if value has been set, else false.
// @error Non-existent field, or repeated field.
public native bool HasField(const char[] field);
// Sets an int32, uint32, sint32, fixed32, sfixed32, or enum value on a protobuf message.
//
// @param field Field name.
// @param value Integer value to set.
// @param index Index into repeated field.
// @error Non-existent field, or incorrect field type.
public native void SetInt(const char[] field, int value, int index = PB_FIELD_NOT_REPEATED);
// Sets an int64, uint64, sint64, fixed64, sfixed64 on a protobuf message.
//
// @param field Field name.
// @param value Large integer value to set (0=High bits, 1=Low bits).
// @param index Index into repeated field.
// @error Non-existent field, or incorrect field type.
public native void SetInt64(const char[] field, int value[2], int index = PB_FIELD_NOT_REPEATED);
// Sets a float or double on a protobuf message.
//
// @param field Field name.
// @param value Float value to set.
// @param index Index into repeated field.
// @error Non-existent field, or incorrect field type.
public native void SetFloat(const char[] field, float value, int index = PB_FIELD_NOT_REPEATED);
// Sets a bool on a protobuf message.
//
// @param field Field name.
// @param value Boolean value to set.
// @param index Index into repeated field.
// @error Non-existent field, or incorrect field type.
public native void SetBool(const char[] field, bool value, int index = PB_FIELD_NOT_REPEATED);
// Sets a string on a protobuf message.
//
// @param field Field name.
// @param value String value to set.
// @param index Index into repeated field.
// @error Non-existent field, or incorrect field type.
public native void SetString(const char[] field, const char[] value, int index = PB_FIELD_NOT_REPEATED);
// Sets an RGBA color on a protobuf message.
//
// @param field Field name.
// @param color Color value to set.
// @param index Index into repeated field.
// @error Non-existent field, or incorrect field type.
public native void SetColor(const char[] field, const int color[4], int index = PB_FIELD_NOT_REPEATED);
// Sets an XYZ angle on a protobuf message.
//
// @param field Field name.
// @param angle Angle value to set.
// @param index Index into repeated field.
// @error Non-existent field, or incorrect field type.
public native void SetAngle(const char[] field, const float angle[3], int index = PB_FIELD_NOT_REPEATED);
// Sets an XYZ vector on a protobuf message.
//
// @param field Field name.
// @param vec Vector value to set.
// @param index Index into repeated field.
// @error Non-existent field, or incorrect field type.
public native void SetVector(const char[] field, const float vec[3], int index = PB_FIELD_NOT_REPEATED);
// Sets an XY vector on a protobuf message.
//
// @param field Field name.
// @param vec Vector value to set.
// @param index Index into repeated field.
// @error Non-existent field, or incorrect field type.
public native void SetVector2D(const char[] field, const float vec[2], int index = PB_FIELD_NOT_REPEATED);
// Add an int32, uint32, sint32, fixed32, sfixed32, or enum value to a protobuf message repeated field.
//
// @param field Field name.
// @param value Integer value to add.
// @error Non-existent field, or incorrect field type.
public native void AddInt(const char[] field, int value);
// Add an int64, uint64, sint64, fixed64, sfixed64 to a protobuf message repeated field.
//
// @param field Field name.
// @param value Large integer value to add (0=High bits, 1=Low bits).
// @error Non-existent field, or incorrect field type.
public native void AddInt64(const char[] field, int value[2]);
// Add a float or double to a protobuf message repeated field.
//
// @param field Field name.
// @param value Float value to add.
// @error Non-existent field, or incorrect field type.
public native void AddFloat(const char[] field, float value);
// Add a bool to a protobuf message repeated field.
//
// @param field Field name.
// @param value Boolean value to add.
// @error Non-existent field, or incorrect field type.
public native void AddBool(const char[] field, bool value);
// Add a string to a protobuf message repeated field.
//
// @param field Field name.
// @param value String value to add.
// @error Non-existent field, or incorrect field type.
public native void AddString(const char[] field, const char[] value);
// Add an RGBA color to a protobuf message repeated field.
//
// @param field Field name.
// @param color Color value to add.
// @error Non-existent field, or incorrect field type.
public native void AddColor(const char[] field, const int color[4]);
// Add an XYZ angle to a protobuf message repeated field.
//
// @param field Field name.
// @param angle Angle value to add.
// @error Non-existent field, or incorrect field type.
public native void AddAngle(const char[] field, const float angle[3]);
// Add an XYZ vector to a protobuf message repeated field.
//
// @param field Field name.
// @param vec Vector value to add.
// @error Non-existent field, or incorrect field type.
public native void AddVector(const char[] field, const float vec[3]);
// Add an XY vector to a protobuf message repeated field.
//
// @param field Field name.
// @param vec Vector value to add.
// @error Non-existent field, or incorrect field type.
public native void AddVector2D(const char[] field, const float vec[2]);
// Removes a value by index from a protobuf message repeated field.
//
// @param field Field name.
// @param index Index into repeated field.
// @error Non-existent field, or incorrect field type.
public native void RemoveRepeatedFieldValue(const char[] field, int index);
// Retrieve a handle to an embedded protobuf message in a protobuf message.
//
// @param field Field name.
// @return Protobuf handle to embedded message.
// @error Non-existent field, or incorrect field type.
public native Protobuf ReadMessage(const char[] field);
// Retrieve a handle to an embedded protobuf message in a protobuf message
// repeated field.
//
// @param field Field name.
// @param index Index in the repeated field.
// @return Protobuf handle to embedded message.
// @error Non-existent field, or incorrect field type.
public native Protobuf ReadRepeatedMessage(const char[] field, int index);
// Adds an embedded protobuf message to a protobuf message repeated field.
//
// @param field Field name.
// @return Protobuf handle to added, embedded message.
// @error Non-existent field, or incorrect field type.
public native Protobuf AddMessage(const char[] field);
};
/**
* Reads an int32, uint32, sint32, fixed32, sfixed32, or enum value from a protobuf message.
*
* @param pb protobuf handle.
* @param field Field name.
* @param index Index into repeated field.
* @return Integer value read.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native int PbReadInt(Handle pb, const char[] field, int index = PB_FIELD_NOT_REPEATED);
/**
* Reads a float or downcasted double from a protobuf message.
*
* @param pb protobuf handle.
* @param field Field name.
* @param index Index into repeated field.
* @return Float value read.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native float PbReadFloat(Handle pb, const char[] field, int index = PB_FIELD_NOT_REPEATED);
/**
* Reads a bool from a protobuf message.
*
* @param pb protobuf handle.
* @param field Field name.
* @param index Index into repeated field.
* @return Boolean value read.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native bool PbReadBool(Handle pb, const char[] field, int index = PB_FIELD_NOT_REPEATED);
/**
* Reads a string from a protobuf message.
*
* @param pb protobuf handle.
* @param field Field name.
* @param buffer Destination string buffer.
* @param maxlength Maximum length of output string buffer.
* @param index Index into repeated field.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbReadString(Handle pb, const char[] field, char[] buffer, int maxlength, int index = PB_FIELD_NOT_REPEATED);
/**
* Reads an RGBA color value from a protobuf message.
*
* @param pb protobuf handle.
* @param field Field name.
* @param buffer Destination color buffer.
* @param index Index into repeated field.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbReadColor(Handle pb, const char[] field, int buffer[4], int index = PB_FIELD_NOT_REPEATED);
/**
* Reads an XYZ angle value from a protobuf message.
*
* @param pb protobuf handle.
* @param field Field name.
* @param buffer Destination angle buffer.
* @param index Index into repeated field.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbReadAngle(Handle pb, const char[] field, float buffer[3], int index = PB_FIELD_NOT_REPEATED);
/**
* Reads an XYZ vector value from a protobuf message.
*
* @param pb protobuf handle.
* @param field Field name.
* @param buffer Destination vector buffer.
* @param index Index into repeated field.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbReadVector(Handle pb, const char[] field, float buffer[3], int index = PB_FIELD_NOT_REPEATED);
/**
* Reads an XY vector value from a protobuf message.
*
* @param pb protobuf handle.
* @param field Field name.
* @param buffer Destination vector buffer.
* @param index Index into repeated field.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbReadVector2D(Handle pb, const char[] field, float buffer[2], int index = PB_FIELD_NOT_REPEATED);
/**
* Gets the number of elements in a repeated field of a protobuf message.
*
* @param pb protobuf handle.
* @param field Field name.
* @return Number of elements in the field.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native int PbGetRepeatedFieldCount(Handle pb, const char[] field);
/**
* Sets an int32, uint32, sint32, fixed32, sfixed32, or enum value on a protobuf message.
*
* @param pb protobuf handle.
* @param field Field name.
* @param value Integer value to set.
* @param index Index into repeated field.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbSetInt(Handle pb, const char[] field, int value, int index = PB_FIELD_NOT_REPEATED);
/**
* Sets a float or double on a protobuf message.
*
* @param pb protobuf handle.
* @param field Field name.
* @param value Float value to set.
* @param index Index into repeated field.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbSetFloat(Handle pb, const char[] field, float value, int index = PB_FIELD_NOT_REPEATED);
/**
* Sets a bool on a protobuf message.
*
* @param pb protobuf handle.
* @param field Field name.
* @param value Boolean value to set.
* @param index Index into repeated field.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbSetBool(Handle pb, const char[] field, bool value, int index = PB_FIELD_NOT_REPEATED);
/**
* Sets a string on a protobuf message.
*
* @param pb protobuf handle.
* @param field Field name.
* @param value String value to set.
* @param index Index into repeated field.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbSetString(Handle pb, const char[] field, const char[] value, int index = PB_FIELD_NOT_REPEATED);
/**
* Sets an RGBA color on a protobuf message.
*
* @param pb protobuf handle.
* @param field Field name.
* @param color Color value to set.
* @param index Index into repeated field.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbSetColor(Handle pb, const char[] field, const int color[4], int index = PB_FIELD_NOT_REPEATED);
/**
* Sets an XYZ angle on a protobuf message.
*
* @param pb protobuf handle.
* @param field Field name.
* @param angle Angle value to set.
* @param index Index into repeated field.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbSetAngle(Handle pb, const char[] field, const float angle[3], int index = PB_FIELD_NOT_REPEATED);
/**
* Sets an XYZ vector on a protobuf message.
*
* @param pb protobuf handle.
* @param field Field name.
* @param vec Vector value to set.
* @param index Index into repeated field.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbSetVector(Handle pb, const char[] field, const float vec[3], int index = PB_FIELD_NOT_REPEATED);
/**
* Sets an XY vector on a protobuf message.
*
* @param pb protobuf handle.
* @param field Field name.
* @param vec Vector value to set.
* @param index Index into repeated field.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbSetVector2D(Handle pb, const char[] field, const float vec[2], int index = PB_FIELD_NOT_REPEATED);
/**
* Add an int32, uint32, sint32, fixed32, sfixed32, or enum value to a protobuf message repeated field.
*
* @param pb protobuf handle.
* @param field Field name.
* @param value Integer value to add.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbAddInt(Handle pb, const char[] field, int value);
/**
* Add a float or double to a protobuf message repeated field.
*
* @param pb protobuf handle.
* @param field Field name.
* @param value Float value to add.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbAddFloat(Handle pb, const char[] field, float value);
/**
* Add a bool to a protobuf message repeated field.
*
* @param pb protobuf handle.
* @param field Field name.
* @param value Boolean value to add.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbAddBool(Handle pb, const char[] field, bool value);
/**
* Add a string to a protobuf message repeated field.
*
* @param pb protobuf handle.
* @param field Field name.
* @param value String value to add.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbAddString(Handle pb, const char[] field, const char[] value);
/**
* Add an RGBA color to a protobuf message repeated field.
*
* @param pb protobuf handle.
* @param field Field name.
* @param color Color value to add.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbAddColor(Handle pb, const char[] field, const int color[4]);
/**
* Add an XYZ angle to a protobuf message repeated field.
*
* @param pb protobuf handle.
* @param field Field name.
* @param angle Angle value to add.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbAddAngle(Handle pb, const char[] field, const float angle[3]);
/**
* Add an XYZ vector to a protobuf message repeated field.
*
* @param pb protobuf handle.
* @param field Field name.
* @param vec Vector value to add.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbAddVector(Handle pb, const char[] field, const float vec[3]);
/**
* Add an XY vector to a protobuf message repeated field.
*
* @param pb protobuf handle.
* @param field Field name.
* @param vec Vector value to add.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbAddVector2D(Handle pb, const char[] field, const float vec[2]);
/**
* Removes a value by index from a protobuf message repeated field.
*
* @param pb protobuf handle.
* @param field Field name.
* @param index Index into repeated field.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native void PbRemoveRepeatedFieldValue(Handle pb, const char[] field, int index);
/**
* Retrieve a handle to an embedded protobuf message in a protobuf message.
*
* @param pb protobuf handle.
* @param field Field name.
* @return protobuf handle to embedded message.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native Handle PbReadMessage(Handle pb, const char[] field);
/**
* Retrieve a handle to an embedded protobuf message in a protobuf message repeated field.
*
* @param pb protobuf handle.
* @param field Field name.
* @param index Index in the repeated field.
* @return protobuf handle to embedded message.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native Handle PbReadRepeatedMessage(Handle pb, const char[] field, int index);
/**
* Adds an embedded protobuf message to a protobuf message repeated field.
*
* @param pb protobuf handle.
* @param field Field name.
* @return protobuf handle to added, embedded message.
* @error Invalid or incorrect Handle, non-existent field, or incorrect field type.
*/
native Handle PbAddMessage(Handle pb, const char[] field);

291
scripting/include/regex.inc Normal file
View File

@@ -0,0 +1,291 @@
/**
* vim: set ts=4 sw=4 tw=99 noet :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _regex_included
#endinput
#endif
#define _regex_included
/**
* @section Flags for compiling regex expressions. These come directly from the
* pcre library and can be used in MatchRegex and CompileRegex.
*/
#define PCRE_CASELESS 0x00000001 /* Ignore Case */
#define PCRE_MULTILINE 0x00000002 /* Multilines (affects ^ and $ so that they match the start/end of a line rather than matching the start/end of the string). */
#define PCRE_DOTALL 0x00000004 /* Single line (affects . so that it matches any character, even new line characters). */
#define PCRE_EXTENDED 0x00000008 /* Pattern extension (ignore whitespace and # comments). */
#define PCRE_ANCHORED 0x00000010 /* Force pattern anchoring. */
#define PCRE_DOLLAR_ENDONLY 0x00000020 /* $ not to match newline at end. */
#define PCRE_UNGREEDY 0x00000200 /* Invert greediness of quantifiers */
#define PCRE_NOTEMPTY 0x00000400 /* An empty string is not a valid match. */
#define PCRE_UTF8 0x00000800 /* Use UTF-8 Chars */
#define PCRE_NO_UTF8_CHECK 0x00002000 /* Do not check the pattern for UTF-8 validity (only relevant if PCRE_UTF8 is set) */
#define PCRE_UCP 0x20000000 /* Use Unicode properties for \ed, \ew, etc. */
/**
* Regex expression error codes.
*/
enum RegexError
{
REGEX_ERROR_NONE = 0, /* No error */
REGEX_ERROR_ASSERT = 1, /* internal error ? */
REGEX_ERROR_BADBR, /* invalid repeat counts in {} */
REGEX_ERROR_BADPAT, /* pattern error */
REGEX_ERROR_BADRPT, /* ? * + invalid */
REGEX_ERROR_EBRACE, /* unbalanced {} */
REGEX_ERROR_EBRACK, /* unbalanced [] */
REGEX_ERROR_ECOLLATE, /* collation error - not relevant */
REGEX_ERROR_ECTYPE, /* bad class */
REGEX_ERROR_EESCAPE, /* bad escape sequence */
REGEX_ERROR_EMPTY, /* empty expression */
REGEX_ERROR_EPAREN, /* unbalanced () */
REGEX_ERROR_ERANGE, /* bad range inside [] */
REGEX_ERROR_ESIZE, /* expression too big */
REGEX_ERROR_ESPACE, /* failed to get memory */
REGEX_ERROR_ESUBREG, /* bad back reference */
REGEX_ERROR_INVARG, /* bad argument */
REGEX_ERROR_NOMATCH = -1, /* No match was found */
REGEX_ERROR_NULL = -2,
REGEX_ERROR_BADOPTION = -3,
REGEX_ERROR_BADMAGIC = -4,
REGEX_ERROR_UNKNOWN_OPCODE = -5,
REGEX_ERROR_NOMEMORY = -6,
REGEX_ERROR_NOSUBSTRING = -7,
REGEX_ERROR_MATCHLIMIT = -8,
REGEX_ERROR_CALLOUT = -9, /* Never used by PCRE itself */
REGEX_ERROR_BADUTF8 = -10,
REGEX_ERROR_BADUTF8_OFFSET = -11,
REGEX_ERROR_PARTIAL = -12,
REGEX_ERROR_BADPARTIAL = -13,
REGEX_ERROR_INTERNAL = -14,
REGEX_ERROR_BADCOUNT = -15,
REGEX_ERROR_DFA_UITEM = -16,
REGEX_ERROR_DFA_UCOND = -17,
REGEX_ERROR_DFA_UMLIMIT = -18,
REGEX_ERROR_DFA_WSSIZE = -19,
REGEX_ERROR_DFA_RECURSE = -20,
REGEX_ERROR_RECURSIONLIMIT = -21,
REGEX_ERROR_NULLWSLIMIT = -22, /* No longer actually used */
REGEX_ERROR_BADNEWLINE = -23,
REGEX_ERROR_BADOFFSET = -24,
REGEX_ERROR_SHORTUTF8 = -25,
REGEX_ERROR_RECURSELOOP = -26,
REGEX_ERROR_JIT_STACKLIMIT = -27,
REGEX_ERROR_BADMODE = -28,
REGEX_ERROR_BADENDIANNESS = -29,
REGEX_ERROR_DFA_BADRESTART = -30,
REGEX_ERROR_JIT_BADOPTION = -31,
REGEX_ERROR_BADLENGTH = -32
};
// Regular expression objects are used to match or decompose strings based on
// patterns.
methodmap Regex < Handle
{
// Compile a regular expression.
//
// @param pattern The regular expression pattern.
// @param flags General flags for the regular expression.
// @param error Error message encountered, if applicable.
// @param maxLen Maximum string length of the error buffer.
// @param errcode Regex type error code encountered, if applicable.
public native Regex(const char[] pattern, int flags = 0, char[] error="", int maxLen = 0, RegexError &errcode = REGEX_ERROR_NONE);
// Matches a string against a pre-compiled regular expression pattern.
//
// @param str The string to check.
// @param ret Error code, if applicable.
// @param offset Offset in the string to start searching from. MatchOffset returns the offset of the match.
// @return Number of captures found or -1 on failure.
//
// @note Use the regex handle passed to this function to extract
// matches with GetSubString().
public native int Match(const char[] str, RegexError &ret = REGEX_ERROR_NONE, int offset = 0);
// Gets all matches from a string against a pre-compiled regular expression pattern.
//
// @param str The string to check.
// @param ret Error code, if applicable.
// @return Number of matches found or -1 on failure.
//
// @note Use GetSubString() and loop from 0 -> totalmatches - 1.
public native int MatchAll(const char[] str, RegexError &ret = REGEX_ERROR_NONE);
// Returns a matched substring from a regex handle.
//
// Substring ids start at 0 and end at captures-1, where captures is the
// number returned by Regex.Match or Regex.CaptureCount.
//
// @param str_id The index of the expression to get - starts at 0, and ends at captures - 1.
// @param buffer The buffer to set to the matching substring.
// @param maxlen The maximum string length of the buffer.
// @param match Match to get the captures for - starts at 0, and ends at MatchCount() -1
// @return True if a substring was found, False on fail/error
//
// @note str_id = 0 is the full captured string, anything else is the capture group index.
// if Regex.Match is used match can only be 0
public native bool GetSubString(int str_id, char[] buffer, int maxlen, int match = 0);
// Returns number of matches
//
// When using Match this is always 1 or 0 (unless an error occured)
// @return Total number of matches found.
public native int MatchCount();
// Returns number of captures for a match
//
// @param match Match to get the number of captures for. Match starts at 0, and ends at MatchCount() -1
// @return Number of captures in the match.
//
// @note Use GetSubString() and loop from 1 -> captures -1 for str_id to get all captures
public native int CaptureCount(int match = 0);
// Returns the string offset of a match.
//
// @param match Match to get the offset of. Match starts at 0, and ends at MatchCount() -1
// @return Offset of the match in the string.
public native int MatchOffset(int match = 0);
};
/**
* Precompile a regular expression. Use this if you intend on using the
* same expression multiple times. Pass the regex handle returned here to
* MatchRegex to check for matches.
*
* @param pattern The regular expression pattern.
* @param flags General flags for the regular expression.
* @param error Error message encountered, if applicable.
* @param maxLen Maximum string length of the error buffer.
* @param errcode Regex type error code encountered, if applicable.
* @return Valid regex handle on success, INVALID_HANDLE on failure.
*/
native Regex CompileRegex(const char[] pattern, int flags = 0, char[] error="", int maxLen = 0, RegexError &errcode = REGEX_ERROR_NONE);
/**
* Matches a string against a pre-compiled regular expression pattern.
*
* @param regex Regex Handle from CompileRegex()
* @param str The string to check.
* @param ret Error code, if applicable.
* @param offset Offset in the string to start searching from.
* @return Number of captures found or -1 on failure.
*
* @note Use the regex handle passed to this function to extract
* matches with GetRegexSubString().
*/
native int MatchRegex(Handle regex, const char[] str, RegexError &ret = REGEX_ERROR_NONE, int offset = 0);
/**
* Returns a matched substring from a regex handle.
* Substring ids start at 0 and end at captures-1, where captures is the number returned
* by MatchRegex.
*
* @param regex The regex handle to extract data from.
* @param str_id The index of the expression to get - starts at 0, and ends at captures - 1.
* @param buffer The buffer to set to the matching substring.
* @param maxlen The maximum string length of the buffer.
* @return True if a substring was found, False on fail/error
*
* @note str_id = 0 is the full captured string, anything else is the capture group index.
*
*/
native bool GetRegexSubString(Handle regex, int str_id, char[] buffer, int maxlen);
/**
* Matches a string against a regular expression pattern.
*
* @note If you intend on using the same regular expression pattern
* multiple times, consider using CompileRegex and MatchRegex
* instead of making this function reparse the expression each time.
*
* @param str The string to check.
* @param pattern The regular expression pattern.
* @param flags General flags for the regular expression.
* @param error Error message, if applicable.
* @param maxLen Maximum length of the error buffer.
* @return Number of substrings found or -1 on failure.
*/
stock int SimpleRegexMatch(const char[] str, const char[] pattern, int flags = 0, char[] error="", int maxLen = 0)
{
Regex regex = new Regex(pattern, flags, error, maxLen);
if (!regex)
{
return -1;
}
int substrings = regex.Match(str);
delete regex;
return substrings;
}
/**
* @endsection
*/
/**
* Do not edit below this line!
*/
public Extension __ext_regex =
{
name = "Regex Extension",
file = "regex.ext",
#if defined AUTOLOAD_EXTENSIONS
autoload = 1,
#else
autoload = 0,
#endif
#if defined REQUIRE_EXTENSIONS
required = 1,
#else
required = 0,
#endif
};
#if !defined REQUIRE_EXTENSIONS
public void __ext_regex_SetNTVOptional()
{
MarkNativeAsOptional("CompileRegex");
MarkNativeAsOptional("MatchRegex");
MarkNativeAsOptional("GetRegexSubString");
MarkNativeAsOptional("Regex.Regex");
MarkNativeAsOptional("Regex.Match");
MarkNativeAsOptional("Regex.MatchAll");
MarkNativeAsOptional("Regex.GetSubString");
MarkNativeAsOptional("Regex.MatchCount");
MarkNativeAsOptional("Regex.CaptureCount");
MarkNativeAsOptional("Regex.MatchOffset");
}
#endif

295
scripting/include/rtd2.inc Normal file
View File

@@ -0,0 +1,295 @@
#if defined _rtd2_included
#endinput
#endif
#define _rtd2_included
public SharedPlugin:__pl_rtd2 = {
name = "RollTheDice2",
file = "rtd2.smx",
#if defined REQUIRE_PLUGIN
required = 1,
#else
required = 0,
#endif
};
#if !defined REQUIRE_PLUGIN
public __pl_rtd2_SetNTVOptional(){
MarkNativeAsOptional("RTD2_GetClientPerkId");
MarkNativeAsOptional("RTD2_GetClientPerkTime");
MarkNativeAsOptional("RTD2_ForcePerk");
MarkNativeAsOptional("RTD2_RollPerk");
MarkNativeAsOptional("RTD2_RemovePerk");
MarkNativeAsOptional("RTD2_GetPerkOfString");
MarkNativeAsOptional("RTD2_RegisterPerk");
MarkNativeAsOptional("RTD2_IsRegOpen");
MarkNativeAsOptional("RTD2_SetPerkByToken");
MarkNativeAsOptional("RTD2_SetPerkById");
MarkNativeAsOptional("RTD2_DefaultCorePerk");
MarkNativeAsOptional("RTD2_CanPlayerBeHurt");
}
#endif
/****************************\
- F O R W A R D S -
\****************************/
/**
* Called everytime rtd is activated to determine if the player can use the dice mod.
* Return Plugin_Continue to allow, anything else denies them access.
*
* @note sm_forcertd command and RTD2_ForcePerk native does not call this.
*
* @param client Client index.
*/
forward Action:RTD2_CanRollDice(client);
/**
* Called when a perk (iPerkId) is about to be forced by an admin (client) on a target (iTarget).
* Return Plugin_Continue to allow, anything else denies the force.
*
* @note Called only by sm_forcertd command and RTD2_ForcePerk native.
*
* @param client Client index.
* @param iTarget Target client index.
* @param iPerkId ID of the perk about to be forced.
*/
forward Action:RTD2_CanForcePerk(client, iTarget, iPerkId);
/**
* Called when a perk (iPerkId) is about to be removed by an admin (client) from a target (iTarget).
* Return Plugin_Continue to allow, anything else denies the force.
*
* @note Called only by sm_removertd command and RTD2_RemovePerk native.
*
* @param client Client index.
* @param iTarget Target client index.
* @param iPerkId ID of the perk about to be removed.
*/
forward Action:RTD2_CanRemovePerk(client, iTarget, iPerkId);
/**
* Called when a perk has just been activated on a player.
*
* @param client Client Index.
* @param iPerk Perk Index.
* @param iDuration Perk Duration (-1 if no time).
*/
forward RTD2_Rolled(client, iPerk, iDuration);
/**
* Called when a perk has just been activated on a player.
*
* @param client Client Index.
* @param iPerk Removed Perk's Index.
* @param iReason Reason Index (0=plugin unload, 1=death, 2=class change, 3=wear off, 4=disconnect, 5=custom/unknown).
*/
forward RTD2_Removed(client, iPerk, iReason);
/**************************\
- N A T I V E S -
\**************************/
/**
* Returns player's current perk index. Meant to check if player is using RTD.
*
* @param client Client Index.
*
* @return Perk index if client is using RTD, -1 otherwise.
*/
native RTD2_GetClientPerkId(client);
/**
* Returns time in seconds the player has left to the perk end.
*
* @param client Client Index.
*
* @return Time in seconds if client is using RTD, -1 otherwise.
*/
native RTD2_GetClientPerkTime(client);
/**
* Forces a perk on a player
*
* @param client Client Index.
* @param sPerk Perk string, containing id, token or a tag. If invalid a roll will be used.
* @param iTime Custom perk's time. -1 = don't use.
* @param bOvrClass 0/1 - If perk doesn't match player's class, should it be applied anyway?
* @param initiator Entity which initiated forcing the perk.
*
* @return -5 if RTD2_CanForcePerk forward was blocked,
* -4 if client index is not valid (bots are not valid either),
* -3 if client is using RTD,
* -2 if client is dead,
* -1 if there were no perks available,
* <0 and more> forced perk's index.
*/
native RTD2_ForcePerk(client, String:sPerk[]="-1", iTime=-1, bOvrClass=0, initiator=0);
/**
* Rolls a perk with given data.
*
* @note This does NOT apply the perk to the client.
*
* @param client Client Index.
* @param bOverrideDisabled 0/1 - Roll disabled perks?
* @param bOverrideClass 0/1 - Roll perks NOT for player's class?
* @param bCountRepeat 0/1 - Roll perks which repeated twice in 2 rolls for client? (sm_rtd2_repeat 1 ONLY)
* @param bCountGreatRepeat 0/1 - Roll perks which repeated twice in 3 rolls for client? (sm_rtd2_repeatgreat 1 ONLY)
*
* @return Perk index on success, -1 otherwise
*/
native RTD2_RollPerk(client=0, bOverrideDisabled=0, bOverrideClass=0, bCountRepeat=1, bCountGreatRepeat=1);
/**
* Removes current perk from the client.
*
* @param client Client Index.
* @param iReason Reason Index (0=plugin unload, 1=death, 2=class change, 3=wear off, 4=disconnect, 5=custom/unknown).
* @param sReason Provide custom reason IF iReason=5.
*
* @return Perk index which got removed, -1 if client wasn't using RTD.
*/
native RTD2_RemovePerk(client, iReason=3, const String:sReason[]="");
/**
* Gets the perk's index by either the actual index, perk's token or a single tag
*
* @param sString String to search by.
*
* @return Perk's index on success, -1 otherwise.
*/
native RTD2_GetPerkOfString(const String:sString[]="");
/****************************\
******************************
- E X T E R N A L -
******************************
\****************************/
/*
The following are grouped individually,
because they are meant to be for plugins
which register their own perks to the RTD.
For a full tutorial on how to use those,
see the RTD's thread on AlliedModders:
https://forums.alliedmods.net/showthread.php?t=278579
*/
functag RTD2Manager public(client, iPerkId, bool:bEnable);
/**
* Registers a perk from a different plugin to the core.
* The parameters match the fields in the KV file.
* Perks cannot be unregistered, disable them instead.
* If a token was found in another perk, it will OVERRIDE that perk.
* For in-depth information, see the RTD thread on AlliedModders.
*
* @param sToken Unique token used for addressing the perk.
* @param sName Perk name.
* @param iGood 0 - bad perk; 1 - good perk
* @param sSound Path to the initiation sound file.
* @param iTime -1 -> no timer; 0 -> ConVar default time; 0< -> Custom perk time.
* @param sClass Class string to limit the perk to.
* @param sWeapon Weapon classnames to limit the perk to.
* @param sTags Perk's tags used to find or address the perk.
* @param funcPerk Callback function; public(client, iPerkId, bool:bEnable)
*
* @return Perk's index on success, -1 otherwise (not all paremeters filled).
*/
native RTD2_RegisterPerk(const String:sToken[], const String:sName[], iGood, const String:sSound[], iTime, const String:sClass[], const String:sWeapons[], const String:sTags[], RTD2Manager:funcPerk);
/**
* Registering a perk via external plugin is possible only after all the core ones were registered.
* You can register new perks in OnPluginStart() when this native returns 1 (if late-loaded).
* Otherwise, register them in the RTD2_OnRegOpen() forward.
*
* @return 1 if registering is open, 0 otherwise.
*/
native RTD2_IsRegOpen();
/**
* This forward will fire when RTD is ready handle perk registration.
* RTD2_RegisterPerk() should ALWAYS be executed in this forward.
*/
forward RTD2_OnRegOpen();
/**
* Enables/disables perk by token.
*
* @params sToken The token to find the perk by.
* @params iDir (direction) -1 = disable, 0 = toggle, 1 = enable
*
* @return ID of the perk, -1 if not found.
*/
native RTD2_SetPerkByToken(const String:sToken[], iDir=0);
/**
* Enables/disables perk by ID.
*
* @params iId Perk's ID.
* @params iDir (direction) -1 = disable, 0 = toggle, 1 = enable
*
* @return 1 if anything changed, 0 if was already in the requested state, -1 on error.
*/
native RTD2_SetPerkById(iId, iDir=0);
/**
* If RTD2_RegisterPerk() was used to override functionality of a core perk,
* this native can be used to set it back to the default one.
* It will accept either the perk's ID or its token (id > token).
* You should use it only on core perks.
*
* @params iId Perk's ID.
* @params sToken Perk's token.
*
* @return 1 if anything was changed, 0 nothing was changed, -1 on error.
*/
native RTD2_DefaultCorePerk(iId=-1, const String:sToken[]="");
/**
* A miscellaneous native which returns whether the client can be hurt.
* Optionally, hurt by whom.
* It is adived to use this as it checks if the client is in Friendly Mode.
*
* @params client Can this client be hurt...
* @params by ...by this client?
*
* @return 1 if yes, 0 if not or error.
*/
native RTD2_CanPlayerBeHurt(client, by=0);

100
scripting/include/scp.inc Normal file
View File

@@ -0,0 +1,100 @@
/************************************************************************
*************************************************************************
Simple Plugins
Description:
Included file for Simple Chat Processor in the Simple Plugins project
*************************************************************************
*************************************************************************
This file is part of Simple Plugins project.
This plugin is free software: you can redistribute
it and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation, either version 3 of the License, or
later version.
This plugin 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 plugin. If not, see <http://www.gnu.org/licenses/>.
*************************************************************************
*************************************************************************
File Information
$Id: scp.inc 175 2011-09-07 00:42:17Z antithasys $
$Author: antithasys $
$Revision: 175 $
$Date: 2011-09-06 19:42:17 -0500 (Tue, 06 Sep 2011) $
$LastChangedBy: antithasys $
$LastChangedDate: 2011-09-06 19:42:17 -0500 (Tue, 06 Sep 2011) $
$URL: https://sm-simple-plugins.googlecode.com/svn/trunk/Simple%20Chat%20Processor/addons/sourcemod/scripting/include/scp.inc $
$Copyright: (c) Simple Plugins 2008-2009$
*************************************************************************
*************************************************************************/
#if defined _scp_included
#endinput
#endif
#define _scp_included
#define MAXLENGTH_INPUT 128 // Inclues \0 and is the size of the chat input box.
#define MAXLENGTH_NAME 64 // This is backwords math to get compability. Sourcemod has it set at 32, but there is room for more.
#define MAXLENGTH_MESSAGE 256 // This is based upon the SDK and the length of the entire message, including tags, name, : etc.
#define CHATFLAGS_INVALID 0
#define CHATFLAGS_ALL (1<<0)
#define CHATFLAGS_TEAM (1<<1)
#define CHATFLAGS_SPEC (1<<2)
#define CHATFLAGS_DEAD (1<<3)
/**********************************************************************
* When a player types a chat message
*
* NOTES:
* Use MAXLENGTH_ constants above for formating the strings
* Do not rely on the recipients handle to exist beyond the forward
* Do not start another usermessage (PrintToChat) within this forward
*
* @param author The client index of the player who sent the chat message (Byref)
* @param recipients The handle to the client index adt array of the players who should recieve the chat message
* @param name The client's name of the player who sent the chat message (Byref)
* @param message The contents of the chat message (Byref)
* @noreturn
**********************************************************************/
forward Action:OnChatMessage(&author, Handle:recipients, String:name[], String:message[]);
/**********************************************************************
* Gets the current flags for the chat message
* Should only be called within OnChatMessage()
*
* @return The current type of chat message (see constants)
**********************************************************************/
native GetMessageFlags();
/**
Shared plugin information
**/
public SharedPlugin:_pl_scp =
{
name = "scp",
file = "simple-chatprocessor.smx",
#if defined REQUIRE_PLUGIN
required = 1
#else
required = 0
#endif
};
#if !defined REQUIRE_PLUGIN
public _pl_scp_SetNTVOptional()
{
MarkNativeAsOptional("GetMessageFlags");
}
#endif

Binary file not shown.

View File

@@ -0,0 +1,461 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2009-2013 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*/
#if defined _sdkhooks_included
#endinput
#endif
#define _sdkhooks_included
// this is obviously _not_ a robust check, but it will solve most conflict and is clean
#if !defined DMG_GENERIC
#define DMG_GENERIC 0 /**< generic damage was done */
#define DMG_CRUSH (1 << 0) /**< crushed by falling or moving object.
NOTE: It's assumed crush damage is occurring as a result of physics collision,
so no extra physics force is generated by crush damage.
DON'T use DMG_CRUSH when damaging entities unless it's the result of a physics
collision. You probably want DMG_CLUB instead. */
#define DMG_BULLET (1 << 1) /**< shot */
#define DMG_SLASH (1 << 2) /**< cut, clawed, stabbed */
#define DMG_BURN (1 << 3) /**< heat burned */
#define DMG_VEHICLE (1 << 4) /**< hit by a vehicle */
#define DMG_FALL (1 << 5) /**< fell too far */
#define DMG_BLAST (1 << 6) /**< explosive blast damage */
#define DMG_CLUB (1 << 7) /**< crowbar, punch, headbutt */
#define DMG_SHOCK (1 << 8) /**< electric shock */
#define DMG_SONIC (1 << 9) /**< sound pulse shockwave */
#define DMG_ENERGYBEAM (1 << 10) /**< laser or other high energy beam */
#define DMG_PREVENT_PHYSICS_FORCE (1 << 11) /**< Prevent a physics force */
#define DMG_NEVERGIB (1 << 12) /**< with this bit OR'd in, no damage type will be able to gib victims upon death */
#define DMG_ALWAYSGIB (1 << 13) /**< with this bit OR'd in, any damage type can be made to gib victims upon death. */
#define DMG_DROWN (1 << 14) /**< Drowning */
#define DMG_PARALYZE (1 << 15) /**< slows affected creature down */
#define DMG_NERVEGAS (1 << 16) /**< nerve toxins, very bad */
#define DMG_POISON (1 << 17) /**< blood poisoning - heals over time like drowning damage */
#define DMG_RADIATION (1 << 18) /**< radiation exposure */
#define DMG_DROWNRECOVER (1 << 19) /**< drowning recovery */
#define DMG_ACID (1 << 20) /**< toxic chemicals or acid burns */
#define DMG_SLOWBURN (1 << 21) /**< in an oven */
#define DMG_REMOVENORAGDOLL (1 << 22) /**< with this bit OR'd in, no ragdoll will be created, and the target will be quietly removed.
use this to kill an entity that you've already got a server-side ragdoll for */
#define DMG_PHYSGUN (1 << 23) /**< Hit by manipulator. Usually doesn't do any damage. */
#define DMG_PLASMA (1 << 24) /**< Shot by Cremator */
#define DMG_AIRBOAT (1 << 25) /**< Hit by the airboat's gun */
#define DMG_DISSOLVE (1 << 26) /**< Dissolving! */
#define DMG_BLAST_SURFACE (1 << 27) /**< A blast on the surface of water that cannot harm things underwater */
#define DMG_DIRECT (1 << 28)
#define DMG_BUCKSHOT (1 << 29) /**< not quite a bullet. Little, rounder, different. */
#endif
#if !defined DMG_CRIT
#define DMG_CRIT DMG_ACID /**< TF2 crits and minicrits */
#endif
#if !defined DMG_RADIUS_MAX
#define DMG_RADIUS_MAX DMG_ENERGYBEAM /**< No damage falloff */
#endif
#if !defined DMG_NOCLOSEDISTANCEMOD
#define DMG_NOCLOSEDISTANCEMOD DMG_POISON /**< Don't do damage falloff too close */
#endif
#if !defined DMG_HALF_FALLOFF
#define DMG_HALF_FALLOFF DMG_RADIATION /**< 50% damage falloff */
#endif
#if !defined DMG_USEDISTANCEMOD
#define DMG_USEDISTANCEMOD DMG_SLOWBURN /**< Do damage falloff */
#endif
#if !defined DMG_IGNITE
#define DMG_IGNITE DMG_PLASMA /**< Ignite victim */
#endif
#if !defined DMG_USE_HITLOCATIONS
#define DMG_USE_HITLOCATIONS DMG_AIRBOAT /**< Do hit location damage (Like the sniperrifle and ambassador) */
#endif
enum SDKHookType
{
SDKHook_EndTouch,
SDKHook_FireBulletsPost,
SDKHook_OnTakeDamage,
SDKHook_OnTakeDamagePost,
SDKHook_PreThink,
SDKHook_PostThink,
SDKHook_SetTransmit,
SDKHook_Spawn,
SDKHook_StartTouch,
SDKHook_Think,
SDKHook_Touch,
SDKHook_TraceAttack,
SDKHook_TraceAttackPost,
SDKHook_WeaponCanSwitchTo,
SDKHook_WeaponCanUse,
SDKHook_WeaponDrop,
SDKHook_WeaponEquip,
SDKHook_WeaponSwitch,
SDKHook_ShouldCollide,
SDKHook_PreThinkPost,
SDKHook_PostThinkPost,
SDKHook_ThinkPost,
SDKHook_EndTouchPost,
SDKHook_GroundEntChangedPost,
SDKHook_SpawnPost,
SDKHook_StartTouchPost,
SDKHook_TouchPost,
SDKHook_VPhysicsUpdate,
SDKHook_VPhysicsUpdatePost,
SDKHook_WeaponCanSwitchToPost,
SDKHook_WeaponCanUsePost,
SDKHook_WeaponDropPost,
SDKHook_WeaponEquipPost,
SDKHook_WeaponSwitchPost,
SDKHook_Use,
SDKHook_UsePost,
SDKHook_Reload,
SDKHook_ReloadPost,
SDKHook_GetMaxHealth, /**< ep2v and later */
SDKHook_Blocked,
SDKHook_BlockedPost,
SDKHook_OnTakeDamageAlive,
SDKHook_OnTakeDamageAlivePost,
SDKHook_CanBeAutobalanced
};
/*
Alphabetized for easy readability
SDKHook_Blocked,
SDKHook_BlockedPost,
SDKHook_CanBeAutobalanced,
SDKHook_EndTouch,
SDKHook_EndTouchPost,
SDKHook_FireBulletsPost,
SDKHook_GetMaxHealth, (ep2v and later)
SDKHook_GroundEntChangedPost,
SDKHook_OnTakeDamage,
SDKHook_OnTakeDamagePost,
SDKHook_OnTakeDamageAlive,
SDKHook_OnTakeDamageAlivePost,
SDKHook_PreThink,
SDKHook_PreThinkPost,
SDKHook_PostThink,
SDKHook_PostThinkPost,
SDKHook_Reload,
SDKHook_ReloadPost,
SDKHook_SetTransmit,
SDKHook_ShouldCollide,
SDKHook_Spawn,
SDKHook_SpawnPost,
SDKHook_StartTouch,
SDKHook_StartTouchPost,
SDKHook_Think,
SDKHook_ThinkPost,
SDKHook_Touch,
SDKHook_TouchPost,
SDKHook_TraceAttack,
SDKHook_TraceAttackPost,
SDKHook_Use,
SDKHook_UsePost,
SDKHook_VPhysicsUpdate,
SDKHook_VPhysicsUpdatePost,
SDKHook_WeaponCanSwitchTo,
SDKHook_WeaponCanSwitchToPost,
SDKHook_WeaponCanUse,
SDKHook_WeaponCanUsePost,
SDKHook_WeaponDrop,
SDKHook_WeaponDropPost,
SDKHook_WeaponEquip,
SDKHook_WeaponEquipPost,
SDKHook_WeaponSwitch,
SDKHook_WeaponSwitchPost
*/
enum UseType
{
Use_Off,
Use_On,
Use_Set,
Use_Toggle
};
typeset SDKHookCB
{
// PreThink/Post
// PostThink/Post
function void (int client);
// Spawn
// Think
function Action (int entity);
// GroundEntChanged
// SpawnPost
// ThinkPost
// VPhysicsUpdate/Post
function void (int entity);
// EndTouch
// StartTouch
// Touch
// Blocked
function Action (int entity, int other);
// EndTouchPost
// StartTouchPost
// TouchPost
function void (int entity, int other);
// SetTransmit
function Action (int entity, int client);
// WeaponCanSwitchTo
// WeaponCanUse
// WeaponDrop
// WeaponEquip
// WeaponSwitch
function Action (int client, int weapon);
// WeaponCanSwitchToPost
// WeaponCanUsePost
// WeaponDropPost
// WeaponEquipPost
// WeaponSwitchPost
function void (int client, int weapon);
// GetMaxHealth (ep2v and later)
function Action (int entity, int &maxhealth);
// OnTakeDamage
// OnTakeDamageAlive
// SDKHooks 1.0+
function Action (int victim, int &attacker, int &inflictor, float &damage, int &damagetype);
// OnTakeDamage
// OnTakeDamageAlive
// Note: The weapon parameter is not used by all games and damage sources.
// Note: Force application is dependent on game and damage type(s)
// SDKHooks 2.0+
function Action (int victim, int &attacker, int &inflictor, float &damage, int &damagetype, int &weapon, float damageForce[3], float damagePosition[3]);
// OnTakeDamage
// OnTakeDamageAlive
// Note: The weapon parameter is not used by all games and damage sources.
// Note: Force application is dependent on game and damage type(s)
// SDKHooks 2.1+ (can check for support at runtime using GetFeatureStatus on SDKHook_DmgCustomInOTD capability.
// DON'T attempt to access 'damagecustom' var if feature status != available
function Action (int victim, int &attacker, int &inflictor, float &damage, int &damagetype, int &weapon,
float damageForce[3], float damagePosition[3], int damagecustom);
// OnTakeDamagePost
// OnTakeDamageAlivePost
function void (int victim, int attacker, int inflictor, float damage, int damagetype);
// OnTakeDamagePost
// OnTakeDamageAlivePost
function void (int victim, int attacker, int inflictor, float damage, int damagetype, int weapon, const float damageForce[3], const float damagePosition[3]);
// OnTakeDamagePost
// OnTakeDamageAlivePost
function void (int victim, int attacker, int inflictor, float damage, int damagetype, int weapon,
const float damageForce[3], const float damagePosition[3], int damagecustom);
// FireBulletsPost
function void (int client, int shots, const char[] weaponname);
// TraceAttack
function Action (int victim, int &attacker, int &inflictor, float &damage, int &damagetype, int &ammotype, int hitbox, int hitgroup);
// TraceAttackPost
function void (int victim, int attacker, int inflictor, float damage, int damagetype, int ammotype, int hitbox, int hitgroup);
// ShouldCollide
function bool (int entity, int collisiongroup, int contentsmask, bool originalResult);
// Use
function Action (int entity, int activator, int caller, UseType type, float value);
// UsePost
function void (int entity, int activator, int caller, UseType type, float value);
// Reload
function Action (int weapon);
// Reload post
function void (int weapon, bool bSuccessful);
// CanBeAutobalanced
function bool (int client, bool origRet);
};
/**
* When an entity is created
*
* @param entity Entity index
* @param classname Class name
*/
forward void OnEntityCreated(int entity, const char[] classname);
/**
* When an entity is destroyed
*
* @param entity Entity index or edict reference.
*/
forward void OnEntityDestroyed(int entity);
/**
* When the game description is retrieved
*
* @note Not supported on ep2v.
*
* @param gameDesc Game description
* @return Plugin_Changed if gameDesc has been edited, else no change.
*/
forward Action OnGetGameDescription(char gameDesc[64]);
/**
* When the level is initialized
*
* @param mapName Name of the map
* @param mapEntities Unused, always empty
* @return Unused, return value is ignored
*/
#pragma deprecated Use OnMapInit() instead
forward Action OnLevelInit(const char[] mapName, char mapEntities[2097152]);
/**
* Hooks an entity
*
* Unhooked automatically upon destruction/removal of the entity
*
* @param entity Entity index
* @param type Type of function to hook
* @param callback Function to call when hook is called
*/
native void SDKHook(int entity, SDKHookType type, SDKHookCB callback);
/**
* Hooks an entity
*
* Unhooked automatically upon destruction/removal of the entity
*
* @param entity Entity index
* @param type Type of function to hook
* @param callback Function to call when hook is called
* @return Hook Successful
*/
native bool SDKHookEx(int entity, SDKHookType type, SDKHookCB callback);
/**
* Unhooks an entity
*
* @param entity Entity index
* @param type Type of function to unhook
* @param callback Callback function to unhook
*/
native void SDKUnhook(int entity, SDKHookType type, SDKHookCB callback);
/**
* Applies damage to an entity
*
* @note Force application is dependent on game and damage type(s)
*
* @param entity Entity index taking damage
* @param inflictor Inflictor entity index
* @param attacker Attacker entity index
* @param damage Amount of damage
* @param damageType Bitfield of damage types
* @param weapon Weapon index (orangebox and later) or -1 for unspecified
* @param damageForce Velocity of damage force
* @param damagePosition Origin of damage
* @param bypassHooks If true, bypass SDK hooks on OnTakeDamage
* @error Invalid entity, attacker, inflictor, or weapon entity.
*/
native void SDKHooks_TakeDamage(int entity, int inflictor, int attacker,
float damage, int damageType=DMG_GENERIC, int weapon=-1,
const float damageForce[3]=NULL_VECTOR, const float damagePosition[3]=NULL_VECTOR,
bool bypassHooks = true);
/**
* Forces a client to drop the specified weapon
*
* @param client Client index.
* @param weapon Weapon entity index.
* @param vecTarget Location to toss weapon to, or NULL_VECTOR for default.
* @param vecVelocity Velocity at which to toss weapon, or NULL_VECTOR for default.
* @param bypassHooks If true, bypass SDK hooks on Weapon Drop
* @error Invalid client or weapon entity, weapon not owned by client.
*/
native void SDKHooks_DropWeapon(int client, int weapon, const float vecTarget[3]=NULL_VECTOR,
const float vecVelocity[3]=NULL_VECTOR, bool bypassHooks = true);
/**
* Do not edit below this line!
*/
public Extension __ext_sdkhooks =
{
name = "SDKHooks",
file = "sdkhooks.ext",
#if defined AUTOLOAD_EXTENSIONS
autoload = 1,
#else
autoload = 0,
#endif
#if defined REQUIRE_EXTENSIONS
required = 1,
#else
required = 0,
#endif
};

View File

@@ -0,0 +1,234 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2017 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _sdktools_included
#endinput
#endif
#define _sdktools_included
#include <core>
#include <sdktools_engine>
#include <sdktools_functions>
#if !defined SDKTOOLS_DISABLE_SOUNDAPI
#include <sdktools_sound>
#endif
#include <sdktools_stringtables>
#include <sdktools_trace>
#include <sdktools_tempents>
#include <sdktools_tempents_stocks>
#include <sdktools_voice>
#include <sdktools_variant_t>
#include <sdktools_entinput>
#include <sdktools_entoutput>
#include <sdktools_hooks>
#include <sdktools_gamerules>
#include <sdktools_client>
enum SDKCallType
{
SDKCall_Static, /**< Static call */
SDKCall_Entity, /**< CBaseEntity call */
SDKCall_Player, /**< CBasePlayer call */
SDKCall_GameRules, /**< CGameRules call */
SDKCall_EntityList, /**< CGlobalEntityList call */
SDKCall_Raw, /**< |this| pointer with an arbitrary address */
SDKCall_Server, /**< CBaseServer call */
SDKCall_Engine /**< CVEngineServer call */
};
enum SDKLibrary
{
SDKLibrary_Server, /**< server.dll/server_i486.so */
SDKLibrary_Engine /**< engine.dll/engine_*.so */
};
enum SDKFuncConfSource
{
SDKConf_Virtual = 0, /**< Read a virtual index from the Offsets section */
SDKConf_Signature = 1, /**< Read a signature from the Signatures section */
SDKConf_Address = 2 /**< Read an address from the Addresses section */
};
enum SDKType
{
SDKType_CBaseEntity, /**< CBaseEntity (always as pointer) */
SDKType_CBasePlayer, /**< CBasePlayer (always as pointer) */
SDKType_Vector, /**< Vector (pointer, byval, or byref) */
SDKType_QAngle, /**< QAngles (pointer, byval, or byref) */
SDKType_PlainOldData, /**< Integer/generic data <=32bit (any) */
SDKType_Float, /**< Float (any) */
SDKType_Edict, /**< edict_t (always as pointer) */
SDKType_String, /**< NULL-terminated string (always as pointer) */
SDKType_Bool /**< Boolean (any) */
};
enum SDKPassMethod
{
SDKPass_Pointer, /**< Pass as a pointer */
SDKPass_Plain, /**< Pass as plain data */
SDKPass_ByValue, /**< Pass an object by value */
SDKPass_ByRef /**< Pass an object by reference */
};
#define VDECODE_FLAG_ALLOWNULL (1<<0) /**< Allow NULL for pointers */
#define VDECODE_FLAG_ALLOWNOTINGAME (1<<1) /**< Allow players not in game */
#define VDECODE_FLAG_ALLOWWORLD (1<<2) /**< Allow World entity */
#define VDECODE_FLAG_BYREF (1<<3) /**< Floats/ints by reference */
#define VENCODE_FLAG_COPYBACK (1<<0) /**< Copy back data once done */
/**
* Starts the preparation of an SDK call.
*
* @param type Type of function call this will be.
*/
native void StartPrepSDKCall(SDKCallType type);
/**
* Sets the virtual index of the SDK call if it is virtual.
*
* @param vtblidx Virtual table index.
*/
native void PrepSDKCall_SetVirtual(int vtblidx);
/**
* Finds an address in a library and sets it as the address to use for the SDK call.
*
* @param lib Library to use.
* @param signature Binary data to search for in the library. If it starts with '@',
* the bytes parameter is ignored and the signature is interpreted
* as a symbol lookup in the library.
* @param bytes Number of bytes in the binary search string.
* @return True on success, false if nothing was found.
*/
native bool PrepSDKCall_SetSignature(SDKLibrary lib, const char[] signature, int bytes);
/**
* Uses the given function address for the SDK call.
*
* @param addr Address of function to use.
* @return True on success, false on failure.
*/
native bool PrepSDKCall_SetAddress(Address addr);
/**
* Finds an address or virtual function index in a GameConfig file and sets it as
* the calling information for the SDK call.
*
* @param gameconf GameConfig Handle, or INVALID_HANDLE to use sdktools.games.txt.
* @param source Whether to look in Offsets or Signatures.
* @param name Name of the property to find.
* @return True on success, false if nothing was found.
* @error Invalid game config Handle.
*/
native bool PrepSDKCall_SetFromConf(Handle gameconf, SDKFuncConfSource source, const char[] name);
/**
* Sets the return information of an SDK call. Do not call this if there is no return data.
* This must be called if there is a return value (i.e. it is not necessarily safe to ignore
* the data).
*
* @param type Data type to convert to/from.
* @param pass How the data is passed in C++.
* @param decflags Flags on decoding from the plugin to C++.
* @param encflags Flags on encoding from C++ to the plugin.
*/
native void PrepSDKCall_SetReturnInfo(SDKType type, SDKPassMethod pass, int decflags=0, int encflags=0);
/**
* Adds a parameter to the calling convention. This should be called in normal ascending order.
*
* @param type Data type to convert to/from.
* @param pass How the data is passed in C++.
* @param decflags Flags on decoding from the plugin to C++.
* @param encflags Flags on encoding from C++ to the plugin.
* @error Parameter limit for SDK calls reached.
*/
native void PrepSDKCall_AddParameter(SDKType type, SDKPassMethod pass, int decflags=0, int encflags=0);
/**
* Finalizes an SDK call preparation and returns the resultant Handle.
*
* @return A new SDKCall Handle on success, or INVALID_HANDLE on failure.
*/
native Handle EndPrepSDKCall();
/**
* Calls an SDK function with the given parameters.
*
* If the call type is Entity or Player, the index MUST ALWAYS be the FIRST parameter passed.
* If the call type is GameRules, then nothing special needs to be passed.
* If the return value is a Vector or QAngles, the SECOND parameter must be a Float[3].
* If the return value is a string, the THIRD parameter must be a String buffer, and the
* FOURTH parameter must be the maximum length.
* All parameters must be passed after the above is followed. Failure to follow these
* rules will result in crashes or wildly unexpected behavior!
*
* If the return value is a float or integer, the return value will be this value.
* If the return value is a string, the value returned by the function will be the number of bytes written, or -1 for NULL.
* If the return value is a CBaseEntity, CBasePlayer, or edict, the return value will
* always be the entity index, or -1 for NULL.
*
* @param call SDKCall Handle.
* @param ... Call Parameters.
* @return Simple return value, if any.
* @error Invalid Handle or internal decoding error.
*/
native any SDKCall(Handle call, any ...);
/**
* Returns the entity index of the player resource/manager entity.
*
* @return Index of resource entity or -1 if not found.
*/
native int GetPlayerResourceEntity();
#include <sdktools_stocks>
/**
* Do not edit below this line!
*/
public Extension __ext_sdktools =
{
name = "SDKTools",
file = "sdktools.ext",
#if defined AUTOLOAD_EXTENSIONS
autoload = 1,
#else
autoload = 0,
#endif
#if defined REQUIRE_EXTENSIONS
required = 1,
#else
required = 0,
#endif
};

View File

@@ -0,0 +1,52 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _sdktools_client_included
#endinput
#endif
#define _sdktools_client_included
/**
* Sets the client to an inactive state waiting for a new map
*
* @param client The client index
* @error Invalid client index.
*/
native void InactivateClient(int client);
/**
* Reconnect a client without dropping the netchannel
*
* @param client The client index
* @error Invalid client index.
*/
native void ReconnectClient(int client);

View File

@@ -0,0 +1,66 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _sdktools_engine_included
#endinput
#endif
#define _sdktools_engine_included
#define MAX_LIGHTSTYLES 64
/**
* Sets a client's "viewing entity."
*
* @param client Client index.
* @param entity Entity index.
* @error Invalid client or entity, lack of mod support, or client not in
* game.
*/
native void SetClientViewEntity(int client, int entity);
/**
* Sets a light style.
*
* @param style Light style (from 0 to MAX_LIGHTSTYLES-1)
* @param value Light value string (see world.cpp/light.cpp in dlls)
* @error Light style index is out of range.
*/
native void SetLightStyle(int style, const char[] value);
/**
* Returns the client's eye position.
*
* @param client Player's index.
* @param pos Destination vector to store the client's eye position.
* @error Invalid client index, client not in game, or no mod support.
*/
native void GetClientEyePosition(int client, float pos[3]);

View File

@@ -0,0 +1,51 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2017 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _sdktools_entinput_included
#endinput
#endif
#define _sdktools_entinput_included
/**
* Invokes a named input method on an entity.
*
* After completion (successful or not), the current global variant is re-initialized.
*
* @param dest Destination entity index.
* @param input Input action.
* @param activator Entity index which initiated the sequence of actions (-1 for a NULL entity).
* @param caller Entity index from which this event is sent (-1 for a NULL entity).
* @param outputid Unknown.
* @return True if successful otherwise false.
* @error Invalid entity index or no mod support.
*/
native bool AcceptEntityInput(int dest, const char[] input, int activator=-1, int caller=-1, int outputid=0);

View File

@@ -0,0 +1,108 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2017 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _sdktools_entoutput_included
#endinput
#endif
#define _sdktools_entoutput_included
/**
* Called when an entity output is fired.
*
* @param output Name of the output that fired.
* @param caller Entity index of the caller.
* @param activator Entity index of the activator.
* @param delay Delay in seconds? before the event gets fired.
* @return Anything other than Plugin_Continue will supress this event,
* returning Plugin_Continue will allow it to propagate the results
* of this output to any entity inputs.
*/
typeset EntityOutput
{
function void (const char[] output, int caller, int activator, float delay);
function Action (const char[] output, int caller, int activator, float delay);
};
/**
* Add an entity output hook on a entity classname
*
* @param classname The classname to hook.
* @param output The output name to hook.
* @param callback An EntityOutput function pointer.
* @error Entity Outputs disabled.
*/
native void HookEntityOutput(const char[] classname, const char[] output, EntityOutput callback);
/**
* Remove an entity output hook.
* @param classname The classname to hook.
* @param output The output name to hook.
* @param callback An EntityOutput function pointer.
* @return True on success, false if no valid hook was found.
* @error Entity Outputs disabled.
*/
native bool UnhookEntityOutput(const char[] classname, const char[] output, EntityOutput callback);
/**
* Add an entity output hook on a single entity instance
*
* @param entity The entity on which to add a hook.
* @param output The output name to hook.
* @param callback An EntityOutput function pointer.
* @param once Only fire this hook once and then remove itself.
* @error Entity Outputs disabled or Invalid Entity index.
*/
native void HookSingleEntityOutput(int entity, const char[] output, EntityOutput callback, bool once=false);
/**
* Remove a single entity output hook.
*
* @param entity The entity on which to remove the hook.
* @param output The output name to hook.
* @param callback An EntityOutput function pointer.
* @return True on success, false if no valid hook was found.
* @error Entity Outputs disabled or Invalid Entity index.
*/
native bool UnhookSingleEntityOutput(int entity, const char[] output, EntityOutput callback);
/**
* Fire a named output on an entity.
*
* After completion (successful or not), the current global variant is re-initialized.
*
* @param caller Entity index from where the output is fired.
* @param output Output name.
* @param activator Entity index which initiated the sequence of actions (-1 for a NULL entity).
* @param delay Delay before firing the output.
* @error Invalid entity index or no mod support.
*/
native void FireEntityOutput(int caller, const char[] output, int activator=-1, float delay=0.0);

View File

@@ -0,0 +1,419 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _sdktools_functions_included
#endinput
#endif
#define _sdktools_functions_included
/**
* Removes a player's item.
*
* @param client Client index.
* @param item CBaseCombatWeapon entity index.
* @return True on success, false otherwise.
* @error Invalid client or entity, lack of mod support, or client not in
* game.
*/
native bool RemovePlayerItem(int client, int item);
/**
* Gives a named item to a player.
*
* @param client Client index.
* @param item Item classname (such as weapon_ak47).
* @param iSubType Unknown.
* @return Entity index on success, or -1 on failure.
* @error Invalid client or client not in game, or lack of mod support.
*/
native int GivePlayerItem(int client, const char[] item, int iSubType=0);
/**
* Returns the weapon in a player's slot.
*
* @param client Client index.
* @param slot Slot index (mod specific).
* @return Entity index on success, -1 if no weapon existed.
* @error Invalid client or client not in game, or lack of mod support.
*/
native int GetPlayerWeaponSlot(int client, int slot);
/**
* Ignites an entity on fire.
*
* @param entity Entity index.
* @param time Number of seconds to set on fire.
* @param npc True to only affect NPCs.
* @param size Unknown.
* @param level Unknown.
* @error Invalid entity or client not in game, or lack of mod support.
*/
native void IgniteEntity(int entity, float time, bool npc=false, float size=0.0, bool level=false);
/**
* Extinguishes an entity that is on fire.
*
* @param entity Entity index.
* @error Invalid entity or client not in game, or lack of mod support.
*/
native void ExtinguishEntity(int entity);
/**
* Teleports an entity.
*
* @param entity Client index.
* @param origin New origin, or NULL_VECTOR for no change.
* @param angles New angles, or NULL_VECTOR for no change.
* @param velocity New velocity, or NULL_VECTOR for no change.
* @error Invalid entity or client not in game, or lack of mod support.
*/
native void TeleportEntity(int entity, const float origin[3] = NULL_VECTOR, const float angles[3] = NULL_VECTOR, const float velocity[3] = NULL_VECTOR);
/**
* Forces a player to commit suicide.
*
* @param client Client index.
* @param explode If true, explode the player.
* @error Invalid client or client not in game, or lack of mod support.
*/
native void ForcePlayerSuicide(int client, bool explode = false);
/**
* Slaps a player in a random direction.
*
* @param client Client index.
* @param health Health to subtract.
* @param sound False to disable the sound effects.
* @error Invalid client or client not in game, or lack of mod support.
*/
native void SlapPlayer(int client, int health=5, bool sound=true);
/**
* Searches for an entity by classname.
*
* @param startEnt A valid entity's index after which to begin searching from.
* Use -1 to start from the first entity.
* @param classname Classname of the entity to find.
* @return Entity index >= 0 if found, -1 otherwise.
* @error Invalid start entity or lack of mod support.
*/
native int FindEntityByClassname(int startEnt, const char[] classname);
/**
* Returns the client's eye angles.
*
* @param client Player's index.
* @param ang Destination vector to store the client's eye angles.
* @return True on success, false on failure.
* @error Invalid client index, client not in game, or lack of mod support.
*/
native bool GetClientEyeAngles(int client, float ang[3]);
/**
* Creates an entity by string name, but does not spawn it (see DispatchSpawn).
* If ForceEdictIndex is not -1, then it will use the edict by that index. If the index is
* invalid or there is already an edict using that index, it will error out.
*
* @param classname Entity classname.
* @param ForceEdictIndex Edict index used by the created entity (ignored on Orangebox and above).
* @return Entity index on success, or -1 on failure.
* @error Invalid edict index, no map is running, or lack of mod support.
*/
native int CreateEntityByName(const char[] classname, int ForceEdictIndex=-1);
/**
* Spawns an entity into the game.
*
* @param entity Entity index of the created entity.
* @return True on success, false otherwise.
* @error Invalid entity index or lack of mod support.
*/
native bool DispatchSpawn(int entity);
/**
* Dispatches a KeyValue into given entity using a string value.
*
* @param entity Destination entity index.
* @param keyName Name of the key.
* @param value String value.
* @return True on success, false otherwise.
* @error Invalid entity index or lack of mod support.
*/
native bool DispatchKeyValue(int entity, const char[] keyName, const char[] value);
/**
* Dispatches a KeyValue into given entity using an integer value.
*
* @param entity Destination entity index.
* @param keyName Name of the key.
* @param value Integer value.
* @return True on success, false otherwise.
* @error Invalid entity index or lack of mod support.
*/
stock bool DispatchKeyValueInt(int entity, const char[] keyName, int value)
{
char str[12];
FormatEx(str, sizeof(str), "%d", value);
return DispatchKeyValue(entity, keyName, str);
}
/**
* Dispatches a KeyValue into given entity using a floating point value.
*
* @param entity Destination entity index.
* @param keyName Name of the key.
* @param value Floating point value.
* @return True on success, false otherwise.
* @error Invalid entity index or lack of mod support.
*/
native bool DispatchKeyValueFloat(int entity, const char[] keyName, float value);
/**
* Dispatches a KeyValue into given entity using a vector value.
*
* @param entity Destination entity index.
* @param keyName Name of the key.
* @param vec Vector value.
* @return True on success, false otherwise.
* @error Invalid entity index or lack of mod support.
*/
native bool DispatchKeyValueVector(int entity, const char[] keyName, const float vec[3]);
/**
* Returns the entity a client is aiming at.
*
* @param client Client performing the aiming.
* @param only_clients True to exclude all entities but clients.
* @return Entity index being aimed at.
* -1 if no entity is being aimed at.
* -2 if the function is not supported.
* @error Invalid client index or client not in game.
*/
native int GetClientAimTarget(int client, bool only_clients=true);
/**
* Returns the total number of teams in a game.
* Note: This native should not be called before OnMapStart.
*
* @return Total number of teams.
*/
native int GetTeamCount();
/**
* Retrieves the team name based on a team index.
* Note: This native should not be called before OnMapStart.
*
* @param index Team index.
* @param name Buffer to store string in.
* @param maxlength Maximum length of string buffer.
* @error Invalid team index.
*/
native void GetTeamName(int index, char[] name, int maxlength);
/**
* Returns the score of a team based on a team index.
* Note: This native should not be called before OnMapStart.
*
* @param index Team index.
* @return Score.
* @error Invalid team index.
*/
native int GetTeamScore(int index);
/**
* Sets the score of a team based on a team index.
* Note: This native should not be called before OnMapStart.
*
* @param index Team index.
* @param value New score value.
* @error Invalid team index.
*/
native void SetTeamScore(int index, int value);
/**
* Retrieves the number of players in a certain team.
* Note: This native should not be called before OnMapStart.
*
* @param index Team index.
* @return Number of players in the team.
* @error Invalid team index.
*/
native int GetTeamClientCount(int index);
/**
* Returns the entity index of a team.
*
* @param teamIndex Team index.
* @return Entity index of team.
* @error Invalid team index.
*/
native int GetTeamEntity(int teamIndex);
/**
* Sets the model to a given entity.
*
* @param entity Entity index.
* @param model Model name.
* @error Invalid entity index or lack of mod support.
*/
native void SetEntityModel(int entity, const char[] model);
/**
* Retrieves the decal file name associated with a given client.
*
* @param client Player's index.
* @param hex Buffer to store the logo filename.
* @param maxlength Maximum length of string buffer.
* @return True on success, otherwise false.
* @error Invalid client or client not in game.
*/
native bool GetPlayerDecalFile(int client, char[] hex, int maxlength);
/**
* Retrieves the jingle file name associated with a given client.
*
* @param client Player's index.
* @param hex Buffer to store the jingle filename.
* @param maxlength Maximum length of string buffer.
* @return True on success, otherwise false.
* @error Invalid client or client not in game.
*/
native bool GetPlayerJingleFile(int client, char[] hex, int maxlength);
/**
* Returns the average server network traffic in bytes/sec.
*
* @param in Buffer to store the input traffic velocity.
* @param out Buffer to store the output traffic velocity.
* @error Lack of mod support.
*/
native void GetServerNetStats(float &inAmount, float &outAmout);
/**
* Equip's a player's weapon.
*
* @param client Client index.
* @param weapon CBaseCombatWeapon entity index.
* @error Invalid client or entity, lack of mod support, or client not in
* game.
*/
native void EquipPlayerWeapon(int client, int weapon);
/**
* Activates an entity (CBaseAnimating::Activate)
*
* @param entity Entity index.
* @error Invalid entity or lack of mod support.
*/
native void ActivateEntity(int entity);
/**
* Sets values to client info buffer keys and notifies the engine of the change.
* The change does not get propagated to mods until the next frame.
*
* @param client Player's index.
* @param key Key string.
* @param value Value string.
* @error Invalid client index, client not connected, or lack of mod support.
*/
native void SetClientInfo(int client, const char[] key, const char[] value);
/**
* Changes a client's name.
*
* @param client Player's index.
* @param name New name.
* @error Invalid client index, client not connected, or lack of mod support.
*/
native void SetClientName(int client, const char[] name);
/**
* Gives ammo of a certain type to a player.
* This natives obeys the maximum amount of ammo a player can carry per ammo type.
*
* @param client The client index.
* @param amount Amount of ammo to give. Is capped at ammotype's limit.
* @param ammotype Type of ammo to give to player.
* @param suppressSound If true, don't play the ammo pickup sound.
* @return Amount of ammo actually given.
* @error Lack of mod support.
*/
native int GivePlayerAmmo(int client, int amount, int ammotype, bool suppressSound=false);
/**
* Changes an entity's collision group (CBaseEntity::SetCollisionGroup).
*
* @param entity The entity index.
* @param collisionGroup Collision group to use.
* @error Invalid entity or lack of mod support.
*/
native void SetEntityCollisionGroup(int entity, int collisionGroup);
/**
* Recaculates entity collision rules (CBaseEntity::CollisionRulesChanged).
*
* @param entity The entity index.
* @error Invalid entity or lack of mod support.
*/
native void EntityCollisionRulesChanged(int entity);
/**
* Sets an entity's owner (CBaseEntity::SetEntityOwner).
*
* @param entity The entity index.
* @param owner The owner entity index, can be invalid.
* @error Invalid entity or lack of mod support.
*/
native void SetEntityOwner(int entity, int owner=INVALID_ENT_REFERENCE);
/**
* Returns the index number of a given named attachment.
*
* @param entity The entity index.
* @param name The attachment name.
* @return An attachment index, or 0 if the attachment name is invalid or unused.
* @error Invalid entity or lack of mod support.
*/
native int LookupEntityAttachment(int entity, const char[] name);
/**
* Returns the world location and world angles of an attachment.
*
* @param entity The entity index.
* @param attachment The attachment index.
* @param origin Destination vector to store the attachment's origin vector.
* @param angles Destination vector to store the attachment's position angle.
* @return True on success, otherwise false.
* @error Invalid entity or lack of mod support.
*/
native bool GetEntityAttachment(int entity, int attachment, float origin[3], float angles[3]);

View File

@@ -0,0 +1,199 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2011 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _sdktools_gamerules_included
#endinput
#endif
#define _sdktools_gamerules_included
enum RoundState {
// initialize the game, create teams
RoundState_Init,
//Before players have joined the game. Periodically checks to see if enough players are ready
//to start a game. Also reverts to this when there are no active players
RoundState_Pregame,
//The game is about to start, wait a bit and spawn everyone
RoundState_StartGame,
//All players are respawned, frozen in place
RoundState_Preround,
//Round is on, playing normally
RoundState_RoundRunning,
//Someone has won the round
RoundState_TeamWin,
//Noone has won, manually restart the game, reset scores
RoundState_Restart,
//Noone has won, restart the game
RoundState_Stalemate,
//Game is over, showing the scoreboard etc
RoundState_GameOver,
//Game is over, doing bonus round stuff
RoundState_Bonus,
//Between rounds
RoundState_BetweenRounds
};
/**
* Retrieves an integer value from a property of the gamerules entity.
*
* @param prop Property name.
* @param size Number of bytes to read (valid values are 1, 2, or 4).
* This value is auto-detected, and the size parameter is
* only used as a fallback in case detection fails.
* @param element Element # (starting from 0) if property is an array.
* @return Value at the given property offset.
* @error Prop type is not an integer, or lack of mod support.
*/
native int GameRules_GetProp(const char[] prop, int size=4, int element=0);
/**
* Sets an integer value for a property of the gamerules entity.
*
* @param prop Property name.
* @param value Value to set.
* @param size Number of bytes to write (valid values are 1, 2, or 4).
* This value is auto-detected, and the size parameter is
* only used as a fallback in case detection fails.
* @param element Element # (starting from 0) if property is an array.
* @param changeState This parameter is ignored.
* @error Prop type is not an integer, or lack of mod support.
*/
native void GameRules_SetProp(const char[] prop, any value, int size=4, int element=0, bool changeState=false);
/**
* Retrieves a float value from a property of the gamerules entity.
*
* @param prop Property name.
* @param element Element # (starting from 0) if property is an array.
* @return Value at the given property offset.
* @error Prop type is not a float, or lack of mod support.
*/
native float GameRules_GetPropFloat(const char[] prop, int element=0);
/**
* Sets a float value for a property of the gamerules entity.
*
* @param prop Property name.
* @param value Value to set.
* @param element Element # (starting from 0) if property is an array.
* @param changeState This parameter is ignored.
* @error Prop type is not a float, or lack of mod support.
*/
native void GameRules_SetPropFloat(const char[] prop, float value, int element=0, bool changeState=false);
/**
* Retrieves a entity index from a property of the gamerules entity.
*
* @param prop Property name.
* @param element Element # (starting from 0) if property is an array.
* @return Entity index at the given property.
* If there is no entity, or the entity is not valid,
* then -1 is returned.
* @error Prop type is not an entity, or lack of mod support.
*/
native int GameRules_GetPropEnt(const char[] prop, int element=0);
/**
* Sets an entity index for a property of the gamerules entity.
*
* @param prop Property name.
* @param other Entity index to set, or -1 to unset.
* @param element Element # (starting from 0) if property is an array.
* @param changeState This parameter is ignored.
* @error Prop type is not an entity, invalid entity, or lack of mod support.
*/
native void GameRules_SetPropEnt(const char[] prop, int other, int element=0, bool changeState=false);
/**
* Retrieves a vector of floats from the gamerules entity, given a named network property.
*
* @param prop Property name.
* @param vec Vector buffer to store data in.
* @param element Element # (starting from 0) if property is an array.
* @error Prop type is not a vector, or lack of mod support.
*/
native void GameRules_GetPropVector(const char[] prop, float vec[3], int element=0);
/**
* Sets a vector of floats in the gamerules entity, given a named network property.
*
* @param prop Property name.
* @param vec Vector to set.
* @param element Element # (starting from 0) if property is an array.
* @param changeState This parameter is ignored.
* @error Prop type is not a vector, or lack of mod support.
*/
native void GameRules_SetPropVector(const char[] prop, const float vec[3], int element=0, bool changeState=false);
/**
* Gets a gamerules property as a string.
*
* @param prop Property to use.
* @param buffer Destination string buffer.
* @param maxlen Maximum length of output string buffer.
* @param element Element # (starting from 0) if property is an array.
* @return Number of non-null bytes written.
* @error Prop type is not a string, or lack of mod support.
*/
native int GameRules_GetPropString(const char[] prop, char[] buffer, int maxlen, int element=0);
/**
* Sets a gamerules property as a string.
*
* @param prop Property to use.
* @param buffer String to set.
* @param changeState This parameter is ignored.
* @param element Element # (starting from 0) if property is an array.
* @return Number of non-null bytes written.
* @error Prop type is not a string, or lack of mod support.
*/
native int GameRules_SetPropString(const char[] prop, const char[] buffer, bool changeState=false, int element=0);
/**
* Gets the current round state.
*
* @return Round state.
* @error Game doesn't support round state.
*/
stock RoundState GameRules_GetRoundState()
{
return view_as<RoundState>(GameRules_GetProp("m_iRoundState"));
}

View File

@@ -0,0 +1,112 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2009 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _sdktools_hooks_included
#endinput
#endif
#define _sdktools_hooks_included
#define FEATURECAP_PLAYERRUNCMD_11PARAMS "SDKTools PlayerRunCmd 11Params"
/**
* Called when a clients movement buttons are being processed (Read Only)
*
* @param client Index of the client.
* @param buttons Current commands (as bitflags - see entity_prop_stocks.inc).
* @param impulse Current impulse command.
* @param vel Players desired velocity.
* @param angles Players desired view angles.
* @param weapon Entity index of the new weapon if player switches weapon, 0 otherwise.
* @param subtype Weapon subtype when selected from a menu.
* @param cmdnum Command number. Increments from the first command sent.
* @param tickcount Tick count. A client's prediction based on the server's GetGameTickCount value.
* @param seed Random seed. Used to determine weapon recoil, spread, and other predicted elements.
* @param mouse Mouse direction (x, y).
*/
forward void OnPlayerRunCmdPre(int client, int buttons, int impulse, const float vel[3], const float angles[3], int weapon, int subtype, int cmdnum, int tickcount, int seed, const int mouse[2]);
/**
* Called when a clients movement buttons are being processed
*
* @param client Index of the client.
* @param buttons Copyback buffer containing the current commands (as bitflags - see entity_prop_stocks.inc).
* @param impulse Copyback buffer containing the current impulse command.
* @param vel Players desired velocity.
* @param angles Players desired view angles.
* @param weapon Entity index of the new weapon if player switches weapon, 0 otherwise.
* @param subtype Weapon subtype when selected from a menu.
* @param cmdnum Command number. Increments from the first command sent.
* @param tickcount Tick count. A client's prediction based on the server's GetGameTickCount value.
* @param seed Random seed. Used to determine weapon recoil, spread, and other predicted elements.
* @param mouse Mouse direction (x, y).
* @return Plugin_Handled to block the commands from being processed, Plugin_Continue otherwise.
*
* @note To see if all 11 params are available, use FeatureType_Capability and FEATURECAP_PLAYERRUNCMD_11PARAMS.
*/
forward Action OnPlayerRunCmd(int client, int &buttons, int &impulse, float vel[3], float angles[3], int &weapon, int &subtype, int &cmdnum, int &tickcount, int &seed, int mouse[2]);
/**
* Called after a clients movement buttons were processed.
*
* @param client Index of the client.
* @param buttons The current commands (as bitflags - see entity_prop_stocks.inc).
* @param impulse The current impulse command.
* @param vel Players desired velocity.
* @param angles Players desired view angles.
* @param weapon Entity index of the new weapon if player switches weapon, 0 otherwise.
* @param subtype Weapon subtype when selected from a menu.
* @param cmdnum Command number. Increments from the first command sent.
* @param tickcount Tick count. A client's prediction based on the server's GetGameTickCount value.
* @param seed Random seed. Used to determine weapon recoil, spread, and other predicted elements.
* @param mouse Mouse direction (x, y).
*/
forward void OnPlayerRunCmdPost(int client, int buttons, int impulse, const float vel[3], const float angles[3], int weapon, int subtype, int cmdnum, int tickcount, int seed, const int mouse[2]);
/**
* Called when a client requests a file from the server.
*
* @param client Client index.
* @param sFile Requested file path.
*
* @return Plugin_Handled to block the transfer, Plugin_Continue to let it proceed.
*/
forward Action OnFileSend(int client, const char[] sFile);
/**
* Called when a client sends a file to the server.
*
* @param client Client index.
* @param sFile Requested file path.
*
* @return Plugin_Handled to block the transfer, Plugin_Continue to let it proceed.
*/
forward Action OnFileReceive(int client, const char[] sFile);

View File

@@ -0,0 +1,722 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _sdktools_sound_included
#endinput
#endif
#define _sdktools_sound_included
/**
* Sound should be from the target client.
*/
#define SOUND_FROM_PLAYER -2
/**
* Sound should be from the listen server player.
*/
#define SOUND_FROM_LOCAL_PLAYER -1
/**
* Sound is from the world.
*/
#define SOUND_FROM_WORLD 0
/**
* Sound channels.
*/
enum
{
SNDCHAN_REPLACE = -1, /**< Unknown */
SNDCHAN_AUTO = 0, /**< Auto */
SNDCHAN_WEAPON = 1, /**< Weapons */
SNDCHAN_VOICE = 2, /**< Voices */
SNDCHAN_ITEM = 3, /**< Items */
SNDCHAN_BODY = 4, /**< Player? */
SNDCHAN_STREAM = 5, /**< "Stream channel from the static or dynamic area" */
SNDCHAN_STATIC = 6, /**< "Stream channel from the static area" */
SNDCHAN_VOICE_BASE = 7, /**< "Channel for network voice data" */
SNDCHAN_USER_BASE = 135 /**< Anything >= this is allocated to game code */
};
/**
* Sound flags for the sound emitter system.
*/
enum
{
SND_NOFLAGS = 0, /** Nothing */
SND_CHANGEVOL = (1 << 0), /** Change sound volume */
SND_CHANGEPITCH = (1 << 1), /** Change sound pitch */
SND_STOP = (1 << 2), /** Stop the sound */
SND_SPAWNING = (1 << 3), /** Used in some cases for ambients */
SND_DELAY = (1 << 4), /** Sound has an initial delay */
SND_STOPLOOPING = (1 << 5), /** Stop looping all sounds on the entity */
SND_SPEAKER = (1 << 6), /** Being played by a mic through a speaker */
SND_SHOULDPAUSE = (1 << 7), /** Pause if game is paused */
SND_IGNORE_PHONEMES = (1 << 8), /** Prevents flex animation from being driven by this sound */
SND_IGNORE_NAME = (1 << 9), /** Changes all sounds emitted on the entity, regardless of actual name */
SND_DO_NOT_OVERWRITE_EXISTING_ON_CHANNEL = (1 << 10) /** If an existing sound is found on the channel, the sound will not play instead of overwriting it */
};
/**
* Various predefined sound levels in dB.
*/
enum
{
SNDLEVEL_NONE = 0, /**< None */
SNDLEVEL_RUSTLE = 20, /**< Rustling leaves */
SNDLEVEL_WHISPER = 25, /**< Whispering */
SNDLEVEL_LIBRARY = 30, /**< In a library */
SNDLEVEL_FRIDGE = 45, /**< Refrigerator */
SNDLEVEL_HOME = 50, /**< Average home (3.9 attn) */
SNDLEVEL_CONVO = 60, /**< Normal conversation (2.0 attn) */
SNDLEVEL_DRYER = 60, /**< Clothes dryer */
SNDLEVEL_DISHWASHER = 65, /**< Dishwasher/washing machine (1.5 attn) */
SNDLEVEL_CAR = 70, /**< Car or vacuum cleaner (1.0 attn) */
SNDLEVEL_NORMAL = 75, /**< Normal sound level */
SNDLEVEL_TRAFFIC = 75, /**< Busy traffic (0.8 attn) */
SNDLEVEL_MINIBIKE = 80, /**< Mini-bike, alarm clock (0.7 attn) */
SNDLEVEL_SCREAMING = 90, /**< Screaming child (0.5 attn) */
SNDLEVEL_TRAIN = 100, /**< Subway train, pneumatic drill (0.4 attn) */
SNDLEVEL_HELICOPTER = 105, /**< Helicopter */
SNDLEVEL_SNOWMOBILE = 110, /**< Snow mobile */
SNDLEVEL_AIRCRAFT = 120, /**< Auto horn, aircraft */
SNDLEVEL_RAIDSIREN = 130, /**< Air raid siren */
SNDLEVEL_GUNFIRE = 140, /**< Gunshot, jet engine (0.27 attn) */
SNDLEVEL_ROCKET = 180 /**< Rocket launching (0.2 attn) */
};
#define SNDVOL_NORMAL 1.0 /**< Normal volume */
#define SNDPITCH_NORMAL 100 /**< Normal pitch */
#define SNDPITCH_LOW 95 /**< A low pitch */
#define SNDPITCH_HIGH 120 /**< A high pitch */
#define SNDATTN_NONE 0.0 /**< No attenuation */
#define SNDATTN_NORMAL 0.8 /**< Normal attenuation */
#define SNDATTN_STATIC 1.25 /**< Static attenuation? */
#define SNDATTN_RICOCHET 1.5 /**< Ricochet effect */
#define SNDATTN_IDLE 2.0 /**< Idle attenuation? */
/**
* Prefetches a sound.
*
* @param name Sound file name relative to the "sound" folder.
*/
native void PrefetchSound(const char[] name);
/**
* This function is not known to work, and may crash. You should
* not use it. It is provided for backwards compatibility only.
*
* @param name Sound file name relative to the "sound" folder.
* @return Duration in seconds.
* @deprecated Does not work, may crash.
*/
#pragma deprecated Does not work, may crash.
native float GetSoundDuration(const char[] name);
/**
* Emits an ambient sound.
*
* @param name Sound file name relative to the "sound" folder.
* @param pos Origin of sound.
* @param entity Entity index to associate sound with.
* @param level Sound level (from 0 to 255).
* @param flags Sound flags.
* @param vol Volume (from 0.0 to 1.0).
* @param pitch Pitch (from 0 to 255).
* @param delay Play delay.
*/
native void EmitAmbientSound(const char[] name,
const float pos[3],
int entity = SOUND_FROM_WORLD,
int level = SNDLEVEL_NORMAL,
int flags = SND_NOFLAGS,
float vol = SNDVOL_NORMAL,
int pitch = SNDPITCH_NORMAL,
float delay = 0.0);
/**
* Fades a client's volume level toward silence or a given percentage.
*
* @param client Client index.
* @param percent Fade percentage.
* @param outtime Fade out time, in seconds.
* @param holdtime Hold time, in seconds.
* @param intime Fade in time, in seconds.
* @error Invalid client index or client not in game.
*/
native void FadeClientVolume(int client, float percent, float outtime, float holdtime, float intime);
/**
* Stops a sound.
*
* @param entity Entity index.
* @param channel Channel number.
* @param name Sound file name relative to the "sound" folder.
*/
native void StopSound(int entity, int channel, const char[] name);
/**
* Emits a sound to a list of clients.
*
* @param clients Array of client indexes.
* @param numClients Number of clients in the array.
* @param sample Sound file name relative to the "sound" folder.
* @param entity Entity to emit from.
* @param channel Channel to emit with.
* @param level Sound level.
* @param flags Sound flags.
* @param volume Sound volume.
* @param pitch Sound pitch.
* @param speakerentity Unknown.
* @param origin Sound origin.
* @param dir Sound direction.
* @param updatePos Unknown (updates positions?)
* @param soundtime Alternate time to play sound for.
* @param ... Optional list of Float[3] arrays to specify additional origins.
* @error Invalid client index or client not in game.
*/
native void EmitSound(const int[] clients,
int numClients,
const char[] sample,
int entity = SOUND_FROM_PLAYER,
int channel = SNDCHAN_AUTO,
int level = SNDLEVEL_NORMAL,
int flags = SND_NOFLAGS,
float volume = SNDVOL_NORMAL,
int pitch = SNDPITCH_NORMAL,
int speakerentity = -1,
const float origin[3] = NULL_VECTOR,
const float dir[3] = NULL_VECTOR,
bool updatePos = true,
float soundtime = 0.0,
any ...);
/**
* Emits a sound or game sound to a list of clients using the latest version of the engine sound interface.
* This native is only available in engines that are greater than or equal to Portal 2.
*
* @param clients Array of client indexes.
* @param numClients Number of clients in the array.
* @param soundEntry Sound entry name.
* @param sample Sound file name relative to the "sound" folder.
* @param entity Entity to emit from.
* @param channel Channel to emit with.
* @param level Sound level.
* @param seed Sound seed.
* @param flags Sound flags.
* @param volume Sound volume.
* @param pitch Sound pitch.
* @param speakerentity Unknown.
* @param origin Sound origin.
* @param dir Sound direction.
* @param updatePos Unknown (updates positions?)
* @param soundtime Alternate time to play sound for.
* @param ... Optional list of Float[3] arrays to specify additional origins.
* @error Invalid client index, client not in game, or lack of mod support.
*/
native void EmitSoundEntry(const int[] clients,
int numClients,
const char[] soundEntry,
const char[] sample,
int entity = SOUND_FROM_PLAYER,
int channel = SNDCHAN_AUTO,
int level = SNDLEVEL_NORMAL,
int seed = 0,
int flags = SND_NOFLAGS,
float volume = SNDVOL_NORMAL,
int pitch = SNDPITCH_NORMAL,
int speakerentity = -1,
const float origin[3] = NULL_VECTOR,
const float dir[3] = NULL_VECTOR,
bool updatePos = true,
float soundtime = 0.0,
any ...);
/**
* Emits a sentence to a list of clients.
*
* @param clients Array of client indexes.
* @param numClients Number of clients in the array.
* @param sentence Sentence index (from PrecacheSentenceFile).
* @param entity Entity to emit from.
* @param channel Channel to emit with.
* @param level Sound level.
* @param flags Sound flags.
* @param volume Sound volume.
* @param pitch Sound pitch.
* @param speakerentity Unknown.
* @param origin Sound origin.
* @param dir Sound direction.
* @param updatePos Unknown (updates positions?)
* @param soundtime Alternate time to play sound for.
* @param ... Optional list of Float[3] arrays to specify additional origins.
* @error Invalid client index or client not in game.
*/
native void EmitSentence(const int[] clients,
int numClients,
int sentence,
int entity,
int channel = SNDCHAN_AUTO,
int level = SNDLEVEL_NORMAL,
int flags = SND_NOFLAGS,
float volume = SNDVOL_NORMAL,
int pitch = SNDPITCH_NORMAL,
int speakerentity = -1,
const float origin[3] = NULL_VECTOR,
const float dir[3] = NULL_VECTOR,
bool updatePos = true,
float soundtime = 0.0,
any ...);
/**
* Calculates gain of sound on given distance with given sound level in decibel
*
* @param soundlevel decibel of sound, like SNDLEVEL_NORMAL or integer value
* @param distance distance of sound to calculate, not meter or feet, but Source Engine`s normal Coordinate unit
* @return gain of sound. you can multiply this with original sound`s volume to calculate volume on given distance
*/
native float GetDistGainFromSoundLevel(int soundlevel, float distance);
/**
* Called when an ambient sound is about to be emitted to one or more clients.
*
* NOTICE: all parameters can be overwritten to modify the default behavior.
*
* @param sample Sound file name relative to the "sound" folder.
* @param entity Entity index associated to the sound.
* @param volume Volume (from 0.0 to 1.0).
* @param level Sound level (from 0 to 255).
* @param pitch Pitch (from 0 to 255).
* @param pos Origin of sound.
* @param flags Sound flags.
* @param delay Play delay.
* @return Plugin_Continue to allow the sound to be played, Plugin_Stop to block it,
* Plugin_Changed when any parameter has been modified.
*/
typedef AmbientSHook = function Action (
char sample[PLATFORM_MAX_PATH],
int &entity,
float &volume,
int &level,
int &pitch,
float pos[3],
int &flags,
float &delay
);
typeset NormalSHook
{
// Called when a sound is going to be emitted to one or more clients.
// NOTICE: all params can be overwritten to modify the default behavior.
//
// @param clients Array of client indexes.
// @param numClients Number of clients in the array (modify this value if you add/remove elements from the client array).
// @param sample Sound file name relative to the "sound" folder.
// @param entity Entity emitting the sound.
// @param channel Channel emitting the sound.
// @param volume Sound volume.
// @param level Sound level.
// @param pitch Sound pitch.
// @param flags Sound flags.
// @param soundEntry Game sound entry name. (Used in engines newer than Portal 2)
// @param seed Sound seed. (Used in engines newer than Portal 2)
// @return Plugin_Continue to allow the sound to be played, Plugin_Stop to block it,
// Plugin_Changed when any parameter has been modified.
function Action (int clients[MAXPLAYERS], int &numClients, char sample[PLATFORM_MAX_PATH],
int &entity, int &channel, float &volume, int &level, int &pitch, int &flags,
char soundEntry[PLATFORM_MAX_PATH], int &seed);
// Deprecated. Use other prototype.
function Action (int clients[64], int &numClients, char sample[PLATFORM_MAX_PATH],
int &entity, int &channel, float &volume, int &level, int &pitch, int &flags,
char soundEntry[PLATFORM_MAX_PATH], int &seed);
// Deprecated. Use other prototype.
function Action (int clients[64], int &numClients, char sample[PLATFORM_MAX_PATH],
int &entity, int &channel, float &volume, int &level, int &pitch, int &flags);
};
/**
* Hooks all played ambient sounds.
*
* @param hook Function to use as a hook.
* @error Invalid function hook.
*/
native void AddAmbientSoundHook(AmbientSHook hook);
/**
* Hooks all played normal sounds.
*
* @param hook Function to use as a hook.
* @error Invalid function hook.
*/
native void AddNormalSoundHook(NormalSHook hook);
/**
* Unhooks all played ambient sounds.
*
* @param hook Function used for the hook.
* @error Invalid function hook.
*/
native void RemoveAmbientSoundHook(AmbientSHook hook);
/**
* Unhooks all played normal sounds.
*
* @param hook Function used for the hook.
* @error Invalid function hook.
*/
native void RemoveNormalSoundHook(NormalSHook hook);
/**
* Wrapper to emit sound to one client.
*
* @param client Client index.
* @param sample Sound file name relative to the "sound" folder.
* @param entity Entity to emit from.
* @param channel Channel to emit with.
* @param level Sound level.
* @param flags Sound flags.
* @param volume Sound volume.
* @param pitch Sound pitch.
* @param speakerentity Unknown.
* @param origin Sound origin.
* @param dir Sound direction.
* @param updatePos Unknown (updates positions?)
* @param soundtime Alternate time to play sound for.
* @error Invalid client index or client not in game.
*/
stock void EmitSoundToClient(int client,
const char[] sample,
int entity = SOUND_FROM_PLAYER,
int channel = SNDCHAN_AUTO,
int level = SNDLEVEL_NORMAL,
int flags = SND_NOFLAGS,
float volume = SNDVOL_NORMAL,
int pitch = SNDPITCH_NORMAL,
int speakerentity = -1,
const float origin[3] = NULL_VECTOR,
const float dir[3] = NULL_VECTOR,
bool updatePos = true,
float soundtime = 0.0)
{
int clients[1];
clients[0] = client;
/* Save some work for SDKTools and remove SOUND_FROM_PLAYER references */
entity = (entity == SOUND_FROM_PLAYER) ? client : entity;
EmitSound(clients, 1, sample, entity, channel,
level, flags, volume, pitch, speakerentity,
origin, dir, updatePos, soundtime);
}
/**
* Wrapper to emit sound to all clients.
*
* @param sample Sound file name relative to the "sound" folder.
* @param entity Entity to emit from.
* @param channel Channel to emit with.
* @param level Sound level.
* @param flags Sound flags.
* @param volume Sound volume.
* @param pitch Sound pitch.
* @param speakerentity Unknown.
* @param origin Sound origin.
* @param dir Sound direction.
* @param updatePos Unknown (updates positions?)
* @param soundtime Alternate time to play sound for.
* @error Invalid client index.
*/
stock void EmitSoundToAll(const char[] sample,
int entity = SOUND_FROM_PLAYER,
int channel = SNDCHAN_AUTO,
int level = SNDLEVEL_NORMAL,
int flags = SND_NOFLAGS,
float volume = SNDVOL_NORMAL,
int pitch = SNDPITCH_NORMAL,
int speakerentity = -1,
const float origin[3] = NULL_VECTOR,
const float dir[3] = NULL_VECTOR,
bool updatePos = true,
float soundtime = 0.0)
{
int[] clients = new int[MaxClients];
int total = 0;
for (int i=1; i<=MaxClients; i++)
{
if (IsClientInGame(i))
{
clients[total++] = i;
}
}
if (total)
{
EmitSound(clients, total, sample, entity, channel,
level, flags, volume, pitch, speakerentity,
origin, dir, updatePos, soundtime);
}
}
/**
* Converts an attenuation value to a sound level.
* This function is from the HL2SDK.
*
* @param attn Attenuation value.
* @return Integer sound level.
*/
stock int ATTN_TO_SNDLEVEL(float attn)
{
if (attn > 0.0)
{
return RoundFloat(50.0 + (20.0 / attn));
}
return 0;
}
/**
* Retrieves the parameters for a game sound.
*
* Game sounds are found in a game's scripts/game_sound.txt or other files
* referenced from it
*
* Note that if a game sound has a rndwave section, one of them will be returned
* at random.
*
* @param gameSound Name of game sound.
* @param channel Channel to emit with.
* @param level Sound level.
* @param volume Sound volume.
* @param pitch Sound pitch.
* @param sample Sound file name relative to the "sound" folder.
* @param maxlength Maximum length of sample string buffer.
* @param entity Entity the sound is being emitted from.
* @return True if the sound was successfully retrieved, false if it
* was not found
*/
native bool GetGameSoundParams(const char[] gameSound,
int &channel,
int &soundLevel,
float &volume,
int &pitch,
char[] sample,
int maxlength,
int entity=SOUND_FROM_PLAYER);
/**
* Emits a game sound to a list of clients.
*
* Game sounds are found in a game's scripts/game_sound.txt or other files
* referenced from it
*
* Note that if a game sound has a rndwave section, one of them will be returned
* at random.
*
* @param clients Array of client indexes.
* @param numClients Number of clients in the array.
* @param gameSound Name of game sound.
* @param entity Entity to emit from.
* @param flags Sound flags.
* @param speakerentity Unknown.
* @param origin Sound origin.
* @param dir Sound direction.
* @param updatePos Unknown (updates positions?)
* @param soundtime Alternate time to play sound for.
* @return True if the sound was played successfully, false if it failed
* @error Invalid client index or client not in game.
*/
stock bool EmitGameSound(const int[] clients,
int numClients,
const char[] gameSound,
int entity = SOUND_FROM_PLAYER,
int flags = SND_NOFLAGS,
int speakerentity = -1,
const float origin[3] = NULL_VECTOR,
const float dir[3] = NULL_VECTOR,
bool updatePos = true,
float soundtime = 0.0)
{
int channel;
int level;
float volume;
int pitch;
char sample[PLATFORM_MAX_PATH];
if (GetGameSoundParams(gameSound, channel, level, volume, pitch, sample, sizeof(sample), entity))
{
EmitSound(clients, numClients, sample, entity, channel, level, flags, volume, pitch, speakerentity, origin, dir, updatePos, soundtime);
return true;
}
return false;
}
/**
* Emits an ambient game sound.
*
* Game sounds are found in a game's scripts/game_sound.txt or other files
* referenced from it
*
* Note that if a game sound has a rndwave section, one of them will be returned
* at random.
*
* @param gameSound Name of game sound.
* @param pos Origin of sound.
* @param entity Entity index to associate sound with.
* @param flags Sound flags.
* @param delay Play delay.
*/
stock bool EmitAmbientGameSound(const char[] gameSound,
const float pos[3],
int entity = SOUND_FROM_WORLD,
int flags = SND_NOFLAGS,
float delay = 0.0)
{
int channel; // This is never actually used for Ambients, but it's a mandatory field to GetGameSoundParams
int level;
float volume;
int pitch;
char sample[PLATFORM_MAX_PATH];
if (GetGameSoundParams(gameSound, channel, level, volume, pitch, sample, sizeof(sample), entity))
{
EmitAmbientSound(sample, pos, entity, level, flags, volume, pitch, delay);
return true;
}
return false;
}
/**
* Wrapper to emit a game sound to one client.
*
* Game sounds are found in a game's scripts/game_sound.txt or other files
* referenced from it
*
* Note that if a game sound has a rndwave section, one of them will be returned
* at random.
*
* @param client Client index.
* @param gameSound Name of game sound.
* @param entity Entity to emit from.
* @param flags Sound flags.
* @param speakerentity Unknown.
* @param origin Sound origin.
* @param dir Sound direction.
* @param updatePos Unknown (updates positions?)
* @param soundtime Alternate time to play sound for.
* @error Invalid client index or client not in game.
*/
stock bool EmitGameSoundToClient(int client,
const char[] gameSound,
int entity = SOUND_FROM_PLAYER,
int flags = SND_NOFLAGS,
int speakerentity = -1,
const float origin[3] = NULL_VECTOR,
const float dir[3] = NULL_VECTOR,
bool updatePos = true,
float soundtime = 0.0)
{
int clients[1];
clients[0] = client;
/* Save some work for SDKTools and remove SOUND_FROM_PLAYER references */
entity = (entity == SOUND_FROM_PLAYER) ? client : entity;
return EmitGameSound(clients, 1, gameSound, entity, flags,
speakerentity, origin, dir, updatePos, soundtime);
}
/**
* Wrapper to emit game sound to all clients.
*
* Game sounds are found in a game's scripts/game_sound.txt or other files
* referenced from it
*
* Note that if a game sound has a rndwave section, one of them will be returned
* at random.
*
* @param gameSound Name of game sound.
* @param entity Entity to emit from.
* @param flags Sound flags.
* @param speakerentity Unknown.
* @param origin Sound origin.
* @param dir Sound direction.
* @param updatePos Unknown (updates positions?)
* @param soundtime Alternate time to play sound for.
* @error Invalid client index.
*/
stock bool EmitGameSoundToAll(const char[] gameSound,
int entity = SOUND_FROM_PLAYER,
int flags = SND_NOFLAGS,
int speakerentity = -1,
const float origin[3] = NULL_VECTOR,
const float dir[3] = NULL_VECTOR,
bool updatePos = true,
float soundtime = 0.0)
{
int[] clients = new int[MaxClients];
int total = 0;
for (int i=1; i<=MaxClients; i++)
{
if (IsClientInGame(i))
{
clients[total++] = i;
}
}
if (!total)
{
return false;
}
return EmitGameSound(clients, total, gameSound, entity, flags,
speakerentity, origin, dir, updatePos, soundtime);
}
/**
* Precache a game sound.
*
* Most games will precache all game sounds on map start, but this is not guaranteed...
* Team Fortress 2 is known to not pre-cache MvM game mode sounds on non-MvM maps.
*
* Due to the above, this native should be called before any calls to GetGameSoundParams,
* EmitGameSound*, or EmitAmbientGameSound.
*
* It should be safe to pass already precached game sounds to this function.
*
* Note: It precaches all files for a game sound.
*
* @param soundname Game sound to precache
* @return True if the game sound was found, false if sound did not exist
* or had no files
*/
native bool PrecacheScriptSound(const char[] soundname);

View File

@@ -0,0 +1,75 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _sdktools_stocks_included
#endinput
#endif
#define _sdktools_stocks_included
/**
* Given a partial team name, attempts to find a matching team.
*
* The search is performed case insensitively and only against the
* first N characters of the team names, where N is the number of
* characters in the search pattern.
*
* @param name Partial or full team name.
* @return A valid team index on success.
* -1 if no team matched.
* -2 if more than one team matched.
*/
stock int FindTeamByName(const char[] name)
{
int name_len = strlen(name);
int num_teams = GetTeamCount();
char team_name[32];
int found_team = -1;
for (int i = 0; i < num_teams; i++)
{
GetTeamName(i, team_name, sizeof(team_name));
if (strncmp(team_name, name, name_len, false) == 0)
{
if (found_team >= 0)
{
return -2;
}
else
{
found_team = i;
}
}
}
return found_team;
}

View File

@@ -0,0 +1,180 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _sdktools_stringtables_included
#endinput
#endif
#define _sdktools_stringtables_included
#define INVALID_STRING_TABLE -1 /**< An invalid string table index */
#define INVALID_STRING_INDEX -1 /**< An invalid string index in a table */
/**
* Searches for a string table.
*
* @param name Name of string table to find.
* @return A string table index number if found, INVALID_STRING_TABLE otherwise.
*/
native int FindStringTable(const char[] name);
/**
* Returns the number of string tables that currently exist.
*
* @return Number of string tables that currently exist.
*/
native int GetNumStringTables();
/**
* Returns the number of strings that currently exist in a given string table.
*
* @param tableidx A string table index.
* @return Number of strings that currently exist.
* @error Invalid string table index.
*/
native int GetStringTableNumStrings(int tableidx);
/**
* Returns the maximum number of strings that are allowed in a given string table.
*
* @param tableidx A string table index.
* @return Maximum number of strings allowed.
* @error Invalid string table index.
*/
native int GetStringTableMaxStrings(int tableidx);
/**
* Retrieves the name of a string table.
*
* @param tableidx A string table index.
* @param name Buffer to store the name of the string table.
* @param maxlength Maximum length of string buffer.
* @return Number of bytes written to the buffer (UTF-8 safe).
* @error Invalid string table index.
*/
native int GetStringTableName(int tableidx, char[] name, int maxlength);
/**
* Searches for the index of a given string in a string table.
*
* @param tableidx A string table index.
* @param str String to find.
* @return String index if found, INVALID_STRING_INDEX otherwise.
* @error Invalid string table index.
*/
native int FindStringIndex(int tableidx, const char[] str);
/**
* Retrieves the string at a given index of a string table.
*
* @param tableidx A string table index.
* @param stringidx A string index.
* @param str Buffer to store the string value.
* @param maxlength Maximum length of string buffer.
* @return Number of bytes written to the buffer (UTF-8 safe).
* @error Invalid string table index or string index.
*/
native int ReadStringTable(int tableidx, int stringidx, char[] str, int maxlength);
/**
* Returns the length of the user data associated with a given string index.
*
* @param tableidx A string table index.
* @param stringidx A string index.
* @return Length of user data. This will be 0 if there is no user data.
* @error Invalid string table index or string index.
*/
native int GetStringTableDataLength(int tableidx, int stringidx);
/**
* Retrieves the user data associated with a given string index.
*
* @param tableidx A string table index.
* @param stringidx A string index.
* @param userdata Buffer to store the user data. This will be set to "" if there is no user data
* @param maxlength Maximum length of string buffer.
* @return Number of bytes written to the buffer (binary safe, includes the null terminator).
* @error Invalid string table index or string index.
*/
native int GetStringTableData(int tableidx, int stringidx, char[] userdata, int maxlength);
/**
* Sets the user data associated with a given string index.
*
* @param tableidx A string table index.
* @param stringidx A string index.
* @param userdata User data string that will be set.
* @param length Length of user data string. This should include the null terminator.
* @error Invalid string table index or string index.
*/
native void SetStringTableData(int tableidx, int stringidx, const char[] userdata, int length);
/**
* Adds a string to a given string table.
*
* @param tableidx A string table index.
* @param str String to add.
* @param userdata An optional user data string.
* @param length Length of user data string. This should include the null terminator.
* If set to -1, then user data will be not be altered if the specified string
* already exists in the string table.
* @error Invalid string table index.
*/
native void AddToStringTable(int tableidx, const char[] str, const char[] userdata="", int length=-1);
/**
* Locks or unlocks the network string tables.
*
* @param lock Determines whether network string tables should be locked.
* True means the tables should be locked for writing; false means unlocked.
* @return Previous lock state.
*/
native bool LockStringTables(bool lock);
/**
* Adds a file to the downloadables network string table.
* This forces a client to download the file if they do not already have it.
*
* @param filename File that will be added to downloadables table.
*/
stock void AddFileToDownloadsTable(const char[] filename)
{
static int table = INVALID_STRING_TABLE;
if (table == INVALID_STRING_TABLE)
{
table = FindStringTable("downloadables");
}
bool save = LockStringTables(false);
AddToStringTable(table, filename);
LockStringTables(save);
}

View File

@@ -0,0 +1,250 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _sdktools_tempents_included
#endinput
#endif
#define _sdktools_tempents_included
/**
* Called when a temp entity is going to be sent.
*
* @param te_name TE name.
* @param Players Array containing target player indexes.
* @param numClients Number of players in the array.
* @param delay Delay in seconds to send the TE.
* @return Plugin_Continue to allow the transmission of the TE, Plugin_Stop to block it.
*/
typedef TEHook = function Action (const char[] te_name, const int[] Players, int numClients, float delay);
/**
* Hooks a temp entity.
*
* @param te_name TE name to hook.
* @param hook Function to use as a hook.
* @error Temp Entity name not available or invalid function hook.
*/
native void AddTempEntHook(const char[] te_name, TEHook hook);
/**
* Removes a temp entity hook.
*
* @param te_name TE name to unhook.
* @param hook Function used for the hook.
* @error Temp Entity name not available or invalid function hook.
*/
native void RemoveTempEntHook(const char[] te_name, TEHook hook);
/**
* Starts a temp entity transmission.
*
* @param te_name TE name.
* @error Temp Entity name not available.
*/
native void TE_Start(const char[] te_name);
/**
* Checks if a certain TE property exists.
*
* @param prop Property to use.
* @return True if the property exists, otherwise false.
*/
native bool TE_IsValidProp(const char[] prop);
/**
* Sets an integer value in the current temp entity.
*
* @param prop Property to use.
* @param value Integer value to set.
* @error Property not found.
*/
native void TE_WriteNum(const char[] prop, int value);
/**
* Reads an integer value in the current temp entity.
*
* @param prop Property to use.
* @return Property value.
* @error Property not found.
*/
native int TE_ReadNum(const char[] prop);
/**
* Sets an entity value in the current temp entity.
*
* @param prop Property to use.
* @param value Entity reference or index value to set.
* @error Property not found.
*/
native void TE_WriteEnt(const char[] prop, int value);
/**
* Reads an entity value in the current temp entity.
*
* @param prop Property to use.
* @return Property value as backwards compatible entity reference.
* @error Property not found.
*/
native int TE_ReadEnt(const char[] prop);
/**
* Sets a floating point number in the current temp entity.
*
* @param prop Property to use.
* @param value Floating point number to set.
* @error Property not found.
*/
native void TE_WriteFloat(const char[] prop, float value);
/**
* Reads a floating point number in the current temp entity.
*
* @param prop Property to use.
* @return Property value.
* @error Property not found.
*/
native float TE_ReadFloat(const char[] prop);
/**
* Sets a vector in the current temp entity.
*
* @param prop Property to use.
* @param vector Vector to set.
* @error Property not found.
*/
native void TE_WriteVector(const char[] prop, const float vector[3]);
/**
* Reads a vector in the current temp entity.
*
* @param prop Property to use.
* @param vector Vector to read.
* @error Property not found.
*/
native void TE_ReadVector(const char[] prop, float vector[3]);
/**
* Sets a QAngle in the current temp entity.
*
* @param prop Property to use.
* @param angles Angles to set.
* @error Property not found.
*/
native void TE_WriteAngles(const char[] prop, const float angles[3]);
/**
* Sets an array of floats in the current temp entity.
*
* @param prop Property to use.
* @param array Array of values to copy.
* @param arraySize Number of values to copy.
* @error Property not found.
*/
native void TE_WriteFloatArray(const char[] prop, const float[] array, int arraySize);
/**
* Sends the current temp entity to one or more clients.
*
* @param clients Array containing player indexes to broadcast to.
* @param numClients Number of players in the array.
* @param delay Delay in seconds to send the TE.
* @error Invalid client index or client not in game.
*/
native void TE_Send(const int[] clients, int numClients, float delay=0.0);
/**
* Sets an encoded entity index in the current temp entity.
* (This is usually used for m_nStartEntity and m_nEndEntity).
*
* @param prop Property to use.
* @param value Value to set.
* @error Property not found.
*/
stock void TE_WriteEncodedEnt(const char[] prop, int value)
{
int encvalue = (value & 0x0FFF) | ((1 & 0xF)<<12);
TE_WriteNum(prop, encvalue);
}
/**
* Broadcasts the current temp entity to all clients.
* @note See TE_Start().
*
* @param delay Delay in seconds to send the TE.
*/
stock void TE_SendToAll(float delay=0.0)
{
int total = 0;
int[] clients = new int[MaxClients];
for (int i=1; i<=MaxClients; i++)
{
if (IsClientInGame(i))
{
clients[total++] = i;
}
}
TE_Send(clients, total, delay);
}
/**
* Sends the current TE to only a client.
* @note See TE_Start().
*
* @param client Client to send to.
* @param delay Delay in seconds to send the TE.
* @error Invalid client index or client not in game.
*/
stock void TE_SendToClient(int client, float delay=0.0)
{
int players[1];
players[0] = client;
TE_Send(players, 1, delay);
}
/**
* Sends the current TE to all clients that are in
* visible or audible range of the origin.
* @note See TE_Start().
* @note See GetClientsInRange()
*
* @param origin Coordinates from which to test range.
* @param rangeType Range type to use for filtering clients.
* @param delay Delay in seconds to send the TE.
*/
stock void TE_SendToAllInRange(const float origin[3], ClientRangeType rangeType, float delay=0.0)
{
int[] clients = new int[MaxClients];
int total = GetClientsInRange(origin, rangeType, clients, MaxClients);
TE_Send(clients, total, delay);
}

View File

@@ -0,0 +1,443 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _te_stocks_included
#endinput
#endif
#define _te_stocks_included
/**
* @section TE Explosion flags.
*/
#define TE_EXPLFLAG_NONE 0x0 /**< all flags clear makes default Half-Life explosion */
#define TE_EXPLFLAG_NOADDITIVE 0x1 /**< sprite will be drawn opaque (ensure that the sprite you send is a non-additive sprite) */
#define TE_EXPLFLAG_NODLIGHTS 0x2 /**< do not render dynamic lights */
#define TE_EXPLFLAG_NOSOUND 0x4 /**< do not play client explosion sound */
#define TE_EXPLFLAG_NOPARTICLES 0x8 /**< do not draw particles */
#define TE_EXPLFLAG_DRAWALPHA 0x10 /**< sprite will be drawn alpha */
#define TE_EXPLFLAG_ROTATE 0x20 /**< rotate the sprite randomly */
#define TE_EXPLFLAG_NOFIREBALL 0x40 /**< do not draw a fireball */
#define TE_EXPLFLAG_NOFIREBALLSMOKE 0x80 /**< do not draw smoke with the fireball */
/**
* @endsection
*/
/**
* @section TE Beam flags.
*/
#define FBEAM_STARTENTITY 0x00000001
#define FBEAM_ENDENTITY 0x00000002
#define FBEAM_FADEIN 0x00000004
#define FBEAM_FADEOUT 0x00000008
#define FBEAM_SINENOISE 0x00000010
#define FBEAM_SOLID 0x00000020
#define FBEAM_SHADEIN 0x00000040
#define FBEAM_SHADEOUT 0x00000080
#define FBEAM_ONLYNOISEONCE 0x00000100 /**< Only calculate our noise once */
#define FBEAM_NOTILE 0x00000200
#define FBEAM_USE_HITBOXES 0x00000400 /**< Attachment indices represent hitbox indices instead when this is set. */
#define FBEAM_STARTVISIBLE 0x00000800 /**< Has this client actually seen this beam's start entity yet? */
#define FBEAM_ENDVISIBLE 0x00001000 /**< Has this client actually seen this beam's end entity yet? */
#define FBEAM_ISACTIVE 0x00002000
#define FBEAM_FOREVER 0x00004000
#define FBEAM_HALOBEAM 0x00008000 /**< When drawing a beam with a halo, don't ignore the segments and endwidth */
/**
* @endsection
*/
/**
* Sets up a sparks effect.
*
* @param pos Position of the sparks.
* @param dir Direction of the sparks.
* @param Magnitude Sparks size.
* @param TrailLength Trail lenght of the sparks.
*/
stock void TE_SetupSparks(const float pos[3], const float dir[3], int Magnitude, int TrailLength)
{
TE_Start("Sparks");
TE_WriteVector("m_vecOrigin[0]", pos);
TE_WriteVector("m_vecDir", dir);
TE_WriteNum("m_nMagnitude", Magnitude);
TE_WriteNum("m_nTrailLength", TrailLength);
}
/**
* Sets up a smoke effect.
*
* @param pos Position of the smoke.
* @param Model Precached model index.
* @param Scale Scale of the smoke.
* @param FrameRate Frame rate of the smoke.
*/
stock void TE_SetupSmoke(const float pos[3], int Model, float Scale, int FrameRate)
{
TE_Start("Smoke");
TE_WriteVector("m_vecOrigin", pos);
TE_WriteNum("m_nModelIndex", Model);
TE_WriteFloat("m_fScale", Scale);
TE_WriteNum("m_nFrameRate", FrameRate);
}
/**
* Sets up a dust cloud effect.
*
* @param pos Position of the dust.
* @param dir Direction of the dust.
* @param Size Dust cloud size.
* @param Speed Dust cloud speed.
*/
stock void TE_SetupDust(const float pos[3], const float dir[3], float Size, float Speed)
{
TE_Start("Dust");
TE_WriteVector("m_vecOrigin[0]", pos);
TE_WriteVector("m_vecDirection", dir);
TE_WriteFloat("m_flSize", Size);
TE_WriteFloat("m_flSpeed", Speed);
}
/**
* Sets up a muzzle flash effect.
*
* @param pos Position of the muzzle flash.
* @param angles Rotation angles of the muzzle flash.
* @param Scale Scale of the muzzle flash.
* @param Type Muzzle flash type to render (Mod specific).
*/
stock void TE_SetupMuzzleFlash(const float pos[3], const float angles[3], float Scale, int Type)
{
TE_Start("MuzzleFlash");
TE_WriteVector("m_vecOrigin", pos);
TE_WriteVector("m_vecAngles", angles);
TE_WriteFloat("m_flScale", Scale);
TE_WriteNum("m_nType", Type);
}
/**
* Sets up a metal sparks effect.
*
* @param pos Position of the metal sparks.
* @param dir Direction of the metal sparks.
*/
stock void TE_SetupMetalSparks(const float pos[3], const float dir[3])
{
TE_Start("Metal Sparks");
TE_WriteVector("m_vecPos", pos);
TE_WriteVector("m_vecDir", dir);
}
/**
* Sets up an energy splash effect.
*
* @param pos Position of the energy splash.
* @param dir Direction of the energy splash.
* @param Explosive Makes the effect explosive.
*/
stock void TE_SetupEnergySplash(const float pos[3], const float dir[3], bool Explosive)
{
TE_Start("Energy Splash");
TE_WriteVector("m_vecPos", pos);
TE_WriteVector("m_vecDir", dir);
TE_WriteNum("m_bExplosive", Explosive);
}
/**
* Sets up an armor ricochet effect.
*
* @param pos Position of the armor ricochet.
* @param dir Direction of the armor ricochet.
*/
stock void TE_SetupArmorRicochet(const float pos[3], const float dir[3])
{
TE_Start("Armor Ricochet");
TE_WriteVector("m_vecPos", pos);
TE_WriteVector("m_vecDir", dir);
}
/**
* Sets up a glowing sprite effect.
*
* @param pos Position of the sprite.
* @param Model Precached model index.
* @param Life Time duration of the sprite.
* @param Size Sprite size.
* @param Brightness Sprite brightness.
*/
stock void TE_SetupGlowSprite(const float pos[3], int Model, float Life, float Size, int Brightness)
{
TE_Start("GlowSprite");
TE_WriteVector("m_vecOrigin", pos);
TE_WriteNum("m_nModelIndex", Model);
TE_WriteFloat("m_fScale", Size);
TE_WriteFloat("m_fLife", Life);
TE_WriteNum("m_nBrightness", Brightness);
}
/**
* Sets up a explosion effect.
*
* @param pos Explosion position.
* @param Model Precached model index.
* @param Scale Explosion scale.
* @param Framerate Explosion frame rate.
* @param Flags Explosion flags.
* @param Radius Explosion radius.
* @param Magnitude Explosion size.
* @param normal Normal vector to the explosion.
* @param MaterialType Exploded material type.
*/
stock void TE_SetupExplosion(const float pos[3], int Model, float Scale, int Framerate, int Flags, int Radius, int Magnitude, const float normal[3]={0.0, 0.0, 1.0}, int MaterialType='C')
{
TE_Start("Explosion");
TE_WriteVector("m_vecOrigin[0]", pos);
TE_WriteVector("m_vecNormal", normal);
TE_WriteNum("m_nModelIndex", Model);
TE_WriteFloat("m_fScale", Scale);
TE_WriteNum("m_nFrameRate", Framerate);
TE_WriteNum("m_nFlags", Flags);
TE_WriteNum("m_nRadius", Radius);
TE_WriteNum("m_nMagnitude", Magnitude);
TE_WriteNum("m_chMaterialType", MaterialType);
}
/**
* Sets up a blood sprite effect.
*
* @param pos Position of the sprite.
* @param dir Sprite direction.
* @param color Color array (r, g, b, a).
* @param Size Sprite size.
* @param SprayModel Precached model index.
* @param BloodDropModel Precached model index.
*/
stock void TE_SetupBloodSprite(const float pos[3], const float dir[3], const int color[4], int Size, int SprayModel, int BloodDropModel)
{
TE_Start("Blood Sprite");
TE_WriteVector("m_vecOrigin", pos);
TE_WriteVector("m_vecDirection", dir);
TE_WriteNum("r", color[0]);
TE_WriteNum("g", color[1]);
TE_WriteNum("b", color[2]);
TE_WriteNum("a", color[3]);
TE_WriteNum("m_nSize", Size);
TE_WriteNum("m_nSprayModel", SprayModel);
TE_WriteNum("m_nDropModel", BloodDropModel);
}
/**
* Sets up a beam ring point effect.
*
* @param center Center position of the ring.
* @param Start_Radius Initial ring radius.
* @param End_Radius Final ring radius.
* @param ModelIndex Precached model index.
* @param HaloIndex Precached model index.
* @param StartFrame Initial frame to render.
* @param FrameRate Ring frame rate.
* @param Life Time duration of the ring.
* @param Width Beam width.
* @param Amplitude Beam amplitude.
* @param Color Color array (r, g, b, a).
* @param Speed Speed of the beam.
* @param Flags Beam flags.
*/
stock void TE_SetupBeamRingPoint(const float center[3], float Start_Radius, float End_Radius, int ModelIndex, int HaloIndex, int StartFrame,
int FrameRate, float Life, float Width, float Amplitude, const int Color[4], int Speed, int Flags)
{
TE_Start("BeamRingPoint");
TE_WriteVector("m_vecCenter", center);
TE_WriteFloat("m_flStartRadius", Start_Radius);
TE_WriteFloat("m_flEndRadius", End_Radius);
TE_WriteNum("m_nModelIndex", ModelIndex);
TE_WriteNum("m_nHaloIndex", HaloIndex);
TE_WriteNum("m_nStartFrame", StartFrame);
TE_WriteNum("m_nFrameRate", FrameRate);
TE_WriteFloat("m_fLife", Life);
TE_WriteFloat("m_fWidth", Width);
TE_WriteFloat("m_fEndWidth", Width);
TE_WriteFloat("m_fAmplitude", Amplitude);
TE_WriteNum("r", Color[0]);
TE_WriteNum("g", Color[1]);
TE_WriteNum("b", Color[2]);
TE_WriteNum("a", Color[3]);
TE_WriteNum("m_nSpeed", Speed);
TE_WriteNum("m_nFlags", Flags);
TE_WriteNum("m_nFadeLength", 0);
}
/**
* Sets up a point to point beam effect.
*
* @param start Start position of the beam.
* @param end End position of the beam.
* @param ModelIndex Precached model index.
* @param HaloIndex Precached model index.
* @param StartFrame Initial frame to render.
* @param FrameRate Beam frame rate.
* @param Life Time duration of the beam.
* @param Width Initial beam width.
* @param EndWidth Final beam width.
* @param FadeLength Beam fade time duration.
* @param Amplitude Beam amplitude.
* @param Color Color array (r, g, b, a).
* @param Speed Speed of the beam.
*/
stock void TE_SetupBeamPoints(const float start[3], const float end[3], int ModelIndex, int HaloIndex, int StartFrame, int FrameRate, float Life,
float Width, float EndWidth, int FadeLength, float Amplitude, const int Color[4], int Speed)
{
TE_Start("BeamPoints");
TE_WriteVector("m_vecStartPoint", start);
TE_WriteVector("m_vecEndPoint", end);
TE_WriteNum("m_nModelIndex", ModelIndex);
TE_WriteNum("m_nHaloIndex", HaloIndex);
TE_WriteNum("m_nStartFrame", StartFrame);
TE_WriteNum("m_nFrameRate", FrameRate);
TE_WriteFloat("m_fLife", Life);
TE_WriteFloat("m_fWidth", Width);
TE_WriteFloat("m_fEndWidth", EndWidth);
TE_WriteFloat("m_fAmplitude", Amplitude);
TE_WriteNum("r", Color[0]);
TE_WriteNum("g", Color[1]);
TE_WriteNum("b", Color[2]);
TE_WriteNum("a", Color[3]);
TE_WriteNum("m_nSpeed", Speed);
TE_WriteNum("m_nFadeLength", FadeLength);
}
/**
* Sets up an entity to entity laser effect.
*
* @param StartEntity Entity index from where the beam starts.
* @param EndEntity Entity index from where the beam ends.
* @param ModelIndex Precached model index.
* @param HaloIndex Precached model index.
* @param StartFrame Initial frame to render.
* @param FrameRate Beam frame rate.
* @param Life Time duration of the beam.
* @param Width Initial beam width.
* @param EndWidth Final beam width.
* @param FadeLength Beam fade time duration.
* @param Amplitude Beam amplitude.
* @param Color Color array (r, g, b, a).
* @param Speed Speed of the beam.
*/
stock void TE_SetupBeamLaser(int StartEntity, int EndEntity, int ModelIndex, int HaloIndex, int StartFrame, int FrameRate, float Life,
float Width, float EndWidth, int FadeLength, float Amplitude, const int Color[4], int Speed)
{
TE_Start("BeamLaser");
TE_WriteEncodedEnt("m_nStartEntity", StartEntity);
TE_WriteEncodedEnt("m_nEndEntity", EndEntity);
TE_WriteNum("m_nModelIndex", ModelIndex);
TE_WriteNum("m_nHaloIndex", HaloIndex);
TE_WriteNum("m_nStartFrame", StartFrame);
TE_WriteNum("m_nFrameRate", FrameRate);
TE_WriteFloat("m_fLife", Life);
TE_WriteFloat("m_fWidth", Width);
TE_WriteFloat("m_fEndWidth", EndWidth);
TE_WriteFloat("m_fAmplitude", Amplitude);
TE_WriteNum("r", Color[0]);
TE_WriteNum("g", Color[1]);
TE_WriteNum("b", Color[2]);
TE_WriteNum("a", Color[3]);
TE_WriteNum("m_nSpeed", Speed);
TE_WriteNum("m_nFadeLength", FadeLength);
}
/**
* Sets up a beam ring effect.
*
* @param StartEntity Entity index from where the ring starts.
* @param EndEntity Entity index from where the ring ends.
* @param ModelIndex Precached model index.
* @param HaloIndex Precached model index.
* @param StartFrame Initial frame to render.
* @param FrameRate Ring frame rate.
* @param Life Time duration of the ring.
* @param Width Beam width.
* @param Amplitude Beam amplitude.
* @param Color Color array (r, g, b, a).
* @param Speed Speed of the beam.
* @param Flags Beam flags.
*/
stock void TE_SetupBeamRing(int StartEntity, int EndEntity, int ModelIndex, int HaloIndex, int StartFrame, int FrameRate, float Life, float Width, float Amplitude, const int Color[4], int Speed, int Flags)
{
TE_Start("BeamRing");
TE_WriteEncodedEnt("m_nStartEntity", StartEntity);
TE_WriteEncodedEnt("m_nEndEntity", EndEntity);
TE_WriteNum("m_nModelIndex", ModelIndex);
TE_WriteNum("m_nHaloIndex", HaloIndex);
TE_WriteNum("m_nStartFrame", StartFrame);
TE_WriteNum("m_nFrameRate", FrameRate);
TE_WriteFloat("m_fLife", Life);
TE_WriteFloat("m_fWidth", Width);
TE_WriteFloat("m_fEndWidth", Width);
TE_WriteFloat("m_fAmplitude", Amplitude);
TE_WriteNum("r", Color[0]);
TE_WriteNum("g", Color[1]);
TE_WriteNum("b", Color[2]);
TE_WriteNum("a", Color[3]);
TE_WriteNum("m_nSpeed", Speed);
TE_WriteNum("m_nFadeLength", 0);
TE_WriteNum("m_nFlags", Flags);
}
/**
* Sets up a follow beam effect.
*
* @param EntIndex Entity index from where the beam starts.
* @param ModelIndex Precached model index.
* @param HaloIndex Precached model index.
* @param Life Time duration of the beam.
* @param Width Initial beam width.
* @param EndWidth Final beam width.
* @param FadeLength Beam fade time duration.
* @param Color Color array (r, g, b, a).
*/
stock void TE_SetupBeamFollow(int EntIndex, int ModelIndex, int HaloIndex, float Life, float Width, float EndWidth, int FadeLength, const int Color[4])
{
TE_Start("BeamFollow");
TE_WriteEncodedEnt("m_iEntIndex", EntIndex);
TE_WriteNum("m_nModelIndex", ModelIndex);
TE_WriteNum("m_nHaloIndex", HaloIndex);
TE_WriteNum("m_nStartFrame", 0);
TE_WriteNum("m_nFrameRate", 0);
TE_WriteFloat("m_fLife", Life);
TE_WriteFloat("m_fWidth", Width);
TE_WriteFloat("m_fEndWidth", EndWidth);
TE_WriteNum("m_nFadeLength", FadeLength);
TE_WriteNum("r", Color[0]);
TE_WriteNum("g", Color[1]);
TE_WriteNum("b", Color[2]);
TE_WriteNum("a", Color[3]);
}

View File

@@ -0,0 +1,732 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _sdktools_trace_included
#endinput
#endif
#define _sdktools_trace_included
#define CONTENTS_EMPTY 0 /**< No contents. */
#define CONTENTS_SOLID 0x1 /**< an eye is never valid in a solid . */
#define CONTENTS_WINDOW 0x2 /**< translucent, but not watery (glass). */
#define CONTENTS_AUX 0x4
#define CONTENTS_GRATE 0x8 /**< alpha-tested "grate" textures. Bullets/sight pass through, but solids don't. */
#define CONTENTS_SLIME 0x10
#define CONTENTS_WATER 0x20
#define CONTENTS_MIST 0x40
#define CONTENTS_OPAQUE 0x80 /**< things that cannot be seen through (may be non-solid though). */
#define LAST_VISIBLE_CONTENTS 0x80
#define ALL_VISIBLE_CONTENTS (LAST_VISIBLE_CONTENTS | (LAST_VISIBLE_CONTENTS-1))
#define CONTENTS_TESTFOGVOLUME 0x100
#define CONTENTS_UNUSED5 0x200
#define CONTENTS_UNUSED6 0x4000
#define CONTENTS_TEAM1 0x800 /**< per team contents used to differentiate collisions. */
#define CONTENTS_TEAM2 0x1000 /**< between players and objects on different teams. */
#define CONTENTS_IGNORE_NODRAW_OPAQUE 0x2000 /**< ignore CONTENTS_OPAQUE on surfaces that have SURF_NODRAW. */
#define CONTENTS_MOVEABLE 0x4000 /**< hits entities which are MOVETYPE_PUSH (doors, plats, etc) */
#define CONTENTS_AREAPORTAL 0x8000 /**< remaining contents are non-visible, and don't eat brushes. */
#define CONTENTS_PLAYERCLIP 0x10000
#define CONTENTS_MONSTERCLIP 0x20000
/**
* @section currents can be added to any other contents, and may be mixed
*/
#define CONTENTS_CURRENT_0 0x40000
#define CONTENTS_CURRENT_90 0x80000
#define CONTENTS_CURRENT_180 0x100000
#define CONTENTS_CURRENT_270 0x200000
#define CONTENTS_CURRENT_UP 0x400000
#define CONTENTS_CURRENT_DOWN 0x800000
/**
* @endsection
*/
#define CONTENTS_ORIGIN 0x1000000 /**< removed before bsp-ing an entity. */
#define CONTENTS_MONSTER 0x2000000 /**< should never be on a brush, only in game. */
#define CONTENTS_DEBRIS 0x4000000
#define CONTENTS_DETAIL 0x8000000 /**< brushes to be added after vis leafs. */
#define CONTENTS_TRANSLUCENT 0x10000000 /**< auto set if any surface has trans. */
#define CONTENTS_LADDER 0x20000000
#define CONTENTS_HITBOX 0x40000000 /**< use accurate hitboxes on trace. */
/**
* @section Trace masks.
*/
#define MASK_ALL (0xFFFFFFFF)
#define MASK_SOLID (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_WINDOW|CONTENTS_MONSTER|CONTENTS_GRATE) /**< everything that is normally solid */
#define MASK_PLAYERSOLID (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_PLAYERCLIP|CONTENTS_WINDOW|CONTENTS_MONSTER|CONTENTS_GRATE) /**< everything that blocks player movement */
#define MASK_NPCSOLID (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_MONSTERCLIP|CONTENTS_WINDOW|CONTENTS_MONSTER|CONTENTS_GRATE) /**< blocks npc movement */
#define MASK_WATER (CONTENTS_WATER|CONTENTS_MOVEABLE|CONTENTS_SLIME) /**< water physics in these contents */
#define MASK_OPAQUE (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_OPAQUE) /**< everything that blocks line of sight for AI, lighting, etc */
#define MASK_OPAQUE_AND_NPCS (MASK_OPAQUE|CONTENTS_MONSTER) /**< everything that blocks line of sight for AI, lighting, etc, but with monsters added. */
#define MASK_VISIBLE (MASK_OPAQUE|CONTENTS_IGNORE_NODRAW_OPAQUE) /**< everything that blocks line of sight for players */
#define MASK_VISIBLE_AND_NPCS (MASK_OPAQUE_AND_NPCS|CONTENTS_IGNORE_NODRAW_OPAQUE) /**< everything that blocks line of sight for players, but with monsters added. */
#define MASK_SHOT (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_MONSTER|CONTENTS_WINDOW|CONTENTS_DEBRIS|CONTENTS_HITBOX) /**< bullets see these as solid */
#define MASK_SHOT_HULL (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_MONSTER|CONTENTS_WINDOW|CONTENTS_DEBRIS|CONTENTS_GRATE) /**< non-raycasted weapons see this as solid (includes grates) */
#define MASK_SHOT_PORTAL (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_WINDOW) /**< hits solids (not grates) and passes through everything else */
#define MASK_SOLID_BRUSHONLY (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_WINDOW|CONTENTS_GRATE) /**< everything normally solid, except monsters (world+brush only) */
#define MASK_PLAYERSOLID_BRUSHONLY (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_WINDOW|CONTENTS_PLAYERCLIP|CONTENTS_GRATE) /**< everything normally solid for player movement, except monsters (world+brush only) */
#define MASK_NPCSOLID_BRUSHONLY (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_WINDOW|CONTENTS_MONSTERCLIP|CONTENTS_GRATE) /**< everything normally solid for npc movement, except monsters (world+brush only) */
#define MASK_NPCWORLDSTATIC (CONTENTS_SOLID|CONTENTS_WINDOW|CONTENTS_MONSTERCLIP|CONTENTS_GRATE) /**< just the world, used for route rebuilding */
#define MASK_SPLITAREAPORTAL (CONTENTS_WATER|CONTENTS_SLIME) /**< These are things that can split areaportals */
/**
* @endsection
*/
/**
* @section Surface flags.
*/
#define SURF_LIGHT 0x0001 /**< value will hold the light strength */
#define SURF_SKY2D 0x0002 /**< don't draw, indicates we should skylight + draw 2d sky but not draw the 3D skybox */
#define SURF_SKY 0x0004 /**< don't draw, but add to skybox */
#define SURF_WARP 0x0008 /**< turbulent water warp */
#define SURF_TRANS 0x0010
#define SURF_NOPORTAL 0x0020 /**< the surface can not have a portal placed on it */
#define SURF_TRIGGER 0x0040 /**< This is an xbox hack to work around elimination of trigger surfaces, which breaks occluders */
#define SURF_NODRAW 0x0080 /**< don't bother referencing the texture */
#define SURF_HINT 0x0100 /**< make a primary bsp splitter */
#define SURF_SKIP 0x0200 /**< completely ignore, allowing non-closed brushes */
#define SURF_NOLIGHT 0x0400 /**< Don't calculate light */
#define SURF_BUMPLIGHT 0x0800 /**< calculate three lightmaps for the surface for bumpmapping */
#define SURF_NOSHADOWS 0x1000 /**< Don't receive shadows */
#define SURF_NODECALS 0x2000 /**< Don't receive decals */
#define SURF_NOCHOP 0x4000 /**< Don't subdivide patches on this surface */
#define SURF_HITBOX 0x8000 /**< surface is part of a hitbox */
/**
* @endsection
*/
/**
* @section Partition masks.
*/
#define PARTITION_SOLID_EDICTS (1 << 1) /**< every edict_t that isn't SOLID_TRIGGER or SOLID_NOT (and static props) */
#define PARTITION_TRIGGER_EDICTS (1 << 2) /**< every edict_t that IS SOLID_TRIGGER */
#define PARTITION_NON_STATIC_EDICTS (1 << 5) /**< everything in solid & trigger except the static props, includes SOLID_NOTs */
#define PARTITION_STATIC_PROPS (1 << 7)
/**
* @endsection
*/
/**
* @section Displacement flags.
*/
#define DISPSURF_FLAG_SURFACE (1<<0)
#define DISPSURF_FLAG_WALKABLE (1<<1)
#define DISPSURF_FLAG_BUILDABLE (1<<2)
#define DISPSURF_FLAG_SURFPROP1 (1<<3)
#define DISPSURF_FLAG_SURFPROP2 (1<<4)
/**
* @endsection
*/
enum RayType
{
RayType_EndPoint, /**< The trace ray will go from the start position to the end position. */
RayType_Infinite /**< The trace ray will go from the start position to infinity using a direction vector. */
};
enum TraceType
{
TRACE_EVERYTHING = 0,
TRACE_WORLD_ONLY, /**< NOTE: This does *not* test static props!!! */
TRACE_ENTITIES_ONLY, /**< NOTE: This version will *not* test static props */
TRACE_EVERYTHING_FILTER_PROPS /**< NOTE: This version will pass the IHandleEntity for props through the filter, unlike all other filters */
};
typeset TraceEntityFilter
{
/**
* Called on entity filtering.
*
* @param entity Entity index.
* @param contentsMask Contents Mask.
* @return True to allow the current entity to be hit, otherwise false.
*/
function bool (int entity, int contentsMask);
/**
* Called on entity filtering.
*
* @param entity Entity index.
* @param contentsMask Contents Mask.
* @param data Data value, if used.
* @return True to allow the current entity to be hit, otherwise false.
*/
function bool (int entity, int contentsMask, any data);
};
typeset TraceEntityEnumerator
{
/**
* Called for each entity enumerated with EnumerateEntities*.
*
* @param entity Entity index.
* @return True to continue enumerating, otherwise false.
*/
function bool (int entity);
/**
* Called for each entity enumerated with EnumerateEntities*.
*
* @param entity Entity index.
* @param data Data value, if used.
* @return True to continue enumerating, otherwise false. */
function bool (int entity, any data);
}
/**
* Get the contents mask and the entity index at the given position.
*
* @param pos World position to test.
* @param entindex Entity index found at the given position (by reference).
* @return Contents mask.
*/
native int TR_GetPointContents(const float pos[3], int &entindex=-1);
/**
* Get the point contents testing only the given entity index.
*
* @param entindex Entity index to test.
* @param pos World position.
* @return Contents mask.
* @error Invalid entity.
*/
native int TR_GetPointContentsEnt(int entindex, const float pos[3]);
/**
* Starts up a new trace ray using a global trace result.
*
* @param pos Starting position of the ray.
* @param vec Depending on RayType, it will be used as the
* ending point, or the direction angle.
* @param flags Trace flags.
* @param rtype Method to calculate the ray direction.
*/
native void TR_TraceRay(const float pos[3],
const float vec[3],
int flags,
RayType rtype);
/**
* Starts up a new trace hull using a global trace result.
*
* @param pos Starting position of the ray.
* @param vec Ending position of the ray.
* @param mins Hull minimum size.
* @param maxs Hull maximum size.
* @param flags Trace flags.
*/
native void TR_TraceHull(const float pos[3],
const float vec[3],
const float mins[3],
const float maxs[3],
int flags);
/**
* Enumerates over entities along a ray. This may find entities that are
* close to the ray but do not actually intersect it. Use TR_Clip*RayToEntity
* with TR_DidHit to check if the ray actually intersects the entity.
*
* @param pos Starting position of the ray.
* @param vec Depending on RayType, it will be used as the ending
* point, or the direction angle.
* @param mask Mask to use for the trace. See PARTITION_* flags.
* @param rtype Method to calculate the ray direction.
* @param enumerator Function to use as enumerator. For each entity found
* along the ray, this function is called.
* @param data Arbitrary data value to pass through to the enumerator.
*/
native void TR_EnumerateEntities(const float pos[3],
const float vec[3],
int mask,
RayType rtype,
TraceEntityEnumerator enumerator,
any data=0);
/**
* Enumerates over entities along a ray hull. This may find entities that are
* close to the ray but do not actually intersect it. Use TR_Clip*RayToEntity
* with TR_DidHit to check if the ray actually intersects the entity.
*
* @param pos Starting position of the ray.
* @param vec Ending position of the ray.
* @param mins Hull minimum size.
* @param maxs Hull maximum size.
* @param mask Mask to use for the trace. See PARTITION_* flags.
* @param enumerator Function to use as enumerator. For each entity found
* along the ray, this function is called.
* @param data Arbitrary data value to pass through to the enumerator.
*/
native void TR_EnumerateEntitiesHull(const float pos[3],
const float vec[3],
const float mins[3],
const float maxs[3],
int mask,
TraceEntityEnumerator enumerator,
any data=0);
/**
* Enumerates over entities in a sphere.
*
* @param pos Starting position of the ray.
* @param radius Radius of the ray.
* @param mask Mask to use for the trace. See PARTITION_* flags.
* @param enumerator Function to use as enumerator. For each entity found
* along the ray, this function is called.
* @param data Arbitrary data value to pass through to the enumerator.
*/
native void TR_EnumerateEntitiesSphere(const float pos[3],
float radius,
int mask,
TraceEntityEnumerator enumerator,
any data=0);
/**
* Enumerates over entities in a box.
*
* @param mins Box minimum size.
* @param maxs Box maximum size.
* @param mask Mask to use for the trace. See PARTITION_* flags.
* @param enumerator Function to use as enumerator. For each entity found
* along the box, this function is called.
* @param data Arbitrary data value to pass through to the enumerator.
*/
native void TR_EnumerateEntitiesBox(const float mins[3],
const float maxs[3],
int mask,
TraceEntityEnumerator enumerator,
any data=0);
/**
* Enumerates over entities at point.
*
* @param pos Position of the point.
* @param mask Mask to use for the trace. See PARTITION_* flags.
* @param enumerator Function to use as enumerator. For each entity found
* along the point, this function is called.
* @param data Arbitrary data value to pass through to the enumerator.
*/
native void TR_EnumerateEntitiesPoint(const float pos[3],
int mask,
TraceEntityEnumerator enumerator,
any data=0);
/**
* Starts up a new trace ray using a global trace result and a customized
* trace ray filter.
*
* Calling TR_Trace*Filter or TR_Trace*FilterEx from inside a filter
* function is currently not allowed and may not work.
*
* @param pos Starting position of the ray.
* @param vec Depending on RayType, it will be used as the ending
* point, or the direction angle.
* @param flags Trace flags.
* @param rtype Method to calculate the ray direction.
* @param filter Function to use as a filter.
* @param data Arbitrary data value to pass through to the filter
* function.
* @param traceType Trace type.
*/
native void TR_TraceRayFilter(const float pos[3],
const float vec[3],
int flags,
RayType rtype,
TraceEntityFilter filter,
any data=0,
TraceType traceType=TRACE_EVERYTHING);
/**
* Starts up a new trace hull using a global trace result and a customized
* trace ray filter.
*
* Calling TR_Trace*Filter or TR_Trace*FilterEx from inside a filter
* function is currently not allowed and may not work.
*
* @param pos Starting position of the ray.
* @param vec Ending position of the ray.
* @param mins Hull minimum size.
* @param maxs Hull maximum size.
* @param flags Trace flags.
* @param filter Function to use as a filter.
* @param data Arbitrary data value to pass through to the filter
* function.
* @param traceType Trace type.
*/
native void TR_TraceHullFilter(const float pos[3],
const float vec[3],
const float mins[3],
const float maxs[3],
int flags,
TraceEntityFilter filter,
any data=0,
TraceType traceType=TRACE_EVERYTHING);
/**
* Clips a ray to a particular entity.
*
* @param pos Starting position of the ray.
* @param vec Depending on RayType, it will be used as the ending
* point, or the direction angle.
* @param flags Trace flags.
* @param rtype Method to calculate the ray direction.
* @param entity Entity to clip to.
* @error Invalid entity.
*/
native void TR_ClipRayToEntity(const float pos[3],
const float vec[3],
int flags,
RayType rtype,
int entity);
/**
* Clips a ray hull to a particular entity.
*
* @param pos Starting position of the ray.
* @param vec Ending position of the ray.
* @param mins Hull minimum size.
* @param maxs Hull maximum size.
* @param flags Trace flags.
* @param entity Entity to clip to.
* @error Invalid entity.
*/
native void TR_ClipRayHullToEntity(const float pos[3],
const float vec[3],
const float mins[3],
const float maxs[3],
int flags,
int entity);
/**
* Clips the current global ray (or hull) to a particular entity.
*
* @param flags Trace flags.
* @param entity Entity to clip to.
* @error Invalid entity.
*/
native void TR_ClipCurrentRayToEntity(int flags, int entity);
/**
* Starts up a new trace ray using a new trace result.
*
* @param pos Starting position of the ray.
* @param vec Depending on RayType, it will be used as the ending
* point, or the direction angle.
* @param flags Trace flags.
* @param rtype Method to calculate the ray direction.
* @return Ray trace handle, which must be closed via CloseHandle().
*/
native Handle TR_TraceRayEx(const float pos[3],
const float vec[3],
int flags,
RayType rtype);
/**
* Starts up a new trace hull using a new trace result.
*
* @param pos Starting position of the ray.
* @param vec Ending position of the ray.
* @param mins Hull minimum size.
* @param maxs Hull maximum size.
* @param flags Trace flags.
* @return Ray trace handle, which must be closed via CloseHandle().
*/
native Handle TR_TraceHullEx(const float pos[3],
const float vec[3],
const float mins[3],
const float maxs[3],
int flags);
/**
* Starts up a new trace ray using a new trace result and a customized
* trace ray filter.
*
* Calling TR_Trace*Filter or TR_TraceRay*Ex from inside a filter
* function is currently not allowed and may not work.
*
* @param pos Starting position of the ray.
* @param vec Depending on RayType, it will be used as the ending
* point, or the direction angle.
* @param flags Trace flags.
* @param rtype Method to calculate the ray direction.
* @param filter Function to use as a filter.
* @param data Arbitrary data value to pass through to the filter function.
* @param traceType Trace type.
* @return Ray trace handle, which must be closed via CloseHandle().
*/
native Handle TR_TraceRayFilterEx(const float pos[3],
const float vec[3],
int flags,
RayType rtype,
TraceEntityFilter filter,
any data=0,
TraceType traceType=TRACE_EVERYTHING);
/**
* Starts up a new trace hull using a new trace result and a customized
* trace ray filter.
*
* Calling TR_Trace*Filter or TR_Trace*FilterEx from inside a filter
* function is currently not allowed and may not work.
*
* @param pos Starting position of the ray.
* @param vec Ending position of the ray.
* @param mins Hull minimum size.
* @param maxs Hull maximum size.
* @param flags Trace flags.
* @param filter Function to use as a filter.
* @param data Arbitrary data value to pass through to the filter function.
* @param traceType Trace type.
* @return Ray trace handle, which must be closed via CloseHandle().
*/
native Handle TR_TraceHullFilterEx(const float pos[3],
const float vec[3],
const float mins[3],
const float maxs[3],
int flags,
TraceEntityFilter filter,
any data=0,
TraceType traceType=TRACE_EVERYTHING);
/**
* Clips a ray to a particular entity.
*
* @param pos Starting position of the ray.
* @param vec Depending on RayType, it will be used as the ending
* point, or the direction angle.
* @param flags Trace flags.
* @param rtype Method to calculate the ray direction.
* @param entity Entity to clip to.
* @return Ray trace handle, which must be closed via CloseHandle().
* @error Invalid entity.
*/
native Handle TR_ClipRayToEntityEx(const float pos[3],
const float vec[3],
int flags,
RayType rtype,
int entity);
/**
* Clips a ray hull to a particular entity.
*
* @param pos Starting position of the ray.
* @param vec Ending position of the ray.
* @param mins Hull minimum size.
* @param maxs Hull maximum size.
* @param flags Trace flags.
* @param entity Entity to clip to.
* @return Ray trace handle, which must be closed via CloseHandle().
* @error Invalid entity.
*/
native Handle TR_ClipRayHullToEntityEx(const float pos[3],
const float vec[3],
const float mins[3],
const float maxs[3],
int flags,
int entity);
/**
* Clips the current global ray (or hull) to a particular entity.
*
* @param flags Trace flags.
* @param entity Entity to clip to.
* @return Ray trace handle, which must be closed via CloseHandle().
* @error Invalid entity.
*/
native Handle TR_ClipCurrentRayToEntityEx(int flags, int entity);
/**
* Returns the time fraction from a trace result (1.0 means no collision).
*
* @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result.
* @return Time fraction value of the trace.
* @error Invalid Handle.
*/
native float TR_GetFraction(Handle hndl=INVALID_HANDLE);
/**
* Returns the time fraction from a trace result when it left a solid.
* Only valid if trace started in solid
*
* @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result.
* @return Time fraction left solid value of the trace.
* @error Invalid Handle.
*/
native float TR_GetFractionLeftSolid(Handle hndl=INVALID_HANDLE);
/**
* Returns the starting position of a trace.
*
* @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result.
* @param pos Vector buffer to store data in.
* @error Invalid Handle.
*/
native void TR_GetStartPosition(Handle hndl, float pos[3]);
/**
* Returns the collision position of a trace result.
*
* @param pos Vector buffer to store data in.
* @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result.
* @error Invalid Handle.
*/
native void TR_GetEndPosition(float pos[3], Handle hndl=INVALID_HANDLE);
/**
* Returns the entity index that collided with the trace.
*
* @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result.
* @return Entity index or -1 for no collision.
* @error Invalid Handle.
*/
native int TR_GetEntityIndex(Handle hndl=INVALID_HANDLE);
/**
* Returns the displacement flags for the surface that was hit. See DISPSURF_FLAG_*.
*
* @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result.
* @return Displacement flags.
* @error Invalid Handle.
*/
native int TR_GetDisplacementFlags(Handle hndl=INVALID_HANDLE);
/**
* Returns the name of the surface that was hit.
*
* @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result.
* @param buffer Buffer to store surface name in
* @param maxlen Maximum length of output buffer
* @error Invalid Handle.
*/
native void TR_GetSurfaceName(Handle hndl, char[] buffer, int maxlen);
/**
* Returns the surface properties index of the surface that was hit.
*
* @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result.
* @return Surface props.
* @error Invalid Handle.
*/
native int TR_GetSurfaceProps(Handle hndl=INVALID_HANDLE);
/**
* Returns the surface flags. See SURF_*.
*
* @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result.
* @return Surface flags.
* @error Invalid Handle.
*/
native int TR_GetSurfaceFlags(Handle hndl=INVALID_HANDLE);
/**
* Returns the index of the physics bone that was hit.
*
* @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result.
* @return Physics bone index.
* @error Invalid Handle.
*/
native int TR_GetPhysicsBone(Handle hndl=INVALID_HANDLE);
/**
* Returns whether the entire trace was in a solid area.
*
* @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result.
* @return True if entire trace was in a solid area, otherwise false.
* @error Invalid Handle.
*/
native bool TR_AllSolid(Handle hndl=INVALID_HANDLE);
/**
* Returns whether the initial point was in a solid area.
*
* @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result.
* @return True if initial point was in a solid area, otherwise false.
* @error Invalid Handle.
*/
native bool TR_StartSolid(Handle hndl=INVALID_HANDLE);
/**
* Returns if there was any kind of collision along the trace ray.
*
* @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result.
* @return True if any collision found, otherwise false.
* @error Invalid Handle.
*/
native bool TR_DidHit(Handle hndl=INVALID_HANDLE);
/**
* Returns in which body hit group the trace collided if any.
*
* @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result.
* @return Body hit group.
* @error Invalid Handle.
*/
native int TR_GetHitGroup(Handle hndl=INVALID_HANDLE);
/**
* Returns in which hitbox the trace collided if any.
*
* Note: if the entity that collided with the trace is the world entity,
* then this function doesn't return an hitbox index but a static prop index.
*
* @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result.
* @return Hitbox index (Or static prop index).
* @error Invalid Handle.
*/
native int TR_GetHitBoxIndex(Handle hndl=INVALID_HANDLE);
/**
* Find the normal vector to the collision plane of a trace.
*
* @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result.
* @param normal Vector buffer to store the vector normal to the collision plane
* @error Invalid Handle
*/
native void TR_GetPlaneNormal(Handle hndl, float normal[3]);
/**
* Tests a point to see if it's outside any playable area
*
* @param pos Vector buffer to store data in.
* @return True if outside world, otherwise false.
*/
native bool TR_PointOutsideWorld(float pos[3]);

View File

@@ -0,0 +1,93 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2017 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _sdktools_variant_t_included
#endinput
#endif
#define _sdktools_variant_t_included
/**
* Sets a bool value in the global variant object.
*
* @param val Input value.
*/
native void SetVariantBool(bool val);
/**
* Sets a string in the global variant object.
*
* @param str Input string.
*/
native void SetVariantString(const char[] str);
/**
* Sets an integer value in the global variant object.
*
* @param val Input value.
*/
native void SetVariantInt(int val);
/**
* Sets a floating point value in the global variant object.
*
* @param val Input value.
*/
native void SetVariantFloat(float val);
/**
* Sets a 3D vector in the global variant object.
*
* @param vec Input vector.
*/
native void SetVariantVector3D(const float vec[3]);
/**
* Sets a 3D position vector in the global variant object.
*
* @param vec Input position vector.
*/
native void SetVariantPosVector3D(const float vec[3]);
/**
* Sets a color in the global variant object.
*
* @param color Input color.
*/
native void SetVariantColor(const int color[4]);
/**
* Sets an entity in the global variant object.
*
* @param entity Entity index.
* @error Invalid entity index.
*/
native void SetVariantEntity(int entity);

View File

@@ -0,0 +1,143 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This file is part of the SourceMod/SourcePawn SDK.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#if defined _sdktools_voice_included
#endinput
#endif
#define _sdktools_voice_included
/**
* @section voice flags.
*/
#define VOICE_NORMAL 0 /**< Allow the client to listen and speak normally. */
#define VOICE_MUTED 1 /**< Mutes the client from speaking to everyone. */
#define VOICE_SPEAKALL 2 /**< Allow the client to speak to everyone. */
#define VOICE_LISTENALL 4 /**< Allow the client to listen to everyone. */
#define VOICE_TEAM 8 /**< Allow the client to always speak to team, even when dead. */
#define VOICE_LISTENTEAM 16 /**< Allow the client to always hear teammates, including dead ones. */
/**
* @endsection
*/
enum ListenOverride
{
Listen_Default = 0, /**< Leave it up to the game */
Listen_No, /**< Can't hear */
Listen_Yes /**< Can hear */
};
/**
* Called when a client is speaking.
*
* @param client The client index
*/
forward void OnClientSpeaking(int client);
/**
* Called once a client speaking end.
*
* @param client The client index
*/
forward void OnClientSpeakingEnd(int client);
/**
* Set the client listening flags.
*
* @param client The client index
* @param flags The voice flags
* @error Invalid client index or client not connected.
*/
native void SetClientListeningFlags(int client, int flags);
/**
* Retrieve the client current listening flags.
*
* @param client The client index
* @return The current voice flags
* @error Invalid client index or client not connected.
*/
native int GetClientListeningFlags(int client);
/**
* Set the receiver ability to listen to the sender.
*
* @param iReceiver The listener index.
* @param iSender The sender index.
* @param bListen True if the receiver can listen to the sender, false otherwise.
* @return True if successful otherwise false.
* @deprecated Use SetListenOverride() instead.
*/
#pragma deprecated Use SetListenOverride() instead
native bool SetClientListening(int iReceiver, int iSender, bool bListen);
/**
* Retrieves if the receiver can listen to the sender.
*
* @param iReceiver The listener index.
* @param iSender The sender index.
* @return True if successful otherwise false.
* @deprecated GetListenOverride() instead.
*/
#pragma deprecated GetListenOverride() instead
native bool GetClientListening(int iReceiver, int iSender);
/**
* Override the receiver's ability to listen to the sender.
*
* @param iReceiver The listener index.
* @param iSender The sender index.
* @param override The override of the receiver's ability to listen to the sender.
* @return True if successful otherwise false.
* @error Listener or sender client index is invalid or not connected.
*/
native bool SetListenOverride(int iReceiver, int iSender, ListenOverride override);
/**
* Retrieves the override of the receiver's ability to listen to the sender.
*
* @param iReceiver The listener index.
* @param iSender The sender index.
* @return The override value.
* @error Listener or sender client index is invalid or not connected.
*/
native ListenOverride GetListenOverride(int iReceiver, int iSender);
/**
* Retrieves if the muter has muted the mutee.
*
* @param iMuter The muter index.
* @param iMutee The mutee index.
* @return True if muter has muted mutee, false otherwise.
* @error Muter or mutee client index is invalid or not connected.
*/
native bool IsClientMuted(int iMuter, int iMutee);

View File

@@ -0,0 +1,190 @@
stock Downloader_GetMaterialsFromMDL(const String:model[], String:files[][], maxsize, maxlen)
{
if(!FileExists(model))
return 0;
new m_iNum = 0;
new Handle:m_hFile = OpenFile(model, "rb");
FileSeek(m_hFile, 204, SEEK_SET);
ReadFileCell(m_hFile, m_iNum, 4);
FileSeek(m_hFile, 0, SEEK_END);
decl m_cChar;
decl m_iPos;
do
{
FileSeek(m_hFile, -2, SEEK_CUR);
ReadFileCell(m_hFile, m_cChar, 1);
} while (m_cChar == 0);
FileSeek(m_hFile, 1, SEEK_CUR);
decl String:m_szPath[PLATFORM_MAX_PATH];
do
{
FileSeek(m_hFile, -2, SEEK_CUR);
ReadFileCell(m_hFile, m_cChar, 1);
} while(m_cChar != 0);
m_iPos = FilePosition(m_hFile);
ReadFileString(m_hFile, m_szPath, sizeof(m_szPath));
FileSeek(m_hFile, m_iPos, SEEK_SET);
decl m_iRet;
decl String:m_szFile[PLATFORM_MAX_PATH];
for(m_iRet=0;m_iRet<m_iNum;++m_iRet)
{
if(m_iNum == maxsize)
break;
FileSeek(m_hFile, -1, SEEK_CUR);
do
{
FileSeek(m_hFile, -2, SEEK_CUR);
ReadFileCell(m_hFile, m_cChar, 1);
} while(m_cChar != 0);
m_iPos = FilePosition(m_hFile);
ReadFileString(m_hFile, m_szFile, sizeof(m_szFile));
Format(files[m_iRet], maxlen, "materials\\%s%s.vmt", m_szPath, m_szFile);
FileSeek(m_hFile, m_iPos, SEEK_SET);
}
return m_iRet;
}
new String:g_szModelExts[][16] = {".phy", ".sw.vtx", ".dx80.vtx", ".dx90.vtx", ".vtx", ".xbox.vtx", ".vvd"};
stock Downloader_GetModelFiles(const String:model[], String:files[][], maxsize, maxlen)
{
decl String:m_szRawPath[PLATFORM_MAX_PATH];
strcopy(m_szRawPath, sizeof(m_szRawPath), model);
new m_iDot = FindCharInString(m_szRawPath, '.', true);
if(m_iDot == -1)
return 0;
m_szRawPath[m_iDot] = 0;
new m_iNum = 0;
for(new i=0;i<sizeof(g_szModelExts);++i)
{
if(m_iNum == maxsize)
break;
Format(files[m_iNum], maxlen, "%s%s", m_szRawPath, g_szModelExts[i]);
if(FileExists(files[m_iNum]))
++m_iNum;
}
return m_iNum;
}
new String:g_szMaterialKeys[][64] = {"$baseTexture", "$bumpmap", "$lightwarptexture"};
stock Downloader_GetMaterialsFromVMT(const String:vmt[], String:materials[][], maxsize, maxlen)
{
if(!FileExists(vmt))
return 0;
decl String:m_szLine[512];
new Handle:m_hFile = OpenFile(vmt, "r");
new bool:m_bFound[sizeof(g_szMaterialKeys)];
decl m_iPos;
decl m_iLast;
new m_iNum = 0;
while(ReadFileLine(m_hFile, m_szLine, sizeof(m_szLine))!=false)
{
if(m_iNum == sizeof(g_szMaterialKeys) || maxsize == m_iNum)
break;
for(new i=0;i<sizeof(g_szMaterialKeys);++i)
{
if(m_bFound[i])
continue;
if((m_iPos = StrContains(m_szLine, g_szMaterialKeys[i], false)) > 0)
{
m_bFound[i]=true;
while(m_szLine[m_iPos] != '"' && m_szLine[m_iPos] != ' ' && m_szLine[m_iPos] != ' ')
++m_iPos;
while(m_szLine[m_iPos] == ' ' || m_szLine[m_iPos] == ' ' || m_szLine[m_iPos] == '"')
++m_iPos;
m_iLast = m_iPos;
while(m_szLine[m_iLast] != '"' && m_szLine[m_iLast] != '\r' && m_szLine[m_iLast] != '\n' && m_szLine[m_iLast] != ' ' && m_szLine[m_iLast] != ' ' && m_szLine[m_iLast] != 0)
++m_iLast;
m_szLine[m_iLast] = 0;
strcopy(materials[m_iNum], maxlen, m_szLine[m_iPos]);
++m_iNum;
}
}
}
CloseHandle(m_hFile);
return m_iNum;
}
new Handle:g_hCachedFiles = INVALID_HANDLE;
new Handle:g_hCachedNums = INVALID_HANDLE;
stock Downloader_AddFileToDownloadsTable(const String:filename[])
{
if(!FileExists(filename))
return 0;
if(g_hCachedNums == INVALID_HANDLE)
{
g_hCachedNums = CreateTrie();
g_hCachedFiles = CreateArray(PLATFORM_MAX_PATH);
}
AddFileToDownloadsTable(filename);
decl m_iValue;
if(GetTrieValue(g_hCachedNums, filename, m_iValue))
{
new m_iStart = FindStringInArray(g_hCachedFiles, filename)+1;
decl String:m_szFile[PLATFORM_MAX_PATH];
for(new i=m_iStart-m_iValue-1;i<m_iStart-1;++i)
{
GetArrayString(g_hCachedFiles, i, m_szFile, sizeof(m_szFile));
AddFileToDownloadsTable(m_szFile);
}
return true;
}
decl String:m_szExt[16];
new m_iDot = FindCharInString(filename, '.', true);
if(m_iDot == -1)
return true;
new m_iNumFiles = 0;
strcopy(m_szExt, sizeof(m_szExt), filename[m_iDot]);
decl String:m_szMaterials[16][PLATFORM_MAX_PATH];
decl m_iNum;
if(strcmp(m_szExt, ".mdl") == 0)
{
decl String:m_szFiles[sizeof(g_szModelExts)][PLATFORM_MAX_PATH];
m_iNum = Downloader_GetModelFiles(filename, m_szFiles, sizeof(m_szFiles), sizeof(m_szFiles[]));
for(new i=0;i<m_iNum;++i)
m_iNumFiles += Downloader_AddFileToDownloadsTable(m_szFiles[i])+1;
m_iNum = Downloader_GetMaterialsFromMDL(filename, m_szMaterials, sizeof(m_szMaterials), sizeof(m_szMaterials[]));
for(new i=0;i<m_iNum;++i)
{
if(FileExists(m_szMaterials[i]))
m_iNumFiles += Downloader_AddFileToDownloadsTable(m_szMaterials[i])+1;
}
} else if(strcmp(m_szExt, ".vmt") == 0)
{
m_iNum = Downloader_GetMaterialsFromVMT(filename, m_szMaterials, sizeof(m_szMaterials), sizeof(m_szMaterials[]));
decl String:m_szMaterial[PLATFORM_MAX_PATH];
for(new i=0;i<m_iNum;++i)
{
Format(m_szMaterial, sizeof(m_szMaterial), "materials\\%s.vtf", m_szMaterials[i]);
if(FileExists(m_szMaterial))
m_iNumFiles += Downloader_AddFileToDownloadsTable(m_szMaterial)+1;
}
}
PushArrayString(g_hCachedFiles, filename);
SetTrieValue(g_hCachedNums, filename, m_iNumFiles);
return m_iNumFiles;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,32 @@
#if defined _smlib_included
#endinput
#endif
#define _smlib_included
#define SMLIB_VERSION "0.9.7"
#include <smlib/general>
#include <smlib/arrays>
#include <smlib/clients>
#include <smlib/colors>
#include <smlib/concommands>
#include <smlib/convars>
#include <smlib/crypt>
#include <smlib/debug>
#include <smlib/dynarrays>
#include <smlib/edicts>
#include <smlib/effects>
#include <smlib/entities>
#include <smlib/files>
#include <smlib/game>
#include <smlib/math>
#include <smlib/menus>
//#include <smlib/pluginmanager>
#include <smlib/server>
#include <smlib/strings>
#include <smlib/sql>
#include <smlib/teams>
#include <smlib/vehicles>
#include <smlib/weapons>
#include <smlib/world>

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