diff --git a/lib/LandLighting.cpp b/lib/LandLighting.cpp index 651b8a4a..acd4f74b 100644 --- a/lib/LandLighting.cpp +++ b/lib/LandLighting.cpp @@ -1,717 +1,717 @@ -#include "wpch.hpp" - -#if _ARMA3_NEW_LIGHTING_CFG - -#include "landLighting.hpp" -#include "El/ParamFile/paramFile.hpp" -#include "paramFileExt.hpp" -#include "global.hpp" - -/// returns if given floats are approximately equal (with given epsilon toleration) -inline bool floatApproxEq(float a, float b, float epsilon = 0.0001f) {return fabs(a-b) <= epsilon;} - -/// F9 / ciclo 9 - pequeno ganho de saturacao, usado para dar profundidade ao ceu. -static Color SkyBoostSaturation(const Color &c, float amount) -{ - float lum = c.R()*0.299f + c.G()*0.587f + c.B()*0.114f; - return Color( - lum + (c.R()-lum)*(1.0f+amount), - lum + (c.G()-lum)*(1.0f+amount), - lum + (c.B()-lum)*(1.0f+amount), - c.A() - ); -} - -// [F10] rebuild forcado -//=================================================================== -// Implementation of LandLighting::Item -//=================================================================== -LandLighting::Item::Item() -:_cosSun(0) -,_sunOrMoon(1) -,_ambient(0,0,0, 0) -,_ambientCloud(0,0,0, 0) -,_diffuse(1,1,1,1) -,_diffuseCloud(1,1,1,1) -,_groundReflection(0,0,0,0) -,_groundReflectionCloud(0,0,0,0) -,_bidirect(0,0,0,0) -,_bidirectCloud(0,0,0,0) -,_sky(0,0,0,0) -,_skyAroundSun(0,0,0,0) -,_desiredLuminanceCoef(1) -,_desiredLuminanceCoefCloud(1) -,_luminanceRectCoef(1) -,_luminanceRectCoefCloud(1) -,_rayleigh(0,0,0,0) -,_mie(0,0,0,0) -,_cloudsColor(1,1,1,1) -,_swBrightness(1) -{} - -void LandLighting::Item::Load(ParamEntryPar entry) -{ - float sunAngle = 0; - - if (entry.IsArray()) - { - _height = entry[0]; - _overcast = entry[1]; - sunAngle = entry[2]; - _sunOrMoon = entry[3]; - } - else - { - // read values as separate config values - _height = entry >> "height"; - _overcast = entry >> "overcast"; - sunAngle = entry >> "sunAngle"; - _sunOrMoon = entry >> "sunOrMoon"; - } - - // note: we want cos from vertical, but angle from horizontal is given instead - // cos (pi/2-x) = sin(x) - _cosSun = sin(sunAngle*(H_PI / 180.0f)); - - /// load remaining data - LoadData(entry, ArrayDataStart); -} - -void LandLighting::Item::LoadData(ParamEntryPar entry, int base) -{ - if (entry.IsArray()) - { - // read values as array - int n = entry.GetSize(); - for (int i=base; i> "diffuse"); - GetHDRColor(_ambient,entry >> "ambient"); - GetHDRColor(_diffuseCloud,entry >> "diffuseCloud"); - GetHDRColor(_ambientCloud,entry >> "ambientCloud"); - - GetHDRColor(_groundReflection,entry >> "groundReflection"); - GetHDRColor(_groundReflectionCloud,entry >> "groundReflectionCloud"); - GetHDRColor(_bidirect,entry >> "bidirect"); - GetHDRColor(_bidirectCloud,entry >> "bidirectCloud"); - - GetHDRColor(_sky,entry >> "sky"); - GetHDRColor(_skyAroundSun,entry >> "skyAroundSun"); - - _desiredLuminanceCoef = entry >> "desiredLuminanceCoef"; - _desiredLuminanceCoefCloud = entry >> "desiredLuminanceCoefCloud"; - _luminanceRectCoef = entry >> "luminanceRectCoef"; - _luminanceRectCoefCloud = entry >> "luminanceRectCoefCloud"; - - GetHDRColor(_rayleigh,entry >> "rayleigh"); - GetHDRColor(_mie,entry >> "mie"); - GetHDRColor(_cloudsColor,entry >> "cloudsColor"); - _swBrightness = entry >> "swBrightness"; - } - - // first entry is actually not diffuse, but max. direct light, i.e. ambient + diffuse - // TODO - ? ask gugla how he wants it - //_diffuse = _diffuse - _ambient; - //_diffuseCloud = _diffuseCloud - _ambientCloud; - - _diffuse.SaturateZero(); - _ambient.SaturateZero(); - _diffuseCloud.SaturateZero(); - _ambientCloud.SaturateZero(); - _groundReflection.SaturateZero(); - _groundReflectionCloud.SaturateZero(); - _bidirect.SaturateZero(); - _bidirectCloud.SaturateZero(); - _sky.SaturateZero(); - _skyAroundSun.SaturateZero(); - - // alpha has no value here - set it to 1 to avoid possible artifacts - _diffuse.SetA(1); - _ambient.SetA(1); - _diffuseCloud.SetA(1); - _ambientCloud.SetA(1); - _groundReflection.SetA(1); - _groundReflectionCloud.SetA(1); - _bidirect.SetA(1); - _bidirectCloud.SetA(1); - _sky.SetA(1); - _skyAroundSun.SetA(1); -} - -void LandLighting::Item::InterpolateWith(const Item& other, float coef, Item& result) const -{ - result._sunOrMoon = GetInterpolatedValue(coef, _sunOrMoon, other._sunOrMoon); - result._ambient = GetInterpolatedValue(coef, _ambient, other._ambient); - result._ambientCloud = GetInterpolatedValue(coef, _ambientCloud, other._ambientCloud); - result._diffuse = GetInterpolatedValue(coef, _diffuse, other._diffuse); - result._diffuseCloud = GetInterpolatedValue(coef, _diffuseCloud, other._diffuseCloud); - result._groundReflection = GetInterpolatedValue(coef, _groundReflection, other._groundReflection); - result._groundReflectionCloud = GetInterpolatedValue(coef, _groundReflectionCloud, other._groundReflectionCloud); - result._bidirect = GetInterpolatedValue(coef, _bidirect, other._bidirect); - result._bidirectCloud = GetInterpolatedValue(coef, _bidirectCloud, other._bidirectCloud); - result._sky = GetInterpolatedValue(coef, _sky, other._sky); - result._skyAroundSun = GetInterpolatedValue(coef, _skyAroundSun, other._skyAroundSun); - result._desiredLuminanceCoef = GetInterpolatedValue(coef, _desiredLuminanceCoef, other._desiredLuminanceCoef); - result._desiredLuminanceCoefCloud = GetInterpolatedValue(coef, _desiredLuminanceCoefCloud, other._desiredLuminanceCoefCloud); - result._luminanceRectCoef = GetInterpolatedValue(coef, _luminanceRectCoef, other._luminanceRectCoef); - result._luminanceRectCoefCloud = GetInterpolatedValue(coef, _luminanceRectCoefCloud, other._luminanceRectCoefCloud); - result._rayleigh = GetInterpolatedValue(coef, _rayleigh, other._rayleigh); - result._mie = GetInterpolatedValue(coef, _mie, other._mie); - result._cloudsColor = GetInterpolatedValue(coef, _cloudsColor, other._cloudsColor); - result._swBrightness = GetInterpolatedValue(coef, _swBrightness, other._swBrightness); -} - -// [F10] rebuild forcado -//=================================================================== -// Implementation of LandLighting::LightingResult -//=================================================================== -LandLighting::LightingResult::LightingResult() -:_sunOrMoon(1) -,_diffuse(1,1,1,1) -,_ambient(0,0,0,0) -,_sun(1,1,1,1) -,_groundReflection(0,0,0,0) -,_bidirect(0,0,0,0) -,_sky(1,1,1,1) -,_skyAroundSun(1,1,1,1) -,_desiredLuminanceCoef(1) -,_luminanceRectCoef(1) -,_rayleigh(0,0,0,0) -,_mie(0,0,0,0) -,_cloudsColor(1,1,1,1) -,_swBrightness(1) -{ - -} - -void LandLighting::LightingResult::InitFrom(const LandLighting::Item& item, float cloud, float cosSun) -{ - // [F9-DIAG] mostra o relogio real do client a cada 5s (temporario). - { - static DWORD s_lastClockLog = 0; - DWORD nowMs = GetTickCount(); - if (nowMs - s_lastClockLog > 5000) - { - s_lastClockLog = nowMs; - Clock &cw = Glob.clockWeather; - tm t = {0}; - cw.GetDate(t); - RptF("F9-clock tod=%.2fh clock=%.2fh date=%04d-%02d-%02d %02d:%02d", - cw.GetTimeOfDay()*24.0f, Glob.clock.GetTimeOfDay()*24.0f, - t.tm_year+1900, t.tm_mon+1, t.tm_mday, t.tm_hour, t.tm_min); - } - } - - _sunOrMoon = item.GetSunOrMoon(); - _diffuse = item.GetDiffuse(cloud); - _ambient = item.GetAmbient(cloud); - _groundReflection = item.GetGroundReflection(cloud); - _bidirect = item.GetBiDirect(cloud); - _sky = item.GetSky(); - _skyAroundSun = item.GetSkyAroundSun(); - _desiredLuminanceCoef = item.GetDesiredLuminanceCoef(cloud); - _luminanceRectCoef = item.GetLuminanceRectCoef(cloud); - _mie = item.GetMie(); - _rayleigh = item.GetRayleigh(); - _cloudsColor = item.GetCloudsColor(); - _swBrightness = item.GetSWBrightness(); - - _sun = item.GetDiffuse(); - _sun.SaturateMax(_skyAroundSun); - - // ---- F9 / ciclo 9 - ceu ---- - // Amplia a profundidade do ceu de dia e o calor do nascer/por do sol. - // E o que o 0.62 tem e o 0.45 nao: transicoes atmosfericas de verdade. - // [F10] usa o cos do sol REAL (antes usava o cos gravado no item da tabela, - // que e constante e nunca batia com a hora do jogo -> poente nunca aparecia). - // 1 quando o sol esta no horizonte, 0 no alto do ceu (e a noite tambem) - float horizon = 1.0f - floatMinMax(fabsf(cosSun) / 0.35f, 0.0f, 1.0f); - horizon *= horizon; - // 1 durante o dia - float day = floatMinMax((cosSun - 0.10f) / 0.45f, 0.0f, 1.0f); - - // ceu de dia mais profundo (saturacao) - _sky = SkyBoostSaturation(_sky, 0.20f * day); - _skyAroundSun = SkyBoostSaturation(_skyAroundSun, 0.25f * day); - - // nascer/por do sol: lado do sol quente, ceu com tom de poente - _skyAroundSun = Color( - _skyAroundSun.R() * (1.0f + 2.40f * horizon) * (1.0f - 0.15f * horizon), - _skyAroundSun.G() * (1.0f + 0.40f * horizon) * (1.0f - 0.15f * horizon), - _skyAroundSun.B() * (1.0f - 0.78f * horizon) * (1.0f - 0.15f * horizon), - _skyAroundSun.A() - ); - // escurece o ceu junto com o calor: sem isto o HDR estoura em branco - // e a cor (o laranja) some no tonemap. - float duskDim = 1.0f - 0.60f * horizon; - _sky = Color( - _sky.R() * (1.0f + 2.20f * horizon) * duskDim, - _sky.G() * (1.0f + 0.35f * horizon) * duskDim, - _sky.B() * (1.0f - 0.72f * horizon) * duskDim, - _sky.A() - ); - - // nuvens douradas no nascer/por do sol (a foto de referencia) - _cloudsColor = Color( - _cloudsColor.R() * (1.0f + 1.60f * horizon) * (1.0f - 0.25f * horizon), - _cloudsColor.G() * (1.0f + 0.25f * horizon) * (1.0f - 0.25f * horizon), - _cloudsColor.B() * (1.0f - 0.60f * horizon) * (1.0f - 0.25f * horizon), - _cloudsColor.A() - ); - - // [F10] O ceu visivel no 0.45 e o Simul Weather (scattering atmosferico): - // ele ignora _sky e usa Mie / Rayleigh / brilho. Sem mexer nisto nao ha poente. - _rayleigh = Color( - _rayleigh.R() * (1.0f + 1.40f * horizon), - _rayleigh.G() * (1.0f + 0.25f * horizon), - _rayleigh.B() * (1.0f - 0.55f * horizon), - _rayleigh.A() - ); - _mie = Color( - _mie.R() * (1.0f + 3.50f * horizon), - _mie.G() * (1.0f + 1.40f * horizon), - _mie.B() * (1.0f + 0.25f * horizon), - _mie.A() - ); - _swBrightness *= (1.0f - 0.35f * horizon); - - // nuvens douradas no nascer/por do sol (a foto de referencia) - _cloudsColor = Color( - _cloudsColor.R() * (1.0f + 0.50f * horizon), - _cloudsColor.G() * (1.0f + 0.15f * horizon), - _cloudsColor.B() * (1.0f - 0.28f * horizon), - _cloudsColor.A() - ); - - _sky.SaturateZero(); - _skyAroundSun.SaturateZero(); - _cloudsColor.SaturateZero(); - - // log de calibracao: uma linha a cada mudanca relevante de altura do sol - static float s_lastLoggedCos = 2.0f; - if (fabsf(cosSun - s_lastLoggedCos) > 0.15f) - { - s_lastLoggedCos = cosSun; - float todH = Glob.clockWeather.GetTimeOfDay() * 24.0f; - float todClockH = Glob.clock.GetTimeOfDay() * 24.0f; - RptF("F9-sky tod=%.2fh clock=%.2fh cosSun=%.3f horizon=%.2f day=%.2f sky=(%.2f,%.2f,%.2f) around=(%.2f,%.2f,%.2f) clouds=(%.2f,%.2f,%.2f) mie=(%.4f,%.4f,%.4f) ray=(%.4f,%.4f,%.4f) sw=%.3f", - todH, todClockH, cosSun, horizon, day, - _sky.R(), _sky.G(), _sky.B(), - _skyAroundSun.R(), _skyAroundSun.G(), _skyAroundSun.B(), - _cloudsColor.R(), _cloudsColor.G(), _cloudsColor.B(), - _mie.R(), _mie.G(), _mie.B(), - _rayleigh.R(), _rayleigh.G(), _rayleigh.B(), - _swBrightness); - } -} - -// [F10] rebuild forcado -//=================================================================== -// Implementation of LandLighting -//=================================================================== -LandLighting::LandLighting() -{ - -} - -void LandLighting::Load(ParamEntryPar entry) -{ - _items.Clear(); - - int count = entry.GetEntryCount(); - for (int i=0; i< count; ++i) - { - ParamEntryVal itemEntry= entry.GetEntry(i); - if (!itemEntry.IsClass()) - continue; //skip all non-class entries - Item item; - item.Load(itemEntry); - AddItem(item); - } - - _items.Compact(); - -#if 0 && _ENABLE_REPORT - DebugOutputItems(); -#endif -} - -/// writes all items to output -void LandLighting::DebugOutputItems() -{ - for (int heightIndex=0; heightIndex<_items.Size(); ++heightIndex) - { - for (int overcastIndex = 0; overcastIndex < _items[heightIndex].Size(); ++overcastIndex) - { - for (int i=0; i < _items[heightIndex][overcastIndex].Size(); ++i) - { - const Item& item = _items[heightIndex][overcastIndex][i]; - LogF("height: %f, overcast: %f, cosSun: %f", item.GetHeight(), item.GetOvercast(), item.GetCosSun()); - } - } - } - -} - -void LandLighting::AddItem(const LandLighting::Item& item) -{ - // first try to find corresponding height slot - int foundHeightIndex = -1; - for (int heightIndex=0; heightIndex<_items.Size(); ++heightIndex) - { - if (_items[heightIndex].Size() > 0 && _items[heightIndex][0].Size() > 0 ) - { - if (floatApproxEq(_items[heightIndex][0][0].GetHeight(), item.GetHeight())) - { - foundHeightIndex = heightIndex; - break; //found - } - } - } - - if (-1 == foundHeightIndex) - { - // lets find where to insert new array - int insertIndex = 0; - for (insertIndex=0; insertIndex<_items.Size(); ++insertIndex) - { - if (_items[insertIndex].Size() > 0 && _items[insertIndex][0].Size() > 0 && _items[insertIndex][0][0].GetHeight() > item.GetHeight()) - break; - } - - TItemList2& newHeightList = _items.Insert(insertIndex); - TItemList& newOvercastList = newHeightList.Append(); - newOvercastList.Add(item); - return; - } - - // try to find corresponding overcast slot - int foundOvercastIndex = -1; - for (int overcastIndex=0; overcastIndex < _items[foundHeightIndex].Size(); ++overcastIndex) - { - if (_items[foundHeightIndex][overcastIndex].Size() > 0) - { - if (floatApproxEq(_items[foundHeightIndex][overcastIndex][0].GetOvercast(), item.GetOvercast())) - { - foundOvercastIndex = overcastIndex; - break; //found - } - } - } - - if (-1 == foundOvercastIndex) - { - // lets find where to insert new array - int insertIndex = 0; - for (insertIndex=0; insertIndex<_items[foundHeightIndex].Size(); ++insertIndex) - { - if (_items[foundHeightIndex][insertIndex].Size() > 0 && _items[foundHeightIndex][insertIndex][0].GetOvercast() > item.GetOvercast()) - break; - } - - // not found, create new - TItemList& newOvercastList = _items[foundHeightIndex].Insert(insertIndex); - newOvercastList.Add(item); - return; - } - - // lets find where to insert new item - int insertIndex = 0; - for (insertIndex=0; insertIndex<_items[foundHeightIndex][foundOvercastIndex].Size(); ++insertIndex) - { - if (_items[foundHeightIndex][foundOvercastIndex][insertIndex].GetCosSun() > item.GetCosSun()) - break; - } - - _items[foundHeightIndex][foundOvercastIndex].Insert(insertIndex, item); -} - -bool LandLighting::GetLighting(LightingResult& result, float height, float overcast, float cosSun, float cloud) const -{ - if (_items.Size() == 0) - return false; - - // find height index - int heightIndex = 0; - for (heightIndex = 0; heightIndex < _items.Size(); ++heightIndex) - { - Assert(_items[heightIndex].Size() > 0 && _items[heightIndex][0].Size() > 0); - if (_items[heightIndex].Size() == 0 || _items[heightIndex][0].Size() == 0) - continue; - - if (_items[heightIndex][0][0].GetHeight() > height) - break; - } - - int index1 = heightIndex-1; - int index2 = heightIndex; - if (index1 < 0) - index1 = 0; - if (index2 >= _items.Size()) - index2 = _items.Size() - 1; - - // coefficient for interpolation - float interpCoef = 0.0f; - if (index1 != index2) - { - // height difference - float height1 = GetHeight(index1); - float height2 = GetHeight(index2); - Assert(height2 > height1 && height >= height1 && height <= height2); - - float diff = height2 - height1; - Assert(diff > 0); - - // compute coef for interpolation - if (diff > 0) - { - interpCoef = (height - height1) / diff; - saturate(interpCoef, 0, 1); - } - } - - Item resultItem; - bool ok = false; - - if (interpCoef < 0.0001f) - { - ok = GetInterpolatedItemHeight(resultItem, index1, overcast, cosSun, cloud); - } - else if (interpCoef > 1.0f - 0.0001f) - { - ok = GetInterpolatedItemHeight(resultItem, index2, overcast, cosSun, cloud); - } - else - { - // interpolate - Item item1; - Item item2; - ok = GetInterpolatedItemHeight(item1, index1, overcast, cosSun, cloud); - ok |= GetInterpolatedItemHeight(item2, index2, overcast, cosSun, cloud); - - if (ok) - item1.InterpolateWith(item2, interpCoef, resultItem); - } - - if (ok) - { - // fill result - result.InitFrom(resultItem, cloud, cosSun); - } - - return ok; -} - -bool LandLighting::GetInterpolatedItemHeight(LandLighting::Item& result, int heightIndex, float overcast, float cosSun, float cloud) const -{ - Assert(heightIndex >= 0 && heightIndex < _items.Size()); - if (heightIndex < 0 || heightIndex >= _items.Size()) - return false; - - Assert(_items[heightIndex].Size() > 0); - if (_items[heightIndex].Size() == 0) - return false; - - // find overcast index - int overcastIndex = 0; - for (overcastIndex = 0; overcastIndex < _items[heightIndex].Size(); ++overcastIndex) - { - Assert(_items[heightIndex][overcastIndex].Size() > 0); - if (_items[heightIndex][overcastIndex].Size() == 0) - continue; - - if (_items[heightIndex][overcastIndex][0].GetOvercast() > overcast) - break; - } - - int index1 = overcastIndex-1; - int index2 = overcastIndex; - if (index1 < 0) - index1 = 0; - if (index2 >= _items[heightIndex].Size()) - index2 = _items[heightIndex].Size() - 1; - - // coefficient for interpolation - float interpCoef = 0.0f; - if (index1 != index2) - { - // height difference - float overcast1 = GetOvercast(heightIndex, index1); - float overcast2 = GetOvercast(heightIndex, index2); - Assert(overcast2 > overcast1 && overcast >= overcast1 && overcast <= overcast2); - - float diff = overcast2 - overcast1; - Assert(diff > 0); - - // compute coef for interpolation - if (diff > 0) - { - interpCoef = (overcast - overcast1) / diff; - saturate(interpCoef, 0, 1); - } - } - - bool ok = false; - - if (interpCoef < 0.0001f) - { - ok = GetInterpolatedItemOvercast(result, heightIndex, index1, cosSun, cloud); - } - else if (interpCoef > 1.0f - 0.0001f) - { - ok = GetInterpolatedItemOvercast(result, heightIndex, index2, cosSun, cloud); - } - else - { - // interpolate - Item item1; - Item item2; - ok = GetInterpolatedItemOvercast(item1, heightIndex, index1, cosSun, cloud); - ok |= GetInterpolatedItemOvercast(item2, heightIndex, index2, cosSun, cloud); - - if (ok) - item1.InterpolateWith(item2, interpCoef, result); - } - - return ok; -} - -bool LandLighting::GetInterpolatedItemOvercast(LandLighting::Item& result, int heightIndex, int overcastIndex, float cosSun, float cloud) const -{ - Assert(heightIndex >= 0 && heightIndex < _items.Size()); - if (heightIndex < 0 || heightIndex >= _items.Size()) - return false; - - Assert(overcastIndex >= 0 && overcastIndex < _items[heightIndex].Size()); - if (overcastIndex < 0 || overcastIndex >= _items[heightIndex].Size()) - return false; - - Assert(_items[heightIndex][overcastIndex].Size() > 0); - if (_items[heightIndex][overcastIndex].Size() == 0) - return false; - - // find item index - int itemIndex = 0; - for (itemIndex = 0; itemIndex < _items[heightIndex][overcastIndex].Size(); ++itemIndex) - { - if (_items[heightIndex][overcastIndex][itemIndex].GetCosSun() > cosSun) - break; - } - - int index1 = itemIndex-1; - int index2 = itemIndex; - if (index1 < 0) - index1 = 0; - if (index2 >= _items[heightIndex][overcastIndex].Size()) - index2 = _items[heightIndex][overcastIndex].Size() - 1; - - // coefficient for interpolation - float interpCoef = 0.0f; - if (index1 != index2) - { - // height difference - float sunCos1 = _items[heightIndex][overcastIndex][index1].GetCosSun(); - float sunCos2 = _items[heightIndex][overcastIndex][index2].GetCosSun(); - Assert(sunCos2 > sunCos1 && cosSun >= sunCos1 && cosSun <= sunCos2); - - float diff = sunCos2 - sunCos1; - Assert(diff > 0); - - // compute coef for interpolation - if (diff > 0) - { - interpCoef = (cosSun - sunCos1) / diff; - saturate(interpCoef, 0, 1); - } - } - - if (interpCoef < 0.0001f) - { - result = _items[heightIndex][overcastIndex][index1]; - } - else if (interpCoef > 1.0f - 0.0001f) - { - result = _items[heightIndex][overcastIndex][index2]; - } - else - { - // interpolate - _items[heightIndex][overcastIndex][index1].InterpolateWith(_items[heightIndex][overcastIndex][index2], interpCoef, result); - } - - return true; -} - -/// clears items list -void LandLighting::Clear() -{ - _items.Clear(); -} - - -#endif //#if _ARMA3_NEW_LIGHTING_CFG +#include "wpch.hpp" + +#if _ARMA3_NEW_LIGHTING_CFG + +#include "landLighting.hpp" +#include "El/ParamFile/paramFile.hpp" +#include "paramFileExt.hpp" +#include "global.hpp" + +/// returns if given floats are approximately equal (with given epsilon toleration) +inline bool floatApproxEq(float a, float b, float epsilon = 0.0001f) {return fabs(a-b) <= epsilon;} + +/// F9 / ciclo 9 - pequeno ganho de saturacao, usado para dar profundidade ao ceu. +static Color SkyBoostSaturation(const Color &c, float amount) +{ + float lum = c.R()*0.299f + c.G()*0.587f + c.B()*0.114f; + return Color( + lum + (c.R()-lum)*(1.0f+amount), + lum + (c.G()-lum)*(1.0f+amount), + lum + (c.B()-lum)*(1.0f+amount), + c.A() + ); +} + +// [F10] rebuild forcado +//=================================================================== +// Implementation of LandLighting::Item +//=================================================================== +LandLighting::Item::Item() +:_cosSun(0) +,_sunOrMoon(1) +,_ambient(0,0,0, 0) +,_ambientCloud(0,0,0, 0) +,_diffuse(1,1,1,1) +,_diffuseCloud(1,1,1,1) +,_groundReflection(0,0,0,0) +,_groundReflectionCloud(0,0,0,0) +,_bidirect(0,0,0,0) +,_bidirectCloud(0,0,0,0) +,_sky(0,0,0,0) +,_skyAroundSun(0,0,0,0) +,_desiredLuminanceCoef(1) +,_desiredLuminanceCoefCloud(1) +,_luminanceRectCoef(1) +,_luminanceRectCoefCloud(1) +,_rayleigh(0,0,0,0) +,_mie(0,0,0,0) +,_cloudsColor(1,1,1,1) +,_swBrightness(1) +{} + +void LandLighting::Item::Load(ParamEntryPar entry) +{ + float sunAngle = 0; + + if (entry.IsArray()) + { + _height = entry[0]; + _overcast = entry[1]; + sunAngle = entry[2]; + _sunOrMoon = entry[3]; + } + else + { + // read values as separate config values + _height = entry >> "height"; + _overcast = entry >> "overcast"; + sunAngle = entry >> "sunAngle"; + _sunOrMoon = entry >> "sunOrMoon"; + } + + // note: we want cos from vertical, but angle from horizontal is given instead + // cos (pi/2-x) = sin(x) + _cosSun = sin(sunAngle*(H_PI / 180.0f)); + + /// load remaining data + LoadData(entry, ArrayDataStart); +} + +void LandLighting::Item::LoadData(ParamEntryPar entry, int base) +{ + if (entry.IsArray()) + { + // read values as array + int n = entry.GetSize(); + for (int i=base; i> "diffuse"); + GetHDRColor(_ambient,entry >> "ambient"); + GetHDRColor(_diffuseCloud,entry >> "diffuseCloud"); + GetHDRColor(_ambientCloud,entry >> "ambientCloud"); + + GetHDRColor(_groundReflection,entry >> "groundReflection"); + GetHDRColor(_groundReflectionCloud,entry >> "groundReflectionCloud"); + GetHDRColor(_bidirect,entry >> "bidirect"); + GetHDRColor(_bidirectCloud,entry >> "bidirectCloud"); + + GetHDRColor(_sky,entry >> "sky"); + GetHDRColor(_skyAroundSun,entry >> "skyAroundSun"); + + _desiredLuminanceCoef = entry >> "desiredLuminanceCoef"; + _desiredLuminanceCoefCloud = entry >> "desiredLuminanceCoefCloud"; + _luminanceRectCoef = entry >> "luminanceRectCoef"; + _luminanceRectCoefCloud = entry >> "luminanceRectCoefCloud"; + + GetHDRColor(_rayleigh,entry >> "rayleigh"); + GetHDRColor(_mie,entry >> "mie"); + GetHDRColor(_cloudsColor,entry >> "cloudsColor"); + _swBrightness = entry >> "swBrightness"; + } + + // first entry is actually not diffuse, but max. direct light, i.e. ambient + diffuse + // TODO - ? ask gugla how he wants it + //_diffuse = _diffuse - _ambient; + //_diffuseCloud = _diffuseCloud - _ambientCloud; + + _diffuse.SaturateZero(); + _ambient.SaturateZero(); + _diffuseCloud.SaturateZero(); + _ambientCloud.SaturateZero(); + _groundReflection.SaturateZero(); + _groundReflectionCloud.SaturateZero(); + _bidirect.SaturateZero(); + _bidirectCloud.SaturateZero(); + _sky.SaturateZero(); + _skyAroundSun.SaturateZero(); + + // alpha has no value here - set it to 1 to avoid possible artifacts + _diffuse.SetA(1); + _ambient.SetA(1); + _diffuseCloud.SetA(1); + _ambientCloud.SetA(1); + _groundReflection.SetA(1); + _groundReflectionCloud.SetA(1); + _bidirect.SetA(1); + _bidirectCloud.SetA(1); + _sky.SetA(1); + _skyAroundSun.SetA(1); +} + +void LandLighting::Item::InterpolateWith(const Item& other, float coef, Item& result) const +{ + result._sunOrMoon = GetInterpolatedValue(coef, _sunOrMoon, other._sunOrMoon); + result._ambient = GetInterpolatedValue(coef, _ambient, other._ambient); + result._ambientCloud = GetInterpolatedValue(coef, _ambientCloud, other._ambientCloud); + result._diffuse = GetInterpolatedValue(coef, _diffuse, other._diffuse); + result._diffuseCloud = GetInterpolatedValue(coef, _diffuseCloud, other._diffuseCloud); + result._groundReflection = GetInterpolatedValue(coef, _groundReflection, other._groundReflection); + result._groundReflectionCloud = GetInterpolatedValue(coef, _groundReflectionCloud, other._groundReflectionCloud); + result._bidirect = GetInterpolatedValue(coef, _bidirect, other._bidirect); + result._bidirectCloud = GetInterpolatedValue(coef, _bidirectCloud, other._bidirectCloud); + result._sky = GetInterpolatedValue(coef, _sky, other._sky); + result._skyAroundSun = GetInterpolatedValue(coef, _skyAroundSun, other._skyAroundSun); + result._desiredLuminanceCoef = GetInterpolatedValue(coef, _desiredLuminanceCoef, other._desiredLuminanceCoef); + result._desiredLuminanceCoefCloud = GetInterpolatedValue(coef, _desiredLuminanceCoefCloud, other._desiredLuminanceCoefCloud); + result._luminanceRectCoef = GetInterpolatedValue(coef, _luminanceRectCoef, other._luminanceRectCoef); + result._luminanceRectCoefCloud = GetInterpolatedValue(coef, _luminanceRectCoefCloud, other._luminanceRectCoefCloud); + result._rayleigh = GetInterpolatedValue(coef, _rayleigh, other._rayleigh); + result._mie = GetInterpolatedValue(coef, _mie, other._mie); + result._cloudsColor = GetInterpolatedValue(coef, _cloudsColor, other._cloudsColor); + result._swBrightness = GetInterpolatedValue(coef, _swBrightness, other._swBrightness); +} + +// [F10] rebuild forcado +//=================================================================== +// Implementation of LandLighting::LightingResult +//=================================================================== +LandLighting::LightingResult::LightingResult() +:_sunOrMoon(1) +,_diffuse(1,1,1,1) +,_ambient(0,0,0,0) +,_sun(1,1,1,1) +,_groundReflection(0,0,0,0) +,_bidirect(0,0,0,0) +,_sky(1,1,1,1) +,_skyAroundSun(1,1,1,1) +,_desiredLuminanceCoef(1) +,_luminanceRectCoef(1) +,_rayleigh(0,0,0,0) +,_mie(0,0,0,0) +,_cloudsColor(1,1,1,1) +,_swBrightness(1) +{ + +} + +void LandLighting::LightingResult::InitFrom(const LandLighting::Item& item, float cloud, float cosSun) +{ + // [F9-DIAG] mostra o relogio real do client a cada 5s (temporario). + { + static DWORD s_lastClockLog = 0; + DWORD nowMs = GetTickCount(); + if (nowMs - s_lastClockLog > 5000) + { + s_lastClockLog = nowMs; + Clock &cw = Glob.clockWeather; + tm t = {0}; + cw.GetDate(t); + RptF("F9-clock tod=%.2fh clock=%.2fh date=%04d-%02d-%02d %02d:%02d", + cw.GetTimeOfDay()*24.0f, Glob.clock.GetTimeOfDay()*24.0f, + t.tm_year+1900, t.tm_mon+1, t.tm_mday, t.tm_hour, t.tm_min); + } + } + + _sunOrMoon = item.GetSunOrMoon(); + _diffuse = item.GetDiffuse(cloud); + _ambient = item.GetAmbient(cloud); + _groundReflection = item.GetGroundReflection(cloud); + _bidirect = item.GetBiDirect(cloud); + _sky = item.GetSky(); + _skyAroundSun = item.GetSkyAroundSun(); + _desiredLuminanceCoef = item.GetDesiredLuminanceCoef(cloud); + _luminanceRectCoef = item.GetLuminanceRectCoef(cloud); + _mie = item.GetMie(); + _rayleigh = item.GetRayleigh(); + _cloudsColor = item.GetCloudsColor(); + _swBrightness = item.GetSWBrightness(); + + _sun = item.GetDiffuse(); + _sun.SaturateMax(_skyAroundSun); + + // ---- F9 / ciclo 9 - ceu ---- + // Amplia a profundidade do ceu de dia e o calor do nascer/por do sol. + // E o que o 0.62 tem e o 0.45 nao: transicoes atmosfericas de verdade. + // [F10] usa o cos do sol REAL (antes usava o cos gravado no item da tabela, + // que e constante e nunca batia com a hora do jogo -> poente nunca aparecia). + // 1 quando o sol esta no horizonte, 0 no alto do ceu (e a noite tambem) + float horizon = 1.0f - floatMinMax(fabsf(cosSun) / 0.35f, 0.0f, 1.0f); + horizon *= horizon; + // 1 durante o dia + float day = floatMinMax((cosSun - 0.10f) / 0.45f, 0.0f, 1.0f); + + // ceu de dia mais profundo (saturacao) + _sky = SkyBoostSaturation(_sky, 0.20f * day); + _skyAroundSun = SkyBoostSaturation(_skyAroundSun, 0.25f * day); + + // nascer/por do sol: lado do sol quente, ceu com tom de poente + _skyAroundSun = Color( + _skyAroundSun.R() * (1.0f + 2.40f * horizon) * (1.0f - 0.15f * horizon), + _skyAroundSun.G() * (1.0f + 0.40f * horizon) * (1.0f - 0.15f * horizon), + _skyAroundSun.B() * (1.0f - 0.78f * horizon) * (1.0f - 0.15f * horizon), + _skyAroundSun.A() + ); + // escurece o ceu junto com o calor: sem isto o HDR estoura em branco + // e a cor (o laranja) some no tonemap. + float duskDim = 1.0f - 0.60f * horizon; + _sky = Color( + _sky.R() * (1.0f + 2.20f * horizon) * duskDim, + _sky.G() * (1.0f + 0.35f * horizon) * duskDim, + _sky.B() * (1.0f - 0.72f * horizon) * duskDim, + _sky.A() + ); + + // nuvens douradas no nascer/por do sol (a foto de referencia) + _cloudsColor = Color( + _cloudsColor.R() * (1.0f + 1.60f * horizon) * (1.0f - 0.25f * horizon), + _cloudsColor.G() * (1.0f + 0.25f * horizon) * (1.0f - 0.25f * horizon), + _cloudsColor.B() * (1.0f - 0.60f * horizon) * (1.0f - 0.25f * horizon), + _cloudsColor.A() + ); + + // [F10] O ceu visivel no 0.45 e o Simul Weather (scattering atmosferico): + // ele ignora _sky e usa Mie / Rayleigh / brilho. Sem mexer nisto nao ha poente. + _rayleigh = Color( + _rayleigh.R() * (1.0f + 1.40f * horizon), + _rayleigh.G() * (1.0f + 0.25f * horizon), + _rayleigh.B() * (1.0f - 0.55f * horizon), + _rayleigh.A() + ); + _mie = Color( + _mie.R() * (1.0f + 3.50f * horizon), + _mie.G() * (1.0f + 1.40f * horizon), + _mie.B() * (1.0f + 0.25f * horizon), + _mie.A() + ); + _swBrightness *= (1.0f - 0.35f * horizon); + + // nuvens douradas no nascer/por do sol (a foto de referencia) + _cloudsColor = Color( + _cloudsColor.R() * (1.0f + 0.50f * horizon), + _cloudsColor.G() * (1.0f + 0.15f * horizon), + _cloudsColor.B() * (1.0f - 0.28f * horizon), + _cloudsColor.A() + ); + + _sky.SaturateZero(); + _skyAroundSun.SaturateZero(); + _cloudsColor.SaturateZero(); + + // log de calibracao: uma linha a cada mudanca relevante de altura do sol + static float s_lastLoggedCos = 2.0f; + if (fabsf(cosSun - s_lastLoggedCos) > 0.15f) + { + s_lastLoggedCos = cosSun; + float todH = Glob.clockWeather.GetTimeOfDay() * 24.0f; + float todClockH = Glob.clock.GetTimeOfDay() * 24.0f; + RptF("F9-sky tod=%.2fh clock=%.2fh cosSun=%.3f horizon=%.2f day=%.2f sky=(%.2f,%.2f,%.2f) around=(%.2f,%.2f,%.2f) clouds=(%.2f,%.2f,%.2f) mie=(%.4f,%.4f,%.4f) ray=(%.4f,%.4f,%.4f) sw=%.3f", + todH, todClockH, cosSun, horizon, day, + _sky.R(), _sky.G(), _sky.B(), + _skyAroundSun.R(), _skyAroundSun.G(), _skyAroundSun.B(), + _cloudsColor.R(), _cloudsColor.G(), _cloudsColor.B(), + _mie.R(), _mie.G(), _mie.B(), + _rayleigh.R(), _rayleigh.G(), _rayleigh.B(), + _swBrightness); + } +} + +// [F10] rebuild forcado +//=================================================================== +// Implementation of LandLighting +//=================================================================== +LandLighting::LandLighting() +{ + +} + +void LandLighting::Load(ParamEntryPar entry) +{ + _items.Clear(); + + int count = entry.GetEntryCount(); + for (int i=0; i< count; ++i) + { + ParamEntryVal itemEntry= entry.GetEntry(i); + if (!itemEntry.IsClass()) + continue; //skip all non-class entries + Item item; + item.Load(itemEntry); + AddItem(item); + } + + _items.Compact(); + +#if 0 && _ENABLE_REPORT + DebugOutputItems(); +#endif +} + +/// writes all items to output +void LandLighting::DebugOutputItems() +{ + for (int heightIndex=0; heightIndex<_items.Size(); ++heightIndex) + { + for (int overcastIndex = 0; overcastIndex < _items[heightIndex].Size(); ++overcastIndex) + { + for (int i=0; i < _items[heightIndex][overcastIndex].Size(); ++i) + { + const Item& item = _items[heightIndex][overcastIndex][i]; + LogF("height: %f, overcast: %f, cosSun: %f", item.GetHeight(), item.GetOvercast(), item.GetCosSun()); + } + } + } + +} + +void LandLighting::AddItem(const LandLighting::Item& item) +{ + // first try to find corresponding height slot + int foundHeightIndex = -1; + for (int heightIndex=0; heightIndex<_items.Size(); ++heightIndex) + { + if (_items[heightIndex].Size() > 0 && _items[heightIndex][0].Size() > 0 ) + { + if (floatApproxEq(_items[heightIndex][0][0].GetHeight(), item.GetHeight())) + { + foundHeightIndex = heightIndex; + break; //found + } + } + } + + if (-1 == foundHeightIndex) + { + // lets find where to insert new array + int insertIndex = 0; + for (insertIndex=0; insertIndex<_items.Size(); ++insertIndex) + { + if (_items[insertIndex].Size() > 0 && _items[insertIndex][0].Size() > 0 && _items[insertIndex][0][0].GetHeight() > item.GetHeight()) + break; + } + + TItemList2& newHeightList = _items.Insert(insertIndex); + TItemList& newOvercastList = newHeightList.Append(); + newOvercastList.Add(item); + return; + } + + // try to find corresponding overcast slot + int foundOvercastIndex = -1; + for (int overcastIndex=0; overcastIndex < _items[foundHeightIndex].Size(); ++overcastIndex) + { + if (_items[foundHeightIndex][overcastIndex].Size() > 0) + { + if (floatApproxEq(_items[foundHeightIndex][overcastIndex][0].GetOvercast(), item.GetOvercast())) + { + foundOvercastIndex = overcastIndex; + break; //found + } + } + } + + if (-1 == foundOvercastIndex) + { + // lets find where to insert new array + int insertIndex = 0; + for (insertIndex=0; insertIndex<_items[foundHeightIndex].Size(); ++insertIndex) + { + if (_items[foundHeightIndex][insertIndex].Size() > 0 && _items[foundHeightIndex][insertIndex][0].GetOvercast() > item.GetOvercast()) + break; + } + + // not found, create new + TItemList& newOvercastList = _items[foundHeightIndex].Insert(insertIndex); + newOvercastList.Add(item); + return; + } + + // lets find where to insert new item + int insertIndex = 0; + for (insertIndex=0; insertIndex<_items[foundHeightIndex][foundOvercastIndex].Size(); ++insertIndex) + { + if (_items[foundHeightIndex][foundOvercastIndex][insertIndex].GetCosSun() > item.GetCosSun()) + break; + } + + _items[foundHeightIndex][foundOvercastIndex].Insert(insertIndex, item); +} + +bool LandLighting::GetLighting(LightingResult& result, float height, float overcast, float cosSun, float cloud) const +{ + if (_items.Size() == 0) + return false; + + // find height index + int heightIndex = 0; + for (heightIndex = 0; heightIndex < _items.Size(); ++heightIndex) + { + Assert(_items[heightIndex].Size() > 0 && _items[heightIndex][0].Size() > 0); + if (_items[heightIndex].Size() == 0 || _items[heightIndex][0].Size() == 0) + continue; + + if (_items[heightIndex][0][0].GetHeight() > height) + break; + } + + int index1 = heightIndex-1; + int index2 = heightIndex; + if (index1 < 0) + index1 = 0; + if (index2 >= _items.Size()) + index2 = _items.Size() - 1; + + // coefficient for interpolation + float interpCoef = 0.0f; + if (index1 != index2) + { + // height difference + float height1 = GetHeight(index1); + float height2 = GetHeight(index2); + Assert(height2 > height1 && height >= height1 && height <= height2); + + float diff = height2 - height1; + Assert(diff > 0); + + // compute coef for interpolation + if (diff > 0) + { + interpCoef = (height - height1) / diff; + saturate(interpCoef, 0, 1); + } + } + + Item resultItem; + bool ok = false; + + if (interpCoef < 0.0001f) + { + ok = GetInterpolatedItemHeight(resultItem, index1, overcast, cosSun, cloud); + } + else if (interpCoef > 1.0f - 0.0001f) + { + ok = GetInterpolatedItemHeight(resultItem, index2, overcast, cosSun, cloud); + } + else + { + // interpolate + Item item1; + Item item2; + ok = GetInterpolatedItemHeight(item1, index1, overcast, cosSun, cloud); + ok |= GetInterpolatedItemHeight(item2, index2, overcast, cosSun, cloud); + + if (ok) + item1.InterpolateWith(item2, interpCoef, resultItem); + } + + if (ok) + { + // fill result + result.InitFrom(resultItem, cloud, cosSun); + } + + return ok; +} + +bool LandLighting::GetInterpolatedItemHeight(LandLighting::Item& result, int heightIndex, float overcast, float cosSun, float cloud) const +{ + Assert(heightIndex >= 0 && heightIndex < _items.Size()); + if (heightIndex < 0 || heightIndex >= _items.Size()) + return false; + + Assert(_items[heightIndex].Size() > 0); + if (_items[heightIndex].Size() == 0) + return false; + + // find overcast index + int overcastIndex = 0; + for (overcastIndex = 0; overcastIndex < _items[heightIndex].Size(); ++overcastIndex) + { + Assert(_items[heightIndex][overcastIndex].Size() > 0); + if (_items[heightIndex][overcastIndex].Size() == 0) + continue; + + if (_items[heightIndex][overcastIndex][0].GetOvercast() > overcast) + break; + } + + int index1 = overcastIndex-1; + int index2 = overcastIndex; + if (index1 < 0) + index1 = 0; + if (index2 >= _items[heightIndex].Size()) + index2 = _items[heightIndex].Size() - 1; + + // coefficient for interpolation + float interpCoef = 0.0f; + if (index1 != index2) + { + // height difference + float overcast1 = GetOvercast(heightIndex, index1); + float overcast2 = GetOvercast(heightIndex, index2); + Assert(overcast2 > overcast1 && overcast >= overcast1 && overcast <= overcast2); + + float diff = overcast2 - overcast1; + Assert(diff > 0); + + // compute coef for interpolation + if (diff > 0) + { + interpCoef = (overcast - overcast1) / diff; + saturate(interpCoef, 0, 1); + } + } + + bool ok = false; + + if (interpCoef < 0.0001f) + { + ok = GetInterpolatedItemOvercast(result, heightIndex, index1, cosSun, cloud); + } + else if (interpCoef > 1.0f - 0.0001f) + { + ok = GetInterpolatedItemOvercast(result, heightIndex, index2, cosSun, cloud); + } + else + { + // interpolate + Item item1; + Item item2; + ok = GetInterpolatedItemOvercast(item1, heightIndex, index1, cosSun, cloud); + ok |= GetInterpolatedItemOvercast(item2, heightIndex, index2, cosSun, cloud); + + if (ok) + item1.InterpolateWith(item2, interpCoef, result); + } + + return ok; +} + +bool LandLighting::GetInterpolatedItemOvercast(LandLighting::Item& result, int heightIndex, int overcastIndex, float cosSun, float cloud) const +{ + Assert(heightIndex >= 0 && heightIndex < _items.Size()); + if (heightIndex < 0 || heightIndex >= _items.Size()) + return false; + + Assert(overcastIndex >= 0 && overcastIndex < _items[heightIndex].Size()); + if (overcastIndex < 0 || overcastIndex >= _items[heightIndex].Size()) + return false; + + Assert(_items[heightIndex][overcastIndex].Size() > 0); + if (_items[heightIndex][overcastIndex].Size() == 0) + return false; + + // find item index + int itemIndex = 0; + for (itemIndex = 0; itemIndex < _items[heightIndex][overcastIndex].Size(); ++itemIndex) + { + if (_items[heightIndex][overcastIndex][itemIndex].GetCosSun() > cosSun) + break; + } + + int index1 = itemIndex-1; + int index2 = itemIndex; + if (index1 < 0) + index1 = 0; + if (index2 >= _items[heightIndex][overcastIndex].Size()) + index2 = _items[heightIndex][overcastIndex].Size() - 1; + + // coefficient for interpolation + float interpCoef = 0.0f; + if (index1 != index2) + { + // height difference + float sunCos1 = _items[heightIndex][overcastIndex][index1].GetCosSun(); + float sunCos2 = _items[heightIndex][overcastIndex][index2].GetCosSun(); + Assert(sunCos2 > sunCos1 && cosSun >= sunCos1 && cosSun <= sunCos2); + + float diff = sunCos2 - sunCos1; + Assert(diff > 0); + + // compute coef for interpolation + if (diff > 0) + { + interpCoef = (cosSun - sunCos1) / diff; + saturate(interpCoef, 0, 1); + } + } + + if (interpCoef < 0.0001f) + { + result = _items[heightIndex][overcastIndex][index1]; + } + else if (interpCoef > 1.0f - 0.0001f) + { + result = _items[heightIndex][overcastIndex][index2]; + } + else + { + // interpolate + _items[heightIndex][overcastIndex][index1].InterpolateWith(_items[heightIndex][overcastIndex][index2], interpCoef, result); + } + + return true; +} + +/// clears items list +void LandLighting::Clear() +{ + _items.Clear(); +} + + +#endif //#if _ARMA3_NEW_LIGHTING_CFG diff --git a/lib/Network/networkImpl.hpp b/lib/Network/networkImpl.hpp index 498e46e5..a81c59d0 100644 --- a/lib/Network/networkImpl.hpp +++ b/lib/Network/networkImpl.hpp @@ -1,6626 +1,6626 @@ -#ifdef _MSC_VER -#pragma once -#endif - -#ifndef _NETWORK_IMPL_HPP -#define _NETWORK_IMPL_HPP - - -#include "netTransport.hpp" -#include "network.hpp" -#include "../versionNo.h" -#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) -#include -#endif - -#include -#include "../memHeap.hpp" - -#include "../speaker.hpp" -#include "../arcadeWaypoint.hpp" - -#include "../paramFileExt.hpp" - -#include -#include -#include - -#include -#include -#include "Es/Containers/quadtreeEx.hpp" - -#include -#include - -#if _ENABLE_STEAM_MATCHMAKING -# include -# include -#endif - -#include "../AI/ai.hpp" -#include "../house.hpp" - - - -/*! -\file -Internal interface file for multiplayer game (included only from inside of multiplayer files) -*/ - -//! Magic for distinguish applications -#define MAGIC_APP ((int)'D'+((int)'a'<<8)+((int)'y'<<16)+((int)'Z'<<24)) - -/* ArmA 1 values -#elif _DEMO // demo and ArmA do not share LAN sessions - #define MAGIC_APP 0x45454545 -#else // ArmA - #define MAGIC_APP 0x23232323 -#else // ArmA 2 - #define MAGIC_APP 0x25252525 -#endif -*/ - -// old OFP had #define MAGIC_APP 0x00000000 - -#define NO_CLIENT 0 -#define TO_SERVER 1 -// TODO: Avoid usage of this value as regular client ID -#define BOT_CLIENT 2 - -extern const int DiagLevel; -bool DiagFilter(NetworkMessageType type); -RString GetMsgTypeName(NetworkMessageType type); -// extern const char *NetworkMessageTypeNames[]; - -struct NetworkPlayerInfo; -class NetworkServer; - -#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) -class SteamValidation -{ - uint64 _steamId; - NetworkServer *_server; - int _dpid; - bool _started; - bool _authPending; - unsigned long _ticksStarted; - RString _name; - AutoArray _steamSessionTicket; -public: - SteamValidation(); - ~SteamValidation(); - void Start(PlayerIdentity &identity, NetworkServer *server); - void HandleTimeout(); - STEAM_GAMESERVER_CALLBACK(SteamValidation, OnValidateAuthTicketResponse, ValidateAuthTicketResponse_t, _callbackGSAuthTicketResponse); -}; -#endif - -////////////////////////////////////////////////////////////////////////////// -// Network Messages - -//! Encapsulation for block of data transferred over network. -/*! -Implement methods nedded for transfer of NetworkMessage into raw data. -\todo Implement compression methods. -\todo Work with bits, no bytes. -*/ -class NetworkMessageRaw -{ -protected: - //! raw data itself - AutoArray _buffer; - //! read / write position - int _pos; - - //! external raw data - char *_externalBuffer; - //! size of external raw data - int _externalBufferSize; -public: - //! Constructor - NetworkMessageRaw() - {_pos = 0; _buffer.Realloc(1024); _externalBuffer = NULL; _externalBufferSize = 0;} - //! Constructor - /*! - \param buffer external data - \param size size of external data - */ - NetworkMessageRaw(char *buffer, int size) - {_pos = 0; _externalBuffer = buffer; _externalBufferSize = size;} - - //! Return total size of valid data - int GetSize() const {return _externalBuffer ? _externalBufferSize : _buffer.Size();} - //! Set new size of internal buffer, sets position to 0 - void SetSize(int size) {_buffer.Resize(size); _pos = 0;} - //! Get (read only) pointer to valid data - const char *GetData() const {return _externalBuffer ? _externalBuffer : _buffer.Data();} - //! Get (read and write) pointer to internal buffer - char *SetData() {return _buffer.Data();} - //! Return current read / write position in message - int GetPos() const {return _pos;} - - template - void PutSmallUnsigned(IntType value); - - //@{ - //! Write single value to buffer - /*! - \param value value to write - \param compression compression algorithm - */ - void Put(bool value, NetworkCompressionType compression); - void Put(char value, NetworkCompressionType compression); - void Put(int value, NetworkCompressionType compression); - void Put(NetInt64 &value, NetworkCompressionType compression); - void Put(float value, NetworkCompressionType compression); - void Put(RString value, NetworkCompressionType compression); - void Put(RStringB value, NetworkCompressionType compression); - void Put(const LocalizedString &value, NetworkCompressionType compression); - void Put(Time value, NetworkCompressionType compression); - void Put(Vector3Par value, NetworkCompressionType compression); - void Put(Matrix3Par value, NetworkCompressionType compression); - void Put(NetworkId &value, NetworkCompressionType compression); - void Put(CreatorId &value, NetworkCompressionType compression); - void Put(XNADDR &value, NetworkCompressionType compression); - void Put(XONLINE_STAT &value, NetworkCompressionType compression); - void* PutRaw(int size); - - //@} - - //@{ - //! Read single value from buffer - /*! - \param value reference to variable read into - \param compression compression algorithm - \return true if value was read, otherwise false - */ - bool GetNoCompression(RString &value); - bool GetNoCompression(RStringB &value); - - template - bool GetSmallUnsigned(IntType &value); - - bool Get(bool &value, NetworkCompressionType compression); - bool Get(char &value, NetworkCompressionType compression); - bool Get(int &value, NetworkCompressionType compression); - bool Get(NetInt64 &value, NetworkCompressionType compression); - bool Get(float &value, NetworkCompressionType compression); - bool Get(RString &value, NetworkCompressionType compression); - bool Get(RStringB &value, NetworkCompressionType compression); - bool Get(LocalizedString &value, NetworkCompressionType compression); - bool Get(Time &value, NetworkCompressionType compression); - bool Get(Vector3 &value, NetworkCompressionType compression); - bool Get(Matrix3 &value, NetworkCompressionType compression); - bool Get(NetworkId &value, NetworkCompressionType compression); - bool Get(CreatorId &value, NetworkCompressionType compression); - bool Get(XNADDR &value, NetworkCompressionType compression); - bool Get(XONLINE_STAT &value, NetworkCompressionType compression); - void* GetRaw(int size); - //@} - -protected: - //! Write raw data to buffer - /*! - \param buffer raw data - \param size raw data size - */ - void Write(const void *buffer, int size) - { - int minSize = _pos + size; - if (_buffer.Size() < minSize) _buffer.Resize(minSize); - memcpy(_buffer.Data() + _pos, buffer, size); - _pos += size; - } - //! Read raw data from buffer - /*! - \param buffer where read raw data - \param size size of data to read - \return true if data available in buffer, otherwise false - */ - bool Read(void *buffer, int size) - { - int minSize = _pos + size; - if (_externalBuffer) - { - if (_externalBufferSize < minSize) return false; - memcpy(buffer, _externalBuffer + _pos, size); - } - else - { - if (_buffer.Size() < minSize) return false; - memcpy(buffer, _buffer.Data() + _pos, size); - } - _pos += size; - return true; - } -}; -TypeIsMovable(NetworkMessageRaw) - -#define PLAYER_MSG(MessageName, XX) \ - XX(MessageName, int, player, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Unique ID of client (player)"), TRANSF)\ - XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Player's name"), TRANSF)\ - XX(MessageName, bool, server, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Bot client (running in the same process as server)"), TRANSF)\ - XX(MessageName, bool, vonDisabled, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Voice over Net disabled"), TRANSF)\ - XX(MessageName, int, vonCodecQuality, NDTInteger, int, NCTNone, DEFVALUE(int, 3), DOC_MSG("Voice over Net codec quality"), TRANSF)\ - XX(MessageName, bool, battlEye, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("BattlEye is required by the server"), TRANSF)\ - XX(MessageName, NetInt64, steamServerId, NDTInt64, NetInt64, NCTNone, DEFVALUE(NetInt64, 0), DOC_MSG("Steam server id"), TRANSF)\ - XX(MessageName, bool, steamSecure, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Steam VAC protection is active"), TRANSF)\ - XX(MessageName, int, sigVerRequired, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Required signatures version on the server"), TRANSF)\ - /*XX(MessageName, RString, regURL, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("ID Registration URL"), TRANSF)*/\ - XX(MessageName, bool, updatesGuaranteed, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Guaranteed (diffed) updates sent by the server"), TRANSF)\ - -DECLARE_NET_MESSAGE(Player, PLAYER_MSG) - -#define LOGOUT_MSG(MessageName, XX) \ - XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("ID of client (player)"), TRANSF) - -DECLARE_NET_MESSAGE(Logout, LOGOUT_MSG) - -#define PUB_VAR_TO_MSG(MessageName, XX) \ - XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Variable name"), TRANSF) \ - XX(MessageName, AutoArray, value, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Variable value"), TRANSF) \ - XX(MessageName, int, player, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Unique ID of client (player)"), TRANSF) - -DECLARE_NET_MESSAGE_INIT_MSG(PublicVariableTo, PUB_VAR_TO_MSG) - -#define SPAWN_FOR_PLAYER_MSG(MessageName, XX) \ - XX(MessageName, RString, code, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Code to execute"), TRANSF) \ - XX(MessageName, AutoArray, signature, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Code signature to verify it was issued by the server"), TRANSF) \ - XX(MessageName, AutoArray, value, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Parameters"), TRANSF) - -DECLARE_NET_MESSAGE_INIT_MSG(SpawnForPlayer,SPAWN_FOR_PLAYER_MSG) - -TypeIsMovable(SpawnForPlayerMessage); - -#define SYNCHRONIZE_VARIABLE_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(EntityAI), veh, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Variable owner"), TRANSF_REF) \ - XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Variable name"), TRANSF) \ - XX(MessageName, float, coef, NDTFloat, float, NCTFloatMostly0To1, DEFVALUE(float, 0), DOC_MSG("Importance"), TRANSF) \ - XX(MessageName, RString, handler, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Change handler"), TRANSF) \ - -DECLARE_NET_MESSAGE(SynchronizeVariable,SYNCHRONIZE_VARIABLE_MSG) - -#define APPLYWEATHER_MSG(MessageName,XX) \ - XX(MessageName, float,seaLevelOffset, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF) \ - XX(MessageName, float,overcastSetSky, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF) \ - /*XX(MessageName, float,overcastSetClouds, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF)*/ \ - XX(MessageName, float,fogSet, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF) \ - /*XX(MessageName, float,cloudsPos, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF)*/ \ - /*XX(MessageName, float,cloudsAlpha, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF)*/ \ - /*XX(MessageName, float,cloudsBrightness, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF)*/ \ - /*XX(MessageName, float,cloudsSpeed, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF)*/ \ - /*XX(MessageName, float,skyThrough, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF)*/ \ - /*XX(MessageName, float,rainDensity, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF)*/ \ - XX(MessageName, float,wind, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF) \ - XX(MessageName, float,rainDensityWanted, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF) \ - XX(MessageName, float,rainDensitySpeed, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF) \ - XX(MessageName, int,rainNextChange, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ - XX(MessageName, int,nextWeatherChange, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ - XX(MessageName, int,lastWindSpeedChange, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ - XX(MessageName, int,gustUntil, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ - XX(MessageName, Vector3,windSpeed, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG(""), TRANSF) \ - XX(MessageName, Vector3,currentWindSpeed, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG(""), TRANSF) \ - XX(MessageName, Vector3,currentWindSpeedSlow, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG(""), TRANSF) \ - XX(MessageName, Vector3,gust, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG(""), TRANSF) \ - XX(MessageName, int,year, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ - XX(MessageName, int,month, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ - XX(MessageName, int,day, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ - XX(MessageName, int,hour, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ - XX(MessageName, int,minute, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) - -DECLARE_NET_MESSAGE(ApplyWeather, APPLYWEATHER_MSG) - -#if _VBS3 - -#define AARDOUPDATE_MSG(MessageName,XX) \ - XX(MessageName, int, type, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Type of AAR message"), TRANSF) \ - XX(MessageName, int, intType, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("int type can be anything"), TRANSF) \ - XX(MessageName, RString, stringOne , NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("string can be anything"), TRANSF) \ - XX(MessageName, RString, stringTwo , NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("string can be anything"), TRANSF) \ - XX(MessageName, float , floatType , NDTFloat, float, NCTNone, DEFVALUE(float, 0.5), DOC_MSG("float type can be anything"), TRANSF) \ - -DECLARE_NET_MESSAGE(AARDoUpdate, AARDOUPDATE_MSG) - -#define AARASKUPDATE_MSG(MessageName,XX) \ - XX(MessageName, int, type, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Type of AAR message"), TRANSF) \ - XX(MessageName, int, intType, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("int type can be anything"), TRANSF) \ - XX(MessageName, RString, stringOne , NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("string can be anything"), TRANSF) \ - XX(MessageName, RString, stringTwo , NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("string can be anything"), TRANSF) \ - XX(MessageName, float , floatType , NDTFloat, float, NCTNone, DEFVALUE(float, 0.5), DOC_MSG("float type can be anything"), TRANSF) \ - -DECLARE_NET_MESSAGE(AARAskUpdate, AARASKUPDATE_MSG) - - -#define ADDMPREPORT_MSG(MessageName,XX) \ - XX(MessageName, int, type , NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Type of string carried to add to all clients"), TRANSF) \ - XX(MessageName, RString, myString , NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("string can be anything"), TRANSF) \ - -DECLARE_NET_MESSAGE(AddMPReport, ADDMPREPORT_MSG) - -#define LOADISLAND_MSG(MessageName,XX) \ - XX(MessageName, RString, islandName , NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Island to load on the client"), TRANSF) \ - -DECLARE_NET_MESSAGE(LoadIsland, LOADISLAND_MSG) - - -#define ASKCOMMANDEROVERRIDE_MSG(MessageName,XX) \ - XX(MessageName, OLinkPermNO(Turret), turret, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Specification of turret to override"), TRANSF_REF) \ - XX(MessageName, OLinkNO(Turret), overriddenByTurret, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Which turret takes control"), TRANSF_REF) - -DECLARE_NET_MESSAGE(AskCommanderOverride, ASKCOMMANDEROVERRIDE_MSG) - -#endif //_VBS3 - -#define ASK_FOR_SET_ITEM_SHORTCUT_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Player person"), TRANSF_REF) \ - XX(MessageName, int, index, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Shortcut index"), TRANSF)\ - XX(MessageName, OLinkPermO(InventoryItem), item, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Bound inventory item"), TRANSF_REF) \ - XX(MessageName, RString, itemType, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Name of the item type"), TRANSF) \ - -DECLARE_NET_MESSAGE(AskForSetItemShortcut, ASK_FOR_SET_ITEM_SHORTCUT_MSG) - -#define ASK_INVENTORY_MENU_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(Person), unit, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Asked unit"), TRANSF_REF) \ - XX(MessageName, OLinkPermO(InventoryItem), item1, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Involved item"), TRANSF_REF) \ - XX(MessageName, OLinkPermO(InventoryItem), item2, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Involved item"), TRANSF_REF) \ - -DECLARE_NET_MESSAGE(AskInventoryMenu, ASK_INVENTORY_MENU_MSG) - -#define ASK_FOR_THROW_ITEM_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(Man), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person throwing the item"), TRANSF_REF) \ - XX(MessageName, OLinkPermO(InventoryItem), item, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Thrown item"), TRANSF_REF) \ - XX(MessageName, Vector3, pos, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, Vector3(0, 0, 0)), DOC_MSG("item start position in world"), TRANSF) \ - XX(MessageName, Vector3, dir, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, Vector3(0, 0, 0)), DOC_MSG("throw direction"), TRANSF) \ - -DECLARE_NET_MESSAGE(AskForThrowItem, ASK_FOR_THROW_ITEM_MSG) - -#define ASK_FOR_DROP_ITEM_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person dropping the item"), TRANSF_REF) \ - XX(MessageName, OLinkPermO(InventoryItem), item, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Dropped item"), TRANSF_REF) \ - -DECLARE_NET_MESSAGE(AskForDropItem, ASK_FOR_DROP_ITEM_MSG) - -#define ASK_FOR_MOVE_ITEM_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(EntityAI), target, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("New owner of the item"), TRANSF_REF) \ - XX(MessageName, int, index, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Slot index"), TRANSF)\ - XX(MessageName, OLinkPermO(InventoryItem), item, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Moved item"), TRANSF_REF) \ - XX(MessageName, bool, rotated, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Requested inventory orientation"), TRANSF) \ - -DECLARE_NET_MESSAGE(AskForMoveItem, ASK_FOR_MOVE_ITEM_MSG) - -#define ASK_FOR_ROTATE_INVENTORY_ITEM_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Player requesting item rotation"), TRANSF_REF) \ - XX(MessageName, OLinkPermO(InventoryItem), item, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Item to rotate in cargo"), TRANSF_REF) \ - -DECLARE_NET_MESSAGE(AskForRotateInventoryItem, ASK_FOR_ROTATE_INVENTORY_ITEM_MSG) - -#define ASK_FOR_TAKE_ITEM_TO_HANDS_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person holding the item"), TRANSF_REF) \ - XX(MessageName, OLinkPermO(InventoryItem), item, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Held item"), TRANSF_REF) \ - -DECLARE_NET_MESSAGE(AskForTakeItemToHands, ASK_FOR_TAKE_ITEM_TO_HANDS_MSG) - -#define ASK_FOR_SWAP_ITEMS_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(InventoryItem), item1, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Swapping item"), TRANSF_REF) \ - XX(MessageName, OLinkPermO(InventoryItem), item2, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Swapping item"), TRANSF_REF) \ - XX(MessageName, OLinkPermO(Person), owner, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person owning the items"), TRANSF_REF) \ - -DECLARE_NET_MESSAGE(AskForSwapItems, ASK_FOR_SWAP_ITEMS_MSG) - -#define ASK_FOR_PLAYER_ACTION_MSG(MessageName, XX) \ - XX(MessageName, RString, action, NDTString, RString, NCTStringMove, DEFVALUE(RString, ""), DOC_MSG("Action identification"), TRANSF) \ - XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person doing the action (must be owned by the client)"), TRANSF_REF) \ - -DECLARE_NET_MESSAGE(AskForPlayerAction, ASK_FOR_PLAYER_ACTION_MSG) - -#if _VBS3 // respawn command -#define PAUSESIMULATION_MSG(MessageName, XX) \ - XX(MessageName, bool, pause, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Pause local simulation"), TRANSF) - -DECLARE_NET_MESSAGE(PauseSimulation,PAUSESIMULATION_MSG) - -#endif - -#if _ENABLE_ATTACHED_OBJECTS -#define ATTACHOBJECT_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(Object), obj, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Object to attach"), TRANSF_REF) \ - XX(MessageName, OLinkPermO(Object), attachTo, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Object to attach to"), TRANSF_REF) \ - XX(MessageName, int, memIndex, NDTInteger, int, NCTNone, DEFVALUE(int, -1), DOC_MSG("memory point index"), TRANSF) \ - XX(MessageName, Vector3, pos, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, Vector3(0, 0, 0)), DOC_MSG("offset"), TRANSF) \ - XX(MessageName, int, flags, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Additional flags"), TRANSF) - -DECLARE_NET_MESSAGE(AttachObject,ATTACHOBJECT_MSG) - -#define DETACHOBJECT_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(Object), obj, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Object to detach"), TRANSF_REF) - -DECLARE_NET_MESSAGE(DetachObject,DETACHOBJECT_MSG) -#endif - -#define MISSION_PARAMS_MSG(MessageName, XX) \ - XX(MessageName, float, param1, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG("Mission parameter"), TRANSF) \ - XX(MessageName, float, param2, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG("Mission parameter"), TRANSF) \ - XX(MessageName, AutoArray, paramsArray, NDTFloatArray, AutoArray, NCTNone, DEFVALUEFLOATARRAY, DOC_MSG("Array of mission parameters"), TRANSF) \ - XX(MessageName, bool, updateOnly, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Change of params from dialog"), TRANSF) - -DECLARE_NET_MESSAGE(MissionParams, MISSION_PARAMS_MSG) - -#define ANIMATION_PHASE_MSG(MessageName, XX) \ - XX(MessageName, OLink(Entity), vehicle, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Animated vehicle"), TRANSF_REF) \ - XX(MessageName, RString, animation, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Animation ID"), TRANSF) \ - XX(MessageName, float, phase, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG("Animation state (phase)"), TRANSF) - -DECLARE_NET_MESSAGE_INIT_MSG(AskForAnimationPhase,ANIMATION_PHASE_MSG) - -#define VEHICLE_DAMAGED_MSG(MessageName, XX) \ - XX(MessageName, OLink(EntityAI), damaged, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Damaged entity"), TRANSF_REF) \ - XX(MessageName, OLinkPermO(EntityAI), killer, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Entity, causing damage"), TRANSF_REF) \ - XX(MessageName, float, damage, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG("Amount of damage"), TRANSF) \ - XX(MessageName, RString, ammo, NDTString, RString, NCTDefault, DEFVALUE(RString, ""), DOC_MSG("Used ammunition type"), TRANSF) - -DECLARE_NET_MESSAGE(VehicleDamaged, VEHICLE_DAMAGED_MSG) - -#define SERVER_STATE_MSG(MessageName, XX) \ - XX(MessageName, int, serverState, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Server state"), TRANSF) - -DECLARE_NET_MESSAGE(ServerState, SERVER_STATE_MSG) - -#define CLIENT_STATE_MSG(MessageName, XX) \ - XX(MessageName, int, clientState, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Client state"), TRANSF) - -DECLARE_NET_MESSAGE(ClientState, CLIENT_STATE_MSG) - -#define PLAYER_CLIENT_STATE_MSG(MessageName, XX) \ - XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Client (player) id"), TRANSF) \ - XX(MessageName, int, clientState, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Client state"), TRANSF) - -DECLARE_NET_MESSAGE(PlayerClientState, PLAYER_CLIENT_STATE_MSG) - -#define APPLY_IDENTITY_MSG(MessageName, XX) \ - XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Client (player) id"), TRANSF) \ - XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person, which identity will be changed"), TRANSF_REF) - -#define FORCE_DELETE_OBJECT_MSG(MessageName, XX) \ - XX(MessageName, OLinkNO(NetworkObject), object, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Object to destroy"), TRANSF_REF) - -DECLARE_NET_MESSAGE(ForceDeleteObject, FORCE_DELETE_OBJECT_MSG) - -#define MUTE_LIST_MSG(MessageName, XX) \ - XX(MessageName, XUID_ARRAY_TYPE, list, XUID_ARRAY_NET_TYPE, XUID_ARRAY_TYPE, NCTNone, XUID_ARRAY_DEF_VALUE, DOC_MSG("User ids"), TRANSF) - -DECLARE_NET_MESSAGE(MuteList, MUTE_LIST_MSG) - -#define REMOTE_MUTE_LIST_MSG(MessageName, XX) \ - XX(MessageName, AutoArray, list, NDTIntArray, AutoArray, NCTNone, DEFVALUEINTARRAY, DOC_MSG("List of muting players"), TRANSF) - -DECLARE_NET_MESSAGE(RemoteMuteList, REMOTE_MUTE_LIST_MSG) - -#define VOICE_ON_MSG(MessageName, XX) \ - XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Client (player) id"), TRANSF) \ - XX(MessageName, bool, voiceOn, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Voice communicator is connected"), TRANSF) - -DECLARE_NET_MESSAGE(VoiceOn, VOICE_ON_MSG) - -#define CLEANUP_PLAYER_MSG(MessageName, XX) \ - XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Client (player) id"), TRANSF) \ - XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Id of player person"), TRANSF) \ - XX(MessageName, int, id, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Id of player person"), TRANSF) - -DECLARE_NET_MESSAGE(CleanupPlayer, CLEANUP_PLAYER_MSG) - -#define PROCESS_ACTION_MSG(MessageName, XX) \ - XX(MessageName, int, actionType, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, -1), DOC_MSG("Action type"), TRANSF) \ - XX(MessageName, OLink(Object), actionTarget, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Action target"), TRANSF_REF) \ - XX(MessageName, AutoArray, actionParams, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Action parameters based on type"), TRANSF) \ - XX(MessageName, OLinkPermO(Person), unit, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person processing the action"), TRANSF_REF) - -DECLARE_NET_MESSAGE(ProcessAction, PROCESS_ACTION_MSG) - -#define PROCESS_RECIPE_MSG(MessageName, XX) \ - XX(MessageName, RString, recipe, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Recipe name"), TRANSF) \ - XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person executing the recipe"), TRANSF_REF) \ - XX(MessageName, OLinkPermO(InventoryItem), item1, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Item involved in recipe"), TRANSF_REF) \ - XX(MessageName, OLinkPermO(InventoryItem), item2, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Item involved in recipe"), TRANSF_REF) \ - -DECLARE_NET_MESSAGE(ProcessRecipe, PROCESS_RECIPE_MSG) - -#define USE_ITEM_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Owner of the item"), TRANSF_REF) \ - XX(MessageName, OLinkPermO(InventoryItem), item, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Item to use"), TRANSF_REF) \ - -DECLARE_NET_MESSAGE(UseItem, USE_ITEM_MSG) - -#define CHAT_MSG(MessageName, XX) \ - XX(MessageName, int, channel, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Radio channel"), TRANSF) \ - XX(MessageName, OLinkPermO(Person), sender, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Sender unit"), TRANSF_REF) \ - XX(MessageName, RefArray, units, NDTRefArray, AutoArray, NCTNone, DEFVALUEREFARRAY, DOC_MSG("List of receiving units"), TRANSF_REFS) \ - XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Sender name"), TRANSF) \ - XX(MessageName, RString, text, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Message content"), TRANSF) - -DECLARE_NET_MESSAGE(Chat, CHAT_MSG) - -#define RADIO_CHAT_MSG(MessageName, XX) \ - XX(MessageName, int, channel, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Radio channel"), TRANSF) \ - XX(MessageName, OLinkPermO(Person), sender, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Sender unit"), TRANSF_REF) \ - XX(MessageName, RefArray, units, NDTRefArray, AutoArray, NCTNone, DEFVALUEREFARRAY, DOC_MSG("List of receiving units"), TRANSF_REFS) \ - XX(MessageName, RString, text, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Message content"), TRANSF) \ - XX(MessageName, RadioSentence, sentence, NDTSentence, RadioSentence, NCTNone, DEFVALUE(RadioSentence, RadioSentence()), DOC_MSG("Content of message (list of words to say)"), TRANSF) \ - XX(MessageName, RString, wordsClass, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Possible subclass in class words to define alternative set of words such as whisper"), TRANSF) - -DECLARE_NET_MESSAGE(RadioChat, RADIO_CHAT_MSG) - -#define RADIO_CHAT_WAVE_MSG(MessageName, XX) \ - XX(MessageName, int, channel, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Radio channel"), TRANSF) \ - XX(MessageName, OLinkPermO(Person), sender, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Sender unit"), TRANSF_REF) \ - XX(MessageName, RefArray, units, NDTRefArray, AutoArray, NCTNone, DEFVALUEREFARRAY, DOC_MSG("List of receiving units"), TRANSF_REFS) \ - XX(MessageName, RString, senderName, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Sender name"), TRANSF) \ - XX(MessageName, RString, wave, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Sound identifier"), TRANSF) - -DECLARE_NET_MESSAGE(RadioChatWave, RADIO_CHAT_WAVE_MSG) - -/** adapted from CHAT_MSG */ -#define LOCALIZED_CHAT_MSG(MessageName, XX) \ - XX(MessageName, int, channel, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Radio channel"), TRANSF) \ - XX(MessageName, OLinkPermO(Person), sender, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Sender unit"), TRANSF_REF) \ - XX(MessageName, RefArray, units, NDTRefArray, AutoArray, NCTNone, DEFVALUEREFARRAY, DOC_MSG("List of receiving units"), TRANSF_REFS) \ - XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Sender name"), TRANSF) \ - XX(MessageName, AutoArray, args, NDTLocalizedStringArray, AutoArray, NCTNone, DEFVALUELOCALIZEDSTRINGARRAY, DOC_MSG("Client-side localized text with arguments"), TRANSF) \ - -DECLARE_NET_MESSAGE(LocalizedChat,LOCALIZED_CHAT_MSG) - -#define SET_SPEAKER_MSG(MessageName, XX) \ - XX(MessageName, int, player, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Client (player) ID of speaking player"), TRANSF) \ - XX(MessageName, int, on, NDTBool, int, NCTNone, DEFVALUE(bool, false), DOC_MSG("Turn on / off direct speaking"), TRANSF) \ - XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("ID of speaking unit"), TRANSF) \ - XX(MessageName, OIDInt, id, NDTOID, OIDInt, NOIDIntComp, DEFVALUE(OIDInt, 0), DOC_MSG("ID of speaking unit"), TRANSF) - -DECLARE_NET_MESSAGE(SetSpeaker, SET_SPEAKER_MSG) - -#define SELECT_PLAYER_MSG(MessageName, XX) \ - XX(MessageName, int, player, NDTInteger, int, NCTNone, DEFVALUE(int, AI_PLAYER), DOC_MSG("Client (player) ID of player"), TRANSF) \ - XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("ID of player's unit"), TRANSF) \ - XX(MessageName, OIDInt, id, NDTOID, OIDInt, NOIDIntComp, DEFVALUE(OIDInt, 0), DOC_MSG("ID of player's unit"), TRANSF) \ - XX(MessageName, Vector3, position, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, Vector3(-FLT_MAX, -FLT_MAX, -FLT_MAX)), DOC_MSG("Player's unit position"), TRANSF) \ - XX(MessageName, bool, respawn, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Selection of player's unit after respawn"), TRANSF) - -DECLARE_NET_MESSAGE(SelectPlayer, SELECT_PLAYER_MSG) - -#define CHANGE_OWNER_MSG(MessageName, XX) \ - XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("ID of object, which owner is changing"), TRANSF) \ - XX(MessageName, OIDInt, id, NDTOID, OIDInt, NOIDIntComp, DEFVALUE(OIDInt, 0), DOC_MSG("ID of object, whic player is changing"), TRANSF) \ - XX(MessageName, int, owner, NDTInteger, int, NCTNone, DEFVALUE(int, AI_PLAYER), DOC_MSG("Client ID of new owner"), TRANSF) \ - XX(MessageName, bool, disconnected, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Disconnected player becomes AI"), TRANSF) - -DECLARE_NET_MESSAGE(ChangeOwner, CHANGE_OWNER_MSG) - -#define OWNER_CHANGED_MSG(MessageName, XX) \ - XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("ID of object, which owner was changed"), TRANSF) \ - XX(MessageName, OIDInt, id, NDTOID, OIDInt, NOIDIntComp, DEFVALUE(OIDInt, 0), DOC_MSG("ID of object, whic player is changing"), TRANSF) - -DECLARE_NET_MESSAGE(OwnerChanged, OWNER_CHANGED_MSG) - -#define PLAY_SOUND_MSG(MessageName, XX) \ - XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Sound identifier"), TRANSF) \ - XX(MessageName, Vector3, position, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Sound source position"), TRANSF) \ - XX(MessageName, Vector3, speed, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Sound source speed"), TRANSF) \ - XX(MessageName, float, volume, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG("Sound volume"), TRANSF) \ - XX(MessageName, float, frequency, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG("Sound pitch"), TRANSF) \ - XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Unique network ID of sound"), TRANSF) \ - XX(MessageName, int, soundId, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Unique network ID of sound"), TRANSF) - -DECLARE_NET_MESSAGE(PlaySound, PLAY_SOUND_MSG) - -#define SOUND_STATE_MSG(MessageName, XX) \ - XX(MessageName, int, state, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("New state of sound"), TRANSF) \ - XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Network ID of sound"), TRANSF) \ - XX(MessageName, int, soundId, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Network ID of sound"), TRANSF) - -DECLARE_NET_MESSAGE(SoundState, SOUND_STATE_MSG) - -#define DELETE_OBJECT_MSG(MessageName, XX) \ - XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Id of object to destroy"), TRANSF) \ - XX(MessageName, OIDInt, id, NDTOID, OIDInt, NOIDIntComp, DEFVALUE(OIDInt, 0), DOC_MSG("Id of object to destroy"), TRANSF) - -DECLARE_NET_MESSAGE(DeleteObject, DELETE_OBJECT_MSG) - -#define DELETED_OBJECT_MSG(MessageName, XX) \ - XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Id of object destroyed"), TRANSF) \ - XX(MessageName, OIDInt, id, NDTOID, OIDInt, NOIDIntComp, DEFVALUE(OIDInt, 0), DOC_MSG("Id of object destroyed"), TRANSF) - -DECLARE_NET_MESSAGE(DeletedObject, DELETED_OBJECT_MSG) - -#define ASK_FOR_PILOT_LIGHT_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(EntityAI), vehicle, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Force switch on/off pilot light"), TRANSF_REF) \ - XX(MessageName, bool, enable, NDTBool, bool, NCTNone, DEFVALUE(bool, true), DOC_MSG(""), TRANSF) - -DECLARE_NET_MESSAGE(AskForPilotLight, ASK_FOR_PILOT_LIGHT_MSG) - -#define ASK_FOR_VEHICLE_DOOR_STATE_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(Transport), vehicle, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Open or close vehicle door"), TRANSF_REF) \ - XX(MessageName, int, doorIndex, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, -1), DOC_MSG("Index of door"), TRANSF) \ - XX(MessageName, bool, opened, NDTBool, bool, NCTNone, DEFVALUE(bool, true), DOC_MSG(""), TRANSF) - -DECLARE_NET_MESSAGE(AskForVehicleDoorState, ASK_FOR_VEHICLE_DOOR_STATE_MSG) - -#define ASK_FOR_AMMO_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(EntityAIFull), vehicle, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Vehicle which ammo is changing"), TRANSF_REF) \ - XX(MessageName, OLinkPermNO(Turret), turret, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Turret which ammo is changing"), TRANSF_REF) \ - XX(MessageName, OLinkPermO(Weapon), weapon, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Weapon"), TRANSF_REF) \ - XX(MessageName, int, muzzle, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Muzzle index"), TRANSF) \ - XX(MessageName, int, mode, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Mode index"), TRANSF) \ - XX(MessageName, int, burst, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 1), DOC_MSG("Amount of ammo to decrease"), TRANSF) - -DECLARE_NET_MESSAGE(AskForAmmo, ASK_FOR_AMMO_MSG) - -#define ASK_FOR_MOVE_VECTOR_MSG(MessageName, XX) \ - XX(MessageName, OLinkPerm, vehicle, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Moving object"), TRANSF_REF) \ - XX(MessageName, Vector3, pos, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("New position"), TRANSF) - -DECLARE_NET_MESSAGE(AskForMoveVector, ASK_FOR_MOVE_VECTOR_MSG) - -#define ASK_FOR_MOVE_MATRIX_MSG(MessageName, XX) \ - XX(MessageName, OLinkPerm, vehicle, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Moving object"), TRANSF_REF) \ - XX(MessageName, Vector3, pos, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("New position"), TRANSF) \ - XX(MessageName, Matrix3, orient, NDTMatrix, Matrix3, NCTNone, DEFVALUE(Matrix3, M3Identity), DOC_MSG("New orientation"), TRANSF) - -DECLARE_NET_MESSAGE(AskForMoveMatrix, ASK_FOR_MOVE_MATRIX_MSG) - -#define ASK_FOR_SET_MAGAZINE_AMMO_MSG(MessageName, XX) \ - XX(MessageName, OLinkPerm, magazine, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Magazine object"), TRANSF_REF) \ - XX(MessageName, int, ammo, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("New amount of ammo"), TRANSF) - -DECLARE_NET_MESSAGE(AskForSetMagazineAmmo, ASK_FOR_SET_MAGAZINE_AMMO_MSG) - -/* -void ExplosionDamage(EntityAI *owner, Shot *shot, Object *directHit, Vector3Par directHitModelPos, HitInfoPar hitInfo, Object *componentOwner=NULL, int componentIndex=-1, float energyFactor=1.0f, float explosionFactor=0.3f); -void ExplosionDamageEffects(EntityAI *owner, Object *directHit, HitInfoPar hitInfo, int componentIndex, bool enemyDamage, float energyFactor, float explosionFactor); -*/ - -#define EXPLOSION_DAMAGE_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(EntityAI), owner, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Shot owner (who is responsible for explosion)"), TRANSF_REF) \ - XX(MessageName, OLink(Object), directHit, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Hit object"), TRANSF_REF) \ - XX(MessageName, Vector3, originDir, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("World space origin direction relative to the target"), TRANSF) /*TODO: replace with originPos*/ \ - XX(MessageName, Vector3, directHitModelPos, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Explosion position in directHit model coordinates"), TRANSF) \ - XX(MessageName, OLink(Object), componentOwner, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Hit object - may be proxy, owner of componentIndex"), TRANSF_REF) \ - XX(MessageName, int, componentIndex, NDTInteger, int, NCTNone, DEFVALUE(int, -1), DOC_MSG("Index of hit convex component"), TRANSF) \ - XX(MessageName, RString, type, NDTString, RString, NCTDefault, DEFVALUE(RString, ""), DOC_MSG("Ammunition type"), TRANSF) \ - XX(MessageName, Vector3, pos, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Explosion position"), TRANSF) \ - XX(MessageName, Vector3, surfNormal, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VUp), DOC_MSG("Surface normal at the explosion"), TRANSF) \ - XX(MessageName, Vector3, inSpeed, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Speed of the corresponding bullet/shell/missile"), TRANSF) \ - XX(MessageName, Vector3, outSpeed, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Result speed (if any)"), TRANSF) \ - XX(MessageName, float, energyFactor, NDTFloat, float, NCTFloatMostly0To1, DEFVALUE(float, 1), DOC_MSG("Energy coefficient for distant hits"), TRANSF) \ - XX(MessageName, float, explosionFactor, NDTFloat, float, NCTFloat0To1, DEFVALUE(float, 0), DOC_MSG("How large explosion is"), TRANSF)\ - XX(MessageName, float, hitDepth, NDTFloat, float, NCTFloat0To1, DEFVALUE(float, 0), DOC_MSG("The penetration depth of the hit"), TRANSF) - -DECLARE_NET_MESSAGE(ExplosionDamage, EXPLOSION_DAMAGE_MSG) - -#define EXPLOSION_DAMAGE_EFFECTS_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(EntityAI), owner, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Shot owner (who is responsible for explosion)"), TRANSF_REF) \ - XX(MessageName, OLink(Object), directHit, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Hit object"), TRANSF_REF) \ - XX(MessageName, int, componentIndex, NDTInteger, int, NCTNone, DEFVALUE(int, -1), DOC_MSG("Index of hit convex component"), TRANSF) \ - XX(MessageName, RString, type, NDTString, RString, NCTDefault, DEFVALUE(RString, ""), DOC_MSG("Ammunition type"), TRANSF) \ - XX(MessageName, Vector3, pos, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Explosion position"), TRANSF) \ - XX(MessageName, Vector3, surfNormal, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VUp), DOC_MSG("Surface normal at the explosion"), TRANSF) \ - XX(MessageName, Vector3, inSpeed, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Speed of the corresponding bullet/shell/missile"), TRANSF) \ - XX(MessageName, Vector3, outSpeed, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Result speed (if any)"), TRANSF) \ - XX(MessageName, bool, enemyDamage, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Some enemy was damaged"), TRANSF) \ - XX(MessageName, float, energyFactor, NDTFloat, float, NCTFloatMostly0To1, DEFVALUE(float, 1), DOC_MSG("Energy coefficient for distant hits"), TRANSF) \ - XX(MessageName, float, explosionFactor, NDTFloat, float, NCTFloat0To1, DEFVALUE(float, 0), DOC_MSG("How large explosion is"), TRANSF) - -DECLARE_NET_MESSAGE(ExplosionDamageEffects, EXPLOSION_DAMAGE_EFFECTS_MSG) - -#define PROJECTILE_DECAL_MSG(MessageName, XX) \ - XX(MessageName, OLink(Object), directHit, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Hit object"), TRANSF_REF) \ - XX(MessageName, int, componentIndex, NDTInteger, int, NCTNone, DEFVALUE(int, -1), DOC_MSG("Index of hit convex component"), TRANSF) \ - XX(MessageName, RString, ammoType, NDTString, RString, NCTDefault, DEFVALUE(RString, ""), DOC_MSG("Ammunition type"), TRANSF) \ - XX(MessageName, Vector3, hitPosWorld, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Explosion position in world space"), TRANSF) \ - XX(MessageName, Vector3, hitPosLcl, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Hit position on the body (model space)"), TRANSF) \ - XX(MessageName, Vector3, surfNormal, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VUp), DOC_MSG("Surface normal at the hit spot"), TRANSF) \ - XX(MessageName, Vector3, inSpeed, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Speed of the corresponding bullet/shell/missile"), TRANSF) \ - XX(MessageName, Vector3, outSpeed, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Result speed (if any)"), TRANSF) \ - XX(MessageName, Vector3, hitDirLcl, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VForward), DOC_MSG("Forward direction of the projectile (model space)"), TRANSF) \ - XX(MessageName, Vector3, hitDirUpLcl, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VUp), DOC_MSG("Up direction of the projectile (model space)"), TRANSF) \ - XX(MessageName, float, hitDepth, NDTFloat, float, NCTFloat0To1, DEFVALUE(float, 0), DOC_MSG("The penetration depth of the projectile"), TRANSF) - -DECLARE_NET_MESSAGE(ProjectileDecal, PROJECTILE_DECAL_MSG) - -#define REM_PROJECTILE_DECALS_MSG(MessageName, XX) \ - XX(MessageName, OLink(Object), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person to remove projectiles from"), TRANSF_REF) \ - -DECLARE_NET_MESSAGE(RemoveProjectileDecals, REM_PROJECTILE_DECALS_MSG) - -#define BOW_STATE_MSG(MessageName, XX) \ - XX(MessageName, OLink(Object), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person using the bow"), TRANSF_REF) \ - XX(MessageName, int, state, NDTInteger, int, NCTNone, DEFVALUE(int, -1), DOC_MSG("Updated bow state"), TRANSF) \ - -DECLARE_NET_MESSAGE(BowState, BOW_STATE_MSG) - -#if _VBS3 - -// Transmit the projectile leaving the weapon -#define FIRE_WEAPON_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(EntityAIFull), vehicle, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Firing vehicle"), TRANSF_REF) \ - XX(MessageName, OLinkPermO(Person), gunner, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Firing gunner"), TRANSF_REF) \ - XX(MessageName, OLink(EntityAI), target, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Aimed target"), TRANSF_REF) \ - XX(MessageName, Vector3, pos, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VForward), DOC_MSG("Position of the fire"), TRANSF) \ - XX(MessageName, Vector3, dir, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VForward), DOC_MSG("Direction of the fire"), TRANSF) \ - XX(MessageName, int, weapon, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Firing weapon index"), TRANSF) \ - XX(MessageName, CreatorId, magazineCreator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Fired magazine id"), TRANSF) \ - XX(MessageName, int, magazineId, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Fired magazine id"), TRANSF) \ - XX(MessageName, float, visible, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG("How much is the fire visible"), TRANSF) \ - XX(MessageName, OLink(Entity), projectile, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Projectile leaving weapon"), TRANSF_REF) - -#else - -#define FIRE_WEAPON_MSG(MessageName, XX) \ - XX(MessageName, OLinkPermO(EntityAIFull), vehicle, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Firing vehicle"), TRANSF_REF) \ - XX(MessageName, OLinkPermO(Person), gunner, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Firing gunner"), TRANSF_REF) \ - XX(MessageName, OLink(EntityAI), target, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Aimed target"), TRANSF_REF) \ - XX(MessageName, Vector3, pos, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VForward), DOC_MSG("Position of the fire"), TRANSF) \ - XX(MessageName, Vector3, dir, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VForward), DOC_MSG("Direction of the fire"), TRANSF) \ - XX(MessageName, OLinkPermO(Weapon), weapon, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Weapon"), TRANSF_REF) \ - XX(MessageName, int, muzzle, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Muzzle index"), TRANSF) \ - XX(MessageName, int, mode, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Mode index"), TRANSF) \ - XX(MessageName, OLinkPermO(Magazine), magazine, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Fired magazine."), TRANSF_REF) \ - XX(MessageName, float, visible, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG("How much is the fire visible"), TRANSF) - -#endif - -DECLARE_NET_MESSAGE(FireWeapon, FIRE_WEAPON_MSG) - -#define VOTE_MISSION_MSG(MessageName, XX) \ - XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE_DEF(RString), DOC_MSG("Name of the mission"), TRANSF) \ - XX(MessageName, RString, diff, NDTString, RString, NCTNone, DEFVALUE_DEF(RString), DOC_MSG("Wanted difficulty"), TRANSF) \ - -DECLARE_NET_MESSAGE(VoteMission,VOTE_MISSION_MSG) - -#define SERVER_TIMEOUT_MSG(MessageName, XX) \ - XX(MessageName, int, timeout, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Timeout in seconds"), TRANSF) \ - -DECLARE_NET_MESSAGE(ServerTimeout,SERVER_TIMEOUT_MSG) - -#define SERVER_INFO_MSG(MessageName, XX) \ - XX(MessageName, RString, hostname, NDTString, RString, NCTNone, DEFVALUE_DEF(RString), DOC_MSG("Server Hostname"), TRANSF) \ - -DECLARE_NET_MESSAGE(ServerInfo,SERVER_INFO_MSG) - -#define VEHICLE_DESTROYED_MSG(MessageName, XX) \ - XX(MessageName, OLinkO(EntityAI), killed, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Destroyed vehicle"), TRANSF_REF) \ - XX(MessageName, OLinkPermO(EntityAI), killer, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Who is responsible for destroying"), TRANSF_REF) - -DECLARE_NET_MESSAGE(VehicleDestroyed, VEHICLE_DESTROYED_MSG) - -#define MARKER_DELETE_MSG(MessageName, XX) \ - XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Name of marker"), TRANSF) - -DECLARE_NET_MESSAGE(MarkerDelete, MARKER_DELETE_MSG) - -struct NetworkMessageMarker; -struct NetworkMessageEffects; - -#define MARKER_CREATE_MSG(MessageName, XX) \ - XX(MessageName, int, channel, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Chat channel (who will see the marker)"), TRANSF) \ - XX(MessageName, OLinkPermO(Person), sender, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Sender unit"), TRANSF_REF) \ - XX(MessageName, RefArray, units, NDTRefArray, AutoArray, NCTNone, DEFVALUEREFARRAY, DOC_MSG("List of receiving units"), TRANSF_REFS) \ - XX(MessageName, ArcadeMarkerInfo, marker, NDTObject, REF_MSG(NetworkMessageMarker), NCTNone, DEFVALUE_MSG(NMTMarker), DOC_MSG("Marker object to create"), TRANSF_OBJECT) - -DECLARE_NET_MESSAGE(MarkerCreate, MARKER_CREATE_MSG) - -#if _ENABLE_VBS - -#define SET_OBJECT_TEXTURE_MSG(MessageName, XX) \ - XX(MessageName, OLink(EntityAI), veh, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Vehicle that will have a texture changed"), TRANSF_REF) \ - XX(MessageName, int, index, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, -1), DOC_MSG("Index of selection to set texture for"), TRANSF) \ - XX(MessageName, RString, name, NDTString, RString, NCTDefault, DEFVALUE(RString, ""), DOC_MSG("Name of texture"), TRANSF) \ - XX(MessageName, RString, eval, NDTString, RString, NCTDefault, DEFVALUE(RString, "true"), DOC_MSG("Evaluation - must evaluate to true if texture is to be set on client"), TRANSF) - -DECLARE_NET_MESSAGE(SetObjectTexture, SET_OBJECT_TEXTURE_MSG) - -#define PUBLICEXEC_MSG(MessageName, XX) \ - XX(MessageName, RString, condition, NDTString, RString, NCTDefault, DEFVALUE(RString, ""), DOC_MSG("Condition to evaluate, if true then command will be executed"), TRANSF) \ - XX(MessageName, RString, command, NDTString, RString, NCTDefault, DEFVALUE(RString, ""), DOC_MSG("Command to execute if evaluation is true"), TRANSF) \ - XX(MessageName, OLink(Object), obj, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Object passed into condition and command as _this"), TRANSF_REF) \ - XX(MessageName, OLinkArray(Object), objs, NDTRefArray, AutoArray, NCTNone, DEFVALUEREFARRAY, DOC_MSG("Joining units"), TRANSF_REFS) - -DECLARE_NET_MESSAGE(PublicExec, PUBLICEXEC_MSG) - -#endif // _ENABLE_VBS - -#define TRANSFER_FILE_MSG(MessageName, XX) \ - XX(MessageName, RString, path, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Path of transferred file"), TRANSF) \ - XX(MessageName, AutoArray, data, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Content of file (single segment)"), TRANSF) \ - XX(MessageName, int, totSize, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Total size of file"), TRANSF) \ - XX(MessageName, int, offset, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Offset of this segment"), TRANSF) \ - XX(MessageName, int, totSegments, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 1), DOC_MSG("Total number of segments"), TRANSF) \ - XX(MessageName, int, curSegment, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Index of this segment"), TRANSF) - -DECLARE_NET_MESSAGE(TransferFile, TRANSFER_FILE_MSG) - -#define SUBSCRIBE_RADIOS_MSG(MessageName, XX) \ - XX(MessageName, int, player, NDTInteger, int, NCTNone, DEFVALUE(int, AI_PLAYER), DOC_MSG("Client (player) ID of player"), TRANSF) \ - XX(MessageName, AutoArray, frequences, NDTFloatArray, FindArray, NCTNone, DEFVALUEFLOATARRAY, DOC_MSG("List of subscribed frequences"), TRANSF) - -DECLARE_NET_MESSAGE(SubscribeRadios, SUBSCRIBE_RADIOS_MSG) - -#define STATUS_CHAT_MSG(MessageName, XX) \ - XX(MessageName, RString, text, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Status text to be shown on client"), TRANSF) \ - XX(MessageName, RString, color, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Color class to use when drawing the text"), TRANSF) \ - -DECLARE_NET_MESSAGE(StatusChat, STATUS_CHAT_MSG) - -//! Message for transfer mission pbo file to other clients -struct TransferMissionFileMessage : public TransferFileMessage -{ - DECLARE_DEFINE_NETWORK_OBJECT_SIMPLE(TransferMissionFile) -}; - -#define TRANSFER_MISSION_FILE_MSG(MessageName, XX) - -DECLARE_NET_INDICES_EX(TransferMissionFile, TransferFile, TRANSFER_MISSION_FILE_MSG) - -//! Message for transfer file to server -struct TransferFileToServerMessage : public TransferFileMessage -{ - DECLARE_DEFINE_NETWORK_OBJECT_SIMPLE(TransferFileToServer) -}; - -#define TRANSFER_FILE_TO_SERVER_MSG(MessageName, XX) - -DECLARE_NET_INDICES_EX(TransferFileToServer, TransferFile, TRANSFER_FILE_TO_SERVER_MSG) - -#define ASK_MISSION_FILE_MSG(MessageName, XX) \ - XX(MessageName, bool, valid, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Mission file is valid (present on client computer)"), TRANSF) - -DECLARE_NET_MESSAGE(AskMissionFile, ASK_MISSION_FILE_MSG) - -//! Single message in agregated message -struct NetworkMessageQueueItem : public RefCount -{ - //! message type - NetworkMessageType type; - //! message itself - Ref msg; - //! guaranteed msg this message depends on - RefR dependOn; - - virtual void SetFence(const RefR &resultMsg) = 0; - - //! MP Save serialization - LSError Serialize(ParamArchive &ar) - { - CHECK(ar.Serialize("Message", msg, 1)) - if (ar.IsLoading()) type = msg->GetNMType(); - return LSOK; - } -}; - -struct ClientQueueItem : public NetworkMessageQueueItem -{ - Ref object; - - virtual void SetFence(const RefR &resultMsg) - { - if (object) object->_fence = resultMsg; - } -}; - -struct ServerQueueItem : public NetworkMessageQueueItem -{ - RefR poInfo; - - virtual void SetFence(const RefR &resultMsg); -}; -TypeIsMovable(ServerQueueItem) - -//! Agregated message -/*! -We want NMTMessaes to be created. This class is not used, it only allows the message factory to compile. -*/ -class NetworkMessageQueue : public NetworkSimpleObject, public RefArray -{ -public: - DECLARE_DEFINE_NETWORK_OBJECT_SIMPLE(Messages) - static NetworkMessageFormat &CreateFormat - ( - NetworkMessageClass cls, - NetworkMessageFormat &format - ); - TMError TransferMsg(NetworkMessageContext &ctx); -}; - -//! Encapsulates info needed for messages sent directly (inside process) instead through DirectPlay -struct NetworkLocalMessageInfo -{ - //! DirectPlay ID of sender - int from; - //! message type - NetworkMessageType type; - //! message itself - Ref msg; -}; -TypeIsMovableZeroed(NetworkLocalMessageInfo) - -/////////////////////////////////////////////////////////////////////////////// -// Network Components - -class NetworkManager; - -//! Info about file currently receiving -struct ReceivingFile -{ - //! name of receiving file - RString fileName; - //! info about which segments already received - AutoArray fileSegments; - //! content of receiving file - AutoArray fileData; - //! total amount of bytes already received (used for statistics) - int received; -}; -TypeIsMovable(ReceivingFile) - -#if _ENABLE_CHEATS -//! Statistic info about messages of given type -/*! -\patch_internal 1.08 Date 07/26/2001 by Jirka -- Improved: network diagnostics -*/ -struct NetworkStatisticsItem -{ - //! message type - int message; - //! count of sent messages (by priority) - int msgSentHighPriority; - int msgSentGuaranteed; - int msgSentOthers; - //! size of sent messages - int sizeSent; - //! count of received messages - int msgReceived; - //! size of received messages - int sizeReceived; - - //! Constructor - NetworkStatisticsItem() - { - message = 0; - msgSentHighPriority = 0; - msgSentGuaranteed = 0; - msgSentOthers = 0; - sizeSent = 0; - msgReceived = 0; - sizeReceived = 0; - }; -}; -TypeIsMovableZeroed(NetworkStatisticsItem) -#endif - -#if _ENABLE_CHEATS || _ENABLE_DEDICATED_SERVER -//! Statistic info about messages physically send / received by players -struct NetworkRawStatisticsItem -{ - //! player ID - int player; - //! count of sent messages - int msgSent; - //! size of sent messages - int sizeSent; - //! count of received messages - int msgReceived; - //! size of received messages - int sizeReceived; - - //! Constructor - NetworkRawStatisticsItem() - { - player = 0; - msgSent = 0; - sizeSent = 0; - msgReceived = 0; - sizeReceived = 0; - }; -}; -TypeIsMovableZeroed(NetworkRawStatisticsItem) - - -/// draw fps history -template -class PerformanceGraph: public IDiagGraph -{ - public: - struct Values - { - float values[sets]; - }; - - private: - static const int maxSamples = 200; - Values value[maxSamples]; - float deltaT[maxSamples]; - - public: - - RString GetName() const {return "Bandwidth";} - PackedColor GetDataColor(int set) const - { - static const PackedColor colors[]= - { - PackedColor(0xffffffff), - PackedColor(0xffffff00), - PackedColor(0xff00ff00), - PackedColor(0xff0000ff), - PackedColor(0xffff0000), - PackedColor(0xffffff00), - }; - if (set>=lenof(colors)) return PackedWhite; - return colors[set]; - } - - PerformanceGraph() - { - for (int i=0; i -{ - DWORD _lastTime; - int _lastSize; - int _lastMsg; - - public: - NetStatsGraph(); - - void OnSimulate(int size, int msg); -}; - -#endif - -class NetworkClient; - -class RadioSubscriber -{ -public: - AutoArray frequencies; - int dpnid; - - RadioSubscriber() : dpnid(0) {} - RadioSubscriber(int dp) : dpnid(dp) {} - bool FrequenciesMatch(float f1, float f2) const; -}; - -TypeIsMovable(RadioSubscriber) - -class RadioSubscribers -{ -public: - AutoArray _subscribers; - - RadioSubscribers() {} - - void OnPlayerDisconnected(int dpnid); // clear given subscriber - void Clear() { _subscribers.Clear(); } - void AddUnique(int dpnid, AutoArray &frequences); -}; - -//! Basic network component (client or server) -class NetworkComponent : public INetworkComponent -{ -protected: - //! creating network manager object - NetworkManager *_parent; // _parent must be valid - //! id of next created network object in this component - int _nextId; - - //! info about logged players - AutoArray _identities; - - //! info about current mission - MissionHeader _missionHeader; - //! parameter of current mission - float _param1; - //! parameter of current mission - float _param2; - //! array of parameters of current mission - AutoArray _paramsArray; - - //! messages received local (inside process) - AutoArray _receivedLocalMessages; - - //! files currently receiving - AutoArray _files; - -#if _ENABLE_CHEATS - //! Statistics about messages by types - AutoArray _statistics; -#endif - -#if _ENABLE_DEDICATED_SERVER || _ENABLE_CHEATS - //! Statistics about messages by players - AutoArray _rawStatistics; - RefArray _rawStatisticsGraph; -#endif - - //! list of accepted keys for data signatures - AutoArray _acceptedKeys; - //! the least signature version the server accepts - int _sigVerRequired; - - /// choose implementation: with guaranteed updates we can make interesting optimizations (delta transfer) - bool _updatesGuaranteed; - - static const int MaxVerifySignatures = 2; - - //! list of files (except banks), where signature will be checked - AutoArray _additionalSignedFiles; - - //! map players to their subscribed radio frequencies - RadioSubscribers _radioSubscribers; - -public: - //! Constructor - /*! - \param parent creating network manager object - */ - NetworkComponent(NetworkManager *parent); - //! Destructor - ~NetworkComponent(); - - //! Add message to local received messages - /*! - \param from DirectPlay ID of sender - \param type message type - \param msg message itself - */ - void AddLocalMessage(int from, NetworkMessageType type, NetworkMessage *msg); - - //! Implementation of direct message send through DirectPlay - /*! - \param to DirectPlay ID of message receiver - \param rawMsg message content - \param msgID out parameter to store DirectPlay ID of message - \param dwFlags DirectPlay flags - */ - virtual Ref DXSendMsg(int to, NetworkMessageRaw &rawMsg, DWORD &msgID, NetMsgFlags dwFlags, const Ref &dependOn) = 0; - - //! Draw any UI indications you need - virtual void OnDraw() = 0; - //! Process (user) message - /*! - \param from DirectPlay ID of sender - \param msg message itself - \param type message type - */ - virtual void OnMessage(int from, NetworkMessage *msg, NetworkMessageType type) = 0; - - //! perform regular memory clean-up - virtual unsigned CleanUpMemory() = 0; - - //! Return if given client is local on server's computer - virtual bool IsLocalClient(int client) const {return false;} - - bool IsUpdatesGuaranteed() const {return _updatesGuaranteed;} - - //{ DEDICATED SERVER SUPPORT - #if _ENABLE_DEDICATED_SERVER - //! Called when message is received to calculate transfer rate on dedicated server - virtual void OnMonitorIn(int size) {} - #endif - //} - - //! Hi-level send of message - /*! - \param to DirectPlay ID of message receiver - \param object message object - \param dwFlags DirectPlay flags - */ - virtual DWORD SendMsg - ( - int to, - NetworkSimpleObject *object, /*int creator, int id,*/ - NetMsgFlags dwFlags - ); - - //! Send single network message - /*! - This function determine, whic type of send will be used - local send, agregation or send using DirectPlay - \param to DirectPlay ID of message receiver - \param msg message itself - \param type type of message - \param dwFlags DirectPlay flags - */ - virtual DWORD SendMsg - ( - int to, NetworkMessage *msg, - NetworkMessageType type, NetMsgFlags dwFlags - ) = 0; - - //! Return mission header - const MissionHeader *GetMissionHeader() const {return &_missionHeader;} - //! Return number of role slots for current mission - - //! Search for identity with given player id - const PlayerIdentity *FindIdentity(int dpnid) const; - //! Search for identity with given player id - PlayerIdentity *FindIdentity(int dpnid); - //! Search for identity with given user friendly player id - const PlayerIdentity *FindIdentityByPlayerId(int playerId) const; - //! Return array of identities - const AutoArray *GetIdentities() const {return &_identities;} - //! Retrieves parameters for current mission - void GetParams(float ¶m1, float ¶m2) const {param1 = _param1; param2 = _param2;} - //! Retrieves parameters for current mission - float GetParams(int index) const { - if(index<_paramsArray.Size()) return _paramsArray[index]; - return 0.0; - }; - - //! Retrieves parameters for current mission - AutoArray GetParamsArray() const{return _paramsArray;}; - - //! Return component type ("server" / "client") for debugging purposes - virtual const char *GetDebugName() const = 0; - - //! Decode (and process) message from raw data - /*! - \param from DirectPlay ID of sender - \param src source raw data - */ - void DecodeMessage(int from, NetworkMessageRaw &src); - //! Calculate size of message after serialization and compression - /*! - \param msg calculated message - \param type type of calculated message - */ - int CalculateMessageSize(NetworkMessage *msg, NetworkMessageType type); - - //! File transfer - /*! - Split file into segments and send segments using standard messages. - \param to DirectPlay ID of file receiver - \param dest filename on destination computer - \param source local filename - */ - void TransferFile(int to, RString dest, RString source); - /*! - Split file into segments and store them into msgList array - \param to DirectPlay ID of file receiver - \param dest filename on destination computer - \param source local filename - */ - void PrepareTransferFileMessages(AutoArray &msgList, RString dest, RString source); - //! Transfer player's face from server to client - /*! - \param to DirectPlay ID of face receiver - \param player player which face is transfered - */ - void TransferFace(int to, RString player); - //! Transfer player's custom radio messages from server to client - /*! - \param to DirectPlay ID of messages receiver - \param player player which messages are transfered - */ - void TransferCustomRadio(int to, RString player); - -#if _ENABLE_CHEATS - //! Write into statistics info about sent message - /*! - \param msg message type - \param size size of sent message - */ - void StatMsgSent(int msg, int size, NetMsgFlags flags); - //! Write into statistics info about received message - /*! - \param msg message type - \param size size of received message - */ - void StatMsgReceived(int msg, int size); - //! Return statistics about messages by types - AutoArray &GetStatistics() {return _statistics;} -#endif - -#if _ENABLE_DEDICATED_SERVER || _ENABLE_CHEATS - //! Write raw statistics info about sent message - /*! - \param msg message type - \param to player - */ - void StatRawMsgSent(int to, int size); - //! Write raw statistics info about received message - /*! - \param msg message type - \param from player - */ - void StatRawMsgReceived(int from, int size); -#endif - - int GetMaxMissionPlayers() const {return _missionHeader._maxPlayers; } - -protected: - //! Encode message into raw data - /*! - \param dst destination data - \param msg source message - \param format format of source message - \param type type of destination message - */ - void EncodeMsg(NetworkMessageRaw &dst, NetworkMessage *msg, NetworkMessageFormatBase *format, NetworkMessageType type); - //! Encode single message item into raw data - /*! - \param dst destination data - \param msg source message - \param ptr pointer to item to encode - \param item format of source message item - */ - void EncodeMsgItem(NetworkMessageRaw &dst, NetworkMessage *msg, void *ptr, NetworkMessageFormatItem &item); - //! Initialize message before decoding - /*! - \param msg destination message - \param type type of destination message - */ - virtual void InitMsg(NetworkMessage *msg, NetworkMessageType type) {} - //! Decode message from raw data - /*! - \param msg destination message - \param src source data - \param format format of destination message - \param type type of destination message - */ - bool DecodeMsg(NetworkMessage *msg, NetworkMessageRaw &src, NetworkMessageFormatBase *format, NetworkMessageType type); - //! Decode single message item from raw data - /*! - \param src source data - \param msg destination message - \param ptr pointer to item to decode - \param item format of source message item - */ - bool DecodeMsgItem(NetworkMessageRaw &src, NetworkMessage *msg, void *ptr, NetworkMessageFormatItem &item); - //! Create copy of message - /*! - \param src source message - \param format format of source message - */ - void CopyMsg(NetworkMessage *dst, const NetworkMessage *src, const NetworkMessageFormatBase *format) const; - //! Calculate size of message after serialization and compression - /*! - \param msg calculated message - \param format format of calculated message - \param type type of calculated message - */ - int CalculateMsgSize(NetworkMessage *msg, NetworkMessageFormatBase *format, NetworkMessageType type); - //! Calculate size of single message item after serialization and compression - /*! - \param msg calculated message - \param ptr calculated message item - \param item format of calculated message item - */ - int CalculateMsgItemSize(void *ptr, const NetworkMessageFormatItem &item); - - //! Process all received messages (local, system and user) - void ReceiveLocalMessages(); - - - //! Send single network message using DirectPlay - /*! - \param to DirectPlay ID of message receiver - \param msg message itself - \param type type of message - \param dwFlags DirectPlay flags - */ - int SendMsgRemote - ( - int to, NetworkMessage *msg, - NetworkMessageType type, NetMsgFlags dwFlags, - RefR *resultMsg, - const RefR &dependOn - ); - //! Send (part of) message queue as single DirectPlay message - /*! - \param to DirectPlay ID of message receiver - \param queue messages to agregate - \param begin index of first message to send - \param end index of first message not to send - \param dwFlags DirectPlay flags - */ - int SendMsgQueue - ( - int to, NetworkMessageQueue &queue, - int begin, int end, NetMsgFlags dwFlags - ); - //! Lo-level data send using DirectPlay - /*! - \param to DirectPlay ID of message receiver - \param rawMsg data to send - \param dwFlags DirectPlay flags - \param diagLevel level of diagnostics about message - */ - DWORD SendMsgRaw(int to, NetworkMessageRaw &rawMsg, NetMsgFlags dwFlags, int diagLevel, RefR *resultMsg, const Ref &dependOn); - - - //! Called when file segment is received - /*! - \param msg segment of file - \return 1 if whole file is received (and saved) - \return -1 if whole file is received, but with errors (save failed) - */ - int ReceiveFileSegment(TransferFileMessage &msg); - - //! verify the real file format matches the extension - bool ValidDataFile(const char *fileName); - -}; - -//! Info about single type of update of network object -struct NetworkUpdateInfo -{ - //! last sent update message - Ref lastSentMsg; - //! cached value of error - float errorStatic; - //! cached value is valid - bool errorValid; - - //! bot-client rejected state received from owner - bool rejected; - - NetworkUpdateInfo() - { - // avoid floating point exceptions - errorStatic = 0; - errorValid = false; - rejected = false; - } - - bool CheckReject(NetworkClient *client, NetworkMessageClass cls, NetworkObject *obj); - -}; - -//! Info about local object on client -struct NetworkLocalObjectInfo //: public RefCount -{ - //! ID of object - NetworkId id; - //! object itself - OLinkNO(NetworkObject) object; - //! state of outgoing updates - NetworkUpdateInfo updates[NMCUpdateN]; -}; -TypeContainsOLink(NetworkLocalObjectInfo) -//TypeIsGeneric(NetworkLocalObjectInfo) - -//! Info about remote object on client -struct NetworkRemoteObjectInfo -{ - //! ID of object - NetworkId id; - //! object itself - OLinkNO(NetworkObject) object; - //! state of incoming updates - Ref updates[NMCUpdateN]; - //! all objects are tracked here, but only some are really remote - bool remote; -}; -TypeContainsOLink(NetworkRemoteObjectInfo) - -/// info about an object which was already deleted on the server -struct NetworkDeletedObjectInfo -{ - NetworkId id; - /// time of deletion - Time time; - /// owner of the object at the time of deletion - int owner; -}; - -TypeIsMovableZeroed(NetworkDeletedObjectInfo); - - -//! map sounds transferred over network to their unique ids -struct PlaySoundInfo -{ - //! unique id of sound - CreatorId creator; - int id; - //! sound itself - Link wave; -}; -TypeIsGeneric(PlaySoundInfo) - -//! Class used for transfer of client info (for example camera position) to server -/*! -\patch_internal 1.27 Date 10/11/2001 by Jirka -- Improved: camera position transfer in multiplayer game -*/ -class ClientInfoObject : public NetworkObject -{ -protected: - NetworkId _id; - -public: - Vector3 _cameraPosition; - int _dpnid; // Direct play id (necessary for hearing of VoN Direct Speech for dead players) - -#if _VBS3 - Vector3 _cameraDirection; - float _cameraFov; -#endif - -public: - // Constructor - ClientInfoObject() - { - _cameraPosition = InvalidCamPos; -#if _VBS3 - _cameraDirection = VForwardP; - _cameraFov = 0.75; -#endif - } - - void SetNetworkId(NetworkId &id) {_id = id;} - NetworkId GetNetworkId() const {return _id;} - Vector3 GetCurrentPosition() const {return VZero;} - bool IsLocal() const {return true;} - void SetLocal(bool local = true) {} - void DestroyObject() {} - - DECLARE_NETWORK_OBJECT - static NetworkMessageFormat &CreateFormat - ( - NetworkMessageClass cls, - NetworkMessageFormat &format - ); - TMError TransferMsg(NetworkMessageContext &ctx); - float CalculateError(NetworkMessageContextWithError &ctx); - virtual float CalculateErrorCoef(Vector3Par position, Vector3Par cameraPosition, float updateDistance, bool updating) const override {return 1.0;} - RString GetDebugName() const; -}; - -#if !_VBS3 -#define UPDATE_CLIENT_INFO_MSG(MessageName, XX) \ - XX(MessageName, Vector3, cameraPosition, NDTVector, Vector3, NCTVectorPositionCamera, DEFVALUE(Vector3, InvalidCamPos), DOC_MSG("Position of camera on client"), TRANSF, ET_ABS_DIF, 1) - -DECLARE_NET_INDICES_EX_ERR(UpdateClientInfo, NetworkObject, UPDATE_CLIENT_INFO_MSG) -#endif - -#define UPDATE_CLIENT_INFO_DPID_MSG(MessageName, XX) \ - XX(MessageName, Vector3, cameraPosition, NDTVector, Vector3, NCTVectorPositionCamera, DEFVALUE(Vector3, InvalidCamPos), DOC_MSG("Position of camera on client"), TRANSF, ET_ABS_DIF, 1) \ - XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Direct play id of dead player."), TRANSF, ET_NOT_EQUAL, 0) - -DECLARE_NET_INDICES_EX_ERR(UpdateClientInfoDpid, NetworkObject, UPDATE_CLIENT_INFO_DPID_MSG) - -#define UPDATE_ACTION_SUBSCRIPTION_MSG(MessageName, XX) \ - XX(MessageName, UserAction, action, NDTInteger, UserAction, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("action"), TRANSF) \ - XX(MessageName, bool, checkFocus, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("checkFocus"), TRANSF) \ - XX(MessageName, float, digitalValue, NDTFloat, float, NCTFloatMostly0To1, DEFVALUE(float, 0), DOC_MSG(""), TRANSF) \ - XX(MessageName, unsigned char, level, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 1), DOC_MSG("level"), TRANSF) \ - -DECLARE_SIMPLE_NETWORK_STRUCTURE(ActionSubscription,UPDATE_ACTION_SUBSCRIPTION_MSG) - -TypeIsSimple(ActionSubscription) - -#define UPDATE_ACTIONTODO_SUBSCRIPTION_MSG(MessageName, XX) \ - XX(MessageName, UserAction, action, NDTInteger, UserAction, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("action"), TRANSF) \ - XX(MessageName, bool, reset, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("reset"), TRANSF) \ - XX(MessageName, bool, checkFocus, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("checkFocus"), TRANSF) \ - XX(MessageName, bool, exclusive, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("exclusive"), TRANSF) \ - XX(MessageName, unsigned char, level, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 1), DOC_MSG("level"), TRANSF) \ - XX(MessageName, bool, blockButtons, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("blockButtons"), TRANSF) \ - -DECLARE_SIMPLE_NETWORK_STRUCTURE(ActionToDoSubscription,UPDATE_ACTIONTODO_SUBSCRIPTION_MSG) - -TypeIsSimple(ActionToDoSubscription) - -#define UPDATE_ACTIONDO_SUBSCRIPTION_MSG(MessageName, XX) \ - XX(MessageName, UserAction, action, NDTInteger, UserAction, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("action"), TRANSF) \ - XX(MessageName, bool, checkFocus, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("checkFocus"), TRANSF) \ - -DECLARE_SIMPLE_NETWORK_STRUCTURE(ActionDoSubscription,UPDATE_ACTIONDO_SUBSCRIPTION_MSG) - -TypeIsSimple(ActionDoSubscription) - -#define UPDATE_ITEM_SHORTCUT_MSG(MessageName, XX) \ - XX(MessageName, RString, itemType, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG(""), TRANSF)\ - -DECLARE_SIMPLE_NETWORK_STRUCTURE(ItemShortcut,UPDATE_ITEM_SHORTCUT_MSG) - -TypeIsMovableZeroed(ItemShortcut) - -#define UPDATE_ACTIONWITHCURVE_SUBSCRIPTION_MSG(MessageName, XX) \ - XX(MessageName, InputInterface::CurveFactor, factorKind, NDTInteger, InputInterface::CurveFactor, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ - XX(MessageName, UserAction, posAction, NDTInteger, UserAction, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ - XX(MessageName, UserAction, negAction, NDTInteger, UserAction, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ - XX(MessageName, bool, checkFocus, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG(""), TRANSF) \ - XX(MessageName, bool, exclusive, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG(""), TRANSF) \ - -DECLARE_SIMPLE_NETWORK_STRUCTURE(ActionWithCurveSubscription,UPDATE_ACTIONWITHCURVE_SUBSCRIPTION_MSG) - -TypeIsSimple(ActionWithCurveSubscription) - -#define UPDATE_CLIENT_INPUT_ACTIONS(MessageName, XX) \ - XX(MessageName, AutoArray, actionState, NDTFloatArray, AutoArray, NCTFloat0To1, DEFVALUEFLOATARRAY, DOC_MSG("Input state"), TRANSF) \ - XX(MessageName, AutoArray, actionToDoState, NDTBoolArray, AutoArray, NCTNone, DEFVALUEBOOLARRAY, DOC_MSG("Input state"), TRANSF) \ - XX(MessageName, AutoArray, actionDoState, NDTBoolArray, AutoArray, NCTNone, DEFVALUEBOOLARRAY, DOC_MSG("Input state"), TRANSF) \ - XX(MessageName, AutoArray, actionWithCurveState, NDTFloatArray, AutoArray, NCTFloatMostly0To1, DEFVALUEFLOATARRAY, DOC_MSG("Input state"), TRANSF) \ - -#define UPDATE_CLIENT_INPUT_MSG(MessageName, XX) \ - UPDATE_CLIENT_INPUT_ACTIONS(MessageName, XX) \ - XX(MessageName, NetworkId, cursorObject, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Object under cursor"), TRANSF) \ - XX(MessageName, RString, cursorSurface, NDTString, RString, NCTNone, DEFVALUE(RString, ""),DOC_MSG("Surface under cursor"), TRANSF) \ - -DECLARE_NET_INDICES(UpdateClientInput, UPDATE_CLIENT_INPUT_MSG) - - -#define UPDATE_CLIENT_OUTPUT_MSG(MessageName, XX) \ - XX(MessageName, FindArrayKey, subscribed, NDTObjectArray, REF_MSG_ARRAY(NetworkMessageUpdateActionSubscription), NCTNone, DEFVALUE_MSG(NMTUpdateActionSubscription), DOC_MSG("Output state"), TRANSF_ARRAY) \ - XX(MessageName, FindArrayKey, subscribedToDo, NDTObjectArray, REF_MSG_ARRAY(NetworkMessageUpdateActionToDoSubscription), NCTNone, DEFVALUE_MSG(NMTUpdateActionToDoSubscription), DOC_MSG("Output state"), TRANSF_ARRAY) \ - XX(MessageName, FindArrayKey, subscribedDo, NDTObjectArray, REF_MSG_ARRAY(NetworkMessageUpdateActionDoSubscription), NCTNone, DEFVALUE_MSG(NMTUpdateActionDoSubscription), DOC_MSG("Output state"), TRANSF_ARRAY) \ - XX(MessageName, FindArrayKey, subscribedWithCurve, NDTObjectArray, REF_MSG_ARRAY(NetworkMessageUpdateActionDoSubscription), NCTNone, DEFVALUE_MSG(NMTUpdateActionWithCurveSubscription), DOC_MSG("Output state"), TRANSF_ARRAY) \ - XX(MessageName, AutoArray, shortcuts, NDTObjectArray, REF_MSG_ARRAY(NetworkMessageUpdateItemShortcut), NCTNone, DEFVALUE_MSG(NMTUpdateItemShortcut), DOC_MSG("Output state"), TRANSF_ARRAY) \ - XX(MessageName, AutoArray, myActions, NDTObjectArray, REF_MSG_ARRAY(NetworkMessageUpdateUIAction), NCTNone, DEFVALUE_MSG(NMTUpdateUIAction), DOC_MSG("Output state"), TRANSF_ARRAY) \ - XX(MessageName, AutoArray, targetActions, NDTObjectArray, REF_MSG_ARRAY(NetworkMessageUpdateUIAction), NCTNone, DEFVALUE_MSG(NMTUpdateUIAction), DOC_MSG("Output state"), TRANSF_ARRAY) \ - -DECLARE_NET_INDICES(UpdateClientOutput, UPDATE_CLIENT_OUTPUT_MSG) - - -// def. message -#define MEMBER_MUTABLE_DEF(MessageName,type,name,datatype,rawType, compres, defval, description, xfer) \ - mutable type _##name; - -// def. message -#define MEMBER_DEF(MessageName,type,name,datatype,rawType, compres, defval, description, xfer) \ - type _##name; - -/// transfer output state from server to client -/** included input settings as well */ -class ClientOutput: public NetworkSimpleObject -{ -public: - UPDATE_CLIENT_OUTPUT_MSG(dummy, MEMBER_DEF) - -public: - ClientOutput(); - - DECLARE_DEFINE_NETWORK_OBJECT_SIMPLE(UpdateClientOutput) - - static NetworkMessageFormat &CreateFormat(NetworkMessageClass cls, NetworkMessageFormat &format); - TMError TransferMsg(NetworkMessageContext &ctx) override; - void OnSent(); - void OnBeforeSend(const NetworkPlayerInfo &info); - - bool Compare(const ClientOutput *with) const; -}; - - -#define MEMBER_USED_MUTABLE_DEF(MessageName,type,name,datatype,rawType, compres, defval, description, xfer) \ - mutable AutoArray _##name##Used; - -/// transfer input state from client to server -class ClientInputState -{ - protected: - UPDATE_CLIENT_INPUT_MSG(dummy, MEMBER_MUTABLE_DEF) - - public: - bool Compare(const ClientInputState *with) const; - const NetworkId &GetCursorObject() const {return _cursorObject;} - const RString &GetCursorSurface() const {return _cursorSurface;} -}; - -class ClientInput: public NetworkSimpleObject, public InputInterface, public ClientInputState, private NoCopy -{ -protected: - bool _local; - - UPDATE_CLIENT_INPUT_ACTIONS(dummy, MEMBER_USED_MUTABLE_DEF) - -public: - // TODO: merge objects instead - SRef _output; - /// last state of the output sent out - SRef _outputLast; - -public: - ClientInput(bool local); - - // Only ClientInputState is transferred, but it is not NetworkSimpleObject (we want to keep it small) - DECLARE_DEFINE_NETWORK_OBJECT_SIMPLE(UpdateClientInput) - static NetworkMessageFormat &CreateFormat(NetworkMessageClass cls, NetworkMessageFormat &format); - TMError TransferMsg(NetworkMessageContext &ctx) override; - - virtual float GetAction(UserAction action, bool checkFocus = true, float digitalValue=1.0f, unsigned char level = 1) const override; - virtual bool GetActionToDo(UserAction action, bool reset = true, bool checkFocus = true, bool exclusive = false, unsigned char level = 1, bool blockButtons = false) override; - virtual bool GetActionDo(UserAction action, bool checkFocus=true) override; - virtual float GetActionWithCurve(CurveFactor factorKind, UserAction posAction, UserAction negAction, bool checkFocus = true, bool exclusive = false) const override; -}; - -class ClientInputLocal: public ClientInput -{ - - public: - - ClientInputLocal():ClientInput(true){} - - void ScanInput(); - void OnOutputReceived(const ClientOutput &output); -}; - -struct UpdateLocalObjectInfo; - -struct BodyInfo -{ - OLinkPermO(Person) body; - Time hideTime; - float value; -}; -TypeContainsOLink(BodyInfo) - -struct WreckInfo -{ - OLinkPermO(Transport) wreck; - Time hideTime; -}; -TypeContainsOLink(WreckInfo) - -class NetworkServer; -void DiagLogF(const char *format, ...); - -/// store event handler executed in reaction to PublicVariableMessage -struct PublicVariableEventHandler -{ - RString _name; -#if USE_PRECOMPILATION - Ref _code; -#else - RString _code; -#endif - - const char *GetKey() const {return _name;} - LSError Serialize(ParamArchive &ar); -}; -TypeIsMovableZeroed(PublicVariableEventHandler); - -template <> -struct MapClassTraits : public MapClassTraitsNoCase -{ -}; - -/// set of all registered event handlers executed in reaction to PublicVariableMessage -typedef MapStringToClass< PublicVariableEventHandler, AutoArray > PublicVariableEventHandlers; - -//! Network Command Types -/*! -\patch_internal 1.11 Date 07/31/2001 by Jirka -- Added: processing of commands entered in chat line -*/ -enum NetworkCommandType -{ - CMDNone = -1, - CMDLogin, - CMDLogout, - CMDKick, - CMDRestart, - CMDMission, - CMDMissions, - CMDShutdown, - CMDReassign, - CMDMonitor, - CMDUserlist, - CMDVote, - CMDAdmin, - CMDInit, - CMDDebug, - CMDExec, - CMDLock, - CMDUnlock, - CMDBEServer, - CMDBEClient, - CMDProfile, -#if _ENABLE_CHEATS - CMDGameExec, -#endif -#if _VBS3 - ,CMDExitAll -#endif -}; - -struct CheckSignatureItem -{ - int _bankIndex; - int _sigVer; - int _level; - bool _initialTest; - //! network message type and the prepared message itself (NMTFileSignatureAnswer or NMTDataSignatureAnswer) - int _type; - NetworkSimpleObject *_msg; - CheckSignatureItem() : _msg(NULL) {} - ~CheckSignatureItem() - { - if(_msg!=NULL) - { - delete _msg; - _msg=NULL; - } - } -}; -TypeIsMovable(CheckSignatureItem) - -template <> -struct FindArrayKeyTraits -{ - typedef int KeyType; - static bool IsEqual(int a, int b) {return a == b;} - static int GetKey(const CheckSignatureItem &a) {return a._bankIndex;} -}; - -template <> -struct ImplicitMapTraits -{ - static NetworkLocalObjectInfo null; ///< Empty value (can be passed as return value). - static NetworkLocalObjectInfo zombie; ///< Removed value (internal usage only). - -}; - -static inline bool operator != (const NetworkLocalObjectInfo &a, const NetworkLocalObjectInfo &b) {return a.id!=b.id;} -static inline bool operator == (const NetworkLocalObjectInfo &a, const NetworkLocalObjectInfo &b) {return a.id==b.id;} - -template <> -struct ImplicitMapTraits -{ - static NetworkRemoteObjectInfo null; ///< Empty value (can be passed as return value). - static NetworkRemoteObjectInfo zombie; ///< Removed value (internal usage only). - -}; - -static inline bool operator != (const NetworkRemoteObjectInfo &a, const NetworkRemoteObjectInfo &b) {return a.id!=b.id;} -static inline bool operator == (const NetworkRemoteObjectInfo &a, const NetworkRemoteObjectInfo &b) {return a.id==b.id;} - - - - - - -template <> -struct ImplicitMapTraits -{ - static NetworkDeletedObjectInfo null; ///< Empty value (can be passed as return value). - static NetworkDeletedObjectInfo zombie; ///< Removed value (internal usage only). - -}; - -static inline bool operator != (const NetworkDeletedObjectInfo &a, const NetworkDeletedObjectInfo &b) {return a.id!=b.id;} -static inline bool operator == (const NetworkDeletedObjectInfo &a, const NetworkDeletedObjectInfo &b) {return a.id==b.id;} - - - - -struct DelayedPublicVariable -{ - RString _name; - int _player; -}; -TypeIsMovableZeroed(DelayedPublicVariable) - -//! SpawnForPlayer code queued until the mission init script has run -struct DelayedSpawnForPlayer -{ - RString _code; - GameValue _args; -}; -TypeIsMovableZeroed(DelayedSpawnForPlayer) - -//! Network Client -class NetworkClient : public NetworkComponent -{ -protected: - //! DirectPlay ID of attached player - int _playerDpid; - - //! low-level client implementation - SRef _client; - -#if _USE_BATTL_EYE_CLIENT - /// BE Integration - class BattlEye - { - protected: - /// dll handle - HMODULE _library; - bool _initialized; - /// remember the scripts which were already checked and do not send them again - - static intptr_t KeyFromString(const RString &src) {return intptr_t(cc_cast(src));} - - ImplicitMap _checked; - AutoArray _checkedFIFO; - //@{ - /// callback functions - typedef void __cdecl PrintMessageF(const char *message); - static void __cdecl PrintMessage(const char *message); - //@} - - //@{ - /// dll functions - typedef bool __cdecl ExitF(); - typedef bool __cdecl RunF(); - typedef void __cdecl CommandF(const char *command); - - struct GameParams - { - unsigned long _address; - unsigned short _port; - PrintMessageF *_printMessage; - }; - GameParams _gameParams; - - struct BEPtrStruct - { - ExitF *_exit; - RunF *_run; - CommandF * _command; - CommandF * _onScriptExec; - }; - BEPtrStruct _callbacks; - - typedef bool __cdecl InitF(int iIntegrationVersion, GameParams *ppvGamePtrTable, BEPtrStruct *ppvBEPtrTable); - typedef int __cdecl GetVerF(); - //@} - - public: - BattlEye(); - ~BattlEye(); - - bool Init(NetworkClient *client); - void Done(); - bool Run(NetworkClient *client); - void Command(const char *command); - bool OnScriptExec(RString script); - - protected: - void CleanUp() - { - _library = NULL; - _callbacks._exit = NULL; - _callbacks._run = NULL; - _callbacks._command = NULL; - _callbacks._onScriptExec = NULL; - } - int GetBEVersion(HMODULE library) const; - }; - - BattlEye _beIntegration; - bool _beWanted; - -public: - bool BattlEyeOnScriptExec(RString script) - { - return _beIntegration.OnScriptExec(script); - } -protected: -#endif - - static NetworkId GetIdFromLocalNetworkObjectInfo(const NetworkLocalObjectInfo &info) {return info.id;} - static NetworkId GetIdFromRemoteNetworkObjectInfo(const NetworkRemoteObjectInfo &info) {return info.id;} - - typedef ImplicitMap LocalObjectsContainer; - typedef ImplicitMap RemoteObjectsContainer; - - - //! info about objects local on client - LocalObjectsContainer _localObjects; - //! info about objects non local (remote) on client - RemoteObjectsContainer _remoteObjects; - //! dead bodies (max MAX_LOCAL_BODIES can be simulated) - AutoArray _bodies; - //! wrecks (max MAX_LOCAL_WRECKS can be simulated) - AutoArray _wrecks; - - /// mark if team switch request is in progress - DWORD _teamSwitchDisabledUntil; - - //! message formats - AutoArray _formats; - //! message queues (candidates for aggregation) - NetworkMessageQueue _messageQueue, _messageQueueNonGuaranteed; - - //! connection quality to server - ConnectionQuality _connectionQuality; - /// de-sync detected by server - ConnectionDesync _connectionDesync; - //! result of _dp->Connect - ConnectResult _connectResult; - - //! current state - NetworkClientState _clientState; - //! current state on server - NetworkServerState _serverState; - - /// information about last know mission voting results - VotingMissionProgressMessage _missionVoting; - - /// last custom files progress state sent by NCMTCustomFilesProgress - int _customFilesProgressMax; - int _customFilesProgressPos; - - /// last timeout value received from the server, INT_MAX if none - int _serverTimeout; - - /// server hostname - RString _serverName; - - //! mission pbo file is valid (actual) - bool _missionFileValid; - - //! player is game master of dedicated server - bool _gameMaster; - //! gamemaster is only voted admin (cannot do shutdown etc.) - bool _admin; - //! show "select mission" dialog for dedicated server - bool _selectMission; - //! show "vote mission" dialog for dedicated server - bool _voteMission; - - //! Game is paused due to disconnection state of game - bool _controlsPaused; - - //! missions on dedicated server - AutoArray _serverMissions; - - //! name of local player - RString _localPlayerName; - - int _playerID; //player identity number - //! short id of player, used as creator in NetworkId - CreatorId _creatorId; - - //! id of next sound - incremented for each PlaySound - int _soundId; - //! list of sent sounds - AutoArray _sentSounds; - //! list of received sounds - AutoArray _receivedSounds; - - //! sound introducing chat message - SoundPars _chatSound; - - //! selected channel for voice chat - int _voiceChannel; - - //! ip address of dedicated server - sockaddr_in _serverVoNAddr; - - //! is NAT negotiation is needed to access server? - bool _natNegotiationNeeded; - - //! password used to connect to server - RString _serverPassword; - - //! used for transfer of client info (for example camera position) to server - Ref _clientInfo; - - SRef _clientInput; - SRef _clientInputLast; - - //! used for make the client camera position synchronized on all clients - Ref _clientCameraPosition; - - //! number of bodies we want to hide - int _hideBodies; - - //! number of wrecks we want to hide - int _hideWrecks; - -#if _VBS3 // player color - bool _sentPlayerColour; -#endif - -#if _ENABLE_CHEATS - //! debugging window - Link _debugWindow; -#endif - -#if _ENABLE_MP - /// who muted me - RemoteMuteListMessage _remoteMuteList; -#endif - -#if _ENABLE_GAMESPY - /// IP Address of the client (how is seen from matchmaking server) - int _publicAddr; -#endif - - /// world transfer progress info - int _totalToCreate; - int _remainingToCreate; - int _totalToUpdate; - int _remainingToUpdate; - - /// event handlers executed in reaction to PublicVariableMessage - PublicVariableEventHandlers _publicVariableEventHandlers; - - /// public variables which have Null networkId during PublicVariable are stored to be proccessed later again - AutoArray _delayedPublicVariables; - - //! true once the mission init script has run and spawned code may execute - bool _initScriptRun; - //! SpawnForPlayer code received before the mission init script ran - AutoArray _delayedSpawns; - - //! time synchronized from server to clients - DWORD _serverTime; - DWORD _serverTimeInitTickCount; - DWORD _serverTimeOfEstimatedEnd; - - //! server admin and gameMaster variables got by ServerAdminMessage - // used to know whether some commands like #vote is available - bool _serverAdmin; - int _serverGameMaster; - -#if _ENABLE_STEAM_MATCHMAKING - HAuthTicket _hAuthTicket; -#endif - -public: - - //! Constructor - /*! - \param parent creating network manager object - \param address URL address of server - \param password password of session - \param botClient client is bot client - */ - NetworkClient(NetworkManager *parent, RString address, RString password); - //! Connect to server - /*! - \param addr host Xbox Title Address - \param address URL address of server - \param password password of session - \return true if client is connected to server - */ - bool Init(RString address, RString password); - - //! Constructor for bot client - /*! - \param parent creating network manager object - \param playerRating rating of player in statistics - */ - NetworkClient(NetworkManager *parent, NetworkServer *server, int playerRating); - //! Connect bot client to server - bool Init(NetworkServer *server); - - //! Return dpid of attached player - int GetPlayer() const {return _playerDpid;} - -#if _ENABLE_GAMESPY - /// Set on which IP Address the client is visible from the matchmaking server - void SetPublicAddress(int addr) {_publicAddr = addr;} -#endif - - /// retrieve the local address client communicate on - bool GetLocalAddress(in_addr &addr) const {return _client ? _client->GetLocalAddress(addr) : false;} - bool GetDistantAddress(in_addr &addr, int &port) const {return _client ? _client->GetDistantAddress(addr,port) : false;} - /// retrieve the port client is listening for voice peer-to-peer communication - int GetVoicePort() const {return _client ? _client->GetVoicePort() : 0;} - - //! Voice over net initialization - void InitVoice(bool isBotClient=false); - //! Connect voice over net to the given player - void ConnectVoice(int player, sockaddr_in &addr); - - /// Suspend voice playback temporarily - void DisableVoice(bool disable); - /// Switches on/off the voice transmition - void SetVoiceTransmition(bool val) - { - #if VOICE_OVER_NET - if (_client) _client->SetVoiceTransmition(val); - #endif - } - /// Sets if voice is toggled on (user is NOT using push to talk button) - virtual void SetVoiceToggleOn(bool val) - { -#if VOICE_OVER_NET - if (_client) _client->SetVoiceToggleOn(val); -#endif - } - /// sets threshold for silence analyzer (0.0f - 1.0f) - virtual void SetVoNRecThreshold(float val) - { -#if VOICE_OVER_NET - if (_client) _client->SetVoNRecThreshold(val); -#endif - } - virtual void SetVoNTransmitterFreq(float f) - { -#if VOICE_OVER_NET - if (_client) _client->SetVoNTransmitterFreq(f); -#endif - } - virtual float GetVoNTransmitterFreq() const - { -#if VOICE_OVER_NET - if (_client) return _client->GetVoNTransmitterFreq(); -#endif - return 0; - } - virtual void SetVoNTransmitterRange(float range) - { -#if VOICE_OVER_NET - if (_client) _client->SetVoNTransmitterRange(range); -#endif - } - virtual float GetVoNTransmitterRange2() const - { -#if VOICE_OVER_NET - if (_client) return _client->GetVoNTransmitterRange2(); -#endif - return 1000000.f; - } - virtual void WhatUnitsOnTransmitterChannel(RefArray &units); - - /// Switches on/off the voice capturing - virtual void SetVoiceCapture(bool val, int quality) - { -#if VOICE_OVER_NET - if (_client) _client->VoiceCapture(val,quality); -#endif - } - - void CustomFilesProgressGet(int &max, int &pos) - { - max = _customFilesProgressMax; pos = _customFilesProgressPos; - } - void CustomFilesProgressClear() - { - _customFilesProgressMax = 1; _customFilesProgressPos = 0; - } - - //! Destructor - ~NetworkClient(); - - //! Disconnect from server - void Done(); - - bool IsValid() const {return _client != NULL;} - - //! Given player is currently speaking - bool IsVoicePlaying(int dpnid) const {return _client ? _client->IsVoicePlaying(dpnid) : false;} - - //! Local player is currently speaking - bool IsVoiceRecording() const {return _client ? _client->IsVoiceRecording() : false;} - - int CheckVoiceChannel(int dpnid, bool &audible2D, bool &audible3D) const - { - if (_client) - { - return _client->CheckVoiceChannel(dpnid,audible2D,audible3D); - } - audible2D = audible3D = false; - return 0; - } - - void IsVoice2D3DPlaying(int dpnid, bool &audible2D, bool &audible3D) const - { - if (_client) - { - _client->IsVoice2D3DPlaying(dpnid,audible2D,audible3D); - } - else - { - audible2D = audible3D = false; - } - } - - void DebugServerExec(RString str); - -#if _ENABLE_CHEATS - void VoNSay(int dpnid, int channel, int frequency, int seconds) - { - if (_client) _client->VoNSay(dpnid, channel, frequency, seconds); - } -#endif - - //! Return connection type info for each player along with the GDebugVoNBank output - RString GetDebugVoNString(); - - //! Server time synchronized to clients - DWORD GetServerTime() - { - _serverTime = ::GetTickCount() - _serverTimeInitTickCount; //make it fresh - return _serverTime; - } - - DWORD GetEstimatedEndServerTime() - { - return _serverTimeOfEstimatedEnd; - } - - RString ServerName() const { return _serverName; } - - int ConsoleF(const char *format, ...); - - //! Create debugging window - void CreateDebugWindow(); - - //! Return name of local player - RString GetLocalPlayerName() const {return _localPlayerName;} - //! Return result of _dp->Connect - ConnectResult GetConnectResult() const {return _connectResult;} - - //! Return if player is game master of dedicated server - bool IsGameMaster() const {return _gameMaster;} - - //! Return if gamemaster is only voted admin (cannot do shutdown etc.) - bool IsAdmin() const {return _admin;} - - //! Return if client is bot client - inline bool IsBotClient() const; - - inline NetworkServer *GetServer() const; - - //! Return connection quality to server - ConnectionQuality GetConnectionQuality() const {return _connectionQuality;} - - //! Return connection quality to server - ConnectionDesync GetConnectionDesync() const {return _connectionDesync;} - - //! Return current state - NetworkClientState GetClientState() const {return _clientState;} - //! Set state and send notification to server - void SetClientState(NetworkClientState state); - - //! Return how much part of world state was already transferred to client - bool GetTransferProgress(float &progress) const; - - //! Handler called when client is joining game in progress - void OnJoiningInProgress(); - - //! Clear possible structures keeping something related to dpnid of disconnecting player (such as subscribed radios) - void OnPlayerLogout(int dpnid); - - //! Time elapsed from start of mission on server - int TimeElapsed() const; - - //! Return current state on server - NetworkServerState GetServerState() const {return _serverState;} - - int GetServerTimeout() const {return _serverTimeout;} - - //! Return recommended chat priorty based on current game state - NetMsgFlags GetChatPriority() const; - - //! Set parameters for current mission - void SetParams(float param1, float param2, bool updateOnly); - //! Set parameters for current mission - void SetParams(float param1, float param2, AutoArray paramsArray, bool updateOnly); - - InputInterface *GetInputInterface(); - - void OnSimulate(); - void OnSimulateDone(); - - /// time critical network update - need to be called several times in frame - void FastUpdate(); - void OnDraw(); - void OnMessage(int from, NetworkMessage *msg, NetworkMessageType type); - - //! perform regular memory clean-up - unsigned CleanUpMemory(); - - /// called before network shutdown is initiated - can be called multiple times - void OnClose(); - //! Process received system messages - void ReceiveSystemMessages(); - //! Process received user messages - void ReceiveUserMessages(); - //! Destroy all received system messages - void RemoveSystemMessages(); - //! Destroy all received user messages - void RemoveUserMessages(); - - - //! Hi-level send of message to server - /*! - \param object message object - \param dwFlags DirectPlay flags - */ - DWORD SendMsg - ( - NetworkSimpleObject *object, NetMsgFlags dwFlags - ); - - //! Send single network message - /*! - This function determine, whic type of send will be used - local send, agregation or send using DirectPlay - \param to DirectPlay ID of message receiver - \param msg message itself - \param type type of message - \param dwFlags DirectPlay flags - */ - DWORD SendMsg - ( - int to, NetworkMessage *msg, - NetworkMessageType type, NetMsgFlags dwFlags, - NetworkObject *object - ); - virtual DWORD SendMsg - ( - int to, NetworkMessage *msg, - NetworkMessageType type, NetMsgFlags dwFlags - ) - { - return SendMsg(to, msg, type, dwFlags, NULL); - } - - Ref DXSendMsg(int to, NetworkMessageRaw &rawMsg, DWORD &msgID, NetMsgFlags dwFlags, const Ref &dependOn); - NetworkMessageFormatBase *GetFormat(/*int client, */int type); - const NetworkMessageFormatBase *GetFormat(/*int client, */int type) const; - - virtual void InitMsg(NetworkMessage *msg, NetworkMessageType type); - - //! Return short id of player, used as creator in NetworkId -#define DEBUG_CREATOR_ID 0 -#if DEBUG_CREATOR_ID - mutable bool _debugCreatorIdSet; -#endif - CreatorId GetCreatorId() const - { -#if DEBUG_CREATOR_ID - if (!_debugCreatorIdSet && _playerDpid!=BOT_CLIENT) - { - RptF("Warning: GetCreatorId called before its change!"); - static bool doIt = false; - if (doIt) - { - _debugCreatorIdSet = true; - } - } -#endif - return _creatorId; - } - //! Set player id directly (used on dedicated server - BOT client has no identity) - void SetCreatorId(CreatorId id) {_creatorId = id;} - void SetPlayerId(int id) {_playerID = id;} - - //! Select person as player - /*! - \param player DirectX player id - \param person player's person - \param respawn play "ressurect" cutscene - */ - void SelectPlayer(int player, Person *person, bool respawn = false); - // Send NMTSelectPlayer message to server - void SendSelectPlayer(int dpid, Person *person); - //! Play sound on all clients (except itself) - /*! - \param name name of sound file - \param position source position - \param speed source speed - \param volume sound volume - \param freq sound frequency - \param wave local sound object (for mapping local sounds to sent sounds) - */ - void PlaySound - ( - RString name, Vector3Par position, Vector3Par speed, - float volume, float freq, AbstractWave *wave - ); - //! Change state of played sound on all clients (except itself) - /*! - \param wave local sound object - \param state state to set - */ - void SoundState(AbstractWave *wave, SoundStateType state); - //! Register vehicle on client and send message to server (and other clients) - /*! - \param veh registered vehicle - \param type id of vehicle list to add into - \param name name of variable vehicle is stored in - \param idVeh id of vehicle (assigned in mission editor) - */ - bool CreateVehicle(Vehicle *veh, VehicleListType type, RString name, int idVeh); - //! Register subobject of vehicle on client and send message to server (and other clients) - /*! - \param veh owner vehicle - \param index unique id of object in vehicle - \param object created object - */ - bool CreateSubobject(Vehicle *veh, TurretPath &path, NetworkObject *object, bool setNetworkId=true); - //! Register generic network object and send message to server (and other clients) - bool CreateObject(NetworkObject *object, bool setNetworkId=true); - - bool SendCreateMessage( NetworkObject * object ); - - //! Send first update of all created objects over network (as guaranteed message) - void CreateAllObjects(); - //! Unregister all objects, both local and remote - void DestroyAllObjects(); - //! Force switch on pilot light - void AskForPilotLight(EntityAI *vehicle, bool enable); - //! Vehicle door open/close - void AskForVehicleDoorState(Transport *vehicle, int doorIndex, bool opened); - - void CreateObjectStatic(Object *who); - - void ExplosionDamage( EntityAI * owner, Vector3Par originDir, Object * directHit, Vector3Par directHitModelPos, HitInfoPar hitInfo, Object * componentOwner, int componentIndex, float energyFactor, float explosionFactor, float hitDepth ); - - //! Ask vehicle owner for change ammo state - /*! - \param vehicle vehicle which ammo is changing - \param turret turret which ammo is changing - \param weapon weapon index - \param burst amount of ammo to decrease - */ - void AskForAmmo( - EntityAIFull *vehicle, Turret *turret, const WeaponModePtr &ptr, int burst - ); - - //! Ask object owner for move object - /*! - \param vehicle moving object - \param pos new position - */ - void AskForMove - ( - Object *vehicle, Vector3Par pos - ); - //! Ask object owner for move object - /*! - \param vehicle moving object - \param trans new transformation matrix - */ - void AskForMove - ( - Object *vehicle, Matrix4Par trans - ); - - //! Ask magazine owner for change its ammo count - /*! - \param magazine - \param ammo - */ - void AskForSetMagazineAmmo - ( - Object *magazine, int ammo - ); - //! Transfer explosion effects (explosion, smoke, etc.) to other clients - /*! - \param owner shot owner (who is responsible for explosion) - \param shot shot - \param directHit hitted object - \param pos explosion position - \param dir explosion direction - \param dir index of the hit component - \param type ammunition - \param enemyDamage some enemy was damaged - \param explosionFactor how large explosion is - */ - void ExplosionDamageEffects - ( - EntityAI *owner, Object *directHit, HitInfoPar hitInfo, int componentIndex, - bool enemyDamage, float energyFactor, float explosionFactor - ); - //! Transfer projectile decals (arrows stuck on body, etc.) to other clients - /*! - \param directHit Object that got hit - \param componentIndex Index of the component that got hit - \param hitInfo Info about the hit - \param hitDepth The depth of penetration - \param hitPosLcl Hit position on the body (local space) - \param hitDirLcl Hit direction relative to the body part (local space) - \param hitDirUpLcl Up direction of hit relative to the body part (local space) - */ - void ApplyProjectileDecal - ( - Object *directHit, int componentIndex, HitInfoPar hitInfo, float hitDepth, Vector3Par hitPosLcl, Vector3Par hitDirLcl, Vector3Par hitDirUpLcl - ); - //! Remove on other clients the projectile decals stuck on victim's body - /*! - \param person The person from which projectiles are removed - */ - void RemoveProjectileDecals(Object *person); - //! Transfer fire effects (sound, fire, smoke, recoil effect, etc.) to other clients - /*! - \param vehicle firing vehicle - \param weapon firing weapon index - \param magazine fired magazine - \param target aimed target - */ - void FireWeapon( - EntityAIFull *vehicle, Person *gunner, const WeaponModePtr &ptr, Magazine *magazine, EntityAI *target, - const RemoteFireWeaponInfo &remoteInfo - ); - //! Transfer bow action state to other clients - /*! - \param entity Person using the bow - \param state The state of bow - */ - void UpdateBowState(EntityAIFull *entity, BowState state ); - //! Set a texture for a vehicle on other clients - /*! - \param vehicle vehicle that will have a texture changed - \param index selection index to change - \param name texture name to use - */ - void SetObjectTexture(EntityAI *veh, int index, RString name, RString eval = "true"); - //! Execute game code on other clients - /*! - \param condition game code to evaluate to true or false - \param command game code to execute - \param obj object to pass as _this - \param objs array of objects to pass as _this - */ - void PublicExec(RString condition, RString command, Object* obj, OLinkArray(Object) &objs); - //! Transfer message who is responsible to destroy vehicle to other clients - /*! - \param killed destroyed vehicle - \param killer who is responsible for destroying - */ - void OnVehicleDestroyed(EntityAI *killed, EntityAI *killer); - //! Transfer message about damage of vehicle to other clients - /*! - \param damaged damaged vehicle - \param damage amount of damage hit - \param ammo ammunition type - */ - void OnVehicleDamaged(EntityAI *damaged, EntityAI *killer, float damage, RString ammo); - //! Transfer info about (user made) marker creation to other clients - /*! - \param channel chat channel (who will see the marker) - \param sender sender unit - \param units receiving units - \param info marker itself - */ - void MarkerCreate(int channel, AIBrain *sender, RefArray &units, ArcadeMarkerInfo &info); - //! Transfer info about (user made) marker was deleted to other clients - /*! - \param name name of marker - */ - void MarkerDelete(RString name); - - //! Public variable to other clients - /*! - \param name variable name - */ - void PublicVariable(RString name, int dpnid); - - void SendAUMessage(GameValuePar oper1); - - /** - Do ErrF locally and send the message to the server as well. - */ - void ServerErrF(const char *format, ...); - - //! Public variables which contains objects with NULL networkId are processed after CreateAllObjects again - void ProcessDelayedPublicVariables(); - void ClearDelayedPublicVariables(); - void AddDelayedPublicVariable(RString name, int dpnid); - - //! Run a SpawnForPlayer code on this client - void RunSpawnedCode(RString code, GameValuePar args); - //! Run all SpawnForPlayer code delayed until the mission init script ran - void ProcessDelayedSpawns(); - - //! Send chat message - /*! - \param channel chat channel - \param text chat text - */ - void Chat(int channel, RString text); - - //! Send chat message - /*! - \param channel chat channel - \param sender sender unit - \param units receiving units - \param text chat text - */ - void Chat(int channel, AIBrain *sender, RefArray &units, RString text); - //! Send chat message - /*! - \param channel chat channel - \param sender sender name - \param units receiving units - \param text chat text - */ - void Chat(int channel, RString sender, RefArray &units, RString text); - - /// Send client-side localized chat message - void LocalizedChat(int channel, const LocalizedFormatedString &text); - - /// Send client-side localized chat message - /*! - \param channel chat channel - \param sender sender unit - \param units receiving units - \param text chat text - */ - void LocalizedChat(int channel, AIBrain *sender, RefArray &units, const LocalizedFormatedString &text); - /// Send client-side localized chat message - /*! - \param channel chat channel - \param sender sender name - \param units receiving units - \param text chat text - */ - void LocalizedChat(int channel, RString sender, RefArray &units, const LocalizedFormatedString &text); - - //! Send radio message as chat (text and sentence) - /*! - \param channel chat channel - \param sender sender name - \param units receiving units - \param text chat text - \param sentence - list of words to be spoken - */ - void RadioChat(int channel, AIBrain *sender, RefArray &units, RString text, RadioSentence &sentence); - //! Send text radio message as chat (sound and title) - /*! - \param channel chat channel - \param units receiving units - \param wave name of class from CfgRadio containing sound and title - \param sender sender unit - \param senderName sender name - */ - void RadioChatWave(int channel, RefArray &units, RString wave, AIBrain *sender, RString senderName); - - /// Return actual channel for voice chat - int GetVoiceChannel() const {return _voiceChannel;} - //! Set channel for Voice Over Net - /*! - \param channel chat channel - */ - void SetVoiceChannel(int channel); - //! Set position and speed of some Voice Over Net source (it affects sources) - /*! - \param dpnid player id got from GetRemotePlayer() - \param pos position of player - \param speed speed of player - */ - void SetVoNPosition(int dpnid, Vector3Par pos, Vector3Par speed); - //! Set position and speed of player in Voice Over Net (it affects listener) - /*! - \param pos position of player - \param speed speed of player - */ - void SetVoNPlayerPosition(Vector3Par pos, Vector3Par speed); - //! Set obstruction of player in Voice Over Net (it affects source) - /*! - \param dpnid player id got from GetRemotePlayer() - */ - void SetVoNObstruction(int dpnid, float obstruction, float occlusion, float deltaT); - //! Updates volume and ear accomodation of player in Voice Over Net (it affects source) - /*! - \param dpnid player id got from GetRemotePlayer() - */ - void UpdateVoNVolumeAndAccomodation(int dpnid, float volume, float accomodation); - //! Advance all voices in VoN (even muted ones) - /*! - \param deltaT time to advance - \param paused whether game is paused - \param quiet whether voices should be muted - */ - void AdvanceAllVoNSounds( float deltaT, bool paused, bool quiet ); - - //! Send update of the content of the Custom Radio Channel - /*! - \param channel The channel in range CCCustom1..CCCustomLast - \param ucr_type What to update (all, label, callSign, units, ...) - */ - void UpdateCustomChannel(int channel, int ucr_type); - - //! Transfer file to server - /*! - \param dest destination filename - \param source source filename - */ - void TransferFileToServer(RString dest, RString source); - //! Retrieve state of file transfer - /*! - \param curBytes amount of transfered bytes - \param totBytes total amount bytes to transfer - */ - void GetTransferStats(int &curBytes, int &totBytes); - void ApplyWeather(); -#if _VBS2 //Convoy trainer - void AARDoUpdate(int type ,int intType,RString stringOne = RString(), RString stringTwo = RString(), float floatType = 0.0); - void AARAskUpdate(int type ,int intType,RString stringOne = RString(), RString stringTwo = RString(), float floatType = 0.0); - void AddMPReport(int type, RString myString); - void LoadIsland(RString islandName); - void AskWeather(); - void AskCommanderOverride(Turret *turret, Turret *overriddenByTurret); -#endif - //! Ask vehicle owner to destroy vehicle - /*! - \param vehicle vehicle to destroy - */ - void AskForDeleteVehicle(Entity *veh); - - void AskForSetItemShortcut(Person *person, int index, const InventoryItemType *type, InventoryItem *item); - void AskForThrowItem(Man *person, InventoryItem *item, Vector3 pos, Vector3 dir); - void AskForDropItem(Person *person, InventoryItem *item); - void AskForMoveItem(EntityAI *target, int index, InventoryItem *item, bool rotated); - void AskForRotateInventoryItem(Person *person, InventoryItem *item); - void AskForTakeItemToHands(Person *person, InventoryItem *item); - void AskForSwapItems(InventoryItem *item1, InventoryItem *item2, Person *owner); - - void AskForPlayerAction( Person * person, RString action ); - - void AskInventoryMenu(AIBrain *unit, InventoryItem *item1, InventoryItem *item2); - -#if _VBS3 // respawn command - //! Tell local simulation to pause itself - /*! - \param pause simulation true or false - */ - void PauseSimulation(bool pause); -#endif - -#if _ENABLE_ATTACHED_OBJECTS - //! Attach Object - /*! - \param obj, object to attach - \param attachTo, where does the object get attached to? - \param memindex, memory point index were it get's attach to parent, (-1) for center - \param pos, position offset from attachPoint - \param flags, additional flags - */ - void AttachObject(Object *obj, Object *attachTo, int memIndex, Vector3 pos, int flags); - //! detach object - /*! - \param obj, object to detach - */ - void DetachObject(Object *obj); -#endif - - //! Ask vehicle for user defined animation - /*! - \param vehicle animated vehicle - \param animation animation name - \param phase wanted animation phase - */ - void AskForAnimationPhase(Entity *vehicle, RString animation, float phase); - - //! Checks if gamemaster is to select mission on dedicated server - bool CanSelectMission() const {return _selectMission;} - //! Checks if client is to vote mission on dedicated server - bool CanVoteMission() const {return _voteMission;} - //! Returns array of missions available on dedicated server - const AutoArray &GetServerMissions() const - { - return _serverMissions; - } - - /// check voting status - const VotingMissionProgressMessage *GetMissionVotingState() const {return &_missionVoting;} - //! Select mission on dedicated server - /*! - \param mission name of selected mission - \param difficulty game difficulty level - */ - void SelectMission(RString mission, int difficulty); - //! Vote mission on dedicated server - /*! - \param mission name of selected mission - \param difficulty game difficulty level - */ - void VoteMission(RString mission, int difficulty); - - /// Find the object (local or remote) by its network id - NetworkObject *GetObject(const NetworkId &id); - //! Unregister given network object, send message to others - void DeleteObject(const NetworkId &id, bool sendMsg); - - //! Process chat command for remote control of dedicated server - /*! - \param command chat command - */ - bool ProcessCommand(RString command); - bool IsCommandAvailable(NetworkCommandType type); - bool IsCommandAvailable(RString command); - - //! Ask server to kick off player - /*! - \param player DirectPlay ID of player to kick off - */ - void SendKick(int player); - - //! Ask server to disable/enable connection of further clients - /*! - \param lock true to disable connection - */ - void SendLockSession(bool lock = true); - - //! player must disconnect due to some mission loading error - void Disconnect(RString message); - - //! Force update of network object - /*! - \param object object to update - \param dwFlags DirectPlay flags - */ - void UpdateObject(NetworkObject *object, NetMsgFlags dwFlags); - - //! Force update of network object (single type of update) - /*! - \param object object to update - \param cls type of update - \param dwFlags DirectPlay flags - */ - int UpdateObject(NetworkObject *object, NetworkMessageClass cls, NetMsgFlags dwFlags); - - const char *GetDebugName() const {return "Client";} - - RString GetDiagText(const NetworkObject *obj) const; - - //! Return estimated end of mission time - Time GetEstimatedEndTime() const; - - //! Body can be hidden (for better performance) - void DisposeBody(Person *body); - - //! Wreck can be hidden (for better performance) - void DisposeWreck(Transport *wreck); - - //! Game is paused due to disconnection state of game - bool IsControlsPaused() {return _controlsPaused;} - - //! Last received message's age in seconds (used to eliminate "disconnect cheat") - float GetLastMsgAgeReliable(); - - //! Cleanup unit after player disconnection - void CleanupPlayer(int dpnid, NetworkId id); - - //! Set voice mask to new value (Xbox) - void ChangeVoiceMask(RString mask); - - /// Reaction to detection of hacked data - void HackedDataDetected(RString filename); - - /// add event handler executed in reaction to PublicVariableMessage - void AddPublicVariableEventHandler(RString name, GameValuePar code); - - void SynchronizeVariable( EntityAI * veh, RString name, float coef, const GameDataCode & code ); - - void ProcessAction(Action *action, AIBrain *unit); - - void ProcessRecipe(RString recipe, Person *person, InventoryItem *item1, InventoryItem *item2); - - // implementation -protected: - //! Find info about local object with given id (NULL if not found) - NetworkLocalObjectInfo *GetLocalObjectInfo(const NetworkId &id); - //! Find info about remote object with given id (NULL if not found) - NetworkRemoteObjectInfo *GetRemoteObjectInfo(const NetworkId &id); - - //! Register network object as local object, assign id to them - NetworkId CreateLocalObject(NetworkObject *object, bool setNetworkId=true); - - void InsertLocalObject(NetworkObject *object); - - void InsertRemoteObject(NetworkObject *obj, bool remote); - - //! Prepare multiplayer game - /*! - Switch landscape, parse mission sqm file, initialize GWorld. - */ - bool PrepareGame(); - - //! Perform actions needed when client reach state NCSPlaying - void OnMissionStarted(); - - //! Select player on local machine - void ProcessSelectPlayer(Person *person, bool respawn, Vector3Par pos); - - ///! Create and Update messages can be received only when client is ready to play - inline bool CanReceiveUpdateMessages() - { - return (_clientState >= NCSMissionReceived && _clientState <= NCSPlaying); - } - - //! Create network object and register as remote object - /*! - \param ctx network message context of create message - \param dummy dummy argument for specification type of created network object - */ - template - bool CreateRemoteObject(NetworkMessageContext &ctx) - { - VehType *dummy; // VehType not seen inside of lambda (Visual Studio 2010), this is a trick to pass it there - auto create = [dummy](NetworkMessageContext &ctx)->NetworkObject * {return dummy->CreateObject(ctx);}; - return CreateRemoteObject(ctx,create); - } - - bool CreateRemoteObject(NetworkMessageContext &ctx, std::function create); - - //! Unregister and destroy remote network object - void DestroyRemoteObject(NetworkId id); - - //! Enforce destruction of (local or remote) object - void ForceDeleteObject(NetworkObject *object); - - //! Send all agregated and update messages - void SendMessages(); - //! Calculate limits for message sending - void EstimateBandwidth(int &nMsgMax, int &nBytesMax); - //! Calculate errors and place object in list sorted by error - /*! - \param objects output sorted list of objects - */ - void CreateObjectsList(AutoArray &objects); - //! Prepare next object update message to message queue - bool PrepareNextUpdate(AutoArray &objects, int &next); - - //! Return number of auto destroyed local objects - used for debugging purposes - int NLocalObjectsNULL() const; - //! Check database of local objects - used for debugging purposes - bool CheckLocalObjects() const; - - /// clear voting once we know it is no longer valid - void ClearMissionVoting(); - //! Server state changed - void OnServerStateChanged(NetworkServerState state); - - //! State change enforced by server - void OnClientStateChanged(NetworkClientState state); - - void EnqueueMsg - ( - int to, NetworkMessage *msg, - NetworkMessageType type, - NetworkObject *object - ); - void EnqueueMsgNonGuaranteed - ( - int to, NetworkMessage *msg, - NetworkMessageType type, const RefR &dependOn - ); - - //! Returns which players hear me - void GetPlayersOnChannel(AutoArray &players, int channel) const; - //! Returns which players can hear me in direct speak (are within the radius range depending on channel) - void GetTargetsInDirectSpeakRange(AutoArray &players, int channel) const; - - //! Check if player is in remote mute list (local player muted by given player) - bool IsPlayerInRemoteMuteList(int player) const; - -protected: - //! start validation of bank hash - //! \param askedIndex index matching NMTDataSignatureAsk - //! \param qBankIx index of bank inside global GFileBanks - //! \return true when check was succesful - bool CheckDataSignature(int askedIndex, int level, QFBank &bank, int gBankIx); - //! start validation of other additional file hash - bool CheckDataSignature(int askedIndex, int level, RString filename); - //! start validation of bank hash (using filename to find inside some bank, sig.ver > 1) - bool CheckFileSignature( int bankIndex, int level, RString filename ); - - /// queue of banks waiting for signature check - FindArrayKey _checkSignatureQueue; - /// currently checked signature - SRef _checkingSignature; - -#if defined _XBOX && _XBOX_VER >= 200 - /// updates all needed based on new local player info list - void UpdateLocalPlayerInfoList(const LocalPlayerInfoList& localPlayerInfoList); - - -#endif -}; - -//! Info about single type of update of network object -struct NetworkCurrentInfo -{ - //! type of message - NetworkMessageType type; - //! sender of message - int from; - //! last received state of object - Ref message; -}; - -#include - -//! info about state of sent updates of network object for single client -struct NetworkPlayerObjectInfo: public RefCount, public TLinkBidirD -{ - //! ID of player - int player; - /// backlink to NetworkObjectInfo, needed for OnStopUpdating - NetworkObjectInfo *oInfo; - //! state of updates - NetworkUpdateInfo updates[NMCUpdateN]; - //! All updates depends on this message (to be handled after) - RefR _fence; - //! is within the updating range - bool updating; - - NetworkPlayerObjectInfo(); - ~NetworkPlayerObjectInfo(); - - //! allocated quite often - USE_FAST_ALLOCATOR -}; - -#include - -//! Info about network object on server -/*! -\patch_internal 1.23 Date 9/18/2001 by Jirka -- Improved: storage of PlayerObjectInfo changes -*/ -#include - -/// messages waiting to be sent until acknowledgement OwnerChanged arrives from previous owner in ChangeOwner process -struct WaitingMessageInfo: public RefCount -{ - Ref msg; - NetworkMessageType type; - - WaitingMessageInfo(NetworkMessageType t, NetworkMessage *m) : msg(m), type(t) {}; - - USE_FAST_ALLOCATOR -}; - -UNIQUE_TYPE(PlayerIndex,int); - -struct NetworkObjectInfo: public RefCount -{ - //! ID of object - NetworkId id; - /// the object itself - OLinkNO(NetworkObject) object; - //! DirectPlay ID of owner client - int owner; - //! DirectPlay ID of new owner client pending (ChangeOwner message sent but waiting to acknowledgment OwnerChanged message) - //! when set to NO_CLIENT no change owner is pending - int pendingOwner; - //! create message (used for JOIN IN PROGRESS) - NetworkCurrentInfo create; - //! state of last received updates - NetworkCurrentInfo currentUpdate[NMCUpdateN]; - //! state of last received updates sent from owner when bot-client sent overrides - NetworkCurrentInfo currentRejected[NMCUpdateN]; - //! current rejection status reported by a bot-client - InitVal rejected[NMCUpdateN]; - //! state of last sent updates (for each player) - RefArray playerToObjects; - //! messages waiting to be sent to clients until acknowledgment OwnerChanged arrives from previous owner in ChangeOwner process - RefArray waitingMessages; - - struct UpdateInfo - { - Vector3 _pos; - float _updateDistance; - - UpdateInfo():_pos(VZero),_updateDistance(FLT_MAX){} - }; - UpdateInfo _updInfo; - - NetworkObjectInfo(); - ~NetworkObjectInfo(); - - //! Find info about network object for given player - NetworkPlayerObjectInfo *GetPlayerObjectInfo(PlayerIndex player, int pid); - //! Create info (register) of new network object for given player - NetworkPlayerObjectInfo *CreatePlayerObjectInfo(PlayerIndex player, int pid); - //! Delete info (unregister) network object for given player - void DeletePlayerObjectInfo(PlayerIndex player, int pid); - //! Delete info (unregister) network object for given player (used when player becomes an owner) - void NullPlayerObjectInfo(PlayerIndex player, int pid); - //! Forget the updates sent to given player - void ResetPlayerObjectInfo(PlayerIndex player, int pid); - - UpdateInfo BestPosition(const NetworkServer *server) const; - UpdateInfo BestPosition() const; - bool CheckBestPositionIntegrity(const NetworkServer *server) const; - - void ScanBestPosition(const NetworkServer *server); - - UpdateInfo CheckBestPosition(const NetworkServer *server) const; - RString GetDebugName() const; - - //! Objects of this type will be allocated quite often - USE_FAST_ALLOCATOR -}; -//TypeIsMovable(NetworkObjectInfo) - -#include - -//! calculate min, max and average from set of values -class CalculateMinMaxAvg -{ - float _min,_max,_sum; - float _weight; - /// last value sampled - float _lastValue; - - public: - CalculateMinMaxAvg(); - //! add sample - void Sample(float value, float weight=1); - //! reset - void Reset(); - //! get current results (min) - float GetMin() const {return _weight>0 ? _min : 0;} - //! get current results (max) - float GetMax() const {return _weight>0 ? _max : 0;} - //! get current results (average) - float GetAvg() const {return _weight>0 ? _sum/_weight :0;} - /// get last value - float GetLastValue() const {return _lastValue;} -}; - -struct PendingDataSignatureCheck -{ - //! the index of checked file - DWORD answerIndex; - //! timeout for question - DWORD checkTimeout; -}; - -TypeIsSimple(PendingDataSignatureCheck) - -struct PendingFileSignatureCheck -{ - //! the checked file - RString filename; - //! the pbo prefix - RString prefix; - //! timeout for question - DWORD checkTimeout; -}; - -TypeIsMovableZeroed(PendingFileSignatureCheck) - -// Helper functor -class CheckSignatureTimeoutFunc -{ -public: - virtual bool operator ()() = 0; -}; - -//! PendingSignatureChecks encapsulates both PendingDataSignatureCheck and PendingFileSignatureCheck -class PendingSignatureChecks -{ - AutoArray pendingFileChecks; - AutoArray pendingDataChecks; -public: - PendingSignatureChecks() {} - - // both data and file signature pendings are checked for timeout and given action is processed when timeouted - void CheckTimeouts(CheckSignatureTimeoutFunc &func -#define DEBUG_SIGNATURES 1 -#if DEBUG_SIGNATURES - , RString &errorInfo -#endif - ); - - // add some time to timeout of initial data signature check - void UpdateInitialCheckTimeout(); - - // add the time specified to all signature timeouts - void DelayCheckTimeouts(DWORD time, const char *playerName); - - //@{ interface to work with PendingDataSignatureChecks - bool Pending(int bankIndex) - { - for (int i=0; i - -/// messages waiting to be sent -struct DelayedMessageInfo: public RefCount -{ - Ref msg; - NetworkMessageType type; - float error; - float invMaxAge; - Vector3 pos; - /// when the message was received - Time timeReceived; - - DelayedMessageInfo(NetworkServer *server, NetworkMessageType t, NetworkMessage *m); - - USE_FAST_ALLOCATOR -}; - -#include - -struct CDKeyCheck -{ - DWORD timeout; - CDKeyCheck() : timeout(0) {} -}; - -//! Hashes collected from DataSignatureAnswer messages -class CollectedHashes -{ - struct CollectedHash - { - RString fileName; - RString prefix; - Temp hash; // DataContentHash - Temp ver2lev0hash; // hash of ( DataContentHash + fileListHash + pbo prefix) - Temp ver2lev2hash; // hash of (nonDataContentHash + fileListHash + pbo prefix) - - //! CollectedHash is initialized during initial SignatureCheck - CollectedHash(RString filNam, Temp &hs) : fileName(filNam), hash(hs) {} - CollectedHash() {}; - ClassIsMovable(CollectedHash) - }; - - static const int SignatureCheckLevels = 3; - struct RandomUsedFileCandidate - { - RString filename; - RString prefix; - int levelAsksCount[CollectedHashes::SignatureCheckLevels]; - - RandomUsedFileCandidate() {} - RandomUsedFileCandidate(RString fn, RString prf) : filename(fn), prefix(prf) - { - for (int i=0; i hashes; - //! collecting hashes from client is in progress (through NetworkServer::InitialSignaturesTest(...)) - bool _collecting; - //! maps prefix to the RandomUsedFileCandidate to track how often which asks are sent - typedef MapStringToClass > PrefixToCandidate; - PrefixToCandidate _candidatesMap; - -public: - static const int CollectEndIndex = 0x50be; //mnemo Sobe - //! number of pbo files loaded - int banksCount; // -1 is default value meaning the client has not sent this information - //! next time for full check (level 1) - DWORD fullCheckNext; - //! timeout time to get banksCount and iKnowLevel2 info - DWORD bankInfoTimeout; - -private: -#if DEBUG_SIGNATURES - RString lastError; -#endif - - void Collecting(bool collect) { _collecting = collect; } - void Clear() { hashes.Resize(0); } - - // return true when HACK detected - bool TestLevelHash(CollectedHash &colHash, int index, int colIndex, Temp &hash, int sigVer, int level) - { - if (!_collecting && index>=0) - { - if ( colIndex != (index % SignaturesCount()) ) - { -#if DEBUG_SIGNATURES - lastError = Format("ColIx(%d)-Ix(%d)", colIndex, index); -#endif - return true; //hack detected - } - } - switch (sigVer) - { - case 1: - { // hash param is the DataContentHash - if (hash.Size() != colHash.hash.Size() || - memcmp(hash.Data(), colHash.hash.Data(), hash.Size()) != 0) return true; //hack detected - } - break; - case 2: - { - switch (level) - { - case 0: - case 1: // hash param is the sigVer2, level=0 hash - if (colHash.ver2lev0hash.Size()>0) - { - if (hash.Size() != colHash.ver2lev0hash.Size() || - memcmp(hash.Data(), colHash.ver2lev0hash.Data(), hash.Size()) != 0) - { -#if DEBUG_SIGNATURES - lastError = "DiffLev0Hash"; -#endif - return true; //hack detected - } - } - else - { // collect ver2lev0hash - colHash.ver2lev0hash = hash; - } - break; - case 2: // hash param is the sigVer2, level=2 hash - if (colHash.ver2lev2hash.Size()>0) - { - if (hash.Size() != colHash.ver2lev2hash.Size() || - memcmp(hash.Data(), colHash.ver2lev2hash.Data(), hash.Size()) != 0) - { -#if DEBUG_SIGNATURES - lastError = "DiffLev2Hash"; -#endif - return true; //hack detected - } - } - else - { // collect ver2lev2hash - colHash.ver2lev2hash = hash; - } - break; - default: -#if DEBUG_SIGNATURES - lastError = "UnknownLevel"; -#endif - return true; // unrecognized level - } - } - break; - default: -#if DEBUG_SIGNATURES - lastError = "UnknownVer"; -#endif - return true; //unknown version - } - return false; //ok - } - // Test the hash against the collectedHash with the given fileName - // return true when HACK detected - bool Test(RString fileName, int index, Temp &hash, int sigVer, int level) - { - if (index>=0) - { - if (!SignaturesCount()) - return true; //HACK, unexpected message with index set during collecting phase - index = index % SignaturesCount(); - if (hashes[index].fileName != fileName) - { -#if DEBUG_SIGNATURES - lastError = "Ix&File"; -#endif - return true; //HACK, index and fileName does not match - } - return TestLevelHash(hashes[index], index, index, hash, sigVer, level); - } - else - { - for (int i=0; i &dataContentHash, Temp &levelHash, int sigVer, int level) - { - // use index when set - if (index>=0) - { - if (!SignaturesCount()) - { -#if DEBUG_SIGNATURES - lastError = "NoStoredSig"; -#endif - return true; //HACK, unexpected answer with index set during collecting phase - } - // cut index to fit within range using modulo - index = index % SignaturesCount(); - // Test prefix - if (hashes[index].prefix.IsEmpty()) - hashes[index].prefix = prefix; // set it at last - else if (hashes[index].prefix!=prefix) - { -#if DEBUG_SIGNATURES - lastError = Format("DiffPrefix(%s,%s)", cc_cast(hashes[index].prefix), cc_cast(prefix)); -#endif - return true; //HACK, prefixes differ - } - // Test dataContentHash - Temp &colDataContentHash = hashes[index].hash; - if ( !colDataContentHash.Size() ) - colDataContentHash = dataContentHash; //possible collect it (but maybe empty again) - else if ( - dataContentHash.Size() && - (dataContentHash.Size()!=colDataContentHash.Size() || (memcmp(dataContentHash.Data(), colDataContentHash.Data(), dataContentHash.Size()) != 0) ) - ) - { -#if DEBUG_SIGNATURES - lastError = "DiffDCH"; -#endif - return true; //dataContentHashes differ - } - // Test levelHash - if (levelHash.Size()) - return TestLevelHash(hashes[index], index, index, levelHash, sigVer, level); - else - return false; //OK, nothing else to check - } - else - { // this happen only for clients before rev.78326 - if (levelHash.Size()>0) - { - for (int i=0; i &hash, int sigVer, int level) - { - for (int i=0; i *colHash = NULL; - if (sigVer==1) colHash = &hashes[i].hash; - else switch (level) - { - case 0: - case 1: colHash = &hashes[i].ver2lev0hash; break; - case 2: colHash = &hashes[i].ver2lev2hash; break; - } - if ( hashes[i].fileName==fileName || - (colHash!=NULL && hash.Size() == colHash->Size() && - memcmp(hash.Data(), colHash->Data(), hash.Size()) == 0) - ) - { -#if DEBUG_SIGNATURES - if (hashes[i].fileName==fileName) - lastError = "SameFile"; - else - lastError = "SameSig"; -#endif - return i; - } - } - return -1; //not found - } - -public: - CollectedHashes() : _collecting(false), banksCount(-1) - { - fullCheckNext = GlobalTickCount() + 40000 + toInt(40000 * GRandGen.RandomValue()); // initial delay 40 s - 80 s - bankInfoTimeout = 0; // no timeout yet - } - - void StartCollecting() - { - Clear(); - Collecting(true); - } - - //! In spite of we are collecting hashes, the SignaturesCount suits better - int SignaturesCount() const - { - if (_collecting) return 0; - else - { - return hashes.Size(); - } - } - - //! AddHash based on fileName [DataSignatureAnswer] - //! return true when HACK detected - bool AddHash(int index, RString fileName, Temp &hash, int sigVer, int level, PendingSignatureChecks &pendingChecks) - { -#if DEBUG_SIGNATURES - lastError = ""; -#endif - //RptF("AddHash: %s, ix=%d, ver=%d, lev=%d", cc_cast(fileName), index, sigVer, level); - if (index<0) - { - if (!_collecting) return Test(fileName, index, hash, sigVer, level); //fileName based Test - else // we are collecting - { - int ix = ArrayIx(fileName, hash, sigVer, level); - if (ix>=0) - { -#if DEBUG_SIGNATURES - lastError = RString("Duplo-") + lastError;; -#endif - return true; //hack detected (the same answer sent second time) - } - // new hash - switch (sigVer) - { - case 1: hashes.Add(CollectedHash(fileName, hash)); break; - case 2: - { - switch (level) - { - case 0: - case 1: - { - int ix = hashes.Add(CollectedHash()); - CollectedHash &colHash = hashes[ix]; - colHash.fileName = fileName; - colHash.ver2lev0hash = hash; - } - break; - case 2: - { - int ix = hashes.Add(CollectedHash()); - CollectedHash &colHash = hashes[ix]; - colHash.fileName = fileName; - colHash.ver2lev2hash = hash; - // we are collecting and asynchronous level=2 check is used. Add more time to pending signature check - pendingChecks.UpdateInitialCheckTimeout(); - } - break; - default: return true; //unrecognized level - } - } - break; - default: return true; //unrecognized version - } - } - return false; //ok - } - else - { - if (_collecting) - { - if (index==CollectEndIndex) - { - _collecting = false; - // when there are too few initial DataSignatureAnswers during "collecting" phase, - // the client is supposed to be cheating. The limit is chosen conservative enough (30 banks). - const int MinimalBankCount = 30; - if ( SignaturesCount() < MinimalBankCount ) - { -#if DEBUG_SIGNATURES - lastError = "MinSigCount"; -#endif - return true; - } - if (UpdatePlayerBankCount(SignaturesCount())) - return true; //hacked - } - else - { -#if DEBUG_SIGNATURES - lastError = "50BE-Expected"; -#endif - return true; // CollectEndIndex was expected! => HACK? - } - } - return Test(fileName, index, hash, sigVer, level); //fileName based Test - } - } - //! AddHash based on bank prefix - //! return true when HACK detected - bool AddHash(int index, RString prefix, Temp &dataContentHash, Temp &levelHash, int sigVer, int level) - { -#if DEBUG_SIGNATURES - lastError = ""; -#endif - //RptF("AddHash: index=%d prefix=%s, ver=%d, lev=%d", index, cc_cast(prefix), sigVer, level); - if (_collecting) - { -#if DEBUG_SIGNATURES - lastError = "Collecting"; -#endif - return true; //this type of answers is not expected during initial collecting phase - } - return Test(index, prefix, dataContentHash, levelHash, sigVer, level); //bank prefix based Test - } - - //! Get the level to use for the next signature check - int ActualCheckLevel() - { - DWORD time = GlobalTickCount(); - if (time > fullCheckNext) - { - fullCheckNext = time + 80000 + toInt(80000 * GRandGen.RandomValue()); // 80 s - 160 s - // note: full check (level=1) is broken, World::CheckHash is very slow and never completes, use 2 instead - return 2; // deep check (level 1) - } -#if 1 - DoAssert(banksCount>0); // the bank count should already be known - // FIX: level=2 checks are now processed async - if ( rand()%4==0 && banksCount>0) - return 2; - else - return 0; // shallow check (hash is taken from stored bank position, not recomputed from its content) -#else - return 0; //HOTFIX: Level 2 checks are too long to compute for both clients and server (async on clients and precomputation on servers should be implemented!) -#endif - } - - RString GetLastError() const - { -#if DEBUG_SIGNATURES - return lastError; -#else - return RString(""); -#endif - } - - //! Check timeout guarding whether client send her banksCount - void CheckTimeouts(CheckSignatureTimeoutFunc &func) - { - if ( bankInfoTimeout && (bankInfoTimeout < GlobalTickCount()) ) - { - (void)func(); - } - } - - //! It calls the GWorld->RandomUsedFile more times to get the file which is not asked too often - RString RandomUsedFile(Vector3Par pos, int level); - - bool IsCollecting() const { return _collecting; } - - // returns true when hack was detected - bool UpdatePlayerBankCount(int bankCount); - -#if DEBUG_SIGNATURES - const AutoArray &Hashes() { return hashes; } -#endif -}; - -struct AsyncDBStorage -{ - // asynchronous save to the central database - struct SaveThreadContext : public RefCount - { - SIGNALED_OBJECT _thread; - RString _url; - RString _request; - RString _uid; - Ref _prevContext; - - SaveThreadContext() : _thread(NoInitHandle) {} - }; - Ref _lastContext; - - bool DBSave(RString baseURL, RString playerUID, RString request); - bool DBQueue(RString baseURL, RString playerUID, RString request); - bool DBKill(RString baseURL, RString playerUID); - bool DBItemDrop(RString baseURL, RString request); - - static DWORD WINAPI DBSaveThreadFunction(void *ctx); - static DWORD WINAPI DBQueueThreadFunction(void *ctx); - static DWORD WINAPI DBKillThreadFunction(void *ctx); - static DWORD WINAPI DBItemDropThreadFunction(void *ctx); - - // asynchronous load to the central database - struct LoadThreadContext : public RefCount - { - SIGNALED_OBJECT _thread; - RString _url; - // load possible when all saves completes - Ref _prevContext; - // the result of the request - RString _result; - int _err; - // the script executed when request completes - Ref _code; - int _playerId; - RString _playerUID; - RString _name; - - LoadThreadContext() : _thread(NoInitHandle) {} - }; - AutoArray< Ref > _loadContexts; - void DBLoad(RString baseURL, int playerId, RString playerUID, RString name, GameDataCode *code); - static DWORD WINAPI DBLoadThreadFunction(void *ctx); - void DBCheckLoaded(); -}; - -#if _ENABLE_STEAM_MATCHMAKING && !(_ENABLE_STEAM_IDENTITY && defined(_WIN64)) -class SteamValidation -{ - /// Steam authentication is completed (need not wait for it) - bool _authDone; - /// Steam authentication passed (client approved) - bool _authOK; - - bool _started; - DWORD _ticksStarted; - - NetworkServer *_server; - - uint64 _steamId; - - AutoArray _steamSessionTicket; - - RString _name; - - int _dpid; - -public: - SteamValidation(); - ~SteamValidation(); - - void Start(PlayerIdentity &identity, NetworkServer *server); - - void HandleTimeout(); - - // Tells us a client has been authenticated and approved to play by Steam (passes auth, license check, VAC status, etc...) - STEAM_GAMESERVER_CALLBACK(SteamValidation, OnValidateAuthTicketResponse, ValidateAuthTicketResponse_t, _callbackGSAuthTicketResponse); -}; -#endif - - -//! Server info about player -struct NetworkPlayerInfo : public AsyncDBStorage, public RefCount, private NoCopy -{ - //! DirectPlay ID of player (client) - int dpid; - //! Voice over net ID of player (client) - int dvid; - - //! chat channel player transmits - int channel; - - //! some clients are "local" (no bandwidth control is needed) - bool _isLocal; - //! name of player - RString name; - //! client state for given player - NetworkClientState clientState; - //! message queue (candidates for aggregation) - NetworkMessageQueue _messageQueue, _messageQueueNonGuaranteed; - - /// messages waiting to be sent to clients - /** messages describing audio or visual effects, no delivery is guaranteed */ - RefArray _delayedMessages; - - /// list of objects which are marked as updating for this player - typedef TListBidir> UpdatingList; - UpdatingList _updating; - - void markAsUpdating(NetworkPlayerObjectInfo *info, UpdatingList &updatingNew) - { - //DoAssert(updatingNew.CheckIntegrity()); - //DoAssert(_updating.CheckIntegrity()); - if (info->IsInList()) - { - //DoAssert(_updating.Contains(info)); - _updating.Delete(info); - } - updatingNew.Insert(info); - //DoAssert(_updating.CheckIntegrity()); - //DoAssert(updatingNew.CheckIntegrity()); - } - - void markAsUpdating(NetworkPlayerObjectInfo *info) - { - //DoAssert(_updating.CheckIntegrity()); - if (!info->IsInList()) _updating.Insert(info); - //DoAssert(_updating.CheckIntegrity()); - } - - //! ping statistics - CalculateMinMaxAvg _ping; - //! bandwidth statistics - CalculateMinMaxAvg _bandwidth; - //! desync statistics - CalculateMinMaxAvg _desync; - - //! player's person - NetworkId person; - - SRef _clientInput; - - //! player occupy private slot - bool privateSlot; - - //! client has actual (valid) mission pbo file - bool missionFileValid; - - //! client has actual (valid) mission pbo file - bool paramFileValid; - - //! kick-off already requested - bool kickedOff; - - //! Connection loosing (no message for 10 seconds) was already reported to other users - bool connectionProblemsReported; - - //! Player was joined using JIP (used to distinguish between normal JIP and JIP forced after MP Load) - bool _jipProcessed; - - //@{ private and public socket address + port - int _publicAddr; - int _publicPort; - - int _privateAddr; - int _privatePort; - //@} - - /// how many times wrong login password was given - int _loginFailedCount; - /// how long is login disabled because of two many wrong attempts - DWORD _loginDisabledUntil; - - /// Signature checks - PendingSignatureChecks signatureChecks; - - /// Hashes collected during initial signature test - CollectedHashes hashes; -#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) - SteamValidation _steamValidate; -#endif - -#if _ENABLE_STEAM_MATCHMAKING && !(_ENABLE_STEAM_IDENTITY && defined(_WIN64)) - SteamValidation _steamValidate; -#endif - - /// CDKey check - CDKeyCheck cdKeyCheck; - - //! time when next regular check will take place - DWORD regularCheckNext; - //! order of the regular check - DWORD regularCheckOrder; - - //! position of camera on given client - Vector3 cameraPosition; - //! time of last update of cameraPosition - Time cameraPositionTime; - -#if _VBS3 - //! Direction of camera on given client - Vector3 cameraDirection; - //! FOV on given client - float cameraFov; -#endif - -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - //! next message of the day index (-1 if done) - int motdIndex; - //! next message of the day time - UITime motdTime; -#endif - - int nextQuestionId; - -#if _ENABLE_MP - MuteListMessage muteList; -#endif - - Time joined; - - /// key for encoding of CD Key validation communication - RString challenge; - - /// challenge to be signed by the PlayerId certiticate - long long certChallenge; - - // Serialize for MP Save/Load - LSError Serialize(ParamArchive &ar); -//} - - /* @return value: true when client is not able to send through network - (because it loads the landscape, mission, do some time exhaustive work,...) - It detects the start and end of the busy state - At start: it remembers the start time - At end: it adds the time spent to all pending signature timeouts - */ - bool ClientStateBusy(); - // helper variable for ClientStateBusy function - DWORD _busyStartTime; // when zero, the client is NOT busy. The start of busy state otherwise. - -#if DEBUG_SIGNATURES - RString errorInfo; -#endif -}; - -//! map person to unit in server database -struct PersonUnitPair -{ - //! id of person - NetworkId person; - //! id of unit - NetworkId unit; -}; -TypeIsMovable(PersonUnitPair) - -//! Single vote in votings -struct Vote -{ - //! DirectPlay ID of player - int player; - //! Voted value - AutoArray value; - - //! Equality operator - /*! - \param val voted value - \param valueSize size of voted value - */ - bool HasValue(const char *val, int valueSize) const; -}; -TypeIsMovable(Vote) - -//! Single voting -class Voting : public AutoArray -{ - friend class Votings; - typedef AutoArray base; - -protected: - /// Unique id of voting - AutoArray _id; - /// Threshold when voting is valid - float _threshold; - /// Check if more than half players has the same value - bool _selection; - - /// when there are to little players, assume other can still connect - int _minVotePlayers; -public: - //! Add new vote - /*! - \param player DirectPlay ID of voting player - \param value voted value (NULL if none) - \param valueSize size of voted value - */ - int Add(int player, const char *value = NULL, int valueSize = 0); - - //! Return ID of Voting - const AutoArray &GetID() const {return _id;} - - //! Check if voting is valid - bool Check(const AutoArray &identities) const; - - /// remote voting of any player which is no longer here - void OnPlayerDeleted(int dpid); - //! Get voted value - /*! - \param n number of votes - */ - const AutoArray *GetValue(int *n = NULL, int *n2=NULL) const; - - struct VoteInfo - { - const Vote *vote; - int count; - - ClassIsSimple(VoteInfo) - }; - - static int CompareVoteInfo(const VoteInfo *v1, const VoteInfo *v2) - { - return v2->count-v1->count; - } - - /// get ordered info about voting - void GetOrder(AutoArray &result) const; - //! Equality operator - /*! - \param id unique identification of voting - \param idSize size of unique identification - */ - bool HasID(const char *id, int idSize) const; -}; -TypeIsMovable(Voting) - -//! Voting system -class Votings : public AutoArray -{ - typedef AutoArray base; - -public: - //! Add new vote - /*! - \param server hosting server - \param id unique identification of voting - \param idSize size of unique identification - \param threshold threshold when voting is valid - \param player DirectPlay ID of voting player - \param value voted value (NULL if none) - \param valueSize size of voted value - */ - void Add( - NetworkServer *server, const char *id, int idSize, float threshold, int player, const char *value = NULL, int valueSize = 0, - bool selection = false, int minVotePlayers=-1 - ); - - /// find given voting - const Voting *Find(int id) {return Find((const char *)&id,sizeof(id));} - - /// find given voting - const Voting *Find(const char *id, int idSize) const; - - /// find index of a corresponding voting - int FindIndex(const char *id, int idSize) const; - - /// delete voting - void DeleteVoting(int id) {return DeleteVoting((const char *)&id,sizeof(id));} - - /// delete given voting - void DeleteVoting(const char *id, int idSize); - - /// remote voting of any player which is no longer here - void OnPlayerDeleted(int dpid); - - //! Check all votings (apply if satisfied) - /*! - \param server hosting server - */ - void Check(NetworkServer *server); - - /// apply voting, if there are no votes return false - bool Apply(NetworkServer *server, int id) {return Apply(server,(const char *)&id,sizeof(id));} - /// apply voting, if there are no votes return false - bool Apply(NetworkServer *server, const char *id, int idSize); -}; - -/// Custom file slot -struct CustomFilePaths -{ - RString _src; - RString _dst; - unsigned int _crc; - int _len; - CustomFilePaths() {} - CustomFilePaths(RString src, RString dst, unsigned int crc, int len) : _src(src), _dst(dst), _crc(crc), _len(len) {} - - DECLARE_NETWORK_OBJECT - static NetworkMessageFormat &CreateFormat - ( - NetworkMessageClass cls, - NetworkMessageFormat &format - ); - TMError TransferMsg(NetworkMessageContext &ctx); -}; -TypeIsMovable(CustomFilePaths) - -TypeIsMovable(TransferFileMessage) - - -//! pending download of squad information -class CheckSquadObject -{ -friend class NetworkServer; - -protected: - - long long _challenge; - //! identify player - PlayerIdentity _identity; - - //! custom files subsets of which is can be sent to some clients - AutoArray _customFileList; - //! TransferFile messages for each custom file (created only when needed) - AutoArray > _customFileMessages; - //! custom files which given clients wants to sent - struct CustomFilesForClient - { - int _dpnid; // client identification - enum CFTState {CFSWaitingToList, CFSSendingFiles, CFSDone} _state; - AutoArray _filesWanted; - //{ Files Transfer members - int _fileNo; // index into _filesWanted, which file is currently being transfered - int _fragmentNo; // number of transfered fragments - int _allFragmentCount; // used for progress bar - int _allFragmentPos; // used for progress bar - DWORD _nextSendTime; // time to send next bunch of TransferFile messages - //} - CustomFilesForClient() {} - CustomFilesForClient(int dpnid) : _dpnid(dpnid), _state(CFSWaitingToList), _fileNo(0), _fragmentNo(0) , - _allFragmentPos(0), _allFragmentCount(200) //200 - approx 100kB before the valid count is not received - { - _nextSendTime=::GetTickCount(); - } - ClassIsMovableZeroed(CustomFilesForClient) - }; - AutoArray _customFilesProgress; - - enum State {SendingCustomFiles,AllDone}; - //! state of download - State _state; - //! address of proxy server - RString _proxy; - -public: - //! start download - CheckSquadObject(PlayerIdentity &identity, RString proxy, NetworkServer *server); - //! destruct - wait until current download step is terminated - ~CheckSquadObject(); - //! check if download is terminated - bool IsDone(bool &canSendCustomFiles, NetworkServer *server); - bool IsPlayer(int dpnid) { return _identity.dpnid==dpnid; }; - - //! custom files transfer to all clients. Returns true when no custom files are being sent. - bool StartSendCustomFilesList(NetworkServer *server); - - //! store content of NMTCustomFilesWanted message - void SetCustomFilesWanted(int dpnid, const AutoArray &filesWanted); - - State GetState() const { return _state; } - -protected: - void CreateCustomFilesList(); -}; - -struct UpdateObjectInfo; -class LiveStatsUpdate; -static const int SessionAttributesCount = 12; - -enum HackType -{ - HTUnsignedData, - HTHackedData -}; - -#if _ENABLE_DEDICATED_SERVER - -#define SERVER_EVENT_ENUM(type, prefix, XX) \ - XX(type, prefix, DoubleIdDetected) /* two users with the same id detected */ \ - XX(type, prefix, OnUserConnected) /* reaction to connected user */ \ - XX(type, prefix, OnUserDisconnected) /* reaction to disconnected user */ \ - XX(type, prefix, OnHackedData) /* reaction to pbo files manipulation */ \ - XX(type, prefix, OnUnsignedData) /* reaction to unsigned file */ \ - XX(type, prefix, RegularCheck) /* called regullary for each user */ \ - -#ifndef DECL_ENUM_SERVER_EVENT -#define DECL_ENUM_SERVER_EVENT -DECL_ENUM(ServerEvent) -#endif -DECLARE_ENUM(ServerEvent, SE, SERVER_EVENT_ENUM) - -#endif - -typedef struct qr2_buffer_s *qr2_buffer_t; -typedef struct qr2_keybuffer_s *qr2_keybuffer_t; - -//((EXE_CRC_CHECK -#if !_SUPER_RELEASE - -/// info about exe segment to investigate -struct ExeSegmentInfo -{ - int offset; - int size; -}; -TypeIsSimple(ExeSegmentInfo); - -/// the status of the client investigation -struct CompareExeClient -{ - int _dpid; - int _answer; - bool _answered; -}; - -/// Find the exe difference for given clients -struct CompareExeInvestigation -{ - /// list of segments to investigate - AutoArray _stack; - /// list of modified segments - AutoArray _modified; - /// item on the top of stack is already investigating - bool _asked; - /// the first client summary - CompareExeClient _client1; - /// the second client summary - CompareExeClient _client2; - - /// prepare structure to investigation - void Init(int dpid1, int dpid2); - /// react to the answer - void OnAnswered(int dpid, int answer); -}; - -#endif -//))EXE_CRC_CHECK - -template <> -struct ImplicitMapTraits< RefD > -{ - static RefD null; ///< Empty value (can be passed as return value). - static RefD zombie; ///< Removed value (internal usage only). - -}; - -static inline int operator % (const NetworkId &id, unsigned i) -{ - unsigned idl = (id.creator.CreatorInt()<<20)+id.id; - return idl%i; -} - -//! Delayed CreateMarker messages, init messages -struct JIPMarkerInfo -{ - Ref _marker; - int _channel; - int _roleIndex; -}; -TypeIsMovableZeroed(JIPMarkerInfo) - -struct ObjectsSpatialLayer: public RefCount -{ - typedef std::function Function; - - virtual void Add(NetworkObjectInfo *oInfo) = 0; - virtual bool Remove(Vector3Par oldPos, NetworkObjectInfo *oInfo) = 0; - virtual void ForEach( Vector3 cameraPos, const Function &function ) = 0; - ObjectsSpatialLayer(){} - virtual ~ObjectsSpatialLayer(){} - -}; - -struct ObjectsSpatialLayerWithDistance: public ObjectsSpatialLayer -{ - float _distance; - - ObjectsSpatialLayerWithDistance(float distance):_distance(distance){} -}; - -//! Network Server -class NetworkServer : public NetworkComponent -{ - friend struct DelayedMessageInfo; - friend struct NetworkObjectInfo; - -protected: - //! low-level server implementation - SRef _server; - - //! server for peer to peer mission sharing -#ifdef PEER2PEER - SRef _p2pServer; -#endif - -#if _USE_BATTL_EYE_SERVER - /// BE Integration - class BattlEye - { - //! BEVersion is used in BE init call in both Win32 and Linux sections - static const int CurrentBEIntegrationVersion = 0; - static const int MinBEVerReq = 176; - public: - enum BEInitFailedReason { BEReasonOther, BEReasonNotInstalled }; - BEInitFailedReason _initFailedReason; - protected: - /// dll handle - HMODULE _library; - bool _initialized; - - //@{ - /// callback functions - typedef void __cdecl PrintMessageF(const char *message); - typedef void __cdecl KickPlayerF(int player, const char *reason); - typedef void __cdecl ExecuteCommandF(const char *command); - static void __cdecl PrintMessage(const char *message); - static void __cdecl KickPlayer(int player, const char *reason); - static void __cdecl ExecuteCommand(const char *command); - //@} - - //@{ - /// dll functions - typedef bool __cdecl ExitF(); - typedef bool __cdecl RunF(); - typedef void __cdecl CommandF(const char *command); - typedef void __cdecl AddPlayerF(int player, unsigned long address, unsigned short port, const char *name); - typedef void __cdecl ChangePlayerStatusF(int player, int status); - typedef void __cdecl ReceivedPlayerGUIDF(int player, void *guid, int guidlen); - typedef void __cdecl PlayerGUIDIsValidF(int player, void *ownerguid, int guidlen); - typedef void __cdecl ReceivedPlayerMessageF(int player, int channel, const char *message); - typedef void __cdecl LoadedMissionF(const char *name); - -// XXX(AddWeapon, const char *netId, const char *type) \ -// XXX(AddMagazine, const char *netId, const char *type) \ - - #define BE_CALLBACKS(XXX) \ - XXX(UpdatePosition, const char *netId, float x, float y, float z, float dirX, float dirY, float dirZ, float upX, float upY, float upZ, float asideX, float asideY, float asideZ ) \ - XXX(UpdateDamage, const char *netId, float damage ) \ - XXX(PublicVariable, const char *name, const char *data) \ - XXX(AttachObject, const char *netId, const char *netIdAttachTo, int memoryIndex, float x, float y, float z) \ - - #define BE_FUNCTION_TYPE(Name, ...) typedef bool __cdecl Name##CallbackF(int player, __VA_ARGS__); - BE_CALLBACKS(BE_FUNCTION_TYPE) - - struct GamePtrStruct - { - char *pstrGameVersion; - PrintMessageF *_printMessage; - KickPlayerF *_kickPlayer; - ExecuteCommandF *_execCommand; - }; - GamePtrStruct _gameParams; - - struct BEPtrStruct - { - ExitF *_exit; - RunF *_run; - CommandF * _command; - AddPlayerF * _addPlayer; - ChangePlayerStatusF * _changePlayerStatus; - ReceivedPlayerGUIDF * _receivedPlayerGUID; - PlayerGUIDIsValidF * _playerGUIDIsValid; - ReceivedPlayerMessageF * _receivedPlayerMessage; - LoadedMissionF * _loadedMission; - - #define BE_FUNCTION_PTR(Name, ...) Name##CallbackF *_callback##Name; - BE_CALLBACKS(BE_FUNCTION_PTR) - }; - BEPtrStruct _callbacks; - - typedef bool __cdecl InitF(int iIntegrationVersion, GamePtrStruct *ppvGamePtrTable, BEPtrStruct *ppvBEPtrTable); - typedef int __cdecl GetVerF(); - //@} - - public: - BattlEye(); - ~BattlEye(); - - bool IsEnabled() const {return _library != NULL;} - - bool Init(); - void Done(); - - bool Run(const NetworkServer *server); - void Command(const char *command); - - //! BEServer.AddPlayer() needs to be called as soon as a client is connected to the server (probably right after the initial join packet - as soon as the client is registered/accepted on the server's internal player list). - void AddPlayer(int player, unsigned long address, unsigned short port, const char *name); - -/*! BEServer.RemovePlayer() will be replaced by BEServer.ChangePlayerStatus(). - - BEServer.ChangePlayerStatus() will be called with status = 1 when the player goes in-game (where AddPlayer() was previously called). - - BEServer.ChangePlayerStatus() will be called with status = 0 when the player goes back to the lobby (where RemovePlayer() was previously called). - - BEServer.ChangePlayerStatus() will be called with status = -1 when the player disconnects from the server. -*/ - void PlayerGoesInGame(int player); - void PlayerGoesInLobby(int player); - void PlayerDisconnected(int player); - - //! BEServer.ReceivedPlayerGUID() will be called as soon as the GameSpy cd-key hash is received from the client (after connecting). -#if _ENABLE_STEAM_OWNERSHIP - void PlayerGUIDReceived(int player, const CSteamID &id); -#else - void PlayerGUIDReceived(int player); -#endif - void PlayerGUIDIsValid(int player); -#if (_ENABLE_STEAM_IDENTITY && defined(_WIN64)) && !_ENABLE_STEAM_OWNERSHIP - void PlayerGUIDReceived(int player, const CSteamID &id); -#endif -#if _ENABLE_STEAM_OWNERSHIP || (_ENABLE_STEAM_IDENTITY && defined(_WIN64)) - void PlayerGUIDIsValid(int player, const CSteamID &ownerId); -#endif - - #define BE_WRAP_CALLBACK(Name, ...) bool __cdecl Name##Callback(int player, __VA_ARGS__); - BE_CALLBACKS(BE_WRAP_CALLBACK) - - //! BEServer.ReceivedPlayerMessage() will be called whenever a client sends an in-game message, so the BE Server can still - //! log the chat to the console (it extracted it from the network traffic before, but that won't be possible anymore after the network traffic scrambling/encryption is introduced). - void PlayerChatReceived(int player, int channel, const char *message); - - void LoadedMission(const char *name); - - protected: - void CleanUp() - { - _library = NULL; - _callbacks._exit = NULL; - _callbacks._run = NULL; - _callbacks._command = NULL; - _callbacks._addPlayer = NULL; - _callbacks._changePlayerStatus = NULL; - _callbacks._receivedPlayerGUID = NULL; - _callbacks._playerGUIDIsValid = NULL; - _callbacks._receivedPlayerMessage = NULL; - _callbacks._loadedMission = NULL; - #define BE_FUNCTION_INIT(Name, ...) _callbacks._callback##Name = NULL; - BE_CALLBACKS(BE_FUNCTION_INIT) - _initialized = false; - } - int GetBEVersion(HMODULE library) const; - }; - BattlEye _beIntegration; - bool BattlEyeEnabled() const - { - // for internal version we want to perform the processing even without the BE to verify it is working fine - return _ENABLE_CHEATS || _beIntegration.IsEnabled(); - } -#else - bool BattlEyeEnabled() const {return false;} -#endif - //! list of players (server specific info) - RefArray _players; - //! list of network objects (actual state) - - static NetworkId GetIdFromNetworkObjectInfo(const RefD &info) {return info->id;} - - typedef ImplicitMap, GetIdFromNetworkObjectInfo > ObjectsMap; - - struct ObjectsSpatialLayerKeyTraits - { - typedef float KeyType; - static bool IsEqual(KeyType a, KeyType b) {return a==b;} - static KeyType GetKey(const ObjectsSpatialLayerWithDistance *a) {return a->_distance;} - }; - - struct ObjectsSpatialIndex - { - typedef NetworkId KeyType; - typedef RefD TargetType; - - /// objects in bubbles stored in layers based on bubble size - FindArrayKey,ObjectsSpatialLayerKeyTraits> _layers; - /// objects with no position or no max distance are not held in layers - Ref _noLayer; - /// all objects in a hash map for easy bulk access - ObjectsMap _all; - - ObjectsSpatialLayer &Distance(float dist); - - bool get ( KeyType key, TargetType &result ) const - { - return _all.get(key,result); - } - - TargetType *get ( KeyType key ) - { - return _all.get(key); - } - const TargetType *get ( KeyType key ) const - { - return _all.get(key); - } - - bool put ( TargetType value ); - - void addToLayer( TargetType value ) - { - auto &layer = Distance(value->_updInfo._updateDistance); - layer.Add(value); - } - void removeFromLayer( Vector3Par oldPos, float oldDist, TargetType value ) - { - auto &layer = Distance(oldDist); - DoVerify(layer.Remove(oldPos,value)); - } - - void removeKey ( KeyType key ); - - - void reset (); - - template - void forEach(const Function &function) - { - _all.forEach(function); - } - - template - void forEach(const Function &function) const - { - _all.forEach(function); - } - - void forEachInBubble(Vector3 cameraPos, const ObjectsSpatialLayer::Function &function); - void onPosChanged(NetworkObjectInfo *oInfo, const NetworkObjectInfo::UpdateInfo &oldPos, const NetworkObjectInfo::UpdateInfo &newPos); - - unsigned card() const {return _all.card();} - - - ObjectsSpatialIndex(); - }; - - - FindArrayKey _indexToPlayerId; - - PlayerIndex GetPlayerIndex(int pid) const {return (PlayerIndex)_indexToPlayerId.FindKey(pid);} - - PlayerIndex CreatePlayerIndex(int pid); - - //typedef ObjectsMap ObjectsContainer; - typedef ObjectsSpatialIndex ObjectsContainer; - - ObjectsContainer _objects; - - - static NetworkId GetIdFromDeletedNetworkObjectInfo(const NetworkDeletedObjectInfo &info) {return info.id;} - - typedef ImplicitMap DeletedObjectsContainer; - - //! info about objects deleted, until deletion is confirmed by the owner - DeletedObjectsContainer _deletedObjects; - - //! original name of current mission - RString _originalName; - - //! no other players are enabled to connect - bool _sessionLocked; - - //! password protected session - bool _password; - - //! equal mod list required by host - bool _equalModRequired; - - //! data signatures required - bool _verifySignatures; - - //! the least buildNo the server accepts - int _buildNoRequired; - - /// level od CD key security required - int _secureIdRequired; - - /// validate CD Key using GameSpy SDK - bool _validateCDKey; - - /// do not report session to GameSpy matchmaking - bool _doNotReport; - - // InitQR was called (so SimulateQR should not call QR sdk) - bool _qrInitDone; - - /// allow persistent missions - continue even when no players are connected - bool _persistent; - - /// destroy body of disconnected players - bool _destroyDisconnected; - - mutable int _longitude; - mutable int _latitude; - - bool _longLatAuto; - -#if _ENABLE_STEAM_MATCHMAKING - // ports for Steam services - int _steamPort; - int _steamQueryPort; -#endif - - struct GeoJobThread - { - SIGNALED_OBJECT _thread; - Future _longitude; - Future _latitude; - RString _ip; - GeoJobThread() : _thread(NoInitHandle) {} - }; - mutable SRef _geoJob; - - static DWORD WINAPI GeoJobThreadFunction(void *ctx); - -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - //! DirectPlay ID of logged gamemaster (AI_PLAYER if no gamemaster) - int _gameMaster; - //! selected mission name - RString _mission; - //! selected mission cadet / veteran mode - int _difficulty; - - //! gamemaster is only voted admin (cannot do shutdown etc.) - bool _admin; - - //! kick off players with duplicate ID - bool _kickDuplicate; - - //! is server dedicated - bool _dedicated; - //! server is asked to restart mission - bool _restart; - //! server is asked to reassign players - bool _reassign; - //! index of next mission in dedicated server config file - int _missionIndex; - //! preloaded dedicated server config file - ParamFile _serverCfg; - - //@{ - //! Info about network trafic on dedicated server - float _monitorInterval; - DWORD _monitorNext; - int _monitorFrames; - int _monitorIn; - int _monitorOut; - //@} - - DWORD _debugNext; - float _debugInterval; - //! switched on debug flags - FindArrayKey _debugOn; - - //! messages of the day - AutoArray _motd; - //! messages of the day interval - float _motdInterval; - - //! URL of Query & Reporting master server - RString _reportingIP; - - /// evaluator for (dedicated) server scripts - GameState _evaluator; - /// global variables for _evaluator - GameDataNamespace _globals; - - /// SDZ_SQF_EXEC: scripts coming from #exec are queued and evaluated after the - /// network messages of the current frame have been processed. Running arbitrary - /// SQF in the middle of message handling touched half-updated object lists and - /// corrupted the script heap (server crashed with no RPT message). - AutoArray _sqfExecQueue; - AutoArray _sqfExecFrom; - bool _sqfExecBusy; - //! event handlers - RString _eventHandlers[NServerEvent]; - -#else - static const bool _dedicated = false; -#endif -//} - - //! time when next ping status should be broadcast - DWORD _pingUpdateNext; - - //! full path to mission pbo file - RString _missionBank; - - //! global (static) ban list - FindArray _banListGlobal; - //! local (dynamic) ban list - FindArray _banListLocal; - - struct KeyListSecure - { - FindArray keys; // blocked keys list - AutoArray signature; // signature of a blocked keys list - } _banListSecure; - - //! actually tested identities (squad competence) - AutoArray< SRef > _squadChecks; - DWORD _squadChecksTimeout; - - //! next available (short) id for player - int _nextPlayerID; - - //! votings currently in progress - Votings _votings; - - /// overall game de-sync - aggregated from all clients - ConnectionDesync _connectionDesync; - - //@{ last valid result from _desyncTotal - float _desyncTotalAvg; - float _desyncTotalMax; - //@} - - /// aggregate de-sync stats for all clients - CalculateMinMaxAvg _desyncTotal; - - /// time when _desyncTotal was last averaged - DWORD _desyncTotalUpdateNext; - - //! threshold for votings - float _voteThreshold; - - //! address of proxy server - RString _proxy; - - //! current server state - NetworkServerState _serverState; - - /// how long is the server state stable - DWORD _serverStateTime; - - /// what timeout value was reported to the clients - int _serverTimeOutSent; - - //! network messages, needed to send to joining player - AutoArray _initMessages; - - //! Marker messages, needed to send to joining player - AutoArray _jipMarkerInfos; - -#if _ENABLE_CHEATS - //! debugging window - Link _debugWindow; -#endif - - int _totalSlots; - - /// last time when timeleft was reported to matchmaking - DWORD _timeLeftLastTime; - /// last value reported to matchmaking - int _timeLeftLastValue; - - /// last value reported to broadcast / QoS - int _timeLeftLastValueBcast; - - /// absolute limit of max. players allowed - int _maxPlayersLimit; - - /// 0 for enable, 1 for disable (configurable in server.cfg by disable3rdPerson entry) - int _disable3rdPerson; - - /// time multiplier for environment - float _environmentTimeMul; - - //! time synchronized to clients - DWORD _serverTime; - DWORD _serverTimeInitTickCount; - DWORD _serverTimeOfEstimatedEnd; - int _secondsToEstimatedEnd; - static const int ServerTimeUpdateInterval = 300*1000; // 5 minutes - DWORD _nextServerTimeUpdate; - -//((EXE_CRC_CHECK -#if !_SUPER_RELEASE - CompareExeInvestigation _exeInvestigation; -#endif -//))EXE_CRC_CHECK - -#if _VBS2 && _VBS2_LITE - bool _memoryWrite; - DWORD _nextRanUpdate; -#endif - -public: - //! Constructor - NetworkServer(NetworkManager *parent, RString name, RString password, int maxPlayers, int port, bool isPrivate); - //! Destructor - ~NetworkServer(); - - int GetSessionPort() const {return _server ? _server->GetSessionPort() : 0;} - - int NextPlayerId() {return _nextPlayerID++;} - - //! Creation of DirectPlay server and MP session - /*! - \param port IP port where server communicate - \param password session password - */ - bool Init(RString name, RString password, int maxPlayers, int port); - //! Destroying of MP session and DirectPlay server - void Done(); - - void InitVoice(); - - //! Create debugging window - void CreateDebugWindow(); - - //! Kick off given player from game - void KickOff(int dpnid, KickOffReason reason, const char *reasonStr=NULL); - //! Ban given player (kick off + add to dynamic ban list) - void Ban(int dpnid); - - void UpdateBanListSecure(const FindArray &keys, const Array &signature); - - //! Return if session was created - bool IsValid() const {return _server != NULL;} - - bool IsDedicatedBotClient(int dpnid) const; - - bool IsLocalClient(int client) const - { - // Assume bot client is always local - return client == BOT_CLIENT; - } - - void RptFObjectIdJournal(const NetworkId &id); - void RptFObjectNotFound(const NetworkId &id, const char *msg, int from); - void RptFObjectNotFound(const NetworkId &id, NetworkMessageType type, int from, const char *context = nullptr); - - void UpdateMaxPlayers(int maxPlayers, int privateSlots); - -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - //! Mark server as dedicated - /*! - \param config name (path) of config file - */ - bool SetDedicated(RString config); - - /// add specific server scripting commands to the _evaluator - void InitEvaluator(); - /// SDZ_SQF_EXEC: queue an expression received through #exec - void QueueExec(int from, RString expression); - /// SDZ_SQF_EXEC: evaluate (and answer) every queued expression - void ProcessQueuedExec(); - - void ProfileAnswer(const RString &output); -#endif -//} - //! force data signatures checking - void SetVerifySignatures(int reqVersion); - - //! verify signature of the single file based on bank index (DataSignatureCheck) - void CheckSignature(int dpnid, int fileIndex, int level); - - //! verify signature of the single file based on filename (FileSignatureCheck) - void CheckSignature(int dpnid, RString filename, RString prefix, int level); - - //! signature check test with index=-1 was started and NetworkPlayerInfo::signatures are to be collected - void InitSignatureCollecting(NetworkPlayerInfo *info); - - //! List of acceptedKey names in the form key1;key2;key3... - //! When nonzero param 'maxLen', the return value has at most maxLen+4 chars. When truncated, the last one is ";..." - RString GetSignaturesList(int maxLen=0); - - //! Get the hash precalculated during server initial banks load - bool MyHash(Temp &hash, RString prefix, int sigVer, int level); - - //! disable/enable connecting of further clients - void LockSession(bool lock = true) - { - if (_sessionLocked != lock) - { - _sessionLocked = lock; - UpdateMatchmakingDescription(false); - _server->UpdateLockedOrPassworded(_sessionLocked, _password); - } - } - - //! Retrieves URL of server - void OnPublicAddressKnown(int ip); - - bool GetURL(char *address, DWORD addressLen); - int BuildNoRequired() { return _buildNoRequired; } - - int SecureIdRequired() {return _secureIdRequired;} - - //! Creates pbo file for selected mission - void CreateMission(RString mission, RString world); - //! Store name of pbo file for selected mission - void SetOriginalName(RString name) {_originalName = name;} - // force the _param1, _param2 and _paramsArray to contain undefined values, so InitMission will rewrite these by mission defaults - void UndefMissionParams(); - //! Initialize mission - /*! - - create and send mission header structure (including difficulty settings) - */ - void InitMission(int difficulty, RString displayName, bool noCopy, RString owner, bool isCampaignMission); - - void KickAllPlayers(int minBuild=0); - - bool DBSave(RString baseURL, int dpnid, RString request); - void DBLoad(RString baseURL, int playerId, GameDataCode *code); - void DBLoad(RString baseURL, int playerId, RString playerUID, GameDataCode *code); - - void OnDraw(); - void OnSimulate(); - void OnSimulateDone(); - - /// time critical network update - need to be called several times in frame - void FastUpdate(); - void OnCreatePlayer(int player, bool privateSlot, const char *name, unsigned long inaddr); - InputInterface *GetInputInterface(int player); - bool OnCreateVoicePlayer(int player); - void OnMessage(int from, NetworkMessage *msg, NetworkMessageType type); - - void ChangeOwnerFinal( NetworkObjectInfo * oInfo, int from, NetworkId &id ); - - - void SpawnForPlayer(int dpnid, GameDataCode *code, const GameValue &args); - -#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) - void PlayerGUIDReceived(int player, const CSteamID &id) { -#if _USE_BATTL_EYE_SERVER - _beIntegration.PlayerGUIDReceived(player, id); -#endif - } - void PlayerGUIDIsValid(int player, const CSteamID &ownerId) { -#if _USE_BATTL_EYE_SERVER - _beIntegration.PlayerGUIDIsValid(player, ownerId); -#endif - } -#endif - - //! The output format is "creator:id friendlyName" - RString NetworkIdToNetIdFriendly(const NetworkId &id); - - #if _ENABLE_DEDICATED_SERVER - void DoReassign(); - void DoReassignDirect(); - void DoMissions(bool admin); -#endif - - /// remove initMessages overridden by this one - void AddInitAndRemoveOverridden(NetworkMessageType type, NetworkMessage * msg, int **updateI=NULL); - /// get diagnostics statistics about initMessages - RString GetAddInitAndRemoveOverriddenStat(); - /// remove initMessages related to a deleted object - void RemoveInitObjectDeleted(NetworkId obj); - - void AddJIPMarkerInfo(NetworkMessage *marker, int channel, int from); - void RemoveJIPMarkerInfo(RString name); - - //! perform regular memory clean-up - unsigned CleanUpMemory(); - - /// called before network shutdown is initiated - can be called multiple times - void OnClose(); - - //! Process received system messages - void ReceiveSystemMessages(); - //! Process received user messages - void ReceiveUserMessages(); - //! Destroy all received system messages - void RemoveSystemMessages(); - //! Destroy all received user messages - void RemoveUserMessages(); - //! Get position of randomly chosen player - Vector3 RandomPlayerPos() const; - //! Perform all active integrity investigations - void PerformIntegrityInvestigations(); - - DWORD SendMsg - ( - int to, NetworkSimpleObject *object, NetMsgFlags dwFlags - ); - - - //! Send single network message - /*! - This function determine, whic type of send will be used - local send, agregation or send using DirectPlay - \param to DirectPlay ID of message receiver - \param msg message itself - \param type type of message - \param dwFlags DirectPlay flags - */ - DWORD SendMsg - ( - int to, NetworkMessage *msg, - NetworkMessageType type, NetMsgFlags dwFlags, - NetworkPlayerObjectInfo *poInfo - ); - - virtual DWORD SendMsg - ( - int to, NetworkMessage *msg, - NetworkMessageType type, NetMsgFlags dwFlags - ) - { - return SendMsg(to, msg, type, dwFlags, NULL); - } - - Ref DXSendMsg(int to, NetworkMessageRaw &rawMsg, DWORD &msgID, NetMsgFlags dwFlags, const Ref &dependOn); - - //! Retrieve list of players - void GetPlayers(AutoArray &players); - - /// ask for item UI invocation - void UseItem(Person *person, InventoryItem *item); - - //! Return connection quality to server - ConnectionDesync GetConnectionDesync() const {return _connectionDesync;} - - NetworkMessageFormatBase *GetFormat(/*int client, */int type); - const NetworkMessageFormatBase *GetFormat(/*int client, */int type) const; - - void OnChangedOnPlayerConnecting(GameValuePar codeValue); - - //! Set current server state and send to clients - void SetServerState(NetworkServerState state); - //! Return client state for given player - NetworkClientState GetClientState(int dpnid); - //! Return name for given player - RString GetPlayerName(int dpid); - //! Return camera position for given player - Vector3 GetCameraPosition(int dpid); - - NetworkId GetPlayerPerson(int dpid); - Object *GetPlayerTarget(int dpid); - - void ServerSelectPlayer(int dpid, const NetworkId &id); - - /// Return the IP address of the connected client - bool GetClientAddress(int client, sockaddr_in &address); - - NetworkObject *GetObject(const NetworkId &id); - - //! Unregister all objects - void DestroyAllObjects(); - - //! Send mission pbo file to clients - /*! - \param dpnid client, server will send mission to (0 for all clients) - */ - void SendMissionFile(int dpnid = 0); - - //! Calculate bandwidth estimation to given client - int GetBandwidthEstimation(int dpnid, int nPlayers); - - const char *GetDebugName() const {return "Server";} - - RString GetDiagText(const NetworkId &id) const; - - - //! Client has sent her bankCount. Detect whether it differs to the previously sent value. - void UpdatePlayerBankCount(NetworkPlayerInfo *info, int bankCount); - //! Report Wrong signatures (write also a line inside DS log window) - // @param report used for additional info - void ReportWrongSignatures(int from, RString filename, const NetworkPlayerInfo *info, RString report=RString()); - - //! Creates player identity - /*! - Called asynchronously when identity is confirmed - \param ident player identity - \param squad player's squad - */ - void CreateIdentity(PlayerIdentity &ident); - - //! Process result of voting when voting is valid - /*! - \param id unique identification of voting - \param value voted value - */ - void ApplyVoting(const AutoArray &id, const AutoArray *value); - - //! some admin state change - scan admin status of all players - void UpdateAdminState(); - - //! Delete player info (unregister player) - void OnPlayerDestroy(int dpid); - - //! Set estimated end of mission time - /*! - \param time estimated time - */ - void SetEstimatedEndTime(Time time); - - /// read to time left estimation - int GetSessionTimeLeft() const; - - //! Return absolute limit of max. players allowed - /** does not include virtual slot on ded. server */ - int GetMaxPlayersLimit() const {return _maxPlayersLimit;} - - /// Return maximal number of players according to bandwidth estimation - /** does not include virtual slot on ded. server */ - int GetMaxPlayersSafe(int bandwidthPerClient, int round) const; - - //! Return maximal allowed number of players on server based on mission and user settings - /** does include virtual slot on ded. server */ - int GetMaxPlayers() const; - - //! Return name of mission pbo file on server to optimize transfer to bot client - RString GetMissionFilename() const {return _missionBank;} - - //! When player joined to game - Time GetPlayerJoined(int dpid) const; - - //! Find info about given player - NetworkPlayerInfo *GetPlayerInfo(int dpid); - -//((EXE_CRC_CHECK -#if !_SUPER_RELEASE - /// Find the exe difference for given clients - void CompareExe(int dpid1, int dpid2) {_exeInvestigation.Init(dpid1, dpid2);} -#endif -//))EXE_CRC_CHECK - - /// Find owner of given network object (used in scripted function owner) - int GetOwner(const NetworkId &id) const; - /// Change owner of given network object (used in scripted function setOwner) - bool SetOwner(const NetworkId &id, int clientId); - - bool StatusChat(int clientId, RString text, RString colorClass); - - void OnRejectChanged(const NetworkId &id, NetworkMessageClass cls, bool reject); - - void OnHierParentChange( Entity* veh ); - -protected: - //! Create player info (register player) - NetworkPlayerInfo *OnPlayerCreate(int dpid, bool privateSlot, const char *name, unsigned long inaddr); - //! Force state change for given client - void SetClientState(int dpnid, NetworkClientState state); - -#if _ENABLE_DEDICATED_SERVER - // select game master on dedicated server - void SetGameMaster(int player, bool admin); - - /// set event handler - void SetEventHandler(RString name, RString value); - /// process event handler (return if the event was handled) - bool OnEvent(ServerEvent event, float par); - /// process event handler (return if the event was handled) - bool OnEvent(ServerEvent event, float par1, float par2); - /// process event handler (return if the event was handled) - bool OnEvent(ServerEvent event, float par1, RString par2); -#endif - - /// Find owner of given network object - int FindOwner(const NetworkId &id); - - //! Find info about given network object - NetworkObjectInfo *GetObjectInfo(const NetworkId &id) const; - //! Create object info (register object) - NetworkObjectInfo *OnObjectCreate(const NetworkId &id, int owner, NetworkMessage *msg, NetworkMessageType type); - //! Delete object info (unregister object), return owner id - int PerformObjectDestroy(const NetworkId &id); - //! Delete object info (unregister object) and send message about destruction - void OnObjectDestroy(const NetworkId &id, int from); - - Vector3 GetObjectPosition( NetworkId obj ); - - - //! Called when update message received - /*! - \param id network object ID - \param from sender DirectPlay ID - \param msg update message - \param type update message type - \param cls update message class - */ - NetworkObjectInfo *OnObjectUpdate(NetworkId &id, int from, NetworkMessage *msg, NetworkMessageType type, NetworkMessageClass cls); - - void RescanBestPosition( NetworkObjectInfo * oInfo ); - - void UpdateChildrenPos(const Entity * veh); - - bool CheckBestPositionIntegrity() const; - //! Send update message - /*! - \param pInfo info about receiving player - \param oInfo info about object to update - \param cls update message class - \param dwFlags DirectPlay flags - */ - int UpdateObject(NetworkPlayerInfo *pInfo, NetworkObjectInfo *oInfo, NetworkMessageClass cls, NetMsgFlags dwFlags); - - //! Calculate time error (message fading) between two stored states (messages) - /*! - \param type update message type - \param msg1 first message - \param msg2 second message - */ - float CalculateErrorTime - ( - NetworkMessageType type, NetworkMessage *msg1, NetworkMessage *msg2 - ); - - //! Owner of some object changes - /*! - \param id ID of network object - \param from DirectPlay ID of old owner - \param to DirectPlay ID of new owner - */ - void ChangeOwner(const NetworkId &id, int from, int to); - - //! Send mission info (mission heade, side slots and role slots) to client - /*! - \param DirectPlay ID of receiving client - \param onlyPlayers do not send mission header - */ - void SendMissionInfo(int to, bool onlyPlayers = false); - - //! Send all agregated and update messages - void SendMessages(); - //! Check if fade out players are to kicked off - void CheckFadeOut(); - //! Calculate limits for message sending - void EstimateBandwidth(NetworkPlayerInfo &pInfo, int nPlayers, int &nMsgMax, int &nBytesMax); - //! Calculate errors and place object in list sorted by error - /*! - \param objects output sorted list of objects - \param pInfo info about receiving player - */ - void CreateObjectsList(AutoArray &objects, NetworkPlayerInfo &pInfo); - - void OnStopUpdating( NetworkObjectInfo &oInfo, NetworkPlayerInfo &pInfo, NetworkPlayerObjectInfo &poInfo); - - //! Prepare next object update message to message queue - bool PrepareNextUpdate(NetworkPlayerInfo &pInfo, AutoArray &objects, int &next); - - //! Dedicated server simulation - void SimulateDS(); - - void SimulateMonitor( DWORD tickCount ); - - /// broadcast current mission voting status to all clients - void MissionVotingEcho(); - /// check time out for current server state - bool CheckTimeOut(int readyCount, int totalCount, DWORD ready, DWORD notReady); - - /// check how much players is need to consider the server to be full - int PlayerServerFull() const; - - //! Show message in both console and chat - void ServerMessage(const char *text); - - //! Show client-side localized message in both console and chat - void ServerMessage(const LocalizedFormatedString &text); - - //! Find players on chat channel - /*! - \param players output array of players - \param units chat target units - \param from DirectPlay ID of sender - \param voice true for Voice Over Net transfer - */ - void GetPlayersOnChannel(AutoArray &players, AutoArray units, DWORD from, bool voice); - //! Find players on chat channel - /*! - \param players output array of players - \param channel chat channel - \param from DirectPlay ID of sender - \param voice true for Voice Over Net transfer - */ - void GetPlayersOnChannel(AutoArray &players, int channel, DWORD from, bool voice); - - /// check if given player in out of game (dead, or in the lobby) - bool CheckPlayerInLobby(const NetworkPlayerInfo &info) const; - /*! - \name GameSpy Query & Reporting SDK support - */ - //@{ -//{ QUERY & REPORTING SDK -#if _ENABLE_GAMESPY - //! Close Query & Reporting SDK support - void DoneQR(); - //! Simulation step of Query & Reporting SDK support - void SimulateQR(); - //! Information about change of inner game state - void ChangeStateQR(); -public: - //! Initialize Query & Reporting SDK support - void InitQR(bool isPrivate); - - void ProcessGeoJob() const; - void CloseGeoJob() const; - - /// Called when a server key needs to be reported - void OnQueryServer(int keyid, qr2_buffer_t outbuf); - /// Called when a player key needs to be reported - void OnQueryPlayer(int keyid, int index, qr2_buffer_t outbuf); - /// Called when a team key needs to be reported - void OnQueryTeam(int keyid, int index, qr2_buffer_t outbuf); - /// Called when we need to report the list of keys we report values for - void OnQueryKeys(int keytype, qr2_keybuffer_t keybuffer); - /// Called when we need to report the number of players and teams - int OnQueryCount(int keytype); - - /// validate CD Key using GameSpy SDK - bool ValidateCDKey() const { return _validateCDKey; } - -#if _VERIFY_CLIENT_KEY - /// called when autorization of CD Key finished - void OnCDKeyAuthorize(int player, int authenticated, const char *errmsg); -#endif - -#elif _ENABLE_STEAM_MATCHMAKING -public: - /// Initialization of Steamworks SDK server reporting interface - void InitSteam(); - /// Steamworks SDK server reporting interface clean up - void DoneSteam(); - /// Simulation of Steamworks SDK callbacks - void SimulateSteam(); - /// Inform Steam master server about the change of the inner game state - void ChangeStateSteam(); -#if _ENABLE_DEDICATED_SERVER - /// Reset TimeAlive Statistics - void ResetCharacterTimeAlive(AIBrain *unit); -#endif - - #if _ENABLE_STEAM_OWNERSHIP && _USE_BATTL_EYE_SERVER - void PlayerGUIDReceived(int player, const CSteamID &id) {_beIntegration.PlayerGUIDReceived(player, id);} - #endif - - // Tells us when we have successfully connected to Steam - STEAM_GAMESERVER_CALLBACK(NetworkServer, OnSteamServersConnected, SteamServersConnected_t, _callbackSteamServersConnected); - // Tells us when there was a failure to connect to Steam - STEAM_GAMESERVER_CALLBACK(NetworkServer, OnSteamServersConnectFailure, SteamServerConnectFailure_t, _callbackSteamServersConnectFailure); - // Tells us when we have been logged out of Steam - STEAM_GAMESERVER_CALLBACK(NetworkServer, OnSteamServersDisconnected, SteamServersDisconnected_t, _callbackSteamServersDisconnected); - // Tells us that Steam has set our security policy (VAC on or off) - STEAM_GAMESERVER_CALLBACK(NetworkServer, OnPolicyResponse, GSPolicyResponse_t, _callbackPolicyResponse); - -protected: -#endif -//} - //@} - - //! Update session description server sending via LAN broadcast - void UpdateSessionDescription(); - - //! Update session description server sending via both mathmaking and LAN broadcast - void UpdateMatchmakingDescription(bool changedParams); - - void SendMuteList(const PlayerIdentity &id); - - void EnqueueMsg(int to, NetworkMessage *msg, NetworkMessageType type, NetworkPlayerObjectInfo *poInfo); - void EnqueueMsgNonGuaranteed(int to, NetworkMessage *msg, NetworkMessageType type, const RefR &dependOn); - -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - //! Set interval in which dedicated server sends info about transfer rates to gamemaster - void Monitor(float interval); - void OnMonitorIn(int size); - -public: - void DebugAsk(RString str); -protected: - void DebugAnswer(RString str); - - int ConsoleF(const char *format, ...); -#else - int ConsoleF ( const char *format, ... ){return 0;} -#endif -//} - - void OnMessageClientInput(int from, NetworkMessageType type, NetworkMessageContext &ctx); - - //! Client state changed - void OnClientStateChanged(int dpnid, NetworkClientState state); - - void ObjectUpdateAll(NetworkObjectInfo * info, int dpnid, NetMsgFlags dwFlags); - - //! Check if dpnid and sender are on the same channel - bool IsPlayerOnChannel(int dpnid, int channel, int roleIndex2); - - //! Send init messages to JIP player, handle special messages - void SendInitMessages(int dpnid); - - void OnPlayerConnecting(int dpnid); - void OnPlayerConnecting(int dpnid, GameValuePar codeValue); - - /// update server database when player leave mission - void DisconnectPlayer(int dpnid, NetworkId playerPerson); - - /// calculate how important is given object to given player - float CalculateErrorCoef(const NetworkPlayerInfo &pInfo, const NetworkObjectInfo &oInfo, bool updating); - - void SendCreateMessage( int dpnid, NetworkObjectInfo &info, NetworkPlayerObjectInfo *poInfo ); - - /// event handler - wrongly signed data or signature check question timed out - void OnHackedData(HackType type, int dpid, RString filename); - -#if _VERIFY_KEY - /// event handler - two players with the same CD-KEY - void OnDoubleIdDetected(const PlayerIdentity &newIdentity, const PlayerIdentity &oldIdentity); -#endif - - /// execute corresponding event handler for all players - void CallOnPlayerDisconnected(); - - /// execute corresponding event handler for a signle players - void OnPlayerDisconnected(NetworkPlayerInfo *info); -public: - /// report hacked data of given player - bool ProcessHackedData(NetworkPlayerInfo &pi); - -private: - // recursive traversal of messages to set correct owner of owned items - void CheckItemsOwner(const NetworkMessageUpdateVehicleAI *msg, int newOwner); - void CheckItemOwner(const NetworkId &id, int newOwner); - - - -}; - -class ReportHackedData : public CheckSignatureTimeoutFunc -{ - NetworkPlayerInfo &_pi; - NetworkServer &_server; -public: - ReportHackedData(NetworkPlayerInfo &pi, NetworkServer &server) : _pi(pi) , _server(server) {} - bool operator ()(); -}; - -/////////////////////////////////////////////////////////////////////////////// -// Network Manager - -TypeIsSimple(INetworkUpdateCallback *) - -//! Implementation of basic network functions -class NetworkManager : public INetworkManager -{ -friend class NetworkComponent; - -protected: - SRef _sessionEnum; - //! time of last call of EnumHosts - UITime _lastEnumHosts; - //! IP address of computer (empty for local network) where search for sessions - RString _ip; - //! port where search for sessions - int _port; - //! additional remote hosts - AutoArray _hosts; - - //! enable creation of physical world - bool _physEnabled; - - //! network server component - SRef _server; - //! network client component - SRef _client; - //! voice over net disabled - bool _disableVoN; - //! voice over net codec quality for encoding - int _vonCodecQuality; - //! log file for dedicated server can be specified in server.cfg by entry logFile - RString _dedServerLogFileName; - FILE *_dedServerLogFile; - - -#if _ENABLE_MP && (!_GAMES_FOR_WINDOWS) - // TODO: Unify X360 / PC mute list handling - MuteListMessage _muteList; -#endif - - float _pendingInvitationX; - float _pendingInvitationY; - float _pendingInvitationW; - float _pendingInvitationH; - - Ref _cqPoorTexture; - Ref _cqBadTexture; - Ref _cqDesyncLow; - Ref _cqDesyncHigh; - - //! voice communicator connected - bool _isVoice; - - //! whether Done was already called in Binarize at the end before destructor - bool _disableDone; - - FindArray _updateCallbacks; - -#if _ENABLE_GAMESPY - bool _trackUsageDone; -#endif - - /// request to disable voice - EDisableVoiceRequest _disableVoiceRequest; - /// time when the request was set - UITime _disableVoiceRequestTime; - - /// helper to enable asynchronous save / load in singleplayer - AsyncDBStorage _spStorage; - -public: - //! Constructor - NetworkManager(); - //! Destructor - ~NetworkManager(); - - bool IsServer() const override {return _server != nullptr;} - //! Return if client is created - bool IsClient() const override {return _client != nullptr;} - - void DisablePhysics() override {_physEnabled = false;} - bool IsPhysicsMaster() const override {return IsServerOwner() && _physEnabled;} - virtual bool IsPhysicsEnabled() const override {return _physEnabled;} - - bool IsServerOwner() const override {return _server != nullptr || _client==nullptr;} - bool IsMultiplayer() const override {DoAssert(_server == nullptr || _client!=nullptr); return _client!=nullptr;} - - NetworkServer *GetServer() const {return _server;} - - int RequiredBuildNo() { return (_server!=NULL) ? _server->BuildNoRequired() : 0; } - - //! Access to server component - NetworkServer *GetServer() {return _server;} - //! Access to client component - NetworkClient *GetClient() {return _client;} - - virtual void TrackUsage(); - - bool VoiceReady() const; - - //! return if voice communicator is connected - bool IsVoice() const {return _isVoice;} - //! Return if player is voice banned - bool IsVoiceBanned() const; - //! return if voice over net is disabled - bool IsVoNDisabled() const {return _disableVoN;} - //! set whether voice over net is disabled - void SetVoNDisabled(bool val) {_disableVoN=val;} - //! return the log File for Dedicated server (entry logFile in server.cfg) - RString GetDedicatedServerLogFileName() { return _dedServerLogFileName; } - FILE *GetDedicatedServerLogFile(); - void CloseDedicatedServerLogFile() { if (_dedServerLogFile) { fclose(_dedServerLogFile); _dedServerLogFile=NULL; } } - //! VoN codec quality for encoding - int VoNCodecQuality() const { return _vonCodecQuality; } - //! VoN codec quality for encoding (should propagate into VoNRecorder too) - void SetVoNCodecQuality(int quality); - - bool Init(RString ip, int port, bool startEnum = true); - void Init(); - void DisableDone() { _disableDone=true; } - - void Done(); - void RemoveEnumeration(); - - bool IsVoicePlaying(int dpnid) const; - bool IsVoiceRecording() const; - int CheckVoiceChannel(int dpnid, bool &audible2D, bool &audible3D) const; - void IsVoice2D3DPlaying(int dpnid, bool &audible2D, bool &audible3D) const; - - void SetVoiceON(); - void SetVoiceOFF(); - void SetVoiceToggleOn(bool value); - /// sets threshold for silence analyzer (0.0f - 1.0f) - void SetVoNRecThreshold(float val); - void SetVoNTransmitterFreq(float f) override; - float GetVoNTransmitterFreq() const override; - void SetVoNTransmitterRange(float range) override; - float GetVoNTransmitterRange2() const override; - void WhatUnitsOnTransmitterChannel(RefArray &units) override; - void SetVoiceCapture(bool value); - //! request disabling of voice - virtual void SetDisableVoiceRequest(EDisableVoiceRequest request); - - -#if _ENABLE_CHEATS - void VoNSay(int dpnid, int channel, int frequency, int seconds); -#endif - - void CustomFilesProgressClear(); - void CustomFilesProgressGet(int &max, int &pos); - DWORD GetServerTime(); - DWORD GetEstimatedEndServerTime(); - void PlayerGUIDIsValid(int player, const CSteamID &ownerId) override; - - -#if _GAMES_FOR_WINDOWS - - virtual SessionType GetSessionType() const {return _sessionType;} - - /// returns if any session exists - virtual bool SessionExists() const {return _sessionHandle != NULL;} - - virtual bool IsSignedIn() const {return true;} - - // Appear offline implemented by Xbox Guide on Xbox 360 - void Cloak(bool set = true) {} - bool IsCloaked() const {return false;} - - void DisableVoice(bool disable); - -#else - bool IsSignedIn() const {return false;} - void Cloak(bool set = true) {} - bool IsCloaked() const {return false;} - - void DisableVoice(bool disable) {} -#endif - - bool IsPlayerInMuteList(const XUID &xuid) const; - void UpdateMuteList(); - void TogglePlayerMute(const XUID &xuid); - - void SetPendingInvitationPos(RString resource); - -public: - bool IsSystemLink() const {return _sessionEnum != NULL;} - - void GetSessions(AutoArray &sessions); - RString IPToGUID(RString ip, int port); - bool CreateSession(SessionType sessionType, RString name, RString password, int maxPlayers, bool isPrivate, int port, bool dedicated, RString config, int playerRating); - - void UpdateMaxPlayers(int maxPlayers, int privateSlots) override; - int GetMaxPlayersLimit() const override; - int GetMaxPlayersSafe(int requiredPerClient, int round) const; - - ConnectResult JoinSession(SessionType sessionType, RString guid, RString password) override; - - const SessionInfo WaitForSession() override; - void GetPlayers(AutoArray &players) override; - void CreateMission(RString mission, RString world); - void SetOriginalName(RString name); - void InitMission(int difficulty, RString displayName, bool noCopy, RString owner, bool isCampaignMission); - void KickAllPlayers(int minBuild=0); - - void Close(); - unsigned CleanUpMemory(); - - int GetMaxMissionPlayers() const; - - void CreateServerDebugWindow(); - void CreateClientDebugWindow(); - - void KickOff(int dpnid, KickOffReason reason); - void Ban(int dpnid); - void LockSession(bool lock = true); - - void OnSimulate(); - void OnSimulateDone(); - - void FastUpdate(); - void RegisterUpdateCallback(INetworkUpdateCallback *callback); - void UnregisterUpdateCallback(INetworkUpdateCallback *callback); - void OnDraw(); - - NetworkServerState GetServerState() const; - int GetServerTimeout() const; - void SetServerState(NetworkServerState state); - - NetworkClientState GetClientState() const; - void SetClientState(NetworkClientState state); - - bool GetTransferProgress(float &progress) const; - - void OnJoiningInProgress(); - - void OnChangedOnPlayerConnecting(GameValuePar codeValue) override; - - int TimeElapsed() const; - - NetworkClientState GetClientState(int dpnid) const; - - bool IsGameMaster() const; - bool IsAdmin() const; - ConnectionQuality GetConnectionQuality() const; - ConnectionDesync GetConnectionDesync() const; - void GetParams(float ¶m1, float ¶m2) const; - float GetParams(int index) const; - AutoArray GetParamsArray() const; - void SetParams(float param1, float param2, bool updateOnly); - void SetParams(float param1, float param2, AutoArray paramsArray, bool updateOnly); - void SetParam(float param, int index, bool updateOnly); - const MissionHeader *GetMissionHeader() const; - int GetPlayer() const; - CreatorId GetCreatorId() const; - - const PlayerIdentity *FindIdentity(int dpnid) const; - const PlayerIdentity *FindIdentityByPlayerId(int playerId) const; - const AutoArray *GetIdentities() const; - - virtual bool DBSave(RString baseURL, int dpnid, RString request) override; - - virtual bool DBSave(RString baseURL, RString uid, RString request) override; - virtual bool DBQueue(RString baseURL, RString uid, RString request) override; - virtual bool DBKill(RString baseURL, RString uid) override; - - virtual bool DBItemDrop(RString baseURL, RString request) override; - - virtual void DBLoad(RString baseURL, int playerId, GameDataCode *code) override; - virtual void DBLoad(RString baseURL, int playerId, RString playerUID, GameDataCode *code) override; - - virtual InputInterface *GetInputInterface(int player) override; - virtual RString GetDiagText(const NetworkObject *obj) const override; - - void SelectPlayer(int player, Person *person, bool respawn = false); - void SendSelectPlayer(int dpid, Person *person); - void PlaySound - ( - RString name, Vector3Par position, Vector3Par speed, - float volume, float freq, AbstractWave *wave - ); - void SoundState(AbstractWave *wave, SoundStateType state); - RString GetPlayerName(int dpid) override; - Vector3 GetCameraPosition(int dpid) override; - NetworkId GetPlayerPerson(int dpid) override; - virtual Object *GetPlayerTarget(int dpid) override; - void ServerSelectPlayer(int dpid, Person *person) override; - NetworkObject *GetObject(const NetworkId &id) override; - int GetOwner(const NetworkId &id) const override; - bool SetOwner(const NetworkId &id, int clientId) override; - bool StatusChat(int clientId, RString text, RString colorClass=RString()); - bool CreateVehicle(Vehicle *veh, VehicleListType type, RString name, int idVeh); - bool CreateSubobject(Vehicle *veh, TurretPath &path, NetworkObject *object); - bool CreateObject(NetworkObject *object, bool setNetworkId=true); - void CreateAllObjects(); - void DeleteObject(const NetworkId &id); - void DestroyAllObjects(); - void AskForPilotLight(EntityAI *vehicle, bool enable); - void AskForVehicleDoorState(Transport *vehicle, int doorIndex, bool opened); - void AskForSetMaxHitZoneDamage - ( - Object *who, float dammage - ); - void CreateObjectStatic(Object *who) override; - void ExplosionDamage(EntityAI *owner, Vector3Par originDir, Object *directHit, Vector3Par directHitModelPos, HitInfoPar hitInfo, - Object *componentOwner, int componentIndex, float energyFactor, float explosionFactor, float hitDepth) override; - - - void AskForAmmo( - EntityAIFull *vehicle, Turret *turret, const WeaponModePtr &ptr, int burst - ); - void AskForMove( - Object *vehicle, Vector3Par pos - ); - - void AskForMove( - Object *vehicle, Matrix4Par trans - ); - void AskForSetMagazineAmmo - ( - Object *magazine, int ammo - ); - - void ExplosionDamageEffects( - EntityAI *owner, Object *directHit, HitInfoPar hitInfo, int componentIndex, - bool enemyDamage, float energyFactor, float explosionFactor - ); - void ApplyProjectileDecal - ( - Object *directHit, int componentIndex, HitInfoPar hitInfo, float hitDepth, Vector3Par hitPosLcl, Vector3Par hitDirLcl, Vector3Par hitDirUpLcl - ); - void RemoveProjectileDecals(Object *person); - void FireWeapon - ( - EntityAIFull *vehicle, Person *gunner, const WeaponModePtr &ptr, Magazine *magazine, EntityAI *target, - const RemoteFireWeaponInfo &remoteInfo - ); - void UpdateBowState(EntityAIFull *entity, BowState state); - void SetObjectTexture(EntityAI *veh, int index, RString name, RString eval = "true"); - void PublicExec(RString condition, RString command, Object* obj, OLinkArray(Object) &objs); - void OnVehicleDestroyed(EntityAI *killed, EntityAI *killer); - void OnVehicleDamaged(EntityAI *damaged, EntityAI *killer, float damage, RString ammo); - void MarkerCreate(int channel, AIBrain *sender, RefArray &units, ArcadeMarkerInfo &info); - void MarkerDelete(RString name); - void SendMsg(NetworkSimpleObject *msg); - - void PublicVariable(RString name, int dpnid); - void SpawnForPlayer(int dpnid, GameDataCode *code, const GameValue &args) override; - - void SendAUMessage(GameValuePar oper1); - - void ClearDelayedPublicVariables(); - void ProcessDelayedPublicVariables(); - - void Chat(int channel, RString text); - void Chat(int channel, AIBrain *sender, RefArray &units, RString text); - void Chat(int channel, RString sender, RefArray &units, RString text); - - void LocalizedChat(int channel, const LocalizedFormatedString &text); - void LocalizedChat(int channel, AIBrain *sender, RefArray &units, const LocalizedFormatedString & text); - void LocalizedChat(int channel, RString sender, RefArray &units, const LocalizedFormatedString & text); - - void RadioChat(int channel, AIBrain *sender, RefArray &units, RString text, RadioSentence &sentence); - void RadioChatWave(int channel, RefArray &units, RString wave, AIBrain *sender, RString senderName); - int GetVoiceChannel() const; - void SetVoiceChannel(int channel); - void SetVoNPosition(int dpnid, Vector3Par pos, Vector3Par speed); - void SetVoNPlayerPosition(Vector3Par pos, Vector3Par speed); - void SetVoNObstruction(int dpnid, float obstruction, float occlusion, float deltaT); - void UpdateVoNVolumeAndAccomodation(int dpnid, float volume, float accomodation); - virtual void AdvanceAllVoNSounds( float deltaT, bool paused, bool quiet ); - - void UpdateCustomChannel(int channel, int ucr_type); - - void TransferFile(RString dest, RString source); - void SendMissionFile(); - void GetTransferStats(int &curBytes, int &totBytes); - - void ApplyWeather(); -#if _VBS3 - void AARDoUpdate(int type ,int intType,RString stringOne = RString(), RString stringTwo = RString(), float floatType = 0.0); - void AARAskUpdate(int type ,int intType,RString stringOne = RString(), RString stringTwo = RString(), float floatType = 0.0); - void AddMPReport(int type, RString myString); - void LoadIsland(RString islandName); - void AskCommanderOverride(Turret *turret, Turret *overriddenByTurret); -#endif - - void AskForDeleteVehicle(Entity *veh); -#if _VBS3 // respawn command - void PauseSimulation(bool pause); -#endif - - virtual void AskForSetItemShortcut(Person *person, int index, const InventoryItemType *type, InventoryItem *item) override; - virtual void AskForThrowItem(Man *person, InventoryItem *item, Vector3 pos, Vector3 dir) override; - virtual void AskForDropItem(Person *person, InventoryItem *item) override; - virtual void AskForMoveItem(EntityAI *target, int index, InventoryItem *item, bool rotated) override; - virtual void AskForRotateInventoryItem(Person *person, InventoryItem *item) override; - virtual void AskForTakeItemToHands(Person *person, InventoryItem *item) override; - virtual void AskForSwapItems(InventoryItem *item1, InventoryItem *item2, Person *owner) override; - - virtual void AskForPlayerAction(Person *person, RString action) override; - - virtual void AskInventoryMenu(AIBrain *unit, InventoryItem *item1, InventoryItem *item2) override; - -#if _ENABLE_ATTACHED_OBJECTS - void AttachObject(Object *obj, Object *attachTo, int memIndex, Vector3 pos, int flags); - void DetachObject(Object *obj); -#endif - - void AskForAnimationPhase(Entity *vehicle, RString animation, float phase); - - bool ProcessCommand(RString command); - bool IsCommandAvailable(RString command); - - void SendKick(int player); - void SendLockSession(bool lock = true); - - bool CanSelectMission() const; - bool CanVoteMission() const; - const VotingMissionProgressMessage *GetMissionVotingState() const; - const AutoArray &GetServerMissions() const; - void SelectMission(RString mission, int difficulty); - void VoteMission(RString mission, int difficulty); - - RString GetHostName() const override; - RString GetServerGUID() const override; - - void UpdateObject(NetworkObject *object); - virtual void UpdateObject(NetworkObject *object, NetworkMessageClass cls) override; - - //! Forget all enumerated hosts - void ClearEnumHosts(); - //! Cancel _dp->EnumHost operation - void StopEnumHosts(); - //! Start _dp->EnumHost operation - bool StartEnumHosts(); - - //! Return original name of local player (without decoration used when several players vith the same name are connected) - RString GetLocalPlayerName() const; - - Time GetEstimatedEndTime() const; - void SetEstimatedEndTime(Time time); - - void DisposeBody(Person *body); - bool IsControlsPaused(); - float GetLastMsgAgeReliable(); - - /// react to communicator insertion/removal - void UpdateVoiceStatus(); - - void ChangeVoiceMask(RString mask); - - void DebugAsk(RString str); - void DebugServerExec(RString str); - - Time GetPlayerJoined(int dpid) const; - - void HackedDataDetected(RString filename); - - void AddPublicVariableEventHandler(RString name, GameValuePar code); - bool BattlEyeOnScriptExec(RString script); - - virtual void ProcessAction(Action *action, AIBrain *unit) override; - virtual void ProcessRecipe(RString recipe, Person *person, InventoryItem *item1, InventoryItem *item2) override; - virtual void UseItem(Person *person, InventoryItem *item) override; - - virtual void SynchronizeVariable( EntityAI * veh, RString name, float coef, const GameDataCode &code ) override; - virtual void SendCreateMessage( EntityAI *veh ) override; - - virtual void OnHierParentChange( Entity* veh ) override; - virtual void RptFObjectIdJournal( const NetworkId &id ) override; - -#if _ENABLE_DEDICATED_SERVER - virtual void ProfileAnswer(const RString &output) override; -#endif - -#if _ENABLE_GAMESPY - /// Set on which IP Address the client is visible from the matchmaking server - virtual void SetPublicAddress(int addr); - -#endif - -#if _GAMES_FOR_WINDOWS - /// Access to the session info - const XSESSION_INFO &GetSessionInfo() const {return _sessionInfo;} - /// Access to the session nonce - the unique key used for arbitration - ULONGLONG GetSessionNonce() const {return _sessionNonce;} - - /// Update the player slots of the session - bool UpdateSession(int maxPlayers, int privateSlots); - - /// Register arbitration for clients (final registration on server is processed in StartSession) - bool ArbitrationRegister(ULONGLONG sessionNonce); - - /// Register player to the session - bool RegisterPlayer(const PlayerIdentity &identity); - /// Unregister player from the session - bool UnregisterPlayer(const PlayerIdentity &identity); - - /// start the match itself, statistics collection begins - bool StartSession(); - /// finish the match itself, statistics will be reported - bool EndSession(); - -protected: - /// Register session on Xbox Live - bool RegisterSession(bool host, int maxPlayers, int maxPrivateSlots); - /// Unregister session from Xbox Live - void UnregisterSession(); - - /// Based on game type, select the leaderboard(s) and algorithm and update the statistics - bool UpdateStatistics(RString gameType); - -#endif -}; - -extern NetworkManager GNetworkManager; -extern NetworkMessageFormat *GMsgFormats[NMTN]; - -extern RString ServerTmpDir; -RString GetServerTmpDir(); -RString GetClientTmpDir(); -RString GetClientCustomFilesDir(); - -//! total number of diagnostic types -/*! -\patch_internal 1.08 Date 07/26/2001 by Jirka -- Improved: network diagnostics -*/ -enum OutputDiagsMode -{ - ODMsgQueue, - ODMsgSent, - ODMsgReceived, - ODMRawStats, - NOutputDiags -}; - -extern int outputDiags; -extern bool outputLogs; - -// transfer parameters -//! When update error (considering distance) is bellow this threshold, update message is not sent -extern float MinErrorToSend; -//! When update error (not considering distance) is bellow this threshold, update message is not sent -extern float MinErrorToSendNear; -//! Maximal number of messages sent in single simulation step -extern int MaxMsgSend; -//! Maximal number of messages sent in single simulation step on dedicated server -extern int DSMaxMsgSend; -//! Maximal size of agregated guaranteed message -extern int MaxSizeGuaranteed; -//! Maximal size of agregated guaranteed message -extern int MaxSizeNonguaranteed; -//! Limit (minimum) for bandwidth estimation -extern int MinBandwidth; -//! Limit (minimum) for bandwidth estimation on dedicated server -extern int DSMinBandwidth; -//! Limit (maximum) for bandwidth estimation -extern int MaxBandwidth; - -//! == default MinErrorToSend / 2, after 2 s update is forced -#define ERR_COEF_TIME_POSITION 0.005 -//! == default MinErrorToSend / 5, after 5 s update is forced -#define ERR_COEF_TIME_GENERIC 0.002 - -#define MSGID_REPLACE 0 - -void WriteDiagOutput(bool server); -int GetDiagLevel(NetworkMessageType type, bool remote); - -//((EXE_CRC_CHECK -/// information for client code verification -struct ExeCRCBlock -{ - int offset, size, crc; -}; -TypeIsSimple(ExeCRCBlock); -//))EXE_CRC_CHECK - -#ifdef _WIN32 -HRESULT WINAPI ReceiveMessage(void *context, DWORD type, void *message); -#endif -void InitMsgFormats(); -const char *FormatVal(float val, char *buffer); - -#if _ENABLE_UNSIGNED_MISSIONS -RString CreateMPMissionBank(RString filename, RString island); -#endif - -int GetNetworkPort(); -int GetServerPort(); - -extern WINDOW_HANDLE hwndApp; - -bool DeleteDirectoryStructure(const char *name, bool deleteDir); -void CreatePath(RString path); -bool ParseMission(bool multiplayer, bool avoidCheckIds = false, bool allowEmpty = false); - -//! Release COM object -#ifndef SAFE_RELEASE -#define SAFE_RELEASE(p) { if(p) {(p)->Release(); (p) = NULL;} } -#endif - -// Multiplayer version info - -#include "../versionNo.h" - -//! Actual multiplayer version -#define MP_VERSION_ACTUAL APP_VERSION_NUM -//! The earliest supported multiplayer version -#define MP_VERSION_REQUIRED APP_VERSION_NUM - -/*** following code shows how to implement a code specific to certain product version - if (MP_VERSION_REQUIRED>=160 && !strcmp(APP_NAME_SHORT,"ArmA2OA")) // TODO: can be removed in 160 - { - // implementation for the new version - } - else - { - #if MP_VERSION_REQUIRED>=160 - #pragma message WARN_MESSAGE("warning: Remove obsolete code") - #endif - // implementation for the old version - } -*/ - -//! Types of Network command messages -enum NetworkCommandMessageType -{ - NCMTLogin, - NCMTLogged, - NCMTLogout, - NCMTKick, - /// used as voting id - restart current mission - NCMTRestart, - /// used as voting id for mission voting - NCMTMission, - /// used as voting id - return to mission selection - NCMTMissions, - NCMTShutdown, - /// used as voting id - return to role selection - NCMTReassign, - NCMTMonitorAsk, - NCMTMonitorAnswer, - NCMTVote, - NCMTVoteMission, - NCMTMissionTimeElapsed, - /// used as voting id for admin voting - NCMTAdmin, - NCMTInit, - NCMTLockSession, - NCMTLoggedOut, - NCMTDebugAsk, - NCMTDebugAnswer, - /// used only as voting id for mission difficulty voting - NCMTDifficulty, - /// execute the server scripting command - NCMTExec, - NCMTExecResult, - /// BattlEye server command - NCMTBattlEye, - /// Progress of custom files uploading from server to clients - NCMTCustomFilesProgress, -#if _ENABLE_CHEATS - /// execute the scripting sommand - NCMTGameExec, -#endif -#if _VBS3 - NCMTExitAll, -#endif - // server asks clients for their VoNFeatures diagnostics, clients responds - NCMTAskVoNDiagnostics, - NCMTMissionDate, - NCMTVoteMissionExt, - NCMTProfileAsk, - NCMTProfileAnswer -}; - -#define NETWORK_COMMAND_MSG(MessageName, XX) \ - XX(MessageName, int, type, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Type of command"), TRANSF) \ - XX(MessageName, SimpleStream, content, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Parameters of command"), TRANSF) - -DECLARE_NET_MESSAGE(NetworkCommand, NETWORK_COMMAND_MSG) - -#define PLAYER_UPDATE_MSG(MessageName, XX) \ - XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Client (player) ID"), TRANSF, ET_NONE, 0) \ - XX(MessageName, int, minPing,NDTInteger,int, NCTSmallUnsigned, DEFVALUE(int, 10), DOC_MSG("Ping range estimation"), TRANSF, ET_ABS_DIF, ERR_COEF_VALUE_MINOR) \ - XX(MessageName, int, avgPing,NDTInteger,int, NCTSmallUnsigned, DEFVALUE(int, 100), DOC_MSG("Ping range estimation"), TRANSF, ET_ABS_DIF, ERR_COEF_VALUE_MAJOR) \ - XX(MessageName, int, maxPing,NDTInteger,int, NCTSmallUnsigned, DEFVALUE(int, 1000), DOC_MSG("Ping range estimation"), TRANSF, ET_ABS_DIF, ERR_COEF_VALUE_MINOR) \ - XX(MessageName, int, minBandwidth,NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 2), DOC_MSG("Bandwidth estimation (in kbps)"), TRANSF, ET_ABS_DIF, ERR_COEF_VALUE_MINOR) \ - XX(MessageName, int, avgBandwidth,NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 14), DOC_MSG("Bandwidth estimation (in kbps)"), TRANSF, ET_ABS_DIF, ERR_COEF_VALUE_MINOR) \ - XX(MessageName, int, maxBandwidth,NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 28), DOC_MSG("Bandwidth estimation (in kbps)"), TRANSF, ET_ABS_DIF, ERR_COEF_VALUE_MINOR) \ - XX(MessageName, int, desync,NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Current desync level (max. error of unsent messages)"), TRANSF, ET_ABS_DIF, ERR_COEF_VALUE_MAJOR) \ - XX(MessageName, int, rights,NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Special rights of given player"), TRANSF, ET_ABS_DIF, ERR_COEF_VALUE_MAJOR) - -DECLARE_NET_INDICES_ERR(PlayerUpdate, PLAYER_UPDATE_MSG) - -inline bool NetworkClient::IsBotClient() const -{ - return _parent->IsServer(); -} - -inline NetworkServer *NetworkClient::GetServer() const -{ - return _parent->GetServer(); -} - - -#define ACCEPTED_KEY_MSG(MessageName, XX) \ - XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Key name"), TRANSF) \ - XX(MessageName, Temp, content, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Key content"), TRANSF) \ - -DECLARE_NET_INDICES(AcceptedKey, ACCEPTED_KEY_MSG) - -//! Accepted public key for data signatures -struct AcceptedKeyMessage : public NetworkSimpleObject -{ - DSKey &_key; - - AcceptedKeyMessage(DSKey &key) : _key(key) {} - - DECLARE_DEFINE_NETWORK_OBJECT_SIMPLE(AcceptedKey) - static NetworkMessageFormat &CreateFormat - ( - NetworkMessageClass cls, - NetworkMessageFormat &format - ); - TMError TransferMsg(NetworkMessageContext &ctx); -}; - -#define ADDITIONAL_SIGNED_FILES_MSG(MessageName, XX) \ - XX(MessageName, AutoArray, list, NDTStringArray, AutoArray, NCTNone, DEFVALUESTRINGARRAY, DOC_MSG("List of additional files to check."), TRANSF) \ - -DECLARE_NET_INDICES(AdditionalSignedFiles, ADDITIONAL_SIGNED_FILES_MSG) - -//! Accepted public key for data signatures -struct AdditionalSignedFilesMessage : public NetworkSimpleObject -{ - AutoArray &_list; - - AdditionalSignedFilesMessage(AutoArray &list) : _list(list) {} - - DECLARE_DEFINE_NETWORK_OBJECT_SIMPLE(AdditionalSignedFiles) - static NetworkMessageFormat &CreateFormat - ( - NetworkMessageClass cls, - NetworkMessageFormat &format - ); - TMError TransferMsg(NetworkMessageContext &ctx); -}; - -#define DATA_SIGNATURE_ASK_MSG(MessageName, XX) \ - XX(MessageName, int, index, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, -1), DOC_MSG("Index of file to check."), TRANSF) \ - XX(MessageName, int, level, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("The level of the check (higher level means deeper check)."), TRANSF) \ - -DECLARE_NET_MESSAGE(DataSignatureAsk, DATA_SIGNATURE_ASK_MSG) - -#define DATA_SIGNATURE_ANSWER_MSG(MessageName, XX) \ - XX(MessageName, int, index, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, -1), DOC_MSG("Index of file to check."), TRANSF) \ - XX(MessageName, RString, filename, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Name of checked file."), TRANSF) \ - XX(MessageName, RString, keyName, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Name of public key"), TRANSF) \ - XX(MessageName, Temp, keyContent, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Content of public key"), TRANSF) \ - XX(MessageName, Temp, signature, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Content of signature"), TRANSF) \ - XX(MessageName, Temp, hash, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Content of hash"), TRANSF) \ - XX(MessageName, int, version, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 1), DOC_MSG("Signature version."), TRANSF) \ - XX(MessageName, int, level, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Ask level."), TRANSF) \ - -DECLARE_NET_INDICES(DataSignatureAnswer, DATA_SIGNATURE_ANSWER_MSG) - -//! Answer to data signature check -struct DataSignatureAnswerMessage : public NetworkSimpleObject -{ - int _index; - RString _filename; - DSSignature _signature; - DSHash _hash; - int _level; - - DECLARE_DEFINE_NETWORK_OBJECT_SIMPLE(DataSignatureAnswer) - static NetworkMessageFormat &CreateFormat - ( - NetworkMessageClass cls, - NetworkMessageFormat &format - ); - TMError TransferMsg(NetworkMessageContext &ctx); -}; - -#define FILE_SIGNATURE_ASK_MSG(MessageName, XX) \ - XX(MessageName, RString, file, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("File to check the signature."), TRANSF) \ - XX(MessageName, int, level, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("The level of the check (higher level means deeper check)."), TRANSF) \ - -DECLARE_NET_MESSAGE(FileSignatureAsk, FILE_SIGNATURE_ASK_MSG) - -#define FILE_SIGNATURE_ANSWER_MSG(MessageName, XX) \ - XX(MessageName, RString, fileName, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Checked filename."), TRANSF) \ - XX(MessageName, RString, keyName, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Name of public key"), TRANSF) \ - XX(MessageName, Temp, keyContent, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Content of public key"), TRANSF) \ - XX(MessageName, Temp, signature, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Content of signature"), TRANSF) \ - XX(MessageName, Temp, dataToHash, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Content which hash was signed"), TRANSF) \ - XX(MessageName, int, version, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 1), DOC_MSG("Signature version."), TRANSF) \ - XX(MessageName, int, level, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Ask level."), TRANSF) \ - XX(MessageName, int, index, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, -1), DOC_MSG("Index of pbo file matching the DataSignatureAsk"), TRANSF) \ - - -DECLARE_NET_INDICES(FileSignatureAnswer, FILE_SIGNATURE_ANSWER_MSG) - -//! Answer to file signature check -struct FileSignatureAnswerMessage : public NetworkSimpleObject -{ - RString _fileName; - DSSignature _signature; - Temp _dataToHash; // for sig.ver.2: (hash of pbo content) + (hash of pbo file list) + (pbo prefix) - int _level; - int _index; - - DECLARE_DEFINE_NETWORK_OBJECT_SIMPLE(FileSignatureAnswer) - static NetworkMessageFormat &CreateFormat - ( - NetworkMessageClass cls, - NetworkMessageFormat &format - ); - TMError TransferMsg(NetworkMessageContext &ctx); - RString GetPrefix() const; // parse the dataToHash to find the stored pbo prefix - void GetDataHash(Temp &hash) const; -}; - -#define CREATE_RADIO_CHANNEL_MSG(MessageName, XX) \ - XX(MessageName, int, channel, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Custom channel in CCCustom1 to CCCustomLast range."), TRANSF) \ - XX(MessageName, int, color, NDTInteger, int, NCTNone, DEFVALUE(int, -1), DOC_MSG("Custom channel color"), TRANSF) \ - XX(MessageName, RString, label, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Channel label."), TRANSF) \ - XX(MessageName, RString, callSign, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Channel Call Sign."), TRANSF) \ - XX(MessageName, RefArray, units, NDTRefArray, AutoArray, NCTNone, DEFVALUEREFARRAY, DOC_MSG("List of participating units"), TRANSF_REFS) - -DECLARE_NET_MESSAGE_INIT_MSG(CreateRadioChannel, CREATE_RADIO_CHANNEL_MSG) - -#define RADIO_CHANNEL_LABEL_MSG(MessageName, XX) \ - XX(MessageName, int, channel, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Custom channel in CCCustom1 to CCCustomLast range."), TRANSF) \ - XX(MessageName, RString, label, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Channel label."), TRANSF) - -DECLARE_NET_MESSAGE_INIT_MSG(RadioChannelLabel, RADIO_CHANNEL_LABEL_MSG) - -#define RADIO_CHANNEL_CALL_SIGN_MSG(MessageName, XX) \ - XX(MessageName, int, channel, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Custom channel in CCCustom1 to CCCustomLast range."), TRANSF) \ - XX(MessageName, RString, callSign, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Channel Call Sign."), TRANSF) - -DECLARE_NET_MESSAGE_INIT_MSG(RadioChannelCallSign, RADIO_CHANNEL_CALL_SIGN_MSG) - -#define RADIO_CHANNEL_UNITS_MSG(MessageName, XX) \ - XX(MessageName, int, channel, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Custom channel in CCCustom1 to CCCustomLast range."), TRANSF) \ - XX(MessageName, RefArray, units, NDTRefArray, AutoArray, NCTNone, DEFVALUEREFARRAY, DOC_MSG("List of participating units"), TRANSF_REFS) - -DECLARE_NET_MESSAGE_INIT_MSG(RadioChannelUnits, RADIO_CHANNEL_UNITS_MSG) - -#define HACKED_DATA_MSG(MessageName, XX) \ - XX(MessageName, int, type, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, HTUnsignedData), DOC_MSG("Type of violation."), TRANSF) \ - XX(MessageName, RString, filename, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Name of hacked file."), TRANSF) \ - -DECLARE_NET_MESSAGE(HackedData, HACKED_DATA_MSG) - -#define CDKEY_CHECK_ASK_MSG(MessageName, XX) \ - XX(MessageName, RString, challenge, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Chalenge string (see GameSpy SDK Help)."), TRANSF) \ - -DECLARE_NET_MESSAGE(CDKeyCheckAsk, CDKEY_CHECK_ASK_MSG) - -#define CDKEY_CHECK_ANSWER_MSG(MessageName, XX) \ - XX(MessageName, RString, response, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Response string (see GameSpy SDK Help)."), TRANSF) \ - -DECLARE_NET_MESSAGE(CDKeyCheckAnswer, CDKEY_CHECK_ANSWER_MSG) - -#define CDKEY_RECHECK_ASK_MSG(MessageName, XX) \ - XX(MessageName, int, hint, NDTInteger, int, NCTNone, DEFVALUE(int, -1), DOC_MSG("Session key (see GameSpy SDK Help)."), TRANSF) \ - XX(MessageName, RString, challenge, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Challenge string (see GameSpy SDK Help)."), TRANSF) \ - -DECLARE_NET_MESSAGE(CDKeyRecheckAsk, CDKEY_RECHECK_ASK_MSG) - -#define CDKEY_RECHECK_ANSWER_MSG(MessageName, XX) \ - XX(MessageName, int, hint, NDTInteger, int, NCTNone, DEFVALUE(int, -1), DOC_MSG("Session key (see GameSpy SDK Help)."), TRANSF) \ - XX(MessageName, RString, response, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Response string (see GameSpy SDK Help)."), TRANSF) \ - -DECLARE_NET_MESSAGE(CDKeyRecheckAnswer, CDKEY_RECHECK_ANSWER_MSG) - -#define ASK_CONNECT_VOICE_MSG(MessageName, XX) \ - XX(MessageName, int, publicAddr, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Public IP address of the client."), TRANSF) \ - XX(MessageName, int, privateAddr, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Private IP address of the client."), TRANSF) \ - XX(MessageName, int, voicePort, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Port voice channel is bind to."), TRANSF) \ - XX(MessageName, int, verNo, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("The build number of client exe file."), TRANSF) \ - -DECLARE_NET_MESSAGE(AskConnectVoice, ASK_CONNECT_VOICE_MSG) - -#define DIAG_OBJECT_INFO_ASK_MSG(MessageName, XX) \ - XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("creator id of object"), TRANSF) \ - XX(MessageName, OIDInt, id, NDTOID, OIDInt, NOIDIntComp, DEFVALUE(OIDInt, 0), DOC_MSG("id object"), TRANSF) - -DECLARE_NET_MESSAGE(DiagObjectInfoAsk, DIAG_OBJECT_INFO_ASK_MSG) - -#define CLIENT_DIAG_TO_SERVER_MSG(MessageName, XX) \ - XX(MessageName, RString, response, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Any info client want server to log in tis report file."), TRANSF) - -DECLARE_NET_MESSAGE(ClientDiagToServer, CLIENT_DIAG_TO_SERVER_MSG) - -#define CONNECT_VOICE_DIRECT_MSG(MessageName, XX) \ - XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("ID of player to connect with"), TRANSF) \ - XX(MessageName, int, addr, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("IP address where connect to."), TRANSF) \ - XX(MessageName, int, port, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Port where connect to."), TRANSF) \ - XX(MessageName, bool, direct, NDTBool, bool, NCTNone, DEFVALUE(bool, true), DOC_MSG("Is the connection direct or punched?"), TRANSF) \ - -DECLARE_NET_MESSAGE(ConnectVoiceDirect, CONNECT_VOICE_DIRECT_MSG) - -#define CONNECT_VOICE_NAT_NEG_MSG(MessageName, XX) \ - XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("ID of player to connect with"), TRANSF) \ - XX(MessageName, int, cookie, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Cookie for Nat negotiation."), TRANSF) \ - XX(MessageName, int, clientIndex, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Client index for Nat negotiation."), TRANSF) \ - -DECLARE_NET_MESSAGE(ConnectVoiceNatNeg, CONNECT_VOICE_NAT_NEG_MSG) // TODO: remove (make dummy) - -#define NAT_NEG_RESULT_MSG(MessageName, XX) \ - XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("ID of NAT negotiating player"), TRANSF) \ - XX(MessageName, bool, result, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Result of NAT negotiation (true for success)."), TRANSF) \ - -DECLARE_NET_MESSAGE(NatNegResult, NAT_NEG_RESULT_MSG) - -#define DISCONNECT_MSG(MessageName, XX) \ - XX(MessageName, RString, message, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Cause why the player was disconnected."), TRANSF) \ - -DECLARE_NET_MESSAGE(Disconnect, DISCONNECT_MSG) - -#define MISSION_STATS_MSG(MessageName, XX) \ - XX(MessageName, int, toCreate, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Number of objects we will create on the client."), TRANSF) \ - XX(MessageName, int, toUpdate, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Number of objects we will update on the client."), TRANSF) \ - -DECLARE_NET_MESSAGE(MissionStats, MISSION_STATS_MSG) - -#define ASK_FOR_ARBITRATION_MSG(MessageName, XX) \ - XX(MessageName, NetInt64, sessionNonce, NDTInt64, NetInt64, NCTNone, DEFVALUE(NetInt64, 0), DOC_MSG("Key used for arbitration."), TRANSF) \ - -DECLARE_NET_MESSAGE(AskForArbitration, ASK_FOR_ARBITRATION_MSG) - -#define BATTLEYE_MSG(MessageName, XX) \ - XX(MessageName, AutoArray, message, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Message content"), TRANSF) \ - -DECLARE_NET_MESSAGE(BattlEye_Obsolete, BATTLEYE_MSG) - -#define SERVERTIME_MSG(MessageName, XX) \ - XX(MessageName, int, time, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Server time"), TRANSF) \ - XX(MessageName, int, endTime, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Server time of estimated end of MP game."), TRANSF) \ - -DECLARE_NET_MESSAGE(ServerTime, SERVERTIME_MSG) - -#define SERVER_ADMIN_MESSAGE(MessageName, XX) \ - XX(MessageName, bool, admin, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("GameMaster on server is voted admin."), TRANSF) \ - XX(MessageName, int, gameMaster, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Id of gameMaster."), TRANSF) \ - -DECLARE_NET_MESSAGE(ServerAdmin, SERVER_ADMIN_MESSAGE) - -#define SEND_AU_MSG(MessageName, XX) \ - XX(MessageName, AutoArray, value, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Send Auto Update message content"), TRANSF) - -DECLARE_NET_MESSAGE(SendAUMsg, SEND_AU_MSG) - -/// Custom file message to check whether the transfer to client is neccessary -#define CUSTOM_FILE_PATHS_MSG(MessageName, XX) \ - XX(MessageName, RString, dst, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Custom file path"), TRANSF) \ - XX(MessageName, int, crc, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("CRC of custom file"), TRANSF) \ - XX(MessageName, int, len, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("File length of custom file"), TRANSF) - -DECLARE_NET_INDICES(CustomFile, CUSTOM_FILE_PATHS_MSG) - -// NetworkMessageCustomFileList to transfer array of CustomFilePaths -#define CUSTOM_FILE_LIST_MSG(MessageName, XX) \ - XX(MessageName, int, player, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Direct play id"), TRANSF) \ - XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Player name"), TRANSF) \ - XX(MessageName, AutoArray, fileList, NDTObjectArray, REF_MSG_ARRAY(NetworkMessageCustomFile), NCTNone, DEFVALUE_MSG(NMTCustomFile), DOC_MSG("List of custom files"), TRANSF_ARRAY) - -DECLARE_NET_MESSAGE(CustomFileList, CUSTOM_FILE_LIST_MSG) - -#define CUSTOM_FILES_WANTED_MSG(MessageName, XX) \ - XX(MessageName, int, player, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Direct play id"), TRANSF) \ - XX(MessageName, AutoArray, filesWanted, NDTIntArray, AutoArray, NCTSmallUnsigned, DEFVALUEINTARRAY, DOC_MSG("Array of indexes to custom file list which client wants to get"), TRANSF) \ - -DECLARE_NET_MESSAGE(CustomFilesWanted, CUSTOM_FILES_WANTED_MSG) - -#define DELETE_CUSTOM_FILES_MSG(MessageName, XX) \ - XX(MessageName, AutoArray, list, NDTStringArray, AutoArray, NCTNone, DEFVALUESTRINGARRAY, DOC_MSG("Array of indexes to custom file list which client wants to get"), TRANSF) \ - -DECLARE_NET_MESSAGE(DeleteCustomFiles, DELETE_CUSTOM_FILES_MSG) - -#if _PROFILE -#define DEBUG_GIVEN_NETWORK_ID 1 -#endif - -#if DEBUG_GIVEN_NETWORK_ID -bool DebugMeBoy(NetworkId id); -bool DebugMeBoy(NetworkMessage *msg, NetworkMessageType type); -#else -inline bool DebugMeBoy(NetworkId id) {return false;} -inline bool DebugMeBoy(NetworkMessage *msg, NetworkMessageType type) {return false;} -#endif -bool ReadValue(GameValue &value, const void* buffer, int buffSize, INetworkManager *netManager); - -#endif +#ifdef _MSC_VER +#pragma once +#endif + +#ifndef _NETWORK_IMPL_HPP +#define _NETWORK_IMPL_HPP + + +#include "netTransport.hpp" +#include "network.hpp" +#include "../versionNo.h" +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) +#include +#endif + +#include +#include "../memHeap.hpp" + +#include "../speaker.hpp" +#include "../arcadeWaypoint.hpp" + +#include "../paramFileExt.hpp" + +#include +#include +#include + +#include +#include +#include "Es/Containers/quadtreeEx.hpp" + +#include +#include + +#if _ENABLE_STEAM_MATCHMAKING +# include +# include +#endif + +#include "../AI/ai.hpp" +#include "../house.hpp" + + + +/*! +\file +Internal interface file for multiplayer game (included only from inside of multiplayer files) +*/ + +//! Magic for distinguish applications +#define MAGIC_APP ((int)'D'+((int)'a'<<8)+((int)'y'<<16)+((int)'Z'<<24)) + +/* ArmA 1 values +#elif _DEMO // demo and ArmA do not share LAN sessions + #define MAGIC_APP 0x45454545 +#else // ArmA + #define MAGIC_APP 0x23232323 +#else // ArmA 2 + #define MAGIC_APP 0x25252525 +#endif +*/ + +// old OFP had #define MAGIC_APP 0x00000000 + +#define NO_CLIENT 0 +#define TO_SERVER 1 +// TODO: Avoid usage of this value as regular client ID +#define BOT_CLIENT 2 + +extern const int DiagLevel; +bool DiagFilter(NetworkMessageType type); +RString GetMsgTypeName(NetworkMessageType type); +// extern const char *NetworkMessageTypeNames[]; + +struct NetworkPlayerInfo; +class NetworkServer; + +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) +class SteamValidation +{ + uint64 _steamId; + NetworkServer *_server; + int _dpid; + bool _started; + bool _authPending; + unsigned long _ticksStarted; + RString _name; + AutoArray _steamSessionTicket; +public: + SteamValidation(); + ~SteamValidation(); + void Start(PlayerIdentity &identity, NetworkServer *server); + void HandleTimeout(); + STEAM_GAMESERVER_CALLBACK(SteamValidation, OnValidateAuthTicketResponse, ValidateAuthTicketResponse_t, _callbackGSAuthTicketResponse); +}; +#endif + +////////////////////////////////////////////////////////////////////////////// +// Network Messages + +//! Encapsulation for block of data transferred over network. +/*! +Implement methods nedded for transfer of NetworkMessage into raw data. +\todo Implement compression methods. +\todo Work with bits, no bytes. +*/ +class NetworkMessageRaw +{ +protected: + //! raw data itself + AutoArray _buffer; + //! read / write position + int _pos; + + //! external raw data + char *_externalBuffer; + //! size of external raw data + int _externalBufferSize; +public: + //! Constructor + NetworkMessageRaw() + {_pos = 0; _buffer.Realloc(1024); _externalBuffer = NULL; _externalBufferSize = 0;} + //! Constructor + /*! + \param buffer external data + \param size size of external data + */ + NetworkMessageRaw(char *buffer, int size) + {_pos = 0; _externalBuffer = buffer; _externalBufferSize = size;} + + //! Return total size of valid data + int GetSize() const {return _externalBuffer ? _externalBufferSize : _buffer.Size();} + //! Set new size of internal buffer, sets position to 0 + void SetSize(int size) {_buffer.Resize(size); _pos = 0;} + //! Get (read only) pointer to valid data + const char *GetData() const {return _externalBuffer ? _externalBuffer : _buffer.Data();} + //! Get (read and write) pointer to internal buffer + char *SetData() {return _buffer.Data();} + //! Return current read / write position in message + int GetPos() const {return _pos;} + + template + void PutSmallUnsigned(IntType value); + + //@{ + //! Write single value to buffer + /*! + \param value value to write + \param compression compression algorithm + */ + void Put(bool value, NetworkCompressionType compression); + void Put(char value, NetworkCompressionType compression); + void Put(int value, NetworkCompressionType compression); + void Put(NetInt64 &value, NetworkCompressionType compression); + void Put(float value, NetworkCompressionType compression); + void Put(RString value, NetworkCompressionType compression); + void Put(RStringB value, NetworkCompressionType compression); + void Put(const LocalizedString &value, NetworkCompressionType compression); + void Put(Time value, NetworkCompressionType compression); + void Put(Vector3Par value, NetworkCompressionType compression); + void Put(Matrix3Par value, NetworkCompressionType compression); + void Put(NetworkId &value, NetworkCompressionType compression); + void Put(CreatorId &value, NetworkCompressionType compression); + void Put(XNADDR &value, NetworkCompressionType compression); + void Put(XONLINE_STAT &value, NetworkCompressionType compression); + void* PutRaw(int size); + + //@} + + //@{ + //! Read single value from buffer + /*! + \param value reference to variable read into + \param compression compression algorithm + \return true if value was read, otherwise false + */ + bool GetNoCompression(RString &value); + bool GetNoCompression(RStringB &value); + + template + bool GetSmallUnsigned(IntType &value); + + bool Get(bool &value, NetworkCompressionType compression); + bool Get(char &value, NetworkCompressionType compression); + bool Get(int &value, NetworkCompressionType compression); + bool Get(NetInt64 &value, NetworkCompressionType compression); + bool Get(float &value, NetworkCompressionType compression); + bool Get(RString &value, NetworkCompressionType compression); + bool Get(RStringB &value, NetworkCompressionType compression); + bool Get(LocalizedString &value, NetworkCompressionType compression); + bool Get(Time &value, NetworkCompressionType compression); + bool Get(Vector3 &value, NetworkCompressionType compression); + bool Get(Matrix3 &value, NetworkCompressionType compression); + bool Get(NetworkId &value, NetworkCompressionType compression); + bool Get(CreatorId &value, NetworkCompressionType compression); + bool Get(XNADDR &value, NetworkCompressionType compression); + bool Get(XONLINE_STAT &value, NetworkCompressionType compression); + void* GetRaw(int size); + //@} + +protected: + //! Write raw data to buffer + /*! + \param buffer raw data + \param size raw data size + */ + void Write(const void *buffer, int size) + { + int minSize = _pos + size; + if (_buffer.Size() < minSize) _buffer.Resize(minSize); + memcpy(_buffer.Data() + _pos, buffer, size); + _pos += size; + } + //! Read raw data from buffer + /*! + \param buffer where read raw data + \param size size of data to read + \return true if data available in buffer, otherwise false + */ + bool Read(void *buffer, int size) + { + int minSize = _pos + size; + if (_externalBuffer) + { + if (_externalBufferSize < minSize) return false; + memcpy(buffer, _externalBuffer + _pos, size); + } + else + { + if (_buffer.Size() < minSize) return false; + memcpy(buffer, _buffer.Data() + _pos, size); + } + _pos += size; + return true; + } +}; +TypeIsMovable(NetworkMessageRaw) + +#define PLAYER_MSG(MessageName, XX) \ + XX(MessageName, int, player, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Unique ID of client (player)"), TRANSF)\ + XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Player's name"), TRANSF)\ + XX(MessageName, bool, server, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Bot client (running in the same process as server)"), TRANSF)\ + XX(MessageName, bool, vonDisabled, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Voice over Net disabled"), TRANSF)\ + XX(MessageName, int, vonCodecQuality, NDTInteger, int, NCTNone, DEFVALUE(int, 3), DOC_MSG("Voice over Net codec quality"), TRANSF)\ + XX(MessageName, bool, battlEye, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("BattlEye is required by the server"), TRANSF)\ + XX(MessageName, NetInt64, steamServerId, NDTInt64, NetInt64, NCTNone, DEFVALUE(NetInt64, 0), DOC_MSG("Steam server id"), TRANSF)\ + XX(MessageName, bool, steamSecure, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Steam VAC protection is active"), TRANSF)\ + XX(MessageName, int, sigVerRequired, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Required signatures version on the server"), TRANSF)\ + /*XX(MessageName, RString, regURL, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("ID Registration URL"), TRANSF)*/\ + XX(MessageName, bool, updatesGuaranteed, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Guaranteed (diffed) updates sent by the server"), TRANSF)\ + +DECLARE_NET_MESSAGE(Player, PLAYER_MSG) + +#define LOGOUT_MSG(MessageName, XX) \ + XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("ID of client (player)"), TRANSF) + +DECLARE_NET_MESSAGE(Logout, LOGOUT_MSG) + +#define PUB_VAR_TO_MSG(MessageName, XX) \ + XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Variable name"), TRANSF) \ + XX(MessageName, AutoArray, value, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Variable value"), TRANSF) \ + XX(MessageName, int, player, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Unique ID of client (player)"), TRANSF) + +DECLARE_NET_MESSAGE_INIT_MSG(PublicVariableTo, PUB_VAR_TO_MSG) + +#define SPAWN_FOR_PLAYER_MSG(MessageName, XX) \ + XX(MessageName, RString, code, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Code to execute"), TRANSF) \ + XX(MessageName, AutoArray, signature, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Code signature to verify it was issued by the server"), TRANSF) \ + XX(MessageName, AutoArray, value, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Parameters"), TRANSF) + +DECLARE_NET_MESSAGE_INIT_MSG(SpawnForPlayer,SPAWN_FOR_PLAYER_MSG) + +TypeIsMovable(SpawnForPlayerMessage); + +#define SYNCHRONIZE_VARIABLE_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(EntityAI), veh, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Variable owner"), TRANSF_REF) \ + XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Variable name"), TRANSF) \ + XX(MessageName, float, coef, NDTFloat, float, NCTFloatMostly0To1, DEFVALUE(float, 0), DOC_MSG("Importance"), TRANSF) \ + XX(MessageName, RString, handler, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Change handler"), TRANSF) \ + +DECLARE_NET_MESSAGE(SynchronizeVariable,SYNCHRONIZE_VARIABLE_MSG) + +#define APPLYWEATHER_MSG(MessageName,XX) \ + XX(MessageName, float,seaLevelOffset, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF) \ + XX(MessageName, float,overcastSetSky, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF) \ + /*XX(MessageName, float,overcastSetClouds, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF)*/ \ + XX(MessageName, float,fogSet, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF) \ + /*XX(MessageName, float,cloudsPos, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF)*/ \ + /*XX(MessageName, float,cloudsAlpha, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF)*/ \ + /*XX(MessageName, float,cloudsBrightness, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF)*/ \ + /*XX(MessageName, float,cloudsSpeed, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF)*/ \ + /*XX(MessageName, float,skyThrough, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF)*/ \ + /*XX(MessageName, float,rainDensity, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF)*/ \ + XX(MessageName, float,wind, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF) \ + XX(MessageName, float,rainDensityWanted, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF) \ + XX(MessageName, float,rainDensitySpeed, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG(""), TRANSF) \ + XX(MessageName, int,rainNextChange, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ + XX(MessageName, int,nextWeatherChange, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ + XX(MessageName, int,lastWindSpeedChange, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ + XX(MessageName, int,gustUntil, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ + XX(MessageName, Vector3,windSpeed, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG(""), TRANSF) \ + XX(MessageName, Vector3,currentWindSpeed, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG(""), TRANSF) \ + XX(MessageName, Vector3,currentWindSpeedSlow, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG(""), TRANSF) \ + XX(MessageName, Vector3,gust, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG(""), TRANSF) \ + XX(MessageName, int,year, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ + XX(MessageName, int,month, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ + XX(MessageName, int,day, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ + XX(MessageName, int,hour, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ + XX(MessageName, int,minute, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) + +DECLARE_NET_MESSAGE(ApplyWeather, APPLYWEATHER_MSG) + +#if _VBS3 + +#define AARDOUPDATE_MSG(MessageName,XX) \ + XX(MessageName, int, type, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Type of AAR message"), TRANSF) \ + XX(MessageName, int, intType, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("int type can be anything"), TRANSF) \ + XX(MessageName, RString, stringOne , NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("string can be anything"), TRANSF) \ + XX(MessageName, RString, stringTwo , NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("string can be anything"), TRANSF) \ + XX(MessageName, float , floatType , NDTFloat, float, NCTNone, DEFVALUE(float, 0.5), DOC_MSG("float type can be anything"), TRANSF) \ + +DECLARE_NET_MESSAGE(AARDoUpdate, AARDOUPDATE_MSG) + +#define AARASKUPDATE_MSG(MessageName,XX) \ + XX(MessageName, int, type, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Type of AAR message"), TRANSF) \ + XX(MessageName, int, intType, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("int type can be anything"), TRANSF) \ + XX(MessageName, RString, stringOne , NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("string can be anything"), TRANSF) \ + XX(MessageName, RString, stringTwo , NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("string can be anything"), TRANSF) \ + XX(MessageName, float , floatType , NDTFloat, float, NCTNone, DEFVALUE(float, 0.5), DOC_MSG("float type can be anything"), TRANSF) \ + +DECLARE_NET_MESSAGE(AARAskUpdate, AARASKUPDATE_MSG) + + +#define ADDMPREPORT_MSG(MessageName,XX) \ + XX(MessageName, int, type , NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Type of string carried to add to all clients"), TRANSF) \ + XX(MessageName, RString, myString , NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("string can be anything"), TRANSF) \ + +DECLARE_NET_MESSAGE(AddMPReport, ADDMPREPORT_MSG) + +#define LOADISLAND_MSG(MessageName,XX) \ + XX(MessageName, RString, islandName , NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Island to load on the client"), TRANSF) \ + +DECLARE_NET_MESSAGE(LoadIsland, LOADISLAND_MSG) + + +#define ASKCOMMANDEROVERRIDE_MSG(MessageName,XX) \ + XX(MessageName, OLinkPermNO(Turret), turret, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Specification of turret to override"), TRANSF_REF) \ + XX(MessageName, OLinkNO(Turret), overriddenByTurret, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Which turret takes control"), TRANSF_REF) + +DECLARE_NET_MESSAGE(AskCommanderOverride, ASKCOMMANDEROVERRIDE_MSG) + +#endif //_VBS3 + +#define ASK_FOR_SET_ITEM_SHORTCUT_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Player person"), TRANSF_REF) \ + XX(MessageName, int, index, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Shortcut index"), TRANSF)\ + XX(MessageName, OLinkPermO(InventoryItem), item, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Bound inventory item"), TRANSF_REF) \ + XX(MessageName, RString, itemType, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Name of the item type"), TRANSF) \ + +DECLARE_NET_MESSAGE(AskForSetItemShortcut, ASK_FOR_SET_ITEM_SHORTCUT_MSG) + +#define ASK_INVENTORY_MENU_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(Person), unit, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Asked unit"), TRANSF_REF) \ + XX(MessageName, OLinkPermO(InventoryItem), item1, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Involved item"), TRANSF_REF) \ + XX(MessageName, OLinkPermO(InventoryItem), item2, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Involved item"), TRANSF_REF) \ + +DECLARE_NET_MESSAGE(AskInventoryMenu, ASK_INVENTORY_MENU_MSG) + +#define ASK_FOR_THROW_ITEM_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(Man), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person throwing the item"), TRANSF_REF) \ + XX(MessageName, OLinkPermO(InventoryItem), item, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Thrown item"), TRANSF_REF) \ + XX(MessageName, Vector3, pos, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, Vector3(0, 0, 0)), DOC_MSG("item start position in world"), TRANSF) \ + XX(MessageName, Vector3, dir, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, Vector3(0, 0, 0)), DOC_MSG("throw direction"), TRANSF) \ + +DECLARE_NET_MESSAGE(AskForThrowItem, ASK_FOR_THROW_ITEM_MSG) + +#define ASK_FOR_DROP_ITEM_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person dropping the item"), TRANSF_REF) \ + XX(MessageName, OLinkPermO(InventoryItem), item, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Dropped item"), TRANSF_REF) \ + +DECLARE_NET_MESSAGE(AskForDropItem, ASK_FOR_DROP_ITEM_MSG) + +#define ASK_FOR_MOVE_ITEM_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(EntityAI), target, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("New owner of the item"), TRANSF_REF) \ + XX(MessageName, int, index, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Slot index"), TRANSF)\ + XX(MessageName, OLinkPermO(InventoryItem), item, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Moved item"), TRANSF_REF) \ + XX(MessageName, bool, rotated, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Requested inventory orientation"), TRANSF) \ + +DECLARE_NET_MESSAGE(AskForMoveItem, ASK_FOR_MOVE_ITEM_MSG) + +#define ASK_FOR_ROTATE_INVENTORY_ITEM_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Player requesting item rotation"), TRANSF_REF) \ + XX(MessageName, OLinkPermO(InventoryItem), item, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Item to rotate in cargo"), TRANSF_REF) \ + +DECLARE_NET_MESSAGE(AskForRotateInventoryItem, ASK_FOR_ROTATE_INVENTORY_ITEM_MSG) + +#define ASK_FOR_TAKE_ITEM_TO_HANDS_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person holding the item"), TRANSF_REF) \ + XX(MessageName, OLinkPermO(InventoryItem), item, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Held item"), TRANSF_REF) \ + +DECLARE_NET_MESSAGE(AskForTakeItemToHands, ASK_FOR_TAKE_ITEM_TO_HANDS_MSG) + +#define ASK_FOR_SWAP_ITEMS_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(InventoryItem), item1, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Swapping item"), TRANSF_REF) \ + XX(MessageName, OLinkPermO(InventoryItem), item2, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Swapping item"), TRANSF_REF) \ + XX(MessageName, OLinkPermO(Person), owner, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person owning the items"), TRANSF_REF) \ + +DECLARE_NET_MESSAGE(AskForSwapItems, ASK_FOR_SWAP_ITEMS_MSG) + +#define ASK_FOR_PLAYER_ACTION_MSG(MessageName, XX) \ + XX(MessageName, RString, action, NDTString, RString, NCTStringMove, DEFVALUE(RString, ""), DOC_MSG("Action identification"), TRANSF) \ + XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person doing the action (must be owned by the client)"), TRANSF_REF) \ + +DECLARE_NET_MESSAGE(AskForPlayerAction, ASK_FOR_PLAYER_ACTION_MSG) + +#if _VBS3 // respawn command +#define PAUSESIMULATION_MSG(MessageName, XX) \ + XX(MessageName, bool, pause, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Pause local simulation"), TRANSF) + +DECLARE_NET_MESSAGE(PauseSimulation,PAUSESIMULATION_MSG) + +#endif + +#if _ENABLE_ATTACHED_OBJECTS +#define ATTACHOBJECT_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(Object), obj, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Object to attach"), TRANSF_REF) \ + XX(MessageName, OLinkPermO(Object), attachTo, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Object to attach to"), TRANSF_REF) \ + XX(MessageName, int, memIndex, NDTInteger, int, NCTNone, DEFVALUE(int, -1), DOC_MSG("memory point index"), TRANSF) \ + XX(MessageName, Vector3, pos, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, Vector3(0, 0, 0)), DOC_MSG("offset"), TRANSF) \ + XX(MessageName, int, flags, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Additional flags"), TRANSF) + +DECLARE_NET_MESSAGE(AttachObject,ATTACHOBJECT_MSG) + +#define DETACHOBJECT_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(Object), obj, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Object to detach"), TRANSF_REF) + +DECLARE_NET_MESSAGE(DetachObject,DETACHOBJECT_MSG) +#endif + +#define MISSION_PARAMS_MSG(MessageName, XX) \ + XX(MessageName, float, param1, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG("Mission parameter"), TRANSF) \ + XX(MessageName, float, param2, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG("Mission parameter"), TRANSF) \ + XX(MessageName, AutoArray, paramsArray, NDTFloatArray, AutoArray, NCTNone, DEFVALUEFLOATARRAY, DOC_MSG("Array of mission parameters"), TRANSF) \ + XX(MessageName, bool, updateOnly, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Change of params from dialog"), TRANSF) + +DECLARE_NET_MESSAGE(MissionParams, MISSION_PARAMS_MSG) + +#define ANIMATION_PHASE_MSG(MessageName, XX) \ + XX(MessageName, OLink(Entity), vehicle, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Animated vehicle"), TRANSF_REF) \ + XX(MessageName, RString, animation, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Animation ID"), TRANSF) \ + XX(MessageName, float, phase, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG("Animation state (phase)"), TRANSF) + +DECLARE_NET_MESSAGE_INIT_MSG(AskForAnimationPhase,ANIMATION_PHASE_MSG) + +#define VEHICLE_DAMAGED_MSG(MessageName, XX) \ + XX(MessageName, OLink(EntityAI), damaged, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Damaged entity"), TRANSF_REF) \ + XX(MessageName, OLinkPermO(EntityAI), killer, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Entity, causing damage"), TRANSF_REF) \ + XX(MessageName, float, damage, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG("Amount of damage"), TRANSF) \ + XX(MessageName, RString, ammo, NDTString, RString, NCTDefault, DEFVALUE(RString, ""), DOC_MSG("Used ammunition type"), TRANSF) + +DECLARE_NET_MESSAGE(VehicleDamaged, VEHICLE_DAMAGED_MSG) + +#define SERVER_STATE_MSG(MessageName, XX) \ + XX(MessageName, int, serverState, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Server state"), TRANSF) + +DECLARE_NET_MESSAGE(ServerState, SERVER_STATE_MSG) + +#define CLIENT_STATE_MSG(MessageName, XX) \ + XX(MessageName, int, clientState, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Client state"), TRANSF) + +DECLARE_NET_MESSAGE(ClientState, CLIENT_STATE_MSG) + +#define PLAYER_CLIENT_STATE_MSG(MessageName, XX) \ + XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Client (player) id"), TRANSF) \ + XX(MessageName, int, clientState, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Client state"), TRANSF) + +DECLARE_NET_MESSAGE(PlayerClientState, PLAYER_CLIENT_STATE_MSG) + +#define APPLY_IDENTITY_MSG(MessageName, XX) \ + XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Client (player) id"), TRANSF) \ + XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person, which identity will be changed"), TRANSF_REF) + +#define FORCE_DELETE_OBJECT_MSG(MessageName, XX) \ + XX(MessageName, OLinkNO(NetworkObject), object, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Object to destroy"), TRANSF_REF) + +DECLARE_NET_MESSAGE(ForceDeleteObject, FORCE_DELETE_OBJECT_MSG) + +#define MUTE_LIST_MSG(MessageName, XX) \ + XX(MessageName, XUID_ARRAY_TYPE, list, XUID_ARRAY_NET_TYPE, XUID_ARRAY_TYPE, NCTNone, XUID_ARRAY_DEF_VALUE, DOC_MSG("User ids"), TRANSF) + +DECLARE_NET_MESSAGE(MuteList, MUTE_LIST_MSG) + +#define REMOTE_MUTE_LIST_MSG(MessageName, XX) \ + XX(MessageName, AutoArray, list, NDTIntArray, AutoArray, NCTNone, DEFVALUEINTARRAY, DOC_MSG("List of muting players"), TRANSF) + +DECLARE_NET_MESSAGE(RemoteMuteList, REMOTE_MUTE_LIST_MSG) + +#define VOICE_ON_MSG(MessageName, XX) \ + XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Client (player) id"), TRANSF) \ + XX(MessageName, bool, voiceOn, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Voice communicator is connected"), TRANSF) + +DECLARE_NET_MESSAGE(VoiceOn, VOICE_ON_MSG) + +#define CLEANUP_PLAYER_MSG(MessageName, XX) \ + XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Client (player) id"), TRANSF) \ + XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Id of player person"), TRANSF) \ + XX(MessageName, int, id, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Id of player person"), TRANSF) + +DECLARE_NET_MESSAGE(CleanupPlayer, CLEANUP_PLAYER_MSG) + +#define PROCESS_ACTION_MSG(MessageName, XX) \ + XX(MessageName, int, actionType, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, -1), DOC_MSG("Action type"), TRANSF) \ + XX(MessageName, OLink(Object), actionTarget, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Action target"), TRANSF_REF) \ + XX(MessageName, AutoArray, actionParams, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Action parameters based on type"), TRANSF) \ + XX(MessageName, OLinkPermO(Person), unit, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person processing the action"), TRANSF_REF) + +DECLARE_NET_MESSAGE(ProcessAction, PROCESS_ACTION_MSG) + +#define PROCESS_RECIPE_MSG(MessageName, XX) \ + XX(MessageName, RString, recipe, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Recipe name"), TRANSF) \ + XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person executing the recipe"), TRANSF_REF) \ + XX(MessageName, OLinkPermO(InventoryItem), item1, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Item involved in recipe"), TRANSF_REF) \ + XX(MessageName, OLinkPermO(InventoryItem), item2, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Item involved in recipe"), TRANSF_REF) \ + +DECLARE_NET_MESSAGE(ProcessRecipe, PROCESS_RECIPE_MSG) + +#define USE_ITEM_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(Person), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Owner of the item"), TRANSF_REF) \ + XX(MessageName, OLinkPermO(InventoryItem), item, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Item to use"), TRANSF_REF) \ + +DECLARE_NET_MESSAGE(UseItem, USE_ITEM_MSG) + +#define CHAT_MSG(MessageName, XX) \ + XX(MessageName, int, channel, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Radio channel"), TRANSF) \ + XX(MessageName, OLinkPermO(Person), sender, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Sender unit"), TRANSF_REF) \ + XX(MessageName, RefArray, units, NDTRefArray, AutoArray, NCTNone, DEFVALUEREFARRAY, DOC_MSG("List of receiving units"), TRANSF_REFS) \ + XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Sender name"), TRANSF) \ + XX(MessageName, RString, text, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Message content"), TRANSF) + +DECLARE_NET_MESSAGE(Chat, CHAT_MSG) + +#define RADIO_CHAT_MSG(MessageName, XX) \ + XX(MessageName, int, channel, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Radio channel"), TRANSF) \ + XX(MessageName, OLinkPermO(Person), sender, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Sender unit"), TRANSF_REF) \ + XX(MessageName, RefArray, units, NDTRefArray, AutoArray, NCTNone, DEFVALUEREFARRAY, DOC_MSG("List of receiving units"), TRANSF_REFS) \ + XX(MessageName, RString, text, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Message content"), TRANSF) \ + XX(MessageName, RadioSentence, sentence, NDTSentence, RadioSentence, NCTNone, DEFVALUE(RadioSentence, RadioSentence()), DOC_MSG("Content of message (list of words to say)"), TRANSF) \ + XX(MessageName, RString, wordsClass, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Possible subclass in class words to define alternative set of words such as whisper"), TRANSF) + +DECLARE_NET_MESSAGE(RadioChat, RADIO_CHAT_MSG) + +#define RADIO_CHAT_WAVE_MSG(MessageName, XX) \ + XX(MessageName, int, channel, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Radio channel"), TRANSF) \ + XX(MessageName, OLinkPermO(Person), sender, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Sender unit"), TRANSF_REF) \ + XX(MessageName, RefArray, units, NDTRefArray, AutoArray, NCTNone, DEFVALUEREFARRAY, DOC_MSG("List of receiving units"), TRANSF_REFS) \ + XX(MessageName, RString, senderName, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Sender name"), TRANSF) \ + XX(MessageName, RString, wave, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Sound identifier"), TRANSF) + +DECLARE_NET_MESSAGE(RadioChatWave, RADIO_CHAT_WAVE_MSG) + +/** adapted from CHAT_MSG */ +#define LOCALIZED_CHAT_MSG(MessageName, XX) \ + XX(MessageName, int, channel, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Radio channel"), TRANSF) \ + XX(MessageName, OLinkPermO(Person), sender, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Sender unit"), TRANSF_REF) \ + XX(MessageName, RefArray, units, NDTRefArray, AutoArray, NCTNone, DEFVALUEREFARRAY, DOC_MSG("List of receiving units"), TRANSF_REFS) \ + XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Sender name"), TRANSF) \ + XX(MessageName, AutoArray, args, NDTLocalizedStringArray, AutoArray, NCTNone, DEFVALUELOCALIZEDSTRINGARRAY, DOC_MSG("Client-side localized text with arguments"), TRANSF) \ + +DECLARE_NET_MESSAGE(LocalizedChat,LOCALIZED_CHAT_MSG) + +#define SET_SPEAKER_MSG(MessageName, XX) \ + XX(MessageName, int, player, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Client (player) ID of speaking player"), TRANSF) \ + XX(MessageName, int, on, NDTBool, int, NCTNone, DEFVALUE(bool, false), DOC_MSG("Turn on / off direct speaking"), TRANSF) \ + XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("ID of speaking unit"), TRANSF) \ + XX(MessageName, OIDInt, id, NDTOID, OIDInt, NOIDIntComp, DEFVALUE(OIDInt, 0), DOC_MSG("ID of speaking unit"), TRANSF) + +DECLARE_NET_MESSAGE(SetSpeaker, SET_SPEAKER_MSG) + +#define SELECT_PLAYER_MSG(MessageName, XX) \ + XX(MessageName, int, player, NDTInteger, int, NCTNone, DEFVALUE(int, AI_PLAYER), DOC_MSG("Client (player) ID of player"), TRANSF) \ + XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("ID of player's unit"), TRANSF) \ + XX(MessageName, OIDInt, id, NDTOID, OIDInt, NOIDIntComp, DEFVALUE(OIDInt, 0), DOC_MSG("ID of player's unit"), TRANSF) \ + XX(MessageName, Vector3, position, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, Vector3(-FLT_MAX, -FLT_MAX, -FLT_MAX)), DOC_MSG("Player's unit position"), TRANSF) \ + XX(MessageName, bool, respawn, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Selection of player's unit after respawn"), TRANSF) + +DECLARE_NET_MESSAGE(SelectPlayer, SELECT_PLAYER_MSG) + +#define CHANGE_OWNER_MSG(MessageName, XX) \ + XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("ID of object, which owner is changing"), TRANSF) \ + XX(MessageName, OIDInt, id, NDTOID, OIDInt, NOIDIntComp, DEFVALUE(OIDInt, 0), DOC_MSG("ID of object, whic player is changing"), TRANSF) \ + XX(MessageName, int, owner, NDTInteger, int, NCTNone, DEFVALUE(int, AI_PLAYER), DOC_MSG("Client ID of new owner"), TRANSF) \ + XX(MessageName, bool, disconnected, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Disconnected player becomes AI"), TRANSF) + +DECLARE_NET_MESSAGE(ChangeOwner, CHANGE_OWNER_MSG) + +#define OWNER_CHANGED_MSG(MessageName, XX) \ + XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("ID of object, which owner was changed"), TRANSF) \ + XX(MessageName, OIDInt, id, NDTOID, OIDInt, NOIDIntComp, DEFVALUE(OIDInt, 0), DOC_MSG("ID of object, whic player is changing"), TRANSF) + +DECLARE_NET_MESSAGE(OwnerChanged, OWNER_CHANGED_MSG) + +#define PLAY_SOUND_MSG(MessageName, XX) \ + XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Sound identifier"), TRANSF) \ + XX(MessageName, Vector3, position, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Sound source position"), TRANSF) \ + XX(MessageName, Vector3, speed, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Sound source speed"), TRANSF) \ + XX(MessageName, float, volume, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG("Sound volume"), TRANSF) \ + XX(MessageName, float, frequency, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG("Sound pitch"), TRANSF) \ + XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Unique network ID of sound"), TRANSF) \ + XX(MessageName, int, soundId, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Unique network ID of sound"), TRANSF) + +DECLARE_NET_MESSAGE(PlaySound, PLAY_SOUND_MSG) + +#define SOUND_STATE_MSG(MessageName, XX) \ + XX(MessageName, int, state, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("New state of sound"), TRANSF) \ + XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Network ID of sound"), TRANSF) \ + XX(MessageName, int, soundId, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Network ID of sound"), TRANSF) + +DECLARE_NET_MESSAGE(SoundState, SOUND_STATE_MSG) + +#define DELETE_OBJECT_MSG(MessageName, XX) \ + XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Id of object to destroy"), TRANSF) \ + XX(MessageName, OIDInt, id, NDTOID, OIDInt, NOIDIntComp, DEFVALUE(OIDInt, 0), DOC_MSG("Id of object to destroy"), TRANSF) + +DECLARE_NET_MESSAGE(DeleteObject, DELETE_OBJECT_MSG) + +#define DELETED_OBJECT_MSG(MessageName, XX) \ + XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Id of object destroyed"), TRANSF) \ + XX(MessageName, OIDInt, id, NDTOID, OIDInt, NOIDIntComp, DEFVALUE(OIDInt, 0), DOC_MSG("Id of object destroyed"), TRANSF) + +DECLARE_NET_MESSAGE(DeletedObject, DELETED_OBJECT_MSG) + +#define ASK_FOR_PILOT_LIGHT_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(EntityAI), vehicle, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Force switch on/off pilot light"), TRANSF_REF) \ + XX(MessageName, bool, enable, NDTBool, bool, NCTNone, DEFVALUE(bool, true), DOC_MSG(""), TRANSF) + +DECLARE_NET_MESSAGE(AskForPilotLight, ASK_FOR_PILOT_LIGHT_MSG) + +#define ASK_FOR_VEHICLE_DOOR_STATE_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(Transport), vehicle, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Open or close vehicle door"), TRANSF_REF) \ + XX(MessageName, int, doorIndex, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, -1), DOC_MSG("Index of door"), TRANSF) \ + XX(MessageName, bool, opened, NDTBool, bool, NCTNone, DEFVALUE(bool, true), DOC_MSG(""), TRANSF) + +DECLARE_NET_MESSAGE(AskForVehicleDoorState, ASK_FOR_VEHICLE_DOOR_STATE_MSG) + +#define ASK_FOR_AMMO_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(EntityAIFull), vehicle, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Vehicle which ammo is changing"), TRANSF_REF) \ + XX(MessageName, OLinkPermNO(Turret), turret, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Turret which ammo is changing"), TRANSF_REF) \ + XX(MessageName, OLinkPermO(Weapon), weapon, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Weapon"), TRANSF_REF) \ + XX(MessageName, int, muzzle, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Muzzle index"), TRANSF) \ + XX(MessageName, int, mode, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Mode index"), TRANSF) \ + XX(MessageName, int, burst, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 1), DOC_MSG("Amount of ammo to decrease"), TRANSF) + +DECLARE_NET_MESSAGE(AskForAmmo, ASK_FOR_AMMO_MSG) + +#define ASK_FOR_MOVE_VECTOR_MSG(MessageName, XX) \ + XX(MessageName, OLinkPerm, vehicle, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Moving object"), TRANSF_REF) \ + XX(MessageName, Vector3, pos, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("New position"), TRANSF) + +DECLARE_NET_MESSAGE(AskForMoveVector, ASK_FOR_MOVE_VECTOR_MSG) + +#define ASK_FOR_MOVE_MATRIX_MSG(MessageName, XX) \ + XX(MessageName, OLinkPerm, vehicle, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Moving object"), TRANSF_REF) \ + XX(MessageName, Vector3, pos, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("New position"), TRANSF) \ + XX(MessageName, Matrix3, orient, NDTMatrix, Matrix3, NCTNone, DEFVALUE(Matrix3, M3Identity), DOC_MSG("New orientation"), TRANSF) + +DECLARE_NET_MESSAGE(AskForMoveMatrix, ASK_FOR_MOVE_MATRIX_MSG) + +#define ASK_FOR_SET_MAGAZINE_AMMO_MSG(MessageName, XX) \ + XX(MessageName, OLinkPerm, magazine, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Magazine object"), TRANSF_REF) \ + XX(MessageName, int, ammo, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("New amount of ammo"), TRANSF) + +DECLARE_NET_MESSAGE(AskForSetMagazineAmmo, ASK_FOR_SET_MAGAZINE_AMMO_MSG) + +/* +void ExplosionDamage(EntityAI *owner, Shot *shot, Object *directHit, Vector3Par directHitModelPos, HitInfoPar hitInfo, Object *componentOwner=NULL, int componentIndex=-1, float energyFactor=1.0f, float explosionFactor=0.3f); +void ExplosionDamageEffects(EntityAI *owner, Object *directHit, HitInfoPar hitInfo, int componentIndex, bool enemyDamage, float energyFactor, float explosionFactor); +*/ + +#define EXPLOSION_DAMAGE_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(EntityAI), owner, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Shot owner (who is responsible for explosion)"), TRANSF_REF) \ + XX(MessageName, OLink(Object), directHit, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Hit object"), TRANSF_REF) \ + XX(MessageName, Vector3, originDir, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("World space origin direction relative to the target"), TRANSF) /*TODO: replace with originPos*/ \ + XX(MessageName, Vector3, directHitModelPos, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Explosion position in directHit model coordinates"), TRANSF) \ + XX(MessageName, OLink(Object), componentOwner, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Hit object - may be proxy, owner of componentIndex"), TRANSF_REF) \ + XX(MessageName, int, componentIndex, NDTInteger, int, NCTNone, DEFVALUE(int, -1), DOC_MSG("Index of hit convex component"), TRANSF) \ + XX(MessageName, RString, type, NDTString, RString, NCTDefault, DEFVALUE(RString, ""), DOC_MSG("Ammunition type"), TRANSF) \ + XX(MessageName, Vector3, pos, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Explosion position"), TRANSF) \ + XX(MessageName, Vector3, surfNormal, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VUp), DOC_MSG("Surface normal at the explosion"), TRANSF) \ + XX(MessageName, Vector3, inSpeed, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Speed of the corresponding bullet/shell/missile"), TRANSF) \ + XX(MessageName, Vector3, outSpeed, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Result speed (if any)"), TRANSF) \ + XX(MessageName, float, energyFactor, NDTFloat, float, NCTFloatMostly0To1, DEFVALUE(float, 1), DOC_MSG("Energy coefficient for distant hits"), TRANSF) \ + XX(MessageName, float, explosionFactor, NDTFloat, float, NCTFloat0To1, DEFVALUE(float, 0), DOC_MSG("How large explosion is"), TRANSF)\ + XX(MessageName, float, hitDepth, NDTFloat, float, NCTFloat0To1, DEFVALUE(float, 0), DOC_MSG("The penetration depth of the hit"), TRANSF) + +DECLARE_NET_MESSAGE(ExplosionDamage, EXPLOSION_DAMAGE_MSG) + +#define EXPLOSION_DAMAGE_EFFECTS_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(EntityAI), owner, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Shot owner (who is responsible for explosion)"), TRANSF_REF) \ + XX(MessageName, OLink(Object), directHit, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Hit object"), TRANSF_REF) \ + XX(MessageName, int, componentIndex, NDTInteger, int, NCTNone, DEFVALUE(int, -1), DOC_MSG("Index of hit convex component"), TRANSF) \ + XX(MessageName, RString, type, NDTString, RString, NCTDefault, DEFVALUE(RString, ""), DOC_MSG("Ammunition type"), TRANSF) \ + XX(MessageName, Vector3, pos, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Explosion position"), TRANSF) \ + XX(MessageName, Vector3, surfNormal, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VUp), DOC_MSG("Surface normal at the explosion"), TRANSF) \ + XX(MessageName, Vector3, inSpeed, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Speed of the corresponding bullet/shell/missile"), TRANSF) \ + XX(MessageName, Vector3, outSpeed, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Result speed (if any)"), TRANSF) \ + XX(MessageName, bool, enemyDamage, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Some enemy was damaged"), TRANSF) \ + XX(MessageName, float, energyFactor, NDTFloat, float, NCTFloatMostly0To1, DEFVALUE(float, 1), DOC_MSG("Energy coefficient for distant hits"), TRANSF) \ + XX(MessageName, float, explosionFactor, NDTFloat, float, NCTFloat0To1, DEFVALUE(float, 0), DOC_MSG("How large explosion is"), TRANSF) + +DECLARE_NET_MESSAGE(ExplosionDamageEffects, EXPLOSION_DAMAGE_EFFECTS_MSG) + +#define PROJECTILE_DECAL_MSG(MessageName, XX) \ + XX(MessageName, OLink(Object), directHit, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Hit object"), TRANSF_REF) \ + XX(MessageName, int, componentIndex, NDTInteger, int, NCTNone, DEFVALUE(int, -1), DOC_MSG("Index of hit convex component"), TRANSF) \ + XX(MessageName, RString, ammoType, NDTString, RString, NCTDefault, DEFVALUE(RString, ""), DOC_MSG("Ammunition type"), TRANSF) \ + XX(MessageName, Vector3, hitPosWorld, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Explosion position in world space"), TRANSF) \ + XX(MessageName, Vector3, hitPosLcl, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Hit position on the body (model space)"), TRANSF) \ + XX(MessageName, Vector3, surfNormal, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VUp), DOC_MSG("Surface normal at the hit spot"), TRANSF) \ + XX(MessageName, Vector3, inSpeed, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Speed of the corresponding bullet/shell/missile"), TRANSF) \ + XX(MessageName, Vector3, outSpeed, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VZero), DOC_MSG("Result speed (if any)"), TRANSF) \ + XX(MessageName, Vector3, hitDirLcl, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VForward), DOC_MSG("Forward direction of the projectile (model space)"), TRANSF) \ + XX(MessageName, Vector3, hitDirUpLcl, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VUp), DOC_MSG("Up direction of the projectile (model space)"), TRANSF) \ + XX(MessageName, float, hitDepth, NDTFloat, float, NCTFloat0To1, DEFVALUE(float, 0), DOC_MSG("The penetration depth of the projectile"), TRANSF) + +DECLARE_NET_MESSAGE(ProjectileDecal, PROJECTILE_DECAL_MSG) + +#define REM_PROJECTILE_DECALS_MSG(MessageName, XX) \ + XX(MessageName, OLink(Object), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person to remove projectiles from"), TRANSF_REF) \ + +DECLARE_NET_MESSAGE(RemoveProjectileDecals, REM_PROJECTILE_DECALS_MSG) + +#define BOW_STATE_MSG(MessageName, XX) \ + XX(MessageName, OLink(Object), person, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Person using the bow"), TRANSF_REF) \ + XX(MessageName, int, state, NDTInteger, int, NCTNone, DEFVALUE(int, -1), DOC_MSG("Updated bow state"), TRANSF) \ + +DECLARE_NET_MESSAGE(BowState, BOW_STATE_MSG) + +#if _VBS3 + +// Transmit the projectile leaving the weapon +#define FIRE_WEAPON_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(EntityAIFull), vehicle, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Firing vehicle"), TRANSF_REF) \ + XX(MessageName, OLinkPermO(Person), gunner, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Firing gunner"), TRANSF_REF) \ + XX(MessageName, OLink(EntityAI), target, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Aimed target"), TRANSF_REF) \ + XX(MessageName, Vector3, pos, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VForward), DOC_MSG("Position of the fire"), TRANSF) \ + XX(MessageName, Vector3, dir, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VForward), DOC_MSG("Direction of the fire"), TRANSF) \ + XX(MessageName, int, weapon, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Firing weapon index"), TRANSF) \ + XX(MessageName, CreatorId, magazineCreator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Fired magazine id"), TRANSF) \ + XX(MessageName, int, magazineId, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Fired magazine id"), TRANSF) \ + XX(MessageName, float, visible, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG("How much is the fire visible"), TRANSF) \ + XX(MessageName, OLink(Entity), projectile, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Projectile leaving weapon"), TRANSF_REF) + +#else + +#define FIRE_WEAPON_MSG(MessageName, XX) \ + XX(MessageName, OLinkPermO(EntityAIFull), vehicle, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Firing vehicle"), TRANSF_REF) \ + XX(MessageName, OLinkPermO(Person), gunner, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Firing gunner"), TRANSF_REF) \ + XX(MessageName, OLink(EntityAI), target, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Aimed target"), TRANSF_REF) \ + XX(MessageName, Vector3, pos, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VForward), DOC_MSG("Position of the fire"), TRANSF) \ + XX(MessageName, Vector3, dir, NDTVector, Vector3, NCTNone, DEFVALUE(Vector3, VForward), DOC_MSG("Direction of the fire"), TRANSF) \ + XX(MessageName, OLinkPermO(Weapon), weapon, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Weapon"), TRANSF_REF) \ + XX(MessageName, int, muzzle, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Muzzle index"), TRANSF) \ + XX(MessageName, int, mode, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Mode index"), TRANSF) \ + XX(MessageName, OLinkPermO(Magazine), magazine, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Fired magazine."), TRANSF_REF) \ + XX(MessageName, float, visible, NDTFloat, float, NCTNone, DEFVALUE(float, 0), DOC_MSG("How much is the fire visible"), TRANSF) + +#endif + +DECLARE_NET_MESSAGE(FireWeapon, FIRE_WEAPON_MSG) + +#define VOTE_MISSION_MSG(MessageName, XX) \ + XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE_DEF(RString), DOC_MSG("Name of the mission"), TRANSF) \ + XX(MessageName, RString, diff, NDTString, RString, NCTNone, DEFVALUE_DEF(RString), DOC_MSG("Wanted difficulty"), TRANSF) \ + +DECLARE_NET_MESSAGE(VoteMission,VOTE_MISSION_MSG) + +#define SERVER_TIMEOUT_MSG(MessageName, XX) \ + XX(MessageName, int, timeout, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Timeout in seconds"), TRANSF) \ + +DECLARE_NET_MESSAGE(ServerTimeout,SERVER_TIMEOUT_MSG) + +#define SERVER_INFO_MSG(MessageName, XX) \ + XX(MessageName, RString, hostname, NDTString, RString, NCTNone, DEFVALUE_DEF(RString), DOC_MSG("Server Hostname"), TRANSF) \ + +DECLARE_NET_MESSAGE(ServerInfo,SERVER_INFO_MSG) + +#define VEHICLE_DESTROYED_MSG(MessageName, XX) \ + XX(MessageName, OLinkO(EntityAI), killed, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Destroyed vehicle"), TRANSF_REF) \ + XX(MessageName, OLinkPermO(EntityAI), killer, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Who is responsible for destroying"), TRANSF_REF) + +DECLARE_NET_MESSAGE(VehicleDestroyed, VEHICLE_DESTROYED_MSG) + +#define MARKER_DELETE_MSG(MessageName, XX) \ + XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Name of marker"), TRANSF) + +DECLARE_NET_MESSAGE(MarkerDelete, MARKER_DELETE_MSG) + +struct NetworkMessageMarker; +struct NetworkMessageEffects; + +#define MARKER_CREATE_MSG(MessageName, XX) \ + XX(MessageName, int, channel, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Chat channel (who will see the marker)"), TRANSF) \ + XX(MessageName, OLinkPermO(Person), sender, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Sender unit"), TRANSF_REF) \ + XX(MessageName, RefArray, units, NDTRefArray, AutoArray, NCTNone, DEFVALUEREFARRAY, DOC_MSG("List of receiving units"), TRANSF_REFS) \ + XX(MessageName, ArcadeMarkerInfo, marker, NDTObject, REF_MSG(NetworkMessageMarker), NCTNone, DEFVALUE_MSG(NMTMarker), DOC_MSG("Marker object to create"), TRANSF_OBJECT) + +DECLARE_NET_MESSAGE(MarkerCreate, MARKER_CREATE_MSG) + +#if _ENABLE_VBS + +#define SET_OBJECT_TEXTURE_MSG(MessageName, XX) \ + XX(MessageName, OLink(EntityAI), veh, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Vehicle that will have a texture changed"), TRANSF_REF) \ + XX(MessageName, int, index, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, -1), DOC_MSG("Index of selection to set texture for"), TRANSF) \ + XX(MessageName, RString, name, NDTString, RString, NCTDefault, DEFVALUE(RString, ""), DOC_MSG("Name of texture"), TRANSF) \ + XX(MessageName, RString, eval, NDTString, RString, NCTDefault, DEFVALUE(RString, "true"), DOC_MSG("Evaluation - must evaluate to true if texture is to be set on client"), TRANSF) + +DECLARE_NET_MESSAGE(SetObjectTexture, SET_OBJECT_TEXTURE_MSG) + +#define PUBLICEXEC_MSG(MessageName, XX) \ + XX(MessageName, RString, condition, NDTString, RString, NCTDefault, DEFVALUE(RString, ""), DOC_MSG("Condition to evaluate, if true then command will be executed"), TRANSF) \ + XX(MessageName, RString, command, NDTString, RString, NCTDefault, DEFVALUE(RString, ""), DOC_MSG("Command to execute if evaluation is true"), TRANSF) \ + XX(MessageName, OLink(Object), obj, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Object passed into condition and command as _this"), TRANSF_REF) \ + XX(MessageName, OLinkArray(Object), objs, NDTRefArray, AutoArray, NCTNone, DEFVALUEREFARRAY, DOC_MSG("Joining units"), TRANSF_REFS) + +DECLARE_NET_MESSAGE(PublicExec, PUBLICEXEC_MSG) + +#endif // _ENABLE_VBS + +#define TRANSFER_FILE_MSG(MessageName, XX) \ + XX(MessageName, RString, path, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Path of transferred file"), TRANSF) \ + XX(MessageName, AutoArray, data, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Content of file (single segment)"), TRANSF) \ + XX(MessageName, int, totSize, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Total size of file"), TRANSF) \ + XX(MessageName, int, offset, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Offset of this segment"), TRANSF) \ + XX(MessageName, int, totSegments, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 1), DOC_MSG("Total number of segments"), TRANSF) \ + XX(MessageName, int, curSegment, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Index of this segment"), TRANSF) + +DECLARE_NET_MESSAGE(TransferFile, TRANSFER_FILE_MSG) + +#define SUBSCRIBE_RADIOS_MSG(MessageName, XX) \ + XX(MessageName, int, player, NDTInteger, int, NCTNone, DEFVALUE(int, AI_PLAYER), DOC_MSG("Client (player) ID of player"), TRANSF) \ + XX(MessageName, AutoArray, frequences, NDTFloatArray, FindArray, NCTNone, DEFVALUEFLOATARRAY, DOC_MSG("List of subscribed frequences"), TRANSF) + +DECLARE_NET_MESSAGE(SubscribeRadios, SUBSCRIBE_RADIOS_MSG) + +#define STATUS_CHAT_MSG(MessageName, XX) \ + XX(MessageName, RString, text, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Status text to be shown on client"), TRANSF) \ + XX(MessageName, RString, color, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Color class to use when drawing the text"), TRANSF) \ + +DECLARE_NET_MESSAGE(StatusChat, STATUS_CHAT_MSG) + +//! Message for transfer mission pbo file to other clients +struct TransferMissionFileMessage : public TransferFileMessage +{ + DECLARE_DEFINE_NETWORK_OBJECT_SIMPLE(TransferMissionFile) +}; + +#define TRANSFER_MISSION_FILE_MSG(MessageName, XX) + +DECLARE_NET_INDICES_EX(TransferMissionFile, TransferFile, TRANSFER_MISSION_FILE_MSG) + +//! Message for transfer file to server +struct TransferFileToServerMessage : public TransferFileMessage +{ + DECLARE_DEFINE_NETWORK_OBJECT_SIMPLE(TransferFileToServer) +}; + +#define TRANSFER_FILE_TO_SERVER_MSG(MessageName, XX) + +DECLARE_NET_INDICES_EX(TransferFileToServer, TransferFile, TRANSFER_FILE_TO_SERVER_MSG) + +#define ASK_MISSION_FILE_MSG(MessageName, XX) \ + XX(MessageName, bool, valid, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Mission file is valid (present on client computer)"), TRANSF) + +DECLARE_NET_MESSAGE(AskMissionFile, ASK_MISSION_FILE_MSG) + +//! Single message in agregated message +struct NetworkMessageQueueItem : public RefCount +{ + //! message type + NetworkMessageType type; + //! message itself + Ref msg; + //! guaranteed msg this message depends on + RefR dependOn; + + virtual void SetFence(const RefR &resultMsg) = 0; + + //! MP Save serialization + LSError Serialize(ParamArchive &ar) + { + CHECK(ar.Serialize("Message", msg, 1)) + if (ar.IsLoading()) type = msg->GetNMType(); + return LSOK; + } +}; + +struct ClientQueueItem : public NetworkMessageQueueItem +{ + Ref object; + + virtual void SetFence(const RefR &resultMsg) + { + if (object) object->_fence = resultMsg; + } +}; + +struct ServerQueueItem : public NetworkMessageQueueItem +{ + RefR poInfo; + + virtual void SetFence(const RefR &resultMsg); +}; +TypeIsMovable(ServerQueueItem) + +//! Agregated message +/*! +We want NMTMessaes to be created. This class is not used, it only allows the message factory to compile. +*/ +class NetworkMessageQueue : public NetworkSimpleObject, public RefArray +{ +public: + DECLARE_DEFINE_NETWORK_OBJECT_SIMPLE(Messages) + static NetworkMessageFormat &CreateFormat + ( + NetworkMessageClass cls, + NetworkMessageFormat &format + ); + TMError TransferMsg(NetworkMessageContext &ctx); +}; + +//! Encapsulates info needed for messages sent directly (inside process) instead through DirectPlay +struct NetworkLocalMessageInfo +{ + //! DirectPlay ID of sender + int from; + //! message type + NetworkMessageType type; + //! message itself + Ref msg; +}; +TypeIsMovableZeroed(NetworkLocalMessageInfo) + +/////////////////////////////////////////////////////////////////////////////// +// Network Components + +class NetworkManager; + +//! Info about file currently receiving +struct ReceivingFile +{ + //! name of receiving file + RString fileName; + //! info about which segments already received + AutoArray fileSegments; + //! content of receiving file + AutoArray fileData; + //! total amount of bytes already received (used for statistics) + int received; +}; +TypeIsMovable(ReceivingFile) + +#if _ENABLE_CHEATS +//! Statistic info about messages of given type +/*! +\patch_internal 1.08 Date 07/26/2001 by Jirka +- Improved: network diagnostics +*/ +struct NetworkStatisticsItem +{ + //! message type + int message; + //! count of sent messages (by priority) + int msgSentHighPriority; + int msgSentGuaranteed; + int msgSentOthers; + //! size of sent messages + int sizeSent; + //! count of received messages + int msgReceived; + //! size of received messages + int sizeReceived; + + //! Constructor + NetworkStatisticsItem() + { + message = 0; + msgSentHighPriority = 0; + msgSentGuaranteed = 0; + msgSentOthers = 0; + sizeSent = 0; + msgReceived = 0; + sizeReceived = 0; + }; +}; +TypeIsMovableZeroed(NetworkStatisticsItem) +#endif + +#if _ENABLE_CHEATS || _ENABLE_DEDICATED_SERVER +//! Statistic info about messages physically send / received by players +struct NetworkRawStatisticsItem +{ + //! player ID + int player; + //! count of sent messages + int msgSent; + //! size of sent messages + int sizeSent; + //! count of received messages + int msgReceived; + //! size of received messages + int sizeReceived; + + //! Constructor + NetworkRawStatisticsItem() + { + player = 0; + msgSent = 0; + sizeSent = 0; + msgReceived = 0; + sizeReceived = 0; + }; +}; +TypeIsMovableZeroed(NetworkRawStatisticsItem) + + +/// draw fps history +template +class PerformanceGraph: public IDiagGraph +{ + public: + struct Values + { + float values[sets]; + }; + + private: + static const int maxSamples = 200; + Values value[maxSamples]; + float deltaT[maxSamples]; + + public: + + RString GetName() const {return "Bandwidth";} + PackedColor GetDataColor(int set) const + { + static const PackedColor colors[]= + { + PackedColor(0xffffffff), + PackedColor(0xffffff00), + PackedColor(0xff00ff00), + PackedColor(0xff0000ff), + PackedColor(0xffff0000), + PackedColor(0xffffff00), + }; + if (set>=lenof(colors)) return PackedWhite; + return colors[set]; + } + + PerformanceGraph() + { + for (int i=0; i +{ + DWORD _lastTime; + int _lastSize; + int _lastMsg; + + public: + NetStatsGraph(); + + void OnSimulate(int size, int msg); +}; + +#endif + +class NetworkClient; + +class RadioSubscriber +{ +public: + AutoArray frequencies; + int dpnid; + + RadioSubscriber() : dpnid(0) {} + RadioSubscriber(int dp) : dpnid(dp) {} + bool FrequenciesMatch(float f1, float f2) const; +}; + +TypeIsMovable(RadioSubscriber) + +class RadioSubscribers +{ +public: + AutoArray _subscribers; + + RadioSubscribers() {} + + void OnPlayerDisconnected(int dpnid); // clear given subscriber + void Clear() { _subscribers.Clear(); } + void AddUnique(int dpnid, AutoArray &frequences); +}; + +//! Basic network component (client or server) +class NetworkComponent : public INetworkComponent +{ +protected: + //! creating network manager object + NetworkManager *_parent; // _parent must be valid + //! id of next created network object in this component + int _nextId; + + //! info about logged players + AutoArray _identities; + + //! info about current mission + MissionHeader _missionHeader; + //! parameter of current mission + float _param1; + //! parameter of current mission + float _param2; + //! array of parameters of current mission + AutoArray _paramsArray; + + //! messages received local (inside process) + AutoArray _receivedLocalMessages; + + //! files currently receiving + AutoArray _files; + +#if _ENABLE_CHEATS + //! Statistics about messages by types + AutoArray _statistics; +#endif + +#if _ENABLE_DEDICATED_SERVER || _ENABLE_CHEATS + //! Statistics about messages by players + AutoArray _rawStatistics; + RefArray _rawStatisticsGraph; +#endif + + //! list of accepted keys for data signatures + AutoArray _acceptedKeys; + //! the least signature version the server accepts + int _sigVerRequired; + + /// choose implementation: with guaranteed updates we can make interesting optimizations (delta transfer) + bool _updatesGuaranteed; + + static const int MaxVerifySignatures = 2; + + //! list of files (except banks), where signature will be checked + AutoArray _additionalSignedFiles; + + //! map players to their subscribed radio frequencies + RadioSubscribers _radioSubscribers; + +public: + //! Constructor + /*! + \param parent creating network manager object + */ + NetworkComponent(NetworkManager *parent); + //! Destructor + ~NetworkComponent(); + + //! Add message to local received messages + /*! + \param from DirectPlay ID of sender + \param type message type + \param msg message itself + */ + void AddLocalMessage(int from, NetworkMessageType type, NetworkMessage *msg); + + //! Implementation of direct message send through DirectPlay + /*! + \param to DirectPlay ID of message receiver + \param rawMsg message content + \param msgID out parameter to store DirectPlay ID of message + \param dwFlags DirectPlay flags + */ + virtual Ref DXSendMsg(int to, NetworkMessageRaw &rawMsg, DWORD &msgID, NetMsgFlags dwFlags, const Ref &dependOn) = 0; + + //! Draw any UI indications you need + virtual void OnDraw() = 0; + //! Process (user) message + /*! + \param from DirectPlay ID of sender + \param msg message itself + \param type message type + */ + virtual void OnMessage(int from, NetworkMessage *msg, NetworkMessageType type) = 0; + + //! perform regular memory clean-up + virtual unsigned CleanUpMemory() = 0; + + //! Return if given client is local on server's computer + virtual bool IsLocalClient(int client) const {return false;} + + bool IsUpdatesGuaranteed() const {return _updatesGuaranteed;} + + //{ DEDICATED SERVER SUPPORT + #if _ENABLE_DEDICATED_SERVER + //! Called when message is received to calculate transfer rate on dedicated server + virtual void OnMonitorIn(int size) {} + #endif + //} + + //! Hi-level send of message + /*! + \param to DirectPlay ID of message receiver + \param object message object + \param dwFlags DirectPlay flags + */ + virtual DWORD SendMsg + ( + int to, + NetworkSimpleObject *object, /*int creator, int id,*/ + NetMsgFlags dwFlags + ); + + //! Send single network message + /*! + This function determine, whic type of send will be used - local send, agregation or send using DirectPlay + \param to DirectPlay ID of message receiver + \param msg message itself + \param type type of message + \param dwFlags DirectPlay flags + */ + virtual DWORD SendMsg + ( + int to, NetworkMessage *msg, + NetworkMessageType type, NetMsgFlags dwFlags + ) = 0; + + //! Return mission header + const MissionHeader *GetMissionHeader() const {return &_missionHeader;} + //! Return number of role slots for current mission + + //! Search for identity with given player id + const PlayerIdentity *FindIdentity(int dpnid) const; + //! Search for identity with given player id + PlayerIdentity *FindIdentity(int dpnid); + //! Search for identity with given user friendly player id + const PlayerIdentity *FindIdentityByPlayerId(int playerId) const; + //! Return array of identities + const AutoArray *GetIdentities() const {return &_identities;} + //! Retrieves parameters for current mission + void GetParams(float ¶m1, float ¶m2) const {param1 = _param1; param2 = _param2;} + //! Retrieves parameters for current mission + float GetParams(int index) const { + if(index<_paramsArray.Size()) return _paramsArray[index]; + return 0.0; + }; + + //! Retrieves parameters for current mission + AutoArray GetParamsArray() const{return _paramsArray;}; + + //! Return component type ("server" / "client") for debugging purposes + virtual const char *GetDebugName() const = 0; + + //! Decode (and process) message from raw data + /*! + \param from DirectPlay ID of sender + \param src source raw data + */ + void DecodeMessage(int from, NetworkMessageRaw &src); + //! Calculate size of message after serialization and compression + /*! + \param msg calculated message + \param type type of calculated message + */ + int CalculateMessageSize(NetworkMessage *msg, NetworkMessageType type); + + //! File transfer + /*! + Split file into segments and send segments using standard messages. + \param to DirectPlay ID of file receiver + \param dest filename on destination computer + \param source local filename + */ + void TransferFile(int to, RString dest, RString source); + /*! + Split file into segments and store them into msgList array + \param to DirectPlay ID of file receiver + \param dest filename on destination computer + \param source local filename + */ + void PrepareTransferFileMessages(AutoArray &msgList, RString dest, RString source); + //! Transfer player's face from server to client + /*! + \param to DirectPlay ID of face receiver + \param player player which face is transfered + */ + void TransferFace(int to, RString player); + //! Transfer player's custom radio messages from server to client + /*! + \param to DirectPlay ID of messages receiver + \param player player which messages are transfered + */ + void TransferCustomRadio(int to, RString player); + +#if _ENABLE_CHEATS + //! Write into statistics info about sent message + /*! + \param msg message type + \param size size of sent message + */ + void StatMsgSent(int msg, int size, NetMsgFlags flags); + //! Write into statistics info about received message + /*! + \param msg message type + \param size size of received message + */ + void StatMsgReceived(int msg, int size); + //! Return statistics about messages by types + AutoArray &GetStatistics() {return _statistics;} +#endif + +#if _ENABLE_DEDICATED_SERVER || _ENABLE_CHEATS + //! Write raw statistics info about sent message + /*! + \param msg message type + \param to player + */ + void StatRawMsgSent(int to, int size); + //! Write raw statistics info about received message + /*! + \param msg message type + \param from player + */ + void StatRawMsgReceived(int from, int size); +#endif + + int GetMaxMissionPlayers() const {return _missionHeader._maxPlayers; } + +protected: + //! Encode message into raw data + /*! + \param dst destination data + \param msg source message + \param format format of source message + \param type type of destination message + */ + void EncodeMsg(NetworkMessageRaw &dst, NetworkMessage *msg, NetworkMessageFormatBase *format, NetworkMessageType type); + //! Encode single message item into raw data + /*! + \param dst destination data + \param msg source message + \param ptr pointer to item to encode + \param item format of source message item + */ + void EncodeMsgItem(NetworkMessageRaw &dst, NetworkMessage *msg, void *ptr, NetworkMessageFormatItem &item); + //! Initialize message before decoding + /*! + \param msg destination message + \param type type of destination message + */ + virtual void InitMsg(NetworkMessage *msg, NetworkMessageType type) {} + //! Decode message from raw data + /*! + \param msg destination message + \param src source data + \param format format of destination message + \param type type of destination message + */ + bool DecodeMsg(NetworkMessage *msg, NetworkMessageRaw &src, NetworkMessageFormatBase *format, NetworkMessageType type); + //! Decode single message item from raw data + /*! + \param src source data + \param msg destination message + \param ptr pointer to item to decode + \param item format of source message item + */ + bool DecodeMsgItem(NetworkMessageRaw &src, NetworkMessage *msg, void *ptr, NetworkMessageFormatItem &item); + //! Create copy of message + /*! + \param src source message + \param format format of source message + */ + void CopyMsg(NetworkMessage *dst, const NetworkMessage *src, const NetworkMessageFormatBase *format) const; + //! Calculate size of message after serialization and compression + /*! + \param msg calculated message + \param format format of calculated message + \param type type of calculated message + */ + int CalculateMsgSize(NetworkMessage *msg, NetworkMessageFormatBase *format, NetworkMessageType type); + //! Calculate size of single message item after serialization and compression + /*! + \param msg calculated message + \param ptr calculated message item + \param item format of calculated message item + */ + int CalculateMsgItemSize(void *ptr, const NetworkMessageFormatItem &item); + + //! Process all received messages (local, system and user) + void ReceiveLocalMessages(); + + + //! Send single network message using DirectPlay + /*! + \param to DirectPlay ID of message receiver + \param msg message itself + \param type type of message + \param dwFlags DirectPlay flags + */ + int SendMsgRemote + ( + int to, NetworkMessage *msg, + NetworkMessageType type, NetMsgFlags dwFlags, + RefR *resultMsg, + const RefR &dependOn + ); + //! Send (part of) message queue as single DirectPlay message + /*! + \param to DirectPlay ID of message receiver + \param queue messages to agregate + \param begin index of first message to send + \param end index of first message not to send + \param dwFlags DirectPlay flags + */ + int SendMsgQueue + ( + int to, NetworkMessageQueue &queue, + int begin, int end, NetMsgFlags dwFlags + ); + //! Lo-level data send using DirectPlay + /*! + \param to DirectPlay ID of message receiver + \param rawMsg data to send + \param dwFlags DirectPlay flags + \param diagLevel level of diagnostics about message + */ + DWORD SendMsgRaw(int to, NetworkMessageRaw &rawMsg, NetMsgFlags dwFlags, int diagLevel, RefR *resultMsg, const Ref &dependOn); + + + //! Called when file segment is received + /*! + \param msg segment of file + \return 1 if whole file is received (and saved) + \return -1 if whole file is received, but with errors (save failed) + */ + int ReceiveFileSegment(TransferFileMessage &msg); + + //! verify the real file format matches the extension + bool ValidDataFile(const char *fileName); + +}; + +//! Info about single type of update of network object +struct NetworkUpdateInfo +{ + //! last sent update message + Ref lastSentMsg; + //! cached value of error + float errorStatic; + //! cached value is valid + bool errorValid; + + //! bot-client rejected state received from owner + bool rejected; + + NetworkUpdateInfo() + { + // avoid floating point exceptions + errorStatic = 0; + errorValid = false; + rejected = false; + } + + bool CheckReject(NetworkClient *client, NetworkMessageClass cls, NetworkObject *obj); + +}; + +//! Info about local object on client +struct NetworkLocalObjectInfo //: public RefCount +{ + //! ID of object + NetworkId id; + //! object itself + OLinkNO(NetworkObject) object; + //! state of outgoing updates + NetworkUpdateInfo updates[NMCUpdateN]; +}; +TypeContainsOLink(NetworkLocalObjectInfo) +//TypeIsGeneric(NetworkLocalObjectInfo) + +//! Info about remote object on client +struct NetworkRemoteObjectInfo +{ + //! ID of object + NetworkId id; + //! object itself + OLinkNO(NetworkObject) object; + //! state of incoming updates + Ref updates[NMCUpdateN]; + //! all objects are tracked here, but only some are really remote + bool remote; +}; +TypeContainsOLink(NetworkRemoteObjectInfo) + +/// info about an object which was already deleted on the server +struct NetworkDeletedObjectInfo +{ + NetworkId id; + /// time of deletion + Time time; + /// owner of the object at the time of deletion + int owner; +}; + +TypeIsMovableZeroed(NetworkDeletedObjectInfo); + + +//! map sounds transferred over network to their unique ids +struct PlaySoundInfo +{ + //! unique id of sound + CreatorId creator; + int id; + //! sound itself + Link wave; +}; +TypeIsGeneric(PlaySoundInfo) + +//! Class used for transfer of client info (for example camera position) to server +/*! +\patch_internal 1.27 Date 10/11/2001 by Jirka +- Improved: camera position transfer in multiplayer game +*/ +class ClientInfoObject : public NetworkObject +{ +protected: + NetworkId _id; + +public: + Vector3 _cameraPosition; + int _dpnid; // Direct play id (necessary for hearing of VoN Direct Speech for dead players) + +#if _VBS3 + Vector3 _cameraDirection; + float _cameraFov; +#endif + +public: + // Constructor + ClientInfoObject() + { + _cameraPosition = InvalidCamPos; +#if _VBS3 + _cameraDirection = VForwardP; + _cameraFov = 0.75; +#endif + } + + void SetNetworkId(NetworkId &id) {_id = id;} + NetworkId GetNetworkId() const {return _id;} + Vector3 GetCurrentPosition() const {return VZero;} + bool IsLocal() const {return true;} + void SetLocal(bool local = true) {} + void DestroyObject() {} + + DECLARE_NETWORK_OBJECT + static NetworkMessageFormat &CreateFormat + ( + NetworkMessageClass cls, + NetworkMessageFormat &format + ); + TMError TransferMsg(NetworkMessageContext &ctx); + float CalculateError(NetworkMessageContextWithError &ctx); + virtual float CalculateErrorCoef(Vector3Par position, Vector3Par cameraPosition, float updateDistance, bool updating) const override {return 1.0;} + RString GetDebugName() const; +}; + +#if !_VBS3 +#define UPDATE_CLIENT_INFO_MSG(MessageName, XX) \ + XX(MessageName, Vector3, cameraPosition, NDTVector, Vector3, NCTVectorPositionCamera, DEFVALUE(Vector3, InvalidCamPos), DOC_MSG("Position of camera on client"), TRANSF, ET_ABS_DIF, 1) + +DECLARE_NET_INDICES_EX_ERR(UpdateClientInfo, NetworkObject, UPDATE_CLIENT_INFO_MSG) +#endif + +#define UPDATE_CLIENT_INFO_DPID_MSG(MessageName, XX) \ + XX(MessageName, Vector3, cameraPosition, NDTVector, Vector3, NCTVectorPositionCamera, DEFVALUE(Vector3, InvalidCamPos), DOC_MSG("Position of camera on client"), TRANSF, ET_ABS_DIF, 1) \ + XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Direct play id of dead player."), TRANSF, ET_NOT_EQUAL, 0) + +DECLARE_NET_INDICES_EX_ERR(UpdateClientInfoDpid, NetworkObject, UPDATE_CLIENT_INFO_DPID_MSG) + +#define UPDATE_ACTION_SUBSCRIPTION_MSG(MessageName, XX) \ + XX(MessageName, UserAction, action, NDTInteger, UserAction, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("action"), TRANSF) \ + XX(MessageName, bool, checkFocus, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("checkFocus"), TRANSF) \ + XX(MessageName, float, digitalValue, NDTFloat, float, NCTFloatMostly0To1, DEFVALUE(float, 0), DOC_MSG(""), TRANSF) \ + XX(MessageName, unsigned char, level, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 1), DOC_MSG("level"), TRANSF) \ + +DECLARE_SIMPLE_NETWORK_STRUCTURE(ActionSubscription,UPDATE_ACTION_SUBSCRIPTION_MSG) + +TypeIsSimple(ActionSubscription) + +#define UPDATE_ACTIONTODO_SUBSCRIPTION_MSG(MessageName, XX) \ + XX(MessageName, UserAction, action, NDTInteger, UserAction, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("action"), TRANSF) \ + XX(MessageName, bool, reset, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("reset"), TRANSF) \ + XX(MessageName, bool, checkFocus, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("checkFocus"), TRANSF) \ + XX(MessageName, bool, exclusive, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("exclusive"), TRANSF) \ + XX(MessageName, unsigned char, level, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 1), DOC_MSG("level"), TRANSF) \ + XX(MessageName, bool, blockButtons, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("blockButtons"), TRANSF) \ + +DECLARE_SIMPLE_NETWORK_STRUCTURE(ActionToDoSubscription,UPDATE_ACTIONTODO_SUBSCRIPTION_MSG) + +TypeIsSimple(ActionToDoSubscription) + +#define UPDATE_ACTIONDO_SUBSCRIPTION_MSG(MessageName, XX) \ + XX(MessageName, UserAction, action, NDTInteger, UserAction, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("action"), TRANSF) \ + XX(MessageName, bool, checkFocus, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("checkFocus"), TRANSF) \ + +DECLARE_SIMPLE_NETWORK_STRUCTURE(ActionDoSubscription,UPDATE_ACTIONDO_SUBSCRIPTION_MSG) + +TypeIsSimple(ActionDoSubscription) + +#define UPDATE_ITEM_SHORTCUT_MSG(MessageName, XX) \ + XX(MessageName, RString, itemType, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG(""), TRANSF)\ + +DECLARE_SIMPLE_NETWORK_STRUCTURE(ItemShortcut,UPDATE_ITEM_SHORTCUT_MSG) + +TypeIsMovableZeroed(ItemShortcut) + +#define UPDATE_ACTIONWITHCURVE_SUBSCRIPTION_MSG(MessageName, XX) \ + XX(MessageName, InputInterface::CurveFactor, factorKind, NDTInteger, InputInterface::CurveFactor, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ + XX(MessageName, UserAction, posAction, NDTInteger, UserAction, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ + XX(MessageName, UserAction, negAction, NDTInteger, UserAction, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG(""), TRANSF) \ + XX(MessageName, bool, checkFocus, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG(""), TRANSF) \ + XX(MessageName, bool, exclusive, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG(""), TRANSF) \ + +DECLARE_SIMPLE_NETWORK_STRUCTURE(ActionWithCurveSubscription,UPDATE_ACTIONWITHCURVE_SUBSCRIPTION_MSG) + +TypeIsSimple(ActionWithCurveSubscription) + +#define UPDATE_CLIENT_INPUT_ACTIONS(MessageName, XX) \ + XX(MessageName, AutoArray, actionState, NDTFloatArray, AutoArray, NCTFloat0To1, DEFVALUEFLOATARRAY, DOC_MSG("Input state"), TRANSF) \ + XX(MessageName, AutoArray, actionToDoState, NDTBoolArray, AutoArray, NCTNone, DEFVALUEBOOLARRAY, DOC_MSG("Input state"), TRANSF) \ + XX(MessageName, AutoArray, actionDoState, NDTBoolArray, AutoArray, NCTNone, DEFVALUEBOOLARRAY, DOC_MSG("Input state"), TRANSF) \ + XX(MessageName, AutoArray, actionWithCurveState, NDTFloatArray, AutoArray, NCTFloatMostly0To1, DEFVALUEFLOATARRAY, DOC_MSG("Input state"), TRANSF) \ + +#define UPDATE_CLIENT_INPUT_MSG(MessageName, XX) \ + UPDATE_CLIENT_INPUT_ACTIONS(MessageName, XX) \ + XX(MessageName, NetworkId, cursorObject, NDTRef, NetworkId, NCTNone, DEFVALUENULL, DOC_MSG("Object under cursor"), TRANSF) \ + XX(MessageName, RString, cursorSurface, NDTString, RString, NCTNone, DEFVALUE(RString, ""),DOC_MSG("Surface under cursor"), TRANSF) \ + +DECLARE_NET_INDICES(UpdateClientInput, UPDATE_CLIENT_INPUT_MSG) + + +#define UPDATE_CLIENT_OUTPUT_MSG(MessageName, XX) \ + XX(MessageName, FindArrayKey, subscribed, NDTObjectArray, REF_MSG_ARRAY(NetworkMessageUpdateActionSubscription), NCTNone, DEFVALUE_MSG(NMTUpdateActionSubscription), DOC_MSG("Output state"), TRANSF_ARRAY) \ + XX(MessageName, FindArrayKey, subscribedToDo, NDTObjectArray, REF_MSG_ARRAY(NetworkMessageUpdateActionToDoSubscription), NCTNone, DEFVALUE_MSG(NMTUpdateActionToDoSubscription), DOC_MSG("Output state"), TRANSF_ARRAY) \ + XX(MessageName, FindArrayKey, subscribedDo, NDTObjectArray, REF_MSG_ARRAY(NetworkMessageUpdateActionDoSubscription), NCTNone, DEFVALUE_MSG(NMTUpdateActionDoSubscription), DOC_MSG("Output state"), TRANSF_ARRAY) \ + XX(MessageName, FindArrayKey, subscribedWithCurve, NDTObjectArray, REF_MSG_ARRAY(NetworkMessageUpdateActionDoSubscription), NCTNone, DEFVALUE_MSG(NMTUpdateActionWithCurveSubscription), DOC_MSG("Output state"), TRANSF_ARRAY) \ + XX(MessageName, AutoArray, shortcuts, NDTObjectArray, REF_MSG_ARRAY(NetworkMessageUpdateItemShortcut), NCTNone, DEFVALUE_MSG(NMTUpdateItemShortcut), DOC_MSG("Output state"), TRANSF_ARRAY) \ + XX(MessageName, AutoArray, myActions, NDTObjectArray, REF_MSG_ARRAY(NetworkMessageUpdateUIAction), NCTNone, DEFVALUE_MSG(NMTUpdateUIAction), DOC_MSG("Output state"), TRANSF_ARRAY) \ + XX(MessageName, AutoArray, targetActions, NDTObjectArray, REF_MSG_ARRAY(NetworkMessageUpdateUIAction), NCTNone, DEFVALUE_MSG(NMTUpdateUIAction), DOC_MSG("Output state"), TRANSF_ARRAY) \ + +DECLARE_NET_INDICES(UpdateClientOutput, UPDATE_CLIENT_OUTPUT_MSG) + + +// def. message +#define MEMBER_MUTABLE_DEF(MessageName,type,name,datatype,rawType, compres, defval, description, xfer) \ + mutable type _##name; + +// def. message +#define MEMBER_DEF(MessageName,type,name,datatype,rawType, compres, defval, description, xfer) \ + type _##name; + +/// transfer output state from server to client +/** included input settings as well */ +class ClientOutput: public NetworkSimpleObject +{ +public: + UPDATE_CLIENT_OUTPUT_MSG(dummy, MEMBER_DEF) + +public: + ClientOutput(); + + DECLARE_DEFINE_NETWORK_OBJECT_SIMPLE(UpdateClientOutput) + + static NetworkMessageFormat &CreateFormat(NetworkMessageClass cls, NetworkMessageFormat &format); + TMError TransferMsg(NetworkMessageContext &ctx) override; + void OnSent(); + void OnBeforeSend(const NetworkPlayerInfo &info); + + bool Compare(const ClientOutput *with) const; +}; + + +#define MEMBER_USED_MUTABLE_DEF(MessageName,type,name,datatype,rawType, compres, defval, description, xfer) \ + mutable AutoArray _##name##Used; + +/// transfer input state from client to server +class ClientInputState +{ + protected: + UPDATE_CLIENT_INPUT_MSG(dummy, MEMBER_MUTABLE_DEF) + + public: + bool Compare(const ClientInputState *with) const; + const NetworkId &GetCursorObject() const {return _cursorObject;} + const RString &GetCursorSurface() const {return _cursorSurface;} +}; + +class ClientInput: public NetworkSimpleObject, public InputInterface, public ClientInputState, private NoCopy +{ +protected: + bool _local; + + UPDATE_CLIENT_INPUT_ACTIONS(dummy, MEMBER_USED_MUTABLE_DEF) + +public: + // TODO: merge objects instead + SRef _output; + /// last state of the output sent out + SRef _outputLast; + +public: + ClientInput(bool local); + + // Only ClientInputState is transferred, but it is not NetworkSimpleObject (we want to keep it small) + DECLARE_DEFINE_NETWORK_OBJECT_SIMPLE(UpdateClientInput) + static NetworkMessageFormat &CreateFormat(NetworkMessageClass cls, NetworkMessageFormat &format); + TMError TransferMsg(NetworkMessageContext &ctx) override; + + virtual float GetAction(UserAction action, bool checkFocus = true, float digitalValue=1.0f, unsigned char level = 1) const override; + virtual bool GetActionToDo(UserAction action, bool reset = true, bool checkFocus = true, bool exclusive = false, unsigned char level = 1, bool blockButtons = false) override; + virtual bool GetActionDo(UserAction action, bool checkFocus=true) override; + virtual float GetActionWithCurve(CurveFactor factorKind, UserAction posAction, UserAction negAction, bool checkFocus = true, bool exclusive = false) const override; +}; + +class ClientInputLocal: public ClientInput +{ + + public: + + ClientInputLocal():ClientInput(true){} + + void ScanInput(); + void OnOutputReceived(const ClientOutput &output); +}; + +struct UpdateLocalObjectInfo; + +struct BodyInfo +{ + OLinkPermO(Person) body; + Time hideTime; + float value; +}; +TypeContainsOLink(BodyInfo) + +struct WreckInfo +{ + OLinkPermO(Transport) wreck; + Time hideTime; +}; +TypeContainsOLink(WreckInfo) + +class NetworkServer; +void DiagLogF(const char *format, ...); + +/// store event handler executed in reaction to PublicVariableMessage +struct PublicVariableEventHandler +{ + RString _name; +#if USE_PRECOMPILATION + Ref _code; +#else + RString _code; +#endif + + const char *GetKey() const {return _name;} + LSError Serialize(ParamArchive &ar); +}; +TypeIsMovableZeroed(PublicVariableEventHandler); + +template <> +struct MapClassTraits : public MapClassTraitsNoCase +{ +}; + +/// set of all registered event handlers executed in reaction to PublicVariableMessage +typedef MapStringToClass< PublicVariableEventHandler, AutoArray > PublicVariableEventHandlers; + +//! Network Command Types +/*! +\patch_internal 1.11 Date 07/31/2001 by Jirka +- Added: processing of commands entered in chat line +*/ +enum NetworkCommandType +{ + CMDNone = -1, + CMDLogin, + CMDLogout, + CMDKick, + CMDRestart, + CMDMission, + CMDMissions, + CMDShutdown, + CMDReassign, + CMDMonitor, + CMDUserlist, + CMDVote, + CMDAdmin, + CMDInit, + CMDDebug, + CMDExec, + CMDLock, + CMDUnlock, + CMDBEServer, + CMDBEClient, + CMDProfile, +#if _ENABLE_CHEATS + CMDGameExec, +#endif +#if _VBS3 + ,CMDExitAll +#endif +}; + +struct CheckSignatureItem +{ + int _bankIndex; + int _sigVer; + int _level; + bool _initialTest; + //! network message type and the prepared message itself (NMTFileSignatureAnswer or NMTDataSignatureAnswer) + int _type; + NetworkSimpleObject *_msg; + CheckSignatureItem() : _msg(NULL) {} + ~CheckSignatureItem() + { + if(_msg!=NULL) + { + delete _msg; + _msg=NULL; + } + } +}; +TypeIsMovable(CheckSignatureItem) + +template <> +struct FindArrayKeyTraits +{ + typedef int KeyType; + static bool IsEqual(int a, int b) {return a == b;} + static int GetKey(const CheckSignatureItem &a) {return a._bankIndex;} +}; + +template <> +struct ImplicitMapTraits +{ + static NetworkLocalObjectInfo null; ///< Empty value (can be passed as return value). + static NetworkLocalObjectInfo zombie; ///< Removed value (internal usage only). + +}; + +static inline bool operator != (const NetworkLocalObjectInfo &a, const NetworkLocalObjectInfo &b) {return a.id!=b.id;} +static inline bool operator == (const NetworkLocalObjectInfo &a, const NetworkLocalObjectInfo &b) {return a.id==b.id;} + +template <> +struct ImplicitMapTraits +{ + static NetworkRemoteObjectInfo null; ///< Empty value (can be passed as return value). + static NetworkRemoteObjectInfo zombie; ///< Removed value (internal usage only). + +}; + +static inline bool operator != (const NetworkRemoteObjectInfo &a, const NetworkRemoteObjectInfo &b) {return a.id!=b.id;} +static inline bool operator == (const NetworkRemoteObjectInfo &a, const NetworkRemoteObjectInfo &b) {return a.id==b.id;} + + + + + + +template <> +struct ImplicitMapTraits +{ + static NetworkDeletedObjectInfo null; ///< Empty value (can be passed as return value). + static NetworkDeletedObjectInfo zombie; ///< Removed value (internal usage only). + +}; + +static inline bool operator != (const NetworkDeletedObjectInfo &a, const NetworkDeletedObjectInfo &b) {return a.id!=b.id;} +static inline bool operator == (const NetworkDeletedObjectInfo &a, const NetworkDeletedObjectInfo &b) {return a.id==b.id;} + + + + +struct DelayedPublicVariable +{ + RString _name; + int _player; +}; +TypeIsMovableZeroed(DelayedPublicVariable) + +//! SpawnForPlayer code queued until the mission init script has run +struct DelayedSpawnForPlayer +{ + RString _code; + GameValue _args; +}; +TypeIsMovableZeroed(DelayedSpawnForPlayer) + +//! Network Client +class NetworkClient : public NetworkComponent +{ +protected: + //! DirectPlay ID of attached player + int _playerDpid; + + //! low-level client implementation + SRef _client; + +#if _USE_BATTL_EYE_CLIENT + /// BE Integration + class BattlEye + { + protected: + /// dll handle + HMODULE _library; + bool _initialized; + /// remember the scripts which were already checked and do not send them again + + static intptr_t KeyFromString(const RString &src) {return intptr_t(cc_cast(src));} + + ImplicitMap _checked; + AutoArray _checkedFIFO; + //@{ + /// callback functions + typedef void __cdecl PrintMessageF(const char *message); + static void __cdecl PrintMessage(const char *message); + //@} + + //@{ + /// dll functions + typedef bool __cdecl ExitF(); + typedef bool __cdecl RunF(); + typedef void __cdecl CommandF(const char *command); + + struct GameParams + { + unsigned long _address; + unsigned short _port; + PrintMessageF *_printMessage; + }; + GameParams _gameParams; + + struct BEPtrStruct + { + ExitF *_exit; + RunF *_run; + CommandF * _command; + CommandF * _onScriptExec; + }; + BEPtrStruct _callbacks; + + typedef bool __cdecl InitF(int iIntegrationVersion, GameParams *ppvGamePtrTable, BEPtrStruct *ppvBEPtrTable); + typedef int __cdecl GetVerF(); + //@} + + public: + BattlEye(); + ~BattlEye(); + + bool Init(NetworkClient *client); + void Done(); + bool Run(NetworkClient *client); + void Command(const char *command); + bool OnScriptExec(RString script); + + protected: + void CleanUp() + { + _library = NULL; + _callbacks._exit = NULL; + _callbacks._run = NULL; + _callbacks._command = NULL; + _callbacks._onScriptExec = NULL; + } + int GetBEVersion(HMODULE library) const; + }; + + BattlEye _beIntegration; + bool _beWanted; + +public: + bool BattlEyeOnScriptExec(RString script) + { + return _beIntegration.OnScriptExec(script); + } +protected: +#endif + + static NetworkId GetIdFromLocalNetworkObjectInfo(const NetworkLocalObjectInfo &info) {return info.id;} + static NetworkId GetIdFromRemoteNetworkObjectInfo(const NetworkRemoteObjectInfo &info) {return info.id;} + + typedef ImplicitMap LocalObjectsContainer; + typedef ImplicitMap RemoteObjectsContainer; + + + //! info about objects local on client + LocalObjectsContainer _localObjects; + //! info about objects non local (remote) on client + RemoteObjectsContainer _remoteObjects; + //! dead bodies (max MAX_LOCAL_BODIES can be simulated) + AutoArray _bodies; + //! wrecks (max MAX_LOCAL_WRECKS can be simulated) + AutoArray _wrecks; + + /// mark if team switch request is in progress + DWORD _teamSwitchDisabledUntil; + + //! message formats + AutoArray _formats; + //! message queues (candidates for aggregation) + NetworkMessageQueue _messageQueue, _messageQueueNonGuaranteed; + + //! connection quality to server + ConnectionQuality _connectionQuality; + /// de-sync detected by server + ConnectionDesync _connectionDesync; + //! result of _dp->Connect + ConnectResult _connectResult; + + //! current state + NetworkClientState _clientState; + //! current state on server + NetworkServerState _serverState; + + /// information about last know mission voting results + VotingMissionProgressMessage _missionVoting; + + /// last custom files progress state sent by NCMTCustomFilesProgress + int _customFilesProgressMax; + int _customFilesProgressPos; + + /// last timeout value received from the server, INT_MAX if none + int _serverTimeout; + + /// server hostname + RString _serverName; + + //! mission pbo file is valid (actual) + bool _missionFileValid; + + //! player is game master of dedicated server + bool _gameMaster; + //! gamemaster is only voted admin (cannot do shutdown etc.) + bool _admin; + //! show "select mission" dialog for dedicated server + bool _selectMission; + //! show "vote mission" dialog for dedicated server + bool _voteMission; + + //! Game is paused due to disconnection state of game + bool _controlsPaused; + + //! missions on dedicated server + AutoArray _serverMissions; + + //! name of local player + RString _localPlayerName; + + int _playerID; //player identity number + //! short id of player, used as creator in NetworkId + CreatorId _creatorId; + + //! id of next sound - incremented for each PlaySound + int _soundId; + //! list of sent sounds + AutoArray _sentSounds; + //! list of received sounds + AutoArray _receivedSounds; + + //! sound introducing chat message + SoundPars _chatSound; + + //! selected channel for voice chat + int _voiceChannel; + + //! ip address of dedicated server + sockaddr_in _serverVoNAddr; + + //! is NAT negotiation is needed to access server? + bool _natNegotiationNeeded; + + //! password used to connect to server + RString _serverPassword; + + //! used for transfer of client info (for example camera position) to server + Ref _clientInfo; + + SRef _clientInput; + SRef _clientInputLast; + + //! used for make the client camera position synchronized on all clients + Ref _clientCameraPosition; + + //! number of bodies we want to hide + int _hideBodies; + + //! number of wrecks we want to hide + int _hideWrecks; + +#if _VBS3 // player color + bool _sentPlayerColour; +#endif + +#if _ENABLE_CHEATS + //! debugging window + Link _debugWindow; +#endif + +#if _ENABLE_MP + /// who muted me + RemoteMuteListMessage _remoteMuteList; +#endif + +#if _ENABLE_GAMESPY + /// IP Address of the client (how is seen from matchmaking server) + int _publicAddr; +#endif + + /// world transfer progress info + int _totalToCreate; + int _remainingToCreate; + int _totalToUpdate; + int _remainingToUpdate; + + /// event handlers executed in reaction to PublicVariableMessage + PublicVariableEventHandlers _publicVariableEventHandlers; + + /// public variables which have Null networkId during PublicVariable are stored to be proccessed later again + AutoArray _delayedPublicVariables; + + //! true once the mission init script has run and spawned code may execute + bool _initScriptRun; + //! SpawnForPlayer code received before the mission init script ran + AutoArray _delayedSpawns; + + //! time synchronized from server to clients + DWORD _serverTime; + DWORD _serverTimeInitTickCount; + DWORD _serverTimeOfEstimatedEnd; + + //! server admin and gameMaster variables got by ServerAdminMessage + // used to know whether some commands like #vote is available + bool _serverAdmin; + int _serverGameMaster; + +#if _ENABLE_STEAM_MATCHMAKING + HAuthTicket _hAuthTicket; +#endif + +public: + + //! Constructor + /*! + \param parent creating network manager object + \param address URL address of server + \param password password of session + \param botClient client is bot client + */ + NetworkClient(NetworkManager *parent, RString address, RString password); + //! Connect to server + /*! + \param addr host Xbox Title Address + \param address URL address of server + \param password password of session + \return true if client is connected to server + */ + bool Init(RString address, RString password); + + //! Constructor for bot client + /*! + \param parent creating network manager object + \param playerRating rating of player in statistics + */ + NetworkClient(NetworkManager *parent, NetworkServer *server, int playerRating); + //! Connect bot client to server + bool Init(NetworkServer *server); + + //! Return dpid of attached player + int GetPlayer() const {return _playerDpid;} + +#if _ENABLE_GAMESPY + /// Set on which IP Address the client is visible from the matchmaking server + void SetPublicAddress(int addr) {_publicAddr = addr;} +#endif + + /// retrieve the local address client communicate on + bool GetLocalAddress(in_addr &addr) const {return _client ? _client->GetLocalAddress(addr) : false;} + bool GetDistantAddress(in_addr &addr, int &port) const {return _client ? _client->GetDistantAddress(addr,port) : false;} + /// retrieve the port client is listening for voice peer-to-peer communication + int GetVoicePort() const {return _client ? _client->GetVoicePort() : 0;} + + //! Voice over net initialization + void InitVoice(bool isBotClient=false); + //! Connect voice over net to the given player + void ConnectVoice(int player, sockaddr_in &addr); + + /// Suspend voice playback temporarily + void DisableVoice(bool disable); + /// Switches on/off the voice transmition + void SetVoiceTransmition(bool val) + { + #if VOICE_OVER_NET + if (_client) _client->SetVoiceTransmition(val); + #endif + } + /// Sets if voice is toggled on (user is NOT using push to talk button) + virtual void SetVoiceToggleOn(bool val) + { +#if VOICE_OVER_NET + if (_client) _client->SetVoiceToggleOn(val); +#endif + } + /// sets threshold for silence analyzer (0.0f - 1.0f) + virtual void SetVoNRecThreshold(float val) + { +#if VOICE_OVER_NET + if (_client) _client->SetVoNRecThreshold(val); +#endif + } + virtual void SetVoNTransmitterFreq(float f) + { +#if VOICE_OVER_NET + if (_client) _client->SetVoNTransmitterFreq(f); +#endif + } + virtual float GetVoNTransmitterFreq() const + { +#if VOICE_OVER_NET + if (_client) return _client->GetVoNTransmitterFreq(); +#endif + return 0; + } + virtual void SetVoNTransmitterRange(float range) + { +#if VOICE_OVER_NET + if (_client) _client->SetVoNTransmitterRange(range); +#endif + } + virtual float GetVoNTransmitterRange2() const + { +#if VOICE_OVER_NET + if (_client) return _client->GetVoNTransmitterRange2(); +#endif + return 1000000.f; + } + virtual void WhatUnitsOnTransmitterChannel(RefArray &units); + + /// Switches on/off the voice capturing + virtual void SetVoiceCapture(bool val, int quality) + { +#if VOICE_OVER_NET + if (_client) _client->VoiceCapture(val,quality); +#endif + } + + void CustomFilesProgressGet(int &max, int &pos) + { + max = _customFilesProgressMax; pos = _customFilesProgressPos; + } + void CustomFilesProgressClear() + { + _customFilesProgressMax = 1; _customFilesProgressPos = 0; + } + + //! Destructor + ~NetworkClient(); + + //! Disconnect from server + void Done(); + + bool IsValid() const {return _client != NULL;} + + //! Given player is currently speaking + bool IsVoicePlaying(int dpnid) const {return _client ? _client->IsVoicePlaying(dpnid) : false;} + + //! Local player is currently speaking + bool IsVoiceRecording() const {return _client ? _client->IsVoiceRecording() : false;} + + int CheckVoiceChannel(int dpnid, bool &audible2D, bool &audible3D) const + { + if (_client) + { + return _client->CheckVoiceChannel(dpnid,audible2D,audible3D); + } + audible2D = audible3D = false; + return 0; + } + + void IsVoice2D3DPlaying(int dpnid, bool &audible2D, bool &audible3D) const + { + if (_client) + { + _client->IsVoice2D3DPlaying(dpnid,audible2D,audible3D); + } + else + { + audible2D = audible3D = false; + } + } + + void DebugServerExec(RString str); + +#if _ENABLE_CHEATS + void VoNSay(int dpnid, int channel, int frequency, int seconds) + { + if (_client) _client->VoNSay(dpnid, channel, frequency, seconds); + } +#endif + + //! Return connection type info for each player along with the GDebugVoNBank output + RString GetDebugVoNString(); + + //! Server time synchronized to clients + DWORD GetServerTime() + { + _serverTime = ::GetTickCount() - _serverTimeInitTickCount; //make it fresh + return _serverTime; + } + + DWORD GetEstimatedEndServerTime() + { + return _serverTimeOfEstimatedEnd; + } + + RString ServerName() const { return _serverName; } + + int ConsoleF(const char *format, ...); + + //! Create debugging window + void CreateDebugWindow(); + + //! Return name of local player + RString GetLocalPlayerName() const {return _localPlayerName;} + //! Return result of _dp->Connect + ConnectResult GetConnectResult() const {return _connectResult;} + + //! Return if player is game master of dedicated server + bool IsGameMaster() const {return _gameMaster;} + + //! Return if gamemaster is only voted admin (cannot do shutdown etc.) + bool IsAdmin() const {return _admin;} + + //! Return if client is bot client + inline bool IsBotClient() const; + + inline NetworkServer *GetServer() const; + + //! Return connection quality to server + ConnectionQuality GetConnectionQuality() const {return _connectionQuality;} + + //! Return connection quality to server + ConnectionDesync GetConnectionDesync() const {return _connectionDesync;} + + //! Return current state + NetworkClientState GetClientState() const {return _clientState;} + //! Set state and send notification to server + void SetClientState(NetworkClientState state); + + //! Return how much part of world state was already transferred to client + bool GetTransferProgress(float &progress) const; + + //! Handler called when client is joining game in progress + void OnJoiningInProgress(); + + //! Clear possible structures keeping something related to dpnid of disconnecting player (such as subscribed radios) + void OnPlayerLogout(int dpnid); + + //! Time elapsed from start of mission on server + int TimeElapsed() const; + + //! Return current state on server + NetworkServerState GetServerState() const {return _serverState;} + + int GetServerTimeout() const {return _serverTimeout;} + + //! Return recommended chat priorty based on current game state + NetMsgFlags GetChatPriority() const; + + //! Set parameters for current mission + void SetParams(float param1, float param2, bool updateOnly); + //! Set parameters for current mission + void SetParams(float param1, float param2, AutoArray paramsArray, bool updateOnly); + + InputInterface *GetInputInterface(); + + void OnSimulate(); + void OnSimulateDone(); + + /// time critical network update - need to be called several times in frame + void FastUpdate(); + void OnDraw(); + void OnMessage(int from, NetworkMessage *msg, NetworkMessageType type); + + //! perform regular memory clean-up + unsigned CleanUpMemory(); + + /// called before network shutdown is initiated - can be called multiple times + void OnClose(); + //! Process received system messages + void ReceiveSystemMessages(); + //! Process received user messages + void ReceiveUserMessages(); + //! Destroy all received system messages + void RemoveSystemMessages(); + //! Destroy all received user messages + void RemoveUserMessages(); + + + //! Hi-level send of message to server + /*! + \param object message object + \param dwFlags DirectPlay flags + */ + DWORD SendMsg + ( + NetworkSimpleObject *object, NetMsgFlags dwFlags + ); + + //! Send single network message + /*! + This function determine, whic type of send will be used - local send, agregation or send using DirectPlay + \param to DirectPlay ID of message receiver + \param msg message itself + \param type type of message + \param dwFlags DirectPlay flags + */ + DWORD SendMsg + ( + int to, NetworkMessage *msg, + NetworkMessageType type, NetMsgFlags dwFlags, + NetworkObject *object + ); + virtual DWORD SendMsg + ( + int to, NetworkMessage *msg, + NetworkMessageType type, NetMsgFlags dwFlags + ) + { + return SendMsg(to, msg, type, dwFlags, NULL); + } + + Ref DXSendMsg(int to, NetworkMessageRaw &rawMsg, DWORD &msgID, NetMsgFlags dwFlags, const Ref &dependOn); + NetworkMessageFormatBase *GetFormat(/*int client, */int type); + const NetworkMessageFormatBase *GetFormat(/*int client, */int type) const; + + virtual void InitMsg(NetworkMessage *msg, NetworkMessageType type); + + //! Return short id of player, used as creator in NetworkId +#define DEBUG_CREATOR_ID 0 +#if DEBUG_CREATOR_ID + mutable bool _debugCreatorIdSet; +#endif + CreatorId GetCreatorId() const + { +#if DEBUG_CREATOR_ID + if (!_debugCreatorIdSet && _playerDpid!=BOT_CLIENT) + { + RptF("Warning: GetCreatorId called before its change!"); + static bool doIt = false; + if (doIt) + { + _debugCreatorIdSet = true; + } + } +#endif + return _creatorId; + } + //! Set player id directly (used on dedicated server - BOT client has no identity) + void SetCreatorId(CreatorId id) {_creatorId = id;} + void SetPlayerId(int id) {_playerID = id;} + + //! Select person as player + /*! + \param player DirectX player id + \param person player's person + \param respawn play "ressurect" cutscene + */ + void SelectPlayer(int player, Person *person, bool respawn = false); + // Send NMTSelectPlayer message to server + void SendSelectPlayer(int dpid, Person *person); + //! Play sound on all clients (except itself) + /*! + \param name name of sound file + \param position source position + \param speed source speed + \param volume sound volume + \param freq sound frequency + \param wave local sound object (for mapping local sounds to sent sounds) + */ + void PlaySound + ( + RString name, Vector3Par position, Vector3Par speed, + float volume, float freq, AbstractWave *wave + ); + //! Change state of played sound on all clients (except itself) + /*! + \param wave local sound object + \param state state to set + */ + void SoundState(AbstractWave *wave, SoundStateType state); + //! Register vehicle on client and send message to server (and other clients) + /*! + \param veh registered vehicle + \param type id of vehicle list to add into + \param name name of variable vehicle is stored in + \param idVeh id of vehicle (assigned in mission editor) + */ + bool CreateVehicle(Vehicle *veh, VehicleListType type, RString name, int idVeh); + //! Register subobject of vehicle on client and send message to server (and other clients) + /*! + \param veh owner vehicle + \param index unique id of object in vehicle + \param object created object + */ + bool CreateSubobject(Vehicle *veh, TurretPath &path, NetworkObject *object, bool setNetworkId=true); + //! Register generic network object and send message to server (and other clients) + bool CreateObject(NetworkObject *object, bool setNetworkId=true); + + bool SendCreateMessage( NetworkObject * object ); + + //! Send first update of all created objects over network (as guaranteed message) + void CreateAllObjects(); + //! Unregister all objects, both local and remote + void DestroyAllObjects(); + //! Force switch on pilot light + void AskForPilotLight(EntityAI *vehicle, bool enable); + //! Vehicle door open/close + void AskForVehicleDoorState(Transport *vehicle, int doorIndex, bool opened); + + void CreateObjectStatic(Object *who); + + void ExplosionDamage( EntityAI * owner, Vector3Par originDir, Object * directHit, Vector3Par directHitModelPos, HitInfoPar hitInfo, Object * componentOwner, int componentIndex, float energyFactor, float explosionFactor, float hitDepth ); + + //! Ask vehicle owner for change ammo state + /*! + \param vehicle vehicle which ammo is changing + \param turret turret which ammo is changing + \param weapon weapon index + \param burst amount of ammo to decrease + */ + void AskForAmmo( + EntityAIFull *vehicle, Turret *turret, const WeaponModePtr &ptr, int burst + ); + + //! Ask object owner for move object + /*! + \param vehicle moving object + \param pos new position + */ + void AskForMove + ( + Object *vehicle, Vector3Par pos + ); + //! Ask object owner for move object + /*! + \param vehicle moving object + \param trans new transformation matrix + */ + void AskForMove + ( + Object *vehicle, Matrix4Par trans + ); + + //! Ask magazine owner for change its ammo count + /*! + \param magazine + \param ammo + */ + void AskForSetMagazineAmmo + ( + Object *magazine, int ammo + ); + //! Transfer explosion effects (explosion, smoke, etc.) to other clients + /*! + \param owner shot owner (who is responsible for explosion) + \param shot shot + \param directHit hitted object + \param pos explosion position + \param dir explosion direction + \param dir index of the hit component + \param type ammunition + \param enemyDamage some enemy was damaged + \param explosionFactor how large explosion is + */ + void ExplosionDamageEffects + ( + EntityAI *owner, Object *directHit, HitInfoPar hitInfo, int componentIndex, + bool enemyDamage, float energyFactor, float explosionFactor + ); + //! Transfer projectile decals (arrows stuck on body, etc.) to other clients + /*! + \param directHit Object that got hit + \param componentIndex Index of the component that got hit + \param hitInfo Info about the hit + \param hitDepth The depth of penetration + \param hitPosLcl Hit position on the body (local space) + \param hitDirLcl Hit direction relative to the body part (local space) + \param hitDirUpLcl Up direction of hit relative to the body part (local space) + */ + void ApplyProjectileDecal + ( + Object *directHit, int componentIndex, HitInfoPar hitInfo, float hitDepth, Vector3Par hitPosLcl, Vector3Par hitDirLcl, Vector3Par hitDirUpLcl + ); + //! Remove on other clients the projectile decals stuck on victim's body + /*! + \param person The person from which projectiles are removed + */ + void RemoveProjectileDecals(Object *person); + //! Transfer fire effects (sound, fire, smoke, recoil effect, etc.) to other clients + /*! + \param vehicle firing vehicle + \param weapon firing weapon index + \param magazine fired magazine + \param target aimed target + */ + void FireWeapon( + EntityAIFull *vehicle, Person *gunner, const WeaponModePtr &ptr, Magazine *magazine, EntityAI *target, + const RemoteFireWeaponInfo &remoteInfo + ); + //! Transfer bow action state to other clients + /*! + \param entity Person using the bow + \param state The state of bow + */ + void UpdateBowState(EntityAIFull *entity, BowState state ); + //! Set a texture for a vehicle on other clients + /*! + \param vehicle vehicle that will have a texture changed + \param index selection index to change + \param name texture name to use + */ + void SetObjectTexture(EntityAI *veh, int index, RString name, RString eval = "true"); + //! Execute game code on other clients + /*! + \param condition game code to evaluate to true or false + \param command game code to execute + \param obj object to pass as _this + \param objs array of objects to pass as _this + */ + void PublicExec(RString condition, RString command, Object* obj, OLinkArray(Object) &objs); + //! Transfer message who is responsible to destroy vehicle to other clients + /*! + \param killed destroyed vehicle + \param killer who is responsible for destroying + */ + void OnVehicleDestroyed(EntityAI *killed, EntityAI *killer); + //! Transfer message about damage of vehicle to other clients + /*! + \param damaged damaged vehicle + \param damage amount of damage hit + \param ammo ammunition type + */ + void OnVehicleDamaged(EntityAI *damaged, EntityAI *killer, float damage, RString ammo); + //! Transfer info about (user made) marker creation to other clients + /*! + \param channel chat channel (who will see the marker) + \param sender sender unit + \param units receiving units + \param info marker itself + */ + void MarkerCreate(int channel, AIBrain *sender, RefArray &units, ArcadeMarkerInfo &info); + //! Transfer info about (user made) marker was deleted to other clients + /*! + \param name name of marker + */ + void MarkerDelete(RString name); + + //! Public variable to other clients + /*! + \param name variable name + */ + void PublicVariable(RString name, int dpnid); + + void SendAUMessage(GameValuePar oper1); + + /** + Do ErrF locally and send the message to the server as well. + */ + void ServerErrF(const char *format, ...); + + //! Public variables which contains objects with NULL networkId are processed after CreateAllObjects again + void ProcessDelayedPublicVariables(); + void ClearDelayedPublicVariables(); + void AddDelayedPublicVariable(RString name, int dpnid); + + //! Run a SpawnForPlayer code on this client + void RunSpawnedCode(RString code, GameValuePar args); + //! Run all SpawnForPlayer code delayed until the mission init script ran + void ProcessDelayedSpawns(); + + //! Send chat message + /*! + \param channel chat channel + \param text chat text + */ + void Chat(int channel, RString text); + + //! Send chat message + /*! + \param channel chat channel + \param sender sender unit + \param units receiving units + \param text chat text + */ + void Chat(int channel, AIBrain *sender, RefArray &units, RString text); + //! Send chat message + /*! + \param channel chat channel + \param sender sender name + \param units receiving units + \param text chat text + */ + void Chat(int channel, RString sender, RefArray &units, RString text); + + /// Send client-side localized chat message + void LocalizedChat(int channel, const LocalizedFormatedString &text); + + /// Send client-side localized chat message + /*! + \param channel chat channel + \param sender sender unit + \param units receiving units + \param text chat text + */ + void LocalizedChat(int channel, AIBrain *sender, RefArray &units, const LocalizedFormatedString &text); + /// Send client-side localized chat message + /*! + \param channel chat channel + \param sender sender name + \param units receiving units + \param text chat text + */ + void LocalizedChat(int channel, RString sender, RefArray &units, const LocalizedFormatedString &text); + + //! Send radio message as chat (text and sentence) + /*! + \param channel chat channel + \param sender sender name + \param units receiving units + \param text chat text + \param sentence - list of words to be spoken + */ + void RadioChat(int channel, AIBrain *sender, RefArray &units, RString text, RadioSentence &sentence); + //! Send text radio message as chat (sound and title) + /*! + \param channel chat channel + \param units receiving units + \param wave name of class from CfgRadio containing sound and title + \param sender sender unit + \param senderName sender name + */ + void RadioChatWave(int channel, RefArray &units, RString wave, AIBrain *sender, RString senderName); + + /// Return actual channel for voice chat + int GetVoiceChannel() const {return _voiceChannel;} + //! Set channel for Voice Over Net + /*! + \param channel chat channel + */ + void SetVoiceChannel(int channel); + //! Set position and speed of some Voice Over Net source (it affects sources) + /*! + \param dpnid player id got from GetRemotePlayer() + \param pos position of player + \param speed speed of player + */ + void SetVoNPosition(int dpnid, Vector3Par pos, Vector3Par speed); + //! Set position and speed of player in Voice Over Net (it affects listener) + /*! + \param pos position of player + \param speed speed of player + */ + void SetVoNPlayerPosition(Vector3Par pos, Vector3Par speed); + //! Set obstruction of player in Voice Over Net (it affects source) + /*! + \param dpnid player id got from GetRemotePlayer() + */ + void SetVoNObstruction(int dpnid, float obstruction, float occlusion, float deltaT); + //! Updates volume and ear accomodation of player in Voice Over Net (it affects source) + /*! + \param dpnid player id got from GetRemotePlayer() + */ + void UpdateVoNVolumeAndAccomodation(int dpnid, float volume, float accomodation); + //! Advance all voices in VoN (even muted ones) + /*! + \param deltaT time to advance + \param paused whether game is paused + \param quiet whether voices should be muted + */ + void AdvanceAllVoNSounds( float deltaT, bool paused, bool quiet ); + + //! Send update of the content of the Custom Radio Channel + /*! + \param channel The channel in range CCCustom1..CCCustomLast + \param ucr_type What to update (all, label, callSign, units, ...) + */ + void UpdateCustomChannel(int channel, int ucr_type); + + //! Transfer file to server + /*! + \param dest destination filename + \param source source filename + */ + void TransferFileToServer(RString dest, RString source); + //! Retrieve state of file transfer + /*! + \param curBytes amount of transfered bytes + \param totBytes total amount bytes to transfer + */ + void GetTransferStats(int &curBytes, int &totBytes); + void ApplyWeather(); +#if _VBS2 //Convoy trainer + void AARDoUpdate(int type ,int intType,RString stringOne = RString(), RString stringTwo = RString(), float floatType = 0.0); + void AARAskUpdate(int type ,int intType,RString stringOne = RString(), RString stringTwo = RString(), float floatType = 0.0); + void AddMPReport(int type, RString myString); + void LoadIsland(RString islandName); + void AskWeather(); + void AskCommanderOverride(Turret *turret, Turret *overriddenByTurret); +#endif + //! Ask vehicle owner to destroy vehicle + /*! + \param vehicle vehicle to destroy + */ + void AskForDeleteVehicle(Entity *veh); + + void AskForSetItemShortcut(Person *person, int index, const InventoryItemType *type, InventoryItem *item); + void AskForThrowItem(Man *person, InventoryItem *item, Vector3 pos, Vector3 dir); + void AskForDropItem(Person *person, InventoryItem *item); + void AskForMoveItem(EntityAI *target, int index, InventoryItem *item, bool rotated); + void AskForRotateInventoryItem(Person *person, InventoryItem *item); + void AskForTakeItemToHands(Person *person, InventoryItem *item); + void AskForSwapItems(InventoryItem *item1, InventoryItem *item2, Person *owner); + + void AskForPlayerAction( Person * person, RString action ); + + void AskInventoryMenu(AIBrain *unit, InventoryItem *item1, InventoryItem *item2); + +#if _VBS3 // respawn command + //! Tell local simulation to pause itself + /*! + \param pause simulation true or false + */ + void PauseSimulation(bool pause); +#endif + +#if _ENABLE_ATTACHED_OBJECTS + //! Attach Object + /*! + \param obj, object to attach + \param attachTo, where does the object get attached to? + \param memindex, memory point index were it get's attach to parent, (-1) for center + \param pos, position offset from attachPoint + \param flags, additional flags + */ + void AttachObject(Object *obj, Object *attachTo, int memIndex, Vector3 pos, int flags); + //! detach object + /*! + \param obj, object to detach + */ + void DetachObject(Object *obj); +#endif + + //! Ask vehicle for user defined animation + /*! + \param vehicle animated vehicle + \param animation animation name + \param phase wanted animation phase + */ + void AskForAnimationPhase(Entity *vehicle, RString animation, float phase); + + //! Checks if gamemaster is to select mission on dedicated server + bool CanSelectMission() const {return _selectMission;} + //! Checks if client is to vote mission on dedicated server + bool CanVoteMission() const {return _voteMission;} + //! Returns array of missions available on dedicated server + const AutoArray &GetServerMissions() const + { + return _serverMissions; + } + + /// check voting status + const VotingMissionProgressMessage *GetMissionVotingState() const {return &_missionVoting;} + //! Select mission on dedicated server + /*! + \param mission name of selected mission + \param difficulty game difficulty level + */ + void SelectMission(RString mission, int difficulty); + //! Vote mission on dedicated server + /*! + \param mission name of selected mission + \param difficulty game difficulty level + */ + void VoteMission(RString mission, int difficulty); + + /// Find the object (local or remote) by its network id + NetworkObject *GetObject(const NetworkId &id); + //! Unregister given network object, send message to others + void DeleteObject(const NetworkId &id, bool sendMsg); + + //! Process chat command for remote control of dedicated server + /*! + \param command chat command + */ + bool ProcessCommand(RString command); + bool IsCommandAvailable(NetworkCommandType type); + bool IsCommandAvailable(RString command); + + //! Ask server to kick off player + /*! + \param player DirectPlay ID of player to kick off + */ + void SendKick(int player); + + //! Ask server to disable/enable connection of further clients + /*! + \param lock true to disable connection + */ + void SendLockSession(bool lock = true); + + //! player must disconnect due to some mission loading error + void Disconnect(RString message); + + //! Force update of network object + /*! + \param object object to update + \param dwFlags DirectPlay flags + */ + void UpdateObject(NetworkObject *object, NetMsgFlags dwFlags); + + //! Force update of network object (single type of update) + /*! + \param object object to update + \param cls type of update + \param dwFlags DirectPlay flags + */ + int UpdateObject(NetworkObject *object, NetworkMessageClass cls, NetMsgFlags dwFlags); + + const char *GetDebugName() const {return "Client";} + + RString GetDiagText(const NetworkObject *obj) const; + + //! Return estimated end of mission time + Time GetEstimatedEndTime() const; + + //! Body can be hidden (for better performance) + void DisposeBody(Person *body); + + //! Wreck can be hidden (for better performance) + void DisposeWreck(Transport *wreck); + + //! Game is paused due to disconnection state of game + bool IsControlsPaused() {return _controlsPaused;} + + //! Last received message's age in seconds (used to eliminate "disconnect cheat") + float GetLastMsgAgeReliable(); + + //! Cleanup unit after player disconnection + void CleanupPlayer(int dpnid, NetworkId id); + + //! Set voice mask to new value (Xbox) + void ChangeVoiceMask(RString mask); + + /// Reaction to detection of hacked data + void HackedDataDetected(RString filename); + + /// add event handler executed in reaction to PublicVariableMessage + void AddPublicVariableEventHandler(RString name, GameValuePar code); + + void SynchronizeVariable( EntityAI * veh, RString name, float coef, const GameDataCode & code ); + + void ProcessAction(Action *action, AIBrain *unit); + + void ProcessRecipe(RString recipe, Person *person, InventoryItem *item1, InventoryItem *item2); + + // implementation +protected: + //! Find info about local object with given id (NULL if not found) + NetworkLocalObjectInfo *GetLocalObjectInfo(const NetworkId &id); + //! Find info about remote object with given id (NULL if not found) + NetworkRemoteObjectInfo *GetRemoteObjectInfo(const NetworkId &id); + + //! Register network object as local object, assign id to them + NetworkId CreateLocalObject(NetworkObject *object, bool setNetworkId=true); + + void InsertLocalObject(NetworkObject *object); + + void InsertRemoteObject(NetworkObject *obj, bool remote); + + //! Prepare multiplayer game + /*! + Switch landscape, parse mission sqm file, initialize GWorld. + */ + bool PrepareGame(); + + //! Perform actions needed when client reach state NCSPlaying + void OnMissionStarted(); + + //! Select player on local machine + void ProcessSelectPlayer(Person *person, bool respawn, Vector3Par pos); + + ///! Create and Update messages can be received only when client is ready to play + inline bool CanReceiveUpdateMessages() + { + return (_clientState >= NCSMissionReceived && _clientState <= NCSPlaying); + } + + //! Create network object and register as remote object + /*! + \param ctx network message context of create message + \param dummy dummy argument for specification type of created network object + */ + template + bool CreateRemoteObject(NetworkMessageContext &ctx) + { + VehType *dummy; // VehType not seen inside of lambda (Visual Studio 2010), this is a trick to pass it there + auto create = [dummy](NetworkMessageContext &ctx)->NetworkObject * {return dummy->CreateObject(ctx);}; + return CreateRemoteObject(ctx,create); + } + + bool CreateRemoteObject(NetworkMessageContext &ctx, std::function create); + + //! Unregister and destroy remote network object + void DestroyRemoteObject(NetworkId id); + + //! Enforce destruction of (local or remote) object + void ForceDeleteObject(NetworkObject *object); + + //! Send all agregated and update messages + void SendMessages(); + //! Calculate limits for message sending + void EstimateBandwidth(int &nMsgMax, int &nBytesMax); + //! Calculate errors and place object in list sorted by error + /*! + \param objects output sorted list of objects + */ + void CreateObjectsList(AutoArray &objects); + //! Prepare next object update message to message queue + bool PrepareNextUpdate(AutoArray &objects, int &next); + + //! Return number of auto destroyed local objects - used for debugging purposes + int NLocalObjectsNULL() const; + //! Check database of local objects - used for debugging purposes + bool CheckLocalObjects() const; + + /// clear voting once we know it is no longer valid + void ClearMissionVoting(); + //! Server state changed + void OnServerStateChanged(NetworkServerState state); + + //! State change enforced by server + void OnClientStateChanged(NetworkClientState state); + + void EnqueueMsg + ( + int to, NetworkMessage *msg, + NetworkMessageType type, + NetworkObject *object + ); + void EnqueueMsgNonGuaranteed + ( + int to, NetworkMessage *msg, + NetworkMessageType type, const RefR &dependOn + ); + + //! Returns which players hear me + void GetPlayersOnChannel(AutoArray &players, int channel) const; + //! Returns which players can hear me in direct speak (are within the radius range depending on channel) + void GetTargetsInDirectSpeakRange(AutoArray &players, int channel) const; + + //! Check if player is in remote mute list (local player muted by given player) + bool IsPlayerInRemoteMuteList(int player) const; + +protected: + //! start validation of bank hash + //! \param askedIndex index matching NMTDataSignatureAsk + //! \param qBankIx index of bank inside global GFileBanks + //! \return true when check was succesful + bool CheckDataSignature(int askedIndex, int level, QFBank &bank, int gBankIx); + //! start validation of other additional file hash + bool CheckDataSignature(int askedIndex, int level, RString filename); + //! start validation of bank hash (using filename to find inside some bank, sig.ver > 1) + bool CheckFileSignature( int bankIndex, int level, RString filename ); + + /// queue of banks waiting for signature check + FindArrayKey _checkSignatureQueue; + /// currently checked signature + SRef _checkingSignature; + +#if defined _XBOX && _XBOX_VER >= 200 + /// updates all needed based on new local player info list + void UpdateLocalPlayerInfoList(const LocalPlayerInfoList& localPlayerInfoList); + + +#endif +}; + +//! Info about single type of update of network object +struct NetworkCurrentInfo +{ + //! type of message + NetworkMessageType type; + //! sender of message + int from; + //! last received state of object + Ref message; +}; + +#include + +//! info about state of sent updates of network object for single client +struct NetworkPlayerObjectInfo: public RefCount, public TLinkBidirD +{ + //! ID of player + int player; + /// backlink to NetworkObjectInfo, needed for OnStopUpdating + NetworkObjectInfo *oInfo; + //! state of updates + NetworkUpdateInfo updates[NMCUpdateN]; + //! All updates depends on this message (to be handled after) + RefR _fence; + //! is within the updating range + bool updating; + + NetworkPlayerObjectInfo(); + ~NetworkPlayerObjectInfo(); + + //! allocated quite often + USE_FAST_ALLOCATOR +}; + +#include + +//! Info about network object on server +/*! +\patch_internal 1.23 Date 9/18/2001 by Jirka +- Improved: storage of PlayerObjectInfo changes +*/ +#include + +/// messages waiting to be sent until acknowledgement OwnerChanged arrives from previous owner in ChangeOwner process +struct WaitingMessageInfo: public RefCount +{ + Ref msg; + NetworkMessageType type; + + WaitingMessageInfo(NetworkMessageType t, NetworkMessage *m) : msg(m), type(t) {}; + + USE_FAST_ALLOCATOR +}; + +UNIQUE_TYPE(PlayerIndex,int); + +struct NetworkObjectInfo: public RefCount +{ + //! ID of object + NetworkId id; + /// the object itself + OLinkNO(NetworkObject) object; + //! DirectPlay ID of owner client + int owner; + //! DirectPlay ID of new owner client pending (ChangeOwner message sent but waiting to acknowledgment OwnerChanged message) + //! when set to NO_CLIENT no change owner is pending + int pendingOwner; + //! create message (used for JOIN IN PROGRESS) + NetworkCurrentInfo create; + //! state of last received updates + NetworkCurrentInfo currentUpdate[NMCUpdateN]; + //! state of last received updates sent from owner when bot-client sent overrides + NetworkCurrentInfo currentRejected[NMCUpdateN]; + //! current rejection status reported by a bot-client + InitVal rejected[NMCUpdateN]; + //! state of last sent updates (for each player) + RefArray playerToObjects; + //! messages waiting to be sent to clients until acknowledgment OwnerChanged arrives from previous owner in ChangeOwner process + RefArray waitingMessages; + + struct UpdateInfo + { + Vector3 _pos; + float _updateDistance; + + UpdateInfo():_pos(VZero),_updateDistance(FLT_MAX){} + }; + UpdateInfo _updInfo; + + NetworkObjectInfo(); + ~NetworkObjectInfo(); + + //! Find info about network object for given player + NetworkPlayerObjectInfo *GetPlayerObjectInfo(PlayerIndex player, int pid); + //! Create info (register) of new network object for given player + NetworkPlayerObjectInfo *CreatePlayerObjectInfo(PlayerIndex player, int pid); + //! Delete info (unregister) network object for given player + void DeletePlayerObjectInfo(PlayerIndex player, int pid); + //! Delete info (unregister) network object for given player (used when player becomes an owner) + void NullPlayerObjectInfo(PlayerIndex player, int pid); + //! Forget the updates sent to given player + void ResetPlayerObjectInfo(PlayerIndex player, int pid); + + UpdateInfo BestPosition(const NetworkServer *server) const; + UpdateInfo BestPosition() const; + bool CheckBestPositionIntegrity(const NetworkServer *server) const; + + void ScanBestPosition(const NetworkServer *server); + + UpdateInfo CheckBestPosition(const NetworkServer *server) const; + RString GetDebugName() const; + + //! Objects of this type will be allocated quite often + USE_FAST_ALLOCATOR +}; +//TypeIsMovable(NetworkObjectInfo) + +#include + +//! calculate min, max and average from set of values +class CalculateMinMaxAvg +{ + float _min,_max,_sum; + float _weight; + /// last value sampled + float _lastValue; + + public: + CalculateMinMaxAvg(); + //! add sample + void Sample(float value, float weight=1); + //! reset + void Reset(); + //! get current results (min) + float GetMin() const {return _weight>0 ? _min : 0;} + //! get current results (max) + float GetMax() const {return _weight>0 ? _max : 0;} + //! get current results (average) + float GetAvg() const {return _weight>0 ? _sum/_weight :0;} + /// get last value + float GetLastValue() const {return _lastValue;} +}; + +struct PendingDataSignatureCheck +{ + //! the index of checked file + DWORD answerIndex; + //! timeout for question + DWORD checkTimeout; +}; + +TypeIsSimple(PendingDataSignatureCheck) + +struct PendingFileSignatureCheck +{ + //! the checked file + RString filename; + //! the pbo prefix + RString prefix; + //! timeout for question + DWORD checkTimeout; +}; + +TypeIsMovableZeroed(PendingFileSignatureCheck) + +// Helper functor +class CheckSignatureTimeoutFunc +{ +public: + virtual bool operator ()() = 0; +}; + +//! PendingSignatureChecks encapsulates both PendingDataSignatureCheck and PendingFileSignatureCheck +class PendingSignatureChecks +{ + AutoArray pendingFileChecks; + AutoArray pendingDataChecks; +public: + PendingSignatureChecks() {} + + // both data and file signature pendings are checked for timeout and given action is processed when timeouted + void CheckTimeouts(CheckSignatureTimeoutFunc &func +#define DEBUG_SIGNATURES 1 +#if DEBUG_SIGNATURES + , RString &errorInfo +#endif + ); + + // add some time to timeout of initial data signature check + void UpdateInitialCheckTimeout(); + + // add the time specified to all signature timeouts + void DelayCheckTimeouts(DWORD time, const char *playerName); + + //@{ interface to work with PendingDataSignatureChecks + bool Pending(int bankIndex) + { + for (int i=0; i + +/// messages waiting to be sent +struct DelayedMessageInfo: public RefCount +{ + Ref msg; + NetworkMessageType type; + float error; + float invMaxAge; + Vector3 pos; + /// when the message was received + Time timeReceived; + + DelayedMessageInfo(NetworkServer *server, NetworkMessageType t, NetworkMessage *m); + + USE_FAST_ALLOCATOR +}; + +#include + +struct CDKeyCheck +{ + DWORD timeout; + CDKeyCheck() : timeout(0) {} +}; + +//! Hashes collected from DataSignatureAnswer messages +class CollectedHashes +{ + struct CollectedHash + { + RString fileName; + RString prefix; + Temp hash; // DataContentHash + Temp ver2lev0hash; // hash of ( DataContentHash + fileListHash + pbo prefix) + Temp ver2lev2hash; // hash of (nonDataContentHash + fileListHash + pbo prefix) + + //! CollectedHash is initialized during initial SignatureCheck + CollectedHash(RString filNam, Temp &hs) : fileName(filNam), hash(hs) {} + CollectedHash() {}; + ClassIsMovable(CollectedHash) + }; + + static const int SignatureCheckLevels = 3; + struct RandomUsedFileCandidate + { + RString filename; + RString prefix; + int levelAsksCount[CollectedHashes::SignatureCheckLevels]; + + RandomUsedFileCandidate() {} + RandomUsedFileCandidate(RString fn, RString prf) : filename(fn), prefix(prf) + { + for (int i=0; i hashes; + //! collecting hashes from client is in progress (through NetworkServer::InitialSignaturesTest(...)) + bool _collecting; + //! maps prefix to the RandomUsedFileCandidate to track how often which asks are sent + typedef MapStringToClass > PrefixToCandidate; + PrefixToCandidate _candidatesMap; + +public: + static const int CollectEndIndex = 0x50be; //mnemo Sobe + //! number of pbo files loaded + int banksCount; // -1 is default value meaning the client has not sent this information + //! next time for full check (level 1) + DWORD fullCheckNext; + //! timeout time to get banksCount and iKnowLevel2 info + DWORD bankInfoTimeout; + +private: +#if DEBUG_SIGNATURES + RString lastError; +#endif + + void Collecting(bool collect) { _collecting = collect; } + void Clear() { hashes.Resize(0); } + + // return true when HACK detected + bool TestLevelHash(CollectedHash &colHash, int index, int colIndex, Temp &hash, int sigVer, int level) + { + if (!_collecting && index>=0) + { + if ( colIndex != (index % SignaturesCount()) ) + { +#if DEBUG_SIGNATURES + lastError = Format("ColIx(%d)-Ix(%d)", colIndex, index); +#endif + return true; //hack detected + } + } + switch (sigVer) + { + case 1: + { // hash param is the DataContentHash + if (hash.Size() != colHash.hash.Size() || + memcmp(hash.Data(), colHash.hash.Data(), hash.Size()) != 0) return true; //hack detected + } + break; + case 2: + { + switch (level) + { + case 0: + case 1: // hash param is the sigVer2, level=0 hash + if (colHash.ver2lev0hash.Size()>0) + { + if (hash.Size() != colHash.ver2lev0hash.Size() || + memcmp(hash.Data(), colHash.ver2lev0hash.Data(), hash.Size()) != 0) + { +#if DEBUG_SIGNATURES + lastError = "DiffLev0Hash"; +#endif + return true; //hack detected + } + } + else + { // collect ver2lev0hash + colHash.ver2lev0hash = hash; + } + break; + case 2: // hash param is the sigVer2, level=2 hash + if (colHash.ver2lev2hash.Size()>0) + { + if (hash.Size() != colHash.ver2lev2hash.Size() || + memcmp(hash.Data(), colHash.ver2lev2hash.Data(), hash.Size()) != 0) + { +#if DEBUG_SIGNATURES + lastError = "DiffLev2Hash"; +#endif + return true; //hack detected + } + } + else + { // collect ver2lev2hash + colHash.ver2lev2hash = hash; + } + break; + default: +#if DEBUG_SIGNATURES + lastError = "UnknownLevel"; +#endif + return true; // unrecognized level + } + } + break; + default: +#if DEBUG_SIGNATURES + lastError = "UnknownVer"; +#endif + return true; //unknown version + } + return false; //ok + } + // Test the hash against the collectedHash with the given fileName + // return true when HACK detected + bool Test(RString fileName, int index, Temp &hash, int sigVer, int level) + { + if (index>=0) + { + if (!SignaturesCount()) + return true; //HACK, unexpected message with index set during collecting phase + index = index % SignaturesCount(); + if (hashes[index].fileName != fileName) + { +#if DEBUG_SIGNATURES + lastError = "Ix&File"; +#endif + return true; //HACK, index and fileName does not match + } + return TestLevelHash(hashes[index], index, index, hash, sigVer, level); + } + else + { + for (int i=0; i &dataContentHash, Temp &levelHash, int sigVer, int level) + { + // use index when set + if (index>=0) + { + if (!SignaturesCount()) + { +#if DEBUG_SIGNATURES + lastError = "NoStoredSig"; +#endif + return true; //HACK, unexpected answer with index set during collecting phase + } + // cut index to fit within range using modulo + index = index % SignaturesCount(); + // Test prefix + if (hashes[index].prefix.IsEmpty()) + hashes[index].prefix = prefix; // set it at last + else if (hashes[index].prefix!=prefix) + { +#if DEBUG_SIGNATURES + lastError = Format("DiffPrefix(%s,%s)", cc_cast(hashes[index].prefix), cc_cast(prefix)); +#endif + return true; //HACK, prefixes differ + } + // Test dataContentHash + Temp &colDataContentHash = hashes[index].hash; + if ( !colDataContentHash.Size() ) + colDataContentHash = dataContentHash; //possible collect it (but maybe empty again) + else if ( + dataContentHash.Size() && + (dataContentHash.Size()!=colDataContentHash.Size() || (memcmp(dataContentHash.Data(), colDataContentHash.Data(), dataContentHash.Size()) != 0) ) + ) + { +#if DEBUG_SIGNATURES + lastError = "DiffDCH"; +#endif + return true; //dataContentHashes differ + } + // Test levelHash + if (levelHash.Size()) + return TestLevelHash(hashes[index], index, index, levelHash, sigVer, level); + else + return false; //OK, nothing else to check + } + else + { // this happen only for clients before rev.78326 + if (levelHash.Size()>0) + { + for (int i=0; i &hash, int sigVer, int level) + { + for (int i=0; i *colHash = NULL; + if (sigVer==1) colHash = &hashes[i].hash; + else switch (level) + { + case 0: + case 1: colHash = &hashes[i].ver2lev0hash; break; + case 2: colHash = &hashes[i].ver2lev2hash; break; + } + if ( hashes[i].fileName==fileName || + (colHash!=NULL && hash.Size() == colHash->Size() && + memcmp(hash.Data(), colHash->Data(), hash.Size()) == 0) + ) + { +#if DEBUG_SIGNATURES + if (hashes[i].fileName==fileName) + lastError = "SameFile"; + else + lastError = "SameSig"; +#endif + return i; + } + } + return -1; //not found + } + +public: + CollectedHashes() : _collecting(false), banksCount(-1) + { + fullCheckNext = GlobalTickCount() + 40000 + toInt(40000 * GRandGen.RandomValue()); // initial delay 40 s - 80 s + bankInfoTimeout = 0; // no timeout yet + } + + void StartCollecting() + { + Clear(); + Collecting(true); + } + + //! In spite of we are collecting hashes, the SignaturesCount suits better + int SignaturesCount() const + { + if (_collecting) return 0; + else + { + return hashes.Size(); + } + } + + //! AddHash based on fileName [DataSignatureAnswer] + //! return true when HACK detected + bool AddHash(int index, RString fileName, Temp &hash, int sigVer, int level, PendingSignatureChecks &pendingChecks) + { +#if DEBUG_SIGNATURES + lastError = ""; +#endif + //RptF("AddHash: %s, ix=%d, ver=%d, lev=%d", cc_cast(fileName), index, sigVer, level); + if (index<0) + { + if (!_collecting) return Test(fileName, index, hash, sigVer, level); //fileName based Test + else // we are collecting + { + int ix = ArrayIx(fileName, hash, sigVer, level); + if (ix>=0) + { +#if DEBUG_SIGNATURES + lastError = RString("Duplo-") + lastError;; +#endif + return true; //hack detected (the same answer sent second time) + } + // new hash + switch (sigVer) + { + case 1: hashes.Add(CollectedHash(fileName, hash)); break; + case 2: + { + switch (level) + { + case 0: + case 1: + { + int ix = hashes.Add(CollectedHash()); + CollectedHash &colHash = hashes[ix]; + colHash.fileName = fileName; + colHash.ver2lev0hash = hash; + } + break; + case 2: + { + int ix = hashes.Add(CollectedHash()); + CollectedHash &colHash = hashes[ix]; + colHash.fileName = fileName; + colHash.ver2lev2hash = hash; + // we are collecting and asynchronous level=2 check is used. Add more time to pending signature check + pendingChecks.UpdateInitialCheckTimeout(); + } + break; + default: return true; //unrecognized level + } + } + break; + default: return true; //unrecognized version + } + } + return false; //ok + } + else + { + if (_collecting) + { + if (index==CollectEndIndex) + { + _collecting = false; + // when there are too few initial DataSignatureAnswers during "collecting" phase, + // the client is supposed to be cheating. The limit is chosen conservative enough (30 banks). + const int MinimalBankCount = 30; + if ( SignaturesCount() < MinimalBankCount ) + { +#if DEBUG_SIGNATURES + lastError = "MinSigCount"; +#endif + return true; + } + if (UpdatePlayerBankCount(SignaturesCount())) + return true; //hacked + } + else + { +#if DEBUG_SIGNATURES + lastError = "50BE-Expected"; +#endif + return true; // CollectEndIndex was expected! => HACK? + } + } + return Test(fileName, index, hash, sigVer, level); //fileName based Test + } + } + //! AddHash based on bank prefix + //! return true when HACK detected + bool AddHash(int index, RString prefix, Temp &dataContentHash, Temp &levelHash, int sigVer, int level) + { +#if DEBUG_SIGNATURES + lastError = ""; +#endif + //RptF("AddHash: index=%d prefix=%s, ver=%d, lev=%d", index, cc_cast(prefix), sigVer, level); + if (_collecting) + { +#if DEBUG_SIGNATURES + lastError = "Collecting"; +#endif + return true; //this type of answers is not expected during initial collecting phase + } + return Test(index, prefix, dataContentHash, levelHash, sigVer, level); //bank prefix based Test + } + + //! Get the level to use for the next signature check + int ActualCheckLevel() + { + DWORD time = GlobalTickCount(); + if (time > fullCheckNext) + { + fullCheckNext = time + 80000 + toInt(80000 * GRandGen.RandomValue()); // 80 s - 160 s + // note: full check (level=1) is broken, World::CheckHash is very slow and never completes, use 2 instead + return 2; // deep check (level 1) + } +#if 1 + DoAssert(banksCount>0); // the bank count should already be known + // FIX: level=2 checks are now processed async + if ( rand()%4==0 && banksCount>0) + return 2; + else + return 0; // shallow check (hash is taken from stored bank position, not recomputed from its content) +#else + return 0; //HOTFIX: Level 2 checks are too long to compute for both clients and server (async on clients and precomputation on servers should be implemented!) +#endif + } + + RString GetLastError() const + { +#if DEBUG_SIGNATURES + return lastError; +#else + return RString(""); +#endif + } + + //! Check timeout guarding whether client send her banksCount + void CheckTimeouts(CheckSignatureTimeoutFunc &func) + { + if ( bankInfoTimeout && (bankInfoTimeout < GlobalTickCount()) ) + { + (void)func(); + } + } + + //! It calls the GWorld->RandomUsedFile more times to get the file which is not asked too often + RString RandomUsedFile(Vector3Par pos, int level); + + bool IsCollecting() const { return _collecting; } + + // returns true when hack was detected + bool UpdatePlayerBankCount(int bankCount); + +#if DEBUG_SIGNATURES + const AutoArray &Hashes() { return hashes; } +#endif +}; + +struct AsyncDBStorage +{ + // asynchronous save to the central database + struct SaveThreadContext : public RefCount + { + SIGNALED_OBJECT _thread; + RString _url; + RString _request; + RString _uid; + Ref _prevContext; + + SaveThreadContext() : _thread(NoInitHandle) {} + }; + Ref _lastContext; + + bool DBSave(RString baseURL, RString playerUID, RString request); + bool DBQueue(RString baseURL, RString playerUID, RString request); + bool DBKill(RString baseURL, RString playerUID); + bool DBItemDrop(RString baseURL, RString request); + + static DWORD WINAPI DBSaveThreadFunction(void *ctx); + static DWORD WINAPI DBQueueThreadFunction(void *ctx); + static DWORD WINAPI DBKillThreadFunction(void *ctx); + static DWORD WINAPI DBItemDropThreadFunction(void *ctx); + + // asynchronous load to the central database + struct LoadThreadContext : public RefCount + { + SIGNALED_OBJECT _thread; + RString _url; + // load possible when all saves completes + Ref _prevContext; + // the result of the request + RString _result; + int _err; + // the script executed when request completes + Ref _code; + int _playerId; + RString _playerUID; + RString _name; + + LoadThreadContext() : _thread(NoInitHandle) {} + }; + AutoArray< Ref > _loadContexts; + void DBLoad(RString baseURL, int playerId, RString playerUID, RString name, GameDataCode *code); + static DWORD WINAPI DBLoadThreadFunction(void *ctx); + void DBCheckLoaded(); +}; + +#if _ENABLE_STEAM_MATCHMAKING && !(_ENABLE_STEAM_IDENTITY && defined(_WIN64)) +class SteamValidation +{ + /// Steam authentication is completed (need not wait for it) + bool _authDone; + /// Steam authentication passed (client approved) + bool _authOK; + + bool _started; + DWORD _ticksStarted; + + NetworkServer *_server; + + uint64 _steamId; + + AutoArray _steamSessionTicket; + + RString _name; + + int _dpid; + +public: + SteamValidation(); + ~SteamValidation(); + + void Start(PlayerIdentity &identity, NetworkServer *server); + + void HandleTimeout(); + + // Tells us a client has been authenticated and approved to play by Steam (passes auth, license check, VAC status, etc...) + STEAM_GAMESERVER_CALLBACK(SteamValidation, OnValidateAuthTicketResponse, ValidateAuthTicketResponse_t, _callbackGSAuthTicketResponse); +}; +#endif + + +//! Server info about player +struct NetworkPlayerInfo : public AsyncDBStorage, public RefCount, private NoCopy +{ + //! DirectPlay ID of player (client) + int dpid; + //! Voice over net ID of player (client) + int dvid; + + //! chat channel player transmits + int channel; + + //! some clients are "local" (no bandwidth control is needed) + bool _isLocal; + //! name of player + RString name; + //! client state for given player + NetworkClientState clientState; + //! message queue (candidates for aggregation) + NetworkMessageQueue _messageQueue, _messageQueueNonGuaranteed; + + /// messages waiting to be sent to clients + /** messages describing audio or visual effects, no delivery is guaranteed */ + RefArray _delayedMessages; + + /// list of objects which are marked as updating for this player + typedef TListBidir> UpdatingList; + UpdatingList _updating; + + void markAsUpdating(NetworkPlayerObjectInfo *info, UpdatingList &updatingNew) + { + //DoAssert(updatingNew.CheckIntegrity()); + //DoAssert(_updating.CheckIntegrity()); + if (info->IsInList()) + { + //DoAssert(_updating.Contains(info)); + _updating.Delete(info); + } + updatingNew.Insert(info); + //DoAssert(_updating.CheckIntegrity()); + //DoAssert(updatingNew.CheckIntegrity()); + } + + void markAsUpdating(NetworkPlayerObjectInfo *info) + { + //DoAssert(_updating.CheckIntegrity()); + if (!info->IsInList()) _updating.Insert(info); + //DoAssert(_updating.CheckIntegrity()); + } + + //! ping statistics + CalculateMinMaxAvg _ping; + //! bandwidth statistics + CalculateMinMaxAvg _bandwidth; + //! desync statistics + CalculateMinMaxAvg _desync; + + //! player's person + NetworkId person; + + SRef _clientInput; + + //! player occupy private slot + bool privateSlot; + + //! client has actual (valid) mission pbo file + bool missionFileValid; + + //! client has actual (valid) mission pbo file + bool paramFileValid; + + //! kick-off already requested + bool kickedOff; + + //! Connection loosing (no message for 10 seconds) was already reported to other users + bool connectionProblemsReported; + + //! Player was joined using JIP (used to distinguish between normal JIP and JIP forced after MP Load) + bool _jipProcessed; + + //@{ private and public socket address + port + int _publicAddr; + int _publicPort; + + int _privateAddr; + int _privatePort; + //@} + + /// how many times wrong login password was given + int _loginFailedCount; + /// how long is login disabled because of two many wrong attempts + DWORD _loginDisabledUntil; + + /// Signature checks + PendingSignatureChecks signatureChecks; + + /// Hashes collected during initial signature test + CollectedHashes hashes; +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) + SteamValidation _steamValidate; +#endif + +#if _ENABLE_STEAM_MATCHMAKING && !(_ENABLE_STEAM_IDENTITY && defined(_WIN64)) + SteamValidation _steamValidate; +#endif + + /// CDKey check + CDKeyCheck cdKeyCheck; + + //! time when next regular check will take place + DWORD regularCheckNext; + //! order of the regular check + DWORD regularCheckOrder; + + //! position of camera on given client + Vector3 cameraPosition; + //! time of last update of cameraPosition + Time cameraPositionTime; + +#if _VBS3 + //! Direction of camera on given client + Vector3 cameraDirection; + //! FOV on given client + float cameraFov; +#endif + +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + //! next message of the day index (-1 if done) + int motdIndex; + //! next message of the day time + UITime motdTime; +#endif + + int nextQuestionId; + +#if _ENABLE_MP + MuteListMessage muteList; +#endif + + Time joined; + + /// key for encoding of CD Key validation communication + RString challenge; + + /// challenge to be signed by the PlayerId certiticate + long long certChallenge; + + // Serialize for MP Save/Load + LSError Serialize(ParamArchive &ar); +//} + + /* @return value: true when client is not able to send through network + (because it loads the landscape, mission, do some time exhaustive work,...) + It detects the start and end of the busy state + At start: it remembers the start time + At end: it adds the time spent to all pending signature timeouts + */ + bool ClientStateBusy(); + // helper variable for ClientStateBusy function + DWORD _busyStartTime; // when zero, the client is NOT busy. The start of busy state otherwise. + +#if DEBUG_SIGNATURES + RString errorInfo; +#endif +}; + +//! map person to unit in server database +struct PersonUnitPair +{ + //! id of person + NetworkId person; + //! id of unit + NetworkId unit; +}; +TypeIsMovable(PersonUnitPair) + +//! Single vote in votings +struct Vote +{ + //! DirectPlay ID of player + int player; + //! Voted value + AutoArray value; + + //! Equality operator + /*! + \param val voted value + \param valueSize size of voted value + */ + bool HasValue(const char *val, int valueSize) const; +}; +TypeIsMovable(Vote) + +//! Single voting +class Voting : public AutoArray +{ + friend class Votings; + typedef AutoArray base; + +protected: + /// Unique id of voting + AutoArray _id; + /// Threshold when voting is valid + float _threshold; + /// Check if more than half players has the same value + bool _selection; + + /// when there are to little players, assume other can still connect + int _minVotePlayers; +public: + //! Add new vote + /*! + \param player DirectPlay ID of voting player + \param value voted value (NULL if none) + \param valueSize size of voted value + */ + int Add(int player, const char *value = NULL, int valueSize = 0); + + //! Return ID of Voting + const AutoArray &GetID() const {return _id;} + + //! Check if voting is valid + bool Check(const AutoArray &identities) const; + + /// remote voting of any player which is no longer here + void OnPlayerDeleted(int dpid); + //! Get voted value + /*! + \param n number of votes + */ + const AutoArray *GetValue(int *n = NULL, int *n2=NULL) const; + + struct VoteInfo + { + const Vote *vote; + int count; + + ClassIsSimple(VoteInfo) + }; + + static int CompareVoteInfo(const VoteInfo *v1, const VoteInfo *v2) + { + return v2->count-v1->count; + } + + /// get ordered info about voting + void GetOrder(AutoArray &result) const; + //! Equality operator + /*! + \param id unique identification of voting + \param idSize size of unique identification + */ + bool HasID(const char *id, int idSize) const; +}; +TypeIsMovable(Voting) + +//! Voting system +class Votings : public AutoArray +{ + typedef AutoArray base; + +public: + //! Add new vote + /*! + \param server hosting server + \param id unique identification of voting + \param idSize size of unique identification + \param threshold threshold when voting is valid + \param player DirectPlay ID of voting player + \param value voted value (NULL if none) + \param valueSize size of voted value + */ + void Add( + NetworkServer *server, const char *id, int idSize, float threshold, int player, const char *value = NULL, int valueSize = 0, + bool selection = false, int minVotePlayers=-1 + ); + + /// find given voting + const Voting *Find(int id) {return Find((const char *)&id,sizeof(id));} + + /// find given voting + const Voting *Find(const char *id, int idSize) const; + + /// find index of a corresponding voting + int FindIndex(const char *id, int idSize) const; + + /// delete voting + void DeleteVoting(int id) {return DeleteVoting((const char *)&id,sizeof(id));} + + /// delete given voting + void DeleteVoting(const char *id, int idSize); + + /// remote voting of any player which is no longer here + void OnPlayerDeleted(int dpid); + + //! Check all votings (apply if satisfied) + /*! + \param server hosting server + */ + void Check(NetworkServer *server); + + /// apply voting, if there are no votes return false + bool Apply(NetworkServer *server, int id) {return Apply(server,(const char *)&id,sizeof(id));} + /// apply voting, if there are no votes return false + bool Apply(NetworkServer *server, const char *id, int idSize); +}; + +/// Custom file slot +struct CustomFilePaths +{ + RString _src; + RString _dst; + unsigned int _crc; + int _len; + CustomFilePaths() {} + CustomFilePaths(RString src, RString dst, unsigned int crc, int len) : _src(src), _dst(dst), _crc(crc), _len(len) {} + + DECLARE_NETWORK_OBJECT + static NetworkMessageFormat &CreateFormat + ( + NetworkMessageClass cls, + NetworkMessageFormat &format + ); + TMError TransferMsg(NetworkMessageContext &ctx); +}; +TypeIsMovable(CustomFilePaths) + +TypeIsMovable(TransferFileMessage) + + +//! pending download of squad information +class CheckSquadObject +{ +friend class NetworkServer; + +protected: + + long long _challenge; + //! identify player + PlayerIdentity _identity; + + //! custom files subsets of which is can be sent to some clients + AutoArray _customFileList; + //! TransferFile messages for each custom file (created only when needed) + AutoArray > _customFileMessages; + //! custom files which given clients wants to sent + struct CustomFilesForClient + { + int _dpnid; // client identification + enum CFTState {CFSWaitingToList, CFSSendingFiles, CFSDone} _state; + AutoArray _filesWanted; + //{ Files Transfer members + int _fileNo; // index into _filesWanted, which file is currently being transfered + int _fragmentNo; // number of transfered fragments + int _allFragmentCount; // used for progress bar + int _allFragmentPos; // used for progress bar + DWORD _nextSendTime; // time to send next bunch of TransferFile messages + //} + CustomFilesForClient() {} + CustomFilesForClient(int dpnid) : _dpnid(dpnid), _state(CFSWaitingToList), _fileNo(0), _fragmentNo(0) , + _allFragmentPos(0), _allFragmentCount(200) //200 - approx 100kB before the valid count is not received + { + _nextSendTime=::GetTickCount(); + } + ClassIsMovableZeroed(CustomFilesForClient) + }; + AutoArray _customFilesProgress; + + enum State {SendingCustomFiles,AllDone}; + //! state of download + State _state; + //! address of proxy server + RString _proxy; + +public: + //! start download + CheckSquadObject(PlayerIdentity &identity, RString proxy, NetworkServer *server); + //! destruct - wait until current download step is terminated + ~CheckSquadObject(); + //! check if download is terminated + bool IsDone(bool &canSendCustomFiles, NetworkServer *server); + bool IsPlayer(int dpnid) { return _identity.dpnid==dpnid; }; + + //! custom files transfer to all clients. Returns true when no custom files are being sent. + bool StartSendCustomFilesList(NetworkServer *server); + + //! store content of NMTCustomFilesWanted message + void SetCustomFilesWanted(int dpnid, const AutoArray &filesWanted); + + State GetState() const { return _state; } + +protected: + void CreateCustomFilesList(); +}; + +struct UpdateObjectInfo; +class LiveStatsUpdate; +static const int SessionAttributesCount = 12; + +enum HackType +{ + HTUnsignedData, + HTHackedData +}; + +#if _ENABLE_DEDICATED_SERVER + +#define SERVER_EVENT_ENUM(type, prefix, XX) \ + XX(type, prefix, DoubleIdDetected) /* two users with the same id detected */ \ + XX(type, prefix, OnUserConnected) /* reaction to connected user */ \ + XX(type, prefix, OnUserDisconnected) /* reaction to disconnected user */ \ + XX(type, prefix, OnHackedData) /* reaction to pbo files manipulation */ \ + XX(type, prefix, OnUnsignedData) /* reaction to unsigned file */ \ + XX(type, prefix, RegularCheck) /* called regullary for each user */ \ + +#ifndef DECL_ENUM_SERVER_EVENT +#define DECL_ENUM_SERVER_EVENT +DECL_ENUM(ServerEvent) +#endif +DECLARE_ENUM(ServerEvent, SE, SERVER_EVENT_ENUM) + +#endif + +typedef struct qr2_buffer_s *qr2_buffer_t; +typedef struct qr2_keybuffer_s *qr2_keybuffer_t; + +//((EXE_CRC_CHECK +#if !_SUPER_RELEASE + +/// info about exe segment to investigate +struct ExeSegmentInfo +{ + int offset; + int size; +}; +TypeIsSimple(ExeSegmentInfo); + +/// the status of the client investigation +struct CompareExeClient +{ + int _dpid; + int _answer; + bool _answered; +}; + +/// Find the exe difference for given clients +struct CompareExeInvestigation +{ + /// list of segments to investigate + AutoArray _stack; + /// list of modified segments + AutoArray _modified; + /// item on the top of stack is already investigating + bool _asked; + /// the first client summary + CompareExeClient _client1; + /// the second client summary + CompareExeClient _client2; + + /// prepare structure to investigation + void Init(int dpid1, int dpid2); + /// react to the answer + void OnAnswered(int dpid, int answer); +}; + +#endif +//))EXE_CRC_CHECK + +template <> +struct ImplicitMapTraits< RefD > +{ + static RefD null; ///< Empty value (can be passed as return value). + static RefD zombie; ///< Removed value (internal usage only). + +}; + +static inline int operator % (const NetworkId &id, unsigned i) +{ + unsigned idl = (id.creator.CreatorInt()<<20)+id.id; + return idl%i; +} + +//! Delayed CreateMarker messages, init messages +struct JIPMarkerInfo +{ + Ref _marker; + int _channel; + int _roleIndex; +}; +TypeIsMovableZeroed(JIPMarkerInfo) + +struct ObjectsSpatialLayer: public RefCount +{ + typedef std::function Function; + + virtual void Add(NetworkObjectInfo *oInfo) = 0; + virtual bool Remove(Vector3Par oldPos, NetworkObjectInfo *oInfo) = 0; + virtual void ForEach( Vector3 cameraPos, const Function &function ) = 0; + ObjectsSpatialLayer(){} + virtual ~ObjectsSpatialLayer(){} + +}; + +struct ObjectsSpatialLayerWithDistance: public ObjectsSpatialLayer +{ + float _distance; + + ObjectsSpatialLayerWithDistance(float distance):_distance(distance){} +}; + +//! Network Server +class NetworkServer : public NetworkComponent +{ + friend struct DelayedMessageInfo; + friend struct NetworkObjectInfo; + +protected: + //! low-level server implementation + SRef _server; + + //! server for peer to peer mission sharing +#ifdef PEER2PEER + SRef _p2pServer; +#endif + +#if _USE_BATTL_EYE_SERVER + /// BE Integration + class BattlEye + { + //! BEVersion is used in BE init call in both Win32 and Linux sections + static const int CurrentBEIntegrationVersion = 0; + static const int MinBEVerReq = 176; + public: + enum BEInitFailedReason { BEReasonOther, BEReasonNotInstalled }; + BEInitFailedReason _initFailedReason; + protected: + /// dll handle + HMODULE _library; + bool _initialized; + + //@{ + /// callback functions + typedef void __cdecl PrintMessageF(const char *message); + typedef void __cdecl KickPlayerF(int player, const char *reason); + typedef void __cdecl ExecuteCommandF(const char *command); + static void __cdecl PrintMessage(const char *message); + static void __cdecl KickPlayer(int player, const char *reason); + static void __cdecl ExecuteCommand(const char *command); + //@} + + //@{ + /// dll functions + typedef bool __cdecl ExitF(); + typedef bool __cdecl RunF(); + typedef void __cdecl CommandF(const char *command); + typedef void __cdecl AddPlayerF(int player, unsigned long address, unsigned short port, const char *name); + typedef void __cdecl ChangePlayerStatusF(int player, int status); + typedef void __cdecl ReceivedPlayerGUIDF(int player, void *guid, int guidlen); + typedef void __cdecl PlayerGUIDIsValidF(int player, void *ownerguid, int guidlen); + typedef void __cdecl ReceivedPlayerMessageF(int player, int channel, const char *message); + typedef void __cdecl LoadedMissionF(const char *name); + +// XXX(AddWeapon, const char *netId, const char *type) \ +// XXX(AddMagazine, const char *netId, const char *type) \ + + #define BE_CALLBACKS(XXX) \ + XXX(UpdatePosition, const char *netId, float x, float y, float z, float dirX, float dirY, float dirZ, float upX, float upY, float upZ, float asideX, float asideY, float asideZ ) \ + XXX(UpdateDamage, const char *netId, float damage ) \ + XXX(PublicVariable, const char *name, const char *data) \ + XXX(AttachObject, const char *netId, const char *netIdAttachTo, int memoryIndex, float x, float y, float z) \ + + #define BE_FUNCTION_TYPE(Name, ...) typedef bool __cdecl Name##CallbackF(int player, __VA_ARGS__); + BE_CALLBACKS(BE_FUNCTION_TYPE) + + struct GamePtrStruct + { + char *pstrGameVersion; + PrintMessageF *_printMessage; + KickPlayerF *_kickPlayer; + ExecuteCommandF *_execCommand; + }; + GamePtrStruct _gameParams; + + struct BEPtrStruct + { + ExitF *_exit; + RunF *_run; + CommandF * _command; + AddPlayerF * _addPlayer; + ChangePlayerStatusF * _changePlayerStatus; + ReceivedPlayerGUIDF * _receivedPlayerGUID; + PlayerGUIDIsValidF * _playerGUIDIsValid; + ReceivedPlayerMessageF * _receivedPlayerMessage; + LoadedMissionF * _loadedMission; + + #define BE_FUNCTION_PTR(Name, ...) Name##CallbackF *_callback##Name; + BE_CALLBACKS(BE_FUNCTION_PTR) + }; + BEPtrStruct _callbacks; + + typedef bool __cdecl InitF(int iIntegrationVersion, GamePtrStruct *ppvGamePtrTable, BEPtrStruct *ppvBEPtrTable); + typedef int __cdecl GetVerF(); + //@} + + public: + BattlEye(); + ~BattlEye(); + + bool IsEnabled() const {return _library != NULL;} + + bool Init(); + void Done(); + + bool Run(const NetworkServer *server); + void Command(const char *command); + + //! BEServer.AddPlayer() needs to be called as soon as a client is connected to the server (probably right after the initial join packet - as soon as the client is registered/accepted on the server's internal player list). + void AddPlayer(int player, unsigned long address, unsigned short port, const char *name); + +/*! BEServer.RemovePlayer() will be replaced by BEServer.ChangePlayerStatus(). + - BEServer.ChangePlayerStatus() will be called with status = 1 when the player goes in-game (where AddPlayer() was previously called). + - BEServer.ChangePlayerStatus() will be called with status = 0 when the player goes back to the lobby (where RemovePlayer() was previously called). + - BEServer.ChangePlayerStatus() will be called with status = -1 when the player disconnects from the server. +*/ + void PlayerGoesInGame(int player); + void PlayerGoesInLobby(int player); + void PlayerDisconnected(int player); + + //! BEServer.ReceivedPlayerGUID() will be called as soon as the GameSpy cd-key hash is received from the client (after connecting). +#if _ENABLE_STEAM_OWNERSHIP + void PlayerGUIDReceived(int player, const CSteamID &id); +#else + void PlayerGUIDReceived(int player); +#endif + void PlayerGUIDIsValid(int player); +#if (_ENABLE_STEAM_IDENTITY && defined(_WIN64)) && !_ENABLE_STEAM_OWNERSHIP + void PlayerGUIDReceived(int player, const CSteamID &id); +#endif +#if _ENABLE_STEAM_OWNERSHIP || (_ENABLE_STEAM_IDENTITY && defined(_WIN64)) + void PlayerGUIDIsValid(int player, const CSteamID &ownerId); +#endif + + #define BE_WRAP_CALLBACK(Name, ...) bool __cdecl Name##Callback(int player, __VA_ARGS__); + BE_CALLBACKS(BE_WRAP_CALLBACK) + + //! BEServer.ReceivedPlayerMessage() will be called whenever a client sends an in-game message, so the BE Server can still + //! log the chat to the console (it extracted it from the network traffic before, but that won't be possible anymore after the network traffic scrambling/encryption is introduced). + void PlayerChatReceived(int player, int channel, const char *message); + + void LoadedMission(const char *name); + + protected: + void CleanUp() + { + _library = NULL; + _callbacks._exit = NULL; + _callbacks._run = NULL; + _callbacks._command = NULL; + _callbacks._addPlayer = NULL; + _callbacks._changePlayerStatus = NULL; + _callbacks._receivedPlayerGUID = NULL; + _callbacks._playerGUIDIsValid = NULL; + _callbacks._receivedPlayerMessage = NULL; + _callbacks._loadedMission = NULL; + #define BE_FUNCTION_INIT(Name, ...) _callbacks._callback##Name = NULL; + BE_CALLBACKS(BE_FUNCTION_INIT) + _initialized = false; + } + int GetBEVersion(HMODULE library) const; + }; + BattlEye _beIntegration; + bool BattlEyeEnabled() const + { + // for internal version we want to perform the processing even without the BE to verify it is working fine + return _ENABLE_CHEATS || _beIntegration.IsEnabled(); + } +#else + bool BattlEyeEnabled() const {return false;} +#endif + //! list of players (server specific info) + RefArray _players; + //! list of network objects (actual state) + + static NetworkId GetIdFromNetworkObjectInfo(const RefD &info) {return info->id;} + + typedef ImplicitMap, GetIdFromNetworkObjectInfo > ObjectsMap; + + struct ObjectsSpatialLayerKeyTraits + { + typedef float KeyType; + static bool IsEqual(KeyType a, KeyType b) {return a==b;} + static KeyType GetKey(const ObjectsSpatialLayerWithDistance *a) {return a->_distance;} + }; + + struct ObjectsSpatialIndex + { + typedef NetworkId KeyType; + typedef RefD TargetType; + + /// objects in bubbles stored in layers based on bubble size + FindArrayKey,ObjectsSpatialLayerKeyTraits> _layers; + /// objects with no position or no max distance are not held in layers + Ref _noLayer; + /// all objects in a hash map for easy bulk access + ObjectsMap _all; + + ObjectsSpatialLayer &Distance(float dist); + + bool get ( KeyType key, TargetType &result ) const + { + return _all.get(key,result); + } + + TargetType *get ( KeyType key ) + { + return _all.get(key); + } + const TargetType *get ( KeyType key ) const + { + return _all.get(key); + } + + bool put ( TargetType value ); + + void addToLayer( TargetType value ) + { + auto &layer = Distance(value->_updInfo._updateDistance); + layer.Add(value); + } + void removeFromLayer( Vector3Par oldPos, float oldDist, TargetType value ) + { + auto &layer = Distance(oldDist); + DoVerify(layer.Remove(oldPos,value)); + } + + void removeKey ( KeyType key ); + + + void reset (); + + template + void forEach(const Function &function) + { + _all.forEach(function); + } + + template + void forEach(const Function &function) const + { + _all.forEach(function); + } + + void forEachInBubble(Vector3 cameraPos, const ObjectsSpatialLayer::Function &function); + void onPosChanged(NetworkObjectInfo *oInfo, const NetworkObjectInfo::UpdateInfo &oldPos, const NetworkObjectInfo::UpdateInfo &newPos); + + unsigned card() const {return _all.card();} + + + ObjectsSpatialIndex(); + }; + + + FindArrayKey _indexToPlayerId; + + PlayerIndex GetPlayerIndex(int pid) const {return (PlayerIndex)_indexToPlayerId.FindKey(pid);} + + PlayerIndex CreatePlayerIndex(int pid); + + //typedef ObjectsMap ObjectsContainer; + typedef ObjectsSpatialIndex ObjectsContainer; + + ObjectsContainer _objects; + + + static NetworkId GetIdFromDeletedNetworkObjectInfo(const NetworkDeletedObjectInfo &info) {return info.id;} + + typedef ImplicitMap DeletedObjectsContainer; + + //! info about objects deleted, until deletion is confirmed by the owner + DeletedObjectsContainer _deletedObjects; + + //! original name of current mission + RString _originalName; + + //! no other players are enabled to connect + bool _sessionLocked; + + //! password protected session + bool _password; + + //! equal mod list required by host + bool _equalModRequired; + + //! data signatures required + bool _verifySignatures; + + //! the least buildNo the server accepts + int _buildNoRequired; + + /// level od CD key security required + int _secureIdRequired; + + /// validate CD Key using GameSpy SDK + bool _validateCDKey; + + /// do not report session to GameSpy matchmaking + bool _doNotReport; + + // InitQR was called (so SimulateQR should not call QR sdk) + bool _qrInitDone; + + /// allow persistent missions - continue even when no players are connected + bool _persistent; + + /// destroy body of disconnected players + bool _destroyDisconnected; + + mutable int _longitude; + mutable int _latitude; + + bool _longLatAuto; + +#if _ENABLE_STEAM_MATCHMAKING + // ports for Steam services + int _steamPort; + int _steamQueryPort; +#endif + + struct GeoJobThread + { + SIGNALED_OBJECT _thread; + Future _longitude; + Future _latitude; + RString _ip; + GeoJobThread() : _thread(NoInitHandle) {} + }; + mutable SRef _geoJob; + + static DWORD WINAPI GeoJobThreadFunction(void *ctx); + +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + //! DirectPlay ID of logged gamemaster (AI_PLAYER if no gamemaster) + int _gameMaster; + //! selected mission name + RString _mission; + //! selected mission cadet / veteran mode + int _difficulty; + + //! gamemaster is only voted admin (cannot do shutdown etc.) + bool _admin; + + //! kick off players with duplicate ID + bool _kickDuplicate; + + //! is server dedicated + bool _dedicated; + //! server is asked to restart mission + bool _restart; + //! server is asked to reassign players + bool _reassign; + //! index of next mission in dedicated server config file + int _missionIndex; + //! preloaded dedicated server config file + ParamFile _serverCfg; + + //@{ + //! Info about network trafic on dedicated server + float _monitorInterval; + DWORD _monitorNext; + int _monitorFrames; + int _monitorIn; + int _monitorOut; + //@} + + DWORD _debugNext; + float _debugInterval; + //! switched on debug flags + FindArrayKey _debugOn; + + //! messages of the day + AutoArray _motd; + //! messages of the day interval + float _motdInterval; + + //! URL of Query & Reporting master server + RString _reportingIP; + + /// evaluator for (dedicated) server scripts + GameState _evaluator; + /// global variables for _evaluator + GameDataNamespace _globals; + + /// SDZ_SQF_EXEC: scripts coming from #exec are queued and evaluated after the + /// network messages of the current frame have been processed. Running arbitrary + /// SQF in the middle of message handling touched half-updated object lists and + /// corrupted the script heap (server crashed with no RPT message). + AutoArray _sqfExecQueue; + AutoArray _sqfExecFrom; + bool _sqfExecBusy; + //! event handlers + RString _eventHandlers[NServerEvent]; + +#else + static const bool _dedicated = false; +#endif +//} + + //! time when next ping status should be broadcast + DWORD _pingUpdateNext; + + //! full path to mission pbo file + RString _missionBank; + + //! global (static) ban list + FindArray _banListGlobal; + //! local (dynamic) ban list + FindArray _banListLocal; + + struct KeyListSecure + { + FindArray keys; // blocked keys list + AutoArray signature; // signature of a blocked keys list + } _banListSecure; + + //! actually tested identities (squad competence) + AutoArray< SRef > _squadChecks; + DWORD _squadChecksTimeout; + + //! next available (short) id for player + int _nextPlayerID; + + //! votings currently in progress + Votings _votings; + + /// overall game de-sync - aggregated from all clients + ConnectionDesync _connectionDesync; + + //@{ last valid result from _desyncTotal + float _desyncTotalAvg; + float _desyncTotalMax; + //@} + + /// aggregate de-sync stats for all clients + CalculateMinMaxAvg _desyncTotal; + + /// time when _desyncTotal was last averaged + DWORD _desyncTotalUpdateNext; + + //! threshold for votings + float _voteThreshold; + + //! address of proxy server + RString _proxy; + + //! current server state + NetworkServerState _serverState; + + /// how long is the server state stable + DWORD _serverStateTime; + + /// what timeout value was reported to the clients + int _serverTimeOutSent; + + //! network messages, needed to send to joining player + AutoArray _initMessages; + + //! Marker messages, needed to send to joining player + AutoArray _jipMarkerInfos; + +#if _ENABLE_CHEATS + //! debugging window + Link _debugWindow; +#endif + + int _totalSlots; + + /// last time when timeleft was reported to matchmaking + DWORD _timeLeftLastTime; + /// last value reported to matchmaking + int _timeLeftLastValue; + + /// last value reported to broadcast / QoS + int _timeLeftLastValueBcast; + + /// absolute limit of max. players allowed + int _maxPlayersLimit; + + /// 0 for enable, 1 for disable (configurable in server.cfg by disable3rdPerson entry) + int _disable3rdPerson; + + /// time multiplier for environment + float _environmentTimeMul; + + //! time synchronized to clients + DWORD _serverTime; + DWORD _serverTimeInitTickCount; + DWORD _serverTimeOfEstimatedEnd; + int _secondsToEstimatedEnd; + static const int ServerTimeUpdateInterval = 300*1000; // 5 minutes + DWORD _nextServerTimeUpdate; + +//((EXE_CRC_CHECK +#if !_SUPER_RELEASE + CompareExeInvestigation _exeInvestigation; +#endif +//))EXE_CRC_CHECK + +#if _VBS2 && _VBS2_LITE + bool _memoryWrite; + DWORD _nextRanUpdate; +#endif + +public: + //! Constructor + NetworkServer(NetworkManager *parent, RString name, RString password, int maxPlayers, int port, bool isPrivate); + //! Destructor + ~NetworkServer(); + + int GetSessionPort() const {return _server ? _server->GetSessionPort() : 0;} + + int NextPlayerId() {return _nextPlayerID++;} + + //! Creation of DirectPlay server and MP session + /*! + \param port IP port where server communicate + \param password session password + */ + bool Init(RString name, RString password, int maxPlayers, int port); + //! Destroying of MP session and DirectPlay server + void Done(); + + void InitVoice(); + + //! Create debugging window + void CreateDebugWindow(); + + //! Kick off given player from game + void KickOff(int dpnid, KickOffReason reason, const char *reasonStr=NULL); + //! Ban given player (kick off + add to dynamic ban list) + void Ban(int dpnid); + + void UpdateBanListSecure(const FindArray &keys, const Array &signature); + + //! Return if session was created + bool IsValid() const {return _server != NULL;} + + bool IsDedicatedBotClient(int dpnid) const; + + bool IsLocalClient(int client) const + { + // Assume bot client is always local + return client == BOT_CLIENT; + } + + void RptFObjectIdJournal(const NetworkId &id); + void RptFObjectNotFound(const NetworkId &id, const char *msg, int from); + void RptFObjectNotFound(const NetworkId &id, NetworkMessageType type, int from, const char *context = nullptr); + + void UpdateMaxPlayers(int maxPlayers, int privateSlots); + +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + //! Mark server as dedicated + /*! + \param config name (path) of config file + */ + bool SetDedicated(RString config); + + /// add specific server scripting commands to the _evaluator + void InitEvaluator(); + /// SDZ_SQF_EXEC: queue an expression received through #exec + void QueueExec(int from, RString expression); + /// SDZ_SQF_EXEC: evaluate (and answer) every queued expression + void ProcessQueuedExec(); + + void ProfileAnswer(const RString &output); +#endif +//} + //! force data signatures checking + void SetVerifySignatures(int reqVersion); + + //! verify signature of the single file based on bank index (DataSignatureCheck) + void CheckSignature(int dpnid, int fileIndex, int level); + + //! verify signature of the single file based on filename (FileSignatureCheck) + void CheckSignature(int dpnid, RString filename, RString prefix, int level); + + //! signature check test with index=-1 was started and NetworkPlayerInfo::signatures are to be collected + void InitSignatureCollecting(NetworkPlayerInfo *info); + + //! List of acceptedKey names in the form key1;key2;key3... + //! When nonzero param 'maxLen', the return value has at most maxLen+4 chars. When truncated, the last one is ";..." + RString GetSignaturesList(int maxLen=0); + + //! Get the hash precalculated during server initial banks load + bool MyHash(Temp &hash, RString prefix, int sigVer, int level); + + //! disable/enable connecting of further clients + void LockSession(bool lock = true) + { + if (_sessionLocked != lock) + { + _sessionLocked = lock; + UpdateMatchmakingDescription(false); + _server->UpdateLockedOrPassworded(_sessionLocked, _password); + } + } + + //! Retrieves URL of server + void OnPublicAddressKnown(int ip); + + bool GetURL(char *address, DWORD addressLen); + int BuildNoRequired() { return _buildNoRequired; } + + int SecureIdRequired() {return _secureIdRequired;} + + //! Creates pbo file for selected mission + void CreateMission(RString mission, RString world); + //! Store name of pbo file for selected mission + void SetOriginalName(RString name) {_originalName = name;} + // force the _param1, _param2 and _paramsArray to contain undefined values, so InitMission will rewrite these by mission defaults + void UndefMissionParams(); + //! Initialize mission + /*! + - create and send mission header structure (including difficulty settings) + */ + void InitMission(int difficulty, RString displayName, bool noCopy, RString owner, bool isCampaignMission); + + void KickAllPlayers(int minBuild=0); + + bool DBSave(RString baseURL, int dpnid, RString request); + void DBLoad(RString baseURL, int playerId, GameDataCode *code); + void DBLoad(RString baseURL, int playerId, RString playerUID, GameDataCode *code); + + void OnDraw(); + void OnSimulate(); + void OnSimulateDone(); + + /// time critical network update - need to be called several times in frame + void FastUpdate(); + void OnCreatePlayer(int player, bool privateSlot, const char *name, unsigned long inaddr); + InputInterface *GetInputInterface(int player); + bool OnCreateVoicePlayer(int player); + void OnMessage(int from, NetworkMessage *msg, NetworkMessageType type); + + void ChangeOwnerFinal( NetworkObjectInfo * oInfo, int from, NetworkId &id ); + + + void SpawnForPlayer(int dpnid, GameDataCode *code, const GameValue &args); + +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) + void PlayerGUIDReceived(int player, const CSteamID &id) { +#if _USE_BATTL_EYE_SERVER + _beIntegration.PlayerGUIDReceived(player, id); +#endif + } + void PlayerGUIDIsValid(int player, const CSteamID &ownerId) { +#if _USE_BATTL_EYE_SERVER + _beIntegration.PlayerGUIDIsValid(player, ownerId); +#endif + } +#endif + + //! The output format is "creator:id friendlyName" + RString NetworkIdToNetIdFriendly(const NetworkId &id); + + #if _ENABLE_DEDICATED_SERVER + void DoReassign(); + void DoReassignDirect(); + void DoMissions(bool admin); +#endif + + /// remove initMessages overridden by this one + void AddInitAndRemoveOverridden(NetworkMessageType type, NetworkMessage * msg, int **updateI=NULL); + /// get diagnostics statistics about initMessages + RString GetAddInitAndRemoveOverriddenStat(); + /// remove initMessages related to a deleted object + void RemoveInitObjectDeleted(NetworkId obj); + + void AddJIPMarkerInfo(NetworkMessage *marker, int channel, int from); + void RemoveJIPMarkerInfo(RString name); + + //! perform regular memory clean-up + unsigned CleanUpMemory(); + + /// called before network shutdown is initiated - can be called multiple times + void OnClose(); + + //! Process received system messages + void ReceiveSystemMessages(); + //! Process received user messages + void ReceiveUserMessages(); + //! Destroy all received system messages + void RemoveSystemMessages(); + //! Destroy all received user messages + void RemoveUserMessages(); + //! Get position of randomly chosen player + Vector3 RandomPlayerPos() const; + //! Perform all active integrity investigations + void PerformIntegrityInvestigations(); + + DWORD SendMsg + ( + int to, NetworkSimpleObject *object, NetMsgFlags dwFlags + ); + + + //! Send single network message + /*! + This function determine, whic type of send will be used - local send, agregation or send using DirectPlay + \param to DirectPlay ID of message receiver + \param msg message itself + \param type type of message + \param dwFlags DirectPlay flags + */ + DWORD SendMsg + ( + int to, NetworkMessage *msg, + NetworkMessageType type, NetMsgFlags dwFlags, + NetworkPlayerObjectInfo *poInfo + ); + + virtual DWORD SendMsg + ( + int to, NetworkMessage *msg, + NetworkMessageType type, NetMsgFlags dwFlags + ) + { + return SendMsg(to, msg, type, dwFlags, NULL); + } + + Ref DXSendMsg(int to, NetworkMessageRaw &rawMsg, DWORD &msgID, NetMsgFlags dwFlags, const Ref &dependOn); + + //! Retrieve list of players + void GetPlayers(AutoArray &players); + + /// ask for item UI invocation + void UseItem(Person *person, InventoryItem *item); + + //! Return connection quality to server + ConnectionDesync GetConnectionDesync() const {return _connectionDesync;} + + NetworkMessageFormatBase *GetFormat(/*int client, */int type); + const NetworkMessageFormatBase *GetFormat(/*int client, */int type) const; + + void OnChangedOnPlayerConnecting(GameValuePar codeValue); + + //! Set current server state and send to clients + void SetServerState(NetworkServerState state); + //! Return client state for given player + NetworkClientState GetClientState(int dpnid); + //! Return name for given player + RString GetPlayerName(int dpid); + //! Return camera position for given player + Vector3 GetCameraPosition(int dpid); + + NetworkId GetPlayerPerson(int dpid); + Object *GetPlayerTarget(int dpid); + + void ServerSelectPlayer(int dpid, const NetworkId &id); + + /// Return the IP address of the connected client + bool GetClientAddress(int client, sockaddr_in &address); + + NetworkObject *GetObject(const NetworkId &id); + + //! Unregister all objects + void DestroyAllObjects(); + + //! Send mission pbo file to clients + /*! + \param dpnid client, server will send mission to (0 for all clients) + */ + void SendMissionFile(int dpnid = 0); + + //! Calculate bandwidth estimation to given client + int GetBandwidthEstimation(int dpnid, int nPlayers); + + const char *GetDebugName() const {return "Server";} + + RString GetDiagText(const NetworkId &id) const; + + + //! Client has sent her bankCount. Detect whether it differs to the previously sent value. + void UpdatePlayerBankCount(NetworkPlayerInfo *info, int bankCount); + //! Report Wrong signatures (write also a line inside DS log window) + // @param report used for additional info + void ReportWrongSignatures(int from, RString filename, const NetworkPlayerInfo *info, RString report=RString()); + + //! Creates player identity + /*! + Called asynchronously when identity is confirmed + \param ident player identity + \param squad player's squad + */ + void CreateIdentity(PlayerIdentity &ident); + + //! Process result of voting when voting is valid + /*! + \param id unique identification of voting + \param value voted value + */ + void ApplyVoting(const AutoArray &id, const AutoArray *value); + + //! some admin state change - scan admin status of all players + void UpdateAdminState(); + + //! Delete player info (unregister player) + void OnPlayerDestroy(int dpid); + + //! Set estimated end of mission time + /*! + \param time estimated time + */ + void SetEstimatedEndTime(Time time); + + /// read to time left estimation + int GetSessionTimeLeft() const; + + //! Return absolute limit of max. players allowed + /** does not include virtual slot on ded. server */ + int GetMaxPlayersLimit() const {return _maxPlayersLimit;} + + /// Return maximal number of players according to bandwidth estimation + /** does not include virtual slot on ded. server */ + int GetMaxPlayersSafe(int bandwidthPerClient, int round) const; + + //! Return maximal allowed number of players on server based on mission and user settings + /** does include virtual slot on ded. server */ + int GetMaxPlayers() const; + + //! Return name of mission pbo file on server to optimize transfer to bot client + RString GetMissionFilename() const {return _missionBank;} + + //! When player joined to game + Time GetPlayerJoined(int dpid) const; + + //! Find info about given player + NetworkPlayerInfo *GetPlayerInfo(int dpid); + +//((EXE_CRC_CHECK +#if !_SUPER_RELEASE + /// Find the exe difference for given clients + void CompareExe(int dpid1, int dpid2) {_exeInvestigation.Init(dpid1, dpid2);} +#endif +//))EXE_CRC_CHECK + + /// Find owner of given network object (used in scripted function owner) + int GetOwner(const NetworkId &id) const; + /// Change owner of given network object (used in scripted function setOwner) + bool SetOwner(const NetworkId &id, int clientId); + + bool StatusChat(int clientId, RString text, RString colorClass); + + void OnRejectChanged(const NetworkId &id, NetworkMessageClass cls, bool reject); + + void OnHierParentChange( Entity* veh ); + +protected: + //! Create player info (register player) + NetworkPlayerInfo *OnPlayerCreate(int dpid, bool privateSlot, const char *name, unsigned long inaddr); + //! Force state change for given client + void SetClientState(int dpnid, NetworkClientState state); + +#if _ENABLE_DEDICATED_SERVER + // select game master on dedicated server + void SetGameMaster(int player, bool admin); + + /// set event handler + void SetEventHandler(RString name, RString value); + /// process event handler (return if the event was handled) + bool OnEvent(ServerEvent event, float par); + /// process event handler (return if the event was handled) + bool OnEvent(ServerEvent event, float par1, float par2); + /// process event handler (return if the event was handled) + bool OnEvent(ServerEvent event, float par1, RString par2); +#endif + + /// Find owner of given network object + int FindOwner(const NetworkId &id); + + //! Find info about given network object + NetworkObjectInfo *GetObjectInfo(const NetworkId &id) const; + //! Create object info (register object) + NetworkObjectInfo *OnObjectCreate(const NetworkId &id, int owner, NetworkMessage *msg, NetworkMessageType type); + //! Delete object info (unregister object), return owner id + int PerformObjectDestroy(const NetworkId &id); + //! Delete object info (unregister object) and send message about destruction + void OnObjectDestroy(const NetworkId &id, int from); + + Vector3 GetObjectPosition( NetworkId obj ); + + + //! Called when update message received + /*! + \param id network object ID + \param from sender DirectPlay ID + \param msg update message + \param type update message type + \param cls update message class + */ + NetworkObjectInfo *OnObjectUpdate(NetworkId &id, int from, NetworkMessage *msg, NetworkMessageType type, NetworkMessageClass cls); + + void RescanBestPosition( NetworkObjectInfo * oInfo ); + + void UpdateChildrenPos(const Entity * veh); + + bool CheckBestPositionIntegrity() const; + //! Send update message + /*! + \param pInfo info about receiving player + \param oInfo info about object to update + \param cls update message class + \param dwFlags DirectPlay flags + */ + int UpdateObject(NetworkPlayerInfo *pInfo, NetworkObjectInfo *oInfo, NetworkMessageClass cls, NetMsgFlags dwFlags); + + //! Calculate time error (message fading) between two stored states (messages) + /*! + \param type update message type + \param msg1 first message + \param msg2 second message + */ + float CalculateErrorTime + ( + NetworkMessageType type, NetworkMessage *msg1, NetworkMessage *msg2 + ); + + //! Owner of some object changes + /*! + \param id ID of network object + \param from DirectPlay ID of old owner + \param to DirectPlay ID of new owner + */ + void ChangeOwner(const NetworkId &id, int from, int to); + + //! Send mission info (mission heade, side slots and role slots) to client + /*! + \param DirectPlay ID of receiving client + \param onlyPlayers do not send mission header + */ + void SendMissionInfo(int to, bool onlyPlayers = false); + + //! Send all agregated and update messages + void SendMessages(); + //! Check if fade out players are to kicked off + void CheckFadeOut(); + //! Calculate limits for message sending + void EstimateBandwidth(NetworkPlayerInfo &pInfo, int nPlayers, int &nMsgMax, int &nBytesMax); + //! Calculate errors and place object in list sorted by error + /*! + \param objects output sorted list of objects + \param pInfo info about receiving player + */ + void CreateObjectsList(AutoArray &objects, NetworkPlayerInfo &pInfo); + + void OnStopUpdating( NetworkObjectInfo &oInfo, NetworkPlayerInfo &pInfo, NetworkPlayerObjectInfo &poInfo); + + //! Prepare next object update message to message queue + bool PrepareNextUpdate(NetworkPlayerInfo &pInfo, AutoArray &objects, int &next); + + //! Dedicated server simulation + void SimulateDS(); + + void SimulateMonitor( DWORD tickCount ); + + /// broadcast current mission voting status to all clients + void MissionVotingEcho(); + /// check time out for current server state + bool CheckTimeOut(int readyCount, int totalCount, DWORD ready, DWORD notReady); + + /// check how much players is need to consider the server to be full + int PlayerServerFull() const; + + //! Show message in both console and chat + void ServerMessage(const char *text); + + //! Show client-side localized message in both console and chat + void ServerMessage(const LocalizedFormatedString &text); + + //! Find players on chat channel + /*! + \param players output array of players + \param units chat target units + \param from DirectPlay ID of sender + \param voice true for Voice Over Net transfer + */ + void GetPlayersOnChannel(AutoArray &players, AutoArray units, DWORD from, bool voice); + //! Find players on chat channel + /*! + \param players output array of players + \param channel chat channel + \param from DirectPlay ID of sender + \param voice true for Voice Over Net transfer + */ + void GetPlayersOnChannel(AutoArray &players, int channel, DWORD from, bool voice); + + /// check if given player in out of game (dead, or in the lobby) + bool CheckPlayerInLobby(const NetworkPlayerInfo &info) const; + /*! + \name GameSpy Query & Reporting SDK support + */ + //@{ +//{ QUERY & REPORTING SDK +#if _ENABLE_GAMESPY + //! Close Query & Reporting SDK support + void DoneQR(); + //! Simulation step of Query & Reporting SDK support + void SimulateQR(); + //! Information about change of inner game state + void ChangeStateQR(); +public: + //! Initialize Query & Reporting SDK support + void InitQR(bool isPrivate); + + void ProcessGeoJob() const; + void CloseGeoJob() const; + + /// Called when a server key needs to be reported + void OnQueryServer(int keyid, qr2_buffer_t outbuf); + /// Called when a player key needs to be reported + void OnQueryPlayer(int keyid, int index, qr2_buffer_t outbuf); + /// Called when a team key needs to be reported + void OnQueryTeam(int keyid, int index, qr2_buffer_t outbuf); + /// Called when we need to report the list of keys we report values for + void OnQueryKeys(int keytype, qr2_keybuffer_t keybuffer); + /// Called when we need to report the number of players and teams + int OnQueryCount(int keytype); + + /// validate CD Key using GameSpy SDK + bool ValidateCDKey() const { return _validateCDKey; } + +#if _VERIFY_CLIENT_KEY + /// called when autorization of CD Key finished + void OnCDKeyAuthorize(int player, int authenticated, const char *errmsg); +#endif + +#elif _ENABLE_STEAM_MATCHMAKING +public: + /// Initialization of Steamworks SDK server reporting interface + void InitSteam(); + /// Steamworks SDK server reporting interface clean up + void DoneSteam(); + /// Simulation of Steamworks SDK callbacks + void SimulateSteam(); + /// Inform Steam master server about the change of the inner game state + void ChangeStateSteam(); +#if _ENABLE_DEDICATED_SERVER + /// Reset TimeAlive Statistics + void ResetCharacterTimeAlive(AIBrain *unit); +#endif + + #if _ENABLE_STEAM_OWNERSHIP && _USE_BATTL_EYE_SERVER + void PlayerGUIDReceived(int player, const CSteamID &id) {_beIntegration.PlayerGUIDReceived(player, id);} + #endif + + // Tells us when we have successfully connected to Steam + STEAM_GAMESERVER_CALLBACK(NetworkServer, OnSteamServersConnected, SteamServersConnected_t, _callbackSteamServersConnected); + // Tells us when there was a failure to connect to Steam + STEAM_GAMESERVER_CALLBACK(NetworkServer, OnSteamServersConnectFailure, SteamServerConnectFailure_t, _callbackSteamServersConnectFailure); + // Tells us when we have been logged out of Steam + STEAM_GAMESERVER_CALLBACK(NetworkServer, OnSteamServersDisconnected, SteamServersDisconnected_t, _callbackSteamServersDisconnected); + // Tells us that Steam has set our security policy (VAC on or off) + STEAM_GAMESERVER_CALLBACK(NetworkServer, OnPolicyResponse, GSPolicyResponse_t, _callbackPolicyResponse); + +protected: +#endif +//} + //@} + + //! Update session description server sending via LAN broadcast + void UpdateSessionDescription(); + + //! Update session description server sending via both mathmaking and LAN broadcast + void UpdateMatchmakingDescription(bool changedParams); + + void SendMuteList(const PlayerIdentity &id); + + void EnqueueMsg(int to, NetworkMessage *msg, NetworkMessageType type, NetworkPlayerObjectInfo *poInfo); + void EnqueueMsgNonGuaranteed(int to, NetworkMessage *msg, NetworkMessageType type, const RefR &dependOn); + +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + //! Set interval in which dedicated server sends info about transfer rates to gamemaster + void Monitor(float interval); + void OnMonitorIn(int size); + +public: + void DebugAsk(RString str); +protected: + void DebugAnswer(RString str); + + int ConsoleF(const char *format, ...); +#else + int ConsoleF ( const char *format, ... ){return 0;} +#endif +//} + + void OnMessageClientInput(int from, NetworkMessageType type, NetworkMessageContext &ctx); + + //! Client state changed + void OnClientStateChanged(int dpnid, NetworkClientState state); + + void ObjectUpdateAll(NetworkObjectInfo * info, int dpnid, NetMsgFlags dwFlags); + + //! Check if dpnid and sender are on the same channel + bool IsPlayerOnChannel(int dpnid, int channel, int roleIndex2); + + //! Send init messages to JIP player, handle special messages + void SendInitMessages(int dpnid); + + void OnPlayerConnecting(int dpnid); + void OnPlayerConnecting(int dpnid, GameValuePar codeValue); + + /// update server database when player leave mission + void DisconnectPlayer(int dpnid, NetworkId playerPerson); + + /// calculate how important is given object to given player + float CalculateErrorCoef(const NetworkPlayerInfo &pInfo, const NetworkObjectInfo &oInfo, bool updating); + + void SendCreateMessage( int dpnid, NetworkObjectInfo &info, NetworkPlayerObjectInfo *poInfo ); + + /// event handler - wrongly signed data or signature check question timed out + void OnHackedData(HackType type, int dpid, RString filename); + +#if _VERIFY_KEY + /// event handler - two players with the same CD-KEY + void OnDoubleIdDetected(const PlayerIdentity &newIdentity, const PlayerIdentity &oldIdentity); +#endif + + /// execute corresponding event handler for all players + void CallOnPlayerDisconnected(); + + /// execute corresponding event handler for a signle players + void OnPlayerDisconnected(NetworkPlayerInfo *info); +public: + /// report hacked data of given player + bool ProcessHackedData(NetworkPlayerInfo &pi); + +private: + // recursive traversal of messages to set correct owner of owned items + void CheckItemsOwner(const NetworkMessageUpdateVehicleAI *msg, int newOwner); + void CheckItemOwner(const NetworkId &id, int newOwner); + + + +}; + +class ReportHackedData : public CheckSignatureTimeoutFunc +{ + NetworkPlayerInfo &_pi; + NetworkServer &_server; +public: + ReportHackedData(NetworkPlayerInfo &pi, NetworkServer &server) : _pi(pi) , _server(server) {} + bool operator ()(); +}; + +/////////////////////////////////////////////////////////////////////////////// +// Network Manager + +TypeIsSimple(INetworkUpdateCallback *) + +//! Implementation of basic network functions +class NetworkManager : public INetworkManager +{ +friend class NetworkComponent; + +protected: + SRef _sessionEnum; + //! time of last call of EnumHosts + UITime _lastEnumHosts; + //! IP address of computer (empty for local network) where search for sessions + RString _ip; + //! port where search for sessions + int _port; + //! additional remote hosts + AutoArray _hosts; + + //! enable creation of physical world + bool _physEnabled; + + //! network server component + SRef _server; + //! network client component + SRef _client; + //! voice over net disabled + bool _disableVoN; + //! voice over net codec quality for encoding + int _vonCodecQuality; + //! log file for dedicated server can be specified in server.cfg by entry logFile + RString _dedServerLogFileName; + FILE *_dedServerLogFile; + + +#if _ENABLE_MP && (!_GAMES_FOR_WINDOWS) + // TODO: Unify X360 / PC mute list handling + MuteListMessage _muteList; +#endif + + float _pendingInvitationX; + float _pendingInvitationY; + float _pendingInvitationW; + float _pendingInvitationH; + + Ref _cqPoorTexture; + Ref _cqBadTexture; + Ref _cqDesyncLow; + Ref _cqDesyncHigh; + + //! voice communicator connected + bool _isVoice; + + //! whether Done was already called in Binarize at the end before destructor + bool _disableDone; + + FindArray _updateCallbacks; + +#if _ENABLE_GAMESPY + bool _trackUsageDone; +#endif + + /// request to disable voice + EDisableVoiceRequest _disableVoiceRequest; + /// time when the request was set + UITime _disableVoiceRequestTime; + + /// helper to enable asynchronous save / load in singleplayer + AsyncDBStorage _spStorage; + +public: + //! Constructor + NetworkManager(); + //! Destructor + ~NetworkManager(); + + bool IsServer() const override {return _server != nullptr;} + //! Return if client is created + bool IsClient() const override {return _client != nullptr;} + + void DisablePhysics() override {_physEnabled = false;} + bool IsPhysicsMaster() const override {return IsServerOwner() && _physEnabled;} + virtual bool IsPhysicsEnabled() const override {return _physEnabled;} + + bool IsServerOwner() const override {return _server != nullptr || _client==nullptr;} + bool IsMultiplayer() const override {DoAssert(_server == nullptr || _client!=nullptr); return _client!=nullptr;} + + NetworkServer *GetServer() const {return _server;} + + int RequiredBuildNo() { return (_server!=NULL) ? _server->BuildNoRequired() : 0; } + + //! Access to server component + NetworkServer *GetServer() {return _server;} + //! Access to client component + NetworkClient *GetClient() {return _client;} + + virtual void TrackUsage(); + + bool VoiceReady() const; + + //! return if voice communicator is connected + bool IsVoice() const {return _isVoice;} + //! Return if player is voice banned + bool IsVoiceBanned() const; + //! return if voice over net is disabled + bool IsVoNDisabled() const {return _disableVoN;} + //! set whether voice over net is disabled + void SetVoNDisabled(bool val) {_disableVoN=val;} + //! return the log File for Dedicated server (entry logFile in server.cfg) + RString GetDedicatedServerLogFileName() { return _dedServerLogFileName; } + FILE *GetDedicatedServerLogFile(); + void CloseDedicatedServerLogFile() { if (_dedServerLogFile) { fclose(_dedServerLogFile); _dedServerLogFile=NULL; } } + //! VoN codec quality for encoding + int VoNCodecQuality() const { return _vonCodecQuality; } + //! VoN codec quality for encoding (should propagate into VoNRecorder too) + void SetVoNCodecQuality(int quality); + + bool Init(RString ip, int port, bool startEnum = true); + void Init(); + void DisableDone() { _disableDone=true; } + + void Done(); + void RemoveEnumeration(); + + bool IsVoicePlaying(int dpnid) const; + bool IsVoiceRecording() const; + int CheckVoiceChannel(int dpnid, bool &audible2D, bool &audible3D) const; + void IsVoice2D3DPlaying(int dpnid, bool &audible2D, bool &audible3D) const; + + void SetVoiceON(); + void SetVoiceOFF(); + void SetVoiceToggleOn(bool value); + /// sets threshold for silence analyzer (0.0f - 1.0f) + void SetVoNRecThreshold(float val); + void SetVoNTransmitterFreq(float f) override; + float GetVoNTransmitterFreq() const override; + void SetVoNTransmitterRange(float range) override; + float GetVoNTransmitterRange2() const override; + void WhatUnitsOnTransmitterChannel(RefArray &units) override; + void SetVoiceCapture(bool value); + //! request disabling of voice + virtual void SetDisableVoiceRequest(EDisableVoiceRequest request); + + +#if _ENABLE_CHEATS + void VoNSay(int dpnid, int channel, int frequency, int seconds); +#endif + + void CustomFilesProgressClear(); + void CustomFilesProgressGet(int &max, int &pos); + DWORD GetServerTime(); + DWORD GetEstimatedEndServerTime(); + void PlayerGUIDIsValid(int player, const CSteamID &ownerId) override; + + +#if _GAMES_FOR_WINDOWS + + virtual SessionType GetSessionType() const {return _sessionType;} + + /// returns if any session exists + virtual bool SessionExists() const {return _sessionHandle != NULL;} + + virtual bool IsSignedIn() const {return true;} + + // Appear offline implemented by Xbox Guide on Xbox 360 + void Cloak(bool set = true) {} + bool IsCloaked() const {return false;} + + void DisableVoice(bool disable); + +#else + bool IsSignedIn() const {return false;} + void Cloak(bool set = true) {} + bool IsCloaked() const {return false;} + + void DisableVoice(bool disable) {} +#endif + + bool IsPlayerInMuteList(const XUID &xuid) const; + void UpdateMuteList(); + void TogglePlayerMute(const XUID &xuid); + + void SetPendingInvitationPos(RString resource); + +public: + bool IsSystemLink() const {return _sessionEnum != NULL;} + + void GetSessions(AutoArray &sessions); + RString IPToGUID(RString ip, int port); + bool CreateSession(SessionType sessionType, RString name, RString password, int maxPlayers, bool isPrivate, int port, bool dedicated, RString config, int playerRating); + + void UpdateMaxPlayers(int maxPlayers, int privateSlots) override; + int GetMaxPlayersLimit() const override; + int GetMaxPlayersSafe(int requiredPerClient, int round) const; + + ConnectResult JoinSession(SessionType sessionType, RString guid, RString password) override; + + const SessionInfo WaitForSession() override; + void GetPlayers(AutoArray &players) override; + void CreateMission(RString mission, RString world); + void SetOriginalName(RString name); + void InitMission(int difficulty, RString displayName, bool noCopy, RString owner, bool isCampaignMission); + void KickAllPlayers(int minBuild=0); + + void Close(); + unsigned CleanUpMemory(); + + int GetMaxMissionPlayers() const; + + void CreateServerDebugWindow(); + void CreateClientDebugWindow(); + + void KickOff(int dpnid, KickOffReason reason); + void Ban(int dpnid); + void LockSession(bool lock = true); + + void OnSimulate(); + void OnSimulateDone(); + + void FastUpdate(); + void RegisterUpdateCallback(INetworkUpdateCallback *callback); + void UnregisterUpdateCallback(INetworkUpdateCallback *callback); + void OnDraw(); + + NetworkServerState GetServerState() const; + int GetServerTimeout() const; + void SetServerState(NetworkServerState state); + + NetworkClientState GetClientState() const; + void SetClientState(NetworkClientState state); + + bool GetTransferProgress(float &progress) const; + + void OnJoiningInProgress(); + + void OnChangedOnPlayerConnecting(GameValuePar codeValue) override; + + int TimeElapsed() const; + + NetworkClientState GetClientState(int dpnid) const; + + bool IsGameMaster() const; + bool IsAdmin() const; + ConnectionQuality GetConnectionQuality() const; + ConnectionDesync GetConnectionDesync() const; + void GetParams(float ¶m1, float ¶m2) const; + float GetParams(int index) const; + AutoArray GetParamsArray() const; + void SetParams(float param1, float param2, bool updateOnly); + void SetParams(float param1, float param2, AutoArray paramsArray, bool updateOnly); + void SetParam(float param, int index, bool updateOnly); + const MissionHeader *GetMissionHeader() const; + int GetPlayer() const; + CreatorId GetCreatorId() const; + + const PlayerIdentity *FindIdentity(int dpnid) const; + const PlayerIdentity *FindIdentityByPlayerId(int playerId) const; + const AutoArray *GetIdentities() const; + + virtual bool DBSave(RString baseURL, int dpnid, RString request) override; + + virtual bool DBSave(RString baseURL, RString uid, RString request) override; + virtual bool DBQueue(RString baseURL, RString uid, RString request) override; + virtual bool DBKill(RString baseURL, RString uid) override; + + virtual bool DBItemDrop(RString baseURL, RString request) override; + + virtual void DBLoad(RString baseURL, int playerId, GameDataCode *code) override; + virtual void DBLoad(RString baseURL, int playerId, RString playerUID, GameDataCode *code) override; + + virtual InputInterface *GetInputInterface(int player) override; + virtual RString GetDiagText(const NetworkObject *obj) const override; + + void SelectPlayer(int player, Person *person, bool respawn = false); + void SendSelectPlayer(int dpid, Person *person); + void PlaySound + ( + RString name, Vector3Par position, Vector3Par speed, + float volume, float freq, AbstractWave *wave + ); + void SoundState(AbstractWave *wave, SoundStateType state); + RString GetPlayerName(int dpid) override; + Vector3 GetCameraPosition(int dpid) override; + NetworkId GetPlayerPerson(int dpid) override; + virtual Object *GetPlayerTarget(int dpid) override; + void ServerSelectPlayer(int dpid, Person *person) override; + NetworkObject *GetObject(const NetworkId &id) override; + int GetOwner(const NetworkId &id) const override; + bool SetOwner(const NetworkId &id, int clientId) override; + bool StatusChat(int clientId, RString text, RString colorClass=RString()); + bool CreateVehicle(Vehicle *veh, VehicleListType type, RString name, int idVeh); + bool CreateSubobject(Vehicle *veh, TurretPath &path, NetworkObject *object); + bool CreateObject(NetworkObject *object, bool setNetworkId=true); + void CreateAllObjects(); + void DeleteObject(const NetworkId &id); + void DestroyAllObjects(); + void AskForPilotLight(EntityAI *vehicle, bool enable); + void AskForVehicleDoorState(Transport *vehicle, int doorIndex, bool opened); + void AskForSetMaxHitZoneDamage + ( + Object *who, float dammage + ); + void CreateObjectStatic(Object *who) override; + void ExplosionDamage(EntityAI *owner, Vector3Par originDir, Object *directHit, Vector3Par directHitModelPos, HitInfoPar hitInfo, + Object *componentOwner, int componentIndex, float energyFactor, float explosionFactor, float hitDepth) override; + + + void AskForAmmo( + EntityAIFull *vehicle, Turret *turret, const WeaponModePtr &ptr, int burst + ); + void AskForMove( + Object *vehicle, Vector3Par pos + ); + + void AskForMove( + Object *vehicle, Matrix4Par trans + ); + void AskForSetMagazineAmmo + ( + Object *magazine, int ammo + ); + + void ExplosionDamageEffects( + EntityAI *owner, Object *directHit, HitInfoPar hitInfo, int componentIndex, + bool enemyDamage, float energyFactor, float explosionFactor + ); + void ApplyProjectileDecal + ( + Object *directHit, int componentIndex, HitInfoPar hitInfo, float hitDepth, Vector3Par hitPosLcl, Vector3Par hitDirLcl, Vector3Par hitDirUpLcl + ); + void RemoveProjectileDecals(Object *person); + void FireWeapon + ( + EntityAIFull *vehicle, Person *gunner, const WeaponModePtr &ptr, Magazine *magazine, EntityAI *target, + const RemoteFireWeaponInfo &remoteInfo + ); + void UpdateBowState(EntityAIFull *entity, BowState state); + void SetObjectTexture(EntityAI *veh, int index, RString name, RString eval = "true"); + void PublicExec(RString condition, RString command, Object* obj, OLinkArray(Object) &objs); + void OnVehicleDestroyed(EntityAI *killed, EntityAI *killer); + void OnVehicleDamaged(EntityAI *damaged, EntityAI *killer, float damage, RString ammo); + void MarkerCreate(int channel, AIBrain *sender, RefArray &units, ArcadeMarkerInfo &info); + void MarkerDelete(RString name); + void SendMsg(NetworkSimpleObject *msg); + + void PublicVariable(RString name, int dpnid); + void SpawnForPlayer(int dpnid, GameDataCode *code, const GameValue &args) override; + + void SendAUMessage(GameValuePar oper1); + + void ClearDelayedPublicVariables(); + void ProcessDelayedPublicVariables(); + + void Chat(int channel, RString text); + void Chat(int channel, AIBrain *sender, RefArray &units, RString text); + void Chat(int channel, RString sender, RefArray &units, RString text); + + void LocalizedChat(int channel, const LocalizedFormatedString &text); + void LocalizedChat(int channel, AIBrain *sender, RefArray &units, const LocalizedFormatedString & text); + void LocalizedChat(int channel, RString sender, RefArray &units, const LocalizedFormatedString & text); + + void RadioChat(int channel, AIBrain *sender, RefArray &units, RString text, RadioSentence &sentence); + void RadioChatWave(int channel, RefArray &units, RString wave, AIBrain *sender, RString senderName); + int GetVoiceChannel() const; + void SetVoiceChannel(int channel); + void SetVoNPosition(int dpnid, Vector3Par pos, Vector3Par speed); + void SetVoNPlayerPosition(Vector3Par pos, Vector3Par speed); + void SetVoNObstruction(int dpnid, float obstruction, float occlusion, float deltaT); + void UpdateVoNVolumeAndAccomodation(int dpnid, float volume, float accomodation); + virtual void AdvanceAllVoNSounds( float deltaT, bool paused, bool quiet ); + + void UpdateCustomChannel(int channel, int ucr_type); + + void TransferFile(RString dest, RString source); + void SendMissionFile(); + void GetTransferStats(int &curBytes, int &totBytes); + + void ApplyWeather(); +#if _VBS3 + void AARDoUpdate(int type ,int intType,RString stringOne = RString(), RString stringTwo = RString(), float floatType = 0.0); + void AARAskUpdate(int type ,int intType,RString stringOne = RString(), RString stringTwo = RString(), float floatType = 0.0); + void AddMPReport(int type, RString myString); + void LoadIsland(RString islandName); + void AskCommanderOverride(Turret *turret, Turret *overriddenByTurret); +#endif + + void AskForDeleteVehicle(Entity *veh); +#if _VBS3 // respawn command + void PauseSimulation(bool pause); +#endif + + virtual void AskForSetItemShortcut(Person *person, int index, const InventoryItemType *type, InventoryItem *item) override; + virtual void AskForThrowItem(Man *person, InventoryItem *item, Vector3 pos, Vector3 dir) override; + virtual void AskForDropItem(Person *person, InventoryItem *item) override; + virtual void AskForMoveItem(EntityAI *target, int index, InventoryItem *item, bool rotated) override; + virtual void AskForRotateInventoryItem(Person *person, InventoryItem *item) override; + virtual void AskForTakeItemToHands(Person *person, InventoryItem *item) override; + virtual void AskForSwapItems(InventoryItem *item1, InventoryItem *item2, Person *owner) override; + + virtual void AskForPlayerAction(Person *person, RString action) override; + + virtual void AskInventoryMenu(AIBrain *unit, InventoryItem *item1, InventoryItem *item2) override; + +#if _ENABLE_ATTACHED_OBJECTS + void AttachObject(Object *obj, Object *attachTo, int memIndex, Vector3 pos, int flags); + void DetachObject(Object *obj); +#endif + + void AskForAnimationPhase(Entity *vehicle, RString animation, float phase); + + bool ProcessCommand(RString command); + bool IsCommandAvailable(RString command); + + void SendKick(int player); + void SendLockSession(bool lock = true); + + bool CanSelectMission() const; + bool CanVoteMission() const; + const VotingMissionProgressMessage *GetMissionVotingState() const; + const AutoArray &GetServerMissions() const; + void SelectMission(RString mission, int difficulty); + void VoteMission(RString mission, int difficulty); + + RString GetHostName() const override; + RString GetServerGUID() const override; + + void UpdateObject(NetworkObject *object); + virtual void UpdateObject(NetworkObject *object, NetworkMessageClass cls) override; + + //! Forget all enumerated hosts + void ClearEnumHosts(); + //! Cancel _dp->EnumHost operation + void StopEnumHosts(); + //! Start _dp->EnumHost operation + bool StartEnumHosts(); + + //! Return original name of local player (without decoration used when several players vith the same name are connected) + RString GetLocalPlayerName() const; + + Time GetEstimatedEndTime() const; + void SetEstimatedEndTime(Time time); + + void DisposeBody(Person *body); + bool IsControlsPaused(); + float GetLastMsgAgeReliable(); + + /// react to communicator insertion/removal + void UpdateVoiceStatus(); + + void ChangeVoiceMask(RString mask); + + void DebugAsk(RString str); + void DebugServerExec(RString str); + + Time GetPlayerJoined(int dpid) const; + + void HackedDataDetected(RString filename); + + void AddPublicVariableEventHandler(RString name, GameValuePar code); + bool BattlEyeOnScriptExec(RString script); + + virtual void ProcessAction(Action *action, AIBrain *unit) override; + virtual void ProcessRecipe(RString recipe, Person *person, InventoryItem *item1, InventoryItem *item2) override; + virtual void UseItem(Person *person, InventoryItem *item) override; + + virtual void SynchronizeVariable( EntityAI * veh, RString name, float coef, const GameDataCode &code ) override; + virtual void SendCreateMessage( EntityAI *veh ) override; + + virtual void OnHierParentChange( Entity* veh ) override; + virtual void RptFObjectIdJournal( const NetworkId &id ) override; + +#if _ENABLE_DEDICATED_SERVER + virtual void ProfileAnswer(const RString &output) override; +#endif + +#if _ENABLE_GAMESPY + /// Set on which IP Address the client is visible from the matchmaking server + virtual void SetPublicAddress(int addr); + +#endif + +#if _GAMES_FOR_WINDOWS + /// Access to the session info + const XSESSION_INFO &GetSessionInfo() const {return _sessionInfo;} + /// Access to the session nonce - the unique key used for arbitration + ULONGLONG GetSessionNonce() const {return _sessionNonce;} + + /// Update the player slots of the session + bool UpdateSession(int maxPlayers, int privateSlots); + + /// Register arbitration for clients (final registration on server is processed in StartSession) + bool ArbitrationRegister(ULONGLONG sessionNonce); + + /// Register player to the session + bool RegisterPlayer(const PlayerIdentity &identity); + /// Unregister player from the session + bool UnregisterPlayer(const PlayerIdentity &identity); + + /// start the match itself, statistics collection begins + bool StartSession(); + /// finish the match itself, statistics will be reported + bool EndSession(); + +protected: + /// Register session on Xbox Live + bool RegisterSession(bool host, int maxPlayers, int maxPrivateSlots); + /// Unregister session from Xbox Live + void UnregisterSession(); + + /// Based on game type, select the leaderboard(s) and algorithm and update the statistics + bool UpdateStatistics(RString gameType); + +#endif +}; + +extern NetworkManager GNetworkManager; +extern NetworkMessageFormat *GMsgFormats[NMTN]; + +extern RString ServerTmpDir; +RString GetServerTmpDir(); +RString GetClientTmpDir(); +RString GetClientCustomFilesDir(); + +//! total number of diagnostic types +/*! +\patch_internal 1.08 Date 07/26/2001 by Jirka +- Improved: network diagnostics +*/ +enum OutputDiagsMode +{ + ODMsgQueue, + ODMsgSent, + ODMsgReceived, + ODMRawStats, + NOutputDiags +}; + +extern int outputDiags; +extern bool outputLogs; + +// transfer parameters +//! When update error (considering distance) is bellow this threshold, update message is not sent +extern float MinErrorToSend; +//! When update error (not considering distance) is bellow this threshold, update message is not sent +extern float MinErrorToSendNear; +//! Maximal number of messages sent in single simulation step +extern int MaxMsgSend; +//! Maximal number of messages sent in single simulation step on dedicated server +extern int DSMaxMsgSend; +//! Maximal size of agregated guaranteed message +extern int MaxSizeGuaranteed; +//! Maximal size of agregated guaranteed message +extern int MaxSizeNonguaranteed; +//! Limit (minimum) for bandwidth estimation +extern int MinBandwidth; +//! Limit (minimum) for bandwidth estimation on dedicated server +extern int DSMinBandwidth; +//! Limit (maximum) for bandwidth estimation +extern int MaxBandwidth; + +//! == default MinErrorToSend / 2, after 2 s update is forced +#define ERR_COEF_TIME_POSITION 0.005 +//! == default MinErrorToSend / 5, after 5 s update is forced +#define ERR_COEF_TIME_GENERIC 0.002 + +#define MSGID_REPLACE 0 + +void WriteDiagOutput(bool server); +int GetDiagLevel(NetworkMessageType type, bool remote); + +//((EXE_CRC_CHECK +/// information for client code verification +struct ExeCRCBlock +{ + int offset, size, crc; +}; +TypeIsSimple(ExeCRCBlock); +//))EXE_CRC_CHECK + +#ifdef _WIN32 +HRESULT WINAPI ReceiveMessage(void *context, DWORD type, void *message); +#endif +void InitMsgFormats(); +const char *FormatVal(float val, char *buffer); + +#if _ENABLE_UNSIGNED_MISSIONS +RString CreateMPMissionBank(RString filename, RString island); +#endif + +int GetNetworkPort(); +int GetServerPort(); + +extern WINDOW_HANDLE hwndApp; + +bool DeleteDirectoryStructure(const char *name, bool deleteDir); +void CreatePath(RString path); +bool ParseMission(bool multiplayer, bool avoidCheckIds = false, bool allowEmpty = false); + +//! Release COM object +#ifndef SAFE_RELEASE +#define SAFE_RELEASE(p) { if(p) {(p)->Release(); (p) = NULL;} } +#endif + +// Multiplayer version info + +#include "../versionNo.h" + +//! Actual multiplayer version +#define MP_VERSION_ACTUAL APP_VERSION_NUM +//! The earliest supported multiplayer version +#define MP_VERSION_REQUIRED APP_VERSION_NUM + +/*** following code shows how to implement a code specific to certain product version + if (MP_VERSION_REQUIRED>=160 && !strcmp(APP_NAME_SHORT,"ArmA2OA")) // TODO: can be removed in 160 + { + // implementation for the new version + } + else + { + #if MP_VERSION_REQUIRED>=160 + #pragma message WARN_MESSAGE("warning: Remove obsolete code") + #endif + // implementation for the old version + } +*/ + +//! Types of Network command messages +enum NetworkCommandMessageType +{ + NCMTLogin, + NCMTLogged, + NCMTLogout, + NCMTKick, + /// used as voting id - restart current mission + NCMTRestart, + /// used as voting id for mission voting + NCMTMission, + /// used as voting id - return to mission selection + NCMTMissions, + NCMTShutdown, + /// used as voting id - return to role selection + NCMTReassign, + NCMTMonitorAsk, + NCMTMonitorAnswer, + NCMTVote, + NCMTVoteMission, + NCMTMissionTimeElapsed, + /// used as voting id for admin voting + NCMTAdmin, + NCMTInit, + NCMTLockSession, + NCMTLoggedOut, + NCMTDebugAsk, + NCMTDebugAnswer, + /// used only as voting id for mission difficulty voting + NCMTDifficulty, + /// execute the server scripting command + NCMTExec, + NCMTExecResult, + /// BattlEye server command + NCMTBattlEye, + /// Progress of custom files uploading from server to clients + NCMTCustomFilesProgress, +#if _ENABLE_CHEATS + /// execute the scripting sommand + NCMTGameExec, +#endif +#if _VBS3 + NCMTExitAll, +#endif + // server asks clients for their VoNFeatures diagnostics, clients responds + NCMTAskVoNDiagnostics, + NCMTMissionDate, + NCMTVoteMissionExt, + NCMTProfileAsk, + NCMTProfileAnswer +}; + +#define NETWORK_COMMAND_MSG(MessageName, XX) \ + XX(MessageName, int, type, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Type of command"), TRANSF) \ + XX(MessageName, SimpleStream, content, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Parameters of command"), TRANSF) + +DECLARE_NET_MESSAGE(NetworkCommand, NETWORK_COMMAND_MSG) + +#define PLAYER_UPDATE_MSG(MessageName, XX) \ + XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Client (player) ID"), TRANSF, ET_NONE, 0) \ + XX(MessageName, int, minPing,NDTInteger,int, NCTSmallUnsigned, DEFVALUE(int, 10), DOC_MSG("Ping range estimation"), TRANSF, ET_ABS_DIF, ERR_COEF_VALUE_MINOR) \ + XX(MessageName, int, avgPing,NDTInteger,int, NCTSmallUnsigned, DEFVALUE(int, 100), DOC_MSG("Ping range estimation"), TRANSF, ET_ABS_DIF, ERR_COEF_VALUE_MAJOR) \ + XX(MessageName, int, maxPing,NDTInteger,int, NCTSmallUnsigned, DEFVALUE(int, 1000), DOC_MSG("Ping range estimation"), TRANSF, ET_ABS_DIF, ERR_COEF_VALUE_MINOR) \ + XX(MessageName, int, minBandwidth,NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 2), DOC_MSG("Bandwidth estimation (in kbps)"), TRANSF, ET_ABS_DIF, ERR_COEF_VALUE_MINOR) \ + XX(MessageName, int, avgBandwidth,NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 14), DOC_MSG("Bandwidth estimation (in kbps)"), TRANSF, ET_ABS_DIF, ERR_COEF_VALUE_MINOR) \ + XX(MessageName, int, maxBandwidth,NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 28), DOC_MSG("Bandwidth estimation (in kbps)"), TRANSF, ET_ABS_DIF, ERR_COEF_VALUE_MINOR) \ + XX(MessageName, int, desync,NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Current desync level (max. error of unsent messages)"), TRANSF, ET_ABS_DIF, ERR_COEF_VALUE_MAJOR) \ + XX(MessageName, int, rights,NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Special rights of given player"), TRANSF, ET_ABS_DIF, ERR_COEF_VALUE_MAJOR) + +DECLARE_NET_INDICES_ERR(PlayerUpdate, PLAYER_UPDATE_MSG) + +inline bool NetworkClient::IsBotClient() const +{ + return _parent->IsServer(); +} + +inline NetworkServer *NetworkClient::GetServer() const +{ + return _parent->GetServer(); +} + + +#define ACCEPTED_KEY_MSG(MessageName, XX) \ + XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Key name"), TRANSF) \ + XX(MessageName, Temp, content, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Key content"), TRANSF) \ + +DECLARE_NET_INDICES(AcceptedKey, ACCEPTED_KEY_MSG) + +//! Accepted public key for data signatures +struct AcceptedKeyMessage : public NetworkSimpleObject +{ + DSKey &_key; + + AcceptedKeyMessage(DSKey &key) : _key(key) {} + + DECLARE_DEFINE_NETWORK_OBJECT_SIMPLE(AcceptedKey) + static NetworkMessageFormat &CreateFormat + ( + NetworkMessageClass cls, + NetworkMessageFormat &format + ); + TMError TransferMsg(NetworkMessageContext &ctx); +}; + +#define ADDITIONAL_SIGNED_FILES_MSG(MessageName, XX) \ + XX(MessageName, AutoArray, list, NDTStringArray, AutoArray, NCTNone, DEFVALUESTRINGARRAY, DOC_MSG("List of additional files to check."), TRANSF) \ + +DECLARE_NET_INDICES(AdditionalSignedFiles, ADDITIONAL_SIGNED_FILES_MSG) + +//! Accepted public key for data signatures +struct AdditionalSignedFilesMessage : public NetworkSimpleObject +{ + AutoArray &_list; + + AdditionalSignedFilesMessage(AutoArray &list) : _list(list) {} + + DECLARE_DEFINE_NETWORK_OBJECT_SIMPLE(AdditionalSignedFiles) + static NetworkMessageFormat &CreateFormat + ( + NetworkMessageClass cls, + NetworkMessageFormat &format + ); + TMError TransferMsg(NetworkMessageContext &ctx); +}; + +#define DATA_SIGNATURE_ASK_MSG(MessageName, XX) \ + XX(MessageName, int, index, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, -1), DOC_MSG("Index of file to check."), TRANSF) \ + XX(MessageName, int, level, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("The level of the check (higher level means deeper check)."), TRANSF) \ + +DECLARE_NET_MESSAGE(DataSignatureAsk, DATA_SIGNATURE_ASK_MSG) + +#define DATA_SIGNATURE_ANSWER_MSG(MessageName, XX) \ + XX(MessageName, int, index, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, -1), DOC_MSG("Index of file to check."), TRANSF) \ + XX(MessageName, RString, filename, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Name of checked file."), TRANSF) \ + XX(MessageName, RString, keyName, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Name of public key"), TRANSF) \ + XX(MessageName, Temp, keyContent, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Content of public key"), TRANSF) \ + XX(MessageName, Temp, signature, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Content of signature"), TRANSF) \ + XX(MessageName, Temp, hash, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Content of hash"), TRANSF) \ + XX(MessageName, int, version, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 1), DOC_MSG("Signature version."), TRANSF) \ + XX(MessageName, int, level, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Ask level."), TRANSF) \ + +DECLARE_NET_INDICES(DataSignatureAnswer, DATA_SIGNATURE_ANSWER_MSG) + +//! Answer to data signature check +struct DataSignatureAnswerMessage : public NetworkSimpleObject +{ + int _index; + RString _filename; + DSSignature _signature; + DSHash _hash; + int _level; + + DECLARE_DEFINE_NETWORK_OBJECT_SIMPLE(DataSignatureAnswer) + static NetworkMessageFormat &CreateFormat + ( + NetworkMessageClass cls, + NetworkMessageFormat &format + ); + TMError TransferMsg(NetworkMessageContext &ctx); +}; + +#define FILE_SIGNATURE_ASK_MSG(MessageName, XX) \ + XX(MessageName, RString, file, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("File to check the signature."), TRANSF) \ + XX(MessageName, int, level, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("The level of the check (higher level means deeper check)."), TRANSF) \ + +DECLARE_NET_MESSAGE(FileSignatureAsk, FILE_SIGNATURE_ASK_MSG) + +#define FILE_SIGNATURE_ANSWER_MSG(MessageName, XX) \ + XX(MessageName, RString, fileName, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Checked filename."), TRANSF) \ + XX(MessageName, RString, keyName, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Name of public key"), TRANSF) \ + XX(MessageName, Temp, keyContent, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Content of public key"), TRANSF) \ + XX(MessageName, Temp, signature, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Content of signature"), TRANSF) \ + XX(MessageName, Temp, dataToHash, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Content which hash was signed"), TRANSF) \ + XX(MessageName, int, version, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 1), DOC_MSG("Signature version."), TRANSF) \ + XX(MessageName, int, level, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Ask level."), TRANSF) \ + XX(MessageName, int, index, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, -1), DOC_MSG("Index of pbo file matching the DataSignatureAsk"), TRANSF) \ + + +DECLARE_NET_INDICES(FileSignatureAnswer, FILE_SIGNATURE_ANSWER_MSG) + +//! Answer to file signature check +struct FileSignatureAnswerMessage : public NetworkSimpleObject +{ + RString _fileName; + DSSignature _signature; + Temp _dataToHash; // for sig.ver.2: (hash of pbo content) + (hash of pbo file list) + (pbo prefix) + int _level; + int _index; + + DECLARE_DEFINE_NETWORK_OBJECT_SIMPLE(FileSignatureAnswer) + static NetworkMessageFormat &CreateFormat + ( + NetworkMessageClass cls, + NetworkMessageFormat &format + ); + TMError TransferMsg(NetworkMessageContext &ctx); + RString GetPrefix() const; // parse the dataToHash to find the stored pbo prefix + void GetDataHash(Temp &hash) const; +}; + +#define CREATE_RADIO_CHANNEL_MSG(MessageName, XX) \ + XX(MessageName, int, channel, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Custom channel in CCCustom1 to CCCustomLast range."), TRANSF) \ + XX(MessageName, int, color, NDTInteger, int, NCTNone, DEFVALUE(int, -1), DOC_MSG("Custom channel color"), TRANSF) \ + XX(MessageName, RString, label, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Channel label."), TRANSF) \ + XX(MessageName, RString, callSign, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Channel Call Sign."), TRANSF) \ + XX(MessageName, RefArray, units, NDTRefArray, AutoArray, NCTNone, DEFVALUEREFARRAY, DOC_MSG("List of participating units"), TRANSF_REFS) + +DECLARE_NET_MESSAGE_INIT_MSG(CreateRadioChannel, CREATE_RADIO_CHANNEL_MSG) + +#define RADIO_CHANNEL_LABEL_MSG(MessageName, XX) \ + XX(MessageName, int, channel, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Custom channel in CCCustom1 to CCCustomLast range."), TRANSF) \ + XX(MessageName, RString, label, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Channel label."), TRANSF) + +DECLARE_NET_MESSAGE_INIT_MSG(RadioChannelLabel, RADIO_CHANNEL_LABEL_MSG) + +#define RADIO_CHANNEL_CALL_SIGN_MSG(MessageName, XX) \ + XX(MessageName, int, channel, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Custom channel in CCCustom1 to CCCustomLast range."), TRANSF) \ + XX(MessageName, RString, callSign, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Channel Call Sign."), TRANSF) + +DECLARE_NET_MESSAGE_INIT_MSG(RadioChannelCallSign, RADIO_CHANNEL_CALL_SIGN_MSG) + +#define RADIO_CHANNEL_UNITS_MSG(MessageName, XX) \ + XX(MessageName, int, channel, NDTInteger, int, NCTSmallSigned, DEFVALUE(int, 0), DOC_MSG("Custom channel in CCCustom1 to CCCustomLast range."), TRANSF) \ + XX(MessageName, RefArray, units, NDTRefArray, AutoArray, NCTNone, DEFVALUEREFARRAY, DOC_MSG("List of participating units"), TRANSF_REFS) + +DECLARE_NET_MESSAGE_INIT_MSG(RadioChannelUnits, RADIO_CHANNEL_UNITS_MSG) + +#define HACKED_DATA_MSG(MessageName, XX) \ + XX(MessageName, int, type, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, HTUnsignedData), DOC_MSG("Type of violation."), TRANSF) \ + XX(MessageName, RString, filename, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Name of hacked file."), TRANSF) \ + +DECLARE_NET_MESSAGE(HackedData, HACKED_DATA_MSG) + +#define CDKEY_CHECK_ASK_MSG(MessageName, XX) \ + XX(MessageName, RString, challenge, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Chalenge string (see GameSpy SDK Help)."), TRANSF) \ + +DECLARE_NET_MESSAGE(CDKeyCheckAsk, CDKEY_CHECK_ASK_MSG) + +#define CDKEY_CHECK_ANSWER_MSG(MessageName, XX) \ + XX(MessageName, RString, response, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Response string (see GameSpy SDK Help)."), TRANSF) \ + +DECLARE_NET_MESSAGE(CDKeyCheckAnswer, CDKEY_CHECK_ANSWER_MSG) + +#define CDKEY_RECHECK_ASK_MSG(MessageName, XX) \ + XX(MessageName, int, hint, NDTInteger, int, NCTNone, DEFVALUE(int, -1), DOC_MSG("Session key (see GameSpy SDK Help)."), TRANSF) \ + XX(MessageName, RString, challenge, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Challenge string (see GameSpy SDK Help)."), TRANSF) \ + +DECLARE_NET_MESSAGE(CDKeyRecheckAsk, CDKEY_RECHECK_ASK_MSG) + +#define CDKEY_RECHECK_ANSWER_MSG(MessageName, XX) \ + XX(MessageName, int, hint, NDTInteger, int, NCTNone, DEFVALUE(int, -1), DOC_MSG("Session key (see GameSpy SDK Help)."), TRANSF) \ + XX(MessageName, RString, response, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Response string (see GameSpy SDK Help)."), TRANSF) \ + +DECLARE_NET_MESSAGE(CDKeyRecheckAnswer, CDKEY_RECHECK_ANSWER_MSG) + +#define ASK_CONNECT_VOICE_MSG(MessageName, XX) \ + XX(MessageName, int, publicAddr, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Public IP address of the client."), TRANSF) \ + XX(MessageName, int, privateAddr, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Private IP address of the client."), TRANSF) \ + XX(MessageName, int, voicePort, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Port voice channel is bind to."), TRANSF) \ + XX(MessageName, int, verNo, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("The build number of client exe file."), TRANSF) \ + +DECLARE_NET_MESSAGE(AskConnectVoice, ASK_CONNECT_VOICE_MSG) + +#define DIAG_OBJECT_INFO_ASK_MSG(MessageName, XX) \ + XX(MessageName, CreatorId, creator, NDTInteger, CreatorId, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("creator id of object"), TRANSF) \ + XX(MessageName, OIDInt, id, NDTOID, OIDInt, NOIDIntComp, DEFVALUE(OIDInt, 0), DOC_MSG("id object"), TRANSF) + +DECLARE_NET_MESSAGE(DiagObjectInfoAsk, DIAG_OBJECT_INFO_ASK_MSG) + +#define CLIENT_DIAG_TO_SERVER_MSG(MessageName, XX) \ + XX(MessageName, RString, response, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Any info client want server to log in tis report file."), TRANSF) + +DECLARE_NET_MESSAGE(ClientDiagToServer, CLIENT_DIAG_TO_SERVER_MSG) + +#define CONNECT_VOICE_DIRECT_MSG(MessageName, XX) \ + XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("ID of player to connect with"), TRANSF) \ + XX(MessageName, int, addr, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("IP address where connect to."), TRANSF) \ + XX(MessageName, int, port, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Port where connect to."), TRANSF) \ + XX(MessageName, bool, direct, NDTBool, bool, NCTNone, DEFVALUE(bool, true), DOC_MSG("Is the connection direct or punched?"), TRANSF) \ + +DECLARE_NET_MESSAGE(ConnectVoiceDirect, CONNECT_VOICE_DIRECT_MSG) + +#define CONNECT_VOICE_NAT_NEG_MSG(MessageName, XX) \ + XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("ID of player to connect with"), TRANSF) \ + XX(MessageName, int, cookie, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Cookie for Nat negotiation."), TRANSF) \ + XX(MessageName, int, clientIndex, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Client index for Nat negotiation."), TRANSF) \ + +DECLARE_NET_MESSAGE(ConnectVoiceNatNeg, CONNECT_VOICE_NAT_NEG_MSG) // TODO: remove (make dummy) + +#define NAT_NEG_RESULT_MSG(MessageName, XX) \ + XX(MessageName, int, dpnid, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("ID of NAT negotiating player"), TRANSF) \ + XX(MessageName, bool, result, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("Result of NAT negotiation (true for success)."), TRANSF) \ + +DECLARE_NET_MESSAGE(NatNegResult, NAT_NEG_RESULT_MSG) + +#define DISCONNECT_MSG(MessageName, XX) \ + XX(MessageName, RString, message, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Cause why the player was disconnected."), TRANSF) \ + +DECLARE_NET_MESSAGE(Disconnect, DISCONNECT_MSG) + +#define MISSION_STATS_MSG(MessageName, XX) \ + XX(MessageName, int, toCreate, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Number of objects we will create on the client."), TRANSF) \ + XX(MessageName, int, toUpdate, NDTInteger, int, NCTSmallUnsigned, DEFVALUE(int, 0), DOC_MSG("Number of objects we will update on the client."), TRANSF) \ + +DECLARE_NET_MESSAGE(MissionStats, MISSION_STATS_MSG) + +#define ASK_FOR_ARBITRATION_MSG(MessageName, XX) \ + XX(MessageName, NetInt64, sessionNonce, NDTInt64, NetInt64, NCTNone, DEFVALUE(NetInt64, 0), DOC_MSG("Key used for arbitration."), TRANSF) \ + +DECLARE_NET_MESSAGE(AskForArbitration, ASK_FOR_ARBITRATION_MSG) + +#define BATTLEYE_MSG(MessageName, XX) \ + XX(MessageName, AutoArray, message, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Message content"), TRANSF) \ + +DECLARE_NET_MESSAGE(BattlEye_Obsolete, BATTLEYE_MSG) + +#define SERVERTIME_MSG(MessageName, XX) \ + XX(MessageName, int, time, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Server time"), TRANSF) \ + XX(MessageName, int, endTime, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Server time of estimated end of MP game."), TRANSF) \ + +DECLARE_NET_MESSAGE(ServerTime, SERVERTIME_MSG) + +#define SERVER_ADMIN_MESSAGE(MessageName, XX) \ + XX(MessageName, bool, admin, NDTBool, bool, NCTNone, DEFVALUE(bool, false), DOC_MSG("GameMaster on server is voted admin."), TRANSF) \ + XX(MessageName, int, gameMaster, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Id of gameMaster."), TRANSF) \ + +DECLARE_NET_MESSAGE(ServerAdmin, SERVER_ADMIN_MESSAGE) + +#define SEND_AU_MSG(MessageName, XX) \ + XX(MessageName, AutoArray, value, NDTRawData, AutoArray, NCTNone, DEFVALUERAWDATA, DOC_MSG("Send Auto Update message content"), TRANSF) + +DECLARE_NET_MESSAGE(SendAUMsg, SEND_AU_MSG) + +/// Custom file message to check whether the transfer to client is neccessary +#define CUSTOM_FILE_PATHS_MSG(MessageName, XX) \ + XX(MessageName, RString, dst, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Custom file path"), TRANSF) \ + XX(MessageName, int, crc, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("CRC of custom file"), TRANSF) \ + XX(MessageName, int, len, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("File length of custom file"), TRANSF) + +DECLARE_NET_INDICES(CustomFile, CUSTOM_FILE_PATHS_MSG) + +// NetworkMessageCustomFileList to transfer array of CustomFilePaths +#define CUSTOM_FILE_LIST_MSG(MessageName, XX) \ + XX(MessageName, int, player, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Direct play id"), TRANSF) \ + XX(MessageName, RString, name, NDTString, RString, NCTNone, DEFVALUE(RString, ""), DOC_MSG("Player name"), TRANSF) \ + XX(MessageName, AutoArray, fileList, NDTObjectArray, REF_MSG_ARRAY(NetworkMessageCustomFile), NCTNone, DEFVALUE_MSG(NMTCustomFile), DOC_MSG("List of custom files"), TRANSF_ARRAY) + +DECLARE_NET_MESSAGE(CustomFileList, CUSTOM_FILE_LIST_MSG) + +#define CUSTOM_FILES_WANTED_MSG(MessageName, XX) \ + XX(MessageName, int, player, NDTInteger, int, NCTNone, DEFVALUE(int, 0), DOC_MSG("Direct play id"), TRANSF) \ + XX(MessageName, AutoArray, filesWanted, NDTIntArray, AutoArray, NCTSmallUnsigned, DEFVALUEINTARRAY, DOC_MSG("Array of indexes to custom file list which client wants to get"), TRANSF) \ + +DECLARE_NET_MESSAGE(CustomFilesWanted, CUSTOM_FILES_WANTED_MSG) + +#define DELETE_CUSTOM_FILES_MSG(MessageName, XX) \ + XX(MessageName, AutoArray, list, NDTStringArray, AutoArray, NCTNone, DEFVALUESTRINGARRAY, DOC_MSG("Array of indexes to custom file list which client wants to get"), TRANSF) \ + +DECLARE_NET_MESSAGE(DeleteCustomFiles, DELETE_CUSTOM_FILES_MSG) + +#if _PROFILE +#define DEBUG_GIVEN_NETWORK_ID 1 +#endif + +#if DEBUG_GIVEN_NETWORK_ID +bool DebugMeBoy(NetworkId id); +bool DebugMeBoy(NetworkMessage *msg, NetworkMessageType type); +#else +inline bool DebugMeBoy(NetworkId id) {return false;} +inline bool DebugMeBoy(NetworkMessage *msg, NetworkMessageType type) {return false;} +#endif +bool ReadValue(GameValue &value, const void* buffer, int buffSize, INetworkManager *netManager); + +#endif diff --git a/lib/Network/networkServer.cpp b/lib/Network/networkServer.cpp index 86eba481..7635e191 100644 --- a/lib/Network/networkServer.cpp +++ b/lib/Network/networkServer.cpp @@ -1,14919 +1,14919 @@ -#include "../wpch.hpp" -#include "networkImpl.hpp" -#include "networkQueueUtils.hpp" - -#include "../global.hpp" -//#include "strIncl.hpp" -#include "../stringtableExt.hpp" - -#include "../arcadeTemplate.hpp" -#include "../AI/ai.hpp" -#include "../world.hpp" -#include "../landscape.hpp" -#include "../UI/chat.hpp" -#include "../UI/uiMap.hpp" -#include "../UI/missionDirs.hpp" -#include - -#include -#include -#include -#include "Es/Containers/RTree.hpp" - -#include "../allAIVehicles.hpp" -#include "../seaGull.hpp" -#include "../detector.hpp" -#include "../shots.hpp" -#include "../fileLocator.hpp" -#include "../gameDirs.hpp" -#include "../registration.hpp" - -#include -#include - -#include -#include -#include - -#if _ENABLE_STEAM && defined(_WIN64) -bool SteamOnlineServerStart(int gamePort, int steamPort, int queryPort, const char *serverName, int maxPlayers, bool passwordProtected); -#endif - -#include - -#include -#include "../gameStateExt.hpp" - -#include "../progress.hpp" -#include - -#include "geoLoc.hpp" -#include "../keyInput.hpp" -#include "../dikCodes.h" -#include "../UI/uiActions.hpp" - -#include -#include -#include -#include - -#include "../saveGame.hpp" -#include "../saveVersion.hpp" - -#include "../AI/aiRadio.hpp" -#include - -#include -#include - -#include "httpRequest.h" - -#ifdef _WIN32 - #include -#endif - -#if defined(_WIN32) - #if _ENABLE_MP - #include - #endif - #if _ENABLE_DEDICATED_SERVER - #include - #endif -#endif - -#include "El/Speech/debugVoN.hpp" - -#if _PROFILE -#pragma optimize( "", off ) -#endif - -/*! -\file -Basic implementation file for network server -*/ - -//((EXE_CRC_CHECK -// random integrity check -#if _SUPER_RELEASE - #define _ENABLE_RANDOM_INTEGRITY_CHECK 1 -#else - #define _ENABLE_RANDOM_INTEGRITY_CHECK 0 -#endif -//))EXE_CRC_CHECK - -#define LOG_SEND_PROCESS 0 - -#define LOG_PLAYERS 1 - -extern int MaxCustomFileSize; - -#define QOS_SERVER_BANDWIDTH 4096 - -//! enable diagnostic logs of message errors -#define LOG_ERRORS 0 -//! limit for diagnostic logs of message errors -static float LogErrorLimit = 1.0f; - -extern GameValue GNetworkPlayerConnected; -extern GameValue GNetworkPlayerDisconnected; - - -RStringB GetExtensionWizardMission(); - -/// generate a 32-bit random number (Implementation of rand() in MSVC returns only 15 bits) -int rand32() -{ - return (rand() & 0x7fff) | (rand() & 0x7fff) << 15 | (rand() & 0x0003) << 30; - -} - -#define STRINGIZE_X(x) #x -#define STRINGIZE(x) STRINGIZE_X(x) - -/*! -\patch 5257 Date 7/15/2008 by Bebul -- Fixed: Players connecting JIP with custom files do not cause server lagging. -\patch 5257 Date 7/15/2008 by Bebul -- Fixed: Players with custom files get no longer kicked when server does not run on default port. -*/ -static RString GetServerPath(RString src) -{ - if (src.GetLength() == 0) return src; - if (src[0] == '$') - { // translate char '$' to Local Settings directory - char dir[MAX_PATH]; - if (!GetLocalSettingsDir(dir)) return src.Substring(2, INT_MAX); // place in current directory - TerminateBy(dir, '\\'); - return RString(dir) + src.Substring(2, INT_MAX); - } - else if (src[0] == '#') - { // translate char '#' to Local Settings directory + ServerTmpDir - return GetServerTmpDir() + src.Substring(1, INT_MAX); // place in current directory - } - else return src; -} - -/*! - \patch 5088 Date 11/06/2006 by Ondra - - Fixed: Possible crash when exiting multiplayer game. -*/ - -void ClearNetServer() -{ -} - -// Moved, declarations needed in BE - -//{ QUERY & REPORTING SDK -#if _ENABLE_GAMESPY - -#define REPORT_ASE 0 - -#include "../GameSpy/qr2/qr2.h" -#include "../GameSpy/natneg/natneg.h" -#if _VERIFY_CLIENT_KEY -# include "../GameSpy/gcdkey/gcdkeys.h" -# ifdef NOMINMAX -# undef min -# undef max -# endif -#include "../GameSpy/gcdkey/gcdkeyc.h" -#endif - -# ifdef NOMINMAX -# undef min -# undef max -# endif - -REGISTER_CREDITS("GameSpy", "2009 GameSpy Industries, Inc.","") - -#if REPORT_ASE -extern "C" -{ -#include "../ASE/ASEMasterSDK.h" -} -#endif - -#ifdef NOMINMAX -# undef min -# undef max -#endif - -char *GetGameName() -{ - // GameSpy game name -#if _LIBERATION - return "IFpc"; -#elif _DEMO - return "takoncopterpcd"; -#else - return "takoncopterpc"; -#endif -} - -char *GetSecretKey() -{ - // GameSpy secret key - static char secret_key[9]; - - //set the secret key, in a semi-obfuscated manner - secret_key[0] = '6'; - secret_key[1] = 'P'; - secret_key[2] = 'V'; - secret_key[3] = 'I'; - secret_key[4] = 'h'; - secret_key[5] = 'e'; - secret_key[6] = '\0'; - - return secret_key; -} - -int GetGameID() -{ - // GameSpy game id -#if _LIBERATION - return 4077; -#elif _DEMO - return 5132; -#else - return 4093; -#endif -} - -int GetProductID() -{ - // GameSpy product id -#if _LIBERATION - return 13905; -#elif _DEMO - return 13916; -#else - return 13916; -#endif -} - -char *GetGcdHostname() -{ - //host DNS - default - return ""; -} - -#endif -//} - -DEFINE_FAST_ALLOCATOR(NetworkPlayerObjectInfo) - -NetworkObjectInfo::NetworkObjectInfo() -{} - - -NetworkObjectInfo::~NetworkObjectInfo() -{ - -} - -#if _PROFILE && USER_Ondra -typedef Journal ProfileJournal; -#else -typedef DummyJournal ProfileJournal; -#endif - -ProfileJournal NetworkPlayerObjectInfoJournal; - -NetworkPlayerObjectInfo::NetworkPlayerObjectInfo() -:updating(false) -{ - NetworkPlayerObjectInfoJournal.Add(Format("Construct %x",this)); -} - -NetworkPlayerObjectInfo::~NetworkPlayerObjectInfo() -{ - NetworkPlayerObjectInfoJournal.Add(Format("Destruct %x, %d",this,IsInList())); -} - -NetworkPlayerObjectInfo *NetworkObjectInfo::GetPlayerObjectInfo(PlayerIndex player, int pid) -{ - DoAssert(playerToObjects[player]->player==pid); - return playerToObjects[player]; -} - -NetworkPlayerObjectInfo *NetworkObjectInfo::CreatePlayerObjectInfo(PlayerIndex player, int pid) -{ - if (player < playerToObjects.Size()) - { - return playerToObjects[player]; - } - int index = playerToObjects.Add(); - DoAssert(index==player); - playerToObjects[index] = new NetworkPlayerObjectInfo; - NetworkPlayerObjectInfo *poInfo = playerToObjects[index]; - poInfo->player = pid; - poInfo->oInfo = this; - for (int j=NMCUpdateFirst; jupdates[j]; - info.errorValid = false; - } - return poInfo; -} - -void NetworkObjectInfo::ResetPlayerObjectInfo(PlayerIndex player, int pid) -{ - if (player<0) return; - DoAssert(playerToObjects[player]->player==pid); - NetworkPlayerObjectInfo *poInfo = playerToObjects[player]; - for (int j=NMCUpdateFirst; jupdates[j]; - info.errorValid = false; - } -} - -void NetworkObjectInfo::DeletePlayerObjectInfo(PlayerIndex player, int pid) -{ - if (player<0) return; - DoAssert(playerToObjects[player]->player==pid); - playerToObjects.Delete(player); -} - -void NetworkObjectInfo::NullPlayerObjectInfo(PlayerIndex player, int pid) -{ - if (player<0) return; - DoAssert(playerToObjects[player]->player==pid); - playerToObjects[player].Free(); -} - -RString NetworkObjectInfo::GetDebugName() const -{ - if (object.IsNull()) return Format("id=%d:%" OID_FORMAT,id.creator,id.id); - return object->GetDebugName(); -} - -NetworkObjectInfo::UpdateInfo NetworkObjectInfo::CheckBestPosition(const NetworkServer *server) const -{ - Vector3 bestPos = VZero; - NetworkMessageClass bestJ = NMCUpdateN; - if (object.NotNull()) - { - - // find the last update of the object - Time time = TIME_MIN; - for (int j=NMCUpdateFirst; jtime > time) - { - time = msg->time; - bestJ = NetworkMessageClass(j); - } - } - } - if (bestJ!=NMCUpdateN) - { - const auto &best = currentUpdate[bestJ]; - - // retrieve position of the object - NetworkMessageContext ctx(best.message, unconst_cast(server), best.from, MSG_RECEIVE); - - PREPARE_TRANSFER(NetworkObject) - if (TRANSF_BASE(objectPosition, bestPos) != TMOK) - { - bestPos = VZero; - bestJ = NMCUpdateN; - } - - } - } - DoAssert(bestJ==NMCUpdateN || bestPos!=VZero); - NetworkObjectInfo::UpdateInfo ret; - if (bestJ!=NMCUpdateN) - { - ret._pos = bestPos; - ret._updateDistance = object ? object->UpdateDistance() : FLT_MAX; - DoAssert(object); - } - - return ret; -} - - -void NetworkObjectInfo::ScanBestPosition(const NetworkServer *server) -{ - _updInfo = CheckBestPosition(server); -} - -NetworkObjectInfo::UpdateInfo NetworkObjectInfo::BestPosition(const NetworkServer *server) const -{ - #if 0 // _ENABLE_REPORT - UpdateInfo updInfo = CheckBestPosition(server); - DoAssert(updInfo._pos==_updInfo._pos); - DoAssert(updInfo._root==_updInfo._root); - DoAssert(updInfo._updateDistance==_updInfo._updateDistance); - #endif - return _updInfo; -} - -bool NetworkObjectInfo::CheckBestPositionIntegrity(const NetworkServer *server) const -{ - UpdateInfo updInfo = CheckBestPosition(server); - // TODO: enforce strict equality - if (updInfo._pos.Distance2(_updInfo._pos)>Square(0.01f)) - { - LogF("%s: pos not matching",cc_cast(GetDebugName())); - return false; - } - if (updInfo._updateDistance!=_updInfo._updateDistance) - { - LogF("%s: updateDistance not matching",cc_cast(GetDebugName())); - return false; - } - return true; -} - - -NetworkObjectInfo::UpdateInfo NetworkObjectInfo::BestPosition() const -{ - return _updInfo; -} - - -#if _ENABLE_DEDICATED_SERVER -int ConsoleF(const char *format, ...); -int VConsoleF(const char *format, va_list argptr); -int ConsoleTitle(const char *format, ...); -#endif -RString GetUserDirectory(); - -#if _USE_BATTL_EYE_SERVER -/*! -\patch 5254 Date 5/2/2008 by Bebul -- Fixed: BattlEye issues while using server.cfg on Linux dedicated server -\patch 5276 Date 4/16/2009 by Bebul -- Fixed: Changed BattlEye integration (fixing "random" player kicks) -*/ - -#include -#ifndef _WIN32 -#include -#endif - -NetworkServer::BattlEye::BattlEye() -{ - CleanUp(); -} - -NetworkServer::BattlEye::~BattlEye() -{ - Done(); -} - -bool GetBELaunchPath(char *launchPath) -{ -#ifndef _XBOX - RString GetBEPath(); - RString forcedPath = GetBEPath(); -#else - RString forcedPath; -#endif - - // decide the path to the "cache" from where dll is used - if (IsRelativePath(forcedPath)) - { - // relative path -#ifdef _WIN32 - if (!GetLocalSettingsDir(launchPath)) return false; - TerminateBy(launchPath, '\\'); - strcat(launchPath, "BattlEye\\"); - strcat(launchPath, forcedPath); - TerminateBy(launchPath, '\\'); -#else - strcpy(launchPath, "./battleye/"); - strcat(launchPath, forcedPath); - CreateDirectory(launchPath, NULL); - TerminateBy(launchPath, '/'); -#endif - } - else - { - // absolute path - strcpy(launchPath, forcedPath); -#ifdef _WIN32 - TerminateBy(launchPath, '\\'); -#else - TerminateBy(launchPath, '/'); -#endif - } - - return true; -} - -#define STRINGIZE_X(x) #x -#define STRINGIZE(x) STRINGIZE_X(x) - -#ifdef _WIN32 - -int NetworkServer::BattlEye::GetBEVersion(HMODULE library) const -{ - if (library) - { - GetVerF *getVer = (GetVerF *)GetProcAddress(library, "GetVer"); - if (getVer) return (*getVer)(); - } - return 0; -} - -// Win32 implementation -bool NetworkServer::BattlEye::Init() -{ - _initFailedReason = BEReasonOther; - _initialized = false; - const char *installPath = "BattlEye\\BEServer.dll"; - char launchPath[MAX_PATH]; - if (!GetBELaunchPath(launchPath)) return false; - - int curBEVersion = 0; - if (QIFileFunctions::FileExists(installPath)) - { - GFileServerFunctions->FlushReadHandle(installPath); - // Get the BEClient.dll version from installPath first - HMODULE installLibrary = LoadLibrary(installPath); - int instVersion = GetBEVersion(installLibrary); - if (installLibrary) - FreeLibrary(installLibrary); - - CreatePath(launchPath); - strcat(launchPath, "BEServer.dll"); - // try to load the dll from the cache - _library = LoadLibrary(launchPath); - if (_library) - { // check whether the BE is updated to the last version - curBEVersion = GetBEVersion(_library); - if (instVersion>curBEVersion) - { - FreeLibrary(_library); - _library = NULL; // so it will be repaired from the install path - } - } - if (!_library) - { - // install / repair the live copy from the install path - chmod(launchPath, S_IREAD | S_IWRITE); - unlink(launchPath); - QIFileFunctions::Copy(installPath, launchPath); - _library = LoadLibrary(launchPath); - if (!_library) return false; -#if _ENABLE_DEDICATED_SERVER - ::ConsoleF(Format("BattlEye server updated to version: %d", instVersion)); -#endif - curBEVersion = instVersion; - } - } - else - { - // BattlEye removed, remove also from the cache - strcat(launchPath, "BEServer.dll"); - chmod(launchPath, S_IREAD | S_IWRITE); - unlink(launchPath); - _initFailedReason = BEReasonNotInstalled; - return false; - } - - InitF *init = (InitF *)GetProcAddress(_library, "Init"); - - _gameParams.pstrGameVersion = APP_NAME " " APP_VERSION_TEXT "." STRINGIZE(BUILD_NO); - _gameParams._execCommand = &ExecuteCommand; - _gameParams._kickPlayer = &KickPlayer; - _gameParams._printMessage = &PrintMessage; - if ((curBEVersionFlushReadHandle(installPath); - CreatePath(launchPath); - strcat(launchPath, "beserver.so"); - // use the install copy instead - _library = dlopen(launchPath, RTLD_LAZY); - if (!_library) - { - // install / repair the live copy from the install path - chmod(launchPath, S_IREAD | S_IWRITE); - unlink(launchPath); - QIFileFunctions::Copy(installPath, launchPath); - _library = dlopen(launchPath, RTLD_LAZY); - if (!_library) return false; - } - } - else - { - // BattlEye removed, remove also from the cache - strcat(launchPath, "beserver.so"); - chmod(launchPath, S_IREAD | S_IWRITE); - unlink(launchPath); - _initFailedReason = BEReasonNotInstalled; - return false; - } - int curBEVersion = GetBEVersion(_library); - - InitF *init = (InitF *)dlsym(_library, "Init"); - _gameParams.pstrGameVersion = APP_NAME " " APP_VERSION_TEXT "." STRINGIZE(BUILD_NO); - _gameParams._execCommand = &ExecuteCommand; - _gameParams._kickPlayer = &KickPlayer; - _gameParams._printMessage = &PrintMessage; - if ((curBEVersion *identities = server->GetIdentities(); - if (identities) - { - for (int i=0; iSize(); i++) - { - const PlayerIdentity &identity = identities->Get(i); - sockaddr_in address; - server->_server->GetClientAddress(identity.dpnid, address); - AddPlayer(identity.dpnid, address.sin_addr.s_addr, address.sin_port, identity.name); -#if _ENABLE_STEAM_OWNERSHIP - PlayerGUIDReceived(identity.dpnid, CSteamID((uint64)identity._steamID)); -#elif _ENABLE_STEAM_IDENTITY && defined(_WIN64) - if (identity._steamID != 0) - PlayerGUIDReceived(identity.dpnid, CSteamID((uint64)identity._steamID)); - else - PlayerGUIDReceived(identity.dpnid); -#else - PlayerGUIDReceived(identity.dpnid); -#endif - if (identity.clientState == NCSPlaying) - PlayerGoesInGame(identity.dpnid); - //else PlayerGoesInLobby(identity.dpnid); //<- assumed as default after AddPlayer - } - } -#endif - } - return true; -} - -void NetworkServer::BattlEye::Command(const char *command) -{ - if (_callbacks._command) (*_callbacks._command)(command); -} - -void NetworkServer::BattlEye::AddPlayer(int player, unsigned long address, unsigned short port, const char *name) -{ - if (_callbacks._addPlayer) (*_callbacks._addPlayer)(player, address, port, name); -} - -void NetworkServer::BattlEye::PlayerGoesInGame(int player) -{ - if (_callbacks._changePlayerStatus) (*_callbacks._changePlayerStatus)(player, 1); -} - -void NetworkServer::BattlEye::PlayerGoesInLobby(int player) -{ - if (_callbacks._changePlayerStatus) (*_callbacks._changePlayerStatus)(player, 0); -} - -void NetworkServer::BattlEye::PlayerDisconnected(int player) -{ - if (_callbacks._changePlayerStatus) (*_callbacks._changePlayerStatus)(player, -1); -} - -#if _ENABLE_STEAM_OWNERSHIP -void NetworkServer::BattlEye::PlayerGUIDReceived(int player, const CSteamID &id) -{ - if (_callbacks._receivedPlayerGUID) - { - uint64 steamId = id.ConvertToUint64(); - (*_callbacks._receivedPlayerGUID)(player, &steamId, sizeof(steamId)); - } -} - -#else -void NetworkServer::BattlEye::PlayerGUIDReceived(int player) -{ - if (_callbacks._receivedPlayerGUID) - { -#if _ENABLE_GAMESPY && _VERIFY_CLIENT_KEY - const char *hash = gcd_getkeyhash(GetGameID(), player); - (*_callbacks._receivedPlayerGUID)(player, (void *)hash, strlen(hash)); -#endif - } -} -#endif - -#if (_ENABLE_STEAM_IDENTITY && defined(_WIN64)) && !_ENABLE_STEAM_OWNERSHIP -void NetworkServer::BattlEye::PlayerGUIDReceived(int player, const CSteamID &id) -{ - if (_callbacks._receivedPlayerGUID) - { - uint64 steamId = id.ConvertToUint64(); - (*_callbacks._receivedPlayerGUID)(player, &steamId, sizeof(steamId)); - } -} -#endif - -void NetworkServer::BattlEye::PlayerGUIDIsValid(int player) -{ -}; - -#if _ENABLE_STEAM_OWNERSHIP || (_ENABLE_STEAM_IDENTITY && defined(_WIN64)) -void NetworkServer::BattlEye::PlayerGUIDIsValid(int player, const CSteamID &ownerId) -{ - if (_callbacks._playerGUIDIsValid) - { - uint64 steamId = ownerId.ConvertToUint64(); - (*_callbacks._playerGUIDIsValid)(player, &steamId, sizeof(steamId)); - } -} -#endif - -bool NetworkServer::BattlEye::UpdatePositionCallback(int player, const char *netId, float x, float y, float z, - float dirX, float dirY, float dirZ, float upX, float upY, float upZ, float asideX, float asideY, float asideZ) -{ - if (_callbacks._callbackUpdatePosition) - { - return (*_callbacks._callbackUpdatePosition)(player,netId,x,y,z,dirX,dirY,dirZ, upX, upY, upZ, asideX, asideY, asideZ); - } - return false; -} - -bool NetworkServer::BattlEye::UpdateDamageCallback(int player, const char *netId, float dam) -{ - if (_callbacks._callbackUpdateDamage) - { - return (*_callbacks._callbackUpdateDamage)(player,netId,dam); - } - return false; -} - -bool NetworkServer::BattlEye::PublicVariableCallback(int player, const char *name, const char *data) -{ - if (_callbacks._callbackPublicVariable) - { - return (*_callbacks._callbackPublicVariable)(player,name,data); - } - return false; -} - -bool NetworkServer::BattlEye::AttachObjectCallback(int player, const char *netId, const char *netIdAttachTo, int memoryIndex, float x, float y, float z) -{ - if (_callbacks._callbackAttachObject) - { - return (*_callbacks._callbackAttachObject)(player,netId,netIdAttachTo,memoryIndex,x,y,z); - } - return false; -} - -void NetworkServer::BattlEye::PlayerChatReceived(int player, int channel, const char *message) -{ - if (_callbacks._receivedPlayerMessage) - (*_callbacks._receivedPlayerMessage)(player, channel, message); -} - -void NetworkServer::BattlEye::LoadedMission(const char *missionName) -{ - if (_callbacks._loadedMission) - (*_callbacks._loadedMission)(missionName); -} - -void NetworkServer::BattlEye::PrintMessage(const char *message) -{ -#if _ENABLE_DEDICATED_SERVER - bool firstLine = true; - while (const char *newline = strchr(message, '\n')) - { - RString line(message, newline - message); - ::ConsoleF(firstLine ? "BattlEye Server: %s" : " %s", cc_cast(line)); - firstLine = false; - message = newline + 1; - } - ::ConsoleF(firstLine ? "BattlEye Server: %s" : " %s", message); -#endif -} - -void NetworkServer::BattlEye::KickPlayer(int player, const char *reason) -{ - NetworkServer *server = GNetworkManager.GetServer(); - if (server) - { -#if _ENABLE_DEDICATED_SERVER - PlayerIdentity *identity = server->FindIdentity(player); - ::ConsoleF("Player %s kicked off by BattlEye: %s", identity ? cc_cast(identity->name) : "", reason); - -/* -// using DisconnectMessage is not sufficient as we need the kick being immediate -// BattleEye "support" attitude: -// "Note that this is of course when the ArmA client does not disconnect itself, -// which it does when you click OK in the BE kick message box - but not before; -// naturally the server itself has to do this to have control and not to allow -// the player to stay on the server with some exploit" - DisconnectMessage msg; - msg._message = Format("Kicked off by BattlEye: %s", reason); - server->SendMsg(player, &msg, NMFGuaranteed); -*/ - - server->KickOff(player,KORBattlEye, reason); -#endif - } -} - -#if _ENABLE_DEDICATED_SERVER -// Large SQF files travel as several ordinary BattlEye commands. Reassemble and -// validate the complete script before putting it on the game-thread queue. -struct SDZBeSqfTransfer -{ - std::string id; - unsigned int expectedParts; - unsigned int expectedCrc; - unsigned int receivedParts; - unsigned int receivedBytes; - DWORD startedAt; - std::vector parts; - std::vector received; - - SDZBeSqfTransfer() : expectedParts(0), expectedCrc(0), receivedParts(0), receivedBytes(0), startedAt(0) {} - void Reset() - { - id.clear(); expectedParts = expectedCrc = receivedParts = receivedBytes = 0; startedAt = 0; - parts.clear(); received.clear(); - } -}; - -static SDZBeSqfTransfer SDZBeTransfer; - -static unsigned int SDZBeCrc32(const char *data, unsigned int length) -{ - unsigned int crc = 0xFFFFFFFF; - for (unsigned int i = 0; i < length; i++) - { - crc ^= (unsigned char)data[i]; - for (int bit = 0; bit < 8; bit++) - crc = (crc & 1) ? ((crc >> 1) ^ 0xEDB88320) : (crc >> 1); - } - return ~crc; -} - -static const char *SDZSkipSpaces(const char *text) -{ - while (*text == ' ' || *text == '\t') text++; - return text; -} - -static bool SDZReadToken(const char **cursor, std::string &token) -{ - const char *start = SDZSkipSpaces(*cursor); - if (!*start) return false; - const char *end = start; - while (*end && *end != ' ' && *end != '\t') end++; - token.assign(start, end - start); - *cursor = end; - return true; -} - -static bool SDZValidTransferId(const std::string &id) -{ - if (id.length() != 32) return false; - for (size_t i = 0; i < id.length(); i++) - if (!((id[i] >= '0' && id[i] <= '9') || (id[i] >= 'a' && id[i] <= 'f') || (id[i] >= 'A' && id[i] <= 'F'))) return false; - return true; -} - -static bool SDZHandleRconSqfTransfer(NetworkServer *server, const char *command) -{ - static const char beginPrefix[] = "#exec __SDZ_BEGIN__ "; - static const char partPrefix[] = "#exec __SDZ_PART__ "; - static const char endPrefix[] = "#exec __SDZ_END__ "; - if (!strnicmp(command, beginPrefix, sizeof(beginPrefix) - 1)) - { - SDZBeTransfer.Reset(); - const char *cursor = command + sizeof(beginPrefix) - 1; - std::string id, countText, crcText, extra; - if (!SDZReadToken(&cursor, id) || !SDZReadToken(&cursor, countText) || !SDZReadToken(&cursor, crcText) || - SDZReadToken(&cursor, extra) || !SDZValidTransferId(id)) - { - RptF("SDZ_BE_RCON: invalid large-SQF begin frame"); - return true; - } - char *parseEnd = NULL; - unsigned long count = strtoul(countText.c_str(), &parseEnd, 10); - if (!parseEnd || *parseEnd || count == 0 || count > 2048) - { - RptF("SDZ_BE_RCON: rejected large-SQF transfer with invalid part count"); - return true; - } - parseEnd = NULL; - unsigned long crc = strtoul(crcText.c_str(), &parseEnd, 16); - if (!parseEnd || *parseEnd || crc > 0xFFFFFFFFUL) - { - RptF("SDZ_BE_RCON: rejected large-SQF transfer with invalid checksum"); - return true; - } - SDZBeTransfer.id = id; - SDZBeTransfer.expectedParts = (unsigned int)count; - SDZBeTransfer.expectedCrc = (unsigned int)crc; - SDZBeTransfer.startedAt = GetTickCount(); - SDZBeTransfer.parts.resize(count); - SDZBeTransfer.received.resize(count, 0); - RptF("SDZ_BE_RCON: large-SQF transfer started (%u parts)", (unsigned int)count); - return true; - } - - if (!strnicmp(command, partPrefix, sizeof(partPrefix) - 1)) - { - if (SDZBeTransfer.expectedParts == 0 || GetTickCount() - SDZBeTransfer.startedAt > 120000) - { - SDZBeTransfer.Reset(); - RptF("SDZ_BE_RCON: rejected large-SQF part without an active transfer"); - return true; - } - const char *cursor = command + sizeof(partPrefix) - 1; - std::string id, indexText; - if (!SDZReadToken(&cursor, id) || !SDZReadToken(&cursor, indexText) || id != SDZBeTransfer.id) - { - RptF("SDZ_BE_RCON: rejected large-SQF part with invalid transfer id"); - return true; - } - char *parseEnd = NULL; - unsigned long index = strtoul(indexText.c_str(), &parseEnd, 10); - if (!parseEnd || *parseEnd || index >= SDZBeTransfer.expectedParts || *cursor != ' ') - { - RptF("SDZ_BE_RCON: rejected malformed large-SQF part"); - return true; - } - const char *chunk = cursor + 1; - size_t chunkLength = strlen(chunk); - if (chunkLength == 0 || chunkLength > 900) - { - RptF("SDZ_BE_RCON: rejected malformed large-SQF part"); - return true; - } - if (SDZBeTransfer.received[index]) - { - const std::string &receivedChunk = SDZBeTransfer.parts[index]; - if (receivedChunk.size() != chunkLength || receivedChunk.compare(0, receivedChunk.size(), chunk, chunkLength) != 0) - RptF("SDZ_BE_RCON: conflicting duplicate large-SQF part"); - return true; - } - if (SDZBeTransfer.receivedBytes + chunkLength > 1048576) - { - SDZBeTransfer.Reset(); - RptF("SDZ_BE_RCON: rejected SQF script larger than 1 MiB"); - return true; - } - SDZBeTransfer.parts[index].assign(chunk, chunkLength); - SDZBeTransfer.received[index] = 1; - SDZBeTransfer.receivedParts++; - SDZBeTransfer.receivedBytes += (unsigned int)chunkLength; - return true; - } - - if (!strnicmp(command, endPrefix, sizeof(endPrefix) - 1)) - { - const char *cursor = command + sizeof(endPrefix) - 1; - std::string id, extra; - if (!SDZReadToken(&cursor, id) || SDZReadToken(&cursor, extra) || id != SDZBeTransfer.id || - SDZBeTransfer.expectedParts == 0 || GetTickCount() - SDZBeTransfer.startedAt > 120000) - { - SDZBeTransfer.Reset(); - RptF("SDZ_BE_RCON: rejected invalid or expired large-SQF end frame"); - return true; - } - if (SDZBeTransfer.receivedParts != SDZBeTransfer.expectedParts) - { - RptF("SDZ_BE_RCON: incomplete large-SQF transfer (%u/%u parts)", SDZBeTransfer.receivedParts, SDZBeTransfer.expectedParts); - SDZBeTransfer.Reset(); - return true; - } - std::string script; - script.reserve(SDZBeTransfer.receivedBytes); - for (unsigned int i = 0; i < SDZBeTransfer.expectedParts; i++) script += SDZBeTransfer.parts[i]; - unsigned int expectedCrc = SDZBeTransfer.expectedCrc; - unsigned int receivedBytes = (unsigned int)script.length(); - SDZBeTransfer.Reset(); - if (SDZBeCrc32(script.c_str(), receivedBytes) != expectedCrc) - { - RptF("SDZ_BE_RCON: rejected large-SQF transfer with checksum mismatch"); - return true; - } - if (!server || script.empty()) - { - RptF("SDZ_BE_RCON: rejected empty large-SQF script or unavailable server"); - return true; - } - server->QueueExec(BOT_CLIENT, RString(script.c_str())); - RptF("SDZ_BE_RCON: queued reassembled SQF (%u bytes)", receivedBytes); - return true; - } - return false; -} -#endif - -void NetworkServer::BattlEye::ExecuteCommand(const char *command) -{ -#if _ENABLE_DEDICATED_SERVER - // BattlEye invokes this callback on the dedicated server. There is normally - // no local NetworkClient there, so forwarding #exec through the client drops - // the command. Queue it for the regular server simulation thread instead. - if (!command || !*command) return; - - if (strlen(command) > 1000) - { - RptF("SDZ_BE_RCON: rejected BattlEye command longer than 1000 bytes"); - return; - } - - NetworkServer *server = GNetworkManager.GetServer(); - if (SDZHandleRconSqfTransfer(server, command)) return; - - if (strnicmp(command, "#exec", 5) == 0 && (command[5] == 0 || command[5] == ' ' || command[5] == '\t')) - { - const char *expression = command + 5; - while (*expression == ' ' || *expression == '\t') expression++; - if (!*expression) - { - RptF("SDZ_BE_RCON: rejected empty #exec command"); - return; - } - if (!server) - { - RptF("SDZ_BE_RCON: rejected #exec because the server is unavailable"); - return; - } - server->QueueExec(BOT_CLIENT, RString(expression)); - RptF("SDZ_BE_RCON: queued #exec (%d bytes)", (int)strlen(expression)); - return; - } - - NetworkClient *client = GNetworkManager.GetClient(); - if (client) - { - client->ProcessCommand(RString(command)); - } -#endif -} - -#endif - -// open the mpStatistics.log file and write the required statistics string -// it open and close the mpStatistics.log file each time -static void LogMPStatistics(RString str) -{ - FILE *file = NULL; - char logFilename[MAX_PATH]; - if ( GetLocalSettingsDir(logFilename) ) - { - CreateDirectory(logFilename, NULL); - TerminateBy(logFilename, '\\'); - strcat(logFilename, "mpStatistics.log"); - file = fopen(logFilename, "a+"); - - if (file) - { - fputs(cc_cast(str), file); - fclose(file); - } - } -} - -//! Load ban list from file -/*! -\param filename name (path) of file -\param list output ban list -*/ -static void LoadBanList(RString filename, FindArray &list) -{ - list.Clear(); - QIFStream f; - f.open(filename); - while (!f.eof() && !f.fail()) - { - int c = f.get(); - if (f.eof() || f.fail()) return; - while (isspace(c) || c==',' || c==';') - { - c = f.get(); - if (f.eof() || f.fail()) return; - } - const int MaxBanIdLength = 255; - char value[MaxBanIdLength+1]; - int ix=0; - while (!isspace(c) && c!=',' && c!=';' && !f.eof() && ix &list) -{ - QOFStream f(filename); - for (int i=0; i=162 - const int DefaultSecureIdRequired = 1; - #pragma message WARN_MESSAGE("warning: Remove obsolete code") -#else - const int DefaultSecureIdRequired = 0; -#endif - -#if _ENABLE_STEAM_MATCHMAKING && _ENABLE_DEDICATED_SERVER - -#define STEAM_STAT_DEFINE_STATICS(name, Type, DefaultValue) \ - RString Stat_##name::apiName=RString(#name); - -STEAM_STATS_LIST(STEAM_STAT_DEFINE_STATICS) - -#define CREATE_STAT_VAR(name, Type, DefaultValue) \ - _stats[EStat_##name] = new Stat_##name; - -SteamStatistics::SteamStatistics() - : _initialized(false), _lastStatsReceivedTime(0), _lastStatsStoredTime(0), _nextStoreStatsTime(0), _nextRequestStatsTime(0), - _lastCharacterTimeAliveSyncTime(0) -{ - for (int i=0; i SteamStatistics::achievementsDef; - -void SteamStatistics::Init(CSteamID &steamID) -{ - _steamID = steamID; - //LogF("STEAM: SteamStatiscics::Init(%llu)", steamID.ConvertToUint64()); - - // fill in the SteamStat *_stats[] array - STEAM_STATS_LIST(CREATE_STAT_VAR) - SteamAPICall_t hSteamAPICall = SteamGameServerStats()->RequestUserStats(_steamID); - // set the function to call when this API completes - _steamCallResultUserStatsReceived.Set( hSteamAPICall, this, &SteamStatistics::OnUserStatsReceived ); - - _achievements.Realloc(achievementsDef.Size()); - _achievements.Resize(achievementsDef.Size()); - for (int i=0; i<_achievements.Size(); i++) - { - _achievements[i].def = &achievementsDef[i]; //SteamAchievement::ix is index into achievementsDef array - } -} - -void SteamStatistics::Reset(SteamStatsEnum stat) -{ - if (_stats[stat]) - { - _stats[stat]->SetDefault(); - _stats[stat]->SetStat(_steamID); - StoreStats(); - } -} - -void SteamStatistics::OnUserStatsReceived( GSStatsReceived_t *pCallback, bool bIOFailure ) -{ - //LogF("STEAM: OnUserStatsReceived %llu", pCallback->m_steamIDUser.ConvertToUint64()); - if ( bIOFailure ) - { - _nextRequestStatsTime = ::GetTickCount() + GRandGen.RandomValue()*120*1000; //within 0..120 seconds - return; - } - if (pCallback->m_steamIDUser != _steamID) - { - RptF("STEAM: Unexpected steamID in OnUserStatsReceived!"); - return; - } - - // even when user has no stats, we can consider SteamStatistics as initialized - _nextRequestStatsTime = 0; - _initialized = true; - - if (pCallback->m_eResult == k_EResultFail) // user has no stats - { - //LogF("STEAM: storing default statistics"); - for (int i=0; iSetDefault(); - _stats[i]->SetStat(_steamID); - } - StoreStats(); - return; - } - - // There was no Failure => fill in stats state - for (int i=0; iGetStat(_steamID); - - // fill in achievements state - for (int i=0; i<_achievements.Size(); i++) - { - AchievementDef *aDef = _achievements[i].def; - if ( aDef && !aDef->apiName.IsEmpty() ) - { - if ( SteamGameServerStats()->GetUserAchievement( _steamID, aDef->apiName, &_achievements[i].unlocked ) ) - LogF(" achievement state: %s = %d", cc_cast(aDef->apiName), _achievements[i].unlocked); - else - LogF(" achievement state request has FAILED!"); - } - } - - _lastStatsReceivedTime = _lastCharacterTimeAliveSyncTime = ::GetTickCount(); -} - -void SteamStatistics::OnUserStatsStored( GSStatsStored_t *pCallback, bool bIOFailure ) -{ - //LogF("STEAM: OnUserStatsStored %llu", pCallback->m_steamIDUser.ConvertToUint64()); - _lastStatsStoredTime = ::GetTickCount(); - _nextStoreStatsTime = _lastStatsStoredTime + 60*1000 + GRandGen.RandomValue()*120*1000; //within 1..3 min -} - -void SteamStatistics::Simulate() -{ - if (_initialized) - { - DWORD curtime = ::GetTickCount(); - if ( StatsValid() ) - { - //{@ characterTimeAlive Update - Stat_characterTimeAlive *stat = dynamic_cast(_stats[EStat_characterTimeAlive]); - if (stat) - { - int aliveTime = stat->GetValue(); - if ( _lastCharacterTimeAliveSyncTime && curtime>_lastCharacterTimeAliveSyncTime ) - { - int timeElapsed = curtime - _lastCharacterTimeAliveSyncTime; - int overtimeMS = timeElapsed % 1000; - timeElapsed /= 1000; //in seconds - if (timeElapsed) - { - stat->SetValue(aliveTime + timeElapsed); - stat->SetStat(_steamID); - _lastCharacterTimeAliveSyncTime = curtime - overtimeMS; // we should add these miliseconds later - //LogF("STEAM: characterTimeAlive=%d", aliveTime + timeElapsed); - } - } - } - //@} - } - // check achievements - for (int i=0; i<_achievements.Size(); i++) - { - SteamAchievement &achvm = _achievements[i]; - if (!achvm.unlocked && achvm.def) - { - if (achvm.def->statIx>=0 && achvm.def->statIxstatIx]; - if (stat->TestAchievementUnlocked(achvm.def->unlockValue)) - { - if (SteamGameServerStats()->SetUserAchievement(_steamID, achvm.def->apiName)) //UnLOCK achievement - { - achvm.unlocked = true; - _nextStoreStatsTime = curtime; //force storeStats - LogF("STEAM: achievement %s UNLOCKED", cc_cast(achvm.def->apiName)); - } - } - } - } -#if USER_Bebul - else // Bebul can reset the achievement manualy - { - static bool doIt = false; - if (doIt) - { - doIt = false; - achvm.unlocked = false; - SteamGameServerStats()->ClearUserAchievement( _steamID, achvm.def->apiName ); - _nextStoreStatsTime = curtime; //force storeStats - RptF("STEAM: achievement %s CLEARED", cc_cast(achvm.def->apiName)); - } - } -#endif - } - if ( _nextRequestStatsTime && (curtime>=_nextRequestStatsTime) && !_steamCallResultUserStatsReceived.IsActive() ) - { - _nextRequestStatsTime = 0; - SteamAPICall_t hSteamAPICall = SteamGameServerStats()->RequestUserStats(_steamID); - // set the function to call when this API completes - _steamCallResultUserStatsReceived.Set( hSteamAPICall, this, &SteamStatistics::OnUserStatsReceived ); - } - if ( !_nextStoreStatsTime && _lastStatsReceivedTime ) // data are valid, we can store them - { - _nextStoreStatsTime = curtime + 60*1000 + GRandGen.RandomValue()*120*1000; //within 1..3 minutes - } - else if ( curtime>=_nextStoreStatsTime ) - { - StoreStats(); - } - } -} - -void SteamStatistics::StoreStats() -{ - if ( !_steamCallResultUserStatsStored.IsActive() ) - { - _lastStatsStoredTime = ::GetTickCount(); - _nextStoreStatsTime= _lastStatsStoredTime + 10*60*1000; //10 minutes, but it SHOULD be reset, as OnUserStatsStored callback is supposed to be called - SteamAPICall_t hSteamAPICall = SteamGameServerStats()->StoreUserStats(_steamID); - // set the function to call when this API completes - _steamCallResultUserStatsStored.Set( hSteamAPICall, this, &SteamStatistics::OnUserStatsStored ); - } -} - -#endif - -#if _ENABLE_STEAM_MATCHMAKING && _ENABLE_DEDICATED_SERVER -void AchievementDef::SetApiName(RString name) -{ -#define STEAM_STAT_TEST(name, Type, DefaultValue) \ - if (apiName==Stat_##name::apiName) { statIx=EStat_##name; break; } - - apiName = name; - do { - // note: macro uses apiName just set - STEAM_STATS_LIST(STEAM_STAT_TEST) - } while(false); -} -#endif - -NetworkServer::NetworkServer(NetworkManager *parent, RString name, RString password, int maxPlayers, int port, bool isPrivate) -: NetworkComponent(parent) -#if _ENABLE_DEDICATED_SERVER -, _globals(&_evaluator, "server", false) -#endif -#if _ENABLE_STEAM_MATCHMAKING -, _callbackSteamServersConnected(this, &NetworkServer::OnSteamServersConnected) -, _callbackSteamServersConnectFailure(this, &NetworkServer::OnSteamServersConnectFailure) -, _callbackSteamServersDisconnected(this, &NetworkServer::OnSteamServersDisconnected) -, _callbackPolicyResponse(this, &NetworkServer::OnPolicyResponse) -#endif -{ - _serverState = NSSSelectingMission; - _serverStateTime = GlobalTickCount(); - _serverTimeOutSent = INT_MAX; - #if _ENABLE_DEDICATED_SERVER - _sqfExecBusy = false; - #endif - _connectionDesync = CDGood; - _desyncTotalUpdateNext = GlobalTickCount(); - _desyncTotalAvg = 0; - _desyncTotalMax = 0; - _buildNoRequired = 0; - _secureIdRequired = DefaultSecureIdRequired; - _longitude = INT_MAX; - _latitude = INT_MAX; - _disable3rdPerson = 0; - _environmentTimeMul = 0.0f; - - #if USER_Ondra - _updatesGuaranteed = true; - #else - _updatesGuaranteed = false; - #endif - _verifySignatures = false; - _validateCDKey = false; - _doNotReport = false; - _qrInitDone = false; - _persistent = false; - _destroyDisconnected = true; - - _maxPlayersLimit = maxPlayers; - _totalSlots = INT_MAX; - - _squadChecksTimeout = 0; - - _serverTime = _serverTimeOfEstimatedEnd = _secondsToEstimatedEnd = 0; - _serverTimeInitTickCount = ::GetTickCount(); - _nextServerTimeUpdate = _serverTime + ServerTimeUpdateInterval; - - /* - if (IsDedicatedServer() && !isPrivate) - { - _geoJob = new GeoLocationJob(); - _geoJob->_longitude = _longitude; - _geoJob->_latitude = _latitude; - GJobManager.CreateJob(_geoJob,10000); - } - */ - -#if _ENABLE_DEDICATED_SERVER - // provide some reasonable default - _difficulty = Glob.config.diffDefault; -#endif - -#if _VBS2 && _VBS2_LITE - _memoryWrite = false; - _nextRanUpdate = 0; -#endif - - _password = password.GetLength() > 0; - - _nextPlayerID = 2; // value 1 is reserved for static objects - - // make sure statistics from previous session will not be present - GStats.ClearMission(); - - Verify(Init(name, password, maxPlayers, port)); - - _param1 = 0; - _param2 = 0; - _paramsArray.Clear(); - - _timeLeftLastValue = 0; - _timeLeftLastTime = 0; - _timeLeftLastValueBcast = 0; - -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - _kickDuplicate = false; - _dedicated = false; - _missionIndex = -1; - - _gameMaster = AI_PLAYER; - _admin = false; - _restart = false; - _reassign = false; - - Monitor(0); - _debugNext = INT_MAX; - _debugInterval = 0; - - InitEvaluator(); -#endif -//} - _pingUpdateNext = GlobalTickCount() + 5000; - - _sessionLocked = false; - - _equalModRequired = false; - - // ensure no content remain - if (_server) DeleteDirectoryStructure(GetServerTmpDir(), false); - - #if _ENABLE_DEDICATED_SERVER - if (!IsDedicatedServer()) - #endif - { - LoadBanList(GetUserDirectory() + RString("ban.txt"), _banListLocal); - } - #if _VERIFY_CLIENT_KEY - { // load secure ban list on DS as well - RString banSecureFilename = GetUserDirectory() + RString("banSecure.txt"); - { - QIFStream f; - f.open(banSecureFilename); - if (f.rest()>0) - { - AutoArray banSecureInput; - banSecureInput.Resize(f.rest()); - f.read(banSecureInput.Data(),banSecureInput.Size()); - ParseSignedKeys(_banListSecure.keys,_banListSecure.signature,banSecureInput.Data()); - } - } - GFileServerFunctions->FlushReadHandle(banSecureFilename); - } - #endif - -#if _ENABLE_GAMESPY - // check that the game's back-end is available - // we need it due to NAT Negotiation - Ref p = ProgressStartExt(true, LocalizeString(IDS_LOAD_WORLD)); - GSIStartAvailableCheck(GetGameName()); - GSIACResult result; - while ((result = GSIAvailableCheckThink()) == GSIACWaiting) - { - msleep(5); - ProgressRefresh(); - } - ProgressFinish(p); -#endif - -#if _ENABLE_STEAM - -#if _ENABLE_STEAM_MATCHMAKING && _ENABLE_DEDICATED_SERVER - ConstParamEntryPtr achEntry = Pars.FindEntry("CfgAchievements"); - if (achEntry && achEntry->IsClass()) - { - SteamStatistics::achievementsDef.Clear(); - for (int i=0; iGetEntryCount(); i++) - { - ParamEntryVal cls = achEntry->GetEntry(i); - // Steam APIName - int ix = SteamStatistics::achievementsDef.Add(); - AchievementDef &achievement = SteamStatistics::achievementsDef[ix]; - achievement.SetApiName(cls.GetName()); //ix set inside - ConstParamEntryPtr entry = cls.FindEntry("progressStat"); - if (entry) achievement.progressStat = (*entry); - entry = cls.FindEntry("unlockValue"); - if (entry) achievement.unlockValue = (*entry); - } - } -#endif -#endif - -#if _ENABLE_STEAM_MATCHMAKING - // ports for Steam services, default are values used in prev. versions - _steamPort = 8766; - _steamQueryPort = 27016; -#endif -} - -void NetworkServer::CreateDebugWindow() -{ -#if _ENABLE_CHEATS - _debugWindow = new DebugListWindow("Server debug"); -#endif -} - -#include "../Protect/selectProtection.h" - -extern const int DefaultNetworkPort; - -DWORD GetGameLanguage() -{ - // use internal language ID instead (and mark it) - int GetLangID(); - return 0x10000 | GetLangID(); -} - - -void NetworkServer::SendMuteList(const PlayerIdentity &id) -{ -#if _ENABLE_MP - int to = id.dpnid; - - RemoteMuteListMessage msg; - - for (int i=0; i<_players.Size(); i++) - { - const NetworkPlayerInfo &info = *_players[i]; - if (info.dpid == to) continue; - - for (int j=0; j 0) - { - et -= Glob.time.toFloat(); - timeleft = toInt(et / 60.0); - saturateMax(timeleft, 1); - } - return timeleft; - } - return 0; -} - -RString GetDefaultSessionName(RString playerName) -{ - char hostName[128]; - bool getLocalName(char *name, unsigned len); - if (getLocalName(hostName, 128)) - { - if (playerName.GetLength() > 0) - return Format(LocalizeString(IDS_SESSION_NAME_FORMAT), cc_cast(playerName), cc_cast(hostName)); - else - return hostName; - } - return LocalizeString(IDS_SESSION_NAME_INIT); -} - -// Macrovision CD Protection -#if _ENABLE_MP - -//! Protected version of NetworkServer::Init -/*! -\param port IP port where server communicate -\param password session password -\patch 1.11 Date 07/31/2001 by Jirka -- Improved: Multiplayer session description -\patch 1.11 Date 08/02/2001 by Jirka -- Changed: Temporary directory on server in now Tmp instead of Tmp -\patch 1.24 Date 09/19/2001 by Jirka -- Added: parameter "hostname" added to dedicated server config -- Added: port displayed in session description if not default -- Added: parameter "maxPlayers" added to dedicated server config -\patch 1.30 Date 11/01/2001 by Jirka -- Added: parameter "voteMissionPlayers" added to dedicated server config - when no Missions section in server config and at least "voteMissionPlayers" (default = 1) - players are connected, mission voting is started automatically -\patch 1.42 Date 1/9/2002 by Jirka -- Added: parameter "voiceOverNet" added to dedicated server config (default = true) -*/ - -CDP_DECL NetTranspServer * __cdecl CDPInitServer(RString name, RString password, int maxPlayers, int port, ParamEntryPar cfg) -{ - NetTranspServer *server = NULL; - SECUROM_MARKER_HIGH_SECURITY_ON(10) - //Direct play has been eliminated from here - server = CreateNetServer(cfg); - ProgressRefresh(); - if (!server) return NULL; - - // load some settings from Flashpoint.cfg - server->SetNetworkParams(cfg); - - MPVersionInfo versionInfo; - versionInfo.versionActual = MP_VERSION_ACTUAL; - versionInfo.versionRequired = MP_VERSION_REQUIRED; - versionInfo.mission[0] = 0; - versionInfo.serverState = NSSSelectingMission; -#if USE_MOD_LIST - RString GetModListNames(); - strncpy(versionInfo.mod, GetModListNames(), MOD_LENGTH); -#else - strncpy(versionInfo.mod, GLoadedContentHash, MOD_LENGTH); -#endif - versionInfo.mod[MOD_LENGTH - 1] = 0; - - bool voiceOverNet = true; - - bool equalModRequired = false; - -#if _ENABLE_DEDICATED_SERVER - if (IsDedicatedServer()) - { - GameDataNamespace globals(NULL, RString(), false); // TODO: parsing namespace if access to globals needed - - ParamFile cfg; - RString GetServerConfig(); - cfg.Parse(GetServerConfig(), NULL, NULL, &globals); - - ConstParamEntryPtr entry = cfg.FindEntry("hostName"); - if (entry) name = *entry; - if (name.GetLength() == 0) name = GetDefaultSessionName(RString()); - - ConstParamEntryPtr instId = cfg.FindEntry("instanceId"); - if (instId) - { - RString id = *instId; - SetInstanceId(id.Data()); - } - - ConstParamEntryPtr instKey = cfg.FindEntry("instanceKey"); - if (instKey) - { - RString key = *instKey; - SetInstanceKey(key.Data()); - } - - entry = cfg.FindEntry("voiceOverNet"); - if (entry) - { - voiceOverNet = *entry; - } - - entry = cfg.FindEntry("equalModRequired"); - if (entry) equalModRequired = *entry; - - // on dedicated server, use only server name as session name - // playerName = LocalizeString(IDS_DEDICATED_SERVER); - } - else -#endif - { - if (name.GetLength() == 0) - { -#if _VBS2 // VBS2 nickname - RString playerName = Glob.header.playerHandle; -#else - RString playerName = Glob.header.GetPlayerName(); -#endif - name = GetDefaultSessionName(playerName); - } - } - - bool ok = server->Init( - name, password, maxPlayers, port, - GetGameLanguage(), Glob.config.difficulty, - versionInfo, equalModRequired, MAGIC_APP - ); - - if (!ok) - { - delete server; - return NULL; - } - -#if _VBS3 - // Force the VON off if requested by the program argument - extern bool DisableVON; - if (DisableVON) - { - voiceOverNet = false; - } -#endif - - if (voiceOverNet) - server->InitVoice(); - - char buffer[256]; - sprintf(buffer, "Tmp%d", server->GetSessionPort()); - ServerTmpDir = buffer; - - SECUROM_MARKER_HIGH_SECURITY_OFF(10) - - return server; -} -#endif // _ENABLE_MP - -void ParseFlashpointCfg(ParamFile &file); -void SaveFlashpointCfg(ParamFile &file); - -/*! -\patch 1.89 Date 10/25/2002 by Jirka -- Added: Item "proxy" added to Flashpoint.cfg to enforce proxy server used to download xml squad page etc. -*/ - -bool NetworkServer::Init(RString name, RString password, int maxPlayers, int port) -{ -#if _ENABLE_MP - // load some settings from Flashpoint.cfg - ParamFile cfg; - ParseFlashpointCfg(cfg); - - ConstParamEntryPtr entry = cfg.FindEntry("proxy"); - if (entry) _proxy = *entry; - - _longitude = cfg.ReadValue("serverLongitude",INT_MAX); - _latitude = cfg.ReadValue("serverLatitude",INT_MAX); - _longLatAuto = cfg.ReadValue("serverGeoLocAuto",true); - - _indexToPlayerId.Add(BOT_CLIENT); - // Macrovision CD Protection - //_serverUpBandwidth = 1000000000; // assume very fast bandwidth unless proven otherwise - 1Gbps - _server = CDPInitServer(name, password, maxPlayers, port, cfg); - return _server != NULL; - #else - return false; - #endif -} - -void NetworkServer::InitVoice() -{ - if (!_parent->IsVoNDisabled()) - if (_server) _server->InitVoice(); -} - -NetworkServer::~NetworkServer() -{ -#if _ENABLE_GAMESPY - CloseGeoJob(); -#endif - RemoveSystemMessages(); - - SetServerState(NSSNone); - -//{ QUERY & REPORTING SDK -#if _ENABLE_GAMESPY - DoneQR(); -#endif -//} - -#if _ENABLE_STEAM_MATCHMAKING - DoneSteam(); -#endif - - Done(); - -#if _ENABLE_CHEATS - if (_debugWindow) _debugWindow->Close(); -#endif -} - -void NetworkServer::Done() -{ -#if PEER2PEER - if (_p2pServer) _p2pServer = NULL; -#endif - - // _dp->CancelAsyncOperation(NULL, DPNCANCEL_ALL_OPERATIONS); - RemoveUserMessages(); - if (_server) DeleteDirectoryStructure(GetServerTmpDir(), true); - _server = NULL; -} - -/*! -\patch 5095 Date 12/5/2006 by Jirka -- Fixed: Dedicated server crash -*/ - -int NetworkServer::GetMaxPlayers() const -{ - int maxPlayers = GetMaxPlayersLimit(); - if (_serverState >= NSSAssigningPlayers) - { // maxPlayers from mission description.ext - saturateMin(maxPlayers, GetMaxMissionPlayers()); - } - saturateMin(maxPlayers, _totalSlots); - - return maxPlayers; -} - -int NetworkServer::GetMaxPlayersSafe(int bandwidthPerClient, int round) const -{ - int maxPlayers = GetMaxPlayersLimit(); - // always return even number - maxPlayers = maxPlayers/round*round; - if (maxPlayersGetURL(address, addressLen); -} - -/*! -\patch 1.21 Date 08/23/2001 by Jirka -- Improved: session description -*/ -void NetworkServer::UpdateSessionDescription() -{ - if (_server) - { - RString gameType, island; - LocalizedString mission; - int timeleft = 0; - int difficulty = Glob.config.difficulty; - if (_serverState >= NSSAssigningPlayers) - { - gameType = _missionHeader._gameType; - mission = _missionHeader._name; - island = _missionHeader._island; - timeleft = GetSessionTimeLeft(); - } - _server->UpdateSessionDescription( - _serverState, gameType, mission, island, timeleft, difficulty - ); - } -} - -RString QosInfo::GetLocalizedMissionName() const -{ - int type = missionLocalizedType-' '; - saturate(type,LocalizedString::PlainText,LocalizedString::Stringtable); - LocalizedString str(LocalizedString::Type(type),missionId.cstr()); - return str.GetLocalizedValue(); -} - -void QosInfo::SetMissionName(const LocalizedString &str) -{ - missionLocalizedType = ' '+str._type; - strcpy(missionId,str._id); -} - -DWORD WINAPI NetworkServer::GeoJobThreadFunction(void *ctx) -{ - GeoJobThread *geoJob = (GeoJobThread *)ctx; - - float latitude,longitude; - GeoLocationFromIP(latitude,longitude,geoJob->_ip); // location of my own IP address - - if (longitude_latitude.SetResult(toInt(latitude)); - geoJob->_longitude.SetResult(toInt(longitude)); - } - else - { - geoJob->_latitude.SetResult(INT_MAX); - geoJob->_longitude.SetResult(INT_MAX); - } - return 0; -} - - -/*! -\patch 1.21 Date 08/22/2001 by Jirka -- Added: GameSpy Query & Reporting SDK support for dedicated server -\patch_internal 1.86 Date 10/16/2002 by Jirka -- Added: ASE SDK support for dedicated server -\patch_internal 1.90 Date 11/12/2002 by Jirka -- Fixed: dedicated server was reporting to ASE even for reportingIP="" -*/ - - -void NetworkServer::OnPublicAddressKnown(int ip) -{ - BString<256> ipText; - sprintf(ipText,"%d.%d.%d.%d",ip&0xff, (ip>>8)&0xff, (ip>>16)&0xff, (ip>>24)&0xff); - - if (!_geoJob && IsDedicatedServer() && !_doNotReport) - { - _geoJob = new GeoJobThread(); - _geoJob->_ip = ipText.cstr(); -#if USE_MT_LIB_FOR_JOBS - _geoJob->_thread.Init( CreateMTThreadOnCPU(64 * 1024, GeoJobThreadFunction, _geoJob, 2, MultiThread::ThreadBase::PriorityNormal, "GeoLocation")); -#else - _geoJob->_thread.Init( CreateThreadOnCPU(64 * 1024, GeoJobThreadFunction, _geoJob, 2, THREAD_PRIORITY_NORMAL, "GeoLocation")); -#endif - } -} - -//{ QUERY & REPORTING SDK -#if _ENABLE_GAMESPY - -// GameSpy callbacks - -/*! -\patch 5090 Date 11/27/2006 by Jirka -- Fixed: Possible crash when hosting MP session -*/ - -// Called when a server key needs to be reported -void serverkey_callback(int keyid, qr2_buffer_t outbuf, void *userdata) -{ - if (GNetworkManager.GetServer() != userdata) return; - NetworkServer *server = ((NetworkServer *)userdata); - if (server->IsValid()) server->OnQueryServer(keyid, outbuf); -} - -// Called when a player key needs to be reported -void playerkey_callback(int keyid, int index, qr2_buffer_t outbuf, void *userdata) -{ - if (GNetworkManager.GetServer() != userdata) return; - NetworkServer *server = ((NetworkServer *)userdata); - if (server->IsValid()) server->OnQueryPlayer(keyid, index, outbuf); -} - -// Called when a team key needs to be reported -void teamkey_callback(int keyid, int index, qr2_buffer_t outbuf, void *userdata) -{ - if (GNetworkManager.GetServer() != userdata) return; - NetworkServer *server = ((NetworkServer *)userdata); - if (server->IsValid()) server->OnQueryTeam(keyid, index, outbuf); -} - -// Called when we need to report the list of keys we report values for -void keylist_callback(qr2_key_type keytype, qr2_keybuffer_t keybuffer, void *userdata) -{ - if (GNetworkManager.GetServer() != userdata) return; - NetworkServer *server = ((NetworkServer *)userdata); - if (server->IsValid()) server->OnQueryKeys(keytype, keybuffer); -} - -// Called when we need to report the number of players and teams -int count_callback(qr2_key_type keytype, void *userdata) -{ - if (GNetworkManager.GetServer() != userdata) return 0; - NetworkServer *server = ((NetworkServer *)userdata); - if (server->IsValid()) return server->OnQueryCount(keytype); - return 0; -} - -// Called if our registration with the GameSpy master server failed -void adderror_callback(qr2_error_t error, gsi_char *errmsg, void *userdata) -{ - // Display an error message to the user indicating that he is unable to host a game and why (e.g., UDP-blocking firewall). - // Note: Applies to Validate Method (GameSpy Source code inspection) - GWorld->CreateWarningMessage(errmsg); - RptF("GameSpy QR2 error: %d, %s", error, errmsg); - (void *)userdata; -} - -// NAT Negotiation callbacks -static void NNProgressCallback(NegotiateState state, void *userdata) -{ -} - -static void NNCompletedCallback(NegotiateResult result, SOCKET gamesocket, struct sockaddr_in *remoteaddr, void *userdata) -{ - switch (result) - { - case nr_success: - RptF("NAT Negotiation completed"); - break; - case nr_deadbeatpartner: - RptF("NAT Negotiation failed - partner not found"); - break; - case nr_inittimeout: - RptF("NAT Negotiation failed - unable to communicate with the server"); - break; - case nr_unknownerror: - RptF("NAT Negotiation failed - unknown error"); - break; - } -} - -void NNDetectionResultsCallback(gsi_bool success, NAT nat) -{ - QOStrStream natType; - if (success) - { - natType << "Begin (NAT type):\n"; - static bool doIt = false; - if (doIt) - { - if (*nat.brand) natType << " Brand: " << nat.brand << "\n"; - if (*nat.model) natType << " Model: " << nat.model << "\n"; - if (*nat.firmware) natType << " Firmware: " << nat.firmware << "\n"; - } - RString natTypeStr; - switch (nat.natType) - { - case no_nat: natTypeStr = "no nat"; break; - case firewall_only: natTypeStr = "firewall only"; break; - case full_cone: natTypeStr = "full cone"; break; - case restricted_cone: natTypeStr = "restricted cone"; break; - case port_restricted_cone: natTypeStr = "port restricted cone"; break; - case symmetric: natTypeStr = "symmetric"; break; - case unknown: - default: natTypeStr = "unknown"; - } - natType << " NAT type: " << cc_cast(natTypeStr) << "\n"; - RString natPromiscuity; - switch (nat.promiscuity) - { - case promiscuous: natPromiscuity = "promiscuous"; break; - case not_promiscuous: natPromiscuity = "not promiscuous"; break; - case port_promiscuous: natPromiscuity = "port promiscuous"; break; - case ip_promiscuous: natPromiscuity = "ip promiscuous"; break; - case promiscuity_not_applicable: - default: natPromiscuity = "promiscuity not applicable"; break; - } - natType << " NAT promiscuity: " << cc_cast(natPromiscuity) << "\n"; - RString natMappingScheme; - switch (nat.mappingScheme) - { - case private_as_public: natMappingScheme = "private as public"; break; - case consistent_port: natMappingScheme = "consistent port"; break; - case incremental: natMappingScheme = "incremental"; break; - case mixed: natMappingScheme = "mixed"; break; - case unrecognized: - default: natMappingScheme = "unrecognized"; break; - } - natType << " NAT mapping scheme: " << cc_cast(natMappingScheme) << "\n"; - if (nat.ipRestricted) natType << " NAT is IP restricted\n"; - if (nat.portRestricted) natType << " NAT is PORT restricted\n"; - if (nat.qr2Compatible) natType << " NAT is qr2 compatible\n"; - natType << "End (NAT type)"; - } - else natType << "NAT detection was not successful."; - RString detectedNatType(natType.str(), natType.pcount()); - GDebugVoNBank._natType = detectedNatType; -#if !_SUPER_RELEASE && ENABLE_REPORT - if (GInput.cheatVoNDetectNatType) - { - RptF(cc_cast(detectedNatType)); - } -#endif -} - -// Called when a client wants to connect using nat negotiation -// (Nat Negotiation must be enabled in qr2_init) -void nn_callback(int cookie, void *userdata) -{ - LogF("NAT Negotiation started for cookie : %d", cookie); - SOCKET GetServerSocket(); - enterNN(); - NegotiateError error = NNBeginNegotiationWithSocket(GetServerSocket(), cookie, 1, NNProgressCallback, NNCompletedCallback, NULL); -#if !_SUPER_RELEASE && _ENABLE_CHEATS - if (!GDebugVoNBank.NatTypeDetectionTriggered()) - { - GDebugVoNBank.TriggerNatTypeDetection(); - NegotiateError errorDet = NNStartNatDetection(NNDetectionResultsCallback); - (void) errorDet; - } -#endif - leaveNN(); - (void)error; - (void)userdata; -} - -void SetQRInitialized(bool set); - -/*! -\patch 5164 Date 10/3/2007 by Jirka -- Fixed: Handling of invalid CD keys on dedicated servers improved -*/ - -#if _ENABLE_GAMESPY && _VERIFY_CLIENT_KEY -void NetworkServer::OnCDKeyAuthorize(int player, int authenticated, const char *errmsg) -{ - if (!authenticated) - { - // wrong CD Key - kick off client, shut down server - if (player == BOT_CLIENT) - { - GChatList.Add(CCGlobal, NULL, errmsg, false, true); - WarningMessage(errmsg); -/* - WarningMessage(LocalizeString(keyInUse ? IDS_MP_CDKEY_IN_USE : IDS_MP_BAD_CDKEY)); -*/ - Done(); - } - else - { -/* - // using DisconnectMessage is not sufficient as we need the kick being immediate - // "Note that this is of course when the ArmA client does not disconnect itself, - // naturally the server itself has to do this to have control and not to allow - // the player to stay on the server with some exploit" - DisconnectMessage msg; - msg._message = errmsg; - SendMsg(player, &msg, NMFGuaranteed); -*/ - bool keyInUse = strcmp(errmsg, "CD Key in use") == 0; - KickOff(player, keyInUse ? KORCDKeyInUse : KORBadCDKey, errmsg); - } -/* - NetworkPlayerInfo *info = GetPlayerInfo(player); - LogF("%f: Player %s (%d) was not authenticated (%s)", 1e-3 * GlobalTickCount(), info ? cc_cast(info->name) : "", player, errmsg); -*/ - } - else - { -/* - NetworkPlayerInfo *info = GetPlayerInfo(player); - LogF("%f: Player %s (%d) was successfully authenticated (%s)", 1e-3 * GlobalTickCount(), info ? cc_cast(info->name) : "", player, errmsg); -*/ - } -} - -/// Callback function to indicate whether a client has been authorized or not. -static void OnAuthorize(int productid, int localid, int authenticated, char *errmsg, void *instance) -{ - NetworkServer *server = reinterpret_cast(instance); - if (server && server == GNetworkManager.GetServer()) server->OnCDKeyAuthorize(localid, authenticated, errmsg); -} - -/// Callback function to reauthorize players. -static void OnRefreshAuthorize(int gameid, int localid, int hint, char *challenge, void *instance) -{ - NetworkServer *server = reinterpret_cast(instance); - - if (server && server == GNetworkManager.GetServer()) - { - CDKeyRecheckAskMessage ask; - ask._hint = hint; - ask._challenge = challenge; - - server->SendMsg(localid, &ask, NMFGuaranteed); - } -} - -// Called when the local clients public address is received -void pa_callback(unsigned int ip, unsigned short port, void *userdata) -{ - NetworkServer *server = reinterpret_cast(userdata); - if (server && server == GNetworkManager.GetServer() /*&& server->IsDedicatedBotClient(BOT_CLIENT)*/) - { - NetworkPlayerInfo *player = server->GetPlayerInfo(BOT_CLIENT); - DoAssert(player); - if (player) - { - player->_publicAddr = ip; - player->_publicPort = port; - - // once we know a public address, we can start geolocating - server->OnPublicAddressKnown(ip); - } - } -} - -#endif - -void RegisterQR2Keys() -{ - qr2_register_key(PARAM1_KEY, "param1"); - qr2_register_key(PARAM2_KEY, "param2"); - qr2_register_key(VER_KEY, "ver"); - qr2_register_key(MOD_KEY, "mod"); - qr2_register_key(GAME_STATE_KEY, "gameState"); - qr2_register_key(PLATFORM_KEY, "platform"); - qr2_register_key(LANGUAGE_KEY, "language"); - qr2_register_key(MISSION_KEY, "mission"); - qr2_register_key(MOD_HASH_KEY, "modhash"); - qr2_register_key(HASH_KEY, "hash"); - qr2_register_key(REQ_BUILD_KEY, "reqBuild"); - qr2_register_key(REQ_SECURE_ID_KEY, "reqSecureId"); - qr2_register_key(LONGITUDE_KEY, "lng"); - qr2_register_key(LATITUDE_KEY, "lat"); - qr2_register_key(DS_KEY, "ds"); - qr2_register_key(EQ_MOD_KEY, "eqMod"); - qr2_register_key(REQ_VER_KEY, "reqVer"); - qr2_register_key(DIFF_KEY, "diff"); - qr2_register_key(BE_KEY, "be"); - qr2_register_key(SIG_KEY, "sig"); - qr2_register_key(VER_SIG_KEY, "verSig"); -} -/*! -\patch 1.34 Date 12/04/2001 by Jirka -- Changed: GameSpy base local port -*/ -void NetworkServer::InitQR(bool isPrivate) -{ - _qrInitDone = true; -#if _ENABLE_DEDICATED_SERVER - if (stricmp(_reportingIP, "noreport") == 0) isPrivate = true; -#endif - _doNotReport = isPrivate; - - RegisterQR2Keys(); - - -#if _ENABLE_DEDICATED_SERVER - if ( !_doNotReport && !_reportingIP.IsEmpty() ) - { - int len = sizeof(qr2_hostname) / sizeof(char); - strncpy(qr2_hostname, _reportingIP, len); - qr2_hostname[len - 1] = 0; - } -#endif - - static bool useNatNegotiation = true; - - SOCKET GetServerSocket(); - if (qr2_init_socket(NULL, GetServerSocket(), GetSessionPort(), - GetGameName(), GetSecretKey(), _doNotReport ? 0 : 1, useNatNegotiation, - serverkey_callback, playerkey_callback, teamkey_callback, - keylist_callback, count_callback, adderror_callback, this) == e_qrnoerror) - { - SetQRInitialized(true); - - // Set a function to be called when we receive a nat negotiation request - qr2_register_natneg_callback(NULL, nn_callback); -#if _VERIFY_CLIENT_KEY - //set host name DNS - gsiSafeStrcpyA(gcd_hostname, GetGcdHostname(), sizeof(gcd_hostname)); - if (gcd_init(GetGameID()) == 0) - _validateCDKey = true; //this enable validation on GameSpy - qr2_register_publicaddress_callback(NULL, pa_callback); -#endif - } - -#if REPORT_ASE - ASEMaster_init(1); -#endif -} - -void NetworkServer::DoneQR() -{ -#if _VERIFY_CLIENT_KEY - if (_validateCDKey) - { - gcd_disconnect_all(GetGameID()); - gcd_shutdown(); - _validateCDKey = false; - } -#endif - - //let game master know we are shutting down (removes dead server entry from the list) - SetQRInitialized(false); - qr2_shutdown(NULL); - -#ifdef GSI_UNICODE - // In Unicode mode we must perform additional cleanup - qr2_internal_key_list_free(); -#endif -} - -void NetworkServer::SimulateQR() -{ - if (!_qrInitDone) - return; //InitQR was not called (possibly playing LAN game) - //check for / process incoming queries - qr2_think(NULL); -#if _VERIFY_CLIENT_KEY - if (_validateCDKey) gcd_think(); -#endif - -#if REPORT_ASE - ASEMaster_heartbeat(0, ::GetServerPort() + 1, GetGameName()); -#endif -} - -void NetworkServer::ChangeStateQR() -{ - qr2_send_statechanged(NULL); -} - -const int MaxGSMaxSize = 1300; - -//max 200B for signatures list GS key -const int MaxGSKey = 200; - -static int GetMaxKeySize(qr2_buffer_t outbuf) -{ - struct qr2_buffer_header - { - char buffer[32]; // in fact much longer, but 32 is something we can be sure of - } * header = reinterpret_cast(outbuf); - // packet type 0 (PACKET_QUERY), followed by some 4 bytes, followed with "splitnum" - if (header->buffer[0]==0 && !strncmp(header->buffer+5,"splitnum",sizeof("splitnum"))) - { - return MaxGSMaxSize; // max. packet size is 1400, but something is needed for splitNum header, keyname ... - } - else - { - return MaxGSKey; - } -} -/// overload to handle cutting very long values transparently -void qr2_buffer_add(qr2_buffer_t outbuf, RString longString) -{ - int len = longString.GetLength(); - int maxSize = GetMaxKeySize(outbuf); - if (len>=maxSize) - { - BString shortString; - shortString = longString; - Assert(maxSize>4); - STATIC_ASSERT(MaxGSMaxSize>4 && MaxGSKey>4); - strcpy(shortString+(maxSize-4),"..."); - qr2_buffer_add(outbuf,cc_cast(shortString)); - } - else - { - qr2_buffer_add(outbuf,cc_cast(longString)); - } -} - -void NetworkServer::CloseGeoJob() const -{ - if (_geoJob) - { - // make sure the thread has done its work and will no longer access any variables - _geoJob->_longitude.GetResult(); - _geoJob->_latitude.GetResult(); - _geoJob->_thread.Wait(); - //RptF("Closing geoJob"); - _geoJob->_thread.Done(); - //RptF("GeoJob closed!"); //NOTE: there was "Critical: Destroying running thread" between these two RptF! - _geoJob.Free(); - } -} - -void NetworkServer::ProcessGeoJob() const -{ - if (_geoJob && _geoJob->_longitude.IsReady()) - { - int longitude = _geoJob->_longitude.GetResult(); - int latitude = _geoJob->_latitude.GetResult(); - CloseGeoJob(); - // save the values so that we can find them next time - ParamFile fCfg; - ParseFlashpointCfg(fCfg); - if (_longLatAuto) - { - _longitude = longitude; - _latitude = latitude; - fCfg.Add("serverLongitude",_longitude); - fCfg.Add("serverLatitude",_latitude); - } - fCfg.Add("serverLongitudeAuto",longitude); - fCfg.Add("serverLatitudeAuto",latitude); - SaveFlashpointCfg(fCfg); - - } -} - -static int IntParam(float param) -{ - if (param>INT_MAX) return INT_MAX; - return toLargeInt(param); -} - -void NetworkServer::OnQueryServer(int keyid, qr2_buffer_t outbuf) -{ - switch (keyid) - { - case GAMEVER_KEY: - qr2_buffer_add(outbuf, Format("%s.%d", APP_VERSION_TEXT, BUILD_NO)); - break; - case HOSTNAME_KEY: - qr2_buffer_add(outbuf, _server->GetSessionName()); - break; - case GAMENAME_KEY: - qr2_buffer_add(outbuf, GetGameName()); - break; -/* - case HOSTPORT_KEY: - qr2_buffer_add_int(outbuf, _server->GetSessionPort()); - break; -*/ - case MAPNAME_KEY: - { - RString island; - if (_serverState >= NSSAssigningPlayers) island = _missionHeader._island; - qr2_buffer_add(outbuf, island); - } - break; - case GAMETYPE_KEY: - { - if (Glob.isDayZ==Globals::IsDayZ) - { - qr2_buffer_add(outbuf, "DAYZ"); - break; - } - else if (Glob.isDayZ==Globals::IsDayZOther) - { - qr2_buffer_add(outbuf, "DAYZ_M"); - break; - } - - RString gameType; - if (_serverState >= NSSAssigningPlayers) gameType = _missionHeader._gameType; - qr2_buffer_add(outbuf, gameType); - } - break; - case MISSION_KEY: - { - RString mission; - if (_serverState >= NSSAssigningPlayers) mission = _missionHeader.GetLocalizedMissionName(); - qr2_buffer_add(outbuf, mission); - } - break; - case NUMPLAYERS_KEY: - qr2_buffer_add_int(outbuf, _identities.Size()); - break; - case NUMTEAMS_KEY: - qr2_buffer_add_int(outbuf, 0); - break; - case MAXPLAYERS_KEY: - qr2_buffer_add_int(outbuf, GetMaxPlayers()); - break; - case GAMEMODE_KEY: - { - const char *mode = ""; - switch (_serverState) - { - case NSSNone: - mode = "exiting"; - break; - case NSSSelectingMission: - case NSSEditingMission: - case NSSAssigningPlayers: - mode = "openwaiting"; - break; - case NSSSendingMission: - case NSSLoadingGame: - case NSSPlaying: - mode = "openplaying"; - break; - case NSSMissionAborted: - mode = "openwaiting"; - break; - default: - Fail("Game state"); - break; - } - qr2_buffer_add(outbuf, mode); - } - break; - case TIMELIMIT_KEY: - { - int timeleft; - if (_serverState == NSSPlaying) - { - timeleft = 15; - - float et = _missionHeader._estimatedEndTime.toFloat(); - if (et > 0) - { - et -= Glob.time.toFloat(); - timeleft = toInt(et / 60.0); - saturateMax(timeleft, 1); - } - } - else timeleft = 0; - qr2_buffer_add_int(outbuf, timeleft); - } - break; - case PASSWORD_KEY: - qr2_buffer_add_int(outbuf, (_password ? 2 : 0) + (_sessionLocked ? 1 : 0)); - break; - case PARAM1_KEY: - qr2_buffer_add_int(outbuf, IntParam(_param1)); - break; - case PARAM2_KEY: - qr2_buffer_add_int(outbuf, IntParam(_param2)); - break; - case CURRENT_VERSION_KEY: - case VER_KEY: - qr2_buffer_add_int(outbuf, MP_VERSION_ACTUAL); - break; - case REQ_VER_KEY: - case REQUIRED_VERSION_KEY: - qr2_buffer_add_int(outbuf, MP_VERSION_REQUIRED); - break; - case MOD_KEY: - { - RString GetModListNames(); - qr2_buffer_add(outbuf, GetModListNames()); - } - break; - case MOD_HASH_KEY: - { - RString hashes; - for (int i=0; i maxLen ) - { // truncate and finish signatures list collecting - list = list + "..."; // mark signatures list as truncated - break; - } - len += sigLen; - list = list + _acceptedKeys[i]._name; - } - return list; -} - -void NetworkServer::OnQueryPlayer(int keyid, int index, qr2_buffer_t outbuf) -{ - //check for valid index - if (index >= _identities.Size()) - { - qr2_buffer_add(outbuf, _T("")); - return; - } - - const PlayerIdentity &identity = _identities[index]; - switch (keyid) - { - case PLAYER__KEY: - qr2_buffer_add(outbuf, identity.name); - break; - case TEAM__KEY: - { - RString squad; - if (identity.squad) squad = identity.squad->_nick; - qr2_buffer_add(outbuf, squad); - } - break; - case SCORE__KEY: - { - //qr2_buffer_add_int(outbuf, score); - } - break; - case DEATHS__KEY: - { - //qr2_buffer_add_int(outbuf, deaths); - } - break; - default: - qr2_buffer_add(outbuf, _T("")); - break; - } -} - -void NetworkServer::OnQueryTeam(int keyid, int index, qr2_buffer_t outbuf) -{ - qr2_buffer_add(outbuf, _T("")); -} - -void NetworkServer::OnQueryKeys(int keytype, qr2_keybuffer_t keybuffer) -{ - //need to add all the keys we support - switch (keytype) - { - case key_server: - qr2_keybuffer_add(keybuffer, GAMEVER_KEY); - qr2_keybuffer_add(keybuffer, HOSTNAME_KEY); -// qr2_keybuffer_add(keybuffer, HOSTPORT_KEY); - qr2_keybuffer_add(keybuffer, MAPNAME_KEY); - qr2_keybuffer_add(keybuffer, GAMETYPE_KEY); - qr2_keybuffer_add(keybuffer, NUMPLAYERS_KEY); - qr2_keybuffer_add(keybuffer, NUMTEAMS_KEY); - qr2_keybuffer_add(keybuffer, MAXPLAYERS_KEY); - qr2_keybuffer_add(keybuffer, GAMEMODE_KEY); - qr2_keybuffer_add(keybuffer, TIMELIMIT_KEY); - qr2_keybuffer_add(keybuffer, PASSWORD_KEY); - qr2_keybuffer_add(keybuffer, PARAM1_KEY); - qr2_keybuffer_add(keybuffer, PARAM2_KEY); - qr2_keybuffer_add(keybuffer, CURRENT_VERSION_KEY); - qr2_keybuffer_add(keybuffer, REQUIRED_VERSION_KEY); - qr2_keybuffer_add(keybuffer, MOD_KEY); - qr2_keybuffer_add(keybuffer, EQUAL_MOD_REQUIRED_KEY); - qr2_keybuffer_add(keybuffer, GAME_STATE_KEY); - qr2_keybuffer_add(keybuffer, DEDICATED_KEY); - qr2_keybuffer_add(keybuffer, PLATFORM_KEY); - qr2_keybuffer_add(keybuffer, LANGUAGE_KEY); - qr2_keybuffer_add(keybuffer, DIFFICULTY_KEY); - qr2_keybuffer_add(keybuffer, MISSION_KEY); - qr2_keybuffer_add(keybuffer, GAMENAME_KEY); - qr2_keybuffer_add(keybuffer, BATTLEYE_KEY); - qr2_keybuffer_add(keybuffer, VERIFY_SIGNATURES_KEY); - qr2_keybuffer_add(keybuffer, SIGNATURES_KEY); - qr2_keybuffer_add(keybuffer, MOD_HASH_KEY); - qr2_keybuffer_add(keybuffer, HASH_KEY); - qr2_keybuffer_add(keybuffer, REQ_BUILD_KEY); - qr2_keybuffer_add(keybuffer, REQ_SECURE_ID_KEY); - qr2_keybuffer_add(keybuffer, LATITUDE_KEY); - qr2_keybuffer_add(keybuffer, LONGITUDE_KEY); - break; - case key_player: - qr2_keybuffer_add(keybuffer, PLAYER__KEY); - qr2_keybuffer_add(keybuffer, TEAM__KEY); - qr2_keybuffer_add(keybuffer, SCORE__KEY); - qr2_keybuffer_add(keybuffer, DEATHS__KEY); - break; - case key_team: - break; - default: - break; - } -} - -int NetworkServer::OnQueryCount(int keytype) -{ - switch (keytype) - { - case key_player: - return _identities.Size(); - case key_team: - return 0; - default: - return 0; - } -} - -/* -void NetworkServer::OnQueryRules(char *outbuf, int maxlen) -{ - if (!SafePrint(ptr, maxlen, "\\mod\\%s", (const char *)GetModListShort())) return; - if (!SafePrint(ptr, maxlen, "\\equalModRequired\\%d", _equalModRequired)) return; - if (!SafePrint(ptr, maxlen, "\\gstate\\%d", _serverState)) return; - + dedicated - - } -*/ - -#endif -//} - -//{ STEAMWORKS SDK -#if _ENABLE_STEAM_MATCHMAKING - -void NetworkServer::InitSteam() -{ - uint32 ip = bindIPAddress; - uint16 masterServerUpdaterPort = _steamQueryPort; - uint16 authenticationPort = _steamPort; - EServerMode mode = eServerModeAuthenticationAndSecure; - RString steamVersion = Format("%s.%d", APP_VERSION_TEXT, BUILD_NO); //such as 0.28.113666 - -#if USER_BebulXX - _putenv("SteamAppId=223350"); -#else - _putenv("SteamAppId=480"); -#endif - - // Initialize the SteamGameServer interface, we tell it some info about us, and we request support - // for both Authentication (making sure users own games) and secure mode, VAC running in our game - // and kicking users who are VAC banned - bool initOK = false; - for (int i=0; i<15; i++, authenticationPort+=13, masterServerUpdaterPort++) //try 15 local ports - { - if (SteamGameServer_Init(ip, authenticationPort, GetSessionPort(), masterServerUpdaterPort, mode, steamVersion)) - { - initOK = true; - break; - } - } - - // Connect to steam servers - if (initOK && SteamGameServer()) - { - ConsoleF("SUCCESS: SteamGameServer_Init(%x,%d,%d,%d,%d,%s)", ip, authenticationPort, GetSessionPort(), masterServerUpdaterPort, mode, steamVersion); - RptF("SUCCESS: SteamGameServer_Init(%x,%d,%d,%d,%d,%s)", ip, authenticationPort, GetSessionPort(), masterServerUpdaterPort, mode, steamVersion); - SteamGameServer()->SetDedicatedServer(_dedicated); - // Set the "game dir". - // This is currently required for all games. However, soon we will be - // using the AppID for most purposes, and this string will only be needed - // for mods. it may not be changed after the server has logged on - SteamGameServer()->SetModDir("dayz"); - - // Tell the Steam Master Server about our game - SteamGameServer()->SetProduct("dayz"); //was APP_NAME - SteamGameServer()->SetGameDescription(APP_NAME); - - //SteamGameServer()->SetGameData("Bebul,Game"); - if (_beIntegration.IsEnabled()) - SteamGameServer()->SetGameTags("battleye"); - - SteamGameServer()->LogOnAnonymous(); - SteamGameServer()->EnableHeartbeats(true); - } - else - { - ConsoleF("FAILED: SteamGameServer_Init(%x,%d,%d,%d,%d,%s)", ip, authenticationPort, GetSessionPort(), masterServerUpdaterPort, mode, steamVersion); - RptF("FAILED: SteamGameServer_Init(%x,%d,%d,%d,%d,%s)", ip, authenticationPort, GetSessionPort(), masterServerUpdaterPort, mode, steamVersion); - } -} - -void NetworkServer::DoneSteam() -{ - // Disconnect from the steam servers - if (SteamGameServer()) SteamGameServer()->LogOff(); - - // Release our reference to the steam client library - SteamGameServer_Shutdown(); -} - -void NetworkServer::SimulateSteam() -{ - // Run any Steam Game Server API callbacks - SteamGameServer_RunCallbacks(); - - // Update our server details - ChangeStateSteam(); -} - -void NetworkServer::ChangeStateSteam() -{ - if (SteamGameServer()) - { - // Tell the Steam Master Server about our game - SteamGameServer()->SetMaxPlayerCount(GetMaxPlayers()); - SteamGameServer()->SetPasswordProtected(_password || _sessionLocked); - SteamGameServer()->SetServerName(_server->GetSessionName()); - SteamGameServer()->SetMapName(_missionHeader.GetLocalizedMissionName()); - - // update any rule values we publish - SteamGameServer()->SetKeyValue("requiredVersion", Format("%d", MP_VERSION_REQUIRED)); -// SteamGameServer()->SetKeyValue("gameType", _missionHeader._gameType); - SteamGameServer()->SetKeyValue("island", _missionHeader._island); -// SteamGameServer()->SetKeyValue("serverState", Format("%d", _serverState)); -#if USE_MOD_LIST - SteamGameServer()->SetKeyValue("mod", GetModListNames()); -#endif -// SteamGameServer()->SetKeyValue("equalModRequired", _equalModRequired ? "1" : "0"); - SteamGameServer()->SetKeyValue("dedicated", _dedicated ? "1" : "0"); - SteamGameServer()->SetKeyValue("language", Format("%d", GetGameLanguage())); -// SteamGameServer()->SetKeyValue("difficulty", Format("%d", Glob.config.difficulty)); - SteamGameServer()->SetKeyValue("requiredBuild", Format("%d", _buildNoRequired)); - - RString gameTags; - if (_beIntegration.IsEnabled()) - gameTags = "battleye,"; - if (_disable3rdPerson) - gameTags = gameTags + "no3rd,"; - - extern const char* GetInstanceId( void ); - if ( GetInstanceId() && stricmp(GetInstanceId(),"000000")!=0 && stricmp(GetInstanceId(),"000001")!=0 ) - { // it is private "hive" server - gameTags = gameTags + "privHive,"; - } - - if (_environmentTimeMul > 0.0f) - { - RString tm = Format("etm%f,", _environmentTimeMul); - gameTags = gameTags + tm; - } - - float dayT = Glob.clockWeather.GetTimeOfDay()*24.0f; - RString dayTm = Format("%02d:%02d", toIntFloor(dayT), toIntFloor(60*(dayT-toIntFloor(dayT)))); - gameTags = gameTags + dayTm; - SteamGameServer()->SetGameTags(gameTags); - -#if defined(_WIN32) - SteamGameServer()->SetKeyValue("platform", "win"); -#elif defined(_LINUX) - SteamGameServer()->SetKeyValue("platform", "linux"); -#else - SteamGameServer()->SetKeyValue("platform", "?"); -#endif - - int timeleft; - if (_serverState == NSSPlaying) - { - timeleft = 15; - - float et = _missionHeader._estimatedEndTime.toFloat(); - if (et > 0) - { - et -= Glob.time.toFloat(); - timeleft = toInt(et / 60.0); - saturateMax(timeleft, 1); - } - } - else timeleft = 0; - SteamGameServer()->SetKeyValue("timeLeft", Format("%d", timeleft)); - if (SteamUtils()) SteamGameServer()->SetKeyValue("country", SteamUtils()->GetIPCountry()); - - // Update all the players names/scores - for (int i=0; i<_identities.Size(); i++) - { - const PlayerIdentity &identity = _identities[i]; - - // TODO: find the score - int score = 0; - SteamGameServer()->BUpdateUserData(CSteamID((uint64)identity._steamID), identity.GetName(), score); - } - } -} - -void NetworkServer::OnSteamServersConnected(SteamServersConnected_t *logonSuccess) -{ - ConsoleF("Connected to Steam"); - - // Steam servers are ready to accept our session info now - ChangeStateSteam(); -} - -void NetworkServer::OnSteamServersConnectFailure( SteamServerConnectFailure_t *connectFailure) -{ - // Even if master server connection fails, publish state for LAN / local players - ChangeStateSteam(); -} - -void NetworkServer::OnSteamServersDisconnected(SteamServersDisconnected_t *loggedOff) -{ - ConsoleF("Disconnected from Steam"); -} - -void NetworkServer::OnPolicyResponse(GSPolicyResponse_t *policyResponse) -{ - ConsoleF("Steam policy response"); -} - -#if _ENABLE_DEDICATED_SERVER -void NetworkServer::ResetCharacterTimeAlive(AIBrain *unit) -{ - Person *person = unit->GetPerson(); - if (person) - { - int dpnid = person->GetRemotePlayer(); - PlayerIdentity *identity = FindIdentity(dpnid); - if (identity && identity->_statistics) - { - identity->_statistics->Reset(EStat_characterTimeAlive); - } - } -} -#endif - -#endif -//} - -bool NetworkServer::DBSave(RString baseURL, int dpnid, RString request) -{ - NetworkPlayerInfo *info = GetPlayerInfo(dpnid); - if (!info) - return false; - PlayerIdentity *identity = FindIdentity(dpnid); - if (!identity) - return false; - - return info->DBSave(baseURL, identity->id, request); -} - -void NetworkServer::DBLoad(RString baseURL, int playerId, GameDataCode *code) -{ - const PlayerIdentity *identity = FindIdentityByPlayerId(playerId); - if (!identity) - return; - NetworkPlayerInfo *info = GetPlayerInfo(identity->dpnid); - if (!info) - return; - if (info) - info->DBLoad(baseURL, playerId, identity->id, info->name, code); -} - -void NetworkServer::DBLoad(RString baseURL, int playerId, RString playerUID, GameDataCode *code) -{ - const PlayerIdentity *identity = FindIdentityByPlayerId(playerId); - if (!identity) - return; - NetworkPlayerInfo *info = GetPlayerInfo(identity->dpnid); - if (!info) - return; - info->DBLoad(baseURL, playerId, playerUID, info->name, code); -} - -void LoadMissions(bool userMissions, AutoArray &missionList, bool campaignCheat=false); -static void AddMissionList(NetworkCommandMessage &answer, NetworkCommandMessage &answer2) -{ - PROFILE_SCOPE_EX(addML, network) - AutoArray missionList; - LoadMissions(false, missionList); - for (int i=0; idpid == player) - { - name = _players[i]->name; - break; - } - } - ConsoleF(LocalizeString(IDS_DS_ADMIN_LOGGED_IN), (const char *)name); - - _votings.Clear(); - - NetworkCommandMessage answer; - answer._type = NCMTLogged; - answer._content.Write(&_admin, sizeof(_admin)); - // AddMissionList(answer); - SendMsg(player, &answer, NMFGuaranteed); - - if (_mission[0] == '?' && _mission[1] == 0) - { - NetworkCommandMessage answer; - answer._type = NCMTVoteMission; - NetworkCommandMessage answer2; - answer2._type = NCMTVoteMissionExt; - AddMissionList(answer, answer2); - SendMsg(player, &answer, NMFGuaranteed); - SendMsg(player, &answer2, NMFGuaranteed); - } - - UpdateAdminState(); -} -#endif - -void NetworkServer::ApplyVoting(const AutoArray &id, const AutoArray *value) -{ -#if _ENABLE_DEDICATED_SERVER - int *ptr = (int *)id.Data(); - int type = *(ptr++); - switch (type) - { - case NCMTMission: - if (value) - { - // difficulty voting is separate - ask it for a result - // the voting is performed at the same time, therefore the result should be ready - _difficulty = Glob.config.diffDefault; - const Voting *diff = _votings.Find(NCMTDifficulty); - if (diff) - { - const AutoArray *diffValue = diff->GetValue(); - if (diffValue) - { - RString diffName(diffValue->Data(),diffValue->Size()); - int difficulty = Glob.config.diffNames.GetValue(diffName); - if (difficulty >= 0) _difficulty = difficulty; - } - _votings.DeleteVoting(NCMTDifficulty); - } - // check mission voting result - _mission = RString(value->Data(),value->Size()); - if (_mission.GetLength() > 0) _restart = true; - if (_serverState != NSSSelectingMission && _serverState != NSSPlaying) - { - GNetworkManager.DestroyAllObjects(); - SetServerState(NSSSelectingMission); - } - } - break; - case NCMTMissions: - DoMissions(false); - break; - case NCMTRestart: - if (_serverState == NSSPlaying) - { - _restart = true; - _reassign = false; - } - break; - case NCMTReassign: - DoReassign(); - break; - case NCMTKick: - { - int player = *(ptr++); - if (player != BOT_CLIENT) KickOff(player,KORKick); - } - break; - case NCMTAdmin: - if (value) - { - const char *p = value->Data(); - int player = *((int *)p); - if (player != AI_PLAYER && _dedicated && _gameMaster == AI_PLAYER) - SetGameMaster(player, true); - } - break; - } -#endif -} - -void OnServerUserMessage(int from, char *buffer, int bufferSize, void *context) -{ - NetworkServer *server = (NetworkServer *)context; - NetworkMessageRaw rawMsg(buffer, bufferSize); - server->DecodeMessage(from, rawMsg); -} - -void OnServerSendComplete(DWORD msgID, bool ok, void *context) -{ -} - -void OnServerPlayerCreate(int player, bool botClient, bool privateSlot, const char *name, const char *mod, unsigned long inaddr, void *context) -{ - if (!botClient && stricmp(mod, GLoadedContentHash) != 0) - { - RString format = LocalizeString(IDS_MP_VALIDERROR_2); - RString message = Format(format, cc_cast(name)); - -#if ENABLE_CLIENT_USE_MODIFIED_DATA_CHAT - if (!ChannelDisabled(CCSystem)) - { - RefArray dummy; - GNetworkManager.Chat(CCSystem, "", dummy, message); - } - GChatList.Add(CCSystem, NULL, message, false, true); -#endif -#if _ENABLE_DEDICATED_SERVER - ConsoleF("%s", cc_cast(message)); -#endif - } - - NetworkServer *server = (NetworkServer *)context; - server->OnCreatePlayer(player, privateSlot, name, inaddr); -} - -void OnServerPlayerDelete(int player, void *context) -{ - NetworkServer *server = (NetworkServer *)context; - server->OnPlayerDestroy(player); -} - -bool OnServerVoicePlayerCreate(int player, void *context) -{ - NetworkServer *server = (NetworkServer *)context; - return server->OnCreateVoicePlayer(player); -} - -unsigned NetworkServer::CleanUpMemory() -{ - if (_server) return _server->FreeMemory(); - return 0; -} - -void NetworkServer::OnClose() -{ -#if _USE_BATTL_EYE_SERVER - _beIntegration.Done(); -#endif -} -void NetworkServer::ReceiveSystemMessages() -{ - if (_server) - { - _server->ProcessSendComplete(OnServerSendComplete, this); - _server->ProcessPlayers(OnServerPlayerCreate, OnServerPlayerDelete, this); - _server->ProcessVoicePlayers(OnServerVoicePlayerCreate, this); - } -} - -void NetworkServer::ReceiveUserMessages() -{ - if (_server) _server->ProcessUserMessages(OnServerUserMessage, this); -} - -void NetworkServer::RemoveSystemMessages() -{ - if (_server) - { - _server->RemoveSendComplete(); - _server->RemovePlayers(); - _server->RemoveVoicePlayers(); - } -} - -void NetworkServer::RemoveUserMessages() -{ - if (_server) _server->RemoveUserMessages(); -} - -void CalculateMinMaxAvg::Sample(float value, float weight) -{ - saturateMin(_min,value); - saturateMax(_max,value); - _sum += value*weight; - _lastValue = value; - _weight += weight; -} - -void CalculateMinMaxAvg::Reset() -{ - _min = FLT_MAX; - _max = FLT_MIN; - _sum = 0; - _weight = 0; - _lastValue = 0; -} - -CalculateMinMaxAvg::CalculateMinMaxAvg() -{ - Reset(); -} - - -inline int toLargeIntSat(float x) -{ - if (x>=INT_MAX) return INT_MAX; - if (x dummy; - GNetworkManager.Chat(CCSystem, "", dummy, text); -} - -void NetworkServer::ServerMessage(const LocalizedFormatedString &text) -{ - RString localized = text.GetLocalizedValue(); -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - ConsoleF("%s", cc_cast(localized)); -#endif -//} - GChatList.Add(CCSystem, NULL, localized, false, true); - RefArray dummy; - GNetworkManager.LocalizedChat(CCSystem, "", dummy, text); -} - - -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - -#define DEBUG_TYPE_ENUM(type,prefix,XX) \ - XX(type, prefix, TotalSent) \ - XX(type, prefix, UserSent) \ - XX(type, prefix, Console) \ - XX(type, prefix, UserInfo) \ - XX(type, prefix, UserQueue) \ - XX(type, prefix, JIPQueue) - -#ifndef DECL_ENUM_DEBUG_TYPE -#define DECL_ENUM_DEBUG_TYPE -DECL_ENUM(DebugType) -#endif -DECLARE_DEFINE_ENUM(DebugType,DT,DEBUG_TYPE_ENUM) - -/*! -\patch 1.88 Date 10/21/2002 by Ondra -- Added: Dedicated server command #debug (userInfo) -(Requires 1.87 client) -\patch 1.90 Date 10/31/2002 by Ondra -- New: MP: Added #debug checkfile command. -Server admins can use this command to check if any file used by clients matches server version. -\patch 1.90 Date 10/31/2002 by Ondra -- New: MP: Added server.cfg array checkfiles[] - -list of files that should be checked for each player connecting. -Example: checkfiles[]={"HWTL\dta\data3d.pbo","dta\data3d.pbo"} -\patch 1.90 Date 10/31/2002 by Ondra -- New: Servers checks if world file (.wrp) used by client matches server version. -*/ - -static RString ExtractWord(RString &line) -{ - const char *endWord = strchr(line,' '); - if (!endWord) - { - RString word = line; - line = RString(); - return word; - } - RString word = line.Substring(0,endWord-line.Data()); - line = endWord+1; - return word; -} - -void NetworkServer::DebugAsk(RString str) -{ - // check for some special debug commands - RString line = str; - RString word = ExtractWord(line); - if (!strcmpi(word,"limitOut")) - { - RString limit = ExtractWord(line); - int limitBW = atoi(limit); - if (limit>0 && _server) - { - int limitBWB = (limitBW+7)/8; - _server->SetConnectionLimits(limitBWB); - RString message = Format("Outgoing bandwidth limited to %d B/s (%d bps) per client",limitBWB,limitBWB*8); - DebugAnswer(message); - } - return; - } - if (!strcmpi(word,"von")) - { - // check whether #debug von is not currently running - if (_server && !GDebugVoNBank.IsRunning()) - { - //P2P Topology - QOStrStream diag; - AutoArray > convTable; - convTable.Realloc(_identities.Size()); - convTable.Resize(_identities.Size()); - for (int i=0; i<_identities.Size(); i++) - { - convTable[i]._dpnid = _identities[i].dpnid; - convTable[i]._id = _identities[i].GetDebugId(); - convTable[i]._name = _identities[i].name; - } - _server->GetVoNTopologyDiag(diag, convTable); - GDebugVoNBank.SetFeature(DebugVoNBank::VoNFeature_NetTopology, RString(diag.str(), diag.pcount()) ); - // Ask each player for her collected VoNFeatures - for (int i=0; i<_players.Size(); i++) - { - const NetworkPlayerInfo &player = *_players[i]; - NetworkCommandMessage ask; - ask._type = NCMTAskVoNDiagnostics; - SendMsg(player.dpid, &ask, NMFGuaranteed); - } - // Set VoNDiagnozer to wait on clients answers and report it after while - GDebugVoNBank.StartCollecting(GlobalTickCount(), _players.Size()); - } - return; - } - if (!strcmpi(word,"jipPerf")) - { - if (_server) - { - //P2PManager diagnostics first - RString initDiag = GetAddInitAndRemoveOverriddenStat(); - DebugAnswer(initDiag); - } - return; - } - #if _ENABLE_CHEATS - if (!strcmpi(word,"exec")) - { - if (_server) - { - GameVarSpace vars(false); - int gshandle = GGameState.BeginContext(&vars); - GGameState.Execute(line, GameState::EvalContext::_default, GWorld->GetMissionNamespace()); // mission namespace - GGameState.EndContext(gshandle); - } - } - #endif - // check if string is only numbers - char *endNum; - float interval = strtod(str,&endNum); - if (*endNum==0) - { - _debugInterval = interval; - saturate(_debugInterval,0.1f,3600); - BString<256> msg; - sprintf(msg,"Debug: Interval %g",_debugInterval); - DebugAnswer(RString(msg)); - return; - } - if (!stricmp(str,"off")) - { - // clear all debug info - _debugOn.Clear(); - DebugAnswer(RString("Debug: All off")); - //_debugInterval = 0; - _debugNext = INT_MAX; - return; - } - - const char *beg = str; - const char *end = strchr(beg, ' '); - int len = end ? end - beg : strlen(beg); - - RString strCommand(beg, len); - DebugType command = GetEnumValue((const char *)strCommand); - if (command < 0) return; - - beg += len; - while (*beg == ' ') beg++; - - if (stricmp(beg, "off") == 0) - { - _debugOn.DeleteKey(command); - DebugAnswer(RString("Debug: ") + strCommand + RString(" off")); - } - else - { - _debugOn.AddUnique(command); - DebugAnswer(RString("Debug: ") + strCommand); - - if (_debugInterval<=0) - { - _debugInterval = 10; - _debugNext = _debugNext + toInt(_debugInterval*1000); - } - DWORD next = GlobalTickCount()+toInt(_debugInterval*1000); - if (_debugNext>next) _debugNext = next; - } -} - -void NetworkServer::DebugAnswer(RString str) -{ - if (_gameMaster != AI_PLAYER || !_dedicated) - { - if (_dedicated) - { - NetworkCommandMessage msg; - msg._type = NCMTDebugAnswer; - msg._content.WriteString(str); - SendMsg(_gameMaster, &msg, NMFGuaranteed); - } - LogDebugger("%s",cc_cast(str)); - } -} - -/*! -\patch 5126 Date 1/31/2007 by Jirka -- Fixed: DS crash occurred when mission with some special name (containing '%') was selected -*/ - -int NetworkServer::ConsoleF(const char *format, ...) -{ - va_list arglist; - va_start(arglist, format); - - if (_debugOn.FindKey(DTConsole) >= 0) - { - BString<512> buf; - vsprintf(buf, format, arglist); - DebugAnswer((const char *)buf); - } - int result = ::VConsoleF(format, arglist); - - va_end( arglist ); - return result; -} - -#endif -//} - -/* -const DWORD VotingTimeOutReady = 30000; // timeout in ms when all players are ready -const DWORD VotingTimeOutNotReady = 120000; // timeout in ms when no players are ready - -const DWORD BriefingTimeOutReady = 15000; // timeout in ms when all players are ready -const DWORD BriefingTimeOutNotReady = 60000; // timeout in ms when no players are ready - -const DWORD DebriefingTimeOutReady = 30000; // timeout in ms when all players are ready -const DWORD DebriefingTimeOutNotReady = 60000; // timeout in ms when no players are ready -*/ - -#include "Es/Common/langExt.hpp" -#define ENABLED_SHORTTIMEOUT_Bebul 1 -#define ENABLED_SHORTTIMEOUT_Jirka 1 -#if ENABLED_FEATURE(SHORTTIMEOUT) - -const DWORD VotingTimeOutReady = 5000; // timeout in ms when all players are ready -const DWORD VotingTimeOutNotReady = 5000; // timeout in ms when no players are ready - -#else - -const DWORD VotingTimeOutReady = 60000; // timeout in ms when all players are ready -const DWORD VotingTimeOutNotReady = 60000; // timeout in ms when no players are ready - -#endif - -const DWORD BriefingTimeOutReady = 60000; // timeout in ms when all players are ready -const DWORD BriefingTimeOutNotReady = 60000; // timeout in ms when no players are ready - -const DWORD DebriefingTimeOutReady = 45000; // timeout in ms when all players are ready -const DWORD DebriefingTimeOutNotReady = 45000; // timeout in ms when no players are ready - -bool NetworkServer::CheckTimeOut(int readyCount, int totalCount, DWORD ready, DWORD notReady) -{ - // with low numbers assume there still will be more players connecting - int minPlayersToVote = 8; - float readyRatio; - if (totalCount=timeToEnd) return true; - DWORD timeLeft = timeToEnd-GlobalTickCount(); - int secondsLeft = timeLeft/1000+1; - - if (_serverTimeOutSent!=secondsLeft) - { - // send to all players - ServerTimeoutMessage msg; - msg._timeout = secondsLeft; - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.clientState < NCSConnected) continue; - SendMsg(info.dpid, &msg, NMFGuaranteed); - } - _serverTimeOutSent = secondsLeft; - } - - #if _ENABLE_REPORT - GlobalShowMessage(1000,"Time left: %d",secondsLeft); - #endif - return false; -} - -RString NetworkServer::GetDiagText(const NetworkId &id) const -{ - NetworkObjectInfo *oInfo = GetObjectInfo(id); - if (!oInfo) return RString(); - - RString ret = Format(" Pos from %d",oInfo->currentUpdate[NMCUpdatePosition].from); - if (oInfo->currentRejected[NMCUpdatePosition].message) ret = ret + Format(" Pos rejected from %d",oInfo->currentRejected[NMCUpdatePosition].from); - if (oInfo->rejected[NMCUpdatePosition]) ret = ret + " Rejected"; - return ret; -} - - -/*! -\patch 1.52 Date 4/19/2002 by Jirka -- Fixed: When gamemaster disconnect from server during mission selection, server was in bad state. -\patch 1.79 Date 7/31/2002 by Jirka -- Improved: Mission on dedicated server launched if all roles are assigned and confirmed even if some players remain -\patch 1.82 Date 8/23/2002 by Ondra -- Fixed: MP: If server had predefined mission cycle, -mission sometimes started while first user was connecting. -\patch 5110 Date 12/21/2006 by Jirka -- Fixed: Dedicated server can use missions in addons now -\patch 5132 Date 2/23/2007 by Jirka -- Fixed: server config parameter persistent is fully working now -\patch 5133 Date 2/26/2007 by Jirka -- Fixed: MP - admin is deciding when briefing is finished now -*/ - -struct MissionParameter -{ - RString name; - float val; - MissionParameter() {}; - MissionParameter(RString name1, float val1) : name(name1), val(val1) {}; - ClassIsMovableZeroed(MissionParameter); -}; - -void NetworkServer::SimulateDS() -{ - PROFILE_SCOPE_EX(nwDS, network) - - DWORD tickCount = GlobalTickCount(); - SimulateMonitor(tickCount); - -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - if (!_dedicated) return; - - - // persistent server with only one mission defined in server.cfg (class Missions) run the mission immediately without any players connected - bool startPersistentMission = false; - if (_persistent && _serverState!=NSSPlaying) - { - ConstParamEntryPtr entry = _serverCfg.FindEntry("Missions"); - int nEntries = entry ? entry->GetEntryCount() : 0; - startPersistentMission = (nEntries >= 1); - } - - if (_players.Size() <= 1 && !(_persistent && _serverState == NSSPlaying) && !startPersistentMission) - { - if (_serverState != NSSSelectingMission) - { - ConsoleF(LocalizeString(IDS_DS_NO_USERS)); - SetServerState(NSSSelectingMission); - CleanUpMemory(); - } - _missionIndex = -1; - _mission = ""; - _restart = false; - _reassign = false; - // restart timeout - _serverStateTime = GlobalTickCount(); - } - else // Main ServerState traverse section [SelectingMission, AssigningPlayers, Playing, Aborting...] - { - static bool loadIsland = false; - switch (_serverState) - { - case NSSSelectingMission: - { - RString t; - // if _param1,2 are not defined in server config, use default - _param1 = FLT_MAX; - _param2 = FLT_MAX; - AutoArray parameters; // secondary parameters - if (_mission.GetLength() == 1 && _mission[0] == '?') - { - // voting in progress - // check timeout, and react if necessary - // check how many players already voted - const Voting *miss = _votings.Find(NCMTMission); - if (!miss) break; - int total = _parent->GetIdentities()->Size(); - int ready = miss->Size(); - - // if server has reached half of its capacity, consider it full - if (CheckTimeOut(ready,total,VotingTimeOutReady,VotingTimeOutNotReady)) - { - // try applying vote first - if (!_votings.Apply(this,NCMTMission)) - { - // no voting available - select a random mission - AutoArray missionList; - LoadMissions(false, missionList); - int random = toIntFloor(GRandGen.RandomValue()*missionList.Size()); - saturate(random,0,missionList.Size()-1); - const MPMissionInfo &info = missionList[random]; - _mission = info.mission+"."+info.world; - // leave difficulty as it is - } - } - - break; - } - else if (_mission.GetLength() > 0) - { - // mission known - start it - t = _mission; - Glob.config.difficulty = _difficulty; - - _mission = ""; - _restart = false; - _reassign = false; - } - else - { - // check if there is some mission list defined - ConstParamEntryPtr entry = _serverCfg.FindEntry("Missions"); - int nEntries = entry ? entry->GetEntryCount() : 0; - if (nEntries == 0) - { - // no mission list - check if there are enough players to start voting - int voteMissionPlayers = 1; - entry = _serverCfg.FindEntry("voteMissionPlayers"); - if (entry) voteMissionPlayers = *entry; - if (_identities.Size() >= voteMissionPlayers) - { - // start voting - _mission = "?"; - NetworkCommandMessage answer; - answer._type = NCMTVoteMission; - NetworkCommandMessage answer2; - answer2._type = NCMTVoteMissionExt; - AddMissionList(answer,answer2); - for (int i=0; i<_identities.Size(); i++) - { - SendMsg(_identities[i].dpnid, &answer, NMFGuaranteed); - SendMsg(_identities[i].dpnid, &answer2, NMFGuaranteed); - } - } - break; - } - - // cycle through the mission list - _missionIndex++; - if (_missionIndex >= nEntries) _missionIndex = 0; - ParamEntryVal item = entry->GetEntry(_missionIndex); - - t = item >> "template"; - - Glob.config.difficulty = Glob.config.diffDefault; - entry = item.FindEntry("difficulty"); - if (entry) - { - RString diffName = *entry; - int difficulty = Glob.config.diffNames.GetValue(diffName); - if (difficulty >= 0) Glob.config.difficulty = difficulty; - } - else - { - bool cadetMode = item >> "cadetMode"; - if (cadetMode) - { - int difficulty = Glob.config.diffNames.GetValue("Cadet"); - if (difficulty >= 0) Glob.config.difficulty = difficulty; - } - else - { - int difficulty = Glob.config.diffNames.GetValue("Veteran"); - if (difficulty >= 0) Glob.config.difficulty = difficulty; - } - } - - if (item.FindEntry("param1")) _param1 = item >> "param1"; - if (item.FindEntry("param2")) _param2 = item >> "param2"; - - //read secondary parameters - ConstParamEntryPtr paramsDesc = item.FindEntry("Params"); - if(paramsDesc && paramsDesc->IsClass()) for(int i=0; i< paramsDesc->GetEntryCount();i++ ) - { - parameters.Add( MissionParameter( paramsDesc->GetEntry(i).GetName(), paramsDesc->GetEntry(i) ) ); - } - } - - // mission selected, start it now - - CurrentMission = ""; - - SetBaseDirectory(false, ""); - - bool noCopy = false; - RString owner; - - char mission[256]; strcpy(mission, t); - char *world = strrchr(mission, '.'); - if (!world) return; - *world = 0; world++; - -#if _ENABLE_MISSION_CONFIG - ConstParamEntryPtr entry = (Pars >> "CfgMissions" >> "MPMissions").FindEntry(mission); - if (entry) - { - ::SelectMission(*entry); - noCopy = true; - owner = entry->GetOwnerName(); - } - else -#endif - { - RString FindBriefingName(RString path); - RString displayName = FindBriefingName(MPMissionsDir + t); - - if (QIFileFunctions::FileExists(MPMissionsDir + t + RString(".pbo"))) - { - // mission in public bank - CreateMission(mission, world); - SetMission(world, "__cur_mp", MPMissionsDir); - Glob.header.filenameReal = mission; - - ConsoleF(LocalizeString(IDS_DS_MISSION_READ_FROM_BANK), (const char *)displayName); - } - else if (QIFileFunctions::FileExists(MPMissionsDir + t + RString("\\mission.sqm")) || - QIFileFunctions::FileExists(MPMissionsDir + t + RString("\\mission.sqf"))) - { - // mission in public directory - CreateMission("", ""); - SetMission(world, mission, MPMissionsDir); - - ConsoleF(LocalizeString(IDS_DS_MISSION_READ_FROM_DIR), (const char *)displayName); - } - else break; - } - - // load template - if (!ParseMission(true, true)) break; - - // if parameters are not set in server config, use defaults - if (_param1 == FLT_MAX) - { - _param1 = 0; - ConstParamEntryPtr cfg = ExtParsMission.FindEntry("defValueParam1"); - if (cfg) _param1 = *cfg; - } - if (_param2 == FLT_MAX) - { - _param2 = 0; - ConstParamEntryPtr cfg = ExtParsMission.FindEntry("defValueParam2"); - if (cfg) _param2 = *cfg; - } - _paramsArray.Clear(); - _paramsArray.Add(_param1); - _paramsArray.Add(_param2); - // secondary parameters - ConstParamEntryPtr paramsDesc = ExtParsMission.FindEntry("Params"); - if(paramsDesc) for(int i=0; i< paramsDesc->GetEntryCount();i++ ) - { - ParamEntryVal parameterDesc = paramsDesc->GetEntry(i); - ConstParamEntryPtr entry = parameterDesc.FindEntry("default"); - _paramsArray.Add(entry ? *entry : 0); - RString name = parameterDesc.GetName(); - for (int j=0; jIsArray()) - { - for (int i=0; iGetSize(); i++) - { - int chan = toInt((float)(*cls)[i]); - DisableChannel(chan); - } - } - - InitMission(Glob.config.difficulty, RString(), noCopy, owner, false); - SetServerState(NSSAssigningPlayers); - } - break; - case NSSAssigningPlayers: - { - _restart = false; - - // create game - SetServerState(NSSSendingMission); - SendMissionFile(); - - ConsoleF(LocalizeString(IDS_DS_ROLES_ASSIGNED)); - - // clear statistics now - ensure they will not be cleared after stats info from clients arrived - GStats.ClearMission(); - SetServerState(NSSLoadingGame); - - loadIsland = true; - } - break; - case NSSSendingMission: - Fail("Temporary state"); - break; - case NSSLoadingGame: - if (loadIsland && GNetworkManager.GetClient()->GetClientState() == NCSMissionReceived) - { - loadIsland = false; - - ConsoleF(LocalizeString(IDS_DS_READING_MISSION)); - - Ref p = GWorld->BegLoadMissionProgress(Glob.header.worldname, *CurrentTemplate, GModeNetware); - - GWorld->SwitchLandscape(Glob.header.worldname); - - //set parameters - after SwitchLandscape - float param1 = 0, param2 = 0; - GetNetworkManager().GetParams(param1, param2); - GameState *gstate = GWorld->GetGameState(); - gstate->VarSet("param1", GameValue(param1), false, false, GWorld->GetMissionNamespace()); // mission namespace - gstate->VarSet("param2", GameValue(param2), false, false, GWorld->GetMissionNamespace()); // mission namespace - GNetworkManager.PublicVariable("param1", 0); - GNetworkManager.PublicVariable("param2", 0); - - const MissionHeader *header = GetNetworkManager().GetMissionHeader(); - AutoArray paramsArray = GetNetworkManager().GetParamsArray(); - GameValue valueAR = gstate->CreateGameValue(GameArray); - GameArrayType &arrayAR = valueAR; - arrayAR.Resize(0); - for(int i=0; i< paramsArray.Size(); i++) - { - if(header->_sizesParamArray[i]<=0) continue; - arrayAR.Add(paramsArray[i]); - } - gstate->VarSet("paramsArray", arrayAR, false, false, GWorld->GetMissionNamespace()); // mission namespace - GNetworkManager.PublicVariable("paramsArray", 0); - - CurrentTemplate->ActivateAddons(Glob.header.worldname); - CurrentTemplate->InitGeneral(GModeNetware); - bool error = !GWorld->InitVehicles(*CurrentTemplate); - - ProgressFinish(p); - - RString message = GetMaxErrorMessage(); - if (message.GetLength()>0) - { - ServerMessage(message); - if (GetMaxError()>=EMError) // on error select another mission, let warning through - { - SetServerState(NSSSelectingMission); - break; - } - } - if (error) - { - ServerMessage(LocalizeString(IDS_DS_LOAD_MISSION_ERROR)); - SetServerState(NSSSelectingMission); - break; - } - - GNetworkManager.CreateAllObjects(); - // objects are created on client, so we can proceed after transfer from client to server completes - - void RunInitScript(); - RunInitScript(); - - message = GetMaxErrorMessage(); - if (message.GetLength()>0) - { - ServerMessage(message); - if (GetMaxError()>=EMError) // on error select another mission, let warning through - { - SetServerState(NSSSelectingMission); - break; - } - } - ConsoleF(LocalizeString(IDS_DS_MISSION_READ)); - } - break; - case NSSPlaying: - if (_restart) - { - GNetworkManager.DestroyAllObjects(); - ConsoleF("Game restarted"); - SetServerState(NSSMissionAborted); - } - else if - ( - GWorld->GetEEndMode() != EMContinue && - ( - (!GWorld->GetCameraEffect() && !GWorld->GetTitleEffect()) || - GWorld->IsEndForced() - ) - ) - { - GNetworkManager.DestroyAllObjects(); - ConsoleF(LocalizeString(IDS_DS_GAME_FINISHED)); - SetServerState(NSSMissionAborted); // we need to wait on the end of mission on other clients - } - else - { - if (!_persistent) - { - // if the server is not persistent, check if some player is still playing the mission - // if not, we want the mission to be terminated - // see also World::CheckMissionEnd to termination on all players dead - - bool all = true; - for (int i=0; i<_players.Size(); i++) - { - int player = _players[i]->dpid; - - NetworkClientState state = GetClientState(player); - if (state >= NCSGameLoaded && state <= NCSGameFinished) - { - all = false; - break; - } - } - if (all) - { - GNetworkManager.DestroyAllObjects(); - ConsoleF(LocalizeString(IDS_DS_GAME_FINISHED)); - SetServerState(NSSMissionAborted); - //debriefing = Glob.uiTime; - } - } - } - break; - case NSSMissionAborted: - { - bool all = true; - if (_gameMaster != AI_PLAYER) - { - NetworkClientState state = GetClientState(_gameMaster); - all = state != NCSPlaying && state != NCSGameFinished; - } - else - { - int total = 0, ready = 0; - for (int i=0; i<_players.Size(); i++) - { - NetworkClientState state = _players[i]->clientState; - - if (state>=NCSPlaying || state<=NCSMissionSelected) - { - total++; - if (state>=NCSGameFinished) - { - ready++; - } - } - } - - all = ( - ready>=total || - CheckTimeOut(ready,total,DebriefingTimeOutReady,DebriefingTimeOutNotReady) - ); - } - if (all) - { - // update statistics - if (_restart && _reassign) - { - DoReassignDirect(); - } - else if (_restart && _mission.GetLength() == 0) - { - SetServerState(NSSAssigningPlayers); - loadIsland = true; - } - else - { - SetServerState(NSSSelectingMission); - ConsoleF(LocalizeString(IDS_DS_WAITING_FOR_NEXT_GAME)); - } - } - } - break; - } - } - - - if (GDebugVoNBank.IsReportReady(tickCount)) - { // Report the #debug von collected info at last - FILE *LogFile = GetNetworkManager().GetDedicatedServerLogFile(); - if ( LogFile ) - { - AutoArray > convTable; - convTable.Realloc(_identities.Size()); - convTable.Resize(_identities.Size()); - for (int i=0; i<_identities.Size(); i++) - { - convTable[i]._dpnid = _identities[i].dpnid; - convTable[i]._id = _identities[i].GetDebugId(); - convTable[i]._name = _identities[i].name; - } - fprintf(LogFile, "*** VoN Topology Diagnostics ((***\n"); - RString response = GDebugVoNBank.GetDebugString(convTable); - GDebugVoNBank.StopCollecting(); // other client responses are too late - GDebugVoNBank.Reset(); // next #debug von should not contain old data - fwrite(cc_cast(response), 1, response.GetLength(), LogFile); - fprintf(LogFile, "*** VoN Topology Diagnostics ))***\n"); - fflush(LogFile); - } - } - - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.clientState < NCSConnected) continue; - if (info.motdIndex >= 0 && Glob.uiTime >= info.motdTime) - { - ChatMessage chat; - chat._channel = CCGlobal; - chat._text = _motd[info.motdIndex]; - chat._name = ""; - SendMsg(info.dpid, &chat, NMFGuaranteed); - - info.motdIndex++; - if (info.motdIndex >= _motd.Size()) info.motdIndex = -1; - else info.motdTime = Glob.uiTime + _motdInterval; - } - } - -#endif // _ENABLE_DEDICATED_SERVER -//} -} - - -void NetworkServer::SimulateMonitor( DWORD tickCount ) -{ -#if _ENABLE_DEDICATED_SERVER - _monitorFrames++; - if (tickCount >= _monitorNext) - { - if (_gameMaster == AI_PLAYER && _dedicated) - { - _monitorInterval = 0; - } - else //if (_state == NGSPlay) - { - NetworkCommandMessage msg; - msg._type = NCMTMonitorAnswer; - float invInterval = 1.0 / (_monitorInterval + 0.001f * (tickCount - _monitorNext)); - float fps = _monitorFrames * invInterval; - int memory = MemoryUsed(); - float in = _monitorIn * invInterval; - float out = _monitorOut * invInterval; - msg._content.Write(&fps, sizeof(fps)); - msg._content.Write(&memory, sizeof(memory)); - msg._content.Write(&in, sizeof(in)); - msg._content.Write(&out, sizeof(out)); - - int sizeG = 0, sizeNG = 0; - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &player = *_players[i]; - for (int j=0; jmsg->size; - for (int j=0; jmsg->size; - } - msg._content.Write(&sizeG, sizeof(sizeG)); - msg._content.Write(&sizeNG, sizeof(sizeNG)); - - SendMsg(_gameMaster!=AI_PLAYER ? _gameMaster : BOT_CLIENT, &msg, NMFGuaranteed); - } - Monitor(_monitorInterval); - } -#endif -} - - - -#if PEER2PEER - -void P2PServerProcess(int channel, P2PMsgType type, BYTE *data, int dataSize, void *context) -{ - if (type == P2PRequest) - { - if (dataSize < 1) return; - PeerToPeerServer *p2p = (PeerToPeerServer*)context; - Assert(p2p); - switch (data[0]) // message type - { - case 0: - // list of missions - { - QOStrStream out; - out.put(0); // response type - - // TODO: caching for faster response - AutoArray list; - SaveHeaderAttributes filter; - filter.Add("type", FindEnumName(STMission)); - filter.Add("player", Glob.header.GetPlayerName()); - GDebugger.PauseCheckingAlive(); - FindSaves(list, filter); - GDebugger.ResumeCheckingAlive(); - for (int i=0; iSendAnswer(channel, (BYTE *)out.str(), out.pcount()); - } - break; - case 1: - // mission - break; - } - } -} - -#endif // PEER2PEER - -#if _ENABLE_CHEATS || _ENABLE_DEDICATED_SERVER - -NetStatsGraph::NetStatsGraph() -{ - _lastTime = ::GlobalTickCount(); - _lastSize = 0; - _lastMsg = 0; -} - -void NetStatsGraph::OnSimulate(int size, int msg) -{ - DWORD now = ::GlobalTickCount(); - float deltaT = (now-_lastTime)*0.001f; - if (deltaT>0) - { - // 8*000.1 convert from B/s to kbps - PerformanceGraph<2>::Values val; - val.values[0] = (size-_lastSize)*8*0.001f/deltaT; - val.values[1] = (msg-_lastMsg)/deltaT; - AddSample(val,deltaT); - } - _lastSize = size; - _lastMsg = msg; - _lastTime = now; - -} - -#endif - -RefD ImplicitMapTraits< RefD >::zombie = (NetworkObjectInfo*)1; -RefD ImplicitMapTraits< RefD >::null; - -/*! -\patch 1.79 Date 7/26/2002 by Jirka -- Added: Elimination of "disconnect cheat" -\patch 1.90 Date 10/30/2002 by Jirka -- Fixed: Message "Player ... is loosing connection" isn't write for server now -*/ - -RString NetworkServer::NetworkIdToNetIdFriendly(const NetworkId &id) -{ - RefD dInfo; - if (_objects.get(id,dInfo)) - { - NetworkMessageCreateVehicle *msg = dynamic_cast(dInfo->create.message.GetRef()); - if (msg) - { - return Format("%s %s", cc_cast(NetworkIdToNetId(id)), cc_cast(msg->_type)); - } - else - { - const char *name = "UNKNOWN"; - switch (dInfo->create.type) - { - case NMTCreateClientCameraPosition: name = "cameraPos"; break; - case NMTCreateTurret: name = "turret"; break; - case NMTCreateShot: name = "shot"; break; - } - return Format("%s %s", name, cc_cast(NetworkIdToNetId(id))); - } - } - //! object not found? - return NetworkIdToNetId(id); -} - -void NetworkServer::OnSimulate() -{ - PROFILE_SCOPE_EX(nwSer, network) - -#if _ENABLE_DEDICATED_SERVER - // Show the dedicated server's own update rate in the console window title. - // This counts server simulation callbacks, not the connected client's render FPS. - if (IsDedicatedServer()) - { - static DWORD fpsWindowStart = 0; - static unsigned int fpsWindowFrames = 0; - const DWORD now = ::GetTickCount(); - if (fpsWindowStart == 0) fpsWindowStart = now; - ++fpsWindowFrames; - const DWORD elapsed = now - fpsWindowStart; - if (elapsed >= 1000) - { - const float serverFps = fpsWindowFrames * 1000.0f / elapsed; - NetworkServer *server = GNetworkManager.GetServer(); - if (server) - { - RString title = APP_NAME " Console version " APP_VERSION_TEXT "." STRINGIZE(BUILD_NO) ": port %d | FPS %.1f"; - ConsoleTitle(title, server->GetSessionPort(), serverFps); - } - fpsWindowStart = now; - fpsWindowFrames = 0; - } - } -#endif - -#define DIAGNOSE_NETWORK_OBJECTS 0 -#if DIAGNOSE_NETWORK_OBJECTS - static volatile bool diagnoseObjects = false; - if (diagnoseObjects) - { - RptF("*** NetworkServer _objects list"); - IteratorState it; - RefD obj; - if ( _objects.getFirst(it,obj) ) - { - do - { - RptF(" %s",NetworkIdToNetIdFriendly(obj->id)); - } - while ( _objects.getNext(it,obj) ); - } - RptF("*** NetworkServer _objects list"); - diagnoseObjects = false; //only once - } -#endif - - // raw statistics -#if _ENABLE_CHEATS - // remove statistics info - static AutoArray texts; - for (int i=0; i= 0) GEngine->RemoveText(texts[i]); - } - texts.Resize(0); - - if (outputDiags == ODMRawStats+NOutputDiags) - { - _rawStatisticsGraph.Resize(_rawStatistics.Size()); - // int y = 40; - for (int i=0; i<_rawStatistics.Size(); i++) - { - char output[1024]; - NetworkPlayerInfo *info = GetPlayerInfo(_rawStatistics[i].player); - if (!info) continue; - sprintf - ( - output, "To %s: sent %d (%d), received %d (%d)", - (const char *)info->name, - _rawStatistics[i].sizeSent, _rawStatistics[i].msgSent, - _rawStatistics[i].sizeReceived, _rawStatistics[i].msgReceived - ); - texts.Add(GEngine->ShowTextF(1000, output)); - //y += 25; - - if (!_rawStatisticsGraph[i]) _rawStatisticsGraph[i] = new NetStatsGraph; - _rawStatisticsGraph[i]->OnSimulate(_rawStatistics[i].sizeSent,_rawStatistics[i].msgSent); - GEngine->ShowDiagGraph(_rawStatisticsGraph[i]); - - } - } -#endif - -#define DIAG_NETWORK_OBJECTS 0 -#if DIAG_NETWORK_OBJECTS - static int diagnozeObjectId = 0; - if (diagnozeObjectId) - { - for (int i=0; i<_objects.Size(); i++) - { - Object *obj = dynamic_cast(GNetworkManager.GetObject(_objects[i]->id)); - if (obj && obj->GetObjectId().Encode()==diagnozeObjectId) - { - LogF( " DIAGNOZED ENTITY: %s, index in _objects=%d", obj->GetDebugName(), i ); - break; - } - } - diagnozeObjectId = 0; - } - // find object diagnoze using her NetworkId - static bool diagnozeNetworkId = false; - static int diagnozeCreator = 0; - static int diagnozeId = 0; - if (diagnozeNetworkId) - { - NetworkId diagNetworkId(diagnozeCreator, diagnozeId); - int index = -1; - for (int i=0; i<_objects.Size(); i++) - { - if (_objects[i]->id==diagNetworkId) { index=i; break; } - } - NetworkObject *nObj = GNetworkManager.GetObject(diagNetworkId); - if (nObj) - { - LogF( " DIAGNOZED ENTITY: %s, index in _objects=%d", nObj->GetDebugName(), index ); - } - else - { - LogF( " DIAGNOZED ENTITY: *NOT FOUND*, index in _objects=%d", index ); - } - diagnozeNetworkId = false; - } -#endif - -#define DIAG_SLOPE_SELECTION_SERVER_LAGGING 0 -#if DIAG_SLOPE_SELECTION_SERVER_LAGGING - // RptF all players networking information from time to time - int currentTickCnt = ::GetTickCount(); - static DWORD lastDiagTickCount = currentTickCnt; - const DWORD nextDiagDelay = 60000; //1 minute - if ( lastDiagTickCount + nextDiagDelay < currentTickCnt ) - { - lastDiagTickCount = currentTickCnt; - RptF("*** Start: Players Networking Diagnostics ***"); - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &pnet = _players[i]; - //if (pnet.dpid==BOT_CLIENT) continue; - PlayerIdentity *id = FindIdentity(pnet.dpid); - if (!id) continue; - RptF(" %s bandwidth=<%d,%d,%d> ping=<%d,%d,%d> desync=%d", - cc_cast(id->name), - toLargeIntSat(pnet._bandwidth.GetMin()/(1024/8)), toLargeIntSat(pnet._bandwidth.GetMax()/(1024/8)), toLargeIntSat(pnet._bandwidth.GetAvg()/(1024/8)), - toInt(pnet._ping.GetMin()), toInt(pnet._ping.GetMax()), toInt(pnet._ping.GetAvg()), - toLargeIntSat(pnet._desync.GetAvg()*100) - ); - } - RptF("*** End: Players Networking Diagnostics ***"); - } -#endif - -#if _ENABLE_DEDICATED_SERVER - - { - DWORD now = GlobalTickCount(); - if (now >= _debugNext) - { - if (_gameMaster == AI_PLAYER && _dedicated || _debugInterval<0.001) - { - _debugNext = INT_MAX; - } - else - { - _debugNext = _debugNext + toInt(_debugInterval*1000); - } - - float invAge = 1/_debugInterval; - - if (_debugOn.FindKey(DTUserSent) >= 0) - { - for (int i=0; i<_rawStatistics.Size(); i++) - { - BString<512> output; - NetworkPlayerInfo *info = GetPlayerInfo(_rawStatistics[i].player); - if (!info) continue; - sprintf - ( - output, "%s: sent %.0f bps (%.2f Msgps), received %.0f bps (%.2f Msgps)", - (const char *)info->name, - invAge * _rawStatistics[i].sizeSent *8, invAge * _rawStatistics[i].msgSent, - invAge * _rawStatistics[i].sizeReceived *8, invAge * _rawStatistics[i].msgReceived - ); - DebugAnswer((const char *)output); - } - } - - if (_debugOn.FindKey(DTTotalSent) >= 0) - { - int totalMsgSent = 0; - int totalMsgReceived = 0; - int totalSizeSent = 0; - int totalSizeReceived = 0; - for (int i=0; i<_rawStatistics.Size(); i++) - { - totalMsgSent += _rawStatistics[i].msgSent; - totalMsgReceived += _rawStatistics[i].msgReceived; - totalSizeSent += _rawStatistics[i].sizeSent; - totalSizeReceived += _rawStatistics[i].sizeReceived; - } - BString<512> output; - sprintf - ( - output, "** Total: sent %.0f bps (%.2f Msgps), received %.0f bps (%.2f Msgps)", - invAge * totalSizeSent * 8, invAge * totalMsgSent, - invAge * totalSizeReceived * 8, invAge * totalMsgReceived - ); - DebugAnswer((const char *)output); - } - - _rawStatistics.Clear(); - - if (_debugOn.FindKey(DTUserQueue) >= 0) - { - // send info about all players - for (int i=0; i<_players.Size(); i++) - { - const NetworkPlayerInfo &player = *_players[i]; - int sizeG = 0, sizeNG = 0; - for (int j=0; jmsg->size; - for (int j=0; jmsg->size; - // print actual desync as well - - BString<512> output; - sprintf - ( - output, "%s: Queue %d B (%d) %d B Guaranteed (%d), Desync %.0f", - (const char *)player.name, - sizeNG, player._messageQueueNonGuaranteed.Size(), sizeG, player._messageQueue.Size(), - player._desync.GetAvg()*100 - ); - DebugAnswer((const char *)output); - } - } - if (_debugOn.FindKey(DTUserInfo) >= 0) - { - // send info about all players - for (int i=0; i<_players.Size(); i++) - { - const NetworkPlayerInfo &player = *_players[i]; - - RString stats = _server->GetStatistics(player.dpid); - - BString<512> output; - sprintf - ( - output, "%s: Info %s", - (const char *)player.name, (const char *)stats - ); - DebugAnswer((const char *)output); - } - } - if (_debugOn.FindKey(DTJIPQueue) >= 0) - { - BString<512> output; - sprintf(output, "Init %d",_initMessages.Size()); - DebugAnswer((const char *)output); - - } - } // if (time for #debug) - - } -#endif - - // receive all system and user messages - { - PROFILE_SCOPE_EX(nwSRv, network) - ReceiveSystemMessages(); - ReceiveLocalMessages(); - ReceiveUserMessages(); - } - - // SDZ_SQF_EXEC: all network messages of this frame are processed; it is now safe - // to run scripts that create/delete objects or walk the mission object list. - #if _ENABLE_DEDICATED_SERVER - if (_dedicated) ProcessQueuedExec(); - #endif - - PerformIntegrityInvestigations(); - - #if _ENABLE_MP - // cancel all update messages - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &pInfo = *_players[i]; - // statistics - if (DiagLevel >= 3) - { - int nMsg, nBytes, nMsgG, nBytesG; - _server->GetSendQueueInfo(pInfo.dpid, nMsg, nBytes, nMsgG, nBytesG); - if (nMsg > 0 || nMsgG > 0) - { - if ( nMsgG < 0 ) // old style - DiagLogF("Server to %s: pending in SendQueue: %d messages, %d bytes", (const char *)pInfo.name, nMsg, nBytes); - else // new style - DiagLogF("Server to %s: pending in SendQueue: common - %d messages, %d bytes, guaranteed - %d messages, %d bytes", - (const char *)pInfo.name, nMsg, nBytes, nMsgG, nBytesG); - } - } - } - #endif - - DWORD tickCount = GlobalTickCount(); - if (GDebugVoNBank.IsReportReady(tickCount)) - { // Report the #debug von collected info at last - AutoArray > convTable; - convTable.Realloc(_identities.Size()); - convTable.Resize(_identities.Size()); - for (int i=0; i<_identities.Size(); i++) - { - convTable[i]._dpnid = _identities[i].dpnid; - convTable[i]._id = _identities[i].GetDebugId(); - convTable[i]._name = _identities[i].name; - } - FILE *LogFile = GetNetworkManager().GetDedicatedServerLogFile(); - if ( LogFile ) - { - fprintf(LogFile, "*** VoN Topology Diagnostics ((***\n"); - RString response = GDebugVoNBank.GetDebugString(convTable); - GDebugVoNBank.StopCollecting(); // other client responses are too late - GDebugVoNBank.Reset(); // next #debug von should not contain old data - fwrite(cc_cast(response), 1, response.GetLength(), LogFile); - fprintf(LogFile, "*** VoN Topology Diagnostics ))***\n"); - fflush(LogFile); - } - else - { - // Set TimeStampFormat of LogF to none in order to make VoN Topology Diagnostics parser VoNDiag2FSM.exe working - TimeStampFormat backup = GTimeStampFormat; - GTimeStampFormat = TSFNone; - LogF("*** VoN Topology Diagnostics ((***"); - RString response = GDebugVoNBank.GetDebugString(convTable); - GDebugVoNBank.StopCollecting(); // other client responses are too late - GDebugVoNBank.Reset(); // next #debug von should not contain old data - response = response + "*** VoN Topology Diagnostics ))***"; - LogF(response); - GTimeStampFormat = backup; - } - } - - SimulateDS(); - - // kick off players faded out - CheckFadeOut(); - - // destroy players kicked out - int size = _identities.Size(); - for (int i=size-1; i>=0; i--) - { - PlayerIdentity &identity = _identities[i]; - if (identity.destroy && Glob.uiTime >= identity.destroyTime) - { - OnPlayerDestroy(identity.dpnid); - } - } - - // send update messages - { - PROFILE_SCOPE_EX(nwSSd, network) - SendMessages(); - } - - // update _serverTime - _serverTime = ::GetTickCount()-_serverTimeInitTickCount; - if ( _serverTime > _nextServerTimeUpdate ) - { - _nextServerTimeUpdate = _serverTime + ServerTimeUpdateInterval; - // send fresh serverTime update to all clients - ServerTimeMessage stmsg; - _serverTime = ::GetTickCount()-_serverTimeInitTickCount; // update _serverTime - stmsg._time = _serverTime; - stmsg._endTime = _serverTimeOfEstimatedEnd; - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.clientState < NCSConnected) continue; - SendMsg(info.dpid, &stmsg, NMFGuaranteed | NMFHighPriority); - } - } - - // calculate aggregate de-sync average - { - float desyncTotal = 0; - - float avgDesync = 0; - float maxDesync = 0; - int nDesync = 0; - for (int i=0; i<_players.Size(); i++) - { - const NetworkPlayerInfo &pnet = *_players[i]; - // bot client has no de-sync by definition - if (pnet.dpid==BOT_CLIENT) continue; - float value = pnet._desync.GetLastValue(); - avgDesync += value, nDesync ++; - saturateMax(maxDesync,value); - } - if (nDesync>0) - { - avgDesync /= nDesync; - // aggregate de-sync - consider both avg and max - desyncTotal = avgDesync*0.7f+maxDesync*0.3f; - } - _desyncTotal.Sample(desyncTotal,1e-3); - } - - - const DWORD desyncTotalPeriod = 5000; - if (GlobalTickCount()>_desyncTotalUpdateNext) - { - // maintain aggregate de-sync average - _desyncTotalAvg = _desyncTotal.GetAvg(); - _desyncTotalMax = _desyncTotal.GetMax(); - _desyncTotal.Reset(); - _desyncTotalUpdateNext = GlobalTickCount()+desyncTotalPeriod; - } - - // avoid flickering the icon - // check de-sync information for all players - _connectionDesync = CDGood; - // show worst de-sync found for any player - float aggDesync = _desyncTotalAvg; - if (aggDesync>PlayerIdentity::DesyncLow/100) - { - if (aggDesync>PlayerIdentity::DesyncHigh/100) - { - _connectionDesync = CDHigh; - } - else - { - _connectionDesync = CDLow; - } - } - - tickCount = GlobalTickCount(); - if (tickCount >= _pingUpdateNext) - { - _pingUpdateNext = tickCount + 30000; - - // update all players information - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &pnet = *_players[i]; - //if (pnet.dpid==BOT_CLIENT) continue; - PlayerIdentity *id = FindIdentity(pnet.dpid); - if (!id) continue; - id->_minBandwidth = toLargeIntSat(pnet._bandwidth.GetMin()/(1024/8)); - id->_maxBandwidth = toLargeIntSat(pnet._bandwidth.GetMax()/(1024/8)); - id->_avgBandwidth = toLargeIntSat(pnet._bandwidth.GetAvg()/(1024/8)); - id->_minPing = toInt(pnet._ping.GetMin()); - id->_maxPing = toInt(pnet._ping.GetMax()); - id->_avgPing = toInt(pnet._ping.GetAvg()); - id->_desync = toLargeIntSat(pnet._desync.GetAvg()*100); - saturate(id->_desync,0,100000); - pnet._ping.Reset(); - pnet._bandwidth.Reset(); - pnet._desync.Reset(); - } - - // broadcast messages about all players to all players - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.clientState < NCSConnected) continue; - for (int i=0; i<_identities.Size(); i++) - { - PlayerIdentity &pi = _identities[i]; - - NetworkMessageType type = pi.GetNMType(NMCUpdatePosition); - - Ref msg = ::CreateNetworkMessage(type); - msg->time = Glob.time; - NetworkMessageContext ctx(msg, this, info.dpid, MSG_SEND); - ctx.SetClass(NMCUpdatePosition); - - PREPARE_TRANSFER(PlayerUpdate) - - TMError err; - int dpnid = pi.dpnid; - err = TRANSF_BASE(dpnid, dpnid); - if (err != TMOK) continue; - err = pi.TransferMsg(ctx); - if (err != TMOK) continue; - - // send message - //NetworkComponent:: - SendMsg(info.dpid,msg,type,NMFNone, NULL); - } - } - } - - // integrity and CDKey checks - DWORD time = GlobalTickCount(); - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - // CDKey check - if (info.cdKeyCheck.timeout) - { - if (time > info.cdKeyCheck.timeout) - { - if (info.dpid == BOT_CLIENT) - { - RString errmsg = LocalizeString(IDS_MP_BAD_CDKEY); - GChatList.Add(CCSystem, NULL, errmsg, false, true); - WarningMessage(errmsg); - Done(); - } - else - { - KickOff(info.dpid, KORAuthTimeOut); - } - info.cdKeyCheck.timeout = 0; //clear - } - } - } - - // squad checks - bool canSendCustomFiles = true; - bool timeout = false; - for (int i=0; i<_squadChecks.Size();) - { - CheckSquadObject *obj = _squadChecks[i]; - if (i==0) - { //first object can be timeouted in order others can connect too - if (_squadChecksTimeout) - { - if (_squadChecksTimeout < ::GetTickCount()) //timeout - timeout = true; - } - else if (obj->GetState()==CheckSquadObject::SendingCustomFiles) - { - _squadChecksTimeout = ::GetTickCount() + 30*1000; //30 seconds - } - } - if (obj->IsDone(canSendCustomFiles, this)) - { - PlayerIdentity &identity = obj->_identity; - CreateIdentity(identity); - _squadChecks.Delete(i); - if (i==0) //reset timeout - { - _squadChecksTimeout = 0; - timeout = false; - } - } - else i++; - } - if (timeout) - { - _squadChecksTimeout = 0; - // shift the squad objects and place the first at the end - int schSize = _squadChecks.Size(); - if (schSize>1) - { - SRef first = _squadChecks[0]; - for (int i=1; i_timeLeftLastTime+minBetweenUpdates) - { -/* - // do not update the session description regularly, server will ask us - - // time from time update matchmaking stats - UpdateMatchmakingDescription(false); -*/ - -#if _GAMES_FOR_WINDOWS - // set the properties and contexts for matchmaking - // - TimeLeft - GSaveSystem.SetProperty(PROPERTY_GAME_TIMELEFT, timeleft); -#endif - } - else if (_timeLeftLastValueBcast!=timeleft) - { - // if there is any timeleft estimation, update it - // updating session description for broadcast session is very quick - // no network traffic required - UpdateSessionDescription(); - _timeLeftLastValueBcast = timeleft; - } - -//{ QUERY & REPORTING SDK -#if _ENABLE_GAMESPY - SimulateQR(); -#endif -//} - - //{ STEAMWORKS SDK -#if _ENABLE_STEAM_MATCHMAKING - SimulateSteam(); -#endif - //} - - //DoAssert(CheckIntegrityOfPendingMessages()); - - //DWORD tickCount = ::GlobalTickCount(); - - - // log all diagnostics - WriteDiagOutput(true); - - // check for disconnected players - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.clientState != NCSPlaying) continue; - if (info.dpid == BOT_CLIENT) continue; - float age = _server->GetLastMsgAgeReliable(info.dpid); - if (info.connectionProblemsReported) - { - info.connectionProblemsReported = age > 5.0f; - } - else if (age >= 10.0f) - { - LocalizedFormatedString message; - message.SetFormat(LocalizedString::Stringtable,"STR_MP_CONNECTION_LOOSING"); - message.AddArg(LocalizedString::PlainText,info.name); - ServerMessage(message); - info.connectionProblemsReported = true; - } - } - -#if _ENABLE_CHEATS - if (_debugWindow) - { - _debugWindow->ResetContent(); - _objects.forEach([this](NetworkObjectInfo *oInfo) - { - if (!oInfo) return; - NetworkId id = oInfo->id; - int owner = oInfo->owner; - RString name = GetPlayerName(owner); - RString typeName; - if (oInfo->currentUpdate[0].message.NotNull()) - { - NetworkMessageType type = oInfo->currentUpdate[0].type; - DoAssert(type >=0 && type < NMTN); - typeName = GetMsgTypeName(type); - } - else typeName = "Unknown"; - BString<1024> text; - sprintf - ( - text, "%s %d:%" OID_FORMAT" - owner %s (%x)", - (const char *)typeName, id.creator.CreatorInt(), id.id, - (const char *)name, owner - ); - _debugWindow->AddString(text); - } - ); - } -#endif - -#if _VBS2 && _VBS2_LITE -// Check if there has been a hack attempt on player size limit -// if, there has been, we randomly select offsets and apply them to random players -if(_server) -{ - if(((_players.Size() << 3) > (_VBS2_MAX_PLAYERS << 3))&&(_memoryWrite == false)) - { - _memoryWrite = true; - _nextRanUpdate = GlobalTickCount() + (DWORD) GRandGen.Gauss((1000*30),(1000*30*2),(1000*30*3)); - } - - if(_memoryWrite && (GlobalTickCount()>_nextRanUpdate)) - { - DWORD nextUpdate = (DWORD) GRandGen.Gauss((1000*30),(1000*30*2),(1000*30*3)); - _nextRanUpdate = GlobalTickCount() + nextUpdate; - - int playerIndex = GRandGen.Gauss(0,0.5,_players.Size()); - if(playerIndex >= 0 && playerIndex < _players.Size()) - { - NetworkPlayerInfo &info = _players[playerIndex]; - NetworkId &id = info.person; - if (!id.IsNull()) - { - NetworkObjectInfo *oInfo = GetObjectInfo(id); - if(GNetworkManager.GetClient()) - { - NetworkObject *netObj = GNetworkManager.GetClient()->GetObject(oInfo->id); - Entity *obj = dyn_cast(netObj); - if(obj) - { - // raise player 100 feet above the ground. - Matrix4 trans = obj->Transform(); - Vector3 pos = trans.Position(); - pos += Vector3( - GRandGen.Gauss(-500.0f,0.0f,500.0f), - GRandGen.Gauss(-1.0f,0.0f,1.0f), - GRandGen.Gauss(-500.0f,0.0f,500.0f)); - - trans.SetPosition(pos); - obj->MoveNetAware(trans); - obj->OnPositionChanged(); - } - } - } - } - } -} -#endif - - // TODO: remove (temporary set all to all) - // Set voice transmission tables on Xbox - if (_server) - { - for (int i=0; i<_players.Size(); i++) - { - // if player is not fully created, he might be unable to receive VoN messages - // this is because VoNClient is created after MAGIC_CREATE_PLAYER message is sent - // perhaps better solution could be to create VoN client before sending the message - // Current solution with player state gives players also some time - // to establish and report peer to peer communication - if (_players[i]->clientStatedpid!=BOT_CLIENT) continue; - // set all other players as recipients - int fromID = _players[i]->dpid; - AUTO_STATIC_ARRAY(int, players, 32); - for (int j=0; j<_players.Size(); j++) - { - if (_players[j]->clientStatedpid!=BOT_CLIENT) continue; - int toID = _players[j]->dpid; - if (toID != fromID) players.Add(toID); -#if HEAR_YOURSELF - else if (hearYourself) players.Add(toID); -#endif - } - _server->SetTransmitTargets(fromID, players); - } - _server->UpdateTransmitTargets(); - } - -#if _USE_BATTL_EYE_SERVER - if (!_beIntegration.Run(this)) - { - // reinitialization after auto-update failed, need to shut-down the server - Done(); - } -#if 0 - // simple test of ExecuteCommand functioinality - static volatile int doIt = -1; //set it to 1000 or something and wait - if (doIt>0) doIt--; - else if (!doIt) - { - doIt--; - BattlEye::ExecuteCommand("#restart"); - } -#endif -#endif - - // check if characters loading is not finished - for (int i=0; i<_players.Size(); i++) - { - _players[i]->DBCheckLoaded(); - } - -#if _ENABLE_STEAM_MATCHMAKING && _ENABLE_DEDICATED_SERVER - static int counter = 0; - if ((counter++ % 10)==0) // TODO - { - for (int i=0; i<_identities.Size(); ++i) - { - if (_identities[i]._statistics) _identities[i]._statistics->Simulate(); - } - } -#endif -} - -void NetworkServer::OnSimulateDone() -{ -} - -void NetworkServer::FastUpdate() -{ -//{ QUERY & REPORTING SDK -#if _ENABLE_GAMESPY - SimulateQR(); -#endif -//} -} - -void NetworkServer::OnDraw() -{ - static bool lagDiags = false; - - if (GInput.GetCheatXToDo(CXTLag)) - { - lagDiags = !lagDiags; - GlobalShowMessage(500,"Lag diags %s",lagDiags ? "On":"Off"); - } - if (lagDiags) - { - static float minLagToShow = 1.0f; - static float badLag = 100.0; - float x = 0.05f; - float y = 0.08f; - float width = 0.80f; - Font *font=GEngine->GetDebugFont(); - float size = 0.02; - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &pnet = *_players[i]; - float maxLag = pnet._desync.GetMax(); - if (maxLagConvert(rect2D,rect); - Point2DAbs pos(rect2D.x,rect2D.y); - MipInfo mip = GEngine->TextBank()->UseMipmap(NULL, 0, 0); - GEngine->Draw2D(mip,color,rect2D); - - y+= size; // proceed to a next line - GEngine->DrawTextF( - pos,size,font,nameColor,0,"%s - %g, max %g, avg %g", - cc_cast(pnet.name),lag,pnet._desync.GetMax(),pnet._desync.GetAvg() - ); - } - } -} - -DEFINE_FAST_ALLOCATOR(NetworkObjectInfo) - -/*! -\patch 1.47 Date 3/7/2002 by Ondra -- New: Player ID now displayed in server console when player is connected. -\patch 1.56 Date 5/13/2002 by Ondra -- New: When player is kicked off or banned, specific message is shown. -\patch 5153 Date 4/17/2007 by Jirka -- Fixed: When failed to join to a locked server, the correct cause is shown now. -*/ - -void NetworkServer::OnCreatePlayer(int player, bool privateSlot, const char *name, unsigned long inaddr) -{ - if (_sessionLocked) - { - // session is locked - _server->KickOff(player, NTRSessionLocked); - return; - } - - OnPlayerCreate(player, privateSlot, name, inaddr); -} - -DummyInput GDummyInput; - -InputInterface *NetworkServer::GetInputInterface(int player) -{ - NetworkPlayerInfo *info = GetPlayerInfo(player); - if (!info) return &GDummyInput; - return info->_clientInput; -} - -bool NetworkServer::OnCreateVoicePlayer(int player) -{ - NetworkPlayerInfo *info = GetPlayerInfo(player); - if (!info) return false; - info->dvid = player; - return true; -} - -void NetworkServer::GetPlayers(AutoArray &players) -{ - players.Resize(0); - for (int i=0; i<_players.Size(); i++) - { - int index = players.Add(); - players[index].dpid = _players[i]->dpid; - players[index].name = _players[i]->name; - players[index].person = _parent->GetClient()->GetObject(_players[i]->person); - } -} - -void NetworkServer::UseItem(Person *person, InventoryItem *item) -{ - const NetworkObjectInfo *info = GetObjectInfo(person->GetNetworkId()); - if (!info) return; - - UseItemMessage msg; - msg._person = person; - msg._item = item; - SendMsg(info->owner, &msg, NMFGuaranteed); -} - -bool NetworkServer::CheckPlayerInLobby(const NetworkPlayerInfo &info) const -{ - if (info.clientState==NCSPlaying) - { - // in-game - check if alive - // this may be difficult, as we are server, and should not have any access to a game world? - // find a network object describing the players unit - const NetworkObjectInfo *obj = GetObjectInfo(info.person); - // if the unit is NULL, session was most likely already terminated on the server - if (!obj) return true; - const NetworkCurrentInfo &curInfo = obj->currentUpdate[NMCUpdateGeneric]; - // HOTFIX: probably possible in some rare conditions (crash occurred) - if (!curInfo.message) return false; - // unless proven otherwise, assume alive - } - else - { - // not in-game - force lobby - return true; - } - return false; -} - -void NetworkServer::GetPlayersOnChannel(AutoArray &players, AutoArray units, DWORD from, bool voice) -{ - players.Resize(0); - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.dpid == from) continue; - if (info.clientState < NCSConnected) continue; - for (int j=0; j &players, int channel, DWORD from, bool voice) -{ - players.Resize(0); - switch (channel) - { - case CCNone: - case CCDirect: - return; - case CCSystem: - case CCGlobal: - for (int i=0; i<_players.Size(); i++) - { - const NetworkPlayerInfo &info = *_players[i]; - if (info.dpid == from) continue; - if (info.clientState < NCSConnected) continue; - if (voice) - { - if (info.dvid != 0) players.Add(info.dvid); - } - else - players.Add(info.dpid); - } - break; - case CCVehicle: - // TODO: remove in DayZ? - break; - } - if (channel>=CCCustom1 && channel<=CCCustomLast) - { - for (int i=0; i<_players.Size(); i++) - { - const NetworkPlayerInfo &info = *_players[i]; - if (info.dpid == from) continue; - if (info.clientState < NCSConnected) continue; - CustomChannelInfo &ccinfo = GCustomChannels.GetCustomChannelInfo(channel); - for (int j=0; jGetNetworkId()) - { - if (voice) - { - if (info.dvid != 0) players.Add(info.dvid); - } - else - players.Add(info.dpid); - } - } - } - } -} - -void NetworkServer::InitSignatureCollecting(NetworkPlayerInfo *info) -{ - // last DataSignatureAnswer with index CollectEndIndex finishes it - info->hashes.StartCollecting(); -#if 0 - // do not send CollectEndIndex packet, as the collecting is run asynchronously on client - // the client itself should send the answer after the collecting is over - DataSignatureAskMessage collectEndMsg; - collectEndMsg._index = CollectedHashes::CollectEndIndex; - collectEndMsg._level = 0; - SendMsg(info->dpid, &collectEndMsg, NMFGuaranteed); -#endif - // add the question to the list of pending questions - info->signatureChecks.Add(CollectedHashes::CollectEndIndex); -} - -RString CollectedHashes::RandomUsedFile(Vector3Par pos, int level) -{ - const int CandidatesMaxCount = 5; - AutoArray > candidates; - for (int i=0; i<10; i++) //max 10 tries to get five non-empty candidates - { - RString file = GWorld->RandomUsedFile(pos); - if (file.IsEmpty()) continue; - QFBank *bank = QFBankQueryFunctions::AutoBank(file); - if (bank) - { - RString prefix = bank->GetPrefix(); - // avoid duplicate banks in candidates - bool duplicate = false; - for (int j=0; j0) - { - int bestIx = 0; int bestAsksCount = INT_MAX; - for (int i=0; i0) - { - if (ident.blockedKeys.Size()>0 && VerifySignedKeys(ident.blockedKeys,ident.blockedKeysSignature)) - { - // if there is any problem with the blocked key list, just ignore it - // synchronize server version of the list - // use always the longer one, as that is the more complete - UpdateBanListSecure(ident.blockedKeys,ident.blockedKeysSignature); - } - - RString message = "Player ID not registered"; - SignValidationResult signOK = SignUnknownError; - if (ident.certificate.Size()>0) - { - signOK = VerifySignedData(ident.id,info->certChallenge,ident.challengeSigned,ident.certificate); - switch (signOK) - { - case SignOK: break; - case SignBlockedUser: message = "CD Key is blocked";break; - case SignBadUserName: message = "Player ID not verified: Certificate belongs to a different user";break; - case SignBadSignature: message = "Player ID not verified: Bad signature";break; - case SignBadCertificate: message = "Player ID not verified: Certificate not accepted";break; - default: message = "Player ID not verified: Unknown error";break; - } - } - if (signOK!=SignOK) - { - if (SecureIdRequired()>=2) - { - // cheat - do not let him connect - KickOff(info->dpid,KORBadCDKey,message); - return; - } - else - { - // forget everything related to playerID verification, so that it is obvious the player was not verified - ident.certificate.Clear(); - ident.challengeSigned.Clear(); - info->certChallenge = 0; - RefArray dummy; - GNetworkManager.Chat(CCSystem, ident.name, dummy, message); - GChatList.Add(CCSystem, ident.name, message, false, true); - #if _ENABLE_DEDICATED_SERVER - if (_dedicated) - { - ConsoleF("%s:%s %s", cc_cast(ident.name), cc_cast(ident.id), cc_cast(message)); - } - #endif - } - } - } - #endif - - int index = _identities.Add(ident); - PlayerIdentity &identity = _identities[index]; - identity.playerid = NextPlayerId(); - -#if _ENABLE_STEAM_MATCHMAKING && _ENABLE_DEDICATED_SERVER - identity._statistics = new SteamStatistics(); - identity._statistics->Init(CSteamID((uint64)identity._steamID)); -#endif - -#if _VERIFY_KEY - // check for double id - if (identity.ValidateID()) - { - // check only when id!=0 - // for id==0 we have better handling - // id==999 is used in Multiplayer Demo - // DEV1,DEV2,...,DEV999 are used in internal versions with INTERNAL_KEYS - for (int i=0; i<_identities.Size(); i++) - { - if (i == index) continue; - - if (IsUserIdMatch(_identities[i].id,identity.id)) - { - OnDoubleIdDetected(identity, _identities[i]); - // check if player was kicked out - if (identity.destroy) return; - break; - } - } - } -#endif - -#if _ENABLE_GAMESPY && _VERIFY_CLIENT_KEY - if ( _validateCDKey && identity.dpnid!=BOT_CLIENT ) - { - #if _ENABLE_CHEATS // internal clients connected to internal exe perform no GS key validation - static const char devPrefix[] = "DEV"; - if (strncmp(identity.id,devPrefix,strlen(devPrefix))) - #endif - { - char buffer[9]; - for (int i=0; ichallenge = buffer; - // initial CD Key test - CDKeyCheckAskMessage ask; - ask._challenge = info->challenge; - SendMsg(identity.dpnid, &ask, NMFGuaranteed); - //increased to 90 seconds after problems with CD-key authentication 15.6.2012 - info->cdKeyCheck.timeout = GlobalTickCount()+90000; //90 seconds - } - } -#endif - - if (identity.dpnid == BOT_CLIENT) - identity._rights |= PRServer; - else - { - if (_verifySignatures) - { - if (_sigVerRequired<2) - { - // initial test of signatures - DataSignatureAskMessage ask; - ask._index = -2; - ask._level = 0; // shallow check - SendMsg(identity.dpnid, &ask, NMFGuaranteed); - InitSignatureCollecting(info); - } - else - { - // initial test using level 2 check - DataSignatureAskMessage askLev2; - askLev2._index = -2; - askLev2._level = 2; //HashOf(nonDataHash+fileListHash+pboPrefix) is used - SendMsg(identity.dpnid, &askLev2, NMFGuaranteed); - InitSignatureCollecting(info); - } - } - - - sockaddr_in address; - if (GetClientAddress(identity.dpnid, address)) - { - identity._voiceAddress = address; - //ConnectVoice(identity.dpnid,address); - } - } - -#if LOG_PLAYERS -LogF -( - "Server: Identity added - name %s, id %d (total %d identities, %d players)", - (const char *)ident.name, ident.dpnid, _identities.Size(), _players.Size() -); -#endif - - identity.name = info->name; - identity.clientState = NCSConnected; -#if _GAMES_FOR_WINDOWS - identity.privateSlot = info->privateSlot; -#endif - - // Send list of current players which custom files should be removed (as new one will be sent) - DeleteCustomFilesMessage dcfMsg; - for (int i=0; i<_identities.Size(); i++) - { - if (i != index) dcfMsg._list.Add(_identities[i].name); - } - if (dcfMsg._list.Size()) SendMsg(identity.dpnid, &dcfMsg, NMFGuaranteed); - - for (int i=0; i<_identities.Size(); i++) - { - PlayerIdentity &player = _identities[i]; - if (i != index) - { - // send all faces and sounds to new player - { - if (stricmp(player.face, "custom") == 0) - TransferFace(identity.dpnid, player.name); - TransferCustomRadio(identity.dpnid, player.name); - } - - // send all identities to new player - SendMsg(identity.dpnid, &player, NMFGuaranteed); - - } - // send new identity to all players - SendMsg(player.dpnid, &identity, NMFGuaranteed); - } - -#if _ENABLE_MP - // send mute list to a new player - SendMuteList(identity); -#endif - -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - if (_dedicated) - { - NetworkClient *client = _parent->GetClient(); - DoAssert(client && client->GetPlayer() != identity.dpnid); - // send new identity to bot client - SendMsg(client->GetPlayer(), &identity, NMFGuaranteed); - } -#endif -//} - -/* - info->state = NGSLogin; - - // all message formats registered, we may send messages - // send state dependent info - if (_state >= NGSPrepareSide) - { - // send mission info - SendMissionInfo(info->dpid); - info->state = NGSPrepareSide; - info->missionFileValid = false; - } - // send current state - ChangeGameState gs(_state); - SendMsg(info->dpid, &gs, NMFGuaranteed); - - // if game is already in progress, send how long is played already - if (_state == NGSPlay) - { - NetworkCommandMessage msg; - msg.type = NCMTMissionTimeElapsed; - int timeElapsed = GlobalTickCount() - _missionHeader.start; - msg.content.Write(&timeElapsed, sizeof(timeElapsed)); - SendMsg(info->dpid, &msg, NMFGuaranteed); - } - - identity.state = info->state; - - // send player state to all clients - SetPlayerState(info->dpid, info->state); -*/ - - // Send server state to client - ServerStateMessage msg; - msg._serverState = _serverState; - SendMsg(identity.dpnid, &msg, NMFGuaranteed); - - identity._minPing = 10; - identity._avgPing = 100; - identity._maxPing = 1000; - - identity._minBandwidth = 14; - identity._avgBandwidth = 28; - identity._maxBandwidth = 33; - - // Send chat message about player is connected - if (identity.dpnid != BOT_CLIENT) - { -/* - // commented out by rocket, not desired for dayz. possibly use for admins only - LocalizedFormatedString message; - message.SetFormat(LocalizedString::Stringtable,"STR_MP_CONNECT"); - message.AddArg(LocalizedString::PlainText,identity.name); - RefArray dummy; - if (!ChannelDisabled(CCSystem)) - GNetworkManager.LocalizedChat(CCSystem, "", dummy, message); - - GChatList.Add(CCSystem, NULL, message.GetLocalizedValue(), false, true); - - // make sure ping information will be refreshed soon - DWORD updatePingTime = GlobalTickCount() + 5000; - if (_pingUpdateNext>updatePingTime) _pingUpdateNext = updatePingTime; -*/ - #if _ENABLE_DEDICATED_SERVER - if (_dedicated) - { - ConsoleF(LocalizeString(IDS_DS_PLAYER_CONNECTED),cc_cast(identity.name), cc_cast(identity.id)); - } - #endif - } - UpdateMatchmakingDescription(false); - -#if _ENABLE_DEDICATED_SERVER - if (_serverState == NSSSelectingMission && _mission.GetLength() == 1 && _mission[0] == '?') - { - NetworkCommandMessage answer; - answer._type = NCMTVoteMission; - NetworkCommandMessage answer2; - answer2._type = NCMTVoteMissionExt; - AddMissionList(answer,answer2); - for (int i=0; i<_identities.Size(); i++) - { - SendMsg(_identities[i].dpnid, &answer, NMFGuaranteed); - SendMsg(_identities[i].dpnid, &answer2, NMFGuaranteed); - } - } -#endif - -#if _ENABLE_DEDICATED_SERVER - // event handler - OnEvent(SEOnUserConnected, identity.playerid); -#endif -} - -#ifndef _WIN32 -extern bool interrupted; -#endif - - -static bool CheckValidUpload(RString path, RString name) -{ - RString prefixShouldBe = GetServerTmpDir() + RString("\\players\\") + EncodeFileName(name) + RString("\\"); - return !strnicmp(path,prefixShouldBe,prefixShouldBe.GetLength()); -} - -static RString GetRelUploadPath(RString path, RString name) -{ - RString prefixShouldBe = GetServerTmpDir() + RString("\\players\\") + EncodeFileName(name) + RString("\\"); - if (strnicmp(path,prefixShouldBe,prefixShouldBe.GetLength())) return path; - return path.Substring(prefixShouldBe.GetLength(),INT_MAX); -} - -DWORD WINAPI AsyncDBStorage::DBSaveThreadFunction(void *ctx) -{ - Ref context = (SaveThreadContext *)ctx; - context->DecRef(); - - // wait until previous requests end - Ref prev = context->_prevContext; - if (prev) - { - prev->_thread.Wait(); - context->_prevContext = NULL; // no longer needed - } - - // send save request - RString result; - int err = GetResponse(EHTTPREQ_POST,result,context->_url,context->_uid,context->_request); - if (err >= 400) - { - LogF("HTTP Error: %d", err); - LogF(result); - } - - return 0; -} - -DWORD WINAPI AsyncDBStorage::DBQueueThreadFunction(void *ctx) -{ - Ref context = (SaveThreadContext *)ctx; - context->DecRef(); - - // wait until previous requests end - Ref prev = context->_prevContext; - if (prev) - { - prev->_thread.Wait(); - context->_prevContext = NULL; // no longer needed - } - - // send save request - RString result; - int err = GetResponse(EHTTPREQ_POST,result,context->_url,context->_uid,context->_request); - if (err >= 400) - { - LogF("HTTP Error: %d", err); - LogF(result); - } - - return 0; -} - -DWORD WINAPI AsyncDBStorage::DBKillThreadFunction(void *ctx) -{ - Ref context = (SaveThreadContext *)ctx; - context->DecRef(); - - // wait until previous requests end - Ref prev = context->_prevContext; - if (prev) - { - prev->_thread.Wait(); - context->_prevContext = NULL; // no longer needed - } - - // send save request - RString result; - - int err = GetResponse(EHTTPREQ_POST,result, context->_url,context->_uid, context->_request); - if (err >= 400) - { - LogF("HTTP Error: %d", err); - LogF(result); - } - - return 0; -} - -DWORD WINAPI AsyncDBStorage::DBItemDropThreadFunction(void *ctx) -{ - Ref context = (SaveThreadContext *)ctx; - context->DecRef(); - - // wait until previous requests end - Ref prev = context->_prevContext; - if (prev) - { - prev->_thread.Wait(); - context->_prevContext = NULL; // no longer needed - } - - // send save request - RString result; - - int err = GetResponse(EHTTPREQ_POST,result, context->_url, NULL, context->_request); - if (err >= 400) - { - LogF("HTTP Error: %d", err); - LogF(result); - } - - return 0; -} - -bool AsyncDBStorage::DBSave(RString baseURL, RString playerUID, RString request) -{ - SaveThreadContext *ctx = new SaveThreadContext(); - ctx->AddRef(); // player can disconnect while Thread still need access to its context - - ctx->_url = baseURL; - ctx->_uid = Format("?uid=%s", cc_cast(playerUID)); - ctx->_request = request; - ctx->_prevContext = _lastContext; - _lastContext = ctx; -#if USE_MT_LIB_FOR_JOBS - ctx->_thread.Init(CreateMTThreadOnCPU(64 * 1024, DBSaveThreadFunction, ctx, 2, MultiThread::ThreadBase::PriorityNormal, "DBSaveCharacter")); -#else - ctx->_thread.Init(CreateThreadOnCPU(64 * 1024, DBSaveThreadFunction, ctx, 2, THREAD_PRIORITY_NORMAL, "DBSaveCharacter")); -#endif - return true; -} - -bool AsyncDBStorage::DBQueue(RString baseURL, RString playerUID, RString request) -{ - SaveThreadContext *ctx = new SaveThreadContext(); - ctx->AddRef(); // player can disconnect while Thread still need access to its context - - ctx->_url = baseURL; - ctx->_uid = playerUID; - ctx->_request = request; - ctx->_prevContext = _lastContext; - _lastContext = ctx; -#if USE_MT_LIB_FOR_JOBS - ctx->_thread.Init(CreateMTThreadOnCPU(64 * 1024, DBQueueThreadFunction, ctx, 2, MultiThread::ThreadBase::PriorityNormal, "DBQueueCharacter")); -#else - ctx->_thread.Init(CreateThreadOnCPU(64 * 1024, DBQueueThreadFunction, ctx, 2, THREAD_PRIORITY_NORMAL, "DBQueueCharacter")); -#endif - return true; -} - -bool AsyncDBStorage::DBKill(RString baseURL, RString playerUID) -{ - SaveThreadContext *ctx = new SaveThreadContext(); - ctx->AddRef(); // player can disconnect while Thread still need access to its context - - ctx->_url = baseURL; - ctx->_uid = playerUID; - ctx->_request = ""; - ctx->_prevContext = _lastContext; - _lastContext = ctx; -#if USE_MT_LIB_FOR_JOBS - ctx->_thread.Init(CreateMTThreadOnCPU(64 * 1024, DBKillThreadFunction, ctx, 2, MultiThread::ThreadBase::PriorityNormal, "DBKillCharacter")); -#else - ctx->_thread.Init(CreateThreadOnCPU(64 * 1024, DBKillThreadFunction, ctx, 2, THREAD_PRIORITY_NORMAL, "DBKillCharacter")); -#endif - return true; -} - -bool AsyncDBStorage::DBItemDrop(RString baseURL, RString request) -{ - SaveThreadContext *ctx = new SaveThreadContext(); - ctx->AddRef(); // player can disconnect while Thread still need access to its context - - ctx->_url = baseURL; - ctx->_request = request; - ctx->_prevContext = _lastContext; - _lastContext = ctx; -#if USE_MT_LIB_FOR_JOBS - ctx->_thread.Init(CreateMTThreadOnCPU(64 * 1024, DBItemDropThreadFunction, ctx, 2, MultiThread::ThreadBase::PriorityNormal, "DBItemDrop")); -#else - ctx->_thread.Init(CreateThreadOnCPU(64 * 1024, DBItemDropThreadFunction, ctx, 2, THREAD_PRIORITY_NORMAL, "DBItemDrop")); -#endif - return true; -} - - -DWORD WINAPI AsyncDBStorage::DBLoadThreadFunction(void *ctx) -{ - Ref context = (LoadThreadContext *)ctx; - context->DecRef(); - - // wait until previous save requests end - Ref prev = context->_prevContext; - if (prev) - { - prev->_thread.Wait(); - context->_prevContext = NULL; // no longer needed - } - - RString uidQuery = Format("?uid=%s", cc_cast(context->_playerUID)); - context->_err = GetResponse(EHTTPREQ_GET,context->_result,context->_url,uidQuery,NULL); - - return 0; -} - -void AsyncDBStorage::DBCheckLoaded() -{ - for (int i=0; i<_loadContexts.Size();) - { - LoadThreadContext *ctx = _loadContexts[i]; - if (!ctx->_thread.TryWait()) - { - // thread is still running - i++; continue; - } - // thread finished, handle results - Person *person = NULL; - if (ctx->_err >= 400) - { - LogF("dbServerLoadCharacter: HTTP Error %d", ctx->_err); - LogF(ctx->_result); - } - else - { - JSONDocument document; - document.Parse(ctx->_result); - - if (document.Empty()) - { - LogF("dbServerLoadCharacter: document not parsed"); - LogF(ctx->_result); - } - else - { - JSONValue &value = document["model"]; - if (!value.IsString()) - { - LogF("dbServerLoadCharacter: model not found"); - LogF(ctx->_result); - } - else - { - RString model = value.GetString(); - - // simplified vehicle creation - Ref veh = GWorld->NewNonAIVehicleWithID(model, RString()); - person = dyn_cast(veh.GetRef()); - if (!person) - { - LogF("dbServerLoadCharacter: cannot create character of type %s", cc_cast(model)); - LogF(ctx->_result); - } - else - { - if (!person->JSONLoad(document)) - { - LogF("dbServerLoadCharacter: cannot load state of character", cc_cast(model)); - LogF(ctx->_result); - person = NULL; - } - else - { - GWorld->AddVehicle(person); - GetNetworkManager().CreateVehicle(person, VLTVehicle, "", -1); - person->Init(person->FutureVisualState().Transform(), true); - - person->UpdateSubobjects(); - GetNetworkManager().UpdateObject(person); - } - } - } - } - } - - // execute the "handler" - GameDataCode *code = ctx->_code; - if (code && code->IsCompiled() && code->GetCode().Size() > 0) - { - GameState *state = GWorld->GetGameState(); - if (state) - { - GameVarSpace vars(false); - int gshandle = state->BeginContext(&vars); - - state->VarSetLocal("_id", (float)ctx->_playerId, true); - state->VarSetLocal("_uid", ctx->_playerUID, true); - state->VarSetLocal("_name", ctx->_name, true); - state->VarSetLocal("_agent", GameValueExt(person), true); - state->Evaluate(code->GetString(), code->GetCode(), GameState::EvalContext::_default, GWorld->GetMissionNamespace()); // mission namespace - - state->EndContext(gshandle); - } - } - - _loadContexts.Delete(i); - } -} - -void AsyncDBStorage::DBLoad(RString baseURL, int playerId, RString playerUID, RString name, GameDataCode *code) -{ - Ref ctx = new LoadThreadContext(); - ctx->AddRef(); // player can disconnect while Thread still need access to its context - - ctx->_url = baseURL; - - ctx->_prevContext = _lastContext; - ctx->_code = code; - ctx->_playerId = playerId; - // Keep the raw UID for the SQF completion handler; only the HTTP request - // should receive the ?uid= query-string wrapper. - ctx->_playerUID = playerUID; - ctx->_name = name; - -#if USE_MT_LIB_FOR_JOBS - ctx->_thread.Init(CreateMTThreadOnCPU(64 * 1024, DBLoadThreadFunction, ctx.GetRef(), 2, MultiThread::ThreadBase::PriorityNormal, "DBLoadCharacter")); -#else - ctx->_thread.Init(CreateThreadOnCPU(64 * 1024, DBLoadThreadFunction, ctx.GetRef(), 2, THREAD_PRIORITY_NORMAL, "DBLoadCharacter")); -#endif - _loadContexts.Add(ctx); -} - -bool NetworkPlayerInfo::ClientStateBusy() -{ - if ( (clientState>=NCSPlayerAssigned) && (clientState logs; - NetworkId key; -}; -TypeIsMovable(NetworkIdJournal) - -template <> -struct MapClassTraits: public DefMapClassTraits -{ - /// key type - typedef const NetworkId &KeyType; - typedef NetworkIdJournal Type; - /// calculate hash value - static unsigned int CalculateHashValue(KeyType key) - { - return 32768*key.creator.CreatorInt()+key.id; - } - - /// compare keys, implementation needs only ZERO when equals - static int CmpKey(KeyType k1, KeyType k2) - { - return k1!=k2; - } - - /// get a key for given a item - static KeyType GetKey(const Type &item) {return item.key;} -}; - -class ObjectsLifeJournal -{ - static const int MaxObjectsLifeJournalCount = 10000; //max count of stored entries - AutoArray _networkIdList; - int lastIndex; //when journal is full, we overwrite old values in circular manner - MapStringToClass > _objEventMap; - - public: - ObjectsLifeJournal():lastIndex(0) {}; - void Add(NetworkId id, RString eventStory); - const AutoArray* Get(NetworkId id) const; - void Clear() - { - _networkIdList.Clear(); - _objEventMap.Clear(); - lastIndex = 0; - } -}; - -void ObjectsLifeJournal::Add(NetworkId id, RString eventStory) -{ - NetworkIdJournal &objectJournal = _objEventMap.Set(id); - if (_objEventMap.IsNull(objectJournal)) - { - // new item - NetworkIdJournal newJournal; newJournal.key=id; newJournal.logs.Add(eventStory); - _objEventMap.Add(newJournal); - if (_networkIdList.Size() < MaxObjectsLifeJournalCount) - lastIndex = _networkIdList.Add(); - else - { - lastIndex = (lastIndex+1) % MaxObjectsLifeJournalCount; - _objEventMap.Remove(_networkIdList[lastIndex]); - } - _networkIdList[lastIndex] = id; - } - else objectJournal.logs.Add(eventStory); -} - -const AutoArray* ObjectsLifeJournal::Get(NetworkId id) const -{ - const NetworkIdJournal &log = _objEventMap.Get(id); - if (_objEventMap.NotNull(log)) - { - return &log.logs; - } - return NULL; -} - -ObjectsLifeJournal GObjLifeJournal; -#endif - -#define EXTRACT_ID(name) objectId = message->_##name; -#define EXTRACT_UNITS units = message->_units; -#define EXTRACT_CHANNEL channel = message->_channel; - -DEFINE_FAST_ALLOCATOR(DelayedMessageInfo) - -DelayedMessageInfo::DelayedMessageInfo(NetworkServer *server, NetworkMessageType t, NetworkMessage *m) -:msg(m),type(t) -{ - error=1; - invMaxAge = 1.0f/10; - timeReceived = Glob.time; - switch (type) - { - case NMTFireWeapon: - { - NetworkMessageFireWeapon *msg = static_cast(m); - static float visibleErrorCoef = 2.0f; - error = msg->_visible*visibleErrorCoef; - pos = msg->_pos; // TODO: remove _pos from the message, use server->GetObjectPosition - invMaxAge = 1.0f/5; - break; - } - case NMTExplosionDamageEffects: - { - NetworkMessageExplosionDamageEffects *msg = static_cast(m); - invMaxAge = 1.0f/20; - - // undefined camera position - pos = msg->_pos; - // if ammo type is not defined, assume some default importance - error = 1; - if (msg->_type.GetLength() > 0) - { - Ref type = VehicleTypes.New(msg->_type); - AmmoType *ammo = dynamic_cast(type.GetRef()); - if (ammo) - { - // cf. Landscape::ExplosionDamageEffects - static float smallExplosionError = 3.0f; - static float bigExplosionError = 10.0f; - float smallError = smallExplosionError; - float bigError = ammo->explosive*ammo->indirectHitRange*bigExplosionError; - error = Lerp(smallError,bigError,ammo->explosive); - } - } - break; - } - case NMTRemoveProjectileDecals: - case NMTProjectileDecal: - case NMTBowState: - { - //what should happen here? - //NetworkMessageProjectileDecal *msg = static_cast(m); - break; - } - case NMTAskForPlayerAction: - { - auto *msg = static_cast(m); - static float visibleErrorCoefAction = 0.7f; - error = visibleErrorCoefAction; - // check player position - pos = server->GetObjectPosition(msg->_person); - invMaxAge = 1.0f/5; - break; - } - default: - Fail("Unexpected message type in DelayedMessageInfo"); - } -} - -DEFINE_FAST_ALLOCATOR(WaitingMessageInfo) - -/// check if new message is overriding the old one -template -inline bool InitMessageIsOverride(const NetworkMessage *msgOld, NetworkMessage *msgNew, Ref &newInitMsg) -{ - // by default assume it is not - return false; -} - -template <> -inline bool InitMessageIsOverride(const NetworkMessage *msgOld, NetworkMessage *msgNew, Ref &newInitMsg) -{ - // we need to process the messages as they are stored on the server - const NetworkMessageAskForAnimationPhase *mOld = static_cast(msgOld); - const NetworkMessageAskForAnimationPhase *mNew = static_cast(msgNew); - return mOld->_vehicle==mNew->_vehicle && mOld->_animation==mNew->_animation; -}; - -template <> -inline bool InitMessageIsOverride(const NetworkMessage *msgOld, NetworkMessage *msgNew, Ref &newInitMsg) -{ - // we need to process the messages as they are stored on the server - const NetworkMessageCreateRadioChannel *mOld = static_cast(msgOld); - const NetworkMessageCreateRadioChannel *mNew = static_cast(msgNew); - return (mOld->_channel==mNew->_channel); -}; - -template <> -inline bool InitMessageIsOverride(const NetworkMessage *msgOld, NetworkMessage *msgNew, Ref &newInitMsg) -{ - // we need to process the messages as they are stored on the server - const NetworkMessageCreateRadioChannel *mOld = static_cast(msgOld); - const NetworkMessageCreateRadioChannel *mNew = static_cast(msgNew); - return (mOld->_channel==mNew->_channel); -}; - -template <> -inline bool InitMessageIsOverride(const NetworkMessage *msgOld, NetworkMessage *msgNew, Ref &newInitMsg) -{ - // we need to process the messages as they are stored on the server - const NetworkMessageCreateRadioChannel *mOld = static_cast(msgOld); - const NetworkMessageCreateRadioChannel *mNew = static_cast(msgNew); - return (mOld->_channel==mNew->_channel); -}; - -template <> -inline bool InitMessageIsOverride(const NetworkMessage *msgOld, NetworkMessage *msgNew, Ref &newInitMsg) -{ - // we need to process the messages as they are stored on the server - const NetworkMessageCreateRadioChannel *mOld = static_cast(msgOld); - const NetworkMessageCreateRadioChannel *mNew = static_cast(msgNew); - return (mOld->_channel==mNew->_channel); -}; - -template -inline bool InitMessageCanOverride(NetworkMessageType oldType, const NetworkMessage *msgOld, NetworkMessage *msgNew, Ref &newInitMsg) -{ - return false; -}; - -static bool InitMessageIsOverride( - NetworkMessageType oldType, const NetworkMessage *msgOld, NetworkMessageType newType, NetworkMessage *msgNew, Ref &newInitMsg -) -{ - if (oldType==newType) - { - switch (oldType) - { - #define NMT_TYPE_CASE_IS_OVERRIDE(macro, class, name, description, group) \ - case NMT##name: return InitMessageIsOverride(msgOld,msgNew, newInitMsg); - // generate cases for all message types - NETWORK_MESSAGE_TYPES(NMT_TYPE_CASE_IS_OVERRIDE); - } - return false; - } - else - { - switch (newType) - { - #define NMT_TYPE_CASE_CAN_OVERRIDE(macro, class, name, description, group) \ - case NMT##name: return InitMessageCanOverride(oldType,msgOld,msgNew,newInitMsg); - // generate cases for all message types - NETWORK_MESSAGE_TYPES(NMT_TYPE_CASE_CAN_OVERRIDE); - } - } - return false; -} - - -/*! -\patch 5161 Date 5/31/2007 by Ondra -- Optimized: Reduced amount of data transferred when JIP into a complex and long running mission. -*/ - -void NetworkServer::AddInitAndRemoveOverridden( - NetworkMessageType type, NetworkMessage * msg, int **updateI -) -{ - int dst,src; - Ref newInitMsg = msg; - for (src=dst=0; src<_initMessages.Size(); ) - { - if (InitMessageIsOverride(_initMessages[src].type,_initMessages[src].msg,type,msg,newInitMsg)) - { - if (updateI) - { - // if deleting before any of updateI, we need to update the value - for (int **ii=updateI; *ii; ii++) - { - if (src<=**ii) --**ii; - } - } - // skip the message, it is obsolete now - src++; - } - else - { - if (src!=dst) _initMessages[dst] = _initMessages[src]; - src++, dst++; - } - } - // if anything was deleted, remove it now - _initMessages.Resize(dst); - if (newInitMsg) - { - // add the new message - //CheckInitMessages(_initMessages, "before _initMessages.Add()"); - int index = _initMessages.Add(); - _initMessages[index].msg = newInitMsg; - _initMessages[index].type = type; - } - //CheckInitMessages(_initMessages, "after _initMessages.Add()"); -} - -/// check if new message is overriding the old one -template -inline bool InitMessageIsDeleted(const NetworkMessage *msg, NetworkId obj) -{ - // by default assume it is not - return false; -} - -static bool InitMessageIsDeleted(NetworkMessageType type, const NetworkMessage *msg, NetworkId obj) -{ - switch (type) - { - #define NMT_TYPE_CASE_IS_DELETED(macro, class, name, description, group) \ - case NMT##name: return InitMessageIsDeleted(msg,obj);break; - // generate cases for all message types - NETWORK_MESSAGE_TYPES(NMT_TYPE_CASE_IS_DELETED); - } - return false; -} - -void NetworkServer::RemoveInitObjectDeleted(NetworkId obj) -{ - int dst,src; - for (src=dst=0; src<_initMessages.Size(); ) - { - if (InitMessageIsDeleted(_initMessages[src].type,_initMessages[src].msg,obj)) - { - // skip the message, it is obsolete now - src++; - } - else - { - if (src!=dst) _initMessages[dst] = _initMessages[src]; - src++, dst++; - } - } - // if anything was deleted, remove it now - _initMessages.Resize(dst); -} - -void NetworkServer::RptFObjectIdJournal(const NetworkId &id) -{ - if (NetworkDeletedObjectInfo *delInfo = _deletedObjects.get(id)) - { - RptF(" - object was deleted, owner %d, time %.3f", delInfo->owner, delInfo->time.toFloat()); - } -#if DIAG_MP_OBJECT_LIFE - if (const AutoArray *logLines = GObjLifeJournal.Get(id)) - { - for (int i=0; iSize(); i++) - { - RptF(" -> %s", cc_cast((*logLines)[i])); - } - } -#endif -} - -void NetworkServer::RptFObjectNotFound(const NetworkId &id, const char *msg, int from) -{ - if (_serverState==NSSLoadingGame || _serverState==NSSPlaying) - { -// RString fromTxt = from>=0 ? Format(" from=%d",from) : RString(); -// RptF("Server: Object %d:%" OID_FORMAT" not found (message %s)%s", id.creator.CreatorInt(), id.id, msg, cc_cast(fromTxt)); - RptFObjectIdJournal(id); -#if DIAG_MP_OBJECT_LIFE - DiagObjectInfoAskMessage ask; - ask._creator=id.creator; - ask._id=id.id; - if (from!=-1) - SendMsg(from, &ask, NMFGuaranteed); - if (from!=BOT_CLIENT) - SendMsg(BOT_CLIENT, &ask, NMFGuaranteed); -#endif - } -} - -void NetworkServer::RptFObjectNotFound(const NetworkId &id, NetworkMessageType type, int from, const char *context) -{ -#if _ENABLE_CHEATS - extern const char *NetworkMessageTypeNames[]; - const char *typeName = NetworkMessageTypeNames[type]; - const char *msg = typeName; -#else - BString<128> typeName; - sprintf(typeName,"Type_%d",type); - const char *msg = typeName; -#endif - BString<256> temp; - if (context) - { - strcpy(temp,typeName); - strcat(temp,context); - msg = temp; - } - RptFObjectNotFound(id,msg,from); -} - -bool CollectedHashes::UpdatePlayerBankCount(int bankCount) -{ - if (banksCount==-1) - { // not set yet - banksCount = bankCount; - bankInfoTimeout = 0; //reset - } - else if (banksCount != bankCount) - { - // player sent different bankCount to her prior info => cheating? - return true; - } - int sigCount = SignaturesCount(); - if (sigCount && sigCount!=bankCount) - { - // player sent different bankCount than was checked during initial signature test => cheating? - return true; - } - return false; -} - -void NetworkServer::ReportWrongSignatures(int from, RString filename, const NetworkPlayerInfo *info, RString report) -{ -#if _ENABLE_DEDICATED_SERVER - LogF("Hacked Signatures?"); - RString reportBase = Format(LocalizeString(IDS_SIGNATURE_WRONG), cc_cast(info->name), cc_cast(filename)); -#if DEBUG_SIGNATURES - if (report.IsEmpty()) - { - NetLog(reportBase); - } - else - { - RString reportMsg = Format("%s (%s)", cc_cast(reportBase), cc_cast(report)); //add additional report info - NetLog(reportMsg); - } -#endif - ServerMessage(reportBase); // report only basic info, diag details are in NetLog -#endif - OnHackedData(HTHackedData, from, filename); -}; - -#if _ENABLE_DEDICATED_SERVER -void NetworkServer::DoReassignDirect() -{ - // send to clients - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.clientState < NCSConnected) continue; - SendMissionInfo(info.dpid, true); - } - - SetServerState(NSSAssigningPlayers); - - _restart = false; - _reassign = false; -} - -void NetworkServer::DoReassign() -{ - _restart = true; - _reassign = true; - if (_serverState != NSSPlaying) - { - GNetworkManager.DestroyAllObjects(); - DoReassignDirect(); - } -} - -void NetworkServer::DoMissions(bool admin) -{ - _mission = "?"; - _restart = true; - if (_serverState != NSSSelectingMission && _serverState != NSSPlaying) - { - GNetworkManager.DestroyAllObjects(); - SetServerState(NSSSelectingMission); - } - NetworkCommandMessage answer; - answer._type = NCMTVoteMission; - NetworkCommandMessage answer2; - answer2._type = NCMTVoteMissionExt; - AddMissionList(answer,answer2); - if (admin) - { - SendMsg(_gameMaster, &answer, NMFGuaranteed); - SendMsg(_gameMaster, &answer2, NMFGuaranteed); - } - else - { - for (int i=0; i<_identities.Size(); i++) - { - SendMsg(_identities[i].dpnid, &answer, NMFGuaranteed); - SendMsg(_identities[i].dpnid, &answer2, NMFGuaranteed); - } - } -} -#endif - -void NetworkServer::SpawnForPlayer(int dpnid, GameDataCode *code, const GameValue &args) -{ - if (dpnid == BOT_CLIENT) - { - ScriptVM *script = new ScriptVM(ScriptVMDirect, *code, args, GWorld->GetGameState()->GetGlobalVariables()); - GWorld->AddScriptVM(script, false); - } - else - { - SpawnForPlayerMessage msg; - msg._code = code->GetString(); - - if (!args.GetNil()) - { - QOStrStream out; - if (WriteValue(args, out)) - { - int size = out.pcount(); - msg._value.Resize(size); - memcpy(msg._value.Data(), out.str(), size); - } - } - - SendMsg(dpnid, &msg, NMFGuaranteed); - } -} - -static int BestAddress(int &portRet, const NetworkPlayerInfo *info, int NetworkPlayerInfo::*addr, int NetworkPlayerInfo::*port) -{ - if (info->*addr!=0 && info->*port!=0) - { - portRet = info->*port; - return info->*addr; - } - else if (info->_publicAddr && info->_publicPort) - { - portRet = info->_publicPort; - return info->_publicAddr; - } - else - { - portRet = info->_privatePort; - return info->_privateAddr; - } -} - -/*! -\patch_internal 1.01 Date 6/22/2001 by Ondra. -- Added: ID==0 refusal -\patch 1.02 Date 7/12/2001 by Jirka: - - Fixed: error in assignment - - allow player assignment only in appropriate state - - ignore messages arrived after state has changed -\patch_internal 1.03 Date 7/13/2001 by Jirka. -- Fixed: Allow \ in url of squad (for debugging purposes) -\patch_internal 1.14 Date 8/9/2001 by Ondra. -- Added: ID>110000000 || ID>10000000 && ID<100000000 refusal -\patch 1.21 Date 8/24/2001 by Jirka: -- Fixed: error in assignment -\patch 1.25 Date 9/29/2001 by Ondra: -- New: Ping to all clients displayed on server. -\patch 1.27 Date 10/15/2001 by Jirka -- Fixed: When CAPS LOCK was pressed, Voice Over Net was not disabled (bug since 1.26) -\patch 1.30 Date 11/01/2001 by Jirka -- Fixed: Voting is echoed to clients -\patch 1.33 Date 11/29/2001 by Jirka -- Improved: Global ban list reloads before player is checked -\patch_internal 1.43 Date 1/31/2002 by Jirka -- Fixed: Server does not send create and update messages to nonplaying clients -\patch 1.82 Date 8/19/2002 by Ondra -- Fixed: Voting is echoed even to the player voting. -\patch 1.86 Date 10/16/2002 by Jirka -- Fixed: On dedicated server with mission rotating, after #login and #missions no missions appears -\patch 5136 Date 2/28/2007 by Jirka -- Fixed: MP - command #exec allowed only for logged (not voted) admin -\patch 5137 Date 3/5/2007 by Jirka -- Fixed: Dedicated server - after #reassign two players could control a single avatar -\patch 5154 Date 5/3/2007 by Jirka -- Fixed: Dedicated server - ban.txt was locked for edit during the game -\patch 5164 Date 10/3/2007 by Jirka -- Fixed: Handling of duplicate CD key improved -\patch 5175 Date 10/16/2007 by Jirka -- Added: After 3 wrong attempts to log in as an admin further attempts are ignored for some time -*/ - -void NetworkServer::OnMessage(int from, NetworkMessage *msg, NetworkMessageType type) -{ -#if _ENABLE_PERFLOG - PROFILE_SCOPE_EX(OnMsg,*); - if (PROFILE_SCOPE_NAME(OnMsg).IsActive()) - { - PROFILE_SCOPE_NAME(OnMsg).AddMoreInfo(Format("type=%d", type)); - } -#endif - - NetworkMessageFormatBase *format = GetFormat(/*from, */type); - if (!format) - { - RptF("Server: Bad message %d(%s) format", (int)type, cc_cast(GetMsgTypeName(type))); - return; - } - NetworkMessageContext ctx(msg, this, from, MSG_RECEIVE); - - #if _ENABLE_CHEATS - int level = GetDiagLevel(type,from!=_parent->GetClient()->GetPlayer()); - if (level >= 2) - { - DiagLogF("Server: received message %s from %d", cc_cast(GetMsgTypeName(type)), from); - ctx.LogMessage(format, level, "\t"); - } - #endif - - NetworkId objectId; - AutoArray units; - int channel = -1; - - bool initMessageAlreadyAdded = false; - switch (type) - { -/* - case NMTMsgFormat: - { - NetworkPlayerInfo *info = GetPlayerInfo(from); - if (!info) info = OnPlayerCreate(from, ""); - int index = msg->id.id - NMTFirstVariant; - if (index >= info->formats.Size()) - info->formats.Resize(index + 1); - info->formats[index].TransferMsg(ctx); - } - break; -*/ - case NMTSelectPlayer: - { -LogF("Server: received SelectPlayer"); - SelectPlayerMessage pl; - pl.TransferMsg(ctx); - Assert(pl._player != AI_PLAYER); - NetworkId person(pl._creator, pl._id); - - NetworkPlayerInfo *info = GetPlayerInfo(pl._player); - if (info) - { - info->person = person; - info->cameraPosition = pl._position; - // HOTFIX: msg->time cannot be used as NMTSelectPlayer is sent by BOT_CLIENT which time can be different - // using Time(0) forces first update from client to set it properly according to clients time - info->cameraPositionTime = Time(0); -#if _VBS3 - info->cameraFov = 0.75; - info->cameraDirection = VForward; -#endif - } - - // first select player, then change owner - // (when changeOwner arrive to client, player must be already known - // - for respawn parameters initialization) - if (from != pl._player) - { -LogF(" sending to %x", pl._player); - SendMsg(pl._player, msg, type, NMFGuaranteed, NULL); - } - - NetworkObjectInfo *oInfo = GetObjectInfo(person); - if (oInfo) - { - ChangeOwner(person, oInfo->owner, pl._player); - } - } - break; - case NMTAskMissionFile: - { - AskMissionFileMessage ask; - ask.TransferMsg(ctx); - if (ask._valid) - { - NetworkPlayerInfo *info = GetPlayerInfo(from); - if (info) info->missionFileValid = true; - } - } - break; - case NMTClientState: - { - ClientStateMessage cs; - cs.TransferMsg(ctx); - OnClientStateChanged(from, (NetworkClientState)cs._clientState); - } - break; - case NMTPlayerClientState: - { - PlayerClientStateMessage pcs; - pcs.TransferMsg(ctx); - SetClientState(pcs._dpnid, (NetworkClientState)pcs._clientState); - } - break; - case NMTLogin: - { - //{ CHANGED - PlayerIdentity identity; - identity.TransferMsg(ctx); - -/* - int index = _identities.Add(); - PlayerIdentity &identity = _identities[index]; - identity.TransferMsg(ctx); -*/ - //} - - // check if not in ban lists - if (from != BOT_CLIENT) - { - // reload ban list - LoadBanList("ban.txt", _banListGlobal); - GFileServerFunctions->FlushReadHandle("ban.txt"); - - bool ban = false; - for (int i=0; i<_banListGlobal.Size(); i++) - if (IsUserIdMatch(identity.id,_banListGlobal[i])) {ban = true; break;} - if (!ban) for (int i=0; i<_banListLocal.Size(); i++) - if (IsUserIdMatch(identity.id,_banListLocal[i])) {ban = true; break;} - if (ban) - { - //{ CHANGED - // _identities.Delete(index); - //} - KickOff(from,KORBan); - break; - } - } - - _squadChecks.Add(new CheckSquadObject(identity, _proxy, this)); - -#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.dpid != from) continue; - info._steamValidate.Start(identity, this); - break; - } -#endif - - //} - - // send server time to player just connected - ServerTimeMessage stmsg; - _serverTime = ::GetTickCount()-_serverTimeInitTickCount; // update _serverTime - stmsg._time = _serverTime; - stmsg._endTime = _serverTimeOfEstimatedEnd; - SendMsg(from, &stmsg, NMFGuaranteed | NMFHighPriority); - -#if _ENABLE_DEDICATED_SERVER - // client need to know whether there is admin on server - ServerAdminMessage samsg; - samsg._admin = _admin; - samsg._gameMaster = _gameMaster; - SendMsg(from, &samsg, NMFGuaranteed); -#endif - } - break; - case NMTCustomFilesWanted: - { - CustomFilesWantedMessage filesWantedMsg; - filesWantedMsg.TransferMsg(ctx); - for (int i=0; i<_squadChecks.Size(); i++) - { - if (_squadChecks[i]->IsPlayer(filesWantedMsg._player)) - { - _squadChecks[i]->SetCustomFilesWanted(from, filesWantedMsg._filesWanted); - break; - } - } - } - break; - case NMTUpdateClientInput: - OnMessageClientInput(from, type, ctx); - break; - case NMTAskForAnimationPhase: - { - PREPARE_TRANSFER(AskForAnimationPhase) - EXTRACT_ID(vehicle) - if (!objectId.IsNull()) - { - if (objectId.creator == CreatorId(STATIC_OBJECT)) - { - // save message for lately connecting players - AddInitAndRemoveOverridden(type,msg); - - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.dpid == from) continue; - if (info.clientState != NCSPlaying) continue; - SendMsg(info.dpid, msg, type, NMFNone, NULL); - } - } - else - { - SendMsg(BOT_CLIENT, msg, type, NMFGuaranteed, NULL); - } - } - } - break; - case NMTAskForPilotLight: - { - PREPARE_TRANSFER(AskForPilotLight) - EXTRACT_ID(vehicle) - } - goto LabelAskWithVehicle; - case NMTAskForVehicleDoorState: - { - PREPARE_TRANSFER(AskForVehicleDoorState) - EXTRACT_ID(vehicle) - } - goto LabelAskWithVehicle; - case NMTAskForSetMagazineAmmo: - { - PREPARE_TRANSFER(AskForSetMagazineAmmo) - EXTRACT_ID(magazine) - } - goto LabelAskWithVehicle; - case NMTAskForAmmo: - { - PREPARE_TRANSFER(AskForAmmo) - EXTRACT_ID(turret) - if (objectId.IsNull()) - { - EXTRACT_ID(vehicle) - } - } - goto LabelAskWithVehicle; - case NMTAskForMoveVector: - { - if (from!=BOT_CLIENT) break; // AskForMove is honored from the bot-client only - PREPARE_TRANSFER(AskForMoveVector) - EXTRACT_ID(vehicle) - } - goto LabelAskWithVehicle; - case NMTAskForMoveMatrix: - { - if (from!=BOT_CLIENT) break; // AskForMove is honored from the bot-client only - PREPARE_TRANSFER(AskForMoveMatrix) - EXTRACT_ID(vehicle) -#if _ENABLE_PHYSICS - //ConsoleF("askformove vehicle %x", _parent->GetObject(message->_vehicle)); -#endif - } - goto LabelAskWithVehicle; -#if _VBS3 - case NMTAskCommanderOverride: - { - PREPARE_TRANSFER(AskCommanderOverride) - EXTRACT_ID(turret) - } - - goto LabelAskWithVehicle; -#endif - LabelAskWithVehicle: - { - NetworkObjectInfo *info = GetObjectInfo(objectId); - if (info) - { - if (info->pendingOwner != NO_CLIENT) - { - WaitingMessageInfo *waitingMsg = new WaitingMessageInfo(type,msg); - info->waitingMessages.Add(waitingMsg); - } - else - { - SendMsg(info->owner, msg, type, NMFGuaranteed, NULL); - } - } - else - { - RptFObjectNotFound(objectId, type,from); - } - } - break; - case NMTForceDeleteObject: - { - // remove from object lists - PREPARE_TRANSFER(ForceDeleteObject) - NetworkId id; - if (TRANSF_GET_ID_BASE(object, id) != TMOK) break; - PerformObjectDestroy(id); - - // send to other clients - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.dpid == from) continue; - if (info.clientState < NCSMissionReceived) continue; - SendMsg(info.dpid, msg, type, NMFGuaranteed, NULL); - } - } - break; - case NMTAskForRotateInventoryItem: - { - AskForRotateInventoryItemMessage ask; - TMError err = ask.TransferMsg(ctx); - if ((err == TMOK || err == TMNotFound) && ask._person && ask._item && - ask._person->GetRemotePlayer() == from && ask._person->FindItem(ask._item)) - SendMsg(BOT_CLIENT, msg, type, NMFGuaranteed); - } - break; - case NMTAskForSetItemShortcut: - case NMTAskForMoveItem: - case NMTAskForTakeItemToHands: - case NMTAskForSwapItems: - SendMsg(BOT_CLIENT, msg, type, NMFGuaranteed); - break; - case NMTAskForRotateInventoryItem: - { - AskForRotateInventoryItemMessage ask; - TMError err = ask.TransferMsg(ctx); - if ((err == TMOK || err == TMNotFound) && ask._person && ask._item && - ask._person->GetRemotePlayer() == from && ask._person->FindItem(ask._item)) - SendMsg(BOT_CLIENT, msg, type, NMFGuaranteed); - } - break; - case NMTAskInventoryMenu: - { - PREPARE_TRANSFER(AskInventoryMenu) - Person *person = dyn_cast(_parent->GetObject(message->_unit)); - InventoryItem *item1 = dyn_cast(_parent->GetObject(message->_item1)); - if (person && person->Brain() && item1) - { - Ref reply = new NetworkMessageInventoryMenu(); - reply->_unit = message->_unit; - reply->_item1 = message->_item1; - reply->_item2 = message->_item2; - reply->_swap = false; - - if (message->_item2.IsNull()) - { - // single item - - // actions - item1->GetActions( - [&reply](const UIAction &action) -> void - { - if (action.action.NotNull()) - { - NetworkMessageInventoryMenuAction *submsg = new NetworkMessageInventoryMenuAction(); - submsg->_actionType = action.action->GetType(); - submsg->_actionTarget = action.action->GetTarget() ? - action.action->GetTarget()->GetNetworkId() : NetworkId::Null(); - - QOStrStream out; - action.action->SaveParams(out); - int size = out.pcount(); - submsg->_actionParams.Resize(size); - memcpy(submsg->_actionParams.Data(), out.str(), size); - - reply->_actions.Add(submsg); - } - }, - person->Brain()); - } - else - { - // two items - InventoryItem *item2 = dyn_cast(_parent->GetObject(message->_item2)); - if (!item2) break; // recipes on two items are expected - - // recipes - Recipes.Collect(person, item1, item2, - [&reply](const Recipe *recipe) -> bool - { - reply->_recipes.Add(recipe->_name); - return false; // continue - }); - - if (item2->CanAddAttachment(item1)) - { - NetworkMessageInventoryMenuAttachment *submsg = new NetworkMessageInventoryMenuAttachment(); - submsg->_attachment = true; - submsg->_item1 = item1->GetNetworkId(); - submsg->_item2 = item2->GetNetworkId(); - reply->_attachments.Add(submsg); - } - else if (item2->CanAddOwnedItem(item1)) - { - NetworkMessageInventoryMenuAttachment *submsg = new NetworkMessageInventoryMenuAttachment(); - submsg->_attachment = false; - submsg->_item1 = item1->GetNetworkId(); - submsg->_item2 = item2->GetNetworkId(); - reply->_attachments.Add(submsg); - } - - bool CanSwapItems(InventoryItem *item1, InventoryItem *item2); - reply->_swap = CanSwapItems(item1, item2); - } - - SendMsg(from, reply, NMTInventoryMenu, NMFGuaranteed); - } - } - break; - case NMTAskForThrowItem: -#if _ENABLE_PHYSICS - { - // change ownership of item to gain control over position - PREPARE_TRANSFER(AskForThrowItem) - - if (!message->_item.IsNull() && !message->_person.IsNull()) - { - NetworkObjectInfo *info = GetObjectInfo(message->_item); - - //nastavi se sice primo v klientovi, ale tam nevidim na info. takhle zabezpecim, ze mi to nikdo neprepise - if (info && info->owner != BOT_CLIENT) - ChangeOwner(message->_item, info->owner, BOT_CLIENT); - //SendMsg(BOT_CLIENT, message, type, NMFGuaranteed); - - if (info) - { - if (info->pendingOwner != NO_CLIENT) - { - WaitingMessageInfo *waitingMsg = new WaitingMessageInfo(type,msg); - info->waitingMessages.Add(waitingMsg); - } - else - { - SendMsg(info->owner, msg, type, NMFGuaranteed, NULL); - } - } - } - } -#endif - break; - case NMTAskForDropItem: - { - // change ownership of item to gain control over position - PREPARE_TRANSFER(AskForDropItem) - if (!message->_item.IsNull()) - { - const NetworkObjectInfo *info = GetObjectInfo(message->_item); - if (info && info->owner != BOT_CLIENT) - ChangeOwner(message->_item, info->owner, BOT_CLIENT); - SendMsg(BOT_CLIENT, message, type, NMFGuaranteed); - } - } - break; - case NMTProcessAction: - { - PREPARE_TRANSFER(ProcessAction) - if (!message->_unit.IsNull()) - { - Person *person = dyn_cast(_parent->GetObject(message->_unit)); - AIBrain *unit = person ? person->Brain() : nullptr; - if (unit && unit->GetVehicle()) - { - Ref action = CreateAction((UIActionType)message->_actionType); - if (action) - { - Object *target = nullptr; - const NetworkId &targetId = message->_actionTarget; - if (!targetId.IsNull()) - target = dyn_cast(_parent->GetObject(targetId)); - - // Static house/door objects are not always present in the - // server's network-object table. For a UserType action, resolve - // the player's authoritative current cursor target as fallback. - // The action's saved parameters still carry the chosen door id. - if (!target && message->_actionType == ATUserType) - target = GetPlayerTarget(from); - - if (message->_actionType == ATUserType) - RptF("ProcessAction UserType: player=%d targetId=%d:%" OID_FORMAT " resolved=%s fallback=%s", - from, targetId.creator.CreatorInt(), targetId.id, - target ? (const char *)target->GetDebugName() : "", - targetId.IsNull() ? "cursor" : "none"); - action->SetTarget(target); - - QIStrStream in(message->_actionParams.Data(), message->_actionParams.Size()); - action->LoadParams(in); - - unit->GetVehicle()->StartActionProcessing(action, unit); - } - } - } - } - break; - case NMTProcessRecipe: - { - PREPARE_TRANSFER(ProcessRecipe) - if (!message->_person.IsNull()) - { - Person *person = dyn_cast(_parent->GetObject(message->_person)); - if (person) - { - const Recipe *recipe = Recipes.Find(message->_recipe); - if (recipe) - { - InventoryItem *item1 = dyn_cast(_parent->GetObject(message->_item1)); - InventoryItem *item2 = dyn_cast(_parent->GetObject(message->_item2)); - recipe->Process(person, item1, item2); - } - } - } - } - break; - case NMTMarkerDelete: - // send to all except from (state Briefing expected) - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.dpid == from) continue; - if (info.clientState < NCSGameLoaded) continue; - SendMsg(info.dpid, msg, type, NMFGuaranteed, NULL); - } - if(type == NMTMarkerDelete) - { - PREPARE_TRANSFER(MarkerDelete) - RemoveJIPMarkerInfo(message->_name); - } - break; -#if _VBS2 //Convoy trainer - #if _EXT_CTRL - case NMTAARAskUpdate:// Here we service the ask request for AAR - { - AARAskUpdateMessage act; - act.TransferMsg(ctx); - - switch(act._type) - { - case StartRecord: - GAAR.Record(); - break; - case StopRecord: - GAAR.RecordStop(); - break; - case SaveFile: - GAAR.RecordSave(act._stringOne); - break; - case AddBookMK: - GAAR.AddBookMark(act._floatType,act._stringOne,act._stringTwo); - break; - case RemBookMK: - GAAR.RemoveBookMark(act._stringOne); - break; - case SaveState: - // Client should never ask to set save state - Assert(false); - break; - default: - Assert(false);// message type not handeled, development bug - } - } - break; - #endif - case NMTAddMPReport: - case NMTAARDoUpdate: // Here we update all clients with their new state. - case NMTPauseSimulation: -#endif - case NMTApplyWeather:// request will be sent to the bot client too - goto ProcessInitMessage; -#if _ENABLE_ATTACHED_OBJECTS - case NMTAttachObject: - case NMTDetachObject: - if (from!=BOT_CLIENT) break; -#endif - ProcessInitMessage: -#if _VBS2 || _ENABLE_ATTACHED_OBJECTS - AddInitAndRemoveOverridden(type, msg); - initMessageAlreadyAdded = true; -#endif - // save message for lately connecting players - if (!initMessageAlreadyAdded) - { - //CheckInitMessages(_initMessages, "before _initMessages.Add()"); - int index = _initMessages.Add(); - _initMessages[index].msg = msg; - _initMessages[index].type = type; - //CheckInitMessages(_initMessages, "after _initMessages.Add()"); - } - // no break here - continue - case NMTPlaySound: - case NMTSoundState: - case NMTVehicleDestroyed: - case NMTVehicleDamaged: -sendToAllPlayers: - // send to all except from (state Play expected) - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.dpid == from) continue; - if (info.clientState != NCSPlaying) continue; - SendMsg(info.dpid, msg, type, NMFGuaranteed, NULL); - } - break; - case NMTSubscribeRadios: - { - NetworkMessageSubscribeRadios *rm = dynamic_cast(msg); - if (rm) - { - for (int i=0; i<_players.Size(); i++) - { - if (_players[i]->dpid==rm->_player) - { - _radioSubscribers.AddUnique(rm->_player, rm->_frequences); - goto sendToAllPlayers; - } - } - } - } - break; - case NMTAskForPlayerAction: - // check if the person in question is the player - { - auto *msgAction = static_cast(msg); - NetworkId playerPerson = GetPlayerPerson(from); - if (playerPerson!=msgAction->_person) - { - RptF("AskForPlayerAction ignored for player %d, person different %d:%" OID_FORMAT "!=%d:%" OID_FORMAT,from, playerPerson.creator.CreatorInt(),playerPerson.id,msgAction->_person.creator.CreatorInt(),msgAction->_person.id); - } - - } - goto DelayedMessageProcessing; - case NMTFireWeapon: - case NMTExplosionDamageEffects: - case NMTBowState: - DelayedMessageProcessing: - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.dpid == from) continue; - if (info.dpid==BOT_CLIENT) - { - SendMsg(BOT_CLIENT, msg, type, NMFGuaranteed, nullptr); - continue; - } - if (info.clientState != NCSPlaying) continue; - { - DelayedMessageInfo *delayed = new DelayedMessageInfo(this,type,msg); - info._delayedMessages.Add(delayed); - } - } - break; - case NMTProjectileDecal: - case NMTRemoveProjectileDecals: - if (from != BOT_CLIENT) - { - SendMsg(BOT_CLIENT, msg, type, NMFGuaranteed, nullptr); - } - else - { - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.dpid == BOT_CLIENT || info.clientState != NCSPlaying) - { - continue; - } - - DelayedMessageInfo *delayed = new DelayedMessageInfo(this,type,msg); - info._delayedMessages.Add(delayed); - } - } - break; - case NMTExplosionDamage: - SendMsg(BOT_CLIENT, msg, type, NMFGuaranteed, nullptr); - break; - case NMTSynchronizeVariable: - if (from!=BOT_CLIENT) break; - goto SendToAll; - // continue - case NMTTransferFile: -#if _ENABLE_UNSIGNED_MISSIONS - case NMTTransferMissionFile: -#endif - case NMTMissionStats: - SendToAll: - // send to all except from (state Mission Received expected) - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.dpid == from) continue; - if (info.clientState < NCSMissionReceived) continue; - SendMsg(info.dpid, msg, type, NMFGuaranteed, NULL); - } -//CheckInitMessages(_initMessages, "after NetworkComponent::SendMsg"); - break; - case NMTSendAUMsg: - { - SendAUMsgMessage auMsg; - auMsg.TransferMsg(ctx); - GameValue value; - if (!ReadValue(value, auMsg._value.Data(), auMsg._value.Size(), _parent)) break; - const GameArrayType &array=value; - if ( array.Size() != 2 ) break; - if (array[0].GetType()==GameScalar) - { - int count = array[0]; - // send to some count of players except from (state Mission Received expected) - for (int i=0; (i<_players.Size()) && (count>0); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.dpid == from) continue; - count--; - SendMsg(info.dpid, msg, type, NMFGuaranteed, NULL); - } - } - else if (array[0].GetType()==GameArray) - { - const GameArrayType &sendTo = array[0]; - // send to all players listed in array - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.dpid == from) continue; - for (int j=0; jdestroy) - { - alreadyKicked = true; - } - - RString name; - for (int i=0; i<_players.Size(); i++) - { - if (_players[i]->dpid == from) - { - name = _players[i]->name; - if (_players[i]->kickedOff) alreadyKicked = true; - break; - } - } - - if (alreadyKicked) - { - LogF - ( - "Transfer file %s request ignored, sender is being kicked off", - (const char *)transfer._path - ); - break; - } - // check if file transferred is within allowed range - // if not, kick off sender - if (transfer._totSize>MaxCustomFileSize) - { - // check name of player (from file name) - RString reason = Format - ( - LocalizeString(IDS_DS_PLAYER_KICKED_BIG_CUSTOM_FILE), - (const char *)name,(const char *)GetRelUploadPath(transfer._path,name), - transfer._totSize,MaxCustomFileSize - ); - ServerMessage(reason); - KickOff(from,KORKick,reason); - break; - } - - if (!CheckValidUpload(transfer._path,name)) - { - RString reason = Format - ( - LocalizeString(IDS_DS_PLAYER_KICKED_INVALID_CUSTOM_FILE), - (const char *)name,(const char *)transfer._path - ); - ServerMessage(reason); - KickOff(from,KORKick, reason); - break; - } - - ReceiveFileSegment(transfer); - } - break; - case NMTDeleteObject: - if (_serverState < NSSLoadingGame) break; // updates from the last session - { - PREPARE_TRANSFER(DeleteObject) - - NetworkId id; - if (TRANSF_BASE(creator, id.creator) != TMOK) break; - if (TRANSF_BASE(id, id.id) != TMOK) break; - - // object deletion should be requested by the bot-client only - if (from!=BOT_CLIENT) - { -#if _ENABLE_PHYSICS1 - { - InventoryItem *item = dyn_cast(_parent->GetObject(id)); - if(item && item->GetPhysics()) - ConsoleF("delete dyn phys for %x user pointer %x", item, ((enf::BulletController*)item->GetPhysics())->GetCollisionObject()->getUserPointer()); - } -#endif - RptF("Object %d:%",OID_FORMAT," delete requested from client %d",id.creator.CreatorInt(),id.id,from); - break; - } - -#if DIAG_MP_OBJECT_LIFE - GObjLifeJournal.Add(id, Format("(%.3f) Delete: from=%d",Glob.time.toFloat(), from)); -#endif - OnObjectDestroy(id, from); - // RptF("Server: Object %d:%" OID_FORMAT" deleted", id.creator.CreatorInt(), id.id); - } - break; - case NMTDeletedObject: - { - if (_serverState < NSSLoadingGame) break; // updates from the last session - { - PREPARE_TRANSFER(DeletedObject) - - NetworkId id; - if (TRANSF_BASE(creator, id.creator) != TMOK) break; - if (TRANSF_BASE(id, id.id) != TMOK) break; - - _deletedObjects.removeKey(id); -#if DIAG_MP_OBJECT_LIFE - GObjLifeJournal.Add(id, Format("(%.3f) Deleted: from=%d",Glob.time.toFloat(), from)); -#endif - } - } - break; - case NMTCreateObject: - case NMTCreateVehicle: - case NMTCreateVehicleAI: - case NMTCreateVehicleBrain: - case NMTCreateShot: - case NMTCreateCrater: - case NMTCreateCraterOnVehicle: - case NMTCreateSoundOnVehicle: - case NMTCreateObjectDestructed: - case NMTCreateDynSoundSource: - case NMTCreateHelicopter: -#if _HELISIM_ROTORLIB - case NMTCreateHelicopterRTD: -#endif - case NMTCreateSeagull: - case NMTCreateTurret: - case NMTCreateDestructionEffects: - case NMTCreateClientCameraPosition: - if (_serverState < NSSLoadingGame) break; // updates from the last session - - { - PREPARE_TRANSFER(NetworkObject) - - NetworkId id; - if (TRANSF_BASE(objectCreator, id.creator) != TMOK) break; - if (TRANSF_BASE(objectId, id.id) != TMOK) break; - - if (from!=BOT_CLIENT && type!=NMTCreateClientCameraPosition) - { - RptF("Object %d:%",OID_FORMAT," create requested from client %d",id.creator.CreatorInt(),id.id,from); - break; // create message may come only from a bot-client, with the exception of the CameraPosition object - } - - // copy message (avoid changes on message in message queue) - Ref copy = ::CreateNetworkMessage(type); - CopyMsg(copy, msg, format); - NetworkObjectInfo *oInfo = OnObjectCreate(id, from, copy, type); - if (!oInfo) break; -// RptF("Server: Object %d:%" OID_FORMAT" created, type %s", id.creator.CreatorInt(), id.id, cc_cast(GetMsgTypeName(type))); - - auto sendToClient = [this,id,oInfo,from] (int i) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.dpid == from) return; - if (info.clientState < NCSMissionReceived) return; - PlayerIndex index = GetPlayerIndex(info.dpid); - DoAssert(index>=0); - if (index<0) return; - - if (info.person!=id) - { - NetworkPlayerObjectInfo *poInfo = oInfo->GetPlayerObjectInfo(index,info.dpid); - if (!poInfo->updating) - { - SendCreateMessage(info.dpid, *oInfo, poInfo); - poInfo->updating = true; - info.markAsUpdating(poInfo); - } - } - }; - - // send to bot-client first - for (int i=0; i<_players.Size(); i++) // TODO: avoid for loop, bot client is always first - { - if (_players[i]->dpid==BOT_CLIENT) {sendToClient(i);break;} - } - oInfo->object = _parent->GetClient()->GetObject(id); - DoAssert(oInfo->object); - - Entity *ent = dyn_cast(oInfo->object); - if (ent) - { - OnHierParentChange(ent); - } - - float maxDist = oInfo->BestPosition()._updateDistance; - for (int i=0; i<_players.Size(); i++) - { - int dpid = _players[i]->dpid; - if (dpid==BOT_CLIENT) continue; - if (DebugMeBoy(oInfo->id)) - { - LogF("*** DebugMeBoy: {%d:%" OID_FORMAT"} Create message for %d dist %g", oInfo->id.creator.CreatorInt(), oInfo->id.id, dpid, maxDist); - } - if (maxDist>=FLT_MAX) sendToClient(i); - } - // SendMsg created the object on the bot-client if necessary, we can get it now - - } - break; - case NMTUpdateDamageVehicleAI: - case NMTUpdateDamageVehicle: - case NMTUpdateDamageObject: - ctx.SetClass(NMCUpdateDamage); - if (BattlEyeEnabled()) - { - PREPARE_TRANSFER(UpdateDamageObject) - - NetworkId id; - float damage; - if (TRANSF_BASE(objectCreator, id.creator) != TMOK) break; - if (TRANSF_BASE(objectId, id.id) != TMOK) break; - if (TRANSF_BASE(dammage, damage) != TMOK) break; - #if _USE_BATTL_EYE_SERVER - if (_beIntegration.UpdateDamageCallback(from,NetworkIdToNetIdFriendly(id),damage)) break; - #endif - } - goto Update; - case NMTUpdatePositionVehicle: - case NMTUpdatePositionMan: - case NMTUpdatePositionTank: - case NMTUpdatePositionCar: - case NMTUpdatePositionAirplane: - case NMTUpdatePositionHelicopter: -#if _HELISIM_ROTORLIB - case NMTUpdatePositionHelicopterRTD: -#endif - case NMTUpdatePositionShip: - case NMTUpdatePositionDoor: - case NMTUpdatePositionSeagull: - case NMTUpdatePositionMotorcycle: - case NMTUpdatePositionMagazine: -#if _USE_BATTL_EYE_SERVER - if (BattlEyeEnabled()) - { - PREPARE_TRANSFER(UpdatePositionVehicle) - - NetworkId id; - Vector3 position; - Matrix3 o; - if (TRANSF_BASE(objectCreator, id.creator) != TMOK) break; - if (TRANSF_BASE(objectId, id.id) != TMOK) break; - if (TRANSF_BASE(position, position) != TMOK) break; - if (TRANSF_BASE(orientation, o) != TMOK) break; - if (_beIntegration.UpdatePositionCallback(from,NetworkIdToNetIdFriendly(id),position.X(),position.Y(),position.Z(), - o.Direction().X(),o.Direction().Y(),o.Direction().Z(), - o.DirectionUp().X(),o.DirectionUp().Y(),o.DirectionUp().Z(), - o.DirectionAside().X(),o.DirectionAside().Y(),o.DirectionAside().Z()) - ) break; - } -#endif - ctx.SetClass(NMCUpdatePosition); - goto Update; - case NMTUpdatePositionTurret: - ctx.SetClass(NMCUpdatePosition); - goto Update; - case NMTUpdateTransport: - case NMTUpdateTankOrCar: - case NMTUpdateTank: - case NMTUpdateCar: - case NMTUpdateAirplane: - case NMTUpdateHelicopter: -#if _HELISIM_ROTORLIB - case NMTUpdateHelicopterRTD: -#endif - case NMTUpdateParachute: - case NMTUpdateShip: - case NMTUpdateDoor: - case NMTUpdateSeagull: - case NMTUpdateObject: - case NMTUpdateVehicle: - case NMTUpdateFlag: - case NMTUpdateShot: - case NMTUpdateMine: - case NMTUpdateWeapon: - case NMTUpdateVehicleAI: - case NMTUpdateVehicleAIFull: - case NMTUpdateVehicleBrain: - case NMTUpdateMan: - case NMTUpdateMotorcycle: - case NMTUpdateFireplace: - case NMTUpdateTurret: - case NMTUpdateClientCameraPosition: - case NMTUpdateInventoryItem: - case NMTUpdateItemRadio: - case NMTUpdateItemTransmitter: - Update: - if (_serverState < NSSLoadingGame) break; // updates from the last session - { - PREPARE_TRANSFER(NetworkObject) - - NetworkId id; - if (TRANSF_BASE(objectCreator, id.creator) != TMOK) break; - if (TRANSF_BASE(objectId, id.id) != TMOK) break; - - if (_updatesGuaranteed && from!=BOT_CLIENT) - { - MessageDiffApply diff; - message->LoadDiff(diff); - - DoAssert(diff.IsIdentity()); - - // TODO: diff messages to the server as well (we need to store or access incoming reference message for that) - //message->ApplyDiff(refMsg,diff); - - message->ResetDiff(); - - } - - #if USER_Bebul -/* - static int doItCounter = 0; - if (!(++doItCounter % 50)) - { - DiagObjectInfoAskMessage ask; ask._creator=id.creator; ask._id=id.id; - SendMsg(from, &ask, NMFGuaranteed); - if (from!=BOT_CLIENT) - SendMsg(BOT_CLIENT, &ask, NMFGuaranteed); - } -*/ - //RptFObjectNotFound(id, type, from); - #endif - - NetworkObjectInfo *oInfo = OnObjectUpdate(id, from, msg, type, ctx.GetClass()); - if (!oInfo) break; - bool guaranteed; - if (TRANSF_BASE(guaranteed, guaranteed) != TMOK) guaranteed = false; - // if (_state < NGSPlay) - if (guaranteed) - { - // init state transfer, send immediately - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &pInfo = *_players[i]; - if (pInfo.dpid == from) continue; - if (pInfo.clientState < NCSMissionReceived) continue; - - if (oInfo->GetPlayerObjectInfo(GetPlayerIndex(pInfo.dpid),pInfo.dpid)->updating) - { - if (DebugMeBoy(id)) - { - LogF("*** DebugMeBoy: {%d:%" OID_FORMAT"} init update sent to %d", id.creator.CreatorInt(), id.id, pInfo.dpid); - } - UpdateObject(&pInfo, oInfo, ctx.GetClass(), NMFGuaranteed); - } - } - } - else if (from!=BOT_CLIENT) - { - // always send immediately to the bot-client - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &pInfo = *_players[i]; - if (pInfo.dpid != BOT_CLIENT) continue; - if (pInfo.clientState < NCSMissionReceived) continue; - - UpdateObject(&pInfo, oInfo, ctx.GetClass(), NMFGuaranteed); - break; - } - - } - if (ctx.GetClass() != NMCUpdateGeneric) break; - - // check ownership of items in cargo - { - NetworkMessageUpdateVehicleAI *msg = dynamic_cast(ctx.GetNetworkMessage()); - if (msg) CheckItemsOwner(msg, oInfo->owner); - } - if (IsUpdateTransport(type)) - { - PREPARE_TRANSFER(UpdateTransport) - - // vehicle is always simulated where driver is local - // if there is no driver, it can be simulated on any computer - NetworkId driver; - NetworkId copilot; - if (TRANSF_GET_ID_BASE(copilot, copilot) == TMOK) - { - // check for NULL id - if (!copilot.IsNull()) - { - int newOwner = FindOwner(copilot); - if (newOwner != 0) ChangeOwner(id, oInfo->owner, newOwner); - } - else if (TRANSF_GET_ID_BASE(driver, driver) == TMOK) - { - // check for NULL id - if (!driver.IsNull()) - { - int newOwner = FindOwner(driver); - if (newOwner != 0) ChangeOwner(id, oInfo->owner, newOwner); - } - } - } - } - else if (type == NMTUpdateMan) - { - // Check owner of items in slots - PREPARE_TRANSFER(UpdateVehicleBrain) - -#define CHECK_SLOT_OWNER(type, typeprefix, name) \ - { \ - const NetworkId &id = message->_slot##name; \ - if (!id.IsNull()) CheckItemOwner(id, oInfo->owner); \ - } - - INVENTORY_SLOT_ENUM(InventorySlotId, IS, CHECK_SLOT_OWNER) - } - else if (type == NMTUpdateTurret) - { - PREPARE_TRANSFER(UpdateTurret) - - // turret is always simulated where gunner is local - // if there is no gunner, it can be simulated on any computer - NetworkId gunner; -#if _VBS3 //commander override, change locality! - NetworkId overriddenByTurret; - bool override = false; - if (TRANSF_GET_ID_BASE(overriddenByTurret, overriddenByTurret) == TMOK) - { - if(!overriddenByTurret.IsNull()) - { - int newOwner = FindOwner(overriddenByTurret); - if (newOwner != 0) - { - ChangeOwner(id, oInfo->owner, newOwner); - override = true; - } - } - } - if(!override) -#endif - if (TRANSF_GET_ID_BASE(gunner, gunner) == TMOK) - { - // check for NULL id - if (!gunner.IsNull()) - { - int newOwner = FindOwner(gunner); - if (newOwner != 0) ChangeOwner(id, oInfo->owner, newOwner); - } - } - } - else if (type == NMTUpdateInventoryItem || type == NMTUpdateItemRadio || type == NMTUpdateItemRadio || type == NMTUpdateItemTransmitter || type == NMTUpdateWeapon) // update of any inventory item - { - PREPARE_TRANSFER(UpdateInventoryItem) - if (message->_inLandscape) CheckItemOwner(id, BOT_CLIENT); - } - } - break; - case NMTUpdateClientInfo: - { - ClientInfoObject clientInfo; - clientInfo.TransferMsg(ctx); - NetworkPlayerInfo *pInfo = GetPlayerInfo(from); - if (pInfo && msg->time > pInfo->cameraPositionTime) - { - pInfo->cameraPosition = clientInfo._cameraPosition; - pInfo->cameraPositionTime = msg->time; -#if _VBS3 - pInfo->cameraFov = clientInfo._cameraFov; - pInfo->cameraDirection = clientInfo._cameraDirection; -#endif - - if (_serverState < NSSLoadingGame || _serverState>NSSPlaying) break; // updates from the last session - { - PREPARE_TRANSFER(UpdateClientInfo); - - NetworkId id; - if (TRANSF_BASE(objectCreator, id.creator) != TMOK) break; - if (TRANSF_BASE(objectId, id.id) != TMOK) break; - // Client Info need to be updated on Clients only for dead players (VoN Direct Speech needs position) - if (CheckPlayerInLobby(*pInfo)) - { - // create if not created yet - OnObjectCreate(id, from, NULL, NMTNone); - - clientInfo._dpnid = from; - - Ref msg2 = ::CreateNetworkMessage(NMTUpdateClientInfoDpid); - msg2->time = Glob.time; - NetworkMessageContext ctx2(msg2, this, from, MSG_SEND); - ctx2.SetClass(NMCUpdatePosition); - - NetworkMessageUpdateClientInfoDpid *message2 = static_cast(msg2.GetRef()); - message2->_guaranteed = false; - - TMError err = clientInfo.TransferMsg(ctx2); - if (err == TMOK) - { - OnObjectUpdate(id, from, msg2, NMTUpdateClientInfoDpid, NMCUpdatePosition); - } - } - } - } - } - break; - case NMTUpdateClientInfoDpid: - Fail("Unexpected on server"); - break; - case NMTChat: - { - PREPARE_TRANSFER(Chat) - - AutoArray units; - if (TRANSF_GET_IDS_BASE(units, units) != TMOK) break; - AUTO_STATIC_ARRAY(int, players, 32); - int channel; - if (TRANSF_BASE(channel, channel) != TMOK) break; - if (channel & 0x80000000) - { - //@{ Ant1HaX0R section - NetworkPlayerInfo *info = GetPlayerInfo(from); - if (info) - { - // does the client know the level 2 signatures asks? - RString text; - if (TRANSF_BASE(text, text) != TMOK) break; - // loaded bank count hidden inside the NMTChat ... channel = ( #loaded banks xor (dpnid & 0x7fffffff) ) | 0x80000000 - int bankCount = (channel & 0x7fffffff) ^ (from & 0x7fffffff); - if (info->hashes.UpdatePlayerBankCount(bankCount)) - KickOff(info->dpid,KORKick); - } - break; - //@} - } - if ((channel != CCGlobal && channel != CCSystem) && units.Size() > 0) - GetPlayersOnChannel(players, units, from, false); - else - GetPlayersOnChannel(players, channel, from, false); - for (int i=0; i units; - if (TRANSF_GET_IDS_BASE(units, units) != TMOK) break; - AUTO_STATIC_ARRAY(int, players, 32); - int channel; - if (TRANSF_BASE(channel, channel) != TMOK) break; - if ((channel != CCGlobal && channel != CCSystem) && units.Size() > 0) - GetPlayersOnChannel(players, units, from, false); - else - GetPlayersOnChannel(players, channel, from, false); - for (int i=0; i_marker, channel, from); // saved for JIP players - } - LabelChat: - { - AUTO_STATIC_ARRAY(int, players, 32); - if (channel != CCGlobal && channel != CCSystem) //units are already extracted, so we simply send it to all units specified - GetPlayersOnChannel(players, units, from, false); - else - GetPlayersOnChannel(players, channel, from, false); - for (int i=0; icertificate.Size()>0) - { - AutoArray admins; - ConstParamEntryPtr entry = _serverCfg.FindEntry("admins"); - if (entry) - { - for (int i=0; iGetSize(); i++) - { - RString adminId = (*entry)[i]; - if (!strcmpi(adminId,ident->id)) - { - adminById = true; - break; - } - } - } - } - - if (!adminById) - { - if (GlobalTickCount() < info->_loginDisabledUntil) break; - RString password = cmd._content.ReadString(); - ConstParamEntryPtr entry = _serverCfg.FindEntry("passwordAdmin"); - if (entry) - { - RString realPassword = *entry; - if (strcmp(password, realPassword) != 0) - { - info->_loginFailedCount++; - if (info->_loginFailedCount >= MaxLoginAttempts) - { - info->_loginFailedCount = 0; - info->_loginDisabledUntil = GlobalTickCount() + DelayAfterMaxAttempts; - } - break; - } - } - } - info->_loginFailedCount = 0; - - if (_gameMaster != AI_PLAYER) - { - NetworkCommandMessage answer; - answer._type = NCMTLoggedOut; - SendMsg(_gameMaster, &answer, NMFGuaranteed); - } - - SetGameMaster(from, false); - } - } - break; - case NCMTLogout: - if (_dedicated && from == _gameMaster) - { - NetworkCommandMessage answer; - answer._type = NCMTLoggedOut; - SendMsg(_gameMaster, &answer, NMFGuaranteed); - - RString name; - for (int i=0; i<_players.Size(); i++) - if (_players[i]->dpid == _gameMaster) - { - name = _players[i]->name; - break; - } - ConsoleF(LocalizeString(IDS_DS_ADMIN_LOGGED_OUT), cc_cast(name)); - - _gameMaster = AI_PLAYER; - _sessionLocked = false; - _debugOn.Clear(); - - UpdateAdminState(); - - if (_mission[0] == '?' && _mission[1] == 0) - { - // when admin logged out, perform mission voting instead - NetworkCommandMessage answer; - answer._type = NCMTVoteMission; - NetworkCommandMessage answer2; - answer2._type = NCMTVoteMissionExt; - AddMissionList(answer,answer2); - for (int i=0; i<_identities.Size(); i++) - { - SendMsg(_identities[i].dpnid, &answer, NMFGuaranteed); - SendMsg(_identities[i].dpnid, &answer2, NMFGuaranteed); - } - } - } - break; - case NCMTShutdown: - if (_dedicated && ((from == _gameMaster && !_admin) || from==BOT_CLIENT)) - { - #if defined _WIN32 - ::PostMessage((HWND)hwndApp, WM_CLOSE, 0, 0); - #else - interrupted = true; - #endif - } - break; -#if _VBS3 - case NCMTExitAll: - { - if (_dedicated && from == _gameMaster) - { - // send command to all clients to shut down! - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = _players[i]; - NetworkComponent::SendMsg(info.dpid, msg, type, NMFGuaranteed); - } - } - } - break; -#endif - case NCMTMonitorAsk: - if (from == _gameMaster || from==BOT_CLIENT) - { - float interval; - cmd._content.Read(&interval, sizeof(interval)); - Monitor(interval); - } - break; - case NCMTDebugAsk: - if - ( - (_dedicated && from == _gameMaster && !_admin) || - from==BOT_CLIENT - ) - { - DebugAsk(cmd._content.ReadString()); - } - break; - case NCMTMission: - if (_dedicated && (from == _gameMaster || from==BOT_CLIENT)) - { - _mission = cmd._content.ReadString(); - - RString diffName = cmd._content.ReadString(); - _difficulty = Glob.config.diffDefault; - int difficulty = Glob.config.diffNames.GetValue(diffName); - if (difficulty >= 0) _difficulty = difficulty; - if (_mission.GetLength() > 0) _restart = true; - if (_serverState != NSSSelectingMission && _serverState != NSSPlaying) - { - GNetworkManager.DestroyAllObjects(); - SetServerState(NSSSelectingMission); - } - } - break; - case NCMTMissions: - if (_dedicated && (from == _gameMaster || from==BOT_CLIENT)) - { - DoMissions(true); - } - break; - case NCMTRestart: - if (_dedicated && _serverState == NSSPlaying && - (from == _gameMaster || from==BOT_CLIENT) ) _restart = true; - break; - case NCMTReassign: - if (_dedicated && (from == _gameMaster || from==BOT_CLIENT)) - { - DoReassign(); - } - break; - case NCMTProfileAsk: -#if _ENABLE_PERFLOG - if (_dedicated && from == _gameMaster) - { - RString params = cmd._content.ReadString(); - params.Trim(); - if (params.IsEmpty()) GPerfProfilers.CaptureSingleFrame(1); - else - { - const char *separator = strchr(params, ','); - if (separator) - { - int len = separator - cc_cast(params); - RString scope = params.Substring(0, len); - scope.Trim(); - GPerfProfilers.CaptureSlowFrame(scope, atof(separator + 1)); - } - else - { - GPerfProfilers.CaptureSingleFrame(atoi(params)); - } - } - } -#endif - break; - case NCMTInit: - if (_dedicated && (from == _gameMaster || from==BOT_CLIENT)) - { - RString GetServerConfig(); - _serverCfg.Parse(GetServerConfig(), NULL, NULL, &GParsingNamespace); // parsing namespace (persistent namespace needed for persistent ParamFile) - } - break; - case NCMTLockSession: - if (_dedicated && ( (from == _gameMaster && !_admin) || from==BOT_CLIENT ) ) - { - bool lock; - if ( cmd._content.Read(&lock, sizeof(bool)) ) - LockSession(lock); - } - break; -#endif - case NCMTKick: - if - ( - from == BOT_CLIENT -#if _ENABLE_DEDICATED_SERVER - || from == _gameMaster -#endif - ) - { - int player; - if - ( - cmd._content.Read(&player, sizeof(int)) && - player != BOT_CLIENT - ) KickOff(player,KORKick); - } - break; -#if _ENABLE_DEDICATED_SERVER - case NCMTVote: - if (_dedicated && _gameMaster == AI_PLAYER) - { - const NetworkPlayerInfo *info = GetPlayerInfo(from); - if (!info) break; - bool doEcho = false; - LocalizedFormatedString echo; - int subtype; - cmd._content.Read(&subtype, sizeof(int)); - switch (subtype) - { - case NCMTMission: - Fail("Command-style mission voting no longer supported"); - break; - case NCMTMissions: - _votings.Add(this, (char *)&subtype, sizeof(int), _voteThreshold, from); - echo.SetFormat(LocalizedString::Stringtable,"STR_DS_VOTES_MISSIONS"); - echo.AddArg(LocalizedString::PlainText,info->name); - doEcho = true; - break; - case NCMTRestart: - _votings.Add(this, (char *)&subtype, sizeof(int), _voteThreshold, from); - echo.SetFormat(LocalizedString::Stringtable,"STR_DS_VOTES_RESTART"); - echo.AddArg(LocalizedString::PlainText,info->name); - doEcho = true; - break; - case NCMTReassign: - _votings.Add(this, (char *)&subtype, sizeof(int), _voteThreshold, from); - echo.SetFormat(LocalizedString::Stringtable,"STR_DS_VOTES_REASSIGN"); - echo.AddArg(LocalizedString::PlainText,info->name); - doEcho = true; - break; - case NCMTKick: - { - int id[2]; - id[0] = subtype; - cmd._content.Read(&id[1], sizeof(int)); - _votings.Add(this, (char *)id, 2 * sizeof(int), _voteThreshold, from); - const NetworkPlayerInfo *kickInfo = GetPlayerInfo(id[1]); - if (kickInfo) - { - echo.SetFormat(LocalizedString::Stringtable,"STR_DS_VOTES_KICK"); - echo.AddArg(LocalizedString::PlainText,info->name); - echo.AddArg(LocalizedString::PlainText,kickInfo->name); - doEcho = true; - } - } - break; - case NCMTAdmin: - { - char *ptr = cmd._content.Data() + cmd._content.GetPos(); - int size = cmd._content.Size() - cmd._content.GetPos(); - _votings.Add( - this, (char *)&subtype, sizeof(int), _voteThreshold, from, - ptr, size - ); - int player = *(int *)ptr; - RString name; - for (int i=0; i<_players.Size(); i++) - if (_players[i]->dpid == player) - { - name = _players[i]->name; - break; - } - echo.SetFormat(LocalizedString::Stringtable,"STR_DS_VOTES_ADMIN"); - echo.AddArg(LocalizedString::PlainText,info->name); - echo.AddArg(LocalizedString::PlainText,name); - doEcho = true; - } - break; - } - // Send voting echo to all other players - if (doEcho) - { - LocalizedChatMessage chat; - chat._channel = CCSystem; - chat._args = echo._args; - for (int i=0; i<_players.Size(); i++) - { - if (_players[i]->clientState >= NCSConnected) - SendMsg(_players[i]->dpid, &chat, NMFGuaranteed); - } - } - } - break; - case NCMTExec: - { - if (_dedicated && ( (from == _gameMaster && !_admin) || from==BOT_CLIENT ) ) - { - RString expression = cmd._content.ReadString(); - - // SDZ_SQF_EXEC: do not evaluate inside the message handler. - // Evaluating here ran the script while the network layer was still - // walking the object list; object/string churn from the script - // corrupted the express heap and killed the server afterwards - // (ACCESS_VIOLATION inside FastAlloc / GameDataObject, no RPT line). - // The expression goes to a queue drained right after the network - // messages of the frame are processed. - if (expression.GetLength() > 0) - { - QueueExec(from, expression); - } - } - } - break; -#if _ENABLE_CHEATS - case NCMTGameExec: - { - GameState *state = GWorld->GetGameState(); - if (state) - { - GameVarSpace vars(false); - GameValue result; - int gshandle = state->BeginContext(&vars); - { - RString code = cmd._content.ReadString(); - if (code.GetLength() > 0) - { - NetworkId playerId = GetNetworkManager().GetPlayerPerson(from); - NetworkObject *playerNO = GetNetworkManager().GetObject(playerId); - Person *playerObj = dyn_cast(playerNO); - if (playerObj) - { - GameValue fromPlayer = GameValueExt(playerObj,GameValExtObject); - state->VarSetLocal("_this", fromPlayer, true); - } - result = state->EvaluateMultiple(code, GameState::EvalContext::_default, GWorld->GetMissionNamespace()); // mission namespace - } - } - state->EndContext(gshandle); - if (!result.GetNil()) - { - NetworkCommandMessage msg; - msg._type = NCMTExecResult; - msg._content.WriteString(result.GetText()); - SendMsg(from, &msg, NMFGuaranteed); - } - } - } - break; -#endif - case NCMTAskVoNDiagnostics: - { - // convert dpnid of sender to CD based ID - PlayerIdentity *id = FindIdentity(from); - RString cdid,name; - if (id) cdid = id->GetDebugId(), name = id->name; - if (cdid.IsEmpty()) cdid = Format("#%d", from); - RString response = cmd._content.ReadString(); - GDebugVoNBank.AddClientResponse(cdid, name, response); - } - break; -#if _USE_BATTL_EYE_SERVER - /// BattlEye server command - case NCMTBattlEye: - if (_dedicated && ( (from == _gameMaster && !_admin) || from==BOT_CLIENT ) ) - { - RString command = cmd._content.ReadString(); - _beIntegration.Command(command); - } - break; -#endif -#endif - default: - Fail("Network command type"); - break; - } - } - break; - case NMTVoteMission: -#if _ENABLE_DEDICATED_SERVER - if (_gameMaster == AI_PLAYER) // voting enabled only when no admin - { - VoteMissionMessage vote; - vote.TransferMsg(ctx); - int diffId = NCMTDifficulty; - // difficulty voting is never finished - int minVotePlayers = (GetMaxPlayers() + 1) / 2; - _votings.Add( - this, (char *)&diffId, sizeof(diffId), 1e6, from, - vote._diff, vote._diff.GetLength(), false, minVotePlayers - ); - int missId = NCMTMission; - _votings.Add( - this, (char *)&missId, sizeof(missId), 0.9999, from, - vote._name, vote._name.GetLength(), true, minVotePlayers - ); - // note: voting may have been completed by the vote - MissionVotingEcho(); - } -#endif - break; - case NMTMissionParams: - { - MissionParamsMessage params; - params.TransferMsg(ctx); - - _param1 = params._param1; - _param2 = params._param2; - - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.dpid == from) continue; - if (info.clientState < NCSConnected) continue; - SendMsg(info.dpid, msg, type, NMFGuaranteed, NULL); - } - } - break; -#if _ENABLE_MP - case NMTMuteList: - { - NetworkPlayerInfo *info = GetPlayerInfo(from); - if (info) - { - info->muteList.TransferMsg(ctx); - // send remote mute lists to other players - for (int i=0; i<_identities.Size(); i++) - { - SendMuteList(_identities[i]); - } - } - } - break; -#endif - case NMTVoiceOn: - { - VoiceOnMessage ask; - ask.TransferMsg(ctx); -#if _GAMES_FOR_WINDOWS - PlayerIdentity *identity = FindIdentity(ask._dpnid); - if (identity) identity->voiceOn = ask._voiceOn; -#endif - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.dpid == from) continue; - if (info.clientState < NCSConnected) continue; - SendMsg(info.dpid, msg, type, NMFGuaranteed, NULL); - } - } - break; - case NMTDataSignatureAnswer: - { - DataSignatureAnswerMessage answer; - answer.TransferMsg(ctx); -#define PROFILE_SIGNATURES 0 -#if _ENABLE_PERFLOG && PROFILE_SIGNATURES - LogF("NMTDataSignatureAnswer START: %s", cc_cast(answer._filename)); - PROFILE_SCOPE_EX(NMTDSA,*); - int time1; - int time2; - int time3; - int time4; -#endif - NetworkPlayerInfo *info = GetPlayerInfo(from); - if (!info) break; - - //NetLog("Client %s: Data signature answer %d:'%s' level %d received, %d pending",cc_cast(info->name),answer._index,cc_cast(answer._filename),answer._level,info->signatureChecks.CountPendingData()); - - if (answer._index >= 0) - { - // remove from the list of pending checks - if (!info->signatureChecks.Remove(answer._index)) - { // I have not asked this question! - if (answer._index != CollectedHashes::CollectEndIndex) - { // backward compatibility (CollectEndIndex was not added into the pending check before) - ReportWrongSignatures(from, answer._filename, info, "DSA Not Pending"); - break; - } - } - } - -#if _ENABLE_PERFLOG && PROFILE_SIGNATURES - time1 = PROFILE_SCOPE_NAME(NMTDSA).TimeSpentNorm(); -#endif - - if (answer._signature.Version()<_sigVerRequired || !DataSignatures::VerifySignature(answer._hash, answer._signature)) - { - RString wsaReport; - if (answer._signature.Version()<_sigVerRequired) wsaReport = Format("DSA insufficient ver=%d", answer._signature.Version()); - else wsaReport = "DSA failed"; - wsaReport = wsaReport + Format(" ix=%d, level=%d", answer._index, answer._level); - ReportWrongSignatures(from, answer._filename, info, wsaReport); - break; - } - else - { -#if _ENABLE_PERFLOG && PROFILE_SIGNATURES - time2 = PROFILE_SCOPE_NAME(NMTDSA).TimeSpentNorm(); -#endif - if (info->hashes.AddHash(answer._index, answer._filename, answer._hash._content, answer._signature.Version(), answer._level, info->signatureChecks)) - { - RString wsaReport = Format("DSA AddHash, level=%d (%s)", answer._level, cc_cast(info->hashes.GetLastError())); - ReportWrongSignatures(from, answer._filename, info, wsaReport); - break; - } - } -#if _ENABLE_PERFLOG && PROFILE_SIGNATURES - time4 = PROFILE_SCOPE_NAME(NMTDSA).TimeSpentNorm(); - extern unsigned getClockFrequency (); - LogF(" %.2f ms spent, A NMT=%d", time1/100.0f, NMTDataSignatureAnswer); - LogF(" %.2f ms spent, B NMT=%d", (time2-time1)/100.0f, NMTDataSignatureAnswer); - LogF(" %.2f ms spent, C NMT=%d", (time3-time2)/100.0f, NMTDataSignatureAnswer); - LogF(" %.2f ms spent, D NMT=%d", (time4-time3)/100.0f, NMTDataSignatureAnswer); - LogF(" TOTAL %.2f ms spent, NMT=%d", time4/100.0f, NMTDataSignatureAnswer); -#endif - } - break; - case NMTFileSignatureAnswer: - { - FileSignatureAnswerMessage answer; - answer.TransferMsg(ctx); - NetworkPlayerInfo *info = GetPlayerInfo(from); - if (!info) break; - - //NetLog("Client %s: File signature answer %x:'%s' level %d received, %d pending",cc_cast(info->name),answer._index,cc_cast(answer._fileName),answer._level,info->signatureChecks.CountPendingFiles()); -/* - if (answer._index >=0) - RptF("FILE SIG INDEX INTEGRITY: %s -> %s", cc_cast(info->hashes.hashes[answer._index].fileName), cc_cast(answer._fileName)); -*/ - // remove from the list of pending checks - RString prefix; - if ( !info->signatureChecks.Remove(answer._fileName,&prefix) ) - { // I have not asked this question! - ReportWrongSignatures(from, answer._fileName, info, "FSA Not Pending"); - break; - } - - // compute the answer hash - DSHash answerHash; - switch (answer._signature.Version()) - { - case 1: - { - Temp dummy; - // only data content hash is signed (but pbo prefix is present in answer._dataToHash => extract it) - answer.GetDataHash(answerHash._content); - // new clients (start from rev.78326) contain DataSignatureAnswer matching index - if (info->hashes.AddHash(answer._index, answer.GetPrefix(), answerHash._content, dummy, answer._signature.Version(), answer._level)) - { - RString wsaReport = Format("FSA AddHash, ver=1, level=%d (%s)", answer._level, cc_cast(info->hashes.GetLastError())); - ReportWrongSignatures(from, answer._fileName, info, wsaReport); - } - } - break; - case 2: - { - Temp dummy; - HashCalculator calculator; - calculator.Add(answer._dataToHash.Data(), answer._dataToHash.Size()); - AutoArray finalHash; - calculator.GetResult(finalHash); - answerHash._content.Realloc(finalHash.Data(), finalHash.Size()); //Ver2 hash - if (answer._level!=2) - { - Temp dataContentHash; - answer.GetDataHash(dataContentHash); - //AddLevel2Hash based on bank prefix - if (info->hashes.AddHash(answer._index, answer.GetPrefix(), dataContentHash, answerHash._content, answer._signature.Version(), answer._level)) //AddHash based on bank prefix - { - RString wsaReport = Format("FSA AddHash, ver=2, level=%d (%s)", answer._level, cc_cast(info->hashes.GetLastError())); - ReportWrongSignatures(from, answer._fileName, info, wsaReport); - } - } - else if (info->hashes.AddHash(answer._index, answer.GetPrefix(), dummy, answerHash._content, answer._signature.Version(), answer._level) ) //AddHash based on bank prefix - { - RString wsaReport = Format("FSA AddHash, ver=2, level=%d (%s)", answer._level, cc_cast(info->hashes.GetLastError())); - ReportWrongSignatures(from, answer._fileName, info, wsaReport); - } - } - break; - } - - if (answer._signature.Version()<_sigVerRequired || !DataSignatures::VerifySignature(answerHash, answer._signature)) - { - RString wsaReport; - if (answer._signature.Version()<_sigVerRequired) wsaReport = Format("FSA insufficient ver=%d", answer._signature.Version()); - else wsaReport = "FSA failed"; - ReportWrongSignatures(from, answer._fileName, info, wsaReport); - break; - } - else - { - // check the answer has the same prefix - if ( stricmp(answer.GetPrefix(),prefix)!=0 ) - { - RString wsaReport = Format("FSA %s!=%s", cc_cast(answer.GetPrefix()), cc_cast(prefix)); - ReportWrongSignatures(from, answer._fileName, info, wsaReport); - break; - } - - } - } - break; - case NMTHackedData: - { - HackedDataMessage answer; - answer.TransferMsg(ctx); - OnHackedData((HackType)answer._type, from, answer._filename); - } - break; - case NMTCDKeyCheckAnswer: -#if _ENABLE_GAMESPY && _VERIFY_CLIENT_KEY - { - CDKeyCheckAnswerMessage answer; - answer.TransferMsg(ctx); - - NetworkPlayerInfo *info = GetPlayerInfo(from); - if (!info) break; - - info->cdKeyCheck.timeout = 0; //answer arrived before timeout elapsed - - sockaddr_in address; - if (!GetClientAddress(from, address)) break; - - gcd_authenticate_user( - GetGameID(), from, address.sin_addr.s_addr, info->challenge, answer._response, - OnAuthorize, OnRefreshAuthorize, this); - - // Bastian: BEServer.ReceivedPlayerGUID() will be called as soon as the GameSpy cd-key hash is received from the client (after connecting). - _beIntegration.PlayerGUIDReceived(info->dpid); - } -#endif - break; - case NMTCDKeyRecheckAnswer: -#if _ENABLE_GAMESPY && _VERIFY_CLIENT_KEY - { - CDKeyRecheckAnswerMessage answer; - answer.TransferMsg(ctx); - - gcd_process_reauth(GetGameID(), from, answer._hint, answer._response); - } -#endif - break; - case NMTAskConnectVoice: - { - AskConnectVoiceMessage ask; - ask.TransferMsg(ctx); - - NetworkPlayerInfo *info = GetPlayerInfo(from); - if (!info) break; - -// ask._privateAddr; - #define AB(v,i) ((v)>>((i)*8)&0xff) - LogF("VoNLog: Server received AskConnectVoiceMessage with %d.%d.%d.%d:%d from %d",AB(ask._privateAddr,0),AB(ask._privateAddr,1),AB(ask._privateAddr,2),AB(ask._privateAddr,3),ask._voicePort,from); - - // do some tests vor GDebugVoNBank collecting system - sockaddr_in clAdr; - bool noClientAddr = !_server->GetClientAddress(from, clAdr) && (from!=BOT_CLIENT); - if (noClientAddr) GDebugVoNBank.SetFeature(DebugVoNBank::VoNFeature_GetClientAddressFailed); - - int distAddr = ADDR(clAdr); - - info->_privateAddr = ask._privateAddr; - info->_privatePort = ask._voicePort; - info->_publicAddr = ask._publicAddr; - info->_publicPort = ask._publicAddr==distAddr ? ntohs(clAdr.sin_port) : ask._voicePort; // port unknown, try the same port as private - - LogF("VoNLog: .. public %d.%d.%d.%d:%d from %d",AB(info->_publicAddr,0),AB(info->_publicAddr,1),AB(info->_publicAddr,2),AB(info->_publicAddr,3),info->_publicPort,from); - LogF("VoNLog: .. private %d.%d.%d.%d:%d from %d",AB(info->_privateAddr,0),AB(info->_privateAddr,1),AB(info->_privateAddr,2),AB(info->_privateAddr,3),info->_privatePort,from); - - int serverPublicAddr = 0; // TODO: handle clients on the server LAN differently - for (int i=0; i<_players.Size(); i++) - { - const NetworkPlayerInfo &player = *_players[i]; - if (player.dpid==BOT_CLIENT) serverPublicAddr = player._publicAddr; - } - for (int i=0; i<_players.Size(); i++) - { - const NetworkPlayerInfo &player = *_players[i]; - if (player.dpid==from) continue; - - // same public ip => same LAN. Send private address - int NetworkPlayerInfo::*addr = info->_publicAddr == player._publicAddr ? &NetworkPlayerInfo::_privateAddr : &NetworkPlayerInfo::_publicAddr; - int NetworkPlayerInfo::*port = info->_publicAddr == player._publicAddr ? &NetworkPlayerInfo::_privatePort : &NetworkPlayerInfo::_publicPort; - - LogF("VoNLog: public %d.%d.%d.%d:%d of %d",AB(player._publicAddr,0),AB(player._publicAddr,1),AB(player._publicAddr,2),AB(player._publicAddr,3),player._publicPort,player.dpid); - LogF("VoNLog: private %d.%d.%d.%d:%d of %d",AB(player._privateAddr,0),AB(player._privateAddr,1),AB(player._privateAddr,2),AB(player._privateAddr,3),player._privatePort,player.dpid); - - LogF("VoNLog: public %d.%d.%d.%d:%d of %d",AB(info->_publicAddr,0),AB(info->_publicAddr,1),AB(info->_publicAddr,2),AB(info->_publicAddr,3),info->_publicPort,info->dpid); - LogF("VoNLog: private %d.%d.%d.%d:%d of %d",AB(info->_privateAddr,0),AB(info->_privateAddr,1),AB(info->_privateAddr,2),AB(info->_privateAddr,3),info->_privatePort,info->dpid); - - ConnectVoiceDirectMessage connect; - connect._dpnid = from; - connect._addr = BestAddress(connect._port,info,addr,port); - connect._direct = true; - SendMsg(player.dpid, &connect, NMFGuaranteed); - LogF("VoNLog: Server sent %d.%d.%d.%d:%d about %d to %d",AB(connect._addr,0),AB(connect._addr,1),AB(connect._addr,2),AB(connect._addr,3),connect._port,from,player.dpid); - - connect._dpnid = player.dpid; - connect._addr = BestAddress(connect._port,&player,addr,port); - connect._direct = true; - SendMsg(from, &connect, NMFGuaranteed); - LogF("VoNLog: Server sent %d.%d.%d.%d:%d about %d to %d",AB(connect._addr,0),AB(connect._addr,1),AB(connect._addr,2),AB(connect._addr,3),connect._port,player.dpid,from); - - } - } - break; - case NMTClientDiagToServer: - { - ClientDiagToServerMessage answer; - answer.TransferMsg(ctx); - RString logline = Format("DiagClient(%d): %s", from, cc_cast(answer._response)); - RptF(logline); - } - break; - case NMTConnectVoiceDirect: - { - } - break; - case NMTOwnerChanged: - { - OwnerChangedMessage ackMsg; - ackMsg.TransferMsg(ctx); - LogF("Owner of %d:%" OID_FORMAT" changed", ackMsg._creator, ackMsg._id); - NetworkId id(ackMsg._creator, ackMsg._id); - NetworkObjectInfo *oInfo = GetObjectInfo(id); - if (!oInfo) - { - RptFObjectNotFound(id, type, from); - return; - } - - ChangeOwnerFinal(oInfo, from, id); - } - break; - default: - //RptF("Server: Unhandled user message %s", cc_cast(GetMsgTypeName(type))); - ConsoleF("Server: Unhandled user message %s", cc_cast(GetMsgTypeName(type))); - break; - } - -#if _ENABLE_PERFLOG - int profileTime = PROFILE_SCOPE_NAME(OnMsg).TimeSpentNorm(); - static float profileTimeLimit = 10.0f; //ms - if (profileTime/100.0f > profileTimeLimit) - { - #if _SUPER_RELEASE - RptF("Warn: %.2f ms spent, NMT=%d", profileTime/100.0f, type); - if (type==NMTNetworkCommand) - { - NetworkCommandMessage cmd; - cmd.TransferMsg(ctx); - RptF(" NetworkCommand: %d", cmd._type); - } - #else - LogF("Warn: %.2f ms spent, NMT=%d", profileTime/100.0f, type); - #endif - } -#endif -} - -void NetworkServer::ChangeOwnerFinal( NetworkObjectInfo * oInfo, int from, NetworkId &id ) -{ - NetworkPlayerInfo *pInfo = GetPlayerInfo(oInfo->pendingOwner); - if (pInfo) - { - PlayerIndex index = GetPlayerIndex(pInfo->dpid); - NetworkPlayerObjectInfo *poInfo = oInfo->GetPlayerObjectInfo(index,pInfo->dpid); - if (!poInfo->updating) - { - SendCreateMessage(pInfo->dpid, *oInfo, poInfo); - poInfo->updating = true; - pInfo->markAsUpdating(poInfo); - } - for (int cls=NMCUpdateFirst; clspendingOwner = BOT_CLIENT; - } - // reset times to ensure update from new owner will take place - for (int cls=NMCUpdateFirst; clscurrentUpdate[cls]; - if (info.message) info.message->time = Time(0); // do not use TIME_MIN - difference is undefined - } - - RescanBestPosition(oInfo); - - if (oInfo->owner==from) - { - // Send message to new owner at last - ChangeOwnerMessage msg; - msg._creator = id.creator; - msg._id = id.id; - msg._owner = oInfo->pendingOwner; - msg._disconnected = false; - SendMsg(oInfo->pendingOwner, &msg, NMFGuaranteed); - - // Send messages waiting to be sent after owner is changed - for (int i=0; iwaitingMessages.Size(); i++) - { - WaitingMessageInfo *wMsgInfo = oInfo->waitingMessages[i]; - SendMsg(oInfo->pendingOwner, wMsgInfo->msg, wMsgInfo->type, NMFGuaranteed, NULL); - } - oInfo->waitingMessages.Clear(); - - // forget anything sent to the old owner before (normally nothing should be sent to the owner?) - oInfo->ResetPlayerObjectInfo(GetPlayerIndex(oInfo->owner),oInfo->owner); - // if we send anything to the new owner before, forget it now - oInfo->ResetPlayerObjectInfo(GetPlayerIndex(oInfo->pendingOwner),oInfo->pendingOwner); - -#if DIAG_MP_OBJECT_LIFE - GObjLifeJournal.Add(id, Format("(%.3f) Owner changed: from=%d to=%d",Glob.time.toFloat(), oInfo->owner, oInfo->pendingOwner)); -#endif - if (DebugMeBoy(id)) - { - LogF("*** DebugMeBoy: {%d:%" OID_FORMAT"} Owner changed from %d to %d", oInfo->id.creator.CreatorInt(), oInfo->id.id, oInfo->owner, oInfo->pendingOwner); - } - - oInfo->owner = oInfo->pendingOwner; - oInfo->pendingOwner = NO_CLIENT; - } - else - { - RptF("Server: OwnerChanged of %d:%" OID_FORMAT" arrived from non owner %d", id.creator.CreatorInt(), id.id, from); - } -} - -void NetworkServer::CheckItemsOwner(const NetworkMessageUpdateVehicleAI *msg, int newOwner) -{ - const NetworkMessageUpdateInventoryItem *invItemUpdate = dynamic_cast(msg); - if (invItemUpdate) - { - // attachments - for (int i=0; i_attachments.Size(); i++) - { - const NetworkId &id = invItemUpdate->_attachments[i]; - if (!id.IsNull()) CheckItemOwner(id, newOwner); - } - } - - // items cargo - const NetworkMessageUpdateSupply *supply = static_cast(msg->_supply.GetRef()); - if (supply) - { - for (int i=0; i_itemsCargo.Size(); i++) - { - const NetworkId &id = supply->_itemsCargo[i]; - if (!id.IsNull()) CheckItemOwner(id, newOwner); - } - } - - // magazines loaded in weapon - const NetworkMessageUpdateWeapon *weapon = dynamic_cast(msg); - if (weapon) - { - for (int i=0; i_muzzles.Size(); i++) - { - const NetworkMessageUpdateMuzzle *muzzle = static_cast(weapon->_muzzles[i].GetRef()); - if (muzzle) - { - const NetworkId &id = muzzle->_magazineWanted; - if (!id.IsNull()) CheckItemOwner(id, newOwner); - } - } - } -} - -void NetworkServer::CheckItemOwner(const NetworkId &id, int newOwner) -{ - const NetworkObjectInfo *info = GetObjectInfo(id); - if (!info || info->owner == newOwner) return; // no change - - // change my owner - ChangeOwner(id, info->owner, newOwner); - // check subitems recursively - const NetworkCurrentInfo &cInfo = info->currentUpdate[NMCUpdateGeneric]; - const NetworkMessageUpdateVehicleAI *msg = dynamic_cast(cInfo.message.GetRef()); - if (msg) CheckItemsOwner(msg, newOwner); -} - -/*! -\patch 5178 Date 11/1/2007 by Bebul -- Fixed: Default handling of different data detected was stricter then intended, resulting in a kick of players. -*/ -void NetworkServer::OnHackedData(HackType type, int dpid, RString filename) -{ - RptF("NetworkHackedData type=%d player=%d file=%s", (int)type, dpid, cc_cast(filename)); - const PlayerIdentity *identity = FindIdentity(dpid); - if (!identity) return; - -#if _ENABLE_DEDICATED_SERVER - switch (type) - { - case HTUnsignedData: - if (OnEvent(SEOnUnsignedData, (float)identity->playerid, filename)) return; - break; - case HTHackedData: - if (OnEvent(SEOnHackedData, (float)identity->playerid, filename)) return; - break; - } -#endif - -#if !SIGNATURES_TEST_ONLY - KickOff(dpid, KORFade); -#endif -} - -#if _VERIFY_KEY -void NetworkServer::OnDoubleIdDetected(const PlayerIdentity &newIdentity, const PlayerIdentity &oldIdentity) -{ - // report problems on global channel - RString message = LocalizeString(IDS_FADE_AWAY); - RString senderName = LocalizeString(IDS_FADE_REMMEMBER); - RefArray dummy; - GNetworkManager.Chat(CCSystem, senderName, dummy, message); - GChatList.Add(CCSystem, senderName, message, false, true); - -#if _ENABLE_DEDICATED_SERVER - if (OnEvent(SEDoubleIdDetected, (float)newIdentity.playerid, (float)oldIdentity.playerid)) return; // handled - if (_kickDuplicate) KickOff(newIdentity.dpnid, KORKick); -#endif -} -#endif - -void NetworkServer::OnPlayerDisconnected(NetworkPlayerInfo *info) -{ - if (GNetworkPlayerDisconnected.GetNil()) return; - GameState *state = GWorld->GetGameState(); - if (state) - { - GameVarSpace vars(false); - int gshandle = state->BeginContext(&vars); - PlayerIdentity *identity = FindIdentity(info->dpid); - RString uid = identity ? identity->id : RString(); - state->VarSetLocal("_id", (float)identity->playerid, true); - state->VarSetLocal("_uid", uid, true); - state->VarSetLocal("_name", info->name, true); - Object *agent = dyn_cast(_parent->GetObject(info->person)); - state->VarSetLocal("_agent", GameValueExt(agent), true); - -#if USE_PRECOMPILATION - if (GNetworkPlayerDisconnected.GetType() == GameCode) - { - GameDataCode *code = static_cast(GNetworkPlayerDisconnected.GetData()); - if (code->IsCompiled() && code->GetCode().Size() > 0) - state->Evaluate(code->GetString(), code->GetCode(), GameState::EvalContext::_default, GWorld->GetMissionNamespace()); // mission namespace - } - else -#endif - if (GNetworkPlayerDisconnected.GetType() == GameString) - { - // make sure string is not destructed while being evaluated - RString code = GNetworkPlayerDisconnected; - if (code.GetLength() > 0) - state->EvaluateMultiple(code, GameState::EvalContext::_default, GWorld->GetMissionNamespace()); // mission namespace - } - state->EndContext(gshandle); - } - -} - -void NetworkServer::CallOnPlayerDisconnected() -{ - for (int i=0; i<_players.Size(); i++) - { - // call only for players which are still playing the mission - if (_players[i]->clientState == NCSPlaying) - { - OnPlayerDisconnected(_players[i]); - } - } -} -int NetworkServer::FindOwner(const NetworkId &id) -{ - RefD dInfo; - if (_objects.get(id,dInfo)) - { - return dInfo->owner; - } - - LogF("Owner of %d:%" OID_FORMAT" not known - searching player",id.creator,id.id); - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &pInfo = *_players[i]; - if (pInfo.person == id) - { - // change owner - LogF("Owner not known - player found"); - return pInfo.dpid; - } - } - // not found - return 0; -} - -void NetworkServer::OnMessageClientInput(int from, NetworkMessageType type, NetworkMessageContext &ctx) -{ - // client input has very special handling, no need to check for any network id, it is send only from clients to the server - NetworkPlayerInfo *info = GetPlayerInfo(from); - if (info && info->_clientInput) - { - info->_clientInput->TransferMsg(ctx); - } -} - -DWORD NetworkServer::SendMsg -( - int to, NetworkSimpleObject *object, NetMsgFlags dwFlags -) -{ - // check if message can be sent - NetworkPlayerInfo *info = GetPlayerInfo(to); - if (!info) - { - RptF("Server: cannot send message - player %d is not known.", to); - return 0xFFFFFFFF; - } - if (info->clientState < NCSConnected && object->GetNMType() >= NMTFirstVariant) - { - RptF("Server: cannot send message - player's %s messages are not registred yet.", (const char *)info->name); - return 0xFFFFFFFF; - } - return NetworkComponent::SendMsg(to, object, dwFlags); -} - -void NetworkServer::EnqueueMsg -( - int to, NetworkMessage *msg, - NetworkMessageType type, - NetworkPlayerObjectInfo *poInfo -) -{ - NetworkPlayerInfo *info = GetPlayerInfo(to); - if (!info) - { - Fail("PlayerInfo"); - return; - } - // if - ServerQueueItem *item = new ServerQueueItem(); - item->type = type; - item->msg = msg; - item->poInfo = poInfo; - info->_messageQueue.Add(item); -} - -void NetworkServer::EnqueueMsgNonGuaranteed -( - int to, NetworkMessage *msg, - NetworkMessageType type, - const RefR &dependOn -) -{ - NetworkPlayerInfo *info = GetPlayerInfo(to); - if (!info) - { - Fail("PlayerInfo"); - return; - } - // if - ServerQueueItem *item = new ServerQueueItem(); - item->type = type; - item->msg = msg; - item->dependOn = dependOn; - info->_messageQueueNonGuaranteed.Add(item); -} - - -Vector3 NetworkServer::RandomPlayerPos() const -{ - if (_players.Size()) - { - return _players[rand() % _players.Size()]->cameraPosition; - } - return VZero; -} - -void NetworkServer::PerformIntegrityInvestigations() -{ - // scan all players - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &pi = *_players[i]; - - if (pi.dpid != BOT_CLIENT) - { - // regular checking - DWORD time = GlobalTickCount(); - if ( time > pi.regularCheckNext && pi.clientState>=NCSGameLoaded && pi.clientState<=NCSPlaying && !pi.hashes.IsCollecting() ) - { - bool handled = false; -#if _ENABLE_DEDICATED_SERVER - const PlayerIdentity *identity = FindIdentity(pi.dpid); - if (identity) - { - handled = OnEvent(SERegularCheck, identity->playerid, pi.regularCheckOrder); - pi.regularCheckOrder++; - } -#endif - if (!handled && _verifySignatures) - { - // next random question - if (rand()%2) - { // use DataSignatureAsk message - int index = toIntFloor(GRandGen.RandomValue() * 0x8000); -#if _ENABLE_CHEATS - static int forceValue = -1; - if (forceValue>=0) - { - index = forceValue; - } -#endif - int level = pi.hashes.ActualCheckLevel(); - CheckSignature(pi.dpid, index, level); - } - else - { // use FileSignatureAsk message - int level = pi.hashes.ActualCheckLevel(); - RString filename = pi.hashes.RandomUsedFile(RandomPlayerPos(), level); -#if _ENABLE_CHEATS - static bool doIt = false; - if (doIt) - { - filename = "ca\\air_d_baf\\aw159_mainrotorblurred_baf.p3d"; - LogF("RandomUsedFile: %s", cc_cast(filename)); - } -#endif - QFBank *bank = QFBankQueryFunctions::AutoBank(filename); - if (bank) - { - CheckSignature(pi.dpid, filename, bank->GetPrefix(),level); - } -#if _ENABLE_CHEATS - else if (!filename.IsEmpty()) - LogF("RandomUsedFile test SKIPPED, bank not found! file: %s", cc_cast(filename)); -#endif - } - } -// The following is only for debugging purposes, define used only not to forget to set more test back to normal in some commit -#define _DEBUG_MORE_SIGNATURE_TESTS (_ENABLE_CHEATS && 0) -#if _DEBUG_MORE_SIGNATURE_TESTS - // more test when debugging - pi.regularCheckNext = time + 500 + toInt(1000 * GRandGen.RandomValue()); // 1 s - 3 s -#else - // Note: timing 80s - 160s is no longer used for regular signature checks, but deep (level=1) checks - // regular signature checks are now more frequent, but only shallow (level=0) - pi.regularCheckNext = time + 5000 + toInt(5000 * GRandGen.RandomValue()); // 5 s - 10 s -#endif - } - - if (_verifySignatures && !pi.ClientStateBusy()) - { - ReportHackedData reportFunc(pi, *this); -#if DEBUG_SIGNATURES - pi.errorInfo = Format("SCh Timeout (cs=%d,ss=%d,#=%d,%d)", pi.clientState, _serverState, pi.hashes.Hashes().Size(),pi.hashes.IsCollecting()); - pi.signatureChecks.CheckTimeouts(reportFunc, pi.errorInfo); -#else - pi.signatureChecks.CheckTimeouts(reportFunc); -#endif -#if DEBUG_SIGNATURES - pi.errorInfo = "BI Timeout"; -#endif - pi.hashes.CheckTimeouts(reportFunc); - } -#if DEBUG_SIGNATURES - pi.errorInfo = ""; -#endif - } - } -} - -void PendingSignatureChecks::CheckTimeouts(CheckSignatureTimeoutFunc &func -#if DEBUG_SIGNATURES - , RString &errorInfo -#endif -) -{ - DWORD time = GlobalTickCount(); - for (int i=0; i pendingDataChecks[i].checkTimeout) - { -#if DEBUG_SIGNATURES - errorInfo = errorInfo + Format(" - ix=%d", pendingDataChecks[i].answerIndex); -#endif - if (func()) // do the action - return; - pendingDataChecks.Delete(i); - i--; - } - } - for (int i=0; i pendingFileChecks[i].checkTimeout) - { -#if DEBUG_SIGNATURES - errorInfo = errorInfo + Format(" - file=%s", cc_cast(pendingFileChecks[i].filename)); -#endif - if (func()) // do something the action - return; - pendingFileChecks.Delete(i); - i--; - } - } -} - -void PendingSignatureChecks::DelayCheckTimeouts(DWORD time, const char *playerName) -{ - NetLog("Signature Timeout delayed %.1f seconds for %s", time/1000.0f,playerName); - for (int i=0; iname, playerName) == 0); - return info; - } - } - - int index = _players.Add(new NetworkPlayerInfo()); - NetworkPlayerInfo &info = *_players[index]; - info.dpid = dpid; - info.dvid = dpid; - info.clientState = NCSCreated; - info.channel = CCNone; - info.name = playerName; - info.cameraPosition = InvalidCamPos; - info.cameraPositionTime = TIME_MIN; - info._busyStartTime = 0; -#if _VBS3 - info.cameraDirection = VForward; - info.cameraFov = 0.75; -#endif - info.privateSlot = privateSlot; - info.connectionProblemsReported = false; - info.kickedOff = false; - info.nextQuestionId = 1; - info._jipProcessed = false; - //LogF("_jip=false dpnid=%d setting in %s on line %d\n", dpid, __FILE__, __LINE__); - info.joined = TIME_MAX; - info._publicAddr = 0; - info._publicPort = 0; - info._privateAddr = 0; - info._privatePort = 0; - info._clientInput = new ClientInput(false); - - info.regularCheckNext = GlobalTickCount() + 40000 + toInt(40000 * GRandGen.RandomValue()); // initial delay 40 s - 80 s - info.regularCheckOrder = 1; - - info._loginFailedCount = 0; - info._loginDisabledUntil = 0; - info._isLocal = false; - - -#if _ENABLE_DEDICATED_SERVER - ConstParamEntryPtr entry = _serverCfg.FindEntry("localClient"); - if (entry) - { - if (entry->IsArray()) - { - for (int i=0; iGetSize(); i++) - { - RString ip = (*entry)[i]; - if (MatchIP(ip,ntohl(inaddr))) {info._isLocal = true;break;} - } - } - else - { - RString ip = entry->GetValue(); - if (MatchIP(ip,ntohl(inaddr))) info._isLocal = true; - } - } -#endif - -#if LOG_PLAYERS -LogF -( - "Server: Player info added - name %s, id %d (total %d identities, %d players)", - (const char *)playerName, dpid, _identities.Size(), _players.Size() -); -#endif - -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - if (_dedicated) - { - info.motdIndex = -1; - if (dpid != BOT_CLIENT && _motd.Size() > 0) info.motdIndex = 0; - } -#endif -//} - - // register formats - for (int mt=NMTFirstVariant; mtGetNMType(NMCCreate); - Ref msg = ::CreateNetworkMessage(type); - msg->time = Glob.time; - NetworkMessageContext ctx(msg, this, dpid, MSG_SEND); - - TMError err; - - NetworkMessageMsgFormat *message = (NetworkMessageMsgFormat *)msg.GetRef(); - message->_index = mt; - - err = item->TransferMsg(ctx); - if (err != TMOK) continue; - - // send message - SendMsg(dpid, msg, type, NMFGuaranteed, NULL); - } - - // enable sending messages - SetClientState(dpid, NCSConnected); - - if (_verifySignatures && dpid != BOT_CLIENT) - { - // send accepted keys - for (int i=0; i<_acceptedKeys.Size(); i++) - { - AcceptedKeyMessage key(_acceptedKeys[i]); - SendMsg(dpid, &key, NMFGuaranteed); - } - // send additional signed files - AdditionalSignedFilesMessage files(_additionalSignedFiles); - SendMsg(dpid, &files, NMFGuaranteed); - // TODO: mark required signatures - } - - #if _USE_BATTL_EYE_SERVER - if (dpid != BOT_CLIENT) - { - sockaddr_in address; - _server->GetClientAddress(dpid, address); - _beIntegration.AddPlayer(dpid, address.sin_addr.s_addr, address.sin_port, info.name); - } - #endif - - PlayerMessage msg; - msg._player = dpid; - msg._name = info.name; - msg._server = server; - msg._vonDisabled = _parent->IsVoNDisabled(); - msg._vonCodecQuality = _parent->VoNCodecQuality(); -#if !_USE_BATTL_EYE_SERVER - msg._battlEye = false; -#else - msg._battlEye = _beIntegration.IsEnabled(); -#endif - msg._sigVerRequired = _sigVerRequired; - msg._updatesGuaranteed = _updatesGuaranteed; - msg._steamServerId = 0; - msg._steamSecure = false; -#if _ENABLE_STEAM_MATCHMAKING - if (SteamGameServer()) - { - msg._steamServerId = SteamGameServer()->GetSteamID().ConvertToUint64(); - msg._steamSecure = SteamGameServer()->BSecure(); - } -#elif _VERIFY_CLIENT_KEY - if (SecureIdRequired()>0) - { - msg._steamServerId = GetSecureRandom(); - msg._regURL = "https://is.bistudio.com:8181/BICDKeys/resources/bicdkeys.cdkeys/"; - if (msg._steamServerId==0) msg._steamServerId = 1; // avoid zero, used as a special case: signature not required - info.certChallenge = msg._steamServerId; - } -#endif - // msg._inaddr = inaddr; - SendMsg(dpid, &msg, NMFGuaranteed); - - // Send ServerInfo message - ServerInfoMessage siMsg; - siMsg._hostname = _server->GetSessionName(); - SendMsg(dpid, &siMsg, NMFGuaranteed); - - // Send chat message about player is connecting - if (dpid != BOT_CLIENT) - { - /* - if (!ChannelDisabled(CCSystem)) - { - //char message[256]; - RefArray dummy; - LocalizedChatMessage chat; - chat._channel = CCSystem; - // format - chat._args.Add(LocalizedString(LocalizedString::Stringtable,"STR_MP_CONNECTING")); - // arguments - chat._args.Add(LocalizedString(LocalizedString::PlainText,info.name)); - for (int i=0; i<_players.Size(); i++) - { - if (_players[i]->clientState >= NCSConnected) - SendMsg(_players[i]->dpid, &chat, NMFGuaranteed); - } - } - */ - } - - // send player int and name to himself -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - if (_dedicated) - { - if (server) - { - ConsoleF(LocalizeString(IDS_DS_SERVER_IDENTITY_CREATED)); - } - else - { - ConsoleF(LocalizeString(IDS_DS_PLAYER_CONNECTING), cc_cast(info.name)); - } - } -#endif -//} - - // set the starting number of private and public slots on DS - - //{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - if (IsDedicatedServer()) - { -#if _GAMES_FOR_WINDOWS - // update of max. number of players - int perClient = 32000; - int round = 1; - int maxPlayers = GetMaxPlayersSafe(perClient, round); - int GetDSPrivateSlots(); - int maxPrivate = GetDSPrivateSlots(); - saturateMin(maxPrivate, maxPlayers); - UpdateMaxPlayers(maxPlayers, maxPrivate); -#else - UpdateMaxPlayers(GetMaxPlayers(), 0); -#endif - } -#endif - //} - - return &info; -} - -void NetworkServer::UpdateAdminState() -{ -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - // send also info about new admin and gameMaster state to all clients - // clients need to know whether there is admin on server - // prepare message - ServerAdminMessage samsg; - samsg._admin = _admin; - samsg._gameMaster = _gameMaster; - // update all players and send them fresh admin message - for (int i=0; i<_identities.Size(); i++) - { - PlayerIdentity &pi = _identities[i]; - pi._rights &= ~(PRAdmin|PRVotedAdmin); - if (pi.dpnid==_gameMaster) - { - pi._rights |= _admin ? PRVotedAdmin : PRAdmin; - } - SendMsg(pi.dpnid, &samsg, NMFGuaranteed); - } - DWORD updatePingTime = GlobalTickCount() + 1000; - if (_pingUpdateNext>updatePingTime) _pingUpdateNext = updatePingTime; -#endif -//} -} - -void NetworkServer::OnPlayerDestroy(int dpid) -{ - if (dpid == BOT_CLIENT) - { - Fail("Not implemented."); - // new bot client must be selected - return; - } - -#if _ENABLE_GAMESPY && _VERIFY_CLIENT_KEY - gcd_disconnect_user(GetGameID(), dpid); -#endif - -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - RString name; - if (dpid == _gameMaster) - { - for (int i=0; i<_players.Size(); i++) - if (_players[i]->dpid == _gameMaster) - { - name = _players[i]->name; - break; - } - } -#endif -//} - - NetworkPlayerInfo *info = GetPlayerInfo(dpid); - NetworkId playerPerson; - if (info) - { - /* - if (!ChannelDisabled(CCSystem)) - { - LocalizedFormatedString message; - message.SetFormat(LocalizedString::Stringtable,"STR_MP_DISCONNECT"); - message.AddArg(LocalizedString::PlainText,info->name); - RefArray dummy; - GNetworkManager.LocalizedChat(CCSystem, "", dummy, message); - GChatList.Add(CCSystem, NULL, message.GetLocalizedValue(), false, true); - } - */ - if (info->clientState == NCSPlaying) - { - OnPlayerDisconnected(info); - } - - playerPerson = info->person; - -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - if (_dedicated) ConsoleF(LocalizeString(IDS_DS_PLAYER_DISCONNECTED), cc_cast(info->name)); -#endif -//} - - _squadChecks.ForEachWithDelete([dpid](CheckSquadObject *check){return check->IsPlayer(dpid);}); - - // delete player info - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.dpid == dpid) - { -#if LOG_PLAYERS -LogF -( - "Server: Player info removed - name %s, id %d (total %d identities, %d players)", - (const char *)info.name, dpid, _identities.Size(), _players.Size() - 1 -); -#endif - _players.Delete(i); - break; - } - } - if (_players.Size() == 0) - { - _nextPlayerID = 2; // value 1 is reserved for static objects - _votings.Clear(); - } -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - else if (_dedicated && _players.Size() == 1) - { - _votings.Clear(); - } -#endif -//} - } - -#if _USE_BATTL_EYE_SERVER - _beIntegration.PlayerDisconnected(dpid); -#endif - - DisconnectPlayer(dpid, playerPerson); - - #if _ENABLE_DEDICATED_SERVER - if (_dedicated) - { - _votings.OnPlayerDeleted(dpid); - } - #endif - - LogoutMessage logout; - logout._dpnid = dpid; - for (int i=0; i<_identities.Size(); i++) - { - if (_identities[i].dpnid == dpid) - { -#if _ENABLE_DEDICATED_SERVER - OnEvent(SEOnUserDisconnected, _identities[i].playerid); -#endif - -#if LOG_PLAYERS -LogF -( - "Server: Identity removed - name %s, id %d (total %d identities, %d players)", - (const char *)_identities[i].name, dpid, _identities.Size() - 1, _players.Size() -); -#endif - _identities.Delete(i); - // check if player info was deleted properly - NetworkPlayerInfo *check = GetPlayerInfo(dpid); - if (check) - { - RptF - ( - "Server error: identity deleted, player info still exist (%s, id %d)", - (const char *)check->name, dpid - ); - } - - _votings.Check(this); - break; - } - } - for (int i=0; i<_identities.Size(); i++) - { - PlayerIdentity &player = _identities[i]; - SendMsg(player.dpnid, &logout, NMFGuaranteed); - } - -//{ QUERY & REPORTING SDK -#if _ENABLE_DEDICATED_SERVER - if (IsDedicatedServer()) - { - NetworkClient *client = _parent->GetClient(); - DoAssert(client && client->GetPlayer() != logout._dpnid); - // send new identity to bot client - SendMsg(client->GetPlayer(), &logout, NMFGuaranteed); - } -#endif -//} - - UpdateMatchmakingDescription(false); - -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - if (_dedicated) - { - if (dpid == _gameMaster) - { - ConsoleF(LocalizeString(IDS_DS_ADMIN_LOGGED_OUT), (const char *)name); - - _gameMaster = AI_PLAYER; - _sessionLocked = false; - _debugOn.Clear(); - - // on Xbox admin disconnect means nothing - if (_serverState == NSSSelectingMission && _mission.GetLength() == 1 && _mission[0] == '?') - { - // enable other players vote mission or continue with mission defined in config - _mission = ""; - _restart = false; - _reassign = false; - } - UpdateAdminState(); - - } - } -#endif -//} - - if (_serverState == NSSSelectingMission) - { - // new clients should get mission voting echo as necessary, so that they can see voting - MissionVotingEcho(); - } -#if _ENABLE_MP - // update remote mute lists - for (int i=0; i<_identities.Size(); i++) - { - SendMuteList(_identities[i]); - } -#endif - -} - -void NetworkServer::SetEstimatedEndTime(Time time) -{ - _missionHeader._estimatedEndTime = time; - _missionHeader._updateOnly = true; - _serverTime = ::GetTickCount() - _serverTimeInitTickCount; - _secondsToEstimatedEnd = time.toInt() - Glob.time.toInt(); - _serverTimeOfEstimatedEnd = _serverTime + _secondsToEstimatedEnd; - _nextServerTimeUpdate = _serverTime; //update endTime (and serverTime) to clients as soon as possible - - // send mission description and roles - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.clientState < NCSConnected) continue; - SendMsg(info.dpid, &_missionHeader, NMFGuaranteed); - } -} - -NetworkObjectInfo *NetworkServer::GetObjectInfo(const NetworkId &id) const -{ - // _objects.get variant does bot cause the refcount to be changed - if (const RefD *dInfo=_objects.get(id)) - { - return *dInfo; - } - return NULL; -} - -Vector3 NetworkServer::GetObjectPosition( NetworkId obj ) -{ - const NetworkObjectInfo *info = GetObjectInfo(obj); - if (!info) return VZero; - return info->object->GetCurrentPosition(); -} - -int NetworkServer::GetOwner(const NetworkId &id) const -{ - const NetworkObjectInfo *info = GetObjectInfo(id); - if (!info) return 0; - - const PlayerIdentity *identity = FindIdentity(info->owner); - if (!identity) return 1; - - return identity->playerid; -} - -bool NetworkServer::SetOwner(const NetworkId &id, int clientId) -{ - const NetworkObjectInfo *info = GetObjectInfo(id); - if (!info) return false; - - const PlayerIdentity *identity = FindIdentityByPlayerId(clientId); - if (!identity) return false; - - if (info->owner == identity->dpnid) return false; - - ChangeOwner(id, info->owner, identity->dpnid); - return true; -} - -bool NetworkServer::StatusChat(int clientId, RString text, RString colorClass) -{ - const PlayerIdentity *identity = FindIdentityByPlayerId(clientId); - if (!identity) return false; - - StatusChatMessage msg; - msg._text = text; msg._color = colorClass; - SendMsg(identity->dpnid, &msg, NMFNone); - return true; -} - -NetworkObjectInfo *NetworkServer::OnObjectCreate(const NetworkId &id, int owner, NetworkMessage *msg, NetworkMessageType type) -{ - if (NetworkObjectInfo *info = GetObjectInfo(id)) - { - /* - if (info->owner!=owner) - { // ownership change not possible in client-server architecture - return nullptr; - } - */ - // create message redefined - info->create.from = owner; - info->create.message = msg; - info->create.type = type; -#if DIAG_MP_OBJECT_LIFE - GObjLifeJournal.Add(id, Format("(%.3f) Redefine create message: from=%d type=%d",Glob.time.toFloat(), owner,type)); -#endif - return info; - } - - NetworkObjectInfo *info = new NetworkObjectInfo; - info->id = id; - info->owner = owner; - info->create.from = owner; - info->create.message = msg; - info->create.type = type; - info->pendingOwner = NO_CLIENT; //no pending - for (int i=0; i<_indexToPlayerId.Size(); i++) - { - info->CreatePlayerObjectInfo(PlayerIndex(i),_indexToPlayerId[i]); - } - DoAssert(_indexToPlayerId.Size()==info->playerToObjects.Size()); - _objects.put(info); - -#if DIAG_MP_OBJECT_LIFE - GObjLifeJournal.Add(id, Format("(%.3f) Create: owner=%d type=%d",Glob.time.toFloat(), owner,type)); -#endif - return info; -} - -/*! -\patch_internal 1.28 Date 10/29/2001 by Jirka -- Fixed: update objects only by messages by object's owner -*/ -NetworkObjectInfo *NetworkServer::OnObjectUpdate(NetworkId &id, int from, NetworkMessage *msg, NetworkMessageType type, NetworkMessageClass cls) -{ - DoAssert(!msg->HasDiff()) - NetworkObjectInfo *oInfo = GetObjectInfo(id); - if (!oInfo) - { - // if the update is from the owner and the object is listed as deleted, ignore the update - NetworkDeletedObjectInfo *delInfo = _deletedObjects.get(id); - if (delInfo && delInfo->owner!=from) - { - RptFObjectNotFound(id, type, from); - } - return NULL; - } - - if (oInfo->owner != from) - { - bool allowNonOwner = false; - if (from==BOT_CLIENT) - { - allowNonOwner = true; - } - if (!allowNonOwner) - { - RptF("Server: Update of object %d:%" OID_FORMAT" arrived from nonowner", id.creator.CreatorInt(), id.id); - return NULL; - } - } - - bool rejectedFromClient = from!=BOT_CLIENT && oInfo->rejected[cls]; - if (rejectedFromClient) - { - LogF("Received rejected %d for %" OID_FORMAT"",cls,oInfo->id.id); - } - - NetworkCurrentInfo &info = rejectedFromClient ? oInfo->currentRejected[cls] : oInfo->currentUpdate[cls]; - - NetworkMessageFormatBase *format = GetFormat(/*from, */type); - if (!format) - { - RptF("Server: Bad message %d(%s) format", (int)type, cc_cast(GetMsgTypeName(type))); - return NULL; - } - - if (info.from==from && info.message && info.message->time > msg->time) - { - if (info.from!=from) - { - LogF("Discarded different owner message for %" OID_FORMAT"(%d) because of time. %d!=%d",oInfo->id.id,rejectedFromClient,info.from,from); - } - - // do not update - if (DiagLevel >= 1) - DiagLogF("Server: update message is old (%.3f s)", info.message->time - msg->time); - return NULL; - } - - if (info.message && info.message->time > msg->time) - { - LogF("Passed old time for %" OID_FORMAT"(%d). %d!=%d",oInfo->id.id,rejectedFromClient,info.from,from); - } - - if (info.from!=from && info.message.NotNull()) - { - LogF("Changing from %d(%d) for %" OID_FORMAT" %d to %d",cls,rejectedFromClient,oInfo->id.id,info.from,from); - } - - - info.from = from; - info.type = type; - info.message = msg; - - RescanBestPosition(oInfo); - - // invalidate cached error - for (int i=0; iplayerToObjects.Size(); i++) - { - NetworkPlayerObjectInfo *poInfo = oInfo->playerToObjects[i]; - if (poInfo) poInfo->updates[cls].errorValid = false; - - } - - if (DiagLevel >= 4) - DiagLogF("Server: object %d:%" OID_FORMAT" updated", id.creator.CreatorInt(), id.id); - - return oInfo; -} - -void NetworkServer::RescanBestPosition( NetworkObjectInfo * oInfo ) -{ - const auto bestPosOld = oInfo->BestPosition(); - const Entity *veh = dyn_cast(oInfo->object); - if (veh && veh->GetHierarchyParent()) - { - return; - } - - oInfo->ScanBestPosition(this); - - const auto bestPosNew = oInfo->BestPosition(); - - _objects.onPosChanged(oInfo,bestPosOld,bestPosNew); - - if (veh && bestPosOld._pos.Distance2(bestPosNew._pos)>Square(0.001f)) - { - UpdateChildrenPos(veh); - return; - } -} - -void NetworkServer::UpdateChildrenPos(const Entity * veh) -{ - NetworkObjectInfo *oInfo = GetObjectInfo(veh->GetNetworkId()); - if (!oInfo) return; - const auto bestPosNew = oInfo->BestPosition(); - - veh->ForEachChildren([this,&bestPosNew](const NetworkObject *obj)->bool{ - NetworkObjectInfo *oInfo = GetObjectInfo(obj->GetNetworkId()); - if (oInfo) - { - const auto bestPosOld = oInfo->BestPosition(); - oInfo->_updInfo = bestPosNew; - - _objects.onPosChanged(oInfo,bestPosOld,bestPosNew); - } - return false; - }); -} - -bool NetworkServer::CheckBestPositionIntegrity() const -{ - // traverse all objects, for all of them check if BestPosition is up to date - bool ok = true; - _objects.forEach([&ok,this](const NetworkObjectInfo *oInfo){ - if (ok) ok = oInfo->CheckBestPositionIntegrity(this); - }); - return ok; -} - - -void NetworkServer::OnRejectChanged(const NetworkId &id, NetworkMessageClass cls, bool reject) -{ - // reset the updates we are sending to the object owner - NetworkObjectInfo *oInfo = GetObjectInfo(id); - if (oInfo) - { - LogF("Reject update %d %d for %" OID_FORMAT" to BOT_CLIENT",reject,cls,id.id); - oInfo->rejected[cls] = reject; - // the update from client ("currentRejected") was accepted by a bot-client, use it as a main object state - if (!reject) - { - oInfo->currentUpdate[cls] = oInfo->currentRejected[cls]; - // forget the bot-client provided update - oInfo->currentRejected[cls].message = nullptr; - oInfo->currentRejected[cls].from = 0; - RescanBestPosition(oInfo); - } - } -} - -NetworkDeletedObjectInfo ImplicitMapTraits::zombie = {NetworkId(CreatorId(-1),-1)}; -NetworkDeletedObjectInfo ImplicitMapTraits::null = {NetworkId(CreatorId(0),0)}; - -int NetworkServer::PerformObjectDestroy(const NetworkId &id) -{ - //DoAssert(CheckIntegrityOfPendingMessages()); - int owner = 0; - if (NetworkObjectInfo *info = GetObjectInfo(id)) - { - owner = info->owner; - - RemoveInitObjectDeleted(id); - //LogF("Performing Object Destroy for (%d:%" OID_FORMAT")", _objects[i]->id.creator.CreatorInt(), _objects[i]->id.id); - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &pInfo = *_players[i]; - int dpid = pInfo.dpid; - PlayerIndex playerIndex = GetPlayerIndex(dpid); - if (playerIndex<0) continue; // player index not created yet, player cannot be aware of any objects, cannot delete them - NetworkPlayerObjectInfo *poInfo = info->GetPlayerObjectInfo(playerIndex,dpid); - if (poInfo->updating) - { - DoAssert(pInfo._updating.CheckIntegrity()); - DoAssert(poInfo->IsInList()); - if (poInfo->IsInList()) pInfo._updating.Delete(poInfo); - DoAssert(pInfo._updating.CheckIntegrity()); - } - } - - NetworkDeletedObjectInfo delInfo; - delInfo.id = id; - delInfo.owner = info->owner; - delInfo.time = Glob.time; - _deletedObjects.put(delInfo); - - _objects.removeKey(id); - } - return owner; -} - -void NetworkServer::OnObjectDestroy(const NetworkId &id, int from) -{ - PerformObjectDestroy(id); - DeleteObjectMessage msg; - msg._creator = id.creator; - msg._id = id.id; - - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &pInfo = *_players[i]; - if (pInfo.clientState < NCSMissionReceived) continue; - if (pInfo.dpid == from) continue; - SendMsg(pInfo.dpid, &msg, NMFGuaranteed); - } -} - -int NetworkServer::UpdateObject(NetworkPlayerInfo *pInfo, NetworkObjectInfo *oInfo, NetworkMessageClass cls, NetMsgFlags dwFlags) -{ - if (!oInfo) - { - // TODO: BUG - DiagLogF("Server: Object not found"); - return -1; - } - - - // when sending to the bot-client use a rejected updated when available - NetworkCurrentInfo &info = pInfo->dpid==BOT_CLIENT && oInfo->rejected[cls] && oInfo->currentRejected[cls].message.NotNull() ? oInfo->currentRejected[cls] : oInfo->currentUpdate[cls]; - if (!info.message) return -1; - - - // SendMsg may change currentRejected, therefore info.message may be no longer valid after it - Ref msg = info.message; - - NetworkMessageType type = info.type; - int to = pInfo->dpid; - - PlayerIndex index = GetPlayerIndex(to); - if (index<0) return -1; - - if (DebugMeBoy(oInfo->id)) - { - LogF("*** DebugMeBoy: {%d:%" OID_FORMAT"} UpdateObject to %d", oInfo->id.creator.CreatorInt(), oInfo->id.id, to); - } - - - // make sure the children are updating, as the message can contain references to them - if (oInfo->object && pInfo->dpid!=BOT_CLIENT) - { - oInfo->object->ForEachChildren([this,index,pInfo,oInfo,type](const NetworkObject *obj)->bool{ - NetworkObjectInfo *objInfo = GetObjectInfo(obj->GetNetworkId()); - if (!objInfo) - { - BString<256> context; - sprintf(context, " ForEachChildren of %s", cc_cast(oInfo->object->GetDebugName())); - RptFObjectNotFound(obj->GetNetworkId(), type, -1, context); - return false; - } - NetworkPlayerObjectInfo *pObjInfo = objInfo->GetPlayerObjectInfo(index,pInfo->dpid); - if (!pObjInfo->updating) - { - DoAssert(objInfo->create.message.NotNull()); - if (objInfo->create.message.NotNull()) - { - LogF("%s to %d: children %s starting updating",cc_cast(oInfo->GetDebugName()),pInfo->dpid,cc_cast(obj->GetDebugName())); - SendCreateMessage(pInfo->dpid, *objInfo, pObjInfo); - pObjInfo->updating = true; - /* - Can be called safely from NetworkServer::CreateObjectsList in spite of existence of local updatingNew list, which is not updated here. - If the children was already visited in the forEachInBubble loop, it was already marked as updating and we are not processing it here. - If it was not visited yet, pInfo.markAsUpdating(poInfo,updatingNew) will be called on it once it will be visited. - */ - pInfo->markAsUpdating(pObjInfo); - } - } - else - { - //LogF("%s to %d: children %s already updating",cc_cast(oInfo->GetDebugName()),pInfo->dpid,cc_cast(obj->GetDebugName())); - } - return false; - }); - } - - // update object info - NetworkPlayerObjectInfo *poInfo = oInfo->GetPlayerObjectInfo(index,to); - - DoAssert(!msg->HasDiff()); - - Ref toSend = msg; - if (_updatesGuaranteed && to!=BOT_CLIENT) - { - NetworkMessage *refMsg = poInfo->updates[cls].lastSentMsg; - if (refMsg) - { - MessageDiffCreate diff; - toSend = toSend->Clone(); - toSend->CreateDiff(refMsg,diff); - toSend->StoreDiff(diff); - } - } - - DWORD dwMsgId = SendMsg(to, toSend, type, dwFlags, poInfo); - if (dwMsgId == 0xFFFFFFFF) return -1; - - // message will be stored and used again, it must not be diffed - DoAssert(!msg->HasDiff()); - msg->ProtectDiff(); - - poInfo->updates[cls].lastSentMsg = msg; - poInfo->updates[cls].errorValid = false; - - return toSend->size; -} - -//! Simplified enumeration of array items -#define FOR_EACH(type,var,array) \ - for (type *var = array.Data(), *end = array.Data() + array.Size(); var < end; var++) - -void NetworkServer::DestroyAllObjects() -{ - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo *player = _players[i]; - player->person = NetworkId::Null(); - player->_delayedMessages.Clear(); - player->_updating.Clear(); - } - _objects.reset(); - _deletedObjects.reset(); -#if DIAG_MP_OBJECT_LIFE - GObjLifeJournal.Clear(); -#endif -//CheckInitMessages(_initMessages, "before _initMessages.Clear()"); - if ( _initMessages.Size() ) - { - // log GetAddInitAndRemoveOverridden statistics into the mpStatistics.log file - LogMPStatistics( GetAddInitAndRemoveOverriddenStat() ); - } - _initMessages.Clear(); - _jipMarkerInfos.Clear(); - - if (_indexToPlayerId.Size()>=1) - { - DoAssert(_indexToPlayerId[0]==BOT_CLIENT); - _indexToPlayerId.Resize(1); - LogF("**** Player index reset"); - } -//CheckInitMessages(_initMessages, "after _initMessages.Clear()"); - - // avoid id duplicity at next missions - // _nextId = 0; -} - - -NetworkMessageFormatBase *NetworkServer::GetFormat(/*int client, */int type) -{ - Assert(type >= 0); - if (type >= NMTN) return NULL; // unknown message - return GMsgFormats[type]; -} - -const NetworkMessageFormatBase *NetworkServer::GetFormat(/*int client, */int type) const -{ - Assert(type >= 0); - if (type >= NMTN) return NULL; // unknown message - return GMsgFormats[type]; -} - -void NetworkServer::CreateMission(RString mission, RString world) -{ - _originalName = mission; -#if _ENABLE_UNSIGNED_MISSIONS - if (mission.GetLength() > 0) - { - RString filename = RString("mpmissions\\") + mission + RString(".") + world; - CreateMPMissionBank(filename, world); - } - else - { - GFileBanks.Remove("mpmissions\\__cur_mp."); - } -#endif // _ENABLE_UNSIGNED_MISSIONS -} - -/// detect client-side localization, if possible use it -LocalizedString ClientSideLocalizedString(RString value, RString mission) -{ - // if possible, localize client-side - RString table; - RString name = TryLocalize(value,table); - if (!strcmpi(table,"global")) - { - // if localized using global table, client can localize it - return LocalizedString(LocalizedString::Stringtable,(const char *)value+1); - } - else - { - if (value[0]=='@') - { - RptF( - "%s: string %s cannot be localized client-side - move to global stringtable", - cc_cast(mission),cc_cast(value) - ); - } - return LocalizedString(LocalizedString::PlainText,name); - } -} - - -#define DIFF_SET(MessageName,name,ids,XX) _missionHeader._diff##name = item.flags[DT##name]; - -void NetworkServer::UndefMissionParams() -{ - _param1 = _param2 = FLT_MAX; - _paramsArray.Clear(); -} - -void NetworkServer::InitMission(int difficulty, RString displayName, bool noCopy, RString owner, bool isCampaignMission) -{ - PROFILE_SCOPE_EX(nsIM1, network) - // unlock session - _sessionLocked = false; - - _missionHeader._estimatedEndTime = TIME_MIN; - _missionHeader._enableAIDisable = !isCampaignMission; - - // mission description - _missionHeader._gameType = RString(); - ConstParamEntryPtr header = ExtParsMission.FindEntry("Header"); - if (header) - { - ConstParamEntryPtr gameType = header->FindEntry("gameType"); - if (gameType) _missionHeader._gameType = *gameType; - } - - _missionHeader._island = Glob.header.worldname; - const ArcadeIntel &intel = CurrentTemplate->Intel(); - if (displayName.GetLength() > 0) - { - _missionHeader._name = LocalizedString(LocalizedString::PlainText,displayName); - } - else - { - _missionHeader._name = ClientSideLocalizedString(intel.briefingName,intel.briefingName); - if (_missionHeader._name._id.GetLength() == 0) - { - _missionHeader._name = LocalizedString( - LocalizedString::PlainText, - _originalName.GetLength() > 0 ? _originalName : Glob.header.filename - ); - } - } - - RString missionName = _missionHeader._name.GetLocalizedValue(); - - _missionHeader._description = ClientSideLocalizedString(intel.briefingDescription,missionName); - - // ADDED in patch 1.01 - checks of addons - _missionHeader._addOns = CurrentTemplate->AddOns(); - // make sure addon owning the mission is present on clients - if (owner.GetLength() > 0) _missionHeader._addOns.AddUnique(owner); - - // ADDED in patch 1.01 - disable AI -#if _ENABLE_AI - _missionHeader._disabledAI = false; - ConstParamEntryPtr disabledAI = ExtParsMission.FindEntry("disabledAI"); - if (disabledAI) _missionHeader._disabledAI = *disabledAI; -#endif - - // difficulty - _missionHeader._diffName = Glob.config.diffNames.GetName(difficulty); - const DifficultySettings &item = Glob.config.diffSettings[difficulty]; - DIFFICULTY_TYPE_ENUM(DIFF_SET, ignored, ignored) - - _missionHeader._aiKills = false; - ConstParamEntryPtr aiKills = ExtParsMission.FindEntry("aiKills"); - if (aiKills) _missionHeader._aiKills = *aiKills; - - _missionHeader._createPlayers = false; //TODO - - // handling players after disconnect - ConstParamEntryPtr entry = ExtParsMission.FindEntry("destroyDisconnected"); - if (entry) _destroyDisconnected = *entry; - else _destroyDisconnected = true; - - // mission parameters - entry = ExtParsMission.FindEntry("titleParam1"); - _missionHeader._titleParam1 = ClientSideLocalizedString(entry ? entry->operator RString() : RString(""),missionName); - _missionHeader._valuesParam1.Resize(0); - _missionHeader._textsParam1.Resize(0); - entry = ExtParsMission.FindEntry("valuesParam1"); - if (entry) - { - int n = entry->GetSize(); - _missionHeader._valuesParam1.Resize(n); - for (int i=0; iGetSize() != n) entryTexts = entry; - - if (entryTexts) - { - _missionHeader._textsParam1.Resize(n); - for (int i=0; ioperator RString() : RString(""),missionName); - _missionHeader._valuesParam2.Resize(0); - _missionHeader._textsParam2.Resize(0); - entry = ExtParsMission.FindEntry("valuesParam2"); - if (entry) - { - int n = entry->GetSize(); - _missionHeader._valuesParam2.Resize(n); - for (int i=0; iGetSize() != n) entryTexts = entry; - - if (entryTexts) - { - _missionHeader._textsParam2.Resize(n); - for (int i=0; i 0; - - _missionHeader._noCopy = noCopy; - - //----------------------------------------------------------------// - //----------------------------------------------------------------// - //array of user mission params - // mission parameters - - _missionHeader._valuesParamArray.Resize(0); - _missionHeader._textsParamArray.Resize(0); - _missionHeader._defaultParamArray.Resize(0); - _missionHeader._titleParamArray.Resize(0); - _missionHeader._sizesParamArray.Resize(0); - if (setParams) _paramsArray.Clear(); - - - //copy param1/2 to new array - _missionHeader._titleParamArray.Add(_missionHeader._titleParam1); - _missionHeader._sizesParamArray.Add(0); - for(int i=0; i<_missionHeader._valuesParam1.Size();i++) - { - _missionHeader._valuesParamArray.Add(_missionHeader._valuesParam1[i]); - _missionHeader._textsParamArray.Add(_missionHeader._textsParam1[i]); - _missionHeader._sizesParamArray[_missionHeader._sizesParamArray.Size()-1]++; - } - _missionHeader._defaultParamArray.Add(_missionHeader._defValueParam1); - if (setParams) _paramsArray.Add(_param1); - - _missionHeader._titleParamArray.Add(_missionHeader._titleParam2); - _missionHeader._sizesParamArray.Add(0); - for(int i=0; i<_missionHeader._valuesParam2.Size();i++) - { - _missionHeader._valuesParamArray.Add(_missionHeader._valuesParam2[i]); - _missionHeader._textsParamArray.Add(_missionHeader._textsParam2[i]); - _missionHeader._sizesParamArray[_missionHeader._sizesParamArray.Size()-1]++; - } - _missionHeader._defaultParamArray.Add(_missionHeader._defValueParam2); - if (setParams) _paramsArray.Add(_param2); - - //read secondary parameters - ConstParamEntryPtr paramsDesc = ExtParsMission.FindEntry("Params"); - //for all parameters add CStatic and CListBox to container - if(paramsDesc) for(int i=0; i< paramsDesc->GetEntryCount();i++ ) - { - //create listbox content text (parameters names) - ParamEntryVal parameterDesc = paramsDesc->GetEntry(i); - - ConstParamEntryPtr entry = parameterDesc.FindEntry("title"); - _missionHeader._titleParamArray.Add(ClientSideLocalizedString(entry ? entry->operator RString() : RString(""),missionName)); - _missionHeader._sizesParamArray.Add(0); - - entry = parameterDesc.FindEntry("values"); - if (entry) - { - int n = entry->GetSize(); - - for (int i=0; iGetSize() != n) entryTexts = entry; - - if (entryTexts) - { - for (int i=0; i=0 && dir[i] == '\\') dir = dir.Substring(0, i); // remove trailing '\' - -#if _VBS2 && _VBS2_LITE - void VBS2EncryptMission(RString fileName,RString directory); - VBS2EncryptMission(_missionBank,dir); -#else - // TODO: do not create temporary __CUR_MP - mgr.Create(_missionBank, dir); -#endif - } - } -#endif // _ENABLE_UNSIGNED_MISSIONS - -#if _USE_BATTL_EYE_SERVER - //ASSERT_RLS(beName.GetLength() > 0, ("Empty mission name for BattlEye service!!!")); - _beIntegration.LoadedMission(beName); -#endif - - { - QIFStream f; - f.open(_missionBank); - - CRCCalculator crc; - crc.Reset(); - f.copy(crc); - _missionHeader._fileCRC = crc.GetResult(); - - _missionHeader._fileSizeH = 0; - _missionHeader._fileSizeL = f.tellg(); - } - -#if _GAMES_FOR_WINDOWS - // set the properties and contexts for matchmaking - // - MPType - int gameType = 0; - if (_missionHeader._gameType.GetLength() > 0) - { - ConstParamEntryPtr cls = (Pars >> "CfgMPGameTypes").FindEntry(_missionHeader._gameType); - if (cls) gameType = *cls >> "id"; - } - GSaveSystem.SetContext(CONTEXT_GAME_MPTYPE, gameType); - // - World - int worldId = 0; - if (_missionHeader._island.GetLength() > 0) - { - ConstParamEntryPtr cls = (Pars >> "CfgWorlds").FindEntry(_missionHeader._island); - if (cls) worldId = *cls >> "worldId"; - } - GSaveSystem.SetContext(CONTEXT_GAME_WORLD, worldId); - // - Difficulty - GSaveSystem.SetContext(CONTEXT_GAME_DIFFICULTY, difficulty); - // - MPMission - int missionId = 0; - // TODOXNET: mission identification - GSaveSystem.SetContext(CONTEXT_GAME_MPMISSION, missionId); -#endif - _missionHeader._forceCameraType = 0; - _missionHeader._environmentTimeMul = 0; -#if _ENABLE_DEDICATED_SERVER - { - ConstParamEntryPtr entry = _serverCfg.FindEntry("disable3rdPerson"); - if(entry) - _missionHeader._forceCameraType = *entry; - - ConstParamEntryPtr entry2 = _serverCfg.FindEntry("environmentTimeMul"); - if(entry2) - _missionHeader._environmentTimeMul = *entry2; - } -#endif - - // send mission description and roles - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.clientState < NCSConnected) continue; - info.missionFileValid = false; - info.paramFileValid = GetMissionParameters().GetLength() == 0; - // set missionFileValid first, as SendMissionInfo on the bot-client will already use it on the receiving end - SendMissionInfo(info.dpid); - } - - if (header) - { -/* - int minPlayers = -1; - ConstParamEntryPtr entry = header->FindEntry("minPlayers"); - if (entry) minPlayers = *entry; -*/ - int maxPlayers = -1; - entry = header->FindEntry("maxPlayers"); - if (entry) maxPlayers = *entry; - - if (maxPlayers > 0) - { - _missionHeader._maxPlayers = maxPlayers; - } - } -} - -void NetworkServer::UpdateMaxPlayers(int maxPlayers, int privateSlots) -{ - _totalSlots = maxPlayers; - - maxPlayers = GetMaxPlayers(); -#if _ENABLE_DEDICATED_SERVER - if (IsDedicatedServer()) maxPlayers++; // one more slot for the dedicated server bot client -#endif - - if(privateSlots > maxPlayers) - privateSlots = maxPlayers; - if (_server) _server->UpdateMaxPlayers(maxPlayers); -# if _ENABLE_GAMESPY - ChangeStateQR(); -# endif - -#if _GAMES_FOR_WINDOWS - // update the session description - if (_parent) _parent->UpdateSession(maxPlayers, privateSlots); -#endif -} - -void NetworkServer::ChangeOwner(const NetworkId &id, int from, int to) -{ - if (from == to) return; - if (id.IsNull()) return; - - NetworkObjectInfo *oInfo = GetObjectInfo(id); - if (!oInfo) - { - RptFObjectNotFound(id,"NetworkServer::ChangeOwner",from); - return; - } - - if (oInfo->pendingOwner!=NO_CLIENT) - { // change of owner of this object is already pending - oInfo->pendingOwner = to; // BUT change pending owner to new one - return; - } - oInfo->pendingOwner = to; // mark this change of owner as pending - - ChangeOwnerMessage msg; - msg._creator = id.creator; - msg._id = id.id; - msg._owner = to; - msg._disconnected = false; -#if DIAG_MP_OBJECT_LIFE - GObjLifeJournal.Add(id, Format("(%.3f) ChangeOwner: from=%d to=%d",Glob.time.toFloat(), from, to)); -#endif - SendMsg(from, &msg, NMFGuaranteed); - //note: new owner will be notified after the ownerChanged returns from previous owner - // so do not SendMsg(to, &msg, NMFGuaranteed); now - - if (DebugMeBoy(id)) - { - LogF("*** DebugMeBoy: {%d:%" OID_FORMAT"} ChangeOwner from %d to %d", oInfo->id.creator.CreatorInt(), oInfo->id.id, from, to); - - } -} - -void NetworkServer::SendMissionInfo(int to, bool onlyPlayers) -{ - _missionHeader._updateOnly = false; - - if (!onlyPlayers) - { - // send at last, client will update its state as reaction - SendMsg(to, &_missionHeader, NMFGuaranteed); // LOGGED IN -> MISSION SELECTED - - MissionParamsMessage msg; - msg._param1 = _param1; - msg._param2 = _param2; - msg._paramsArray = _paramsArray; - msg._updateOnly = false; - SendMsg(to, &msg, NMFGuaranteed); // MISSION SELECTED -> MISSION ASKED - } -} - -void Encrypt(QOStrStream &out,const unsigned char *publicKey, int keySize); - -//{ DEDICATED SERVER SUPPORT -bool NetworkServer::IsDedicatedBotClient(int dpnid) const -{ -#if _ENABLE_DEDICATED_SERVER - return _dedicated && dpnid == BOT_CLIENT; -#else - return false; -#endif -} -//} - -//! Text representation of NetworkServerState enum values -const EnumName NetworkServerStateNames[]= -{ - EnumName(NSSNone, "NONE"), - EnumName(NSSSelectingMission, "SELECTING MISSION"), - EnumName(NSSEditingMission, "EDITING MISSION"), - EnumName(NSSAssigningPlayers, "ASSIGNING PLAYERS"), - EnumName(NSSSendingMission, "SENDING MISSION"), - EnumName(NSSLoadingGame, "LOADING GAME"), - EnumName(NSSPlaying, "PLAYING"), - EnumName(NSSMissionAborted, "MISSION ABORTED"), - EnumName() -}; - -RString NetworkServer::GetAddInitAndRemoveOverriddenStat() -{ - int stats[NMTN]; - for (int i=0; i= 0 && type < NMTN ) stats[type]++; - } - - RString retValStr; - retValStr.CreateBuffer(NMTN * 256); // 256 chars for each line of statistics should be enough - char *buf = retValStr.MutableData(); - sprintf(buf, "AddInitAndRemoveOverridden statistics ... total messages = %d\n", _initMessages.Size()); - for (int i=0; i0 ) - { - RString name = GetMsgTypeName( (NetworkMessageType)i ); - RString newLine = Format("%d ... %s\n", stats[i], cc_cast(name)); - strcat(buf, newLine); - } - } - strcat(buf, "\n\n"); - return retValStr; -} - - -void NetworkServer::OnChangedOnPlayerConnecting(GameValuePar codeValue) -{ - for (int i=0; i<_players.Size(); i++) - { - if (_players[i]->dpid==BOT_CLIENT) - { -#if _ENABLE_DEDICATED_SERVER - bool localDedicated = _dedicated; -#else - bool localDedicated = false; -#endif - if (!localDedicated) OnPlayerConnecting(_players[i]->dpid,codeValue); - } - else if (_players[i]->clientState>=NCSGameLoaded) - { - // can any player be in such state? - OnPlayerConnecting(_players[i]->dpid,codeValue); - } - } -} - - - -void ResetGlobalEventHandlers(); - -//! Map NetworkServerState enum values to its text representation -template<> -const EnumName *GetEnumNames(NetworkServerState dummy) {return NetworkServerStateNames;} - -/*! -\patch 1.32 Date 11/26/2001 by Jirka -- Fixed: players' states are properly send to all clients -\patch 5142 Date 3/16/2007 by Jirka -- Fixed: MP - handling / reporting the current and maximum number of players was wrong sometimes -\patch 5154 Date 5/3/2007 by Jirka -- Fixed: MP mission statistics can be written to the file given by command line argument -ranking=... -\patch 5170 Date 10/8/2007 by Bebul -- New: Command line argument -ranking=... was removed. MP mission statistics can be written to file specified by logFile entry in the server config. -*/ - -void NetworkServer::SetServerState(NetworkServerState state) -{ -//((TO_BE_REMOVED_IN_FINAL -#if _ENABLE_PERFLOG - RptF("### Server: SetServerState to %s", (const char *)FindEnumName(state)); -#endif -//))TO_BE_REMOVED_IN_FINAL - - // Transition graph: - switch (state) - { - case NSSNone: - // nothing to do - break; - case NSSSelectingMission: - GNetworkManager.DestroyAllObjects(); - break; - case NSSEditingMission: - DoAssert(_serverState == NSSSelectingMission); - // nothing to do - break; - case NSSAssigningPlayers: - break; - case NSSSendingMission: - DoAssert(_serverState == NSSAssigningPlayers); - // only bot client need to advance to PlayerAssigned state, normal clients are driven through DisplayClient logic - if (GetClientState(BOT_CLIENT) == NCSMissionAsked) - { - //RptF("### Server: SetClientState NCSPlayerAssigned to BOT_CLIENT"); - SetClientState(BOT_CLIENT, NCSPlayerAssigned); - } - - // reset _jipProcessed flag for all players - for (int i=0; i<_players.Size(); i++) - { - _players[i]->_jipProcessed=false; - } - break; - case NSSLoadingGame: - _serverTimeOfEstimatedEnd = _secondsToEstimatedEnd = 0; - for (int i=0; i<_players.Size(); i++) - { - ServerTimeMessage stmsg; - _serverTime = ::GetTickCount()-_serverTimeInitTickCount; // update _serverTime - stmsg._time = _serverTime; - stmsg._endTime = _serverTimeOfEstimatedEnd; - SendMsg(_players[i]->dpid, &stmsg, NMFGuaranteed | NMFHighPriority); - } - - for (int i=0; i<_players.Size(); i++) - { - CreatePlayerIndex(_players[i]->dpid); - } - break; - case NSSPlaying: - // recompute estimatedTimeOfEnd to be without time spent in briefing - _serverTime = ::GetTickCount() - _serverTimeInitTickCount; //make it fresh - if (_serverTimeOfEstimatedEnd) //recompute - { - _serverTimeOfEstimatedEnd = _serverTime + _secondsToEstimatedEnd; - for (int i=0; i<_players.Size(); i++) - { - // send _serverTime on each client - ServerTimeMessage stmsg; - _serverTime = ::GetTickCount()-_serverTimeInitTickCount; // update _serverTime - stmsg._time = _serverTime; - stmsg._endTime = _serverTimeOfEstimatedEnd; - SendMsg(_players[i]->dpid, &stmsg, NMFGuaranteed | NMFHighPriority); - } - } - break; - case NSSMissionAborted: - CallOnPlayerDisconnected(); - ResetGlobalEventHandlers(); - break; - } - - #if _ENABLE_MP - if (state == NSSAssigningPlayers && _serverState > NSSAssigningPlayers) - { - // cancel all messages - updates from last sessions, file transfers etc. - // !!! cannot do it in this way - some messages are important - // _server->CancelAllMessages(); - - // reset all camera information from previous session - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &p = *_players[i]; - p.cameraPosition = InvalidCamPos; - p.cameraPositionTime = TIME_MIN; - } - } - #endif - - if (state == NSSPlaying) _missionHeader._start = GlobalTickCount(); - - #if _ENABLE_MP - if (state == NSSMissionAborted && _serverState == NSSPlaying) - { - // end of mission - update log file - FILE *LogFile = GetNetworkManager().GetDedicatedServerLogFile(); - if ( LogFile ) - { - ParamFile f; - ParamClassPtr root = f.AddClass("Session"); - if (root) - { - root->Add("mission", _missionHeader.GetLocalizedMissionName()); - root->Add("island", _missionHeader._island); - root->Add("gameType", _missionHeader._gameType); - root->Add("duration", 0.001f * (GlobalTickCount() - _missionHeader._start)); - } - // append ranking statistics to logFile - QOStrStream out; - f.Save(out, 0, "\r\n"); - fwrite(out.str(), 1, out.pcount(), LogFile); - // flush is only at the end of mission (here) or some rare occasions - fflush(LogFile); - } - } - #endif - -#if _GAMES_FOR_WINDOWS - // Xbox Live - start / end the session - if (state == NSSPlaying) - { - if (_serverState != NSSPlaying) - { - _parent->StartSession(); - } - } - else if (_serverState == NSSPlaying) - { - _parent->EndSession(); - } - - if (_parent->GetSessionType() == STRanked) - { - // Ranked match - finish the session when the first game is finished - if (_serverState >= NSSPlaying && state < NSSPlaying) - { - Done(); - return; - } - // Ranked match - close the possibility to join and ask for arbitration - if (state >= NSSSendingMission && _serverState < NSSSendingMission) - { - LockSession(); - // ask all clients for arbitration - AskForArbitrationMessage msg; - msg._sessionNonce = _parent->GetSessionNonce(); - for (int i=0; i<_identities.Size(); i++) - { - int player = _identities[i].dpnid; - if (player != BOT_CLIENT) SendMsg(player, &msg, NMFGuaranteed); - } - } - } -#endif - - _serverState = state; - _serverStateTime = GlobalTickCount(); - _serverTimeOutSent = INT_MAX; // assume no value reported yet - if (state == NSSNone) return; // cannot send messages - - // DS selecting the mission - set the correct maxPlayers - if (state == NSSAssigningPlayers) - { - //{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - if (IsDedicatedServer()) - { -#if _GAMES_FOR_WINDOWS - // update of max. number of players - int perClient = 32000; - int round = 2; - ConstParamEntryPtr header = ExtParsMission.FindEntry("Header"); - if (header) - { - ConstParamEntryPtr entry = header->FindEntry("bandwidthPerClient"); - if (entry) perClient = *entry; - entry = header->FindEntry("playerCountMultipleOf"); - if (entry) round = *entry; - } - int maxPlayers = GetMaxPlayersSafe(perClient, round); - int GetDSPrivateSlots(); - int maxPrivate = GetDSPrivateSlots(); - saturateMin(maxPrivate, maxPlayers); - UpdateMaxPlayers(maxPlayers, maxPrivate); -#else - UpdateMaxPlayers(INT_MAX, 0); -#endif - } -#endif - //} - } - - // DS leaving the mission - reset the original maxPlayers - if (state == NSSSelectingMission) - { - //{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - if (IsDedicatedServer()) - { -#if _GAMES_FOR_WINDOWS - // update of max. number of players - int perClient = 32000; - int round = 1; - int maxPlayers = GetMaxPlayersSafe(perClient, round); - int GetDSPrivateSlots(); - int maxPrivate = GetDSPrivateSlots(); - saturateMin(maxPrivate, maxPlayers); - UpdateMaxPlayers(maxPlayers, maxPrivate); -#else - UpdateMaxPlayers(INT_MAX, 0); -#endif - } -#endif - //} - } - - { - // send to all players - ServerStateMessage msg; - msg._serverState = state; - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.clientState < NCSConnected) continue; - if (!IsDedicatedServer() || info.dpid!=BOT_CLIENT) // bot-client on a dedicated server has no identity - { - if (!FindIdentity(info.dpid)) continue; // prevent clients with unknown identity to proceed with the connection - } - SendMsg(info.dpid, &msg, NMFGuaranteed); - } - } - - UpdateMatchmakingDescription(true); - -#if _GAMES_FOR_WINDOWS - // set the properties and contexts for matchmaking - // - ServerState - GSaveSystem.SetContext(CONTEXT_GAME_SERVERSTATE, state); - // reset the values which have not yet sense - if (state < NSSAssigningPlayers) - { - // - MPType - GSaveSystem.SetContext(CONTEXT_GAME_MPTYPE, 0); - // - World - GSaveSystem.SetContext(CONTEXT_GAME_WORLD, 0); - // - Difficulty - GSaveSystem.SetContext(CONTEXT_GAME_DIFFICULTY, 0); - // - MPMission - GSaveSystem.SetContext(CONTEXT_GAME_MPMISSION, 0); - } - if (state < NSSPlaying) - { - // - TimeLeft - GSaveSystem.SetProperty(PROPERTY_GAME_TIMELEFT, 0); - } -#endif - - if (state == NSSEditingMission) - { - // No Load should be after mission was edited - bool DeleteSaveGames(); - DeleteSaveGames(); - bool DeleteWeaponsFile(); - DeleteWeaponsFile(); - } -} - -/*! -\patch 5111 Date 12/22/2006 by Jirka -- Fixed: DS - Mission voting results show correctly localized mission name for missions in addons -*/ - -void NetworkServer::MissionVotingEcho() -{ - const Voting *miss = _votings.Find(NCMTMission); - const Voting *diff = _votings.Find(NCMTDifficulty); - - // if the voting is no longer here, it has probably completed - if (diff && miss) - { - VotingMissionProgressMessage progress; - const AutoArray *diffValue = diff->GetValue(); - if (diffValue) - { - progress._diff = RString(diffValue->Data(),diffValue->Size()); - } - AutoArray order; - miss->GetOrder(order); - for (int i=0; i &missValue = order[i].vote->value; - int missVotes = order[i].count; - LocalizedString FindLocalizedBriefingName(RString path); - RString name = RString(missValue.Data(),missValue.Size()); - - RString mission = name; - RString dir; - - const char *ext = strrchr(name, '.'); - if (ext) mission = RString(name, ext - cc_cast(name)); - -#if _ENABLE_MISSION_CONFIG - ConstParamEntryPtr entry = (Pars >> "CfgMissions" >> "MPMissions").FindEntry(mission); - if (entry) - dir = (*entry) >> "directory"; - else -#endif - dir = RString("MPMissions\\") + name; - - LocalizedString displayName = FindLocalizedBriefingName(dir); - if (displayName._id.GetLength() == 0) - { - displayName = LocalizedString(LocalizedString::PlainText,name); - } - - progress._missions.Add(displayName); - progress._missionVotes.Add(missVotes); - } - for (int i=0; i<_players.Size(); i++) - { - const NetworkPlayerInfo &player = *_players[i]; - // notify all clients who might be interested - if (player.clientState >= NCSConnected && player.clientState<=NCSMissionSelected) - { - SendMsg(player.dpid, &progress, NMFGuaranteed); - } - } - } -} - -void NetworkServer::UpdateMatchmakingDescription(bool changedParams) -{ - -//{ QUERY & REPORTING SDK -#if _ENABLE_GAMESPY - ChangeStateQR(); -#endif -//} - - UpdateSessionDescription(); - - // update both broadcast and matchmaking - _timeLeftLastValueBcast = _timeLeftLastValue = GetSessionTimeLeft(); - _timeLeftLastTime = GlobalTickCount(); -} - -void NetworkServer::DisconnectPlayer(int dpnid, NetworkId playerPerson) -{ - PlayerIndex playerIndex = GetPlayerIndex(dpnid); - - // player is disconnecting from game, return ownership of objects to bot client - - AutoArray owned; // we cannot let SendMsg to manipulate _objects while iterating it - _objects.forEach([this,playerIndex,dpnid,&owned](NetworkObjectInfo *oInfo) - { - if (playerIndex>=0) oInfo->DeletePlayerObjectInfo(playerIndex,dpnid); - - for (int j=NMCUpdateFirst; jcurrentUpdate[j]; - if (info.from == dpnid) - { - info.from = BOT_CLIENT; - info.message = NULL; - } - } - - RescanBestPosition(oInfo); - - // owner of this object has disconnected - possible pendingOwner can take the full ownership - // or BOT_CLIENT should take it otherwise - if (oInfo->owner == dpnid) - { - owned.Add(oInfo->id); - } - }); - - - if (playerIndex>=0) - { - _indexToPlayerId.DeleteAt(playerIndex); - LogF("**** Player %d index %d removed, %d total",dpnid,int(playerIndex),_indexToPlayerId.Size()); - } - else - { - LogF("**** Player %d index not removed, %d total",dpnid,_indexToPlayerId.Size()); - } - - for (int i=0; i oInfo; - _objects.get(owned[i],oInfo); - if (!oInfo) continue; - if (oInfo->pendingOwner!=NO_CLIENT && oInfo->pendingOwner!=dpnid) - { - NetworkPlayerInfo *pInfo = GetPlayerInfo(oInfo->pendingOwner); - if (!pInfo) - { // new owner has probably disconnected meanwhile - oInfo->pendingOwner = BOT_CLIENT; - } - oInfo->owner = oInfo->pendingOwner; - } - else - { - oInfo->owner = BOT_CLIENT; - } - // not pending now - oInfo->pendingOwner = NO_CLIENT; - - _objects.get(owned[i],oInfo); - // change the owner - if (!oInfo->id.IsNull()) - { - ChangeOwnerMessage msg; - msg._creator = oInfo->id.creator; - msg._id = oInfo->id.id; - msg._owner = oInfo->owner; - msg._disconnected = oInfo->id == playerPerson; // mark player person to enable clean up on it - SendMsg(oInfo->owner, &msg, NMFGuaranteed); - - // destroy the person - if (msg._disconnected && _destroyDisconnected) - { - // playable person with AI disabled - destroy unit - Person *person = dyn_cast(_parent->GetObject(playerPerson)); - if (person) - { - Ref agent = person->Brain(); - - if (agent) - { - // Get out from vehicle - Transport *vehicle = agent->GetVehicleIn(); - if (vehicle) - { - agent->DoGetOut(vehicle, true, false); - } - } - - // detach brain (to avoid respawn during SetDamage) - person->SetBrain(NULL); - - // destroy person - person->SetDamage(1,true); - person->HideBody(); - // DeleteObject(person->GetNetworkId(), true); - } - } - - // owner is chosen so send waiting messages - for ( int i=0; i>oInfo->waitingMessages.Size(); i++ ) - { - WaitingMessageInfo *wMsgInfo = oInfo->waitingMessages[i]; - SendMsg(oInfo->owner, wMsgInfo->msg, wMsgInfo->type, NMFGuaranteed, NULL); - } - oInfo->waitingMessages.Clear(); - } - } - - _radioSubscribers.OnPlayerDisconnected(dpnid); - - CleanupPlayerMessage msg; - msg._dpnid = dpnid; - msg._creator = playerPerson.creator; - msg._id = playerPerson.id; - SendMsg(BOT_CLIENT, &msg, NMFGuaranteed); -} - -bool NetworkServer::IsPlayerOnChannel(int dpnid, int channel, int roleIndex2) -{ - if (channel==CCGlobal || channel==CCSystem) return true; - if (channel==CCDirect || channel==CCNone) return false; - - return false; -} - -bool IsEqualMarker(NetworkMessage *marker1, NetworkMessage *marker2); -bool IsEqualMarker(RString name, NetworkMessage *marker2); - -void NetworkServer::AddJIPMarkerInfo(NetworkMessage *marker, int channel, int from) -{ - for (int i=0; i<_jipMarkerInfos.Size(); i++) - { - if ( IsEqualMarker(marker, _jipMarkerInfos[i]._marker) ) - { - _jipMarkerInfos[i]._marker = marker; - return; - } - } - - JIPMarkerInfo &info = _jipMarkerInfos.Append(); - info._marker = marker; - info._channel = channel; - info._roleIndex = -1; //TODO -} - -void NetworkServer::RemoveJIPMarkerInfo(RString name) -{ - for (int i=0; i<_jipMarkerInfos.Size(); i++) - { - if ( IsEqualMarker(name, _jipMarkerInfos[i]._marker) ) - { - _jipMarkerInfos.Delete(i); - return; - } - } -} - -void NetworkServer::SendInitMessages(int dpnid) -{ - for (int i=0; i<_initMessages.Size(); i++) - { - if (_initMessages[i].msg) - { - SendMsg(dpnid, _initMessages[i].msg, _initMessages[i].type, NMFGuaranteed, NULL); - } - } - for (int i=0; i<_jipMarkerInfos.Size(); i++) - { - JIPMarkerInfo &info = _jipMarkerInfos[i]; - if ( IsPlayerOnChannel(dpnid, info._channel, info._roleIndex) ) - { - NetworkMessageMarkerCreate *msg = new NetworkMessageMarkerCreate; - msg->_channel = info._channel; - msg->_marker = info._marker; - SendMsg(dpnid, msg, NMTMarkerCreate, NMFGuaranteed, NULL); - } - } - AutoArray &_subscribers = _radioSubscribers._subscribers; - for (int i=0; i<_subscribers.Size(); i++) - { - if (_subscribers[i].dpnid == dpnid) continue; - SubscribeRadiosMessage msg; - msg._player = _subscribers[i].dpnid; - msg._frequences = _subscribers[i].frequencies; - SendMsg(dpnid, &msg, NMFGuaranteed); - } -} - -void NetworkServer::OnPlayerConnecting(int dpnid) -{ - NetworkPlayerInfo *info = GetPlayerInfo(dpnid); - PlayerIdentity *identity = FindIdentity(info->dpid); - DoAssert(identity); - if (identity) - { - ::OnPlayerConnecting(dpnid,identity->id,identity->playerid,info->name); - } -} - -void NetworkServer::OnPlayerConnecting(int dpnid, GameValuePar codeValue) -{ - NetworkPlayerInfo *info = GetPlayerInfo(dpnid); - PlayerIdentity *identity = FindIdentity(info->dpid); - DoAssert(identity); - if (identity) - { - ::OnPlayerConnecting(dpnid,identity->id,identity->playerid,info->name,codeValue); - } -} - -void NetworkServer::ObjectUpdateAll(NetworkObjectInfo * info, int dpnid, NetMsgFlags flags) -{ - for (int cls=NMCUpdateFirst; clscurrentUpdate[cls].message) - { - if (info->currentUpdate[cls].type==NMTUpdateClientInfoDpid) continue; - NetworkPlayerInfo *pInfo = GetPlayerInfo(dpnid); - if (pInfo) UpdateObject(pInfo, info, (NetworkMessageClass)cls, flags); - } - } -} - -void NetworkServer::OnClientStateChanged(int dpnid, NetworkClientState state) -{ - PROFILE_SCOPE_EX(onClS, network) - NetworkClientState oldState = NCSNone; - - NetworkPlayerInfo *pInfo = GetPlayerInfo(dpnid); - Assert(pInfo); - if (pInfo) - { - oldState = pInfo->clientState; - if (oldState == state) return; -#if _ENABLE_PERFLOG - RptF("*** Server: OnClientStateChanged %s %s -> %s", (const char *)pInfo->name, (const char *)FindEnumName(pInfo->clientState), (const char *)FindEnumName(state)); -#endif - if (state == NCSPlayerAssigned && oldState > NCSPlayerAssigned) - return; // FIX: problems with mission launching - pInfo->clientState = state; - } - - //RptF("Server: OnClientStateChanged %s to %s", pInfo ? (const char *)pInfo->name : "NULL", (const char *)FindEnumName(state)); - - PlayerIdentity *identity = FindIdentity(dpnid); - if (identity) - { -#if _USE_BATTL_EYE_SERVER -#if _ENABLE_STEAM_MATCHMAKING - if (state == NCSPlaying && identity->clientState != NCSPlaying) - { - _beIntegration.PlayerGoesInGame(identity->dpnid); - } - if (identity->clientState == NCSPlaying && state != NCSPlaying) - { - _beIntegration.PlayerGoesInLobby(identity->dpnid); - } -#endif -#endif - - identity->clientState = state; - } - - PlayerClientStateMessage msg; - msg._dpnid = dpnid; - msg._clientState = state; - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &player = *_players[i]; - if (player.dpid != dpnid && player.clientState >= NCSConnected) - SendMsg(player.dpid, &msg, NMFGuaranteed); - } - - switch (state) - { - case NCSLoggedIn: - if (pInfo && _serverState >= NSSAssigningPlayers) - { - // send mission info - SendMissionInfo(pInfo->dpid); - pInfo->missionFileValid = false; - pInfo->paramFileValid = GetMissionParameters().GetLength() == 0; - } - if (_serverState == NSSPlaying) - { - // if game is already in progress, send how long is played already - NetworkCommandMessage msg; - msg._type = NCMTMissionTimeElapsed; - int timeElapsed = GlobalTickCount() - _missionHeader._start; - msg._content.Write(&timeElapsed, sizeof(timeElapsed)); - SendMsg(dpnid, &msg, NMFGuaranteed); - } - if (_serverState == NSSSelectingMission) - { - // new clients should get mission voting echo as necessary, so that they can see voting - MissionVotingEcho(); - } - break; - case NCSPlayerAssigned: - if (_serverState >= NSSSendingMission) - { - // send mission - SendMissionFile(dpnid); - } - { - PlayerIndex pIndex = CreatePlayerIndex(dpnid); - if (pInfo && _serverState >= NSSLoadingGame) - { - OnPlayerConnecting(pInfo->dpid); - - pInfo->_jipProcessed = true; - // load game - DoAssert(pInfo->clientState == NCSMissionReceived); - - _objects.forEach([pIndex,dpnid](NetworkObjectInfo *oInfo) - { - oInfo->CreatePlayerObjectInfo(pIndex,dpnid); - }); - - // send the info about network objects need to be created - MissionStatsMessage stats; - stats._toCreate = stats._toUpdate = _objects.card(); - SendMsg(dpnid, &stats, NMFGuaranteed); - - // create all game objects - //RptF("*** Sending world state ***"); - //RptF("1. all except AI objects"); - // 1. all except AI objects - - Vector3 camPos = pInfo->cameraPosition; - - _objects.forEach([pIndex,pInfo,dpnid,camPos,this](NetworkObjectInfo *info) - { - // update object info - NetworkPlayerObjectInfo *poInfo = info->GetPlayerObjectInfo(pIndex,dpnid); - - NetworkMessageType type = info->create.type; - // ClientInfo is not the full featured network object, so it should be handled different way - if ( type == NMTNone && info->currentUpdate[NMCUpdatePosition].type == NMTUpdateClientInfoDpid ) - return; - if (poInfo->updating) return; // some objects are already synced, e.g. selectPlayer done from onPlayerConnecting - DoAssert(info->create.message); -#if 0 - if (!info->create.message) - { - LogF(" i=%d, info->create.type=%d message=%x", i, info->create.type, info->create.message.GetRef()); - } - static NetworkId debugNetworkId; - if (debugNetworkId==info->id) - { - _asm nop; - } -#endif - - if (info->object.NotNull()) - { - auto bestPosition = info->BestPosition(this); - if (bestPosition._updateDistanceSquare(bestPosition._updateDistance)) - { - return; - } - } - } - - SendCreateMessage(dpnid,*info, poInfo); - poInfo->updating = true; - pInfo->markAsUpdating(poInfo); - //RptF(" %s: %d:%" OID_FORMAT"", cc_cast(GetMsgTypeName(type)), info->id.creator.CreatorInt(), info->id.id); - }); - - //RptF("*** World state sent ***"); - // update all game objects - _objects.forEach([pIndex,dpnid,this](NetworkObjectInfo *info) - { - if (info->owner==dpnid) - { - return; - } - NetworkPlayerObjectInfo *poInfo = info->GetPlayerObjectInfo(pIndex,dpnid); - if (poInfo->updating) ObjectUpdateAll(info, dpnid, NMFGuaranteed); - }); - // send delayed messages - SendInitMessages(dpnid); - // CheckInitMessages(_initMessages, "after NetworkComponent::SendMsg"); - } - else - { - DoAssert(_objects.card()==0); - _objects.reset(); - _deletedObjects.reset(); -#if DIAG_MP_OBJECT_LIFE - GObjLifeJournal.Clear(); -#endif - } - if (_serverState >= NSSLoadingGame) - { - SetClientState(dpnid, NCSGameLoaded); - } - } - break; - case NCSGameLoaded: - if (dpnid == BOT_CLIENT && _serverState < NSSPlaying) - { - // game is loaded, can start the game - SetServerState(NSSPlaying); - } - break; - case NCSPlaying: - if (pInfo) - { // clients should both send the bankscount info - if ( pInfo->hashes.bankInfoTimeout==0 && pInfo->hashes.banksCount<0 ) - { - pInfo->hashes.bankInfoTimeout = GlobalTickCount() + 10000; //10 seconds - } - } - if (pInfo && oldState != NCSPlaying && !GNetworkPlayerConnected.GetNil()) - { - GameState *state = GWorld->GetGameState(); - if (state) - { - GameVarSpace vars(false); - int gshandle = state->BeginContext(&vars); - PlayerIdentity *identity = FindIdentity(pInfo->dpid); - RString uid = identity ? identity->id : RString(); - int id = identity ? identity->playerid : -1; - DoAssert(identity); - state->VarSetLocal("_id", safe_cast(id), true); - state->VarSetLocal("_uid", uid, true); - state->VarSetLocal("_name", pInfo->name, true); - -#if USE_PRECOMPILATION - if (GNetworkPlayerConnected.GetType() == GameCode) - { - GameDataCode *code = static_cast(GNetworkPlayerConnected.GetData()); - if (code->IsCompiled() && code->GetCode().Size() > 0) - state->Evaluate(code->GetString(), code->GetCode(), GameState::EvalContext::_default, GWorld->GetMissionNamespace()); // mission namespace - } - else -#endif - if (GNetworkPlayerConnected.GetType() == GameString) - { - // make sure string is not destructed while being evaluated - RString code = GNetworkPlayerConnected; - if (code.GetLength() > 0) - state->EvaluateMultiple(code, GameState::EvalContext::_default, GWorld->GetMissionNamespace()); // mission namespace - } - state->EndContext(gshandle); - } - } - if (pInfo) pInfo->joined = Glob.time; - - { // send also current clock - NetworkCommandMessage msg; - Glob.clock.Write(msg._content); - Glob.clockWeather.Write(msg._content); - msg._type = NCMTMissionDate; - SendMsg(dpnid, &msg, NMFGuaranteed); - } - { // [F10] send also current weather + date so the client applies the server clock - ApplyWeatherMessage wmsg; - GLandscape->TranferMsg(wmsg); - SendMsg(dpnid, &wmsg, NMFGuaranteed); - } - break; - case NCSGameFinished: - // disconnected from game - if (_serverState == NSSPlaying) - { - NetworkId playerPerson; - if (pInfo) playerPerson = pInfo->person; - DisconnectPlayer(dpnid, playerPerson); - } - break; - } - - if (pInfo && oldState == NCSPlaying && state != NCSPlaying && _serverState==NSSPlaying) - { - OnPlayerDisconnected(pInfo); - } -} - -void NetworkServer::KickAllPlayers(int minBuild) -{ - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &player = *_players[i]; - if (player.dpid!=BOT_CLIENT) - { - if (minBuild>0) - { - const PlayerIdentity *ident = FindIdentity(player.dpid); - if (!ident || ident->build<0 || ident->build>=minBuild) continue; - } - KickOff(player.dpid,KOROther, "Game Loaded from MP Save, please reconnect!"); - } - } -} - -NetworkClientState NetworkServer::GetClientState(int dpid) -{ - NetworkPlayerInfo *info = GetPlayerInfo(dpid); - if (info) return info->clientState; - else return NCSNone; -} - -void NetworkServer::SetClientState(int dpnid, NetworkClientState state) -{ -// RptF("### Server: Set client state"); - - NetworkPlayerInfo *info = GetPlayerInfo(dpnid); - Assert(info); - if (info) - { - //RptF(" player %s, state %s -> %s", (const char *)info->name, (const char *)FindEnumName(info->clientState), (const char *)FindEnumName(state)); - info->clientState = state; - } - - PlayerIdentity *identity = FindIdentity(dpnid); - if (identity) - { -#if _USE_BATTL_EYE_SERVER -#if _ENABLE_STEAM_MATCHMAKING - if (state == NCSPlaying && identity->clientState != NCSPlaying) - { - - _beIntegration.PlayerGoesInGame(identity->dpnid); - } - if (identity->clientState == NCSPlaying && state != NCSPlaying) - { - _beIntegration.PlayerGoesInLobby(identity->dpnid); - } -#endif -#endif - NetLog("Client %s - changed state from %s to %s",cc_cast(identity->name),cc_cast(FindEnumName(identity->clientState)),cc_cast(FindEnumName(state))); - identity->clientState = state; - } - - ClientStateMessage msg1; - msg1._clientState = state; - SendMsg(dpnid, &msg1, NMFGuaranteed); - - PlayerClientStateMessage msg; - msg._dpnid = dpnid; - msg._clientState = state; - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &player = *_players[i]; - if (player.dpid != dpnid && player.clientState >= NCSConnected) - SendMsg(player.dpid, &msg, NMFGuaranteed); - } -} - -RString NetworkServer::GetPlayerName(int dpid) -{ - NetworkPlayerInfo *info = GetPlayerInfo(dpid); - Assert(info); - if (info) return info->name; - else return "Unknown player"; -} - -NetworkId NetworkServer::GetPlayerPerson(int dpid) -{ - NetworkPlayerInfo *info = GetPlayerInfo(dpid); - Assert(info); - if (info) return info->person; - else return NetworkId(); -} - -Object *NetworkServer::GetPlayerTarget(int dpid) -{ - NetworkPlayerInfo *info = GetPlayerInfo(dpid); - if (!info) return nullptr; - - NetworkObject *obj = GetNetworkManager().GetObject(info->_clientInput->GetCursorObject()); - return dyn_cast(obj); -} - -void NetworkServer::ServerSelectPlayer(int dpid, const NetworkId &id) -{ - NetworkPlayerInfo *info = GetPlayerInfo(dpid); - if (info) - { - info->person = id; - // make sure new person object is known to the client - NetworkObjectInfo *oInfo = GetObjectInfo(id); - DoAssert(oInfo); - if (oInfo) - { - PlayerIndex playerIndex = GetPlayerIndex(dpid); - NetworkPlayerObjectInfo *pInfo = oInfo->GetPlayerObjectInfo(playerIndex,dpid); - if (!pInfo->updating && oInfo->owner!=dpid) - { - if (oInfo->create.message) - { - SendCreateMessage(dpid,*oInfo,pInfo); - ObjectUpdateAll(oInfo, dpid, NMFGuaranteed); - pInfo->updating = true; - info->markAsUpdating(pInfo); - } - } - } - } -} - -Vector3 NetworkServer::GetCameraPosition(int dpid) -{ - NetworkPlayerInfo *info = GetPlayerInfo(dpid); - Assert(info); - if (info) return info->cameraPosition; - else return VZero; -} - -NetworkObject *NetworkServer::GetObject(const NetworkId &id) -{ - if (id.creator == CreatorId(0)) return NULL; - else if (id.creator == CreatorId(STATIC_OBJECT)) - { - ObjectId oid; - oid.Decode(id.id); - return GLandscape->GetObject(oid); - } - - // Message references (OLink) are resolved through NetworkServer while a - // dedicated server decodes client requests. The old stub made every such - // request fail before its handler ran, including inventory rotation. - NetworkObjectInfo *info = GetObjectInfo(id); - return info ? info->object.GetLink() : NULL; -} - -//! Subsidiary structure for sorting messages by error -struct UpdateObjectInfo -{ - Ref msg; - //! Object info - NetworkObjectInfo *oInfo; - //! Player object info - NetworkPlayerObjectInfo *poInfo; - //! Message class type - NetworkMessageClass cls; - //! Error (difference), distance adjusted - float error; - //! Error (difference) - float errorNoCoef; - //! Critical update - bool criticalUpdate; - - UpdateObjectInfo() - { - oInfo = NULL; - poInfo = NULL; - } -}; -TypeIsMovableZeroed(UpdateObjectInfo) - -//! Compare player object infos by error -static int CmpPlayerObjects(const UpdateObjectInfo *info1, const UpdateObjectInfo *info2) -{ - if (info2->error > info1->error) return +1; - if (info2->error < info1->error) return -1; - return 0; - // following is not the same when both errors are INF, as INF-INF is NaN - //return sign(info2->error - info1->error); -} - -void NetworkServer::KickOff(int dpnid, KickOffReason reason, const char *reasonStr) -{ - RString format; - switch (reason) - { - case KORBattlEye: format = Format("Player %%s kicked off by BattlEye: %s", reasonStr); break; - case KORKick: format = LocalizeString(IDS_MP_KICKED); break; - case KORBan: format = LocalizeString(IDS_MP_BANNED); break; - } - PlayerIdentity *id = FindIdentity(dpnid); - if (id) - { - if (id->destroy) - { - LogF("%s: KickOff in progress, new request ignored",(const char *)id->name); - return; - } - if (format.GetLength() > 0) - { - RString message = Format(format,(const char *)id->name); - RefArray dummy; - if (!ChannelDisabled(CCSystem)) - GNetworkManager.Chat(CCSystem,NULL,dummy,message); - GChatList.Add(CCSystem, NULL, message, false, true); - } - id->destroy = true; - id->destroyTime = Glob.uiTime + 15; // destroy player after 15 seconds if no system message arrive - } - // mark player kickoff is initiated - for (int i=0; i<_players.Size(); i++) - { - if (_players[i]->dpid==dpnid) _players[i]->kickedOff = true; - } - NetTerminationReason netReason = NTROther; - switch (reason) - { - case KORKick: netReason = NTRKicked; break; - case KORBan: netReason = NTRBanned; break; - case KORFade: netReason = NTROther; break; - case KORAddon: netReason = NTRMissingAddon; break; - case KORBadCDKey: netReason = NTRBadCDKey; break; - case KORCDKeyInUse: netReason = NTRCDKeyInUse; break; - case KORBattlEye: netReason = NTRBattlEye; break; - case KORAuthTimeOut: netReason = NTRAuthTimeOut; break; - } - _server->KickOff(dpnid,netReason,reasonStr); -} - -void NetworkServer::Ban(int dpnid) -{ - // add to ban list - const PlayerIdentity *identity = FindIdentity(dpnid); - if (!identity) return; - _banListLocal.AddUnique(identity->id); - - // save ban list - RString banList = GetUserDirectory() + RString("ban.txt"); - SaveBanList(banList, _banListLocal); - - // kick off - _server->KickOff(dpnid,NTRBanned); -} - -void NetworkServer::UpdateBanListSecure(const FindArray &keys, const Array &signature) -{ - #if _VERIFY_CLIENT_KEY - Assert(VerifySignedKeys(keys,signature)); // signature already verified - if (keys.Size()>_banListSecure.keys.Size()) - { - _banListSecure.keys = keys; - _banListSecure.signature = signature; - // output the secure key list - RString banSecureFilename = GetUserDirectory() + RString("banSecure.txt"); - RString banListContent = PrintSignedKeys(_banListSecure.keys,_banListSecure.signature); - QOFStream f(banSecureFilename); - f << cc_cast(banListContent); - f.close(); - } - #endif -} - - -#if LOG_ERRORS -//! diagnostic logs of error (difference) between messages -/* -static void LogError -( - NetworkMessageType type, - int dpid1, NetworkMessage *msg1, - int dpid2, NetworkMessage *msg2 -) -{ - if (type < 0 || type >= NMTN) return; - NetworkMessageFormat *format = GMsgFormats[type]; - - float dt = msg1->time - msg2->time; - float error = ( - msg1->CalculateErrorStatic(msg2) + - msg1->CalculateErrorDynamic(msg2) + CalculateErrorTime(type, msg1, msg2) - ); - - if (error > 0) - DiagLogF - ( - " - %s: %g * %g = %g", (const char *)format->GetItem(i).name, - coef, value, error - ); - } -} -*/ -#endif - -#if _ENABLE_REPORT - #define LOG_QUEUE_PROGRESS 0 -#endif - -/*! -\patch_internal 1.01 Date 6/26/2001 by Ondra. Added hacked version player kickoff. -*/ -void NetworkServer::CheckFadeOut() -{ -#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) - for (int i=0; i<_players.Size(); i++) - _players[i]->_steamValidate.HandleTimeout(); -#endif - - if (_serverState == NSSPlaying) - { - for (int i=0; i<_identities.Size(); i++) - { - PlayerIdentity &identity = _identities[i]; -/* -//testing only - static volatile bool doIt=false; - if (doIt) - { - if (identity.dpnid!=2) - KickOff(identity.dpnid,KORBattlEye, "Hello boy!"); - } -*/ - if (Glob.uiTime>=identity.kickOffTime) - { - switch (identity.kickOffState) - { - case KOWait: - { - // transmit explanation - identity.kickOffState = KOWarning; - identity.kickOffTime = Glob.uiTime; - RString string = LocalizeString(IDS_FADE_AWAY); - RString senderName = identity.GetName(); - RefArray dummy; - if (!ChannelDisabled(CCSystem)) - GNetworkManager.Chat(CCSystem,senderName,dummy,string); - GChatList.Add(CCSystem, senderName, string, false, true); - } - break; -//((EXE_CRC_CHECK - case KOExe: -//))EXE_CRC_CHECK - case KOWarning: - if (Glob.uiTime>identity.kickOffTime+15) - { -//((EXE_CRC_CHECK - bool wasExe = identity.kickOffState==KOExe; -//))EXE_CRC_CHECK - identity.kickOffState = KODone; - KickOff(identity.dpnid,KORFade); -//((EXE_CRC_CHECK - if (wasExe) - { - RString format = LocalizeString(IDS_MP_VALIDERROR_1); - - RString message = Format(format, cc_cast(identity.GetName())); - RefArray dummy; - if (!ChannelDisabled(CCSystem)) - GNetworkManager.Chat(CCSystem,"",dummy,message); - GChatList.Add(CCSystem, NULL, message, false, true); -#if _ENABLE_DEDICATED_SERVER - ConsoleF("%s", cc_cast(message)); -#endif - } -//))EXE_CRC_CHECK - UpdateMatchmakingDescription(false); - } - break; - default: - Fail("KickOffState!"); - case KODone: - break; - } - } - } - } -} - -/*! -\patch_internal 1.50 Date 4/8/2002 by Jirka -- Fixed: No limits for server - bot client communication. -\patch 1.53 Date 4/23/2002 by Jirka -- Fixed: Bandwidth estimation on dedicated server -*/ -void NetworkServer::EstimateBandwidth(NetworkPlayerInfo &pInfo, int nPlayers, int &nMsgMax, int &nBytesMax) -{ - if (pInfo.dpid == BOT_CLIENT || pInfo._isLocal) - { - nBytesMax = INT_MAX; - nMsgMax = INT_MAX; - - pInfo._ping.Sample(0); - pInfo._bandwidth.Sample(INT_MAX); - } - else - { - int nMsg = 0, nBytes = 0, nMsgG = 0, nBytesG = 0; - - // calculate quotas - _server->GetSendQueueInfo(pInfo.dpid, nMsg, nBytes, nMsgG, nBytesG); - if (nMsgG > 0) - { - nMsg += nMsgG; - nBytes += nBytesG; - } - - int minBandwidth; -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - if (IsDedicatedServer()) - { - nMsgMax = DSMaxMsgSend; - minBandwidth = DSMinBandwidth; - } - else -#endif -//} - { - nMsgMax = MaxMsgSend; - minBandwidth = MinBandwidth; - } - int bandwidth = 100; // add 800 bps as a basic bandwidth - #if _ENABLE_MP - int latencyMS = 0, throughputBPS = 0; - if (_server->GetConnectionInfo(pInfo.dpid, latencyMS, throughputBPS)) - { - // nBytesMax += 1.25 * throughputBPS; - bandwidth += throughputBPS; - bandwidth += throughputBPS >> 2; // throughputBPS / 4 - } - #endif - // assume server upload bandwidth is at least MinBandwidth - if (nPlayers > 0) - { - int lowLevelMaxBandwidth = INT_MAX; - _server->GetConnectionLimits(lowLevelMaxBandwidth); - // 8 is conversion from bps to Bps - int minBandwidthPerPlayer = minBandwidth/(8*nPlayers); - - // min limit must never be higher than low-level max limit - saturateMin(minBandwidthPerPlayer, lowLevelMaxBandwidth); - saturate(bandwidth, minBandwidthPerPlayer, MaxBandwidth/8); - if (bandwidth>lowLevelMaxBandwidth) bandwidth = lowLevelMaxBandwidth; - } - - // float frmDur = GEngine->GetAvgFrameDuration(); - // LogF(" avgFrame: %.3f", frmDur); - nBytesMax = toInt(0.001 * GEngine->GetAvgFrameDuration() * bandwidth); - - nBytesMax -= nBytes; - nMsgMax -= nMsg; - - { - // statistics - int latencyMSRaw = 0, throughputBPSRaw = 0; - #if _ENABLE_MP - _server->GetConnectionInfoRaw(pInfo.dpid, latencyMSRaw, throughputBPSRaw); - #endif - pInfo._ping.Sample(latencyMSRaw); - pInfo._bandwidth.Sample(throughputBPSRaw); - } - - // write statistics -#if _ENABLE_CHEATS - if (outputLogs) LogF("Server to %s: Limit (%d, %d)", (const char *)pInfo.name, nBytesMax, nMsgMax); -#endif - } -} - -int NetworkServer::GetBandwidthEstimation(int dpnid, int nPlayers) -{ - int bandwidth; - if (dpnid == BOT_CLIENT) - { - bandwidth = INT_MAX; - } - else - { - int minBandwidth; -#if _ENABLE_DEDICATED_SERVER - if (IsDedicatedServer()) minBandwidth = DSMinBandwidth; - else -#endif - { - minBandwidth = MinBandwidth; - } - bandwidth = 100; // add 800 bps as a basic bandwidth -#if _ENABLE_MP - int latencyMS = 0, throughputBPS = 0; - if (_server->GetConnectionInfo(dpnid, latencyMS, throughputBPS)) - { - // nBytesMax += 1.25 * throughputBPS; - bandwidth += throughputBPS; - bandwidth += throughputBPS >> 2; // throughputBPS / 4 - } -#endif - // assume server upload bandwidth is at least MinBandwidth - if (nPlayers > 0) - { - // 8 is conversion from bps to Bps - int minBandwidthPerPlayer = minBandwidth/(8*nPlayers); - - int lowLevelMaxBandwidth = INT_MAX; - _server->GetConnectionLimits(lowLevelMaxBandwidth); - // min limit must never be higher than low-level max limit - saturateMin(minBandwidthPerPlayer, lowLevelMaxBandwidth); - saturate(bandwidth, minBandwidthPerPlayer, MaxBandwidth/8); - } - } - return bandwidth; -} - - -void NetworkServer::SendCreateMessage( int dpnid, NetworkObjectInfo &info, NetworkPlayerObjectInfo *poInfo ) -{ - if (DebugMeBoy(info.id)) - { - LogF("*** DebugMeBoy: {%d:%" OID_FORMAT"} Create for %d", info.id.creator.CreatorInt(), info.id.id, dpnid); - } - SendMsg(dpnid, info.create.message, info.create.type, NMFGuaranteed, poInfo); -} - -void NetworkServer::OnHierParentChange( Entity* veh ) -{ - const Entity *root = veh; - while (root->GetHierarchyParent()) root = root->GetHierarchyParent(); - NetworkId id = root->GetNetworkId(); - NetworkObjectInfo *rootInfo = GetObjectInfo(id); - if (!rootInfo) return; - NetworkObjectInfo *oInfo = GetObjectInfo(veh->GetNetworkId()); - if (!oInfo) return; - - auto bestPosNew = rootInfo->BestPosition(); - auto bestPosOld = oInfo->BestPosition(); - - oInfo->_updInfo = bestPosNew; - _objects.onPosChanged(oInfo,bestPosOld,bestPosNew); - - UpdateChildrenPos(veh); -} - - -float NetworkServer::CalculateErrorCoef(const NetworkPlayerInfo &pInfo, const NetworkObjectInfo &oInfo, bool updating) -{ - const float errorCoefMyVehicle = 2.0f; - const float errorCoefMyBody = 10.0f; - - const NetworkCurrentInfo &update = oInfo.currentUpdate[NMCUpdateGeneric]; - if (update.message && !pInfo.person.IsNull()) - { - if (pInfo.person==oInfo.id) - { - return errorCoefMyBody; - } - - if (IsUpdateTransport(update.type)) - { - // check if player is not inside given vehicle - NetworkMessageUpdateTransport *msg = static_cast(update.message.GetRef()); - if (msg) - { -#if _VBS2 - if(msg->_UpdateCoef > 0.0f ) - return msg->_UpdateCoef; -#endif - if (msg->_driver == pInfo.person) return errorCoefMyVehicle; - for (int i=0; i_manCargo.Size(); i++) - { - if (msg->_manCargo[i] == pInfo.person) return errorCoefMyVehicle; - } - } - } - else if (update.type == NMTUpdateTurret) - { - // check if player is not inside given turret - NetworkMessageUpdateTurret *msg = static_cast(update.message.GetRef()); - if (msg) - { - if (msg->_gunner == pInfo.person) return errorCoefMyVehicle; - } - } - } - - if (!oInfo.object) - { - // no object: this must be UpdateClientInfoDpid - DoAssert(oInfo.currentUpdate[NMCUpdatePosition].type==NMTUpdateClientInfoDpid); - return 1; - } - - //auto pos = oInfo.BestPosition(); - NetworkObject *rootObj = oInfo.object; - Entity *root = dyn_cast(rootObj); - if (root) - { - while (root->GetHierarchyParent()) root = root->GetHierarchyParent(); - rootObj = root; - } - Vector3 pos = rootObj->GetCurrentPosition(); - float updateDistance = rootObj->UpdateDistance(); - - // calculate the error coef by object's position - return oInfo.object->CalculateErrorCoef(pos, pInfo.cameraPosition, updateDistance, updating); -} - - -/*! -\patch_internal 1.12 Date 08/07/2001 by Jirka -- Added: error calculation diagnostics -\patch 5115 Date 1/8/2007 by Jirka -- Fixed: MP - fire effects sometimes did not transferred (especially for JIP players) -*/ - -#if DEBUG_GIVEN_NETWORK_ID -bool DebugMeBoy(NetworkId id) -{ - static NetworkId myId(CreatorId(2),6); - return (id == myId); -} - -bool DebugMeBoy(NetworkMessage *msg, NetworkMessageType type) -{ - static NetworkMessageType debugType = NMTUpdatePositionMan; - if (type==debugType) - { - auto *msg1 = static_cast(msg); - return DebugMeBoy(NetworkId(msg1->_objectCreator, msg1->_objectId)); - } - return false; -} - -#endif - -PlayerIndex NetworkServer::CreatePlayerIndex(int pid) -{ - PlayerIndex pIndex = GetPlayerIndex(pid); - if (pIndex<0) - { - pIndex = (PlayerIndex)_indexToPlayerId.Add(pid); - LogF("**** Player %d index %d added",pid,int(pIndex)); - } - else - { - LogF("**** Player %d index %d used, %d total",pid,int(pIndex),_indexToPlayerId.Size()); - } - return pIndex; -} - -void NetworkServer::OnStopUpdating(NetworkObjectInfo &oInfo, NetworkPlayerInfo &pInfo, NetworkPlayerObjectInfo &poInfo) -{ - // send a destroy message - DeleteObjectMessage msg; - msg._creator = oInfo.id.creator; - msg._id = oInfo.id.id; - - SendMsg(pInfo.dpid, &msg, NMFGuaranteed); - - for (int i=0; i &objects, NetworkPlayerInfo &pInfo) -{ - PROFILE_SCOPE_EX(crOLS, network) - // calculate errors and place object in list sorted by error - - PlayerIndex playerIndex = GetPlayerIndex(pInfo.dpid); - DoAssert(playerIndex>=0); - DoAssert(pInfo.dpid!=BOT_CLIENT); // this function cannot be used for bot client, as it implements player bubble - - NetworkPlayerInfo::UpdatingList updatingNew; - - auto handleUpdatingObject = [playerIndex,&pInfo,this,&objects,&updatingNew](NetworkObjectInfo *info) - { - NetworkObjectInfo &oInfo = *info; - - NetworkPlayerObjectInfo *poInfo = oInfo.GetPlayerObjectInfo(playerIndex,pInfo.dpid); - - float errCoef = CalculateErrorCoef(pInfo, oInfo, poInfo->updating); - if (errCoef < 0) return; - - bool needsUpdate = errCoef>0 || pInfo.dpid==oInfo.owner; - - if (needsUpdate!=poInfo->updating) - { - if (DebugMeBoy(oInfo.id)) - { - LogF("*** DebugMeBoy: {%d:%" OID_FORMAT"} Updating for %d state %d", oInfo.id.creator.CreatorInt(), oInfo.id.id, pInfo.dpid, needsUpdate); - } - if (needsUpdate) - { - // ClientInfoObject has no create message only NMTUpdateClientInfoDpid (position update) - if (oInfo.create.message.NotNull()) - { - SendCreateMessage(pInfo.dpid,oInfo,poInfo); - ObjectUpdateAll(info, pInfo.dpid, NMFGuaranteed); - } - } - else - { - // we could also skip this else branch and leave the cleanup to the pInfo._updating loop below - DoAssert(pInfo._updating.CheckIntegrity()); - OnStopUpdating(oInfo, pInfo, *poInfo); - pInfo._updating.Delete(poInfo); - DoAssert(pInfo._updating.CheckIntegrity()); - } - - poInfo->updating = needsUpdate; - } - - - if (!needsUpdate) return; - - pInfo.markAsUpdating(poInfo,updatingNew); - - for (int j=NMCUpdateFirst; jupdates[j]; - - if (oInfo.owner == pInfo.dpid) - { - if (pInfo.dpid!=BOT_CLIENT && info.from==BOT_CLIENT) - { - // bot-client may override owner information - } - else - { - continue; - } - } - - float error; - // error without distance coef - float errorNoCoef; - if (!update.lastSentMsg) - { - errorNoCoef = info.message->CalculateErrorInitial(); - error = errCoef * errorNoCoef; -#if LOG_ERRORS - DiagLogF("Initial error for %s %d:%" OID_FORMAT" to %d", NetworkMessageTypeNames[info.type], oInfo.id.creator.CreatorInt(), oInfo.id.id, pInfo.dpid); - DiagLogF(" - error %.3f * %.3f = %.3f", errCoef, errorNoCoef, error); -#endif - } - else - { - NetworkMessage *msg1 = info.message; - NetworkMessage *msg2 = update.lastSentMsg; - - DoAssert(!msg1->HasDiff()); - DoAssert(!msg2->HasDiff()); - - if (!update.errorValid) - { - /* - if (info.type==NMTUpdateMan) - { - __asm nop; - } - */ - - update.errorStatic = msg1->CalculateErrorStatic(msg2); - update.errorValid = true; - } - float dt = msg1->time - msg2->time; - float errorDynamic = msg1->CalculateErrorDynamic(msg2, dt); - errorNoCoef = error = update.errorStatic + errorDynamic + CalculateErrorTime(info.type, msg1, msg2); - -#if LOG_ERRORS - if (!(error * errCoef < LogErrorLimit)) // handle NaN well - { - DiagLogF - ( - "Object %s %d:%" OID_FORMAT" - update to %d", - NetworkMessageTypeNames[info.type], oInfo.id.creator.CreatorInt(), oInfo.id.id, - pInfo.dpid - ); - DiagLogF(" - error %.3f = stat %.3f + dyn %.3f", error, update.errorStatic, errorDynamic); - DiagLogF(" - error %.3f * %.3f = %.3f", errCoef, error, errCoef * error); - if (pInfo.cameraPosition[1]!=-FLT_MAX) - { - DiagLogF - ( - " - camera [%.0f, %.0f, %.0f]", - pInfo.cameraPosition[0], pInfo.cameraPosition[1], pInfo.cameraPosition[2] - ); - } - - msg1->CalculateErrorStatic(msg2); - msg1->CalculateErrorDynamic(msg2, dt); - CalculateErrorTime(info.type, msg1, msg2); - } -#endif - error *= errCoef; - } - -#if DEBUG_GIVEN_NETWORK_ID - if (DebugMeBoy(oInfo.id) && error>0) - { - float msgTime = update.lastSentMsg ? update.lastSentMsg->time.toFloat() : 0; - LogF("*** DebugMeBoy: {%d:%" OID_FORMAT"}, Error: %.2f, lastMsgTime: %.3f", oInfo.id.creator.CreatorInt(), oInfo.id.id, error, msgTime); - } -#endif - - // note: following condition seems to be identical to error>MinErrorToSend - // but it is different when error is NaN - if (!(error <= MinErrorToSend) && !(errorNoCoef <= MinErrorToSendNear)) - { - int index = objects.Add(); - // objects[index].pInfo = &pInfo; - objects[index].oInfo = &oInfo; - objects[index].poInfo = poInfo; - objects[index].cls = (NetworkMessageClass)j; - objects[index].error = error; - objects[index].errorNoCoef = errorNoCoef; - objects[index].criticalUpdate = false; - - #if _DEBUG - #define NOP __asm {nop} - switch (info.type) - { - case NMTUpdateMan: NOP; break; - case NMTUpdatePositionMan: NOP; break; - case NMTUpdateVehicleAI: NOP; break; - case NMTUpdateDamageVehicleAI: NOP; break; - case NMTUpdateDamageVehicle: NOP; break; - case NMTUpdateObject: NOP; break; - case NMTUpdateDamageObject: NOP; break; - } - if (update.lastSentMsg) - { - // tracing opportunity - // place breakpoint depending on message type - switch (info.type) - { - case NMTUpdateMan: NOP; break; - case NMTUpdatePositionMan: NOP; break; - case NMTUpdateVehicleAI: NOP; break; - case NMTUpdateDamageVehicleAI: NOP; break; - case NMTUpdateDamageVehicle: NOP; break; - case NMTUpdateObject: NOP; break; - case NMTUpdateDamageObject: NOP; break; - } - NetworkMessage *msg1 = info.message; - NetworkMessage *msg2 = update.lastSentMsg; - float errorStatic = msg1->CalculateErrorStatic(msg2); - float dt = msg1->time - msg2->time; - float errorDynamic = msg1->CalculateErrorDynamic(msg2, dt); - (void)errorStatic; - (void)errorDynamic; - NOP; - } - - #endif - } - } - }; - - _objects.forEachInBubble(pInfo.cameraPosition, handleUpdatingObject); - - // only items in updatingNew should be kept as _updating, the rest needs to be marked as no longer updating - DoAssert(pInfo._updating.CheckIntegrity()); - AUTO_STATIC_ARRAY(NetworkObjectInfo *, owned, 32); - for (NetworkPlayerObjectInfo *poInfo=pInfo._updating.Start(); pInfo._updating.NotEnd(poInfo); poInfo=pInfo._updating.Advance(poInfo)) - { - DoAssert(poInfo->updating); - // oInfo from poInfo - NetworkObjectInfo *oInfo = poInfo->oInfo; - if (pInfo.dpid == oInfo->owner) - { - // delayed handling - handleUpdatingObject is changing pInfo._updating we are traversing - owned.Add(oInfo); - } - else - { - int oCount = pInfo._updating.Size(); - OnStopUpdating(*oInfo, pInfo, *poInfo); - int nCount = pInfo._updating.Size(); - DoAssert(oCount==nCount); - poInfo->updating = false; - } - } - for (int i=0; itimeReceived)*item->invMaxAge; - float errorCoef = 1; - - if (pInfo.cameraPosition[0] != -FLT_MAX && item->pos[0]!=-FLT_MAX) - { - // both positions defined - // coef = limit / distance (maximum is 1) - const float limit = 20.0f; - float dist2 = item->pos.Distance2(pInfo.cameraPosition); - if (dist2 > Square(limit)) - { - errorCoef = Square(limit) / dist2; - } - } - - float error = item->error*ageCoef; - // if age is negative or zero, condition will certainly fail - if (errorCoef*error -class SpatialIndexBruteForce -{ - FindArrayKey _data; -public: - void Add(Type item) - { - _data.Add(item); - } - bool Remove(Vector3Par oldPos, Type item) - { - return _data.DeleteKey(item); - } - - template - void ForEach(Vector3Par pos, float maxDistance, const Function &f) - { - auto fInBubble = [pos,maxDistance,&f](Type oInfo)->bool - { - DoAssert(oInfo->object->UpdateDistance()==maxDistance); - auto oPos = oInfo->BestPosition(); - DoAssert(oPos.second); - float dist2 = pos.Distance2(oPos.first); - if (dist2 -class SpatialIndexNaive -{ - static const float Grid() {return 100.0f;} - - static int SlotNum(float posX) {return toInt(posX * (1.0f/Grid()));} - - typedef FindArrayKey Slot; - - AutoArray _slot; - int _slot0; - -public: - SpatialIndexNaive() - :_slot0(0) - { - } - void Add(Type item) - { - Vector3 pos = item->BestPosition()._pos; - DoAssert(pos.SquareSize()>0); - int slot = SlotNum(pos.X()); - - if (_slot.MaxSize()==0) _slot0 = slot; // empty list, set arbitrary beginning - if (slot<_slot0) - { - _slot.InsertMultiple(0,_slot0-slot); - _slot0 = slot; - } - else if (slot-_slot0>=_slot.Size()) - { - _slot.Resize(slot-_slot0+1); - } - _slot[slot-_slot0].Add(item); - } - bool Remove(Vector3Par oldPos, Type item) - { - int slot = SlotNum(oldPos.X()); - DoAssert(slot>=_slot0 && slot<_slot0+_slot.Size()); - return _slot[slot-_slot0].DeleteKey(item); - } - - template - void ForEach(Vector3Par pos, float maxDistance, const Function &f) - { - if (_slot.Size()<=0) return; - int minSlot = SlotNum(pos.X()-maxDistance); - int maxSlot = SlotNum(pos.X()+maxDistance); - int minSlotI = minSlot-_slot0; - int maxSlotI = maxSlot-_slot0; - saturate(minSlotI,0,_slot.Size()-1); - saturate(maxSlotI,0,_slot.Size()-1); - for (int i=minSlotI; i<=maxSlotI; i++) - { - auto fInBubble = [pos,maxDistance,&f](Type oInfo)->bool - { - // TODO: encapsulate oInfo access in Type traits - auto oPos = oInfo->BestPosition(); - DoAssert(oPos._updateDistance==maxDistance); - float dist2 = pos.Distance2(oPos._pos); - if (dist2 -class SpatialIndexRTree -{ - RTree _data; -public: - void Add(Type item) - { - Vector3 pos = item->BestPosition()._pos; - float vec[2] = {pos[0],pos[2]}; - _data.Insert(vec,vec,item); - } - bool Remove(Vector3Par oldPos, Type item) - { - float vec[2] = {oldPos[0],oldPos[2]}; - return _data.Remove(vec,vec,item); - } - - template - void ForEach(Vector3Par pos, float maxDistance, const Function &f) - { - auto fInBubble = [pos,maxDistance,&f](Type oInfo)->bool - { - auto oPos = oInfo->BestPosition(); - DoAssert(oPos._updateDistance==maxDistance); - float dist2 = pos.Distance2(oPos._pos); - if (dist2 -class SpatialIndexRTreeChecked -{ - SpatialIndexNaive _ref; - SpatialIndexRTree _tst; - - public: - void Add(Type item) - { - _ref.Add(item); - _tst.Add(item); - } - bool Remove(Vector3Par oldPos, Type item) - { - bool ok1 = _ref.Remove(oldPos,item); - bool ok2 = _tst.Remove(oldPos,item); - DoAssert(ok1==ok2); - return ok1; - } - - template - void ForEach(Vector3Par pos, float maxDistance, const Function &f) - { - _ref.ForEach(pos,maxDistance,f); - - FindArrayKey visitedByRef; - FindArrayKey visitedByTst; - - _ref.ForEach(pos,maxDistance,[&visitedByRef](Type oInfo){visitedByRef.Add(oInfo);}); - _tst.ForEach(pos,maxDistance,[&visitedByTst](Type oInfo){visitedByTst.Add(oInfo);}); - - DoAssert(visitedByTst.Size()==visitedByRef.Size()); - - // verify identity - for (int i=0; i=0); - } - for (int i=0; i=0); - } - - - } -}; - -struct ObjectsSpatialLayerImpl: public ObjectsSpatialLayerWithDistance -{ - SpatialIndexRTree _index; - - ObjectsSpatialLayerImpl(float distance):ObjectsSpatialLayerWithDistance(distance){} - virtual void Add(NetworkObjectInfo *oInfo) override; - virtual bool Remove(Vector3Par oldPos, NetworkObjectInfo *oInfo) override; - virtual void ForEach( Vector3 cameraPos, const Function &function ); - -}; - -void ObjectsSpatialLayerImpl::Add(NetworkObjectInfo *oInfo) -{ - _index.Add(oInfo); -} - -bool ObjectsSpatialLayerImpl::Remove(Vector3Par oldPos, NetworkObjectInfo *oInfo) -{ - DoAssert(oldPos.SquareSize()>0); - return _index.Remove(oldPos,oInfo); -} - -void ObjectsSpatialLayerImpl::ForEach( Vector3 cameraPos, const Function &function ) -{ - _index.ForEach(cameraPos,_distance,function); -} - -struct ObjectsSpatialLayerNoBubble: public ObjectsSpatialLayer -{ - FindArrayKey _index; - - virtual void Add(NetworkObjectInfo *oInfo) override {_index.Add(oInfo);} - virtual bool Remove(Vector3Par oldPos, NetworkObjectInfo *oInfo) override {return _index.DeleteKey(oInfo);} - virtual void ForEach(Vector3 cameraPos, const Function &function) - { - _index.ForEachF([function](NetworkObjectInfo *oInfo)->bool {function(oInfo);return false;}); - } - -}; - - -NetworkServer::ObjectsSpatialIndex::ObjectsSpatialIndex() -{ - -} -ObjectsSpatialLayer &NetworkServer::ObjectsSpatialIndex::Distance(float dist) -{ - if (dist0) - { - int index = _layers.FindKey(dist); - if (index>=0) return *_layers[index]; - return *_layers.Append(new ObjectsSpatialLayerImpl(dist)); - } - else - { - if (_noLayer.IsNull()) _noLayer = new ObjectsSpatialLayerNoBubble(); - return *_noLayer; - } -} - -bool NetworkServer::ObjectsSpatialIndex::put( TargetType value ) -{ - addToLayer(value); - return _all.put(value); -} - -void NetworkServer::ObjectsSpatialIndex::removeKey ( KeyType key ) -{ - TargetType value; - if (_all.removeKey(key,&value)) - { - auto pos = value->BestPosition(); - removeFromLayer(pos._pos,pos._updateDistance,value); - } -} - - -void NetworkServer::ObjectsSpatialIndex::forEachInBubble(Vector3 cameraPos, const ObjectsSpatialLayer::Function &function) -{ - for (int i=0; i<_layers.Size(); i++) - { - _layers[i]->ForEach(cameraPos,function); - } - _noLayer->ForEach(cameraPos,function); -} - - -void NetworkServer::ObjectsSpatialIndex::onPosChanged(NetworkObjectInfo *oInfo, const NetworkObjectInfo::UpdateInfo &oldPos, const NetworkObjectInfo::UpdateInfo &newPos) -{ - if (oldPos._pos!=newPos._pos || oldPos._updateDistance!=newPos._updateDistance) - { - removeFromLayer(oldPos._pos,oldPos._updateDistance,oInfo); - addToLayer(oInfo); - } -} - -void NetworkServer::ObjectsSpatialIndex::reset () -{ - _noLayer.Free(); - _layers.Clear(); - _all.reset(); -} - - - - -/*! -\patch 1.27 Date 10/09/2001 by Ondra -- Fixed: Ping times on clients were not updated when mission was not running. -\patch_internal 1.47 Date 3/11/2002 by Ondra -- Fixed: Improved latency on kill. -\patch_internal 1.48 Date 3/12/2002 by Ondra -- Fixed: Latency on kill further improved. -Bug introduced in 1.47 beta causing increased lag of movement fixed. -\patch_internal 1.49 Date 3/14/2002 by Ondra -- Fixed: Latence handling code reverted to version 1.45. -\patch 1.53 Date 4/23/2002 by Ondex -- Fixed: Kill/dammage message have now higher priority - this should improve latency on kill. -*/ -void NetworkServer::SendMessages() -{ - //DoAssert(CheckBestPositionIntegrity()); -#if _ENABLE_CHEATS - // remove statistics info - static AutoArray texts; - for (int i=0; i= 0) GEngine->RemoveText(texts[i]); - } - texts.Resize(0); -#endif - -#if _ENABLE_CHEATS - #define LOG_DESYNC 1 -#endif - -#if LOG_DESYNC - static DWORD time = 0; - DWORD now = GlobalTickCount(); - bool logDesync = false; - if (now >= time + 1000) - { - logDesync = true; - time = now; - } -#endif - - int nPlayers = _identities.Size() - 1; -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - if (IsDedicatedServer()) nPlayers++; -#endif -//} -#define DIAGNOZE_BANDWIDTH 0 -#if DIAGNOZE_BANDWIDTH - bool doDiagnozeBandwidth = false; - static DWORD nextDiagTime = GetTickCount()+5000; - DWORD curTime = GetTickCount(); - if (curTime>=nextDiagTime) - { - nextDiagTime=curTime+5000; - doDiagnozeBandwidth = true; - } -#endif - - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &pInfo = *_players[i]; - - int nMsg = 0; - int nBytes = 0; - int nMsgMax, nBytesMax; - - //LogF(" NsEstB %d, %d Bytes", nMsgMax, nBytesMax); - EstimateBandwidth(pInfo, nPlayers, nMsgMax, nBytesMax); -#if DIAGNOZE_BANDWIDTH - int diagGMsg=0, diagGBytes=0; //state of nMsgMax and nBytesMax after the guaranteed messages are sent - int diagCMsg=0, diagCBytes=0; //state ... after critical updates are sent -#endif - //LogF(" NsEstB %d, %d Bytes", nMsgMax, nBytesMax); - - #if LOG_QUEUE_PROGRESS - if (pInfo._messageQueue.Size() > 0) - { - LogF - ( - "%s: nBytesMax %d, nBytes %d, queue size %d", - (const char *)pInfo.name, - nBytesMax, nBytes, pInfo._messageQueue.Size() - ); - } - #endif - - // send enqueued guaranteed messages - int maxSize = MaxSizeGuaranteed; - - const int nMsgMaxGuaranteed = nMsgMax; - const int nBytesMaxGuaranteed = nBytesMax; - - int firstGuaranteedUnsent = 0; - while (firstGuaranteedUnsent < pInfo._messageQueue.Size()) - { - if (nMsg >= nMsgMaxGuaranteed || nBytes >= nBytesMaxGuaranteed) - { - #if LOG_QUEUE_PROGRESS - int qBytes = 0; - for (int i=firstGuaranteedUnsent; imsg->size; - } - LogF - ( - " -- queue left %d (%d B)",pInfo._messageQueue.Size()-firstGuaranteedUnsent,qBytes - ); - #endif - break; - } - - NetworkMessage *msg = pInfo._messageQueue[firstGuaranteedUnsent]->msg; - int size = msg->size; - if (size >= maxSize) - { - //DWORD dwMsgId = - RefR resultMsg; - /*int rawSize = */SendMsgRemote(pInfo.dpid, msg, pInfo._messageQueue[firstGuaranteedUnsent]->type, NMFGuaranteed|NMFStatsAlreadyDone, &resultMsg, NULL); - pInfo._messageQueue[firstGuaranteedUnsent]->SetFence(resultMsg); - firstGuaranteedUnsent++; - nMsg++; - nBytes += size; - } - else - { - int totalSize = 0; - int i; - for (i=firstGuaranteedUnsent; imsg; - int size = msg->size; - if (totalSize + size > maxSize) break; - totalSize += size; - } - /*int rawSize = */SendMsgQueue(pInfo.dpid, pInfo._messageQueue, firstGuaranteedUnsent, i, NMFGuaranteed); - firstGuaranteedUnsent = i; - nMsg++; - nBytes += totalSize; - } - } - if (firstGuaranteedUnsent > 0) pInfo._messageQueue.Delete(0, firstGuaranteedUnsent); - - #if LOG_QUEUE_PROGRESS - if (nBytes>0) - { - LogF - ( - " -- nMsg %d (nBytes %d)",nMsg,nBytes - ); - if (pInfo._messageQueue.Size()==0) - { - LogF(" ** Queue empty"); - } - } - #endif - - AUTO_STATIC_ARRAY(UpdateObjectInfo, objects, 256); - - #define ENABLE_CRITICAL_UPDATES 1 - -#if DIAGNOZE_BANDWIDTH - diagGBytes = nBytes; - diagGMsg = nMsg; -#endif - - #if !ENABLE_CRITICAL_UPDATES - if (nMsg >= nMsgMax || nBytes >= nBytesMax) - { - #if _ENABLE_CHEATS - if (outputLogs) LogF(" Server to %s: limit reached (guaranteed)", (const char *)pInfo.name); - #endif - goto DoNotSendUpdates; - } - #endif - - // update objects - if (_serverState == NSSPlaying && pInfo.clientState == NCSPlaying) - { - // update errors of objects - if (pInfo.dpid!=BOT_CLIENT) // bot client is sent all updates directly when receiving them - { - CreateObjectsList(objects, pInfo); - - ClientOutput *obj = pInfo._clientInput->_output; - obj->OnBeforeSend(pInfo); - if (!pInfo._clientInput->_outputLast || obj->Compare(pInfo._clientInput->_outputLast)) - { - // TODO: bandwith control - NetworkMessageType type = obj->GetNMType(NMCUpdateGeneric); - Ref msg = ::CreateNetworkMessage(type); - msg->time = Glob.time; - NetworkMessageContext ctx(msg, this, pInfo.dpid, MSG_SEND); - ctx.SetClass(NMCUpdateGeneric); - obj->TransferMsg(ctx); - - SendMsg(pInfo.dpid,msg,type,NMFGuaranteed, NULL); - - // TransferMsg may modify the state - if (!pInfo._clientInput->_outputLast) pInfo._clientInput->_outputLast = new ClientOutput(*obj); - else *pInfo._clientInput->_outputLast = *obj; - obj->OnSent(); - } - } - - // create and send critical updates - #if ENABLE_CRITICAL_UPDATES - PlayerIndex playerIndex = GetPlayerIndex(pInfo.dpid); - for (int i=0; iid)) - { - float times[NMCUpdateN]; - NetworkPlayerObjectInfo *poInfo = oInfo->GetPlayerObjectInfo(playerIndex,pInfo.dpid); - for (int j=0; jupdates[j].lastSentMsg ? poInfo->updates[j].lastSentMsg->time.toFloat() : 0; - LogF("*** DebugMeBoy: {%d:%" OID_FORMAT"} has error %.2f, position in _objects = %d, lastMsgSent: %.02f, %.02f, %.02f", - oInfo->id.creator.CreatorInt(), oInfo->id.id, error, i, times[NMCUpdateGeneric], times[NMCUpdatePosition], times[NMCUpdateDamage]); - } -#endif - - // any message about dammage that transmit change - // that could mean dead should be considered high priority - // errorNoCoef - error with no regard to distance - // error - distance adjusted error - if - ( - errorNoCoef < ERR_COEF_IMMEDIATE && - ( cls != NMCUpdateDamage || error < ERR_COEF_STRUCTURE * 0.01 || errorNoCoef < ERR_COEF_STRUCTURE ) - ) continue; - - info.criticalUpdate = true; - //TODO: do not use fence for high priority updates - NetworkPlayerObjectInfo *poInfo = oInfo->GetPlayerObjectInfo(playerIndex,pInfo.dpid); - int bytes; - if (!poInfo->_fence || poInfo->_fence->WasReceived()) - { - bytes = UpdateObject(&pInfo, oInfo, cls, NMFGuaranteed | NMFHighPriority); - } - else - { - bytes = UpdateObject(&pInfo, oInfo, cls, NMFGuaranteed); - } - - #if _ENABLE_CHEATS - if (outputLogs) - { - LogF - ( - " Server to %s: Object %d:%" OID_FORMAT" updated - size %d bytes, critical", - (const char *)pInfo.name, info.oInfo->id.creator.CreatorInt(), info.oInfo->id.id, bytes - ); - } - #endif - - if (bytes >= 0) - { - // no error - nMsg++; - nBytes += bytes; - } - } - -#if DIAGNOZE_BANDWIDTH - diagCBytes = nBytes; - diagCMsg = nMsg; -#endif - - if (nMsg >= nMsgMax || nBytes >= nBytesMax) - { - #if _ENABLE_CHEATS - if (outputLogs) LogF(" Server to %s: limit reached (guaranteed)", (const char *)pInfo.name); - #endif - goto DoNotSendUpdates; - } - #endif // ENABLE_CRITICAL_UPDATES - } - -DoNotSendUpdates: - // send nonguaranteed enqueued messages - maxSize = MaxSizeNonguaranteed; - // note: even "nonguaranteed" may be actually sent as guaranteed, but they still have their own queue - NetMsgFlags flags = _updatesGuaranteed ? NMFGuaranteed : NMFNone; - int firstNonGuaranteedUnsent = 0; - int next = 0; // index of next object to update - bool empty = false; - while (true) - { - // enforce send last message - if (!empty || firstNonGuaranteedUnsent >= pInfo._messageQueueNonGuaranteed.Size()) - { - if (nMsg >= nMsgMax || nBytes >= nBytesMax) break; - } - - if (firstNonGuaranteedUnsent >= pInfo._messageQueueNonGuaranteed.Size()) - { - empty = true; - // starving, try to create further message - if (!PrepareNextUpdate(pInfo, objects, next)) break; - // local communication - message was already sent - if (pInfo.dpid == BOT_CLIENT) - { - DoAssert(firstNonGuaranteedUnsent >= pInfo._messageQueueNonGuaranteed.Size()); - nMsg++; - continue; - } - DoAssert(firstNonGuaranteedUnsent < pInfo._messageQueueNonGuaranteed.Size()); - } - - NetworkMessageQueueItem *item = pInfo._messageQueueNonGuaranteed[firstNonGuaranteedUnsent]; - int size = item->msg->size; - // enforce send last message - if (size >= maxSize || nMsg >= nMsgMax || nBytes >= nBytesMax) - { - RefR resultMsg; - int rawSize = SendMsgRemote(pInfo.dpid, item->msg, item->type, NMFStatsAlreadyDone|flags, &resultMsg, item->dependOn); - //item->SetFence(resultMsg); //nonquaranteed msg cannot raise a fence - - -#if LOG_SEND_PROCESS - LogF("Server: Message %x sent", dwMsgId); -#endif - firstNonGuaranteedUnsent++; - nMsg++; - nBytes += rawSize; - } - else - { - int totalSize = 0; - int i; - for (i=0; true; i++) - { - int queueIndex = firstNonGuaranteedUnsent + i; - if (queueIndex >= pInfo._messageQueueNonGuaranteed.Size()) - { - empty = true; - // starving, try to create further message - if (!PrepareNextUpdate(pInfo, objects, next)) break; - DoAssert(pInfo.dpid != BOT_CLIENT); - DoAssert(queueIndex < pInfo._messageQueueNonGuaranteed.Size()); - } - - NetworkMessageQueueItem *item = pInfo._messageQueueNonGuaranteed[queueIndex]; - int size = item->msg->size; - if (totalSize + size > maxSize) break; - totalSize += size; - } - - int queueEnd = firstNonGuaranteedUnsent + i; - int normalCount = CompactNetworkMessageQueueRange( - pInfo._messageQueueNonGuaranteed, firstNonGuaranteedUnsent, queueEnd, - [this,&pInfo,flags,&nMsg,&nBytes](NetworkMessageQueueItem *item) - { - // Send dependent messages immediately and keep their queue order. - RefR resultMsg; - int rawSize = SendMsgRemote(pInfo.dpid, item->msg, item->type, NMFStatsAlreadyDone|flags, &resultMsg, item->dependOn); - //item.SetFence(resultMsg); //nonguaranteed messages could not raise a fence - nMsg++; - nBytes += rawSize; - } - ); - - if (normalCount>0) - { - int rawSize = SendMsgQueue(pInfo.dpid, pInfo._messageQueueNonGuaranteed, firstNonGuaranteedUnsent, firstNonGuaranteedUnsent + normalCount, flags); -#if LOG_SEND_PROCESS - LogF("Server: Message %x sent", dwMsgId); -#endif - firstNonGuaranteedUnsent += normalCount; - nMsg++; - nBytes += rawSize; - } - } - } - if (firstNonGuaranteedUnsent > 0) pInfo._messageQueueNonGuaranteed.Delete(0, firstNonGuaranteedUnsent); - DoAssert(!empty || pInfo._messageQueueNonGuaranteed.Size() == 0); - - // search for maximum error not sent - //float sumError = 0; // messages not sent total error - float sumError = 0; - for (int i=next; imsg->size; - - RString output = Format("%s: HLWait%3d(%5dB)", (const char *)pInfo.name, count, size); - texts.Add(GEngine->ShowTextF(1000, output)); - texts.Add(GEngine->ShowTextF(1000, _server->GetStatistics(pInfo.dpid))); - - StatisticsById stats; - for (int i=0; i(item->type),item->msg->size); - } - stats.SortData(false); - int maxLines = 10; - for (int i=0; iShowTextF(1000, " %s: %d", cc_cast(name), item.count)); - } - } -#endif - } -} - -bool NetworkServer::PrepareNextUpdate(NetworkPlayerInfo &pInfo, AutoArray &objects, int &next) -{ - while (next < objects.Size()) - { - UpdateObjectInfo &info = objects[next++]; - if (info.criticalUpdate) continue; - -/* - #if _ENABLE_REPORT - int oldCount = pInfo._messageQueueNonGuaranteed.Size(); - #endif -*/ - NetworkObjectInfo *oInfo = info.oInfo; - if (oInfo) - { - NetworkMessageClass cls = info.cls; - int bytes = UpdateObject(&pInfo, oInfo, cls, NMFNone); - if (bytes < 0) continue; - #if _ENABLE_CHEATS - if (outputLogs) LogF(" Server to %s: Object updated - size %d bytes", (const char *)pInfo.name, bytes); - #endif - } - else - { - //NetworkComponent::SendMsg(pInfo.dpid, info.msg, info.type, NMFGuaranteed); - // non-guaranteed enqueues into the same queue as UpdateObject - SendMsg(pInfo.dpid, info.msg->msg, info.msg->type, NMFNone, NULL); - // set error to zero so that message is deleted - info.msg->error = 0; - #if _ENABLE_CHEATS - if (outputLogs) LogF(" Server to %s: Delayed message sent", (const char *)pInfo.name); - #endif - } -/* - #if _ENABLE_REPORT - if (oldCount == pInfo._messageQueueNonGuaranteed.Size()) - { - Fail("No message added during NetworkServer::PrepareNextUpdate"); - continue; - } - #endif -*/ - - return true; - } - return false; -} - -#if _HELISIM_ROTORLIB - #define ROTOR_LIB_MAP_UPDATE_TO_TYPE(XXXX) \ - XXXX(NMTUpdatePositionHelicopterRTD,HelicopterRTD) \ - XXXX(NMTUpdateHelicopterRTD,HelicopterRTD) - #define ROTOR_LIB_MAP_CREATE_TO_TYPE(XXXX) \ - XXXX(NMTCreateHelicopterRTD,HelicopterRTD) -#else - #define ROTOR_LIB_MAP_UPDATE_TO_TYPE(XXXX) - #define ROTOR_LIB_MAP_CREATE_TO_TYPE(XXXX) -#endif - -#define MAP_UPDATE_TO_TYPE(XXXX) \ - XXXX(NMTUpdateDamageObject,Object) \ - XXXX(NMTUpdateObject,Object) \ - XXXX(NMTUpdatePositionVehicle,Vehicle) \ - XXXX(NMTUpdateDamageVehicle,Vehicle) \ - XXXX(NMTUpdateVehicle,Vehicle) \ - XXXX(NMTUpdateDetector,Detector) \ - XXXX(NMTUpdateFlag,FlagCarrier) \ - XXXX(NMTUpdateShot,Shot) \ - XXXX(NMTUpdateMine,Mine) \ - XXXX(NMTUpdateWeapon,Weapon) \ - XXXX(NMTUpdateDamageVehicleAI,EntityAI) \ - XXXX(NMTUpdateVehicleAI,EntityAI) \ - XXXX(NMTUpdateVehicleBrain,Person) \ - XXXX(NMTUpdateTransport,Transport) \ - XXXX(NMTUpdatePositionMan,Man) \ - XXXX(NMTUpdateMan,Man) \ - XXXX(NMTUpdateTankOrCar,TankOrCar) \ - XXXX(NMTUpdatePositionTank,TankWithAI) \ - XXXX(NMTUpdateTank,TankWithAI) \ - XXXX(NMTUpdatePositionMotorcycle,Motorcycle) \ - XXXX(NMTUpdateMotorcycle,Motorcycle) \ - XXXX(NMTUpdatePositionCar,Car) \ - XXXX(NMTUpdateCar,Car) \ - XXXX(NMTUpdatePositionAirplane,AirplaneAuto) \ - XXXX(NMTUpdateAirplane,AirplaneAuto) \ - XXXX(NMTUpdatePositionHelicopter,HelicopterAuto) \ - XXXX(NMTUpdateHelicopter,HelicopterAuto) \ - XXXX(NMTUpdateParachute,ParachuteAuto) \ - XXXX(NMTUpdatePositionShip,ShipWithAI) \ - XXXX(NMTUpdateShip,ShipWithAI) \ - XXXX(NMTUpdatePositionDoor,Door) \ - XXXX(NMTUpdateDoor,Door) \ - XXXX(NMTUpdatePositionSeagull,SeaGullAuto) \ - XXXX(NMTUpdateSeagull,SeaGullAuto) \ - XXXX(NMTUpdateClientInfo,ClientInfoObject) \ - XXXX(NMTUpdateClientInfoDpid,ClientInfoObject) \ - XXXX(NMTUpdateFireplace,Fireplace) \ - XXXX(NMTUpdatePositionTurret,Turret) \ - XXXX(NMTUpdateTurret,Turret) \ - XXXX(NMTAIStatsMPRowUpdate,AIStatsMPRow) \ - XXXX(NMTUpdateClientCameraPosition,ClientCameraPositionObject) \ - XXXX(NMTUpdateInventoryItem,InventoryItem) \ - XXXX(NMTUpdateItemRadio,ItemRadio) \ - XXXX(NMTUpdateItemTransmitter,ItemTransmitter) \ - ROTOR_LIB_MAP_UPDATE_TO_TYPE(XXXX) - -#define MAP_CREATE_TO_TYPE(XXXX) \ - XXXX(NMTCreateObject,Object) \ - XXXX(NMTCreateVehicle,Vehicle) \ - XXXX(NMTCreateCrater,Crater) \ - XXXX(NMTCreateCraterOnVehicle,CraterOnVehicle) \ - XXXX(NMTCreateSoundOnVehicle,SoundOnVehicle) \ - XXXX(NMTCreateObjectDestructed,ObjectDestructed) \ - XXXX(NMTCreateDynSoundSource,DynSoundSource) \ - XXXX(NMTCreateShot,Shot) \ - XXXX(NMTCreateHelicopter,HelicopterAuto) \ - XXXX(NMTCreateSeagull,SeaGullAuto) \ - XXXX(NMTCreateTurret,Turret) \ - XXXX(NMTAIStatsMPRowCreate,AIStatsMPRow) \ - XXXX(NMTCreateClientCameraPosition,ClientCameraPositionObject) \ - XXXX(NMTCreateDestructionEffects,ItemTransmitter) \ - ROTOR_LIB_MAP_CREATE_TO_TYPE(XXXX) - -#define UPDATE_TO_TYPE_DISTANCE(typeNMT,Type) case typeNMT: return Type::UpdateDistance(); - -/** -@param msg1 last message received from an owner -@param msg2 last message sent to a remote client -*/ -float NetworkServer::CalculateErrorTime -( - NetworkMessageType type, NetworkMessage *msg1, NetworkMessage *msg2 -) -{ - if (type < 0 || type >= NMTN) - { - RptF("Server: Bad message %d format", (int)type); - return 0.0; - } - - float errCoefTime; - switch (type) - { - case NMTUpdatePositionVehicle: - case NMTUpdatePositionMan: - case NMTUpdatePositionTank: - case NMTUpdatePositionCar: - case NMTUpdatePositionMagazine: - case NMTUpdatePositionAirplane: - case NMTUpdatePositionHelicopter: -#if _HELISIM_ROTORLIB - case NMTUpdatePositionHelicopterRTD: -#endif - case NMTUpdatePositionShip: - case NMTUpdatePositionDoor: - case NMTUpdatePositionSeagull: - case NMTUpdatePositionMotorcycle: - errCoefTime = ERR_COEF_TIME_POSITION; - break; - default: - errCoefTime = ERR_COEF_TIME_GENERIC; - break; - } - - // update to clients on receiving on an update from an owner - float dt = msg1->time - msg2->time; - return errCoefTime * dt; -} - -/*! -\patch_internal 5102 Date 12/14/2006 by Jirka -- Fixed: Starting of MP missions in Retail Demo was broken -*/ - -void NetworkServer::SendMissionFile(int dpnid) -{ -#if _ENABLE_UNSIGNED_MISSIONS - -// RptF("*** Server: Send mission file to %d", dpnid); - - bool found = false; - bool foundParams = false; - NetworkPlayerInfo *player = NULL; - if (dpnid == 0) - { - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = *_players[i]; - if (info.clientState != NCSPlayerAssigned) continue; - if (info.dpid == BOT_CLIENT) - { - DoAssert(info.missionFileValid); - } - if (!info.missionFileValid) found = true; - if (!info.paramFileValid) foundParams = true; - } - } - else - { - DoAssert(dpnid != BOT_CLIENT); - player = GetPlayerInfo(dpnid); - if (!player) return; - if (player->clientState != NCSPlayerAssigned) return; - if (!player->missionFileValid) found = true; - if (!player->paramFileValid) foundParams = true; - } - - int maxSegmentSize = 512 - 50; - - if (foundParams) - { - QIFStreamB f; - RString src = GetMissionParameters(); - // char '$' is used as an indication of Local Settings directory (different on client than on server) - RString dst = RString("$\\MPMissionsCache\\__cur_mp.") + GetExtensionWizardMission(); - f.AutoOpen(src); - - TransferFileMessage msg; - msg._path = dst; - msg._totSize = f.rest(); - msg._totSegments = (msg._totSize + maxSegmentSize - 1) / maxSegmentSize; - msg._offset = 0; - for (int i=0; iparamFileValid) - SendMsg(dpnid, &msg, NMFGuaranteed); - - msg._offset += size; - } - } - - if (found) - { - QIFStreamB f; - RString src = _missionBank; - // FIX: transfer mission file always into tmp directory (do not rewrite original file) - // char '$' is used as an indication of Local Settings directory (different on client than on server) - RString dst = RString("$\\MPMissionsCache\\") + _missionHeader._fileName + RString(".pbo"); - f.AutoOpen(src); - - TransferMissionFileMessage msg; - msg._path = dst; - msg._totSize = f.rest(); - msg._totSegments = (msg._totSize + maxSegmentSize - 1) / maxSegmentSize; - msg._offset = 0; - for (int i=0; imissionFileValid) - SendMsg(dpnid, &msg, NMFGuaranteed); - - msg._offset += size; - } - } - - // do not send twice - if (dpnid == 0) - { - for (int j=0; j<_players.Size(); j++) - { - NetworkPlayerInfo &info = *_players[j]; -// RptF(" player %s, has state %s", (const char *)info.name, (const char *)FindEnumName(info.clientState)); - if (info.clientState == NCSPlayerAssigned) - { - info.missionFileValid = true; - info.paramFileValid = true; - SetClientState(info.dpid, NCSMissionReceived); - } - } - } - else - { - player->missionFileValid = true; - player->paramFileValid = true; - SetClientState(dpnid, NCSMissionReceived); - } - -#else - - bool foundParams = false; - NetworkPlayerInfo *player = NULL; - if (dpnid == 0) - { - for (int i=0; i<_players.Size(); i++) - { - NetworkPlayerInfo &info = _players[i]; - if (info.clientState != NCSPlayerAssigned) continue; - if (!info.paramFileValid) foundParams = true; - } - } - else - { - DoAssert(dpnid != BOT_CLIENT); - player = GetPlayerInfo(dpnid); - if (!player) return; - if (player->clientState != NCSPlayerAssigned) return; - if (!player->paramFileValid) foundParams = true; - } - - int maxSegmentSize = 512 - 50; - - if (foundParams) - { - QIFStreamB f; - RString src = GetMissionParameters(); - // char '$' is used as an indication of Local Settings directory (different on client than on server) - RString dst = RString("$\\MPMissionsCache\\__cur_mp.") + GetExtensionWizardMission(); - f.AutoOpen(src); - - TransferFileMessage msg; - msg._path = dst; - msg._totSize = f.rest(); - msg._totSegments = (msg._totSize + maxSegmentSize - 1) / maxSegmentSize; - msg._offset = 0; - for (int i=0; iparamFileValid) - SendMsg(dpnid, &msg, NMFGuaranteed); - - msg._offset += size; - } - } - - // do not send twice - if (dpnid == 0) - { - for (int j=0; j<_players.Size(); j++) - { - NetworkPlayerInfo &info = _players[j]; - // RptF(" player %s, has state %s", (const char *)info.name, (const char *)FindEnumName(info.clientState)); - if (info.clientState == NCSPlayerAssigned) - { - info.missionFileValid = true; - info.paramFileValid = true; - SetClientState(info.dpid, NCSMissionReceived); - } - } - } - else - { - player->missionFileValid = true; - player->paramFileValid = true; - SetClientState(dpnid, NCSMissionReceived); - } - -#endif // _ENABLE_UNSIGNED_MISSIONS -} - -//{ DEDICATED SERVER SUPPORT -#if _ENABLE_DEDICATED_SERVER - -RString GetPidFileName (); -extern bool MyPidFile; - -//! Create dedicated server -/*! -\param config name of server configuaration file -*/ -bool CreateDedicatedServer(SessionType sessionType, RString config) -{ - if (GWorld->Options()) - { - GWorld->Options()->DestroyHUD(-1); - } - - RString GetLiveGamertag(); - RString gamertag = GetLiveGamertag(); - if (gamertag.GetLength()>0) - { - GNetworkManager.Init(); - } - else - { - // create a system link dedicated server - GNetworkManager.Init("", GetServerPort(), false); - } - -#if _GAMES_FOR_WINDOWS - GWorld->CreateDSOptions(); -#endif - - RString password(""); - int maxPlayers = MAX_PLAYERS_DS; - - GameDataNamespace globals(NULL, RString(), false); // TODO: parsing namespace if access to globals needed - - ParamFile serverCfg; - serverCfg.Parse(config, NULL, NULL, &globals); - - ConstParamEntryPtr entry = serverCfg.FindEntry("password"); - if (entry) password = *entry; - - entry = serverCfg.FindEntry("maxPlayers"); - if (entry) maxPlayers = *entry; - maxPlayers += 1; // dedicated server occupy single slot - - RString steamServerName("SourceDayZ Community Server"); - entry = serverCfg.FindEntry("hostname"); - if (entry) steamServerName = *entry; - - int steamPort = 8766; - entry = serverCfg.FindEntry("steamPort"); - if (entry) steamPort = *entry; - - int steamQueryPort = 27016; - entry = serverCfg.FindEntry("steamQueryPort"); - if (entry) steamQueryPort = *entry; - - int port = GetServerPort(); - - int rating = 0; - - GNetworkManager.CreateSession(sessionType, RString(), password, maxPlayers, false, port, true, config, rating); - if (GNetworkManager.IsServer()) - { - RString title = APP_NAME " Console version " APP_VERSION_TEXT "." STRINGIZE(BUILD_NO)" : port %d"; - ConsoleTitle(title, GNetworkManager.GetServer()->GetSessionPort()); - // writting the pid of the server instance: - if ( GetPidFileName().GetLength() ) - { - FILE *pidFp; - if ( (pidFp = fopen((const char*)GetPidFileName(),"wt")) != NULL ) - { - fprintf(pidFp,"%d\n",getpid()); - fclose(pidFp); -#ifdef _WIN32 -#else - fchmod(fileno(pidFp),(S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)); -#endif - MyPidFile = true; - } - } -#if _ENABLE_STEAM && defined(_WIN64) - if (steamPort > 0 && steamPort <= 65535 && steamQueryPort > 0 && steamQueryPort <= 65535) - SteamOnlineServerStart(port, steamPort, steamQueryPort, cc_cast(steamServerName), maxPlayers - 1, !password.IsEmpty()); - else - LogF("Steamworks server-list ports are invalid; use steamPort and steamQueryPort in the dedicated server config"); -#endif - return true; - } - - ConsoleTitle("Server creation failed : %d", port); - return false; -} - -#define ENUM_LOAD(type, prefix, name) \ - entry = _serverCfg.FindEntry(#name); \ - if (entry) _eventHandlers[prefix##name] = *entry; - -/*! -\patch 1.24 Date 09/19/2001 by Jirka -- Added: parameters "motdInterval" and "motd" (for message of the day) added to dedicated server config -\patch 1.24 Date 09/21/2001 by Jirka -- Added: parameter "voteThreshold" added to dedicated server config -\patch 1.27 Date 10/16/2001 by Jirka -- Added: parameter "reportingIP" added to dedicated server config -to change / disable IP address of Query & Reporting master server. - When empty, reporting is disabled. - If entry missing, master.gamespy.com is used and server is advertised to GameSpy. -\patch 1.82 Date 8/27/2002 by Jirka -- Added: parameter "kickDuplicate" added to dedicated server config -\patch 5120 Date 1/18/2007 by Ondra -- New: parameter persistent in the server config to allow the mission to continue - even when no players are connected -\patch 5180 Date 11/12/2007 by Jirka -- New: BattlEye protection integration -*/ - -bool NetworkServer::SetDedicated(RString config) -{ - _dedicated = true; - - _serverCfg.Parse(config, NULL, NULL, &GParsingNamespace); // parsing namespace (persistent namespace needed for persistent ParamFile) - _missionIndex = -1; - - _motdInterval = 5; - ConstParamEntryPtr entry = _serverCfg.FindEntry("motdInterval"); - if (entry) _motdInterval = *entry; - - entry = _serverCfg.FindEntry("motd"); - if (entry) - { - for (int i=0; i<(*entry).GetSize(); i++) _motd.Add((*entry)[i]); - } - -#if _USE_BATTL_EYE_SERVER - entry = _serverCfg.FindEntry("battlEye"); - if (!entry || (bool)*entry) //battlEye is on by default - { - if (!_beIntegration.Init()) - { -#if _ENABLE_DEDICATED_SERVER - if (entry || (_beIntegration._initFailedReason!=BattlEye::BEReasonNotInstalled) ) - { - ConsoleF("BattlEye initialization failed"); - return false; - } -#endif - } - } -#endif - - _voteThreshold = 0.5; - entry = _serverCfg.FindEntry("voteThreshold"); - if (entry) _voteThreshold = *entry; - - // empty string is default now - // to disable reporting, use reportingIP = "noreport"; - entry = _serverCfg.FindEntry("reportingIP"); - if (entry) _reportingIP = *entry; - - entry = _serverCfg.FindEntry("kickDuplicate"); - if (entry) _kickDuplicate = *entry; - - entry = _serverCfg.FindEntry("equalModRequired"); - if (entry) _equalModRequired = *entry; - - entry = _serverCfg.FindEntry("verifySignatures"); - if (entry) - { - int verify = *entry; - if (verify>0) SetVerifySignatures(verify); - } - - // TODO: once stabilized, make _updatesGuaranteed the only option - entry = _serverCfg.FindEntry("guaranteedUpdates"); - if (entry) - { - _updatesGuaranteed = *entry; - } - -#if _ENABLE_STEAM_MATCHMAKING - entry = _serverCfg.FindEntry("steamPort"); - if (entry) - _steamPort = *entry; - else - _steamPort = 8766; // some default value used in prev. versions - - entry = _serverCfg.FindEntry("steamQueryPort"); - if (entry) - _steamQueryPort = *entry; - else - _steamQueryPort = 27016; // some default value used in prev. versions -#endif - - _buildNoRequired = _serverCfg.ReadValue("requiredBuild",0); - // server can never require version higher than it has, as the bot client should meet the requirements as well - if (BUILD_NO>0) - { - if (_buildNoRequired>BUILD_NO) _buildNoRequired = BUILD_NO; - } - - _secureIdRequired = _serverCfg.ReadValue("requiredSecureId",DefaultSecureIdRequired); - - entry = _serverCfg.FindEntry("persistent"); - if (entry) - { - _persistent = *entry; - } - - entry = _serverCfg.FindEntry("additionalSignedFiles"); - if (entry) - { - int n = entry->GetSize(); - _additionalSignedFiles.Realloc(n); - _additionalSignedFiles.Resize(n); - for (int i=0; iIsTextValue()) - { - RString timeStampFormat = *entry; - if (!timeStampFormat.IsEmpty()) - { - if (stricmp(timeStampFormat, "none")==0) GTimeStampFormat = TSFNone; - else if (stricmp(timeStampFormat, "short")==0) GTimeStampFormat = TSFShort; - else if (stricmp(timeStampFormat, "full")==0) GTimeStampFormat = TSFFull; - } - } - - entry = _serverCfg.FindEntry("disable3rdPerson"); - if(entry) - { - _disable3rdPerson = *entry; - } - - entry = _serverCfg.FindEntry("environmentTimeMul"); - if(entry) - { - _environmentTimeMul = *entry; - } - - // event handlers - SERVER_EVENT_ENUM(ServerEvent, SE, ENUM_LOAD) - - return true; -} - -void NetworkServer::Monitor(float interval) -{ - _monitorInterval = interval; - _monitorFrames = 0; - _monitorIn = 0; - _monitorOut = 0; - if (_monitorInterval > 0) _monitorNext = GlobalTickCount() + toInt(1000.0 * _monitorInterval); - else _monitorInterval = UINT_MAX,_monitorNext = UINT_MAX; -} - -void NetworkServer::OnMonitorIn(int size) -{ - if (_dedicated) _monitorIn += size; -} - -#endif -//} - -static bool LoadKey(const FileItem &file, AutoArray &keys) -{ - int index = keys.Add(); - keys[index].Load(file.path + file.filename); - // test duplicity - for (int i=0; iMaxVerifySignatures) _sigVerRequired = MaxVerifySignatures; // 2 is the max value currently supported - - // load all accepted keys - // core keys - ForMaskedFile("Keys\\", "*.bikey", LoadKey, _acceptedKeys); -#if _ENABLE_DEDICATED_SERVER - if (!_dedicated) -#endif - { - // user keys - RString GetUserDirectory(); - ForMaskedFile(GetUserDirectory() + RString("Keys\\"), "*.bikey", LoadKey, _acceptedKeys); - } - ForMaskedFile(RString("Expansion\\Keys\\"), "*.bikey", LoadKey, _acceptedKeys); - _acceptedKeys.Compact(); -} - -/*! -\patch 5164 Date 10/3/2007 by Jirka -- Fixed: Signature verification timeout significantly relaxed. -*/ - -//! verify signature of the single file -void NetworkServer::CheckSignature(int dpnid, int fileIndex, int level) -{ - NetworkPlayerInfo *info = GetPlayerInfo(dpnid); - if (!info) return; - - // check if the same question is not pending - if (info->signatureChecks.Pending(fileIndex)) - return; - - // send the question - DataSignatureAskMessage ask; - ask._index = fileIndex; - ask._level = level; - SendMsg(dpnid, &ask, NMFGuaranteed); - - // add the question to the list of pending questions - info->signatureChecks.Add(fileIndex); -} - -//! verify signature of the single file -void NetworkServer::CheckSignature(int dpnid, RString filename, RString prefix, int level) -{ - NetworkPlayerInfo *info = GetPlayerInfo(dpnid); - if (!info) return; - - // check if the same question is not pending - if ( info->signatureChecks.Pending(filename) ) - return; - - // send the question - FileSignatureAskMessage ask; - ask._file = filename; - ask._level = level; - SendMsg(dpnid, &ask, NMFGuaranteed); - - // add the question to the list of pending questions - info->signatureChecks.Add(filename, prefix); -} - -bool NetworkServer::MyHash(Temp &hash, RString prefix, int sigVer, int level) -{ - // find the stored hash using prefix as key in bankHashes array - int i=0; - for (; i= info.offset) - { - index = i; - if (info.offset + info.size == _modified[i].offset) - { - // join with the next block - _modified[index].offset = info.offset; - _modified[index].size += info.size; - } - else - { - // insert the new block - _modified.Insert(index, info); - } - } - } - if (index < 0) - { - // append it - index = _modified.Add(info); - } - // check if the new block can be merged with the previous one - if (index > 0) - { - ExeSegmentInfo &block1 = _modified[index - 1]; - ExeSegmentInfo &block2 = _modified[index]; - if (block1.offset + block1.size == block2.offset) - { - block1.size += block2.size; - _modified.Delete(index); - } - } - } - else - { - // store further investigations - ExeSegmentInfo &add1 = _stack.Append(); - ExeSegmentInfo &add2 = _stack.Append(); - add1.offset = info.offset; - add1.size = info.size / 2; - add2.offset = info.offset + add1.size; - add2.size = info.size - add1.size; - } - } - - // remove the handled question - _stack.Delete(0); - _asked = false; - _client1._answered = false; - _client2._answered = false; - - if (_stack.Size() == 0) - { - // investigation finished, output the results - QOFStream out; - out.openForAppend("cheats.txt"); - for (int i=0; i<_modified.Size(); i++) - { - RString line = Format(" 0x%08x:0x%08x\r\n", _modified[i].offset, _modified[i].size); - out << line; - } - out.close(); - } -} - -#endif -//))EXE_CRC_CHECK - -bool NetworkServer::GetClientAddress(int client, sockaddr_in &address) -{ - if (client == BOT_CLIENT) - return _server->GetServerAddress(address); - else - return _server->GetClientAddress(client, address); -} - -////////////////////////////////////////////////////////////////////////// -// -// Server scripting functions and event handlers processing -// - -/*! -\patch 5126 Date 2/1/2007 by Jirka -- Added: MP - new server scripting function lock -- Added: MP - new commands #lock, #unlock -*/ - -#if _ENABLE_DEDICATED_SERVER - -DEFINE_ENUM(ServerEvent, SE, SERVER_EVENT_ENUM) - -void NetworkServer::SetEventHandler(RString name, RString value) -{ - ServerEvent event = GetEnumValue(cc_cast(name)); - if (event != INT_MIN) _eventHandlers[event] = value; -} - -bool NetworkServer::OnEvent(ServerEvent event, float par) -{ - RString handler = _eventHandlers[event]; - if (handler.GetLength() == 0) return false; - - GameValue value = GWorld->GetGameState()->CreateGameValue(GameArray); - GameArrayType &arguments = value; - arguments.Add(par); - - GameVarSpace local(false); - int gshandle = _evaluator.BeginContext(&local); - _evaluator.VarSetLocal("_this", arguments, true); - _evaluator.Execute(handler, GameState::EvalContext::_default, &_globals); // server namespace - _evaluator.EndContext(gshandle); - - return true; -} - -bool NetworkServer::OnEvent(ServerEvent event, float par1, float par2) -{ - RString handler = _eventHandlers[event]; - if (handler.GetLength() == 0) return false; - - GameValue value = GWorld->GetGameState()->CreateGameValue(GameArray); - GameArrayType &arguments = value; - arguments.Add(par1); - arguments.Add(par2); - - GameVarSpace local(false); - int gshandle = _evaluator.BeginContext(&local); - _evaluator.VarSetLocal("_this", arguments, true); - _evaluator.Execute(handler, GameState::EvalContext::_default, &_globals); // server namespace - _evaluator.EndContext(gshandle); - - return true; -} - -bool NetworkServer::OnEvent(ServerEvent event, float par1, RString par2) -{ - RString handler = _eventHandlers[event]; - if (handler.GetLength() == 0) return false; - - GameValue value = GWorld->GetGameState()->CreateGameValue(GameArray); - GameArrayType &arguments = value; - arguments.Add(par1); - arguments.Add(par2); - - GameVarSpace local(false); - int gshandle = _evaluator.BeginContext(&local); - _evaluator.VarSetLocal("_this", arguments, true); - _evaluator.Execute(handler, GameState::EvalContext::_default, &_globals); // server namespace - _evaluator.EndContext(gshandle); - - return true; -} - -#if _VBS3 -// forward declaration of checksize and checktype in gamestate.cpp -bool CheckSize(const GameState *state, GameArrayType array, int size); -#else -inline bool CheckSize(const GameState *state, GameArrayType array, int size) -{ - if (array.Size() == size) return true; - state->SetError(EvalDim, array.Size(), size); - return false; -} -#endif - -#if _VBS3 -// forward declaration of checksize and checktype in gamestate.cpp -bool CheckType(const GameState *state, GameValuePar oper, const GameType &type); -#else -inline bool CheckType(const GameState *state, GameValuePar oper, const GameType &type) -{ - if (oper.GetType() == type) return true; - state->TypeError(type, oper.GetType()); - return false; -} -#endif - -GameValue ServerUsers(const GameState *state) -{ - GameValue value = state->CreateGameValue(GameArray); - - NetworkServer *server = GNetworkManager.GetServer(); - if (!server) return value; - const AutoArray *identities = server->GetIdentities(); - if (!identities) return value; - - int n = identities->Size(); - GameArrayType &array = value; - array.Realloc(n); - array.Resize(n); - for (int i=0; iCreateGameValue(GameArray); - GameArrayType &subarray = array[i]; - subarray.Realloc(2); - subarray.Resize(2); - subarray[0] = (float)identity.playerid; - subarray[1] = identity.GetName(); - } - - return value; -} - -GameValue ServerBan(const GameState *state, GameValuePar oper1) -{ - NetworkServer *server = GNetworkManager.GetServer(); - if (!server) return NOTHING; - - int playerId = toInt((float)oper1); - const PlayerIdentity *identity = server->FindIdentityByPlayerId(playerId); - if (!identity) return NOTHING; - - // add global ban list - FindArray banList; - LoadBanList("ban.txt", banList); - GFileServerFunctions->FlushReadHandle("ban.txt"); - banList.AddUnique(identity->id); - SaveBanList("ban.txt", banList); - - // kick off - server->KickOff(identity->dpnid, KORBan); - - return NOTHING; -} - -GameValue ServerKick(const GameState *state, GameValuePar oper1) -{ - NetworkServer *server = GNetworkManager.GetServer(); - if (!server) return NOTHING; - - int playerId = toInt((float)oper1); - const PlayerIdentity *identity = server->FindIdentityByPlayerId(playerId); - if (!identity) return NOTHING; - - server->KickOff(identity->dpnid, KORKick); - - return NOTHING; -} - -GameValue ServerKickUID(const GameState *state, GameValuePar oper1) -{ - NetworkServer *server = GNetworkManager.GetServer(); - if (!server) return NOTHING; - - if (oper1.GetType()==GameString) - { - RString id = oper1; - const AutoArray *identities = server->GetIdentities(); - const PlayerIdentity *identity = NULL; - for (int i=0; i<(*identities).Size(); i++) - { - if ( IsUserIdMatch((*identities)[i].id, id) ) - { - identity = &(*identities)[i]; - break; - } - } - if (!identity) return NOTHING; - - server->KickOff(identity->dpnid, KORKick); - } - return NOTHING; -} - -GameValue ServerBanUID(const GameState *state, GameValuePar oper1) -{ - NetworkServer *server = GNetworkManager.GetServer(); - if (!server) return NOTHING; - - if (oper1.GetType()==GameString) - { - RString id = oper1; - - // add global ban list - FindArray banList; - LoadBanList("ban.txt", banList); - GFileServerFunctions->FlushReadHandle("ban.txt"); - banList.AddUnique(id); - SaveBanList("ban.txt", banList); - - // kick off - return ServerKickUID(state, oper1); - } - return NOTHING; -} - -GameValue ServerNFiles(const GameState *state, GameValuePar oper1) -{ - NetworkServer *server = GNetworkManager.GetServer(); - if (!server) return 0.0f; - - int playerId = toInt((float)oper1); - const PlayerIdentity *identity = server->FindIdentityByPlayerId(playerId); - if (!identity) return 0.0f; - - return (float)identity->filesCount; -} - -GameValue ServerLock(const GameState *state, GameValuePar oper1) -{ - NetworkServer *server = GNetworkManager.GetServer(); - if (server) server->LockSession(oper1); - return NOTHING; -} - -//((EXE_CRC_CHECK -#if !_SUPER_RELEASE -GameValue ServerCmpExe(const GameState *state) -{ - NetworkServer *server = GNetworkManager.GetServer(); - if (!server) return false; - - // check if exactly two identities are present - int dpid1 = 0, dpid2 = 0, dpidCount = 0; - const AutoArray *identities = server->GetIdentities(); - if (!identities) return false; - for (int i=0; iSize(); i++) - { - const PlayerIdentity &identity = identities->Get(i); - if (identity.dpnid == BOT_CLIENT) continue; - dpidCount++; - if (dpidCount == 1) - dpid1 = identity.dpnid; - else if (dpidCount == 2) - dpid2 = identity.dpnid; - else - break; - } - if (dpidCount != 2) return false; - - // start the exe investigation - server->CompareExe(dpid1, dpid2); - return true; -} -#endif -//))EXE_CRC_CHECK - -#define NULARS_SERVER(XX, Category) \ - XX(GameArray, "users", ServerUsers, "The list of the users connected to the server.", "", "", "2.92", "", Category) \ - -//((EXE_CRC_CHECK -#define NULARS_SERVER_DEBUG(XX, Category) \ - XX(GameBool, "cmpExe", ServerCmpExe, "Compare executable of two connected clients.", "", "", "5170", "", Category) \ -//))EXE_CRC_CHECK - -#define FUNCTIONS_SERVER(XX, Category) \ - XX(GameNothing, "ban", ServerBan, GameScalar, "user id", "Add the user to the server ban list.", "", "", "2.92", "", Category) \ - XX(GameNothing, "kick", ServerKick, GameScalar, "user id", "Kick the user from the server.", "", "", "2.92", "", Category) \ - XX(GameScalar, "numberOfFiles", ServerNFiles, GameScalar, "user id", "Return the number of files used by the user.", "", "", "2.92", "", Category) \ - XX(GameNothing, "lock", ServerLock, GameBool, "lock", "Lock / unlock the session.", "", "", "5126", "", Category) \ - -#define OPERATORS_SERVER(XX, Category) \ - -NULARS_SERVER(JNI_NULAR, "Server") -#if !_SUPER_RELEASE - NULARS_SERVER_DEBUG(JNI_NULAR, "Server Debug") -#endif - -static const GameNular ServerNular[]= -{ - NULARS_SERVER(REGISTER_NULAR, "Server") -//((EXE_CRC_CHECK -#if !_SUPER_RELEASE - NULARS_SERVER_DEBUG(REGISTER_NULAR, "Server Debug") -#endif -//))EXE_CRC_CHECK -}; - -FUNCTIONS_SERVER(JNI_FUNCTION, "Server") - -static const GameFunction ServerUnary[]= -{ - FUNCTIONS_SERVER(REGISTER_FUNCTION, "Server") -}; - -OPERATORS_SERVER(JNI_OPERATOR, "Server") - -#if 0 // -static const GameOperator ServerBinary[]= -{ - OPERATORS_SERVER(REGISTER_OPERATOR, "Server") -}; -#endif - -void NetworkServer::InitEvaluator() -{ - // global namespace need to be passed explicitly - _evaluator.DisableDefaultGlobals(); - - // no special types - - // functions - for(int i=0; i= 32 || _sqfExecQueue.Size() != _sqfExecFrom.Size()) - { - RptF("SDZ_SQF_EXEC: rejected command because the execution queue is full or inconsistent"); - return; - } - _sqfExecQueue.Add(expression); - _sqfExecFrom.Add(from); -} - -#if defined(_MSC_VER) -// Keep SEH in a helper without C++ objects that have destructors. -static bool SDZ_TryEvaluateSqf(GameState *state, const char *expression, GameDataNamespace *globals, GameValue *result) -{ - __try - { - *result = state->EvaluateMultiple(expression, GameState::EvalContext::_default, globals); - return true; - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - RptF("SDZ_SQF_EXEC: exception 0x%08X while evaluating script", (unsigned)GetExceptionCode()); - return false; - } -} -#endif - -void NetworkServer::ProcessQueuedExec() -{ - if (_sqfExecBusy || _sqfExecQueue.Size() <= 0) return; - _sqfExecBusy = true; - - GameState *execState = GWorld ? GWorld->GetGameState() : NULL; - GameDataNamespace *mission = GWorld ? GWorld->GetMissionNamespace() : NULL; - if (!execState || !mission) - { - _sqfExecQueue.Resize(0); - _sqfExecFrom.Resize(0); - _sqfExecBusy = false; - return; - } - - while (_sqfExecQueue.Size() > 0) - { - RString expression = _sqfExecQueue[0]; - int from = _sqfExecFrom[0]; - _sqfExecQueue.Delete(0); - _sqfExecFrom.Delete(0); - - GameVarSpace local(false); - int gshandle = execState->BeginContext(&local); - GameValue result = NOTHING; - bool evaluated = false; -#if defined(_MSC_VER) - evaluated = SDZ_TryEvaluateSqf(execState, expression, mission, &result); -#else - result = execState->EvaluateMultiple(expression, GameState::EvalContext::_default, mission); - evaluated = true; -#endif - RString answer; - if (evaluated && !result.GetNil()) answer = result.GetText(); - if (from == BOT_CLIENT) - RptF("SDZ_BE_RCON: SQF evaluation %s", evaluated ? "completed" : "failed (see preceding exception)"); - result = NOTHING; - execState->EndContext(gshandle); - - if (from != BOT_CLIENT && answer.GetLength() > 0) - { - NetworkCommandMessage msg; - msg._type = NCMTExecResult; - msg._content.WriteString(answer); - SendMsg(from, &msg, NMFGuaranteed); - } - } - _sqfExecBusy = false; -} - -#endif // _ENABLE_DEDICATED_SERVER - -void ServerQueueItem::SetFence(const RefR &resultMsg) -{ - if (poInfo) poInfo->_fence = resultMsg; -} - -DWORD NetworkServer::SendMsg -( - int to, NetworkMessage *msg, - NetworkMessageType type, NetMsgFlags dwFlags, - NetworkPlayerObjectInfo *poInfo -) -{ -#if _ENABLE_MP - NetworkMessageFormatBase *format = GetFormat(type); - if (!format) return 0xffffffff; - - if (IsLocalClient(to)) - { - msg->size = 0; - NetworkClient *client = _parent->GetClient(); - client->AddLocalMessage(TO_SERVER, type, msg); - return 0; - } - else if (dwFlags & NMFGuaranteed) - { - msg->size = CalculateMessageSize(msg, type); -#if _ENABLE_CHEATS -StatMsgSent(type, msg->size, dwFlags); -#endif - if (dwFlags&NMFHighPriority) - { - SendMsgRemote(to,msg,type,dwFlags|NMFStatsAlreadyDone, poInfo ? &poInfo->_fence : NULL, NULL); - return 0; - } - else - { - EnqueueMsg(to, msg, type, poInfo); - return 0; - } - } - else - { - msg->size = CalculateMessageSize(msg, type); -#if _ENABLE_CHEATS -StatMsgSent(type, msg->size, dwFlags); -#endif - //invalidate fence when message is acknowledged - RefR fence; - if (poInfo && poInfo->_fence) - { - if ( poInfo->_fence->WasReceived() ) poInfo->_fence = NULL; - else fence = poInfo->_fence; - } - EnqueueMsgNonGuaranteed(to, msg, type, fence); - return 1; - } -#else - return E_FAIL; -#endif -} +#include "../wpch.hpp" +#include "networkImpl.hpp" +#include "networkQueueUtils.hpp" + +#include "../global.hpp" +//#include "strIncl.hpp" +#include "../stringtableExt.hpp" + +#include "../arcadeTemplate.hpp" +#include "../AI/ai.hpp" +#include "../world.hpp" +#include "../landscape.hpp" +#include "../UI/chat.hpp" +#include "../UI/uiMap.hpp" +#include "../UI/missionDirs.hpp" +#include + +#include +#include +#include +#include "Es/Containers/RTree.hpp" + +#include "../allAIVehicles.hpp" +#include "../seaGull.hpp" +#include "../detector.hpp" +#include "../shots.hpp" +#include "../fileLocator.hpp" +#include "../gameDirs.hpp" +#include "../registration.hpp" + +#include +#include + +#include +#include +#include + +#if _ENABLE_STEAM && defined(_WIN64) +bool SteamOnlineServerStart(int gamePort, int steamPort, int queryPort, const char *serverName, int maxPlayers, bool passwordProtected); +#endif + +#include + +#include +#include "../gameStateExt.hpp" + +#include "../progress.hpp" +#include + +#include "geoLoc.hpp" +#include "../keyInput.hpp" +#include "../dikCodes.h" +#include "../UI/uiActions.hpp" + +#include +#include +#include +#include + +#include "../saveGame.hpp" +#include "../saveVersion.hpp" + +#include "../AI/aiRadio.hpp" +#include + +#include +#include + +#include "httpRequest.h" + +#ifdef _WIN32 + #include +#endif + +#if defined(_WIN32) + #if _ENABLE_MP + #include + #endif + #if _ENABLE_DEDICATED_SERVER + #include + #endif +#endif + +#include "El/Speech/debugVoN.hpp" + +#if _PROFILE +#pragma optimize( "", off ) +#endif + +/*! +\file +Basic implementation file for network server +*/ + +//((EXE_CRC_CHECK +// random integrity check +#if _SUPER_RELEASE + #define _ENABLE_RANDOM_INTEGRITY_CHECK 1 +#else + #define _ENABLE_RANDOM_INTEGRITY_CHECK 0 +#endif +//))EXE_CRC_CHECK + +#define LOG_SEND_PROCESS 0 + +#define LOG_PLAYERS 1 + +extern int MaxCustomFileSize; + +#define QOS_SERVER_BANDWIDTH 4096 + +//! enable diagnostic logs of message errors +#define LOG_ERRORS 0 +//! limit for diagnostic logs of message errors +static float LogErrorLimit = 1.0f; + +extern GameValue GNetworkPlayerConnected; +extern GameValue GNetworkPlayerDisconnected; + + +RStringB GetExtensionWizardMission(); + +/// generate a 32-bit random number (Implementation of rand() in MSVC returns only 15 bits) +int rand32() +{ + return (rand() & 0x7fff) | (rand() & 0x7fff) << 15 | (rand() & 0x0003) << 30; + +} + +#define STRINGIZE_X(x) #x +#define STRINGIZE(x) STRINGIZE_X(x) + +/*! +\patch 5257 Date 7/15/2008 by Bebul +- Fixed: Players connecting JIP with custom files do not cause server lagging. +\patch 5257 Date 7/15/2008 by Bebul +- Fixed: Players with custom files get no longer kicked when server does not run on default port. +*/ +static RString GetServerPath(RString src) +{ + if (src.GetLength() == 0) return src; + if (src[0] == '$') + { // translate char '$' to Local Settings directory + char dir[MAX_PATH]; + if (!GetLocalSettingsDir(dir)) return src.Substring(2, INT_MAX); // place in current directory + TerminateBy(dir, '\\'); + return RString(dir) + src.Substring(2, INT_MAX); + } + else if (src[0] == '#') + { // translate char '#' to Local Settings directory + ServerTmpDir + return GetServerTmpDir() + src.Substring(1, INT_MAX); // place in current directory + } + else return src; +} + +/*! + \patch 5088 Date 11/06/2006 by Ondra + - Fixed: Possible crash when exiting multiplayer game. +*/ + +void ClearNetServer() +{ +} + +// Moved, declarations needed in BE + +//{ QUERY & REPORTING SDK +#if _ENABLE_GAMESPY + +#define REPORT_ASE 0 + +#include "../GameSpy/qr2/qr2.h" +#include "../GameSpy/natneg/natneg.h" +#if _VERIFY_CLIENT_KEY +# include "../GameSpy/gcdkey/gcdkeys.h" +# ifdef NOMINMAX +# undef min +# undef max +# endif +#include "../GameSpy/gcdkey/gcdkeyc.h" +#endif + +# ifdef NOMINMAX +# undef min +# undef max +# endif + +REGISTER_CREDITS("GameSpy", "2009 GameSpy Industries, Inc.","") + +#if REPORT_ASE +extern "C" +{ +#include "../ASE/ASEMasterSDK.h" +} +#endif + +#ifdef NOMINMAX +# undef min +# undef max +#endif + +char *GetGameName() +{ + // GameSpy game name +#if _LIBERATION + return "IFpc"; +#elif _DEMO + return "takoncopterpcd"; +#else + return "takoncopterpc"; +#endif +} + +char *GetSecretKey() +{ + // GameSpy secret key + static char secret_key[9]; + + //set the secret key, in a semi-obfuscated manner + secret_key[0] = '6'; + secret_key[1] = 'P'; + secret_key[2] = 'V'; + secret_key[3] = 'I'; + secret_key[4] = 'h'; + secret_key[5] = 'e'; + secret_key[6] = '\0'; + + return secret_key; +} + +int GetGameID() +{ + // GameSpy game id +#if _LIBERATION + return 4077; +#elif _DEMO + return 5132; +#else + return 4093; +#endif +} + +int GetProductID() +{ + // GameSpy product id +#if _LIBERATION + return 13905; +#elif _DEMO + return 13916; +#else + return 13916; +#endif +} + +char *GetGcdHostname() +{ + //host DNS - default + return ""; +} + +#endif +//} + +DEFINE_FAST_ALLOCATOR(NetworkPlayerObjectInfo) + +NetworkObjectInfo::NetworkObjectInfo() +{} + + +NetworkObjectInfo::~NetworkObjectInfo() +{ + +} + +#if _PROFILE && USER_Ondra +typedef Journal ProfileJournal; +#else +typedef DummyJournal ProfileJournal; +#endif + +ProfileJournal NetworkPlayerObjectInfoJournal; + +NetworkPlayerObjectInfo::NetworkPlayerObjectInfo() +:updating(false) +{ + NetworkPlayerObjectInfoJournal.Add(Format("Construct %x",this)); +} + +NetworkPlayerObjectInfo::~NetworkPlayerObjectInfo() +{ + NetworkPlayerObjectInfoJournal.Add(Format("Destruct %x, %d",this,IsInList())); +} + +NetworkPlayerObjectInfo *NetworkObjectInfo::GetPlayerObjectInfo(PlayerIndex player, int pid) +{ + DoAssert(playerToObjects[player]->player==pid); + return playerToObjects[player]; +} + +NetworkPlayerObjectInfo *NetworkObjectInfo::CreatePlayerObjectInfo(PlayerIndex player, int pid) +{ + if (player < playerToObjects.Size()) + { + return playerToObjects[player]; + } + int index = playerToObjects.Add(); + DoAssert(index==player); + playerToObjects[index] = new NetworkPlayerObjectInfo; + NetworkPlayerObjectInfo *poInfo = playerToObjects[index]; + poInfo->player = pid; + poInfo->oInfo = this; + for (int j=NMCUpdateFirst; jupdates[j]; + info.errorValid = false; + } + return poInfo; +} + +void NetworkObjectInfo::ResetPlayerObjectInfo(PlayerIndex player, int pid) +{ + if (player<0) return; + DoAssert(playerToObjects[player]->player==pid); + NetworkPlayerObjectInfo *poInfo = playerToObjects[player]; + for (int j=NMCUpdateFirst; jupdates[j]; + info.errorValid = false; + } +} + +void NetworkObjectInfo::DeletePlayerObjectInfo(PlayerIndex player, int pid) +{ + if (player<0) return; + DoAssert(playerToObjects[player]->player==pid); + playerToObjects.Delete(player); +} + +void NetworkObjectInfo::NullPlayerObjectInfo(PlayerIndex player, int pid) +{ + if (player<0) return; + DoAssert(playerToObjects[player]->player==pid); + playerToObjects[player].Free(); +} + +RString NetworkObjectInfo::GetDebugName() const +{ + if (object.IsNull()) return Format("id=%d:%" OID_FORMAT,id.creator,id.id); + return object->GetDebugName(); +} + +NetworkObjectInfo::UpdateInfo NetworkObjectInfo::CheckBestPosition(const NetworkServer *server) const +{ + Vector3 bestPos = VZero; + NetworkMessageClass bestJ = NMCUpdateN; + if (object.NotNull()) + { + + // find the last update of the object + Time time = TIME_MIN; + for (int j=NMCUpdateFirst; jtime > time) + { + time = msg->time; + bestJ = NetworkMessageClass(j); + } + } + } + if (bestJ!=NMCUpdateN) + { + const auto &best = currentUpdate[bestJ]; + + // retrieve position of the object + NetworkMessageContext ctx(best.message, unconst_cast(server), best.from, MSG_RECEIVE); + + PREPARE_TRANSFER(NetworkObject) + if (TRANSF_BASE(objectPosition, bestPos) != TMOK) + { + bestPos = VZero; + bestJ = NMCUpdateN; + } + + } + } + DoAssert(bestJ==NMCUpdateN || bestPos!=VZero); + NetworkObjectInfo::UpdateInfo ret; + if (bestJ!=NMCUpdateN) + { + ret._pos = bestPos; + ret._updateDistance = object ? object->UpdateDistance() : FLT_MAX; + DoAssert(object); + } + + return ret; +} + + +void NetworkObjectInfo::ScanBestPosition(const NetworkServer *server) +{ + _updInfo = CheckBestPosition(server); +} + +NetworkObjectInfo::UpdateInfo NetworkObjectInfo::BestPosition(const NetworkServer *server) const +{ + #if 0 // _ENABLE_REPORT + UpdateInfo updInfo = CheckBestPosition(server); + DoAssert(updInfo._pos==_updInfo._pos); + DoAssert(updInfo._root==_updInfo._root); + DoAssert(updInfo._updateDistance==_updInfo._updateDistance); + #endif + return _updInfo; +} + +bool NetworkObjectInfo::CheckBestPositionIntegrity(const NetworkServer *server) const +{ + UpdateInfo updInfo = CheckBestPosition(server); + // TODO: enforce strict equality + if (updInfo._pos.Distance2(_updInfo._pos)>Square(0.01f)) + { + LogF("%s: pos not matching",cc_cast(GetDebugName())); + return false; + } + if (updInfo._updateDistance!=_updInfo._updateDistance) + { + LogF("%s: updateDistance not matching",cc_cast(GetDebugName())); + return false; + } + return true; +} + + +NetworkObjectInfo::UpdateInfo NetworkObjectInfo::BestPosition() const +{ + return _updInfo; +} + + +#if _ENABLE_DEDICATED_SERVER +int ConsoleF(const char *format, ...); +int VConsoleF(const char *format, va_list argptr); +int ConsoleTitle(const char *format, ...); +#endif +RString GetUserDirectory(); + +#if _USE_BATTL_EYE_SERVER +/*! +\patch 5254 Date 5/2/2008 by Bebul +- Fixed: BattlEye issues while using server.cfg on Linux dedicated server +\patch 5276 Date 4/16/2009 by Bebul +- Fixed: Changed BattlEye integration (fixing "random" player kicks) +*/ + +#include +#ifndef _WIN32 +#include +#endif + +NetworkServer::BattlEye::BattlEye() +{ + CleanUp(); +} + +NetworkServer::BattlEye::~BattlEye() +{ + Done(); +} + +bool GetBELaunchPath(char *launchPath) +{ +#ifndef _XBOX + RString GetBEPath(); + RString forcedPath = GetBEPath(); +#else + RString forcedPath; +#endif + + // decide the path to the "cache" from where dll is used + if (IsRelativePath(forcedPath)) + { + // relative path +#ifdef _WIN32 + if (!GetLocalSettingsDir(launchPath)) return false; + TerminateBy(launchPath, '\\'); + strcat(launchPath, "BattlEye\\"); + strcat(launchPath, forcedPath); + TerminateBy(launchPath, '\\'); +#else + strcpy(launchPath, "./battleye/"); + strcat(launchPath, forcedPath); + CreateDirectory(launchPath, NULL); + TerminateBy(launchPath, '/'); +#endif + } + else + { + // absolute path + strcpy(launchPath, forcedPath); +#ifdef _WIN32 + TerminateBy(launchPath, '\\'); +#else + TerminateBy(launchPath, '/'); +#endif + } + + return true; +} + +#define STRINGIZE_X(x) #x +#define STRINGIZE(x) STRINGIZE_X(x) + +#ifdef _WIN32 + +int NetworkServer::BattlEye::GetBEVersion(HMODULE library) const +{ + if (library) + { + GetVerF *getVer = (GetVerF *)GetProcAddress(library, "GetVer"); + if (getVer) return (*getVer)(); + } + return 0; +} + +// Win32 implementation +bool NetworkServer::BattlEye::Init() +{ + _initFailedReason = BEReasonOther; + _initialized = false; + const char *installPath = "BattlEye\\BEServer.dll"; + char launchPath[MAX_PATH]; + if (!GetBELaunchPath(launchPath)) return false; + + int curBEVersion = 0; + if (QIFileFunctions::FileExists(installPath)) + { + GFileServerFunctions->FlushReadHandle(installPath); + // Get the BEClient.dll version from installPath first + HMODULE installLibrary = LoadLibrary(installPath); + int instVersion = GetBEVersion(installLibrary); + if (installLibrary) + FreeLibrary(installLibrary); + + CreatePath(launchPath); + strcat(launchPath, "BEServer.dll"); + // try to load the dll from the cache + _library = LoadLibrary(launchPath); + if (_library) + { // check whether the BE is updated to the last version + curBEVersion = GetBEVersion(_library); + if (instVersion>curBEVersion) + { + FreeLibrary(_library); + _library = NULL; // so it will be repaired from the install path + } + } + if (!_library) + { + // install / repair the live copy from the install path + chmod(launchPath, S_IREAD | S_IWRITE); + unlink(launchPath); + QIFileFunctions::Copy(installPath, launchPath); + _library = LoadLibrary(launchPath); + if (!_library) return false; +#if _ENABLE_DEDICATED_SERVER + ::ConsoleF(Format("BattlEye server updated to version: %d", instVersion)); +#endif + curBEVersion = instVersion; + } + } + else + { + // BattlEye removed, remove also from the cache + strcat(launchPath, "BEServer.dll"); + chmod(launchPath, S_IREAD | S_IWRITE); + unlink(launchPath); + _initFailedReason = BEReasonNotInstalled; + return false; + } + + InitF *init = (InitF *)GetProcAddress(_library, "Init"); + + _gameParams.pstrGameVersion = APP_NAME " " APP_VERSION_TEXT "." STRINGIZE(BUILD_NO); + _gameParams._execCommand = &ExecuteCommand; + _gameParams._kickPlayer = &KickPlayer; + _gameParams._printMessage = &PrintMessage; + if ((curBEVersionFlushReadHandle(installPath); + CreatePath(launchPath); + strcat(launchPath, "beserver.so"); + // use the install copy instead + _library = dlopen(launchPath, RTLD_LAZY); + if (!_library) + { + // install / repair the live copy from the install path + chmod(launchPath, S_IREAD | S_IWRITE); + unlink(launchPath); + QIFileFunctions::Copy(installPath, launchPath); + _library = dlopen(launchPath, RTLD_LAZY); + if (!_library) return false; + } + } + else + { + // BattlEye removed, remove also from the cache + strcat(launchPath, "beserver.so"); + chmod(launchPath, S_IREAD | S_IWRITE); + unlink(launchPath); + _initFailedReason = BEReasonNotInstalled; + return false; + } + int curBEVersion = GetBEVersion(_library); + + InitF *init = (InitF *)dlsym(_library, "Init"); + _gameParams.pstrGameVersion = APP_NAME " " APP_VERSION_TEXT "." STRINGIZE(BUILD_NO); + _gameParams._execCommand = &ExecuteCommand; + _gameParams._kickPlayer = &KickPlayer; + _gameParams._printMessage = &PrintMessage; + if ((curBEVersion *identities = server->GetIdentities(); + if (identities) + { + for (int i=0; iSize(); i++) + { + const PlayerIdentity &identity = identities->Get(i); + sockaddr_in address; + server->_server->GetClientAddress(identity.dpnid, address); + AddPlayer(identity.dpnid, address.sin_addr.s_addr, address.sin_port, identity.name); +#if _ENABLE_STEAM_OWNERSHIP + PlayerGUIDReceived(identity.dpnid, CSteamID((uint64)identity._steamID)); +#elif _ENABLE_STEAM_IDENTITY && defined(_WIN64) + if (identity._steamID != 0) + PlayerGUIDReceived(identity.dpnid, CSteamID((uint64)identity._steamID)); + else + PlayerGUIDReceived(identity.dpnid); +#else + PlayerGUIDReceived(identity.dpnid); +#endif + if (identity.clientState == NCSPlaying) + PlayerGoesInGame(identity.dpnid); + //else PlayerGoesInLobby(identity.dpnid); //<- assumed as default after AddPlayer + } + } +#endif + } + return true; +} + +void NetworkServer::BattlEye::Command(const char *command) +{ + if (_callbacks._command) (*_callbacks._command)(command); +} + +void NetworkServer::BattlEye::AddPlayer(int player, unsigned long address, unsigned short port, const char *name) +{ + if (_callbacks._addPlayer) (*_callbacks._addPlayer)(player, address, port, name); +} + +void NetworkServer::BattlEye::PlayerGoesInGame(int player) +{ + if (_callbacks._changePlayerStatus) (*_callbacks._changePlayerStatus)(player, 1); +} + +void NetworkServer::BattlEye::PlayerGoesInLobby(int player) +{ + if (_callbacks._changePlayerStatus) (*_callbacks._changePlayerStatus)(player, 0); +} + +void NetworkServer::BattlEye::PlayerDisconnected(int player) +{ + if (_callbacks._changePlayerStatus) (*_callbacks._changePlayerStatus)(player, -1); +} + +#if _ENABLE_STEAM_OWNERSHIP +void NetworkServer::BattlEye::PlayerGUIDReceived(int player, const CSteamID &id) +{ + if (_callbacks._receivedPlayerGUID) + { + uint64 steamId = id.ConvertToUint64(); + (*_callbacks._receivedPlayerGUID)(player, &steamId, sizeof(steamId)); + } +} + +#else +void NetworkServer::BattlEye::PlayerGUIDReceived(int player) +{ + if (_callbacks._receivedPlayerGUID) + { +#if _ENABLE_GAMESPY && _VERIFY_CLIENT_KEY + const char *hash = gcd_getkeyhash(GetGameID(), player); + (*_callbacks._receivedPlayerGUID)(player, (void *)hash, strlen(hash)); +#endif + } +} +#endif + +#if (_ENABLE_STEAM_IDENTITY && defined(_WIN64)) && !_ENABLE_STEAM_OWNERSHIP +void NetworkServer::BattlEye::PlayerGUIDReceived(int player, const CSteamID &id) +{ + if (_callbacks._receivedPlayerGUID) + { + uint64 steamId = id.ConvertToUint64(); + (*_callbacks._receivedPlayerGUID)(player, &steamId, sizeof(steamId)); + } +} +#endif + +void NetworkServer::BattlEye::PlayerGUIDIsValid(int player) +{ +}; + +#if _ENABLE_STEAM_OWNERSHIP || (_ENABLE_STEAM_IDENTITY && defined(_WIN64)) +void NetworkServer::BattlEye::PlayerGUIDIsValid(int player, const CSteamID &ownerId) +{ + if (_callbacks._playerGUIDIsValid) + { + uint64 steamId = ownerId.ConvertToUint64(); + (*_callbacks._playerGUIDIsValid)(player, &steamId, sizeof(steamId)); + } +} +#endif + +bool NetworkServer::BattlEye::UpdatePositionCallback(int player, const char *netId, float x, float y, float z, + float dirX, float dirY, float dirZ, float upX, float upY, float upZ, float asideX, float asideY, float asideZ) +{ + if (_callbacks._callbackUpdatePosition) + { + return (*_callbacks._callbackUpdatePosition)(player,netId,x,y,z,dirX,dirY,dirZ, upX, upY, upZ, asideX, asideY, asideZ); + } + return false; +} + +bool NetworkServer::BattlEye::UpdateDamageCallback(int player, const char *netId, float dam) +{ + if (_callbacks._callbackUpdateDamage) + { + return (*_callbacks._callbackUpdateDamage)(player,netId,dam); + } + return false; +} + +bool NetworkServer::BattlEye::PublicVariableCallback(int player, const char *name, const char *data) +{ + if (_callbacks._callbackPublicVariable) + { + return (*_callbacks._callbackPublicVariable)(player,name,data); + } + return false; +} + +bool NetworkServer::BattlEye::AttachObjectCallback(int player, const char *netId, const char *netIdAttachTo, int memoryIndex, float x, float y, float z) +{ + if (_callbacks._callbackAttachObject) + { + return (*_callbacks._callbackAttachObject)(player,netId,netIdAttachTo,memoryIndex,x,y,z); + } + return false; +} + +void NetworkServer::BattlEye::PlayerChatReceived(int player, int channel, const char *message) +{ + if (_callbacks._receivedPlayerMessage) + (*_callbacks._receivedPlayerMessage)(player, channel, message); +} + +void NetworkServer::BattlEye::LoadedMission(const char *missionName) +{ + if (_callbacks._loadedMission) + (*_callbacks._loadedMission)(missionName); +} + +void NetworkServer::BattlEye::PrintMessage(const char *message) +{ +#if _ENABLE_DEDICATED_SERVER + bool firstLine = true; + while (const char *newline = strchr(message, '\n')) + { + RString line(message, newline - message); + ::ConsoleF(firstLine ? "BattlEye Server: %s" : " %s", cc_cast(line)); + firstLine = false; + message = newline + 1; + } + ::ConsoleF(firstLine ? "BattlEye Server: %s" : " %s", message); +#endif +} + +void NetworkServer::BattlEye::KickPlayer(int player, const char *reason) +{ + NetworkServer *server = GNetworkManager.GetServer(); + if (server) + { +#if _ENABLE_DEDICATED_SERVER + PlayerIdentity *identity = server->FindIdentity(player); + ::ConsoleF("Player %s kicked off by BattlEye: %s", identity ? cc_cast(identity->name) : "", reason); + +/* +// using DisconnectMessage is not sufficient as we need the kick being immediate +// BattleEye "support" attitude: +// "Note that this is of course when the ArmA client does not disconnect itself, +// which it does when you click OK in the BE kick message box - but not before; +// naturally the server itself has to do this to have control and not to allow +// the player to stay on the server with some exploit" + DisconnectMessage msg; + msg._message = Format("Kicked off by BattlEye: %s", reason); + server->SendMsg(player, &msg, NMFGuaranteed); +*/ + + server->KickOff(player,KORBattlEye, reason); +#endif + } +} + +#if _ENABLE_DEDICATED_SERVER +// Large SQF files travel as several ordinary BattlEye commands. Reassemble and +// validate the complete script before putting it on the game-thread queue. +struct SDZBeSqfTransfer +{ + std::string id; + unsigned int expectedParts; + unsigned int expectedCrc; + unsigned int receivedParts; + unsigned int receivedBytes; + DWORD startedAt; + std::vector parts; + std::vector received; + + SDZBeSqfTransfer() : expectedParts(0), expectedCrc(0), receivedParts(0), receivedBytes(0), startedAt(0) {} + void Reset() + { + id.clear(); expectedParts = expectedCrc = receivedParts = receivedBytes = 0; startedAt = 0; + parts.clear(); received.clear(); + } +}; + +static SDZBeSqfTransfer SDZBeTransfer; + +static unsigned int SDZBeCrc32(const char *data, unsigned int length) +{ + unsigned int crc = 0xFFFFFFFF; + for (unsigned int i = 0; i < length; i++) + { + crc ^= (unsigned char)data[i]; + for (int bit = 0; bit < 8; bit++) + crc = (crc & 1) ? ((crc >> 1) ^ 0xEDB88320) : (crc >> 1); + } + return ~crc; +} + +static const char *SDZSkipSpaces(const char *text) +{ + while (*text == ' ' || *text == '\t') text++; + return text; +} + +static bool SDZReadToken(const char **cursor, std::string &token) +{ + const char *start = SDZSkipSpaces(*cursor); + if (!*start) return false; + const char *end = start; + while (*end && *end != ' ' && *end != '\t') end++; + token.assign(start, end - start); + *cursor = end; + return true; +} + +static bool SDZValidTransferId(const std::string &id) +{ + if (id.length() != 32) return false; + for (size_t i = 0; i < id.length(); i++) + if (!((id[i] >= '0' && id[i] <= '9') || (id[i] >= 'a' && id[i] <= 'f') || (id[i] >= 'A' && id[i] <= 'F'))) return false; + return true; +} + +static bool SDZHandleRconSqfTransfer(NetworkServer *server, const char *command) +{ + static const char beginPrefix[] = "#exec __SDZ_BEGIN__ "; + static const char partPrefix[] = "#exec __SDZ_PART__ "; + static const char endPrefix[] = "#exec __SDZ_END__ "; + if (!strnicmp(command, beginPrefix, sizeof(beginPrefix) - 1)) + { + SDZBeTransfer.Reset(); + const char *cursor = command + sizeof(beginPrefix) - 1; + std::string id, countText, crcText, extra; + if (!SDZReadToken(&cursor, id) || !SDZReadToken(&cursor, countText) || !SDZReadToken(&cursor, crcText) || + SDZReadToken(&cursor, extra) || !SDZValidTransferId(id)) + { + RptF("SDZ_BE_RCON: invalid large-SQF begin frame"); + return true; + } + char *parseEnd = NULL; + unsigned long count = strtoul(countText.c_str(), &parseEnd, 10); + if (!parseEnd || *parseEnd || count == 0 || count > 2048) + { + RptF("SDZ_BE_RCON: rejected large-SQF transfer with invalid part count"); + return true; + } + parseEnd = NULL; + unsigned long crc = strtoul(crcText.c_str(), &parseEnd, 16); + if (!parseEnd || *parseEnd || crc > 0xFFFFFFFFUL) + { + RptF("SDZ_BE_RCON: rejected large-SQF transfer with invalid checksum"); + return true; + } + SDZBeTransfer.id = id; + SDZBeTransfer.expectedParts = (unsigned int)count; + SDZBeTransfer.expectedCrc = (unsigned int)crc; + SDZBeTransfer.startedAt = GetTickCount(); + SDZBeTransfer.parts.resize(count); + SDZBeTransfer.received.resize(count, 0); + RptF("SDZ_BE_RCON: large-SQF transfer started (%u parts)", (unsigned int)count); + return true; + } + + if (!strnicmp(command, partPrefix, sizeof(partPrefix) - 1)) + { + if (SDZBeTransfer.expectedParts == 0 || GetTickCount() - SDZBeTransfer.startedAt > 120000) + { + SDZBeTransfer.Reset(); + RptF("SDZ_BE_RCON: rejected large-SQF part without an active transfer"); + return true; + } + const char *cursor = command + sizeof(partPrefix) - 1; + std::string id, indexText; + if (!SDZReadToken(&cursor, id) || !SDZReadToken(&cursor, indexText) || id != SDZBeTransfer.id) + { + RptF("SDZ_BE_RCON: rejected large-SQF part with invalid transfer id"); + return true; + } + char *parseEnd = NULL; + unsigned long index = strtoul(indexText.c_str(), &parseEnd, 10); + if (!parseEnd || *parseEnd || index >= SDZBeTransfer.expectedParts || *cursor != ' ') + { + RptF("SDZ_BE_RCON: rejected malformed large-SQF part"); + return true; + } + const char *chunk = cursor + 1; + size_t chunkLength = strlen(chunk); + if (chunkLength == 0 || chunkLength > 900) + { + RptF("SDZ_BE_RCON: rejected malformed large-SQF part"); + return true; + } + if (SDZBeTransfer.received[index]) + { + const std::string &receivedChunk = SDZBeTransfer.parts[index]; + if (receivedChunk.size() != chunkLength || receivedChunk.compare(0, receivedChunk.size(), chunk, chunkLength) != 0) + RptF("SDZ_BE_RCON: conflicting duplicate large-SQF part"); + return true; + } + if (SDZBeTransfer.receivedBytes + chunkLength > 1048576) + { + SDZBeTransfer.Reset(); + RptF("SDZ_BE_RCON: rejected SQF script larger than 1 MiB"); + return true; + } + SDZBeTransfer.parts[index].assign(chunk, chunkLength); + SDZBeTransfer.received[index] = 1; + SDZBeTransfer.receivedParts++; + SDZBeTransfer.receivedBytes += (unsigned int)chunkLength; + return true; + } + + if (!strnicmp(command, endPrefix, sizeof(endPrefix) - 1)) + { + const char *cursor = command + sizeof(endPrefix) - 1; + std::string id, extra; + if (!SDZReadToken(&cursor, id) || SDZReadToken(&cursor, extra) || id != SDZBeTransfer.id || + SDZBeTransfer.expectedParts == 0 || GetTickCount() - SDZBeTransfer.startedAt > 120000) + { + SDZBeTransfer.Reset(); + RptF("SDZ_BE_RCON: rejected invalid or expired large-SQF end frame"); + return true; + } + if (SDZBeTransfer.receivedParts != SDZBeTransfer.expectedParts) + { + RptF("SDZ_BE_RCON: incomplete large-SQF transfer (%u/%u parts)", SDZBeTransfer.receivedParts, SDZBeTransfer.expectedParts); + SDZBeTransfer.Reset(); + return true; + } + std::string script; + script.reserve(SDZBeTransfer.receivedBytes); + for (unsigned int i = 0; i < SDZBeTransfer.expectedParts; i++) script += SDZBeTransfer.parts[i]; + unsigned int expectedCrc = SDZBeTransfer.expectedCrc; + unsigned int receivedBytes = (unsigned int)script.length(); + SDZBeTransfer.Reset(); + if (SDZBeCrc32(script.c_str(), receivedBytes) != expectedCrc) + { + RptF("SDZ_BE_RCON: rejected large-SQF transfer with checksum mismatch"); + return true; + } + if (!server || script.empty()) + { + RptF("SDZ_BE_RCON: rejected empty large-SQF script or unavailable server"); + return true; + } + server->QueueExec(BOT_CLIENT, RString(script.c_str())); + RptF("SDZ_BE_RCON: queued reassembled SQF (%u bytes)", receivedBytes); + return true; + } + return false; +} +#endif + +void NetworkServer::BattlEye::ExecuteCommand(const char *command) +{ +#if _ENABLE_DEDICATED_SERVER + // BattlEye invokes this callback on the dedicated server. There is normally + // no local NetworkClient there, so forwarding #exec through the client drops + // the command. Queue it for the regular server simulation thread instead. + if (!command || !*command) return; + + if (strlen(command) > 1000) + { + RptF("SDZ_BE_RCON: rejected BattlEye command longer than 1000 bytes"); + return; + } + + NetworkServer *server = GNetworkManager.GetServer(); + if (SDZHandleRconSqfTransfer(server, command)) return; + + if (strnicmp(command, "#exec", 5) == 0 && (command[5] == 0 || command[5] == ' ' || command[5] == '\t')) + { + const char *expression = command + 5; + while (*expression == ' ' || *expression == '\t') expression++; + if (!*expression) + { + RptF("SDZ_BE_RCON: rejected empty #exec command"); + return; + } + if (!server) + { + RptF("SDZ_BE_RCON: rejected #exec because the server is unavailable"); + return; + } + server->QueueExec(BOT_CLIENT, RString(expression)); + RptF("SDZ_BE_RCON: queued #exec (%d bytes)", (int)strlen(expression)); + return; + } + + NetworkClient *client = GNetworkManager.GetClient(); + if (client) + { + client->ProcessCommand(RString(command)); + } +#endif +} + +#endif + +// open the mpStatistics.log file and write the required statistics string +// it open and close the mpStatistics.log file each time +static void LogMPStatistics(RString str) +{ + FILE *file = NULL; + char logFilename[MAX_PATH]; + if ( GetLocalSettingsDir(logFilename) ) + { + CreateDirectory(logFilename, NULL); + TerminateBy(logFilename, '\\'); + strcat(logFilename, "mpStatistics.log"); + file = fopen(logFilename, "a+"); + + if (file) + { + fputs(cc_cast(str), file); + fclose(file); + } + } +} + +//! Load ban list from file +/*! +\param filename name (path) of file +\param list output ban list +*/ +static void LoadBanList(RString filename, FindArray &list) +{ + list.Clear(); + QIFStream f; + f.open(filename); + while (!f.eof() && !f.fail()) + { + int c = f.get(); + if (f.eof() || f.fail()) return; + while (isspace(c) || c==',' || c==';') + { + c = f.get(); + if (f.eof() || f.fail()) return; + } + const int MaxBanIdLength = 255; + char value[MaxBanIdLength+1]; + int ix=0; + while (!isspace(c) && c!=',' && c!=';' && !f.eof() && ix &list) +{ + QOFStream f(filename); + for (int i=0; i=162 + const int DefaultSecureIdRequired = 1; + #pragma message WARN_MESSAGE("warning: Remove obsolete code") +#else + const int DefaultSecureIdRequired = 0; +#endif + +#if _ENABLE_STEAM_MATCHMAKING && _ENABLE_DEDICATED_SERVER + +#define STEAM_STAT_DEFINE_STATICS(name, Type, DefaultValue) \ + RString Stat_##name::apiName=RString(#name); + +STEAM_STATS_LIST(STEAM_STAT_DEFINE_STATICS) + +#define CREATE_STAT_VAR(name, Type, DefaultValue) \ + _stats[EStat_##name] = new Stat_##name; + +SteamStatistics::SteamStatistics() + : _initialized(false), _lastStatsReceivedTime(0), _lastStatsStoredTime(0), _nextStoreStatsTime(0), _nextRequestStatsTime(0), + _lastCharacterTimeAliveSyncTime(0) +{ + for (int i=0; i SteamStatistics::achievementsDef; + +void SteamStatistics::Init(CSteamID &steamID) +{ + _steamID = steamID; + //LogF("STEAM: SteamStatiscics::Init(%llu)", steamID.ConvertToUint64()); + + // fill in the SteamStat *_stats[] array + STEAM_STATS_LIST(CREATE_STAT_VAR) + SteamAPICall_t hSteamAPICall = SteamGameServerStats()->RequestUserStats(_steamID); + // set the function to call when this API completes + _steamCallResultUserStatsReceived.Set( hSteamAPICall, this, &SteamStatistics::OnUserStatsReceived ); + + _achievements.Realloc(achievementsDef.Size()); + _achievements.Resize(achievementsDef.Size()); + for (int i=0; i<_achievements.Size(); i++) + { + _achievements[i].def = &achievementsDef[i]; //SteamAchievement::ix is index into achievementsDef array + } +} + +void SteamStatistics::Reset(SteamStatsEnum stat) +{ + if (_stats[stat]) + { + _stats[stat]->SetDefault(); + _stats[stat]->SetStat(_steamID); + StoreStats(); + } +} + +void SteamStatistics::OnUserStatsReceived( GSStatsReceived_t *pCallback, bool bIOFailure ) +{ + //LogF("STEAM: OnUserStatsReceived %llu", pCallback->m_steamIDUser.ConvertToUint64()); + if ( bIOFailure ) + { + _nextRequestStatsTime = ::GetTickCount() + GRandGen.RandomValue()*120*1000; //within 0..120 seconds + return; + } + if (pCallback->m_steamIDUser != _steamID) + { + RptF("STEAM: Unexpected steamID in OnUserStatsReceived!"); + return; + } + + // even when user has no stats, we can consider SteamStatistics as initialized + _nextRequestStatsTime = 0; + _initialized = true; + + if (pCallback->m_eResult == k_EResultFail) // user has no stats + { + //LogF("STEAM: storing default statistics"); + for (int i=0; iSetDefault(); + _stats[i]->SetStat(_steamID); + } + StoreStats(); + return; + } + + // There was no Failure => fill in stats state + for (int i=0; iGetStat(_steamID); + + // fill in achievements state + for (int i=0; i<_achievements.Size(); i++) + { + AchievementDef *aDef = _achievements[i].def; + if ( aDef && !aDef->apiName.IsEmpty() ) + { + if ( SteamGameServerStats()->GetUserAchievement( _steamID, aDef->apiName, &_achievements[i].unlocked ) ) + LogF(" achievement state: %s = %d", cc_cast(aDef->apiName), _achievements[i].unlocked); + else + LogF(" achievement state request has FAILED!"); + } + } + + _lastStatsReceivedTime = _lastCharacterTimeAliveSyncTime = ::GetTickCount(); +} + +void SteamStatistics::OnUserStatsStored( GSStatsStored_t *pCallback, bool bIOFailure ) +{ + //LogF("STEAM: OnUserStatsStored %llu", pCallback->m_steamIDUser.ConvertToUint64()); + _lastStatsStoredTime = ::GetTickCount(); + _nextStoreStatsTime = _lastStatsStoredTime + 60*1000 + GRandGen.RandomValue()*120*1000; //within 1..3 min +} + +void SteamStatistics::Simulate() +{ + if (_initialized) + { + DWORD curtime = ::GetTickCount(); + if ( StatsValid() ) + { + //{@ characterTimeAlive Update + Stat_characterTimeAlive *stat = dynamic_cast(_stats[EStat_characterTimeAlive]); + if (stat) + { + int aliveTime = stat->GetValue(); + if ( _lastCharacterTimeAliveSyncTime && curtime>_lastCharacterTimeAliveSyncTime ) + { + int timeElapsed = curtime - _lastCharacterTimeAliveSyncTime; + int overtimeMS = timeElapsed % 1000; + timeElapsed /= 1000; //in seconds + if (timeElapsed) + { + stat->SetValue(aliveTime + timeElapsed); + stat->SetStat(_steamID); + _lastCharacterTimeAliveSyncTime = curtime - overtimeMS; // we should add these miliseconds later + //LogF("STEAM: characterTimeAlive=%d", aliveTime + timeElapsed); + } + } + } + //@} + } + // check achievements + for (int i=0; i<_achievements.Size(); i++) + { + SteamAchievement &achvm = _achievements[i]; + if (!achvm.unlocked && achvm.def) + { + if (achvm.def->statIx>=0 && achvm.def->statIxstatIx]; + if (stat->TestAchievementUnlocked(achvm.def->unlockValue)) + { + if (SteamGameServerStats()->SetUserAchievement(_steamID, achvm.def->apiName)) //UnLOCK achievement + { + achvm.unlocked = true; + _nextStoreStatsTime = curtime; //force storeStats + LogF("STEAM: achievement %s UNLOCKED", cc_cast(achvm.def->apiName)); + } + } + } + } +#if USER_Bebul + else // Bebul can reset the achievement manualy + { + static bool doIt = false; + if (doIt) + { + doIt = false; + achvm.unlocked = false; + SteamGameServerStats()->ClearUserAchievement( _steamID, achvm.def->apiName ); + _nextStoreStatsTime = curtime; //force storeStats + RptF("STEAM: achievement %s CLEARED", cc_cast(achvm.def->apiName)); + } + } +#endif + } + if ( _nextRequestStatsTime && (curtime>=_nextRequestStatsTime) && !_steamCallResultUserStatsReceived.IsActive() ) + { + _nextRequestStatsTime = 0; + SteamAPICall_t hSteamAPICall = SteamGameServerStats()->RequestUserStats(_steamID); + // set the function to call when this API completes + _steamCallResultUserStatsReceived.Set( hSteamAPICall, this, &SteamStatistics::OnUserStatsReceived ); + } + if ( !_nextStoreStatsTime && _lastStatsReceivedTime ) // data are valid, we can store them + { + _nextStoreStatsTime = curtime + 60*1000 + GRandGen.RandomValue()*120*1000; //within 1..3 minutes + } + else if ( curtime>=_nextStoreStatsTime ) + { + StoreStats(); + } + } +} + +void SteamStatistics::StoreStats() +{ + if ( !_steamCallResultUserStatsStored.IsActive() ) + { + _lastStatsStoredTime = ::GetTickCount(); + _nextStoreStatsTime= _lastStatsStoredTime + 10*60*1000; //10 minutes, but it SHOULD be reset, as OnUserStatsStored callback is supposed to be called + SteamAPICall_t hSteamAPICall = SteamGameServerStats()->StoreUserStats(_steamID); + // set the function to call when this API completes + _steamCallResultUserStatsStored.Set( hSteamAPICall, this, &SteamStatistics::OnUserStatsStored ); + } +} + +#endif + +#if _ENABLE_STEAM_MATCHMAKING && _ENABLE_DEDICATED_SERVER +void AchievementDef::SetApiName(RString name) +{ +#define STEAM_STAT_TEST(name, Type, DefaultValue) \ + if (apiName==Stat_##name::apiName) { statIx=EStat_##name; break; } + + apiName = name; + do { + // note: macro uses apiName just set + STEAM_STATS_LIST(STEAM_STAT_TEST) + } while(false); +} +#endif + +NetworkServer::NetworkServer(NetworkManager *parent, RString name, RString password, int maxPlayers, int port, bool isPrivate) +: NetworkComponent(parent) +#if _ENABLE_DEDICATED_SERVER +, _globals(&_evaluator, "server", false) +#endif +#if _ENABLE_STEAM_MATCHMAKING +, _callbackSteamServersConnected(this, &NetworkServer::OnSteamServersConnected) +, _callbackSteamServersConnectFailure(this, &NetworkServer::OnSteamServersConnectFailure) +, _callbackSteamServersDisconnected(this, &NetworkServer::OnSteamServersDisconnected) +, _callbackPolicyResponse(this, &NetworkServer::OnPolicyResponse) +#endif +{ + _serverState = NSSSelectingMission; + _serverStateTime = GlobalTickCount(); + _serverTimeOutSent = INT_MAX; + #if _ENABLE_DEDICATED_SERVER + _sqfExecBusy = false; + #endif + _connectionDesync = CDGood; + _desyncTotalUpdateNext = GlobalTickCount(); + _desyncTotalAvg = 0; + _desyncTotalMax = 0; + _buildNoRequired = 0; + _secureIdRequired = DefaultSecureIdRequired; + _longitude = INT_MAX; + _latitude = INT_MAX; + _disable3rdPerson = 0; + _environmentTimeMul = 0.0f; + + #if USER_Ondra + _updatesGuaranteed = true; + #else + _updatesGuaranteed = false; + #endif + _verifySignatures = false; + _validateCDKey = false; + _doNotReport = false; + _qrInitDone = false; + _persistent = false; + _destroyDisconnected = true; + + _maxPlayersLimit = maxPlayers; + _totalSlots = INT_MAX; + + _squadChecksTimeout = 0; + + _serverTime = _serverTimeOfEstimatedEnd = _secondsToEstimatedEnd = 0; + _serverTimeInitTickCount = ::GetTickCount(); + _nextServerTimeUpdate = _serverTime + ServerTimeUpdateInterval; + + /* + if (IsDedicatedServer() && !isPrivate) + { + _geoJob = new GeoLocationJob(); + _geoJob->_longitude = _longitude; + _geoJob->_latitude = _latitude; + GJobManager.CreateJob(_geoJob,10000); + } + */ + +#if _ENABLE_DEDICATED_SERVER + // provide some reasonable default + _difficulty = Glob.config.diffDefault; +#endif + +#if _VBS2 && _VBS2_LITE + _memoryWrite = false; + _nextRanUpdate = 0; +#endif + + _password = password.GetLength() > 0; + + _nextPlayerID = 2; // value 1 is reserved for static objects + + // make sure statistics from previous session will not be present + GStats.ClearMission(); + + Verify(Init(name, password, maxPlayers, port)); + + _param1 = 0; + _param2 = 0; + _paramsArray.Clear(); + + _timeLeftLastValue = 0; + _timeLeftLastTime = 0; + _timeLeftLastValueBcast = 0; + +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + _kickDuplicate = false; + _dedicated = false; + _missionIndex = -1; + + _gameMaster = AI_PLAYER; + _admin = false; + _restart = false; + _reassign = false; + + Monitor(0); + _debugNext = INT_MAX; + _debugInterval = 0; + + InitEvaluator(); +#endif +//} + _pingUpdateNext = GlobalTickCount() + 5000; + + _sessionLocked = false; + + _equalModRequired = false; + + // ensure no content remain + if (_server) DeleteDirectoryStructure(GetServerTmpDir(), false); + + #if _ENABLE_DEDICATED_SERVER + if (!IsDedicatedServer()) + #endif + { + LoadBanList(GetUserDirectory() + RString("ban.txt"), _banListLocal); + } + #if _VERIFY_CLIENT_KEY + { // load secure ban list on DS as well + RString banSecureFilename = GetUserDirectory() + RString("banSecure.txt"); + { + QIFStream f; + f.open(banSecureFilename); + if (f.rest()>0) + { + AutoArray banSecureInput; + banSecureInput.Resize(f.rest()); + f.read(banSecureInput.Data(),banSecureInput.Size()); + ParseSignedKeys(_banListSecure.keys,_banListSecure.signature,banSecureInput.Data()); + } + } + GFileServerFunctions->FlushReadHandle(banSecureFilename); + } + #endif + +#if _ENABLE_GAMESPY + // check that the game's back-end is available + // we need it due to NAT Negotiation + Ref p = ProgressStartExt(true, LocalizeString(IDS_LOAD_WORLD)); + GSIStartAvailableCheck(GetGameName()); + GSIACResult result; + while ((result = GSIAvailableCheckThink()) == GSIACWaiting) + { + msleep(5); + ProgressRefresh(); + } + ProgressFinish(p); +#endif + +#if _ENABLE_STEAM + +#if _ENABLE_STEAM_MATCHMAKING && _ENABLE_DEDICATED_SERVER + ConstParamEntryPtr achEntry = Pars.FindEntry("CfgAchievements"); + if (achEntry && achEntry->IsClass()) + { + SteamStatistics::achievementsDef.Clear(); + for (int i=0; iGetEntryCount(); i++) + { + ParamEntryVal cls = achEntry->GetEntry(i); + // Steam APIName + int ix = SteamStatistics::achievementsDef.Add(); + AchievementDef &achievement = SteamStatistics::achievementsDef[ix]; + achievement.SetApiName(cls.GetName()); //ix set inside + ConstParamEntryPtr entry = cls.FindEntry("progressStat"); + if (entry) achievement.progressStat = (*entry); + entry = cls.FindEntry("unlockValue"); + if (entry) achievement.unlockValue = (*entry); + } + } +#endif +#endif + +#if _ENABLE_STEAM_MATCHMAKING + // ports for Steam services, default are values used in prev. versions + _steamPort = 8766; + _steamQueryPort = 27016; +#endif +} + +void NetworkServer::CreateDebugWindow() +{ +#if _ENABLE_CHEATS + _debugWindow = new DebugListWindow("Server debug"); +#endif +} + +#include "../Protect/selectProtection.h" + +extern const int DefaultNetworkPort; + +DWORD GetGameLanguage() +{ + // use internal language ID instead (and mark it) + int GetLangID(); + return 0x10000 | GetLangID(); +} + + +void NetworkServer::SendMuteList(const PlayerIdentity &id) +{ +#if _ENABLE_MP + int to = id.dpnid; + + RemoteMuteListMessage msg; + + for (int i=0; i<_players.Size(); i++) + { + const NetworkPlayerInfo &info = *_players[i]; + if (info.dpid == to) continue; + + for (int j=0; j 0) + { + et -= Glob.time.toFloat(); + timeleft = toInt(et / 60.0); + saturateMax(timeleft, 1); + } + return timeleft; + } + return 0; +} + +RString GetDefaultSessionName(RString playerName) +{ + char hostName[128]; + bool getLocalName(char *name, unsigned len); + if (getLocalName(hostName, 128)) + { + if (playerName.GetLength() > 0) + return Format(LocalizeString(IDS_SESSION_NAME_FORMAT), cc_cast(playerName), cc_cast(hostName)); + else + return hostName; + } + return LocalizeString(IDS_SESSION_NAME_INIT); +} + +// Macrovision CD Protection +#if _ENABLE_MP + +//! Protected version of NetworkServer::Init +/*! +\param port IP port where server communicate +\param password session password +\patch 1.11 Date 07/31/2001 by Jirka +- Improved: Multiplayer session description +\patch 1.11 Date 08/02/2001 by Jirka +- Changed: Temporary directory on server in now Tmp instead of Tmp +\patch 1.24 Date 09/19/2001 by Jirka +- Added: parameter "hostname" added to dedicated server config +- Added: port displayed in session description if not default +- Added: parameter "maxPlayers" added to dedicated server config +\patch 1.30 Date 11/01/2001 by Jirka +- Added: parameter "voteMissionPlayers" added to dedicated server config + when no Missions section in server config and at least "voteMissionPlayers" (default = 1) + players are connected, mission voting is started automatically +\patch 1.42 Date 1/9/2002 by Jirka +- Added: parameter "voiceOverNet" added to dedicated server config (default = true) +*/ + +CDP_DECL NetTranspServer * __cdecl CDPInitServer(RString name, RString password, int maxPlayers, int port, ParamEntryPar cfg) +{ + NetTranspServer *server = NULL; + SECUROM_MARKER_HIGH_SECURITY_ON(10) + //Direct play has been eliminated from here + server = CreateNetServer(cfg); + ProgressRefresh(); + if (!server) return NULL; + + // load some settings from Flashpoint.cfg + server->SetNetworkParams(cfg); + + MPVersionInfo versionInfo; + versionInfo.versionActual = MP_VERSION_ACTUAL; + versionInfo.versionRequired = MP_VERSION_REQUIRED; + versionInfo.mission[0] = 0; + versionInfo.serverState = NSSSelectingMission; +#if USE_MOD_LIST + RString GetModListNames(); + strncpy(versionInfo.mod, GetModListNames(), MOD_LENGTH); +#else + strncpy(versionInfo.mod, GLoadedContentHash, MOD_LENGTH); +#endif + versionInfo.mod[MOD_LENGTH - 1] = 0; + + bool voiceOverNet = true; + + bool equalModRequired = false; + +#if _ENABLE_DEDICATED_SERVER + if (IsDedicatedServer()) + { + GameDataNamespace globals(NULL, RString(), false); // TODO: parsing namespace if access to globals needed + + ParamFile cfg; + RString GetServerConfig(); + cfg.Parse(GetServerConfig(), NULL, NULL, &globals); + + ConstParamEntryPtr entry = cfg.FindEntry("hostName"); + if (entry) name = *entry; + if (name.GetLength() == 0) name = GetDefaultSessionName(RString()); + + ConstParamEntryPtr instId = cfg.FindEntry("instanceId"); + if (instId) + { + RString id = *instId; + SetInstanceId(id.Data()); + } + + ConstParamEntryPtr instKey = cfg.FindEntry("instanceKey"); + if (instKey) + { + RString key = *instKey; + SetInstanceKey(key.Data()); + } + + entry = cfg.FindEntry("voiceOverNet"); + if (entry) + { + voiceOverNet = *entry; + } + + entry = cfg.FindEntry("equalModRequired"); + if (entry) equalModRequired = *entry; + + // on dedicated server, use only server name as session name + // playerName = LocalizeString(IDS_DEDICATED_SERVER); + } + else +#endif + { + if (name.GetLength() == 0) + { +#if _VBS2 // VBS2 nickname + RString playerName = Glob.header.playerHandle; +#else + RString playerName = Glob.header.GetPlayerName(); +#endif + name = GetDefaultSessionName(playerName); + } + } + + bool ok = server->Init( + name, password, maxPlayers, port, + GetGameLanguage(), Glob.config.difficulty, + versionInfo, equalModRequired, MAGIC_APP + ); + + if (!ok) + { + delete server; + return NULL; + } + +#if _VBS3 + // Force the VON off if requested by the program argument + extern bool DisableVON; + if (DisableVON) + { + voiceOverNet = false; + } +#endif + + if (voiceOverNet) + server->InitVoice(); + + char buffer[256]; + sprintf(buffer, "Tmp%d", server->GetSessionPort()); + ServerTmpDir = buffer; + + SECUROM_MARKER_HIGH_SECURITY_OFF(10) + + return server; +} +#endif // _ENABLE_MP + +void ParseFlashpointCfg(ParamFile &file); +void SaveFlashpointCfg(ParamFile &file); + +/*! +\patch 1.89 Date 10/25/2002 by Jirka +- Added: Item "proxy" added to Flashpoint.cfg to enforce proxy server used to download xml squad page etc. +*/ + +bool NetworkServer::Init(RString name, RString password, int maxPlayers, int port) +{ +#if _ENABLE_MP + // load some settings from Flashpoint.cfg + ParamFile cfg; + ParseFlashpointCfg(cfg); + + ConstParamEntryPtr entry = cfg.FindEntry("proxy"); + if (entry) _proxy = *entry; + + _longitude = cfg.ReadValue("serverLongitude",INT_MAX); + _latitude = cfg.ReadValue("serverLatitude",INT_MAX); + _longLatAuto = cfg.ReadValue("serverGeoLocAuto",true); + + _indexToPlayerId.Add(BOT_CLIENT); + // Macrovision CD Protection + //_serverUpBandwidth = 1000000000; // assume very fast bandwidth unless proven otherwise - 1Gbps + _server = CDPInitServer(name, password, maxPlayers, port, cfg); + return _server != NULL; + #else + return false; + #endif +} + +void NetworkServer::InitVoice() +{ + if (!_parent->IsVoNDisabled()) + if (_server) _server->InitVoice(); +} + +NetworkServer::~NetworkServer() +{ +#if _ENABLE_GAMESPY + CloseGeoJob(); +#endif + RemoveSystemMessages(); + + SetServerState(NSSNone); + +//{ QUERY & REPORTING SDK +#if _ENABLE_GAMESPY + DoneQR(); +#endif +//} + +#if _ENABLE_STEAM_MATCHMAKING + DoneSteam(); +#endif + + Done(); + +#if _ENABLE_CHEATS + if (_debugWindow) _debugWindow->Close(); +#endif +} + +void NetworkServer::Done() +{ +#if PEER2PEER + if (_p2pServer) _p2pServer = NULL; +#endif + + // _dp->CancelAsyncOperation(NULL, DPNCANCEL_ALL_OPERATIONS); + RemoveUserMessages(); + if (_server) DeleteDirectoryStructure(GetServerTmpDir(), true); + _server = NULL; +} + +/*! +\patch 5095 Date 12/5/2006 by Jirka +- Fixed: Dedicated server crash +*/ + +int NetworkServer::GetMaxPlayers() const +{ + int maxPlayers = GetMaxPlayersLimit(); + if (_serverState >= NSSAssigningPlayers) + { // maxPlayers from mission description.ext + saturateMin(maxPlayers, GetMaxMissionPlayers()); + } + saturateMin(maxPlayers, _totalSlots); + + return maxPlayers; +} + +int NetworkServer::GetMaxPlayersSafe(int bandwidthPerClient, int round) const +{ + int maxPlayers = GetMaxPlayersLimit(); + // always return even number + maxPlayers = maxPlayers/round*round; + if (maxPlayersGetURL(address, addressLen); +} + +/*! +\patch 1.21 Date 08/23/2001 by Jirka +- Improved: session description +*/ +void NetworkServer::UpdateSessionDescription() +{ + if (_server) + { + RString gameType, island; + LocalizedString mission; + int timeleft = 0; + int difficulty = Glob.config.difficulty; + if (_serverState >= NSSAssigningPlayers) + { + gameType = _missionHeader._gameType; + mission = _missionHeader._name; + island = _missionHeader._island; + timeleft = GetSessionTimeLeft(); + } + _server->UpdateSessionDescription( + _serverState, gameType, mission, island, timeleft, difficulty + ); + } +} + +RString QosInfo::GetLocalizedMissionName() const +{ + int type = missionLocalizedType-' '; + saturate(type,LocalizedString::PlainText,LocalizedString::Stringtable); + LocalizedString str(LocalizedString::Type(type),missionId.cstr()); + return str.GetLocalizedValue(); +} + +void QosInfo::SetMissionName(const LocalizedString &str) +{ + missionLocalizedType = ' '+str._type; + strcpy(missionId,str._id); +} + +DWORD WINAPI NetworkServer::GeoJobThreadFunction(void *ctx) +{ + GeoJobThread *geoJob = (GeoJobThread *)ctx; + + float latitude,longitude; + GeoLocationFromIP(latitude,longitude,geoJob->_ip); // location of my own IP address + + if (longitude_latitude.SetResult(toInt(latitude)); + geoJob->_longitude.SetResult(toInt(longitude)); + } + else + { + geoJob->_latitude.SetResult(INT_MAX); + geoJob->_longitude.SetResult(INT_MAX); + } + return 0; +} + + +/*! +\patch 1.21 Date 08/22/2001 by Jirka +- Added: GameSpy Query & Reporting SDK support for dedicated server +\patch_internal 1.86 Date 10/16/2002 by Jirka +- Added: ASE SDK support for dedicated server +\patch_internal 1.90 Date 11/12/2002 by Jirka +- Fixed: dedicated server was reporting to ASE even for reportingIP="" +*/ + + +void NetworkServer::OnPublicAddressKnown(int ip) +{ + BString<256> ipText; + sprintf(ipText,"%d.%d.%d.%d",ip&0xff, (ip>>8)&0xff, (ip>>16)&0xff, (ip>>24)&0xff); + + if (!_geoJob && IsDedicatedServer() && !_doNotReport) + { + _geoJob = new GeoJobThread(); + _geoJob->_ip = ipText.cstr(); +#if USE_MT_LIB_FOR_JOBS + _geoJob->_thread.Init( CreateMTThreadOnCPU(64 * 1024, GeoJobThreadFunction, _geoJob, 2, MultiThread::ThreadBase::PriorityNormal, "GeoLocation")); +#else + _geoJob->_thread.Init( CreateThreadOnCPU(64 * 1024, GeoJobThreadFunction, _geoJob, 2, THREAD_PRIORITY_NORMAL, "GeoLocation")); +#endif + } +} + +//{ QUERY & REPORTING SDK +#if _ENABLE_GAMESPY + +// GameSpy callbacks + +/*! +\patch 5090 Date 11/27/2006 by Jirka +- Fixed: Possible crash when hosting MP session +*/ + +// Called when a server key needs to be reported +void serverkey_callback(int keyid, qr2_buffer_t outbuf, void *userdata) +{ + if (GNetworkManager.GetServer() != userdata) return; + NetworkServer *server = ((NetworkServer *)userdata); + if (server->IsValid()) server->OnQueryServer(keyid, outbuf); +} + +// Called when a player key needs to be reported +void playerkey_callback(int keyid, int index, qr2_buffer_t outbuf, void *userdata) +{ + if (GNetworkManager.GetServer() != userdata) return; + NetworkServer *server = ((NetworkServer *)userdata); + if (server->IsValid()) server->OnQueryPlayer(keyid, index, outbuf); +} + +// Called when a team key needs to be reported +void teamkey_callback(int keyid, int index, qr2_buffer_t outbuf, void *userdata) +{ + if (GNetworkManager.GetServer() != userdata) return; + NetworkServer *server = ((NetworkServer *)userdata); + if (server->IsValid()) server->OnQueryTeam(keyid, index, outbuf); +} + +// Called when we need to report the list of keys we report values for +void keylist_callback(qr2_key_type keytype, qr2_keybuffer_t keybuffer, void *userdata) +{ + if (GNetworkManager.GetServer() != userdata) return; + NetworkServer *server = ((NetworkServer *)userdata); + if (server->IsValid()) server->OnQueryKeys(keytype, keybuffer); +} + +// Called when we need to report the number of players and teams +int count_callback(qr2_key_type keytype, void *userdata) +{ + if (GNetworkManager.GetServer() != userdata) return 0; + NetworkServer *server = ((NetworkServer *)userdata); + if (server->IsValid()) return server->OnQueryCount(keytype); + return 0; +} + +// Called if our registration with the GameSpy master server failed +void adderror_callback(qr2_error_t error, gsi_char *errmsg, void *userdata) +{ + // Display an error message to the user indicating that he is unable to host a game and why (e.g., UDP-blocking firewall). + // Note: Applies to Validate Method (GameSpy Source code inspection) + GWorld->CreateWarningMessage(errmsg); + RptF("GameSpy QR2 error: %d, %s", error, errmsg); + (void *)userdata; +} + +// NAT Negotiation callbacks +static void NNProgressCallback(NegotiateState state, void *userdata) +{ +} + +static void NNCompletedCallback(NegotiateResult result, SOCKET gamesocket, struct sockaddr_in *remoteaddr, void *userdata) +{ + switch (result) + { + case nr_success: + RptF("NAT Negotiation completed"); + break; + case nr_deadbeatpartner: + RptF("NAT Negotiation failed - partner not found"); + break; + case nr_inittimeout: + RptF("NAT Negotiation failed - unable to communicate with the server"); + break; + case nr_unknownerror: + RptF("NAT Negotiation failed - unknown error"); + break; + } +} + +void NNDetectionResultsCallback(gsi_bool success, NAT nat) +{ + QOStrStream natType; + if (success) + { + natType << "Begin (NAT type):\n"; + static bool doIt = false; + if (doIt) + { + if (*nat.brand) natType << " Brand: " << nat.brand << "\n"; + if (*nat.model) natType << " Model: " << nat.model << "\n"; + if (*nat.firmware) natType << " Firmware: " << nat.firmware << "\n"; + } + RString natTypeStr; + switch (nat.natType) + { + case no_nat: natTypeStr = "no nat"; break; + case firewall_only: natTypeStr = "firewall only"; break; + case full_cone: natTypeStr = "full cone"; break; + case restricted_cone: natTypeStr = "restricted cone"; break; + case port_restricted_cone: natTypeStr = "port restricted cone"; break; + case symmetric: natTypeStr = "symmetric"; break; + case unknown: + default: natTypeStr = "unknown"; + } + natType << " NAT type: " << cc_cast(natTypeStr) << "\n"; + RString natPromiscuity; + switch (nat.promiscuity) + { + case promiscuous: natPromiscuity = "promiscuous"; break; + case not_promiscuous: natPromiscuity = "not promiscuous"; break; + case port_promiscuous: natPromiscuity = "port promiscuous"; break; + case ip_promiscuous: natPromiscuity = "ip promiscuous"; break; + case promiscuity_not_applicable: + default: natPromiscuity = "promiscuity not applicable"; break; + } + natType << " NAT promiscuity: " << cc_cast(natPromiscuity) << "\n"; + RString natMappingScheme; + switch (nat.mappingScheme) + { + case private_as_public: natMappingScheme = "private as public"; break; + case consistent_port: natMappingScheme = "consistent port"; break; + case incremental: natMappingScheme = "incremental"; break; + case mixed: natMappingScheme = "mixed"; break; + case unrecognized: + default: natMappingScheme = "unrecognized"; break; + } + natType << " NAT mapping scheme: " << cc_cast(natMappingScheme) << "\n"; + if (nat.ipRestricted) natType << " NAT is IP restricted\n"; + if (nat.portRestricted) natType << " NAT is PORT restricted\n"; + if (nat.qr2Compatible) natType << " NAT is qr2 compatible\n"; + natType << "End (NAT type)"; + } + else natType << "NAT detection was not successful."; + RString detectedNatType(natType.str(), natType.pcount()); + GDebugVoNBank._natType = detectedNatType; +#if !_SUPER_RELEASE && ENABLE_REPORT + if (GInput.cheatVoNDetectNatType) + { + RptF(cc_cast(detectedNatType)); + } +#endif +} + +// Called when a client wants to connect using nat negotiation +// (Nat Negotiation must be enabled in qr2_init) +void nn_callback(int cookie, void *userdata) +{ + LogF("NAT Negotiation started for cookie : %d", cookie); + SOCKET GetServerSocket(); + enterNN(); + NegotiateError error = NNBeginNegotiationWithSocket(GetServerSocket(), cookie, 1, NNProgressCallback, NNCompletedCallback, NULL); +#if !_SUPER_RELEASE && _ENABLE_CHEATS + if (!GDebugVoNBank.NatTypeDetectionTriggered()) + { + GDebugVoNBank.TriggerNatTypeDetection(); + NegotiateError errorDet = NNStartNatDetection(NNDetectionResultsCallback); + (void) errorDet; + } +#endif + leaveNN(); + (void)error; + (void)userdata; +} + +void SetQRInitialized(bool set); + +/*! +\patch 5164 Date 10/3/2007 by Jirka +- Fixed: Handling of invalid CD keys on dedicated servers improved +*/ + +#if _ENABLE_GAMESPY && _VERIFY_CLIENT_KEY +void NetworkServer::OnCDKeyAuthorize(int player, int authenticated, const char *errmsg) +{ + if (!authenticated) + { + // wrong CD Key - kick off client, shut down server + if (player == BOT_CLIENT) + { + GChatList.Add(CCGlobal, NULL, errmsg, false, true); + WarningMessage(errmsg); +/* + WarningMessage(LocalizeString(keyInUse ? IDS_MP_CDKEY_IN_USE : IDS_MP_BAD_CDKEY)); +*/ + Done(); + } + else + { +/* + // using DisconnectMessage is not sufficient as we need the kick being immediate + // "Note that this is of course when the ArmA client does not disconnect itself, + // naturally the server itself has to do this to have control and not to allow + // the player to stay on the server with some exploit" + DisconnectMessage msg; + msg._message = errmsg; + SendMsg(player, &msg, NMFGuaranteed); +*/ + bool keyInUse = strcmp(errmsg, "CD Key in use") == 0; + KickOff(player, keyInUse ? KORCDKeyInUse : KORBadCDKey, errmsg); + } +/* + NetworkPlayerInfo *info = GetPlayerInfo(player); + LogF("%f: Player %s (%d) was not authenticated (%s)", 1e-3 * GlobalTickCount(), info ? cc_cast(info->name) : "", player, errmsg); +*/ + } + else + { +/* + NetworkPlayerInfo *info = GetPlayerInfo(player); + LogF("%f: Player %s (%d) was successfully authenticated (%s)", 1e-3 * GlobalTickCount(), info ? cc_cast(info->name) : "", player, errmsg); +*/ + } +} + +/// Callback function to indicate whether a client has been authorized or not. +static void OnAuthorize(int productid, int localid, int authenticated, char *errmsg, void *instance) +{ + NetworkServer *server = reinterpret_cast(instance); + if (server && server == GNetworkManager.GetServer()) server->OnCDKeyAuthorize(localid, authenticated, errmsg); +} + +/// Callback function to reauthorize players. +static void OnRefreshAuthorize(int gameid, int localid, int hint, char *challenge, void *instance) +{ + NetworkServer *server = reinterpret_cast(instance); + + if (server && server == GNetworkManager.GetServer()) + { + CDKeyRecheckAskMessage ask; + ask._hint = hint; + ask._challenge = challenge; + + server->SendMsg(localid, &ask, NMFGuaranteed); + } +} + +// Called when the local clients public address is received +void pa_callback(unsigned int ip, unsigned short port, void *userdata) +{ + NetworkServer *server = reinterpret_cast(userdata); + if (server && server == GNetworkManager.GetServer() /*&& server->IsDedicatedBotClient(BOT_CLIENT)*/) + { + NetworkPlayerInfo *player = server->GetPlayerInfo(BOT_CLIENT); + DoAssert(player); + if (player) + { + player->_publicAddr = ip; + player->_publicPort = port; + + // once we know a public address, we can start geolocating + server->OnPublicAddressKnown(ip); + } + } +} + +#endif + +void RegisterQR2Keys() +{ + qr2_register_key(PARAM1_KEY, "param1"); + qr2_register_key(PARAM2_KEY, "param2"); + qr2_register_key(VER_KEY, "ver"); + qr2_register_key(MOD_KEY, "mod"); + qr2_register_key(GAME_STATE_KEY, "gameState"); + qr2_register_key(PLATFORM_KEY, "platform"); + qr2_register_key(LANGUAGE_KEY, "language"); + qr2_register_key(MISSION_KEY, "mission"); + qr2_register_key(MOD_HASH_KEY, "modhash"); + qr2_register_key(HASH_KEY, "hash"); + qr2_register_key(REQ_BUILD_KEY, "reqBuild"); + qr2_register_key(REQ_SECURE_ID_KEY, "reqSecureId"); + qr2_register_key(LONGITUDE_KEY, "lng"); + qr2_register_key(LATITUDE_KEY, "lat"); + qr2_register_key(DS_KEY, "ds"); + qr2_register_key(EQ_MOD_KEY, "eqMod"); + qr2_register_key(REQ_VER_KEY, "reqVer"); + qr2_register_key(DIFF_KEY, "diff"); + qr2_register_key(BE_KEY, "be"); + qr2_register_key(SIG_KEY, "sig"); + qr2_register_key(VER_SIG_KEY, "verSig"); +} +/*! +\patch 1.34 Date 12/04/2001 by Jirka +- Changed: GameSpy base local port +*/ +void NetworkServer::InitQR(bool isPrivate) +{ + _qrInitDone = true; +#if _ENABLE_DEDICATED_SERVER + if (stricmp(_reportingIP, "noreport") == 0) isPrivate = true; +#endif + _doNotReport = isPrivate; + + RegisterQR2Keys(); + + +#if _ENABLE_DEDICATED_SERVER + if ( !_doNotReport && !_reportingIP.IsEmpty() ) + { + int len = sizeof(qr2_hostname) / sizeof(char); + strncpy(qr2_hostname, _reportingIP, len); + qr2_hostname[len - 1] = 0; + } +#endif + + static bool useNatNegotiation = true; + + SOCKET GetServerSocket(); + if (qr2_init_socket(NULL, GetServerSocket(), GetSessionPort(), + GetGameName(), GetSecretKey(), _doNotReport ? 0 : 1, useNatNegotiation, + serverkey_callback, playerkey_callback, teamkey_callback, + keylist_callback, count_callback, adderror_callback, this) == e_qrnoerror) + { + SetQRInitialized(true); + + // Set a function to be called when we receive a nat negotiation request + qr2_register_natneg_callback(NULL, nn_callback); +#if _VERIFY_CLIENT_KEY + //set host name DNS + gsiSafeStrcpyA(gcd_hostname, GetGcdHostname(), sizeof(gcd_hostname)); + if (gcd_init(GetGameID()) == 0) + _validateCDKey = true; //this enable validation on GameSpy + qr2_register_publicaddress_callback(NULL, pa_callback); +#endif + } + +#if REPORT_ASE + ASEMaster_init(1); +#endif +} + +void NetworkServer::DoneQR() +{ +#if _VERIFY_CLIENT_KEY + if (_validateCDKey) + { + gcd_disconnect_all(GetGameID()); + gcd_shutdown(); + _validateCDKey = false; + } +#endif + + //let game master know we are shutting down (removes dead server entry from the list) + SetQRInitialized(false); + qr2_shutdown(NULL); + +#ifdef GSI_UNICODE + // In Unicode mode we must perform additional cleanup + qr2_internal_key_list_free(); +#endif +} + +void NetworkServer::SimulateQR() +{ + if (!_qrInitDone) + return; //InitQR was not called (possibly playing LAN game) + //check for / process incoming queries + qr2_think(NULL); +#if _VERIFY_CLIENT_KEY + if (_validateCDKey) gcd_think(); +#endif + +#if REPORT_ASE + ASEMaster_heartbeat(0, ::GetServerPort() + 1, GetGameName()); +#endif +} + +void NetworkServer::ChangeStateQR() +{ + qr2_send_statechanged(NULL); +} + +const int MaxGSMaxSize = 1300; + +//max 200B for signatures list GS key +const int MaxGSKey = 200; + +static int GetMaxKeySize(qr2_buffer_t outbuf) +{ + struct qr2_buffer_header + { + char buffer[32]; // in fact much longer, but 32 is something we can be sure of + } * header = reinterpret_cast(outbuf); + // packet type 0 (PACKET_QUERY), followed by some 4 bytes, followed with "splitnum" + if (header->buffer[0]==0 && !strncmp(header->buffer+5,"splitnum",sizeof("splitnum"))) + { + return MaxGSMaxSize; // max. packet size is 1400, but something is needed for splitNum header, keyname ... + } + else + { + return MaxGSKey; + } +} +/// overload to handle cutting very long values transparently +void qr2_buffer_add(qr2_buffer_t outbuf, RString longString) +{ + int len = longString.GetLength(); + int maxSize = GetMaxKeySize(outbuf); + if (len>=maxSize) + { + BString shortString; + shortString = longString; + Assert(maxSize>4); + STATIC_ASSERT(MaxGSMaxSize>4 && MaxGSKey>4); + strcpy(shortString+(maxSize-4),"..."); + qr2_buffer_add(outbuf,cc_cast(shortString)); + } + else + { + qr2_buffer_add(outbuf,cc_cast(longString)); + } +} + +void NetworkServer::CloseGeoJob() const +{ + if (_geoJob) + { + // make sure the thread has done its work and will no longer access any variables + _geoJob->_longitude.GetResult(); + _geoJob->_latitude.GetResult(); + _geoJob->_thread.Wait(); + //RptF("Closing geoJob"); + _geoJob->_thread.Done(); + //RptF("GeoJob closed!"); //NOTE: there was "Critical: Destroying running thread" between these two RptF! + _geoJob.Free(); + } +} + +void NetworkServer::ProcessGeoJob() const +{ + if (_geoJob && _geoJob->_longitude.IsReady()) + { + int longitude = _geoJob->_longitude.GetResult(); + int latitude = _geoJob->_latitude.GetResult(); + CloseGeoJob(); + // save the values so that we can find them next time + ParamFile fCfg; + ParseFlashpointCfg(fCfg); + if (_longLatAuto) + { + _longitude = longitude; + _latitude = latitude; + fCfg.Add("serverLongitude",_longitude); + fCfg.Add("serverLatitude",_latitude); + } + fCfg.Add("serverLongitudeAuto",longitude); + fCfg.Add("serverLatitudeAuto",latitude); + SaveFlashpointCfg(fCfg); + + } +} + +static int IntParam(float param) +{ + if (param>INT_MAX) return INT_MAX; + return toLargeInt(param); +} + +void NetworkServer::OnQueryServer(int keyid, qr2_buffer_t outbuf) +{ + switch (keyid) + { + case GAMEVER_KEY: + qr2_buffer_add(outbuf, Format("%s.%d", APP_VERSION_TEXT, BUILD_NO)); + break; + case HOSTNAME_KEY: + qr2_buffer_add(outbuf, _server->GetSessionName()); + break; + case GAMENAME_KEY: + qr2_buffer_add(outbuf, GetGameName()); + break; +/* + case HOSTPORT_KEY: + qr2_buffer_add_int(outbuf, _server->GetSessionPort()); + break; +*/ + case MAPNAME_KEY: + { + RString island; + if (_serverState >= NSSAssigningPlayers) island = _missionHeader._island; + qr2_buffer_add(outbuf, island); + } + break; + case GAMETYPE_KEY: + { + if (Glob.isDayZ==Globals::IsDayZ) + { + qr2_buffer_add(outbuf, "DAYZ"); + break; + } + else if (Glob.isDayZ==Globals::IsDayZOther) + { + qr2_buffer_add(outbuf, "DAYZ_M"); + break; + } + + RString gameType; + if (_serverState >= NSSAssigningPlayers) gameType = _missionHeader._gameType; + qr2_buffer_add(outbuf, gameType); + } + break; + case MISSION_KEY: + { + RString mission; + if (_serverState >= NSSAssigningPlayers) mission = _missionHeader.GetLocalizedMissionName(); + qr2_buffer_add(outbuf, mission); + } + break; + case NUMPLAYERS_KEY: + qr2_buffer_add_int(outbuf, _identities.Size()); + break; + case NUMTEAMS_KEY: + qr2_buffer_add_int(outbuf, 0); + break; + case MAXPLAYERS_KEY: + qr2_buffer_add_int(outbuf, GetMaxPlayers()); + break; + case GAMEMODE_KEY: + { + const char *mode = ""; + switch (_serverState) + { + case NSSNone: + mode = "exiting"; + break; + case NSSSelectingMission: + case NSSEditingMission: + case NSSAssigningPlayers: + mode = "openwaiting"; + break; + case NSSSendingMission: + case NSSLoadingGame: + case NSSPlaying: + mode = "openplaying"; + break; + case NSSMissionAborted: + mode = "openwaiting"; + break; + default: + Fail("Game state"); + break; + } + qr2_buffer_add(outbuf, mode); + } + break; + case TIMELIMIT_KEY: + { + int timeleft; + if (_serverState == NSSPlaying) + { + timeleft = 15; + + float et = _missionHeader._estimatedEndTime.toFloat(); + if (et > 0) + { + et -= Glob.time.toFloat(); + timeleft = toInt(et / 60.0); + saturateMax(timeleft, 1); + } + } + else timeleft = 0; + qr2_buffer_add_int(outbuf, timeleft); + } + break; + case PASSWORD_KEY: + qr2_buffer_add_int(outbuf, (_password ? 2 : 0) + (_sessionLocked ? 1 : 0)); + break; + case PARAM1_KEY: + qr2_buffer_add_int(outbuf, IntParam(_param1)); + break; + case PARAM2_KEY: + qr2_buffer_add_int(outbuf, IntParam(_param2)); + break; + case CURRENT_VERSION_KEY: + case VER_KEY: + qr2_buffer_add_int(outbuf, MP_VERSION_ACTUAL); + break; + case REQ_VER_KEY: + case REQUIRED_VERSION_KEY: + qr2_buffer_add_int(outbuf, MP_VERSION_REQUIRED); + break; + case MOD_KEY: + { + RString GetModListNames(); + qr2_buffer_add(outbuf, GetModListNames()); + } + break; + case MOD_HASH_KEY: + { + RString hashes; + for (int i=0; i maxLen ) + { // truncate and finish signatures list collecting + list = list + "..."; // mark signatures list as truncated + break; + } + len += sigLen; + list = list + _acceptedKeys[i]._name; + } + return list; +} + +void NetworkServer::OnQueryPlayer(int keyid, int index, qr2_buffer_t outbuf) +{ + //check for valid index + if (index >= _identities.Size()) + { + qr2_buffer_add(outbuf, _T("")); + return; + } + + const PlayerIdentity &identity = _identities[index]; + switch (keyid) + { + case PLAYER__KEY: + qr2_buffer_add(outbuf, identity.name); + break; + case TEAM__KEY: + { + RString squad; + if (identity.squad) squad = identity.squad->_nick; + qr2_buffer_add(outbuf, squad); + } + break; + case SCORE__KEY: + { + //qr2_buffer_add_int(outbuf, score); + } + break; + case DEATHS__KEY: + { + //qr2_buffer_add_int(outbuf, deaths); + } + break; + default: + qr2_buffer_add(outbuf, _T("")); + break; + } +} + +void NetworkServer::OnQueryTeam(int keyid, int index, qr2_buffer_t outbuf) +{ + qr2_buffer_add(outbuf, _T("")); +} + +void NetworkServer::OnQueryKeys(int keytype, qr2_keybuffer_t keybuffer) +{ + //need to add all the keys we support + switch (keytype) + { + case key_server: + qr2_keybuffer_add(keybuffer, GAMEVER_KEY); + qr2_keybuffer_add(keybuffer, HOSTNAME_KEY); +// qr2_keybuffer_add(keybuffer, HOSTPORT_KEY); + qr2_keybuffer_add(keybuffer, MAPNAME_KEY); + qr2_keybuffer_add(keybuffer, GAMETYPE_KEY); + qr2_keybuffer_add(keybuffer, NUMPLAYERS_KEY); + qr2_keybuffer_add(keybuffer, NUMTEAMS_KEY); + qr2_keybuffer_add(keybuffer, MAXPLAYERS_KEY); + qr2_keybuffer_add(keybuffer, GAMEMODE_KEY); + qr2_keybuffer_add(keybuffer, TIMELIMIT_KEY); + qr2_keybuffer_add(keybuffer, PASSWORD_KEY); + qr2_keybuffer_add(keybuffer, PARAM1_KEY); + qr2_keybuffer_add(keybuffer, PARAM2_KEY); + qr2_keybuffer_add(keybuffer, CURRENT_VERSION_KEY); + qr2_keybuffer_add(keybuffer, REQUIRED_VERSION_KEY); + qr2_keybuffer_add(keybuffer, MOD_KEY); + qr2_keybuffer_add(keybuffer, EQUAL_MOD_REQUIRED_KEY); + qr2_keybuffer_add(keybuffer, GAME_STATE_KEY); + qr2_keybuffer_add(keybuffer, DEDICATED_KEY); + qr2_keybuffer_add(keybuffer, PLATFORM_KEY); + qr2_keybuffer_add(keybuffer, LANGUAGE_KEY); + qr2_keybuffer_add(keybuffer, DIFFICULTY_KEY); + qr2_keybuffer_add(keybuffer, MISSION_KEY); + qr2_keybuffer_add(keybuffer, GAMENAME_KEY); + qr2_keybuffer_add(keybuffer, BATTLEYE_KEY); + qr2_keybuffer_add(keybuffer, VERIFY_SIGNATURES_KEY); + qr2_keybuffer_add(keybuffer, SIGNATURES_KEY); + qr2_keybuffer_add(keybuffer, MOD_HASH_KEY); + qr2_keybuffer_add(keybuffer, HASH_KEY); + qr2_keybuffer_add(keybuffer, REQ_BUILD_KEY); + qr2_keybuffer_add(keybuffer, REQ_SECURE_ID_KEY); + qr2_keybuffer_add(keybuffer, LATITUDE_KEY); + qr2_keybuffer_add(keybuffer, LONGITUDE_KEY); + break; + case key_player: + qr2_keybuffer_add(keybuffer, PLAYER__KEY); + qr2_keybuffer_add(keybuffer, TEAM__KEY); + qr2_keybuffer_add(keybuffer, SCORE__KEY); + qr2_keybuffer_add(keybuffer, DEATHS__KEY); + break; + case key_team: + break; + default: + break; + } +} + +int NetworkServer::OnQueryCount(int keytype) +{ + switch (keytype) + { + case key_player: + return _identities.Size(); + case key_team: + return 0; + default: + return 0; + } +} + +/* +void NetworkServer::OnQueryRules(char *outbuf, int maxlen) +{ + if (!SafePrint(ptr, maxlen, "\\mod\\%s", (const char *)GetModListShort())) return; + if (!SafePrint(ptr, maxlen, "\\equalModRequired\\%d", _equalModRequired)) return; + if (!SafePrint(ptr, maxlen, "\\gstate\\%d", _serverState)) return; + + dedicated + + } +*/ + +#endif +//} + +//{ STEAMWORKS SDK +#if _ENABLE_STEAM_MATCHMAKING + +void NetworkServer::InitSteam() +{ + uint32 ip = bindIPAddress; + uint16 masterServerUpdaterPort = _steamQueryPort; + uint16 authenticationPort = _steamPort; + EServerMode mode = eServerModeAuthenticationAndSecure; + RString steamVersion = Format("%s.%d", APP_VERSION_TEXT, BUILD_NO); //such as 0.28.113666 + +#if USER_BebulXX + _putenv("SteamAppId=223350"); +#else + _putenv("SteamAppId=480"); +#endif + + // Initialize the SteamGameServer interface, we tell it some info about us, and we request support + // for both Authentication (making sure users own games) and secure mode, VAC running in our game + // and kicking users who are VAC banned + bool initOK = false; + for (int i=0; i<15; i++, authenticationPort+=13, masterServerUpdaterPort++) //try 15 local ports + { + if (SteamGameServer_Init(ip, authenticationPort, GetSessionPort(), masterServerUpdaterPort, mode, steamVersion)) + { + initOK = true; + break; + } + } + + // Connect to steam servers + if (initOK && SteamGameServer()) + { + ConsoleF("SUCCESS: SteamGameServer_Init(%x,%d,%d,%d,%d,%s)", ip, authenticationPort, GetSessionPort(), masterServerUpdaterPort, mode, steamVersion); + RptF("SUCCESS: SteamGameServer_Init(%x,%d,%d,%d,%d,%s)", ip, authenticationPort, GetSessionPort(), masterServerUpdaterPort, mode, steamVersion); + SteamGameServer()->SetDedicatedServer(_dedicated); + // Set the "game dir". + // This is currently required for all games. However, soon we will be + // using the AppID for most purposes, and this string will only be needed + // for mods. it may not be changed after the server has logged on + SteamGameServer()->SetModDir("dayz"); + + // Tell the Steam Master Server about our game + SteamGameServer()->SetProduct("dayz"); //was APP_NAME + SteamGameServer()->SetGameDescription(APP_NAME); + + //SteamGameServer()->SetGameData("Bebul,Game"); + if (_beIntegration.IsEnabled()) + SteamGameServer()->SetGameTags("battleye"); + + SteamGameServer()->LogOnAnonymous(); + SteamGameServer()->EnableHeartbeats(true); + } + else + { + ConsoleF("FAILED: SteamGameServer_Init(%x,%d,%d,%d,%d,%s)", ip, authenticationPort, GetSessionPort(), masterServerUpdaterPort, mode, steamVersion); + RptF("FAILED: SteamGameServer_Init(%x,%d,%d,%d,%d,%s)", ip, authenticationPort, GetSessionPort(), masterServerUpdaterPort, mode, steamVersion); + } +} + +void NetworkServer::DoneSteam() +{ + // Disconnect from the steam servers + if (SteamGameServer()) SteamGameServer()->LogOff(); + + // Release our reference to the steam client library + SteamGameServer_Shutdown(); +} + +void NetworkServer::SimulateSteam() +{ + // Run any Steam Game Server API callbacks + SteamGameServer_RunCallbacks(); + + // Update our server details + ChangeStateSteam(); +} + +void NetworkServer::ChangeStateSteam() +{ + if (SteamGameServer()) + { + // Tell the Steam Master Server about our game + SteamGameServer()->SetMaxPlayerCount(GetMaxPlayers()); + SteamGameServer()->SetPasswordProtected(_password || _sessionLocked); + SteamGameServer()->SetServerName(_server->GetSessionName()); + SteamGameServer()->SetMapName(_missionHeader.GetLocalizedMissionName()); + + // update any rule values we publish + SteamGameServer()->SetKeyValue("requiredVersion", Format("%d", MP_VERSION_REQUIRED)); +// SteamGameServer()->SetKeyValue("gameType", _missionHeader._gameType); + SteamGameServer()->SetKeyValue("island", _missionHeader._island); +// SteamGameServer()->SetKeyValue("serverState", Format("%d", _serverState)); +#if USE_MOD_LIST + SteamGameServer()->SetKeyValue("mod", GetModListNames()); +#endif +// SteamGameServer()->SetKeyValue("equalModRequired", _equalModRequired ? "1" : "0"); + SteamGameServer()->SetKeyValue("dedicated", _dedicated ? "1" : "0"); + SteamGameServer()->SetKeyValue("language", Format("%d", GetGameLanguage())); +// SteamGameServer()->SetKeyValue("difficulty", Format("%d", Glob.config.difficulty)); + SteamGameServer()->SetKeyValue("requiredBuild", Format("%d", _buildNoRequired)); + + RString gameTags; + if (_beIntegration.IsEnabled()) + gameTags = "battleye,"; + if (_disable3rdPerson) + gameTags = gameTags + "no3rd,"; + + extern const char* GetInstanceId( void ); + if ( GetInstanceId() && stricmp(GetInstanceId(),"000000")!=0 && stricmp(GetInstanceId(),"000001")!=0 ) + { // it is private "hive" server + gameTags = gameTags + "privHive,"; + } + + if (_environmentTimeMul > 0.0f) + { + RString tm = Format("etm%f,", _environmentTimeMul); + gameTags = gameTags + tm; + } + + float dayT = Glob.clockWeather.GetTimeOfDay()*24.0f; + RString dayTm = Format("%02d:%02d", toIntFloor(dayT), toIntFloor(60*(dayT-toIntFloor(dayT)))); + gameTags = gameTags + dayTm; + SteamGameServer()->SetGameTags(gameTags); + +#if defined(_WIN32) + SteamGameServer()->SetKeyValue("platform", "win"); +#elif defined(_LINUX) + SteamGameServer()->SetKeyValue("platform", "linux"); +#else + SteamGameServer()->SetKeyValue("platform", "?"); +#endif + + int timeleft; + if (_serverState == NSSPlaying) + { + timeleft = 15; + + float et = _missionHeader._estimatedEndTime.toFloat(); + if (et > 0) + { + et -= Glob.time.toFloat(); + timeleft = toInt(et / 60.0); + saturateMax(timeleft, 1); + } + } + else timeleft = 0; + SteamGameServer()->SetKeyValue("timeLeft", Format("%d", timeleft)); + if (SteamUtils()) SteamGameServer()->SetKeyValue("country", SteamUtils()->GetIPCountry()); + + // Update all the players names/scores + for (int i=0; i<_identities.Size(); i++) + { + const PlayerIdentity &identity = _identities[i]; + + // TODO: find the score + int score = 0; + SteamGameServer()->BUpdateUserData(CSteamID((uint64)identity._steamID), identity.GetName(), score); + } + } +} + +void NetworkServer::OnSteamServersConnected(SteamServersConnected_t *logonSuccess) +{ + ConsoleF("Connected to Steam"); + + // Steam servers are ready to accept our session info now + ChangeStateSteam(); +} + +void NetworkServer::OnSteamServersConnectFailure( SteamServerConnectFailure_t *connectFailure) +{ + // Even if master server connection fails, publish state for LAN / local players + ChangeStateSteam(); +} + +void NetworkServer::OnSteamServersDisconnected(SteamServersDisconnected_t *loggedOff) +{ + ConsoleF("Disconnected from Steam"); +} + +void NetworkServer::OnPolicyResponse(GSPolicyResponse_t *policyResponse) +{ + ConsoleF("Steam policy response"); +} + +#if _ENABLE_DEDICATED_SERVER +void NetworkServer::ResetCharacterTimeAlive(AIBrain *unit) +{ + Person *person = unit->GetPerson(); + if (person) + { + int dpnid = person->GetRemotePlayer(); + PlayerIdentity *identity = FindIdentity(dpnid); + if (identity && identity->_statistics) + { + identity->_statistics->Reset(EStat_characterTimeAlive); + } + } +} +#endif + +#endif +//} + +bool NetworkServer::DBSave(RString baseURL, int dpnid, RString request) +{ + NetworkPlayerInfo *info = GetPlayerInfo(dpnid); + if (!info) + return false; + PlayerIdentity *identity = FindIdentity(dpnid); + if (!identity) + return false; + + return info->DBSave(baseURL, identity->id, request); +} + +void NetworkServer::DBLoad(RString baseURL, int playerId, GameDataCode *code) +{ + const PlayerIdentity *identity = FindIdentityByPlayerId(playerId); + if (!identity) + return; + NetworkPlayerInfo *info = GetPlayerInfo(identity->dpnid); + if (!info) + return; + if (info) + info->DBLoad(baseURL, playerId, identity->id, info->name, code); +} + +void NetworkServer::DBLoad(RString baseURL, int playerId, RString playerUID, GameDataCode *code) +{ + const PlayerIdentity *identity = FindIdentityByPlayerId(playerId); + if (!identity) + return; + NetworkPlayerInfo *info = GetPlayerInfo(identity->dpnid); + if (!info) + return; + info->DBLoad(baseURL, playerId, playerUID, info->name, code); +} + +void LoadMissions(bool userMissions, AutoArray &missionList, bool campaignCheat=false); +static void AddMissionList(NetworkCommandMessage &answer, NetworkCommandMessage &answer2) +{ + PROFILE_SCOPE_EX(addML, network) + AutoArray missionList; + LoadMissions(false, missionList); + for (int i=0; idpid == player) + { + name = _players[i]->name; + break; + } + } + ConsoleF(LocalizeString(IDS_DS_ADMIN_LOGGED_IN), (const char *)name); + + _votings.Clear(); + + NetworkCommandMessage answer; + answer._type = NCMTLogged; + answer._content.Write(&_admin, sizeof(_admin)); + // AddMissionList(answer); + SendMsg(player, &answer, NMFGuaranteed); + + if (_mission[0] == '?' && _mission[1] == 0) + { + NetworkCommandMessage answer; + answer._type = NCMTVoteMission; + NetworkCommandMessage answer2; + answer2._type = NCMTVoteMissionExt; + AddMissionList(answer, answer2); + SendMsg(player, &answer, NMFGuaranteed); + SendMsg(player, &answer2, NMFGuaranteed); + } + + UpdateAdminState(); +} +#endif + +void NetworkServer::ApplyVoting(const AutoArray &id, const AutoArray *value) +{ +#if _ENABLE_DEDICATED_SERVER + int *ptr = (int *)id.Data(); + int type = *(ptr++); + switch (type) + { + case NCMTMission: + if (value) + { + // difficulty voting is separate - ask it for a result + // the voting is performed at the same time, therefore the result should be ready + _difficulty = Glob.config.diffDefault; + const Voting *diff = _votings.Find(NCMTDifficulty); + if (diff) + { + const AutoArray *diffValue = diff->GetValue(); + if (diffValue) + { + RString diffName(diffValue->Data(),diffValue->Size()); + int difficulty = Glob.config.diffNames.GetValue(diffName); + if (difficulty >= 0) _difficulty = difficulty; + } + _votings.DeleteVoting(NCMTDifficulty); + } + // check mission voting result + _mission = RString(value->Data(),value->Size()); + if (_mission.GetLength() > 0) _restart = true; + if (_serverState != NSSSelectingMission && _serverState != NSSPlaying) + { + GNetworkManager.DestroyAllObjects(); + SetServerState(NSSSelectingMission); + } + } + break; + case NCMTMissions: + DoMissions(false); + break; + case NCMTRestart: + if (_serverState == NSSPlaying) + { + _restart = true; + _reassign = false; + } + break; + case NCMTReassign: + DoReassign(); + break; + case NCMTKick: + { + int player = *(ptr++); + if (player != BOT_CLIENT) KickOff(player,KORKick); + } + break; + case NCMTAdmin: + if (value) + { + const char *p = value->Data(); + int player = *((int *)p); + if (player != AI_PLAYER && _dedicated && _gameMaster == AI_PLAYER) + SetGameMaster(player, true); + } + break; + } +#endif +} + +void OnServerUserMessage(int from, char *buffer, int bufferSize, void *context) +{ + NetworkServer *server = (NetworkServer *)context; + NetworkMessageRaw rawMsg(buffer, bufferSize); + server->DecodeMessage(from, rawMsg); +} + +void OnServerSendComplete(DWORD msgID, bool ok, void *context) +{ +} + +void OnServerPlayerCreate(int player, bool botClient, bool privateSlot, const char *name, const char *mod, unsigned long inaddr, void *context) +{ + if (!botClient && stricmp(mod, GLoadedContentHash) != 0) + { + RString format = LocalizeString(IDS_MP_VALIDERROR_2); + RString message = Format(format, cc_cast(name)); + +#if ENABLE_CLIENT_USE_MODIFIED_DATA_CHAT + if (!ChannelDisabled(CCSystem)) + { + RefArray dummy; + GNetworkManager.Chat(CCSystem, "", dummy, message); + } + GChatList.Add(CCSystem, NULL, message, false, true); +#endif +#if _ENABLE_DEDICATED_SERVER + ConsoleF("%s", cc_cast(message)); +#endif + } + + NetworkServer *server = (NetworkServer *)context; + server->OnCreatePlayer(player, privateSlot, name, inaddr); +} + +void OnServerPlayerDelete(int player, void *context) +{ + NetworkServer *server = (NetworkServer *)context; + server->OnPlayerDestroy(player); +} + +bool OnServerVoicePlayerCreate(int player, void *context) +{ + NetworkServer *server = (NetworkServer *)context; + return server->OnCreateVoicePlayer(player); +} + +unsigned NetworkServer::CleanUpMemory() +{ + if (_server) return _server->FreeMemory(); + return 0; +} + +void NetworkServer::OnClose() +{ +#if _USE_BATTL_EYE_SERVER + _beIntegration.Done(); +#endif +} +void NetworkServer::ReceiveSystemMessages() +{ + if (_server) + { + _server->ProcessSendComplete(OnServerSendComplete, this); + _server->ProcessPlayers(OnServerPlayerCreate, OnServerPlayerDelete, this); + _server->ProcessVoicePlayers(OnServerVoicePlayerCreate, this); + } +} + +void NetworkServer::ReceiveUserMessages() +{ + if (_server) _server->ProcessUserMessages(OnServerUserMessage, this); +} + +void NetworkServer::RemoveSystemMessages() +{ + if (_server) + { + _server->RemoveSendComplete(); + _server->RemovePlayers(); + _server->RemoveVoicePlayers(); + } +} + +void NetworkServer::RemoveUserMessages() +{ + if (_server) _server->RemoveUserMessages(); +} + +void CalculateMinMaxAvg::Sample(float value, float weight) +{ + saturateMin(_min,value); + saturateMax(_max,value); + _sum += value*weight; + _lastValue = value; + _weight += weight; +} + +void CalculateMinMaxAvg::Reset() +{ + _min = FLT_MAX; + _max = FLT_MIN; + _sum = 0; + _weight = 0; + _lastValue = 0; +} + +CalculateMinMaxAvg::CalculateMinMaxAvg() +{ + Reset(); +} + + +inline int toLargeIntSat(float x) +{ + if (x>=INT_MAX) return INT_MAX; + if (x dummy; + GNetworkManager.Chat(CCSystem, "", dummy, text); +} + +void NetworkServer::ServerMessage(const LocalizedFormatedString &text) +{ + RString localized = text.GetLocalizedValue(); +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + ConsoleF("%s", cc_cast(localized)); +#endif +//} + GChatList.Add(CCSystem, NULL, localized, false, true); + RefArray dummy; + GNetworkManager.LocalizedChat(CCSystem, "", dummy, text); +} + + +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + +#define DEBUG_TYPE_ENUM(type,prefix,XX) \ + XX(type, prefix, TotalSent) \ + XX(type, prefix, UserSent) \ + XX(type, prefix, Console) \ + XX(type, prefix, UserInfo) \ + XX(type, prefix, UserQueue) \ + XX(type, prefix, JIPQueue) + +#ifndef DECL_ENUM_DEBUG_TYPE +#define DECL_ENUM_DEBUG_TYPE +DECL_ENUM(DebugType) +#endif +DECLARE_DEFINE_ENUM(DebugType,DT,DEBUG_TYPE_ENUM) + +/*! +\patch 1.88 Date 10/21/2002 by Ondra +- Added: Dedicated server command #debug (userInfo) +(Requires 1.87 client) +\patch 1.90 Date 10/31/2002 by Ondra +- New: MP: Added #debug checkfile command. +Server admins can use this command to check if any file used by clients matches server version. +\patch 1.90 Date 10/31/2002 by Ondra +- New: MP: Added server.cfg array checkfiles[] - +list of files that should be checked for each player connecting. +Example: checkfiles[]={"HWTL\dta\data3d.pbo","dta\data3d.pbo"} +\patch 1.90 Date 10/31/2002 by Ondra +- New: Servers checks if world file (.wrp) used by client matches server version. +*/ + +static RString ExtractWord(RString &line) +{ + const char *endWord = strchr(line,' '); + if (!endWord) + { + RString word = line; + line = RString(); + return word; + } + RString word = line.Substring(0,endWord-line.Data()); + line = endWord+1; + return word; +} + +void NetworkServer::DebugAsk(RString str) +{ + // check for some special debug commands + RString line = str; + RString word = ExtractWord(line); + if (!strcmpi(word,"limitOut")) + { + RString limit = ExtractWord(line); + int limitBW = atoi(limit); + if (limit>0 && _server) + { + int limitBWB = (limitBW+7)/8; + _server->SetConnectionLimits(limitBWB); + RString message = Format("Outgoing bandwidth limited to %d B/s (%d bps) per client",limitBWB,limitBWB*8); + DebugAnswer(message); + } + return; + } + if (!strcmpi(word,"von")) + { + // check whether #debug von is not currently running + if (_server && !GDebugVoNBank.IsRunning()) + { + //P2P Topology + QOStrStream diag; + AutoArray > convTable; + convTable.Realloc(_identities.Size()); + convTable.Resize(_identities.Size()); + for (int i=0; i<_identities.Size(); i++) + { + convTable[i]._dpnid = _identities[i].dpnid; + convTable[i]._id = _identities[i].GetDebugId(); + convTable[i]._name = _identities[i].name; + } + _server->GetVoNTopologyDiag(diag, convTable); + GDebugVoNBank.SetFeature(DebugVoNBank::VoNFeature_NetTopology, RString(diag.str(), diag.pcount()) ); + // Ask each player for her collected VoNFeatures + for (int i=0; i<_players.Size(); i++) + { + const NetworkPlayerInfo &player = *_players[i]; + NetworkCommandMessage ask; + ask._type = NCMTAskVoNDiagnostics; + SendMsg(player.dpid, &ask, NMFGuaranteed); + } + // Set VoNDiagnozer to wait on clients answers and report it after while + GDebugVoNBank.StartCollecting(GlobalTickCount(), _players.Size()); + } + return; + } + if (!strcmpi(word,"jipPerf")) + { + if (_server) + { + //P2PManager diagnostics first + RString initDiag = GetAddInitAndRemoveOverriddenStat(); + DebugAnswer(initDiag); + } + return; + } + #if _ENABLE_CHEATS + if (!strcmpi(word,"exec")) + { + if (_server) + { + GameVarSpace vars(false); + int gshandle = GGameState.BeginContext(&vars); + GGameState.Execute(line, GameState::EvalContext::_default, GWorld->GetMissionNamespace()); // mission namespace + GGameState.EndContext(gshandle); + } + } + #endif + // check if string is only numbers + char *endNum; + float interval = strtod(str,&endNum); + if (*endNum==0) + { + _debugInterval = interval; + saturate(_debugInterval,0.1f,3600); + BString<256> msg; + sprintf(msg,"Debug: Interval %g",_debugInterval); + DebugAnswer(RString(msg)); + return; + } + if (!stricmp(str,"off")) + { + // clear all debug info + _debugOn.Clear(); + DebugAnswer(RString("Debug: All off")); + //_debugInterval = 0; + _debugNext = INT_MAX; + return; + } + + const char *beg = str; + const char *end = strchr(beg, ' '); + int len = end ? end - beg : strlen(beg); + + RString strCommand(beg, len); + DebugType command = GetEnumValue((const char *)strCommand); + if (command < 0) return; + + beg += len; + while (*beg == ' ') beg++; + + if (stricmp(beg, "off") == 0) + { + _debugOn.DeleteKey(command); + DebugAnswer(RString("Debug: ") + strCommand + RString(" off")); + } + else + { + _debugOn.AddUnique(command); + DebugAnswer(RString("Debug: ") + strCommand); + + if (_debugInterval<=0) + { + _debugInterval = 10; + _debugNext = _debugNext + toInt(_debugInterval*1000); + } + DWORD next = GlobalTickCount()+toInt(_debugInterval*1000); + if (_debugNext>next) _debugNext = next; + } +} + +void NetworkServer::DebugAnswer(RString str) +{ + if (_gameMaster != AI_PLAYER || !_dedicated) + { + if (_dedicated) + { + NetworkCommandMessage msg; + msg._type = NCMTDebugAnswer; + msg._content.WriteString(str); + SendMsg(_gameMaster, &msg, NMFGuaranteed); + } + LogDebugger("%s",cc_cast(str)); + } +} + +/*! +\patch 5126 Date 1/31/2007 by Jirka +- Fixed: DS crash occurred when mission with some special name (containing '%') was selected +*/ + +int NetworkServer::ConsoleF(const char *format, ...) +{ + va_list arglist; + va_start(arglist, format); + + if (_debugOn.FindKey(DTConsole) >= 0) + { + BString<512> buf; + vsprintf(buf, format, arglist); + DebugAnswer((const char *)buf); + } + int result = ::VConsoleF(format, arglist); + + va_end( arglist ); + return result; +} + +#endif +//} + +/* +const DWORD VotingTimeOutReady = 30000; // timeout in ms when all players are ready +const DWORD VotingTimeOutNotReady = 120000; // timeout in ms when no players are ready + +const DWORD BriefingTimeOutReady = 15000; // timeout in ms when all players are ready +const DWORD BriefingTimeOutNotReady = 60000; // timeout in ms when no players are ready + +const DWORD DebriefingTimeOutReady = 30000; // timeout in ms when all players are ready +const DWORD DebriefingTimeOutNotReady = 60000; // timeout in ms when no players are ready +*/ + +#include "Es/Common/langExt.hpp" +#define ENABLED_SHORTTIMEOUT_Bebul 1 +#define ENABLED_SHORTTIMEOUT_Jirka 1 +#if ENABLED_FEATURE(SHORTTIMEOUT) + +const DWORD VotingTimeOutReady = 5000; // timeout in ms when all players are ready +const DWORD VotingTimeOutNotReady = 5000; // timeout in ms when no players are ready + +#else + +const DWORD VotingTimeOutReady = 60000; // timeout in ms when all players are ready +const DWORD VotingTimeOutNotReady = 60000; // timeout in ms when no players are ready + +#endif + +const DWORD BriefingTimeOutReady = 60000; // timeout in ms when all players are ready +const DWORD BriefingTimeOutNotReady = 60000; // timeout in ms when no players are ready + +const DWORD DebriefingTimeOutReady = 45000; // timeout in ms when all players are ready +const DWORD DebriefingTimeOutNotReady = 45000; // timeout in ms when no players are ready + +bool NetworkServer::CheckTimeOut(int readyCount, int totalCount, DWORD ready, DWORD notReady) +{ + // with low numbers assume there still will be more players connecting + int minPlayersToVote = 8; + float readyRatio; + if (totalCount=timeToEnd) return true; + DWORD timeLeft = timeToEnd-GlobalTickCount(); + int secondsLeft = timeLeft/1000+1; + + if (_serverTimeOutSent!=secondsLeft) + { + // send to all players + ServerTimeoutMessage msg; + msg._timeout = secondsLeft; + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.clientState < NCSConnected) continue; + SendMsg(info.dpid, &msg, NMFGuaranteed); + } + _serverTimeOutSent = secondsLeft; + } + + #if _ENABLE_REPORT + GlobalShowMessage(1000,"Time left: %d",secondsLeft); + #endif + return false; +} + +RString NetworkServer::GetDiagText(const NetworkId &id) const +{ + NetworkObjectInfo *oInfo = GetObjectInfo(id); + if (!oInfo) return RString(); + + RString ret = Format(" Pos from %d",oInfo->currentUpdate[NMCUpdatePosition].from); + if (oInfo->currentRejected[NMCUpdatePosition].message) ret = ret + Format(" Pos rejected from %d",oInfo->currentRejected[NMCUpdatePosition].from); + if (oInfo->rejected[NMCUpdatePosition]) ret = ret + " Rejected"; + return ret; +} + + +/*! +\patch 1.52 Date 4/19/2002 by Jirka +- Fixed: When gamemaster disconnect from server during mission selection, server was in bad state. +\patch 1.79 Date 7/31/2002 by Jirka +- Improved: Mission on dedicated server launched if all roles are assigned and confirmed even if some players remain +\patch 1.82 Date 8/23/2002 by Ondra +- Fixed: MP: If server had predefined mission cycle, +mission sometimes started while first user was connecting. +\patch 5110 Date 12/21/2006 by Jirka +- Fixed: Dedicated server can use missions in addons now +\patch 5132 Date 2/23/2007 by Jirka +- Fixed: server config parameter persistent is fully working now +\patch 5133 Date 2/26/2007 by Jirka +- Fixed: MP - admin is deciding when briefing is finished now +*/ + +struct MissionParameter +{ + RString name; + float val; + MissionParameter() {}; + MissionParameter(RString name1, float val1) : name(name1), val(val1) {}; + ClassIsMovableZeroed(MissionParameter); +}; + +void NetworkServer::SimulateDS() +{ + PROFILE_SCOPE_EX(nwDS, network) + + DWORD tickCount = GlobalTickCount(); + SimulateMonitor(tickCount); + +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + if (!_dedicated) return; + + + // persistent server with only one mission defined in server.cfg (class Missions) run the mission immediately without any players connected + bool startPersistentMission = false; + if (_persistent && _serverState!=NSSPlaying) + { + ConstParamEntryPtr entry = _serverCfg.FindEntry("Missions"); + int nEntries = entry ? entry->GetEntryCount() : 0; + startPersistentMission = (nEntries >= 1); + } + + if (_players.Size() <= 1 && !(_persistent && _serverState == NSSPlaying) && !startPersistentMission) + { + if (_serverState != NSSSelectingMission) + { + ConsoleF(LocalizeString(IDS_DS_NO_USERS)); + SetServerState(NSSSelectingMission); + CleanUpMemory(); + } + _missionIndex = -1; + _mission = ""; + _restart = false; + _reassign = false; + // restart timeout + _serverStateTime = GlobalTickCount(); + } + else // Main ServerState traverse section [SelectingMission, AssigningPlayers, Playing, Aborting...] + { + static bool loadIsland = false; + switch (_serverState) + { + case NSSSelectingMission: + { + RString t; + // if _param1,2 are not defined in server config, use default + _param1 = FLT_MAX; + _param2 = FLT_MAX; + AutoArray parameters; // secondary parameters + if (_mission.GetLength() == 1 && _mission[0] == '?') + { + // voting in progress + // check timeout, and react if necessary + // check how many players already voted + const Voting *miss = _votings.Find(NCMTMission); + if (!miss) break; + int total = _parent->GetIdentities()->Size(); + int ready = miss->Size(); + + // if server has reached half of its capacity, consider it full + if (CheckTimeOut(ready,total,VotingTimeOutReady,VotingTimeOutNotReady)) + { + // try applying vote first + if (!_votings.Apply(this,NCMTMission)) + { + // no voting available - select a random mission + AutoArray missionList; + LoadMissions(false, missionList); + int random = toIntFloor(GRandGen.RandomValue()*missionList.Size()); + saturate(random,0,missionList.Size()-1); + const MPMissionInfo &info = missionList[random]; + _mission = info.mission+"."+info.world; + // leave difficulty as it is + } + } + + break; + } + else if (_mission.GetLength() > 0) + { + // mission known - start it + t = _mission; + Glob.config.difficulty = _difficulty; + + _mission = ""; + _restart = false; + _reassign = false; + } + else + { + // check if there is some mission list defined + ConstParamEntryPtr entry = _serverCfg.FindEntry("Missions"); + int nEntries = entry ? entry->GetEntryCount() : 0; + if (nEntries == 0) + { + // no mission list - check if there are enough players to start voting + int voteMissionPlayers = 1; + entry = _serverCfg.FindEntry("voteMissionPlayers"); + if (entry) voteMissionPlayers = *entry; + if (_identities.Size() >= voteMissionPlayers) + { + // start voting + _mission = "?"; + NetworkCommandMessage answer; + answer._type = NCMTVoteMission; + NetworkCommandMessage answer2; + answer2._type = NCMTVoteMissionExt; + AddMissionList(answer,answer2); + for (int i=0; i<_identities.Size(); i++) + { + SendMsg(_identities[i].dpnid, &answer, NMFGuaranteed); + SendMsg(_identities[i].dpnid, &answer2, NMFGuaranteed); + } + } + break; + } + + // cycle through the mission list + _missionIndex++; + if (_missionIndex >= nEntries) _missionIndex = 0; + ParamEntryVal item = entry->GetEntry(_missionIndex); + + t = item >> "template"; + + Glob.config.difficulty = Glob.config.diffDefault; + entry = item.FindEntry("difficulty"); + if (entry) + { + RString diffName = *entry; + int difficulty = Glob.config.diffNames.GetValue(diffName); + if (difficulty >= 0) Glob.config.difficulty = difficulty; + } + else + { + bool cadetMode = item >> "cadetMode"; + if (cadetMode) + { + int difficulty = Glob.config.diffNames.GetValue("Cadet"); + if (difficulty >= 0) Glob.config.difficulty = difficulty; + } + else + { + int difficulty = Glob.config.diffNames.GetValue("Veteran"); + if (difficulty >= 0) Glob.config.difficulty = difficulty; + } + } + + if (item.FindEntry("param1")) _param1 = item >> "param1"; + if (item.FindEntry("param2")) _param2 = item >> "param2"; + + //read secondary parameters + ConstParamEntryPtr paramsDesc = item.FindEntry("Params"); + if(paramsDesc && paramsDesc->IsClass()) for(int i=0; i< paramsDesc->GetEntryCount();i++ ) + { + parameters.Add( MissionParameter( paramsDesc->GetEntry(i).GetName(), paramsDesc->GetEntry(i) ) ); + } + } + + // mission selected, start it now + + CurrentMission = ""; + + SetBaseDirectory(false, ""); + + bool noCopy = false; + RString owner; + + char mission[256]; strcpy(mission, t); + char *world = strrchr(mission, '.'); + if (!world) return; + *world = 0; world++; + +#if _ENABLE_MISSION_CONFIG + ConstParamEntryPtr entry = (Pars >> "CfgMissions" >> "MPMissions").FindEntry(mission); + if (entry) + { + ::SelectMission(*entry); + noCopy = true; + owner = entry->GetOwnerName(); + } + else +#endif + { + RString FindBriefingName(RString path); + RString displayName = FindBriefingName(MPMissionsDir + t); + + if (QIFileFunctions::FileExists(MPMissionsDir + t + RString(".pbo"))) + { + // mission in public bank + CreateMission(mission, world); + SetMission(world, "__cur_mp", MPMissionsDir); + Glob.header.filenameReal = mission; + + ConsoleF(LocalizeString(IDS_DS_MISSION_READ_FROM_BANK), (const char *)displayName); + } + else if (QIFileFunctions::FileExists(MPMissionsDir + t + RString("\\mission.sqm")) || + QIFileFunctions::FileExists(MPMissionsDir + t + RString("\\mission.sqf"))) + { + // mission in public directory + CreateMission("", ""); + SetMission(world, mission, MPMissionsDir); + + ConsoleF(LocalizeString(IDS_DS_MISSION_READ_FROM_DIR), (const char *)displayName); + } + else break; + } + + // load template + if (!ParseMission(true, true)) break; + + // if parameters are not set in server config, use defaults + if (_param1 == FLT_MAX) + { + _param1 = 0; + ConstParamEntryPtr cfg = ExtParsMission.FindEntry("defValueParam1"); + if (cfg) _param1 = *cfg; + } + if (_param2 == FLT_MAX) + { + _param2 = 0; + ConstParamEntryPtr cfg = ExtParsMission.FindEntry("defValueParam2"); + if (cfg) _param2 = *cfg; + } + _paramsArray.Clear(); + _paramsArray.Add(_param1); + _paramsArray.Add(_param2); + // secondary parameters + ConstParamEntryPtr paramsDesc = ExtParsMission.FindEntry("Params"); + if(paramsDesc) for(int i=0; i< paramsDesc->GetEntryCount();i++ ) + { + ParamEntryVal parameterDesc = paramsDesc->GetEntry(i); + ConstParamEntryPtr entry = parameterDesc.FindEntry("default"); + _paramsArray.Add(entry ? *entry : 0); + RString name = parameterDesc.GetName(); + for (int j=0; jIsArray()) + { + for (int i=0; iGetSize(); i++) + { + int chan = toInt((float)(*cls)[i]); + DisableChannel(chan); + } + } + + InitMission(Glob.config.difficulty, RString(), noCopy, owner, false); + SetServerState(NSSAssigningPlayers); + } + break; + case NSSAssigningPlayers: + { + _restart = false; + + // create game + SetServerState(NSSSendingMission); + SendMissionFile(); + + ConsoleF(LocalizeString(IDS_DS_ROLES_ASSIGNED)); + + // clear statistics now - ensure they will not be cleared after stats info from clients arrived + GStats.ClearMission(); + SetServerState(NSSLoadingGame); + + loadIsland = true; + } + break; + case NSSSendingMission: + Fail("Temporary state"); + break; + case NSSLoadingGame: + if (loadIsland && GNetworkManager.GetClient()->GetClientState() == NCSMissionReceived) + { + loadIsland = false; + + ConsoleF(LocalizeString(IDS_DS_READING_MISSION)); + + Ref p = GWorld->BegLoadMissionProgress(Glob.header.worldname, *CurrentTemplate, GModeNetware); + + GWorld->SwitchLandscape(Glob.header.worldname); + + //set parameters - after SwitchLandscape + float param1 = 0, param2 = 0; + GetNetworkManager().GetParams(param1, param2); + GameState *gstate = GWorld->GetGameState(); + gstate->VarSet("param1", GameValue(param1), false, false, GWorld->GetMissionNamespace()); // mission namespace + gstate->VarSet("param2", GameValue(param2), false, false, GWorld->GetMissionNamespace()); // mission namespace + GNetworkManager.PublicVariable("param1", 0); + GNetworkManager.PublicVariable("param2", 0); + + const MissionHeader *header = GetNetworkManager().GetMissionHeader(); + AutoArray paramsArray = GetNetworkManager().GetParamsArray(); + GameValue valueAR = gstate->CreateGameValue(GameArray); + GameArrayType &arrayAR = valueAR; + arrayAR.Resize(0); + for(int i=0; i< paramsArray.Size(); i++) + { + if(header->_sizesParamArray[i]<=0) continue; + arrayAR.Add(paramsArray[i]); + } + gstate->VarSet("paramsArray", arrayAR, false, false, GWorld->GetMissionNamespace()); // mission namespace + GNetworkManager.PublicVariable("paramsArray", 0); + + CurrentTemplate->ActivateAddons(Glob.header.worldname); + CurrentTemplate->InitGeneral(GModeNetware); + bool error = !GWorld->InitVehicles(*CurrentTemplate); + + ProgressFinish(p); + + RString message = GetMaxErrorMessage(); + if (message.GetLength()>0) + { + ServerMessage(message); + if (GetMaxError()>=EMError) // on error select another mission, let warning through + { + SetServerState(NSSSelectingMission); + break; + } + } + if (error) + { + ServerMessage(LocalizeString(IDS_DS_LOAD_MISSION_ERROR)); + SetServerState(NSSSelectingMission); + break; + } + + GNetworkManager.CreateAllObjects(); + // objects are created on client, so we can proceed after transfer from client to server completes + + void RunInitScript(); + RunInitScript(); + + message = GetMaxErrorMessage(); + if (message.GetLength()>0) + { + ServerMessage(message); + if (GetMaxError()>=EMError) // on error select another mission, let warning through + { + SetServerState(NSSSelectingMission); + break; + } + } + ConsoleF(LocalizeString(IDS_DS_MISSION_READ)); + } + break; + case NSSPlaying: + if (_restart) + { + GNetworkManager.DestroyAllObjects(); + ConsoleF("Game restarted"); + SetServerState(NSSMissionAborted); + } + else if + ( + GWorld->GetEEndMode() != EMContinue && + ( + (!GWorld->GetCameraEffect() && !GWorld->GetTitleEffect()) || + GWorld->IsEndForced() + ) + ) + { + GNetworkManager.DestroyAllObjects(); + ConsoleF(LocalizeString(IDS_DS_GAME_FINISHED)); + SetServerState(NSSMissionAborted); // we need to wait on the end of mission on other clients + } + else + { + if (!_persistent) + { + // if the server is not persistent, check if some player is still playing the mission + // if not, we want the mission to be terminated + // see also World::CheckMissionEnd to termination on all players dead + + bool all = true; + for (int i=0; i<_players.Size(); i++) + { + int player = _players[i]->dpid; + + NetworkClientState state = GetClientState(player); + if (state >= NCSGameLoaded && state <= NCSGameFinished) + { + all = false; + break; + } + } + if (all) + { + GNetworkManager.DestroyAllObjects(); + ConsoleF(LocalizeString(IDS_DS_GAME_FINISHED)); + SetServerState(NSSMissionAborted); + //debriefing = Glob.uiTime; + } + } + } + break; + case NSSMissionAborted: + { + bool all = true; + if (_gameMaster != AI_PLAYER) + { + NetworkClientState state = GetClientState(_gameMaster); + all = state != NCSPlaying && state != NCSGameFinished; + } + else + { + int total = 0, ready = 0; + for (int i=0; i<_players.Size(); i++) + { + NetworkClientState state = _players[i]->clientState; + + if (state>=NCSPlaying || state<=NCSMissionSelected) + { + total++; + if (state>=NCSGameFinished) + { + ready++; + } + } + } + + all = ( + ready>=total || + CheckTimeOut(ready,total,DebriefingTimeOutReady,DebriefingTimeOutNotReady) + ); + } + if (all) + { + // update statistics + if (_restart && _reassign) + { + DoReassignDirect(); + } + else if (_restart && _mission.GetLength() == 0) + { + SetServerState(NSSAssigningPlayers); + loadIsland = true; + } + else + { + SetServerState(NSSSelectingMission); + ConsoleF(LocalizeString(IDS_DS_WAITING_FOR_NEXT_GAME)); + } + } + } + break; + } + } + + + if (GDebugVoNBank.IsReportReady(tickCount)) + { // Report the #debug von collected info at last + FILE *LogFile = GetNetworkManager().GetDedicatedServerLogFile(); + if ( LogFile ) + { + AutoArray > convTable; + convTable.Realloc(_identities.Size()); + convTable.Resize(_identities.Size()); + for (int i=0; i<_identities.Size(); i++) + { + convTable[i]._dpnid = _identities[i].dpnid; + convTable[i]._id = _identities[i].GetDebugId(); + convTable[i]._name = _identities[i].name; + } + fprintf(LogFile, "*** VoN Topology Diagnostics ((***\n"); + RString response = GDebugVoNBank.GetDebugString(convTable); + GDebugVoNBank.StopCollecting(); // other client responses are too late + GDebugVoNBank.Reset(); // next #debug von should not contain old data + fwrite(cc_cast(response), 1, response.GetLength(), LogFile); + fprintf(LogFile, "*** VoN Topology Diagnostics ))***\n"); + fflush(LogFile); + } + } + + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.clientState < NCSConnected) continue; + if (info.motdIndex >= 0 && Glob.uiTime >= info.motdTime) + { + ChatMessage chat; + chat._channel = CCGlobal; + chat._text = _motd[info.motdIndex]; + chat._name = ""; + SendMsg(info.dpid, &chat, NMFGuaranteed); + + info.motdIndex++; + if (info.motdIndex >= _motd.Size()) info.motdIndex = -1; + else info.motdTime = Glob.uiTime + _motdInterval; + } + } + +#endif // _ENABLE_DEDICATED_SERVER +//} +} + + +void NetworkServer::SimulateMonitor( DWORD tickCount ) +{ +#if _ENABLE_DEDICATED_SERVER + _monitorFrames++; + if (tickCount >= _monitorNext) + { + if (_gameMaster == AI_PLAYER && _dedicated) + { + _monitorInterval = 0; + } + else //if (_state == NGSPlay) + { + NetworkCommandMessage msg; + msg._type = NCMTMonitorAnswer; + float invInterval = 1.0 / (_monitorInterval + 0.001f * (tickCount - _monitorNext)); + float fps = _monitorFrames * invInterval; + int memory = MemoryUsed(); + float in = _monitorIn * invInterval; + float out = _monitorOut * invInterval; + msg._content.Write(&fps, sizeof(fps)); + msg._content.Write(&memory, sizeof(memory)); + msg._content.Write(&in, sizeof(in)); + msg._content.Write(&out, sizeof(out)); + + int sizeG = 0, sizeNG = 0; + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &player = *_players[i]; + for (int j=0; jmsg->size; + for (int j=0; jmsg->size; + } + msg._content.Write(&sizeG, sizeof(sizeG)); + msg._content.Write(&sizeNG, sizeof(sizeNG)); + + SendMsg(_gameMaster!=AI_PLAYER ? _gameMaster : BOT_CLIENT, &msg, NMFGuaranteed); + } + Monitor(_monitorInterval); + } +#endif +} + + + +#if PEER2PEER + +void P2PServerProcess(int channel, P2PMsgType type, BYTE *data, int dataSize, void *context) +{ + if (type == P2PRequest) + { + if (dataSize < 1) return; + PeerToPeerServer *p2p = (PeerToPeerServer*)context; + Assert(p2p); + switch (data[0]) // message type + { + case 0: + // list of missions + { + QOStrStream out; + out.put(0); // response type + + // TODO: caching for faster response + AutoArray list; + SaveHeaderAttributes filter; + filter.Add("type", FindEnumName(STMission)); + filter.Add("player", Glob.header.GetPlayerName()); + GDebugger.PauseCheckingAlive(); + FindSaves(list, filter); + GDebugger.ResumeCheckingAlive(); + for (int i=0; iSendAnswer(channel, (BYTE *)out.str(), out.pcount()); + } + break; + case 1: + // mission + break; + } + } +} + +#endif // PEER2PEER + +#if _ENABLE_CHEATS || _ENABLE_DEDICATED_SERVER + +NetStatsGraph::NetStatsGraph() +{ + _lastTime = ::GlobalTickCount(); + _lastSize = 0; + _lastMsg = 0; +} + +void NetStatsGraph::OnSimulate(int size, int msg) +{ + DWORD now = ::GlobalTickCount(); + float deltaT = (now-_lastTime)*0.001f; + if (deltaT>0) + { + // 8*000.1 convert from B/s to kbps + PerformanceGraph<2>::Values val; + val.values[0] = (size-_lastSize)*8*0.001f/deltaT; + val.values[1] = (msg-_lastMsg)/deltaT; + AddSample(val,deltaT); + } + _lastSize = size; + _lastMsg = msg; + _lastTime = now; + +} + +#endif + +RefD ImplicitMapTraits< RefD >::zombie = (NetworkObjectInfo*)1; +RefD ImplicitMapTraits< RefD >::null; + +/*! +\patch 1.79 Date 7/26/2002 by Jirka +- Added: Elimination of "disconnect cheat" +\patch 1.90 Date 10/30/2002 by Jirka +- Fixed: Message "Player ... is loosing connection" isn't write for server now +*/ + +RString NetworkServer::NetworkIdToNetIdFriendly(const NetworkId &id) +{ + RefD dInfo; + if (_objects.get(id,dInfo)) + { + NetworkMessageCreateVehicle *msg = dynamic_cast(dInfo->create.message.GetRef()); + if (msg) + { + return Format("%s %s", cc_cast(NetworkIdToNetId(id)), cc_cast(msg->_type)); + } + else + { + const char *name = "UNKNOWN"; + switch (dInfo->create.type) + { + case NMTCreateClientCameraPosition: name = "cameraPos"; break; + case NMTCreateTurret: name = "turret"; break; + case NMTCreateShot: name = "shot"; break; + } + return Format("%s %s", name, cc_cast(NetworkIdToNetId(id))); + } + } + //! object not found? + return NetworkIdToNetId(id); +} + +void NetworkServer::OnSimulate() +{ + PROFILE_SCOPE_EX(nwSer, network) + +#if _ENABLE_DEDICATED_SERVER + // Show the dedicated server's own update rate in the console window title. + // This counts server simulation callbacks, not the connected client's render FPS. + if (IsDedicatedServer()) + { + static DWORD fpsWindowStart = 0; + static unsigned int fpsWindowFrames = 0; + const DWORD now = ::GetTickCount(); + if (fpsWindowStart == 0) fpsWindowStart = now; + ++fpsWindowFrames; + const DWORD elapsed = now - fpsWindowStart; + if (elapsed >= 1000) + { + const float serverFps = fpsWindowFrames * 1000.0f / elapsed; + NetworkServer *server = GNetworkManager.GetServer(); + if (server) + { + RString title = APP_NAME " Console version " APP_VERSION_TEXT "." STRINGIZE(BUILD_NO) ": port %d | FPS %.1f"; + ConsoleTitle(title, server->GetSessionPort(), serverFps); + } + fpsWindowStart = now; + fpsWindowFrames = 0; + } + } +#endif + +#define DIAGNOSE_NETWORK_OBJECTS 0 +#if DIAGNOSE_NETWORK_OBJECTS + static volatile bool diagnoseObjects = false; + if (diagnoseObjects) + { + RptF("*** NetworkServer _objects list"); + IteratorState it; + RefD obj; + if ( _objects.getFirst(it,obj) ) + { + do + { + RptF(" %s",NetworkIdToNetIdFriendly(obj->id)); + } + while ( _objects.getNext(it,obj) ); + } + RptF("*** NetworkServer _objects list"); + diagnoseObjects = false; //only once + } +#endif + + // raw statistics +#if _ENABLE_CHEATS + // remove statistics info + static AutoArray texts; + for (int i=0; i= 0) GEngine->RemoveText(texts[i]); + } + texts.Resize(0); + + if (outputDiags == ODMRawStats+NOutputDiags) + { + _rawStatisticsGraph.Resize(_rawStatistics.Size()); + // int y = 40; + for (int i=0; i<_rawStatistics.Size(); i++) + { + char output[1024]; + NetworkPlayerInfo *info = GetPlayerInfo(_rawStatistics[i].player); + if (!info) continue; + sprintf + ( + output, "To %s: sent %d (%d), received %d (%d)", + (const char *)info->name, + _rawStatistics[i].sizeSent, _rawStatistics[i].msgSent, + _rawStatistics[i].sizeReceived, _rawStatistics[i].msgReceived + ); + texts.Add(GEngine->ShowTextF(1000, output)); + //y += 25; + + if (!_rawStatisticsGraph[i]) _rawStatisticsGraph[i] = new NetStatsGraph; + _rawStatisticsGraph[i]->OnSimulate(_rawStatistics[i].sizeSent,_rawStatistics[i].msgSent); + GEngine->ShowDiagGraph(_rawStatisticsGraph[i]); + + } + } +#endif + +#define DIAG_NETWORK_OBJECTS 0 +#if DIAG_NETWORK_OBJECTS + static int diagnozeObjectId = 0; + if (diagnozeObjectId) + { + for (int i=0; i<_objects.Size(); i++) + { + Object *obj = dynamic_cast(GNetworkManager.GetObject(_objects[i]->id)); + if (obj && obj->GetObjectId().Encode()==diagnozeObjectId) + { + LogF( " DIAGNOZED ENTITY: %s, index in _objects=%d", obj->GetDebugName(), i ); + break; + } + } + diagnozeObjectId = 0; + } + // find object diagnoze using her NetworkId + static bool diagnozeNetworkId = false; + static int diagnozeCreator = 0; + static int diagnozeId = 0; + if (diagnozeNetworkId) + { + NetworkId diagNetworkId(diagnozeCreator, diagnozeId); + int index = -1; + for (int i=0; i<_objects.Size(); i++) + { + if (_objects[i]->id==diagNetworkId) { index=i; break; } + } + NetworkObject *nObj = GNetworkManager.GetObject(diagNetworkId); + if (nObj) + { + LogF( " DIAGNOZED ENTITY: %s, index in _objects=%d", nObj->GetDebugName(), index ); + } + else + { + LogF( " DIAGNOZED ENTITY: *NOT FOUND*, index in _objects=%d", index ); + } + diagnozeNetworkId = false; + } +#endif + +#define DIAG_SLOPE_SELECTION_SERVER_LAGGING 0 +#if DIAG_SLOPE_SELECTION_SERVER_LAGGING + // RptF all players networking information from time to time + int currentTickCnt = ::GetTickCount(); + static DWORD lastDiagTickCount = currentTickCnt; + const DWORD nextDiagDelay = 60000; //1 minute + if ( lastDiagTickCount + nextDiagDelay < currentTickCnt ) + { + lastDiagTickCount = currentTickCnt; + RptF("*** Start: Players Networking Diagnostics ***"); + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &pnet = _players[i]; + //if (pnet.dpid==BOT_CLIENT) continue; + PlayerIdentity *id = FindIdentity(pnet.dpid); + if (!id) continue; + RptF(" %s bandwidth=<%d,%d,%d> ping=<%d,%d,%d> desync=%d", + cc_cast(id->name), + toLargeIntSat(pnet._bandwidth.GetMin()/(1024/8)), toLargeIntSat(pnet._bandwidth.GetMax()/(1024/8)), toLargeIntSat(pnet._bandwidth.GetAvg()/(1024/8)), + toInt(pnet._ping.GetMin()), toInt(pnet._ping.GetMax()), toInt(pnet._ping.GetAvg()), + toLargeIntSat(pnet._desync.GetAvg()*100) + ); + } + RptF("*** End: Players Networking Diagnostics ***"); + } +#endif + +#if _ENABLE_DEDICATED_SERVER + + { + DWORD now = GlobalTickCount(); + if (now >= _debugNext) + { + if (_gameMaster == AI_PLAYER && _dedicated || _debugInterval<0.001) + { + _debugNext = INT_MAX; + } + else + { + _debugNext = _debugNext + toInt(_debugInterval*1000); + } + + float invAge = 1/_debugInterval; + + if (_debugOn.FindKey(DTUserSent) >= 0) + { + for (int i=0; i<_rawStatistics.Size(); i++) + { + BString<512> output; + NetworkPlayerInfo *info = GetPlayerInfo(_rawStatistics[i].player); + if (!info) continue; + sprintf + ( + output, "%s: sent %.0f bps (%.2f Msgps), received %.0f bps (%.2f Msgps)", + (const char *)info->name, + invAge * _rawStatistics[i].sizeSent *8, invAge * _rawStatistics[i].msgSent, + invAge * _rawStatistics[i].sizeReceived *8, invAge * _rawStatistics[i].msgReceived + ); + DebugAnswer((const char *)output); + } + } + + if (_debugOn.FindKey(DTTotalSent) >= 0) + { + int totalMsgSent = 0; + int totalMsgReceived = 0; + int totalSizeSent = 0; + int totalSizeReceived = 0; + for (int i=0; i<_rawStatistics.Size(); i++) + { + totalMsgSent += _rawStatistics[i].msgSent; + totalMsgReceived += _rawStatistics[i].msgReceived; + totalSizeSent += _rawStatistics[i].sizeSent; + totalSizeReceived += _rawStatistics[i].sizeReceived; + } + BString<512> output; + sprintf + ( + output, "** Total: sent %.0f bps (%.2f Msgps), received %.0f bps (%.2f Msgps)", + invAge * totalSizeSent * 8, invAge * totalMsgSent, + invAge * totalSizeReceived * 8, invAge * totalMsgReceived + ); + DebugAnswer((const char *)output); + } + + _rawStatistics.Clear(); + + if (_debugOn.FindKey(DTUserQueue) >= 0) + { + // send info about all players + for (int i=0; i<_players.Size(); i++) + { + const NetworkPlayerInfo &player = *_players[i]; + int sizeG = 0, sizeNG = 0; + for (int j=0; jmsg->size; + for (int j=0; jmsg->size; + // print actual desync as well + + BString<512> output; + sprintf + ( + output, "%s: Queue %d B (%d) %d B Guaranteed (%d), Desync %.0f", + (const char *)player.name, + sizeNG, player._messageQueueNonGuaranteed.Size(), sizeG, player._messageQueue.Size(), + player._desync.GetAvg()*100 + ); + DebugAnswer((const char *)output); + } + } + if (_debugOn.FindKey(DTUserInfo) >= 0) + { + // send info about all players + for (int i=0; i<_players.Size(); i++) + { + const NetworkPlayerInfo &player = *_players[i]; + + RString stats = _server->GetStatistics(player.dpid); + + BString<512> output; + sprintf + ( + output, "%s: Info %s", + (const char *)player.name, (const char *)stats + ); + DebugAnswer((const char *)output); + } + } + if (_debugOn.FindKey(DTJIPQueue) >= 0) + { + BString<512> output; + sprintf(output, "Init %d",_initMessages.Size()); + DebugAnswer((const char *)output); + + } + } // if (time for #debug) + + } +#endif + + // receive all system and user messages + { + PROFILE_SCOPE_EX(nwSRv, network) + ReceiveSystemMessages(); + ReceiveLocalMessages(); + ReceiveUserMessages(); + } + + // SDZ_SQF_EXEC: all network messages of this frame are processed; it is now safe + // to run scripts that create/delete objects or walk the mission object list. + #if _ENABLE_DEDICATED_SERVER + if (_dedicated) ProcessQueuedExec(); + #endif + + PerformIntegrityInvestigations(); + + #if _ENABLE_MP + // cancel all update messages + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &pInfo = *_players[i]; + // statistics + if (DiagLevel >= 3) + { + int nMsg, nBytes, nMsgG, nBytesG; + _server->GetSendQueueInfo(pInfo.dpid, nMsg, nBytes, nMsgG, nBytesG); + if (nMsg > 0 || nMsgG > 0) + { + if ( nMsgG < 0 ) // old style + DiagLogF("Server to %s: pending in SendQueue: %d messages, %d bytes", (const char *)pInfo.name, nMsg, nBytes); + else // new style + DiagLogF("Server to %s: pending in SendQueue: common - %d messages, %d bytes, guaranteed - %d messages, %d bytes", + (const char *)pInfo.name, nMsg, nBytes, nMsgG, nBytesG); + } + } + } + #endif + + DWORD tickCount = GlobalTickCount(); + if (GDebugVoNBank.IsReportReady(tickCount)) + { // Report the #debug von collected info at last + AutoArray > convTable; + convTable.Realloc(_identities.Size()); + convTable.Resize(_identities.Size()); + for (int i=0; i<_identities.Size(); i++) + { + convTable[i]._dpnid = _identities[i].dpnid; + convTable[i]._id = _identities[i].GetDebugId(); + convTable[i]._name = _identities[i].name; + } + FILE *LogFile = GetNetworkManager().GetDedicatedServerLogFile(); + if ( LogFile ) + { + fprintf(LogFile, "*** VoN Topology Diagnostics ((***\n"); + RString response = GDebugVoNBank.GetDebugString(convTable); + GDebugVoNBank.StopCollecting(); // other client responses are too late + GDebugVoNBank.Reset(); // next #debug von should not contain old data + fwrite(cc_cast(response), 1, response.GetLength(), LogFile); + fprintf(LogFile, "*** VoN Topology Diagnostics ))***\n"); + fflush(LogFile); + } + else + { + // Set TimeStampFormat of LogF to none in order to make VoN Topology Diagnostics parser VoNDiag2FSM.exe working + TimeStampFormat backup = GTimeStampFormat; + GTimeStampFormat = TSFNone; + LogF("*** VoN Topology Diagnostics ((***"); + RString response = GDebugVoNBank.GetDebugString(convTable); + GDebugVoNBank.StopCollecting(); // other client responses are too late + GDebugVoNBank.Reset(); // next #debug von should not contain old data + response = response + "*** VoN Topology Diagnostics ))***"; + LogF(response); + GTimeStampFormat = backup; + } + } + + SimulateDS(); + + // kick off players faded out + CheckFadeOut(); + + // destroy players kicked out + int size = _identities.Size(); + for (int i=size-1; i>=0; i--) + { + PlayerIdentity &identity = _identities[i]; + if (identity.destroy && Glob.uiTime >= identity.destroyTime) + { + OnPlayerDestroy(identity.dpnid); + } + } + + // send update messages + { + PROFILE_SCOPE_EX(nwSSd, network) + SendMessages(); + } + + // update _serverTime + _serverTime = ::GetTickCount()-_serverTimeInitTickCount; + if ( _serverTime > _nextServerTimeUpdate ) + { + _nextServerTimeUpdate = _serverTime + ServerTimeUpdateInterval; + // send fresh serverTime update to all clients + ServerTimeMessage stmsg; + _serverTime = ::GetTickCount()-_serverTimeInitTickCount; // update _serverTime + stmsg._time = _serverTime; + stmsg._endTime = _serverTimeOfEstimatedEnd; + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.clientState < NCSConnected) continue; + SendMsg(info.dpid, &stmsg, NMFGuaranteed | NMFHighPriority); + } + } + + // calculate aggregate de-sync average + { + float desyncTotal = 0; + + float avgDesync = 0; + float maxDesync = 0; + int nDesync = 0; + for (int i=0; i<_players.Size(); i++) + { + const NetworkPlayerInfo &pnet = *_players[i]; + // bot client has no de-sync by definition + if (pnet.dpid==BOT_CLIENT) continue; + float value = pnet._desync.GetLastValue(); + avgDesync += value, nDesync ++; + saturateMax(maxDesync,value); + } + if (nDesync>0) + { + avgDesync /= nDesync; + // aggregate de-sync - consider both avg and max + desyncTotal = avgDesync*0.7f+maxDesync*0.3f; + } + _desyncTotal.Sample(desyncTotal,1e-3); + } + + + const DWORD desyncTotalPeriod = 5000; + if (GlobalTickCount()>_desyncTotalUpdateNext) + { + // maintain aggregate de-sync average + _desyncTotalAvg = _desyncTotal.GetAvg(); + _desyncTotalMax = _desyncTotal.GetMax(); + _desyncTotal.Reset(); + _desyncTotalUpdateNext = GlobalTickCount()+desyncTotalPeriod; + } + + // avoid flickering the icon + // check de-sync information for all players + _connectionDesync = CDGood; + // show worst de-sync found for any player + float aggDesync = _desyncTotalAvg; + if (aggDesync>PlayerIdentity::DesyncLow/100) + { + if (aggDesync>PlayerIdentity::DesyncHigh/100) + { + _connectionDesync = CDHigh; + } + else + { + _connectionDesync = CDLow; + } + } + + tickCount = GlobalTickCount(); + if (tickCount >= _pingUpdateNext) + { + _pingUpdateNext = tickCount + 30000; + + // update all players information + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &pnet = *_players[i]; + //if (pnet.dpid==BOT_CLIENT) continue; + PlayerIdentity *id = FindIdentity(pnet.dpid); + if (!id) continue; + id->_minBandwidth = toLargeIntSat(pnet._bandwidth.GetMin()/(1024/8)); + id->_maxBandwidth = toLargeIntSat(pnet._bandwidth.GetMax()/(1024/8)); + id->_avgBandwidth = toLargeIntSat(pnet._bandwidth.GetAvg()/(1024/8)); + id->_minPing = toInt(pnet._ping.GetMin()); + id->_maxPing = toInt(pnet._ping.GetMax()); + id->_avgPing = toInt(pnet._ping.GetAvg()); + id->_desync = toLargeIntSat(pnet._desync.GetAvg()*100); + saturate(id->_desync,0,100000); + pnet._ping.Reset(); + pnet._bandwidth.Reset(); + pnet._desync.Reset(); + } + + // broadcast messages about all players to all players + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.clientState < NCSConnected) continue; + for (int i=0; i<_identities.Size(); i++) + { + PlayerIdentity &pi = _identities[i]; + + NetworkMessageType type = pi.GetNMType(NMCUpdatePosition); + + Ref msg = ::CreateNetworkMessage(type); + msg->time = Glob.time; + NetworkMessageContext ctx(msg, this, info.dpid, MSG_SEND); + ctx.SetClass(NMCUpdatePosition); + + PREPARE_TRANSFER(PlayerUpdate) + + TMError err; + int dpnid = pi.dpnid; + err = TRANSF_BASE(dpnid, dpnid); + if (err != TMOK) continue; + err = pi.TransferMsg(ctx); + if (err != TMOK) continue; + + // send message + //NetworkComponent:: + SendMsg(info.dpid,msg,type,NMFNone, NULL); + } + } + } + + // integrity and CDKey checks + DWORD time = GlobalTickCount(); + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + // CDKey check + if (info.cdKeyCheck.timeout) + { + if (time > info.cdKeyCheck.timeout) + { + if (info.dpid == BOT_CLIENT) + { + RString errmsg = LocalizeString(IDS_MP_BAD_CDKEY); + GChatList.Add(CCSystem, NULL, errmsg, false, true); + WarningMessage(errmsg); + Done(); + } + else + { + KickOff(info.dpid, KORAuthTimeOut); + } + info.cdKeyCheck.timeout = 0; //clear + } + } + } + + // squad checks + bool canSendCustomFiles = true; + bool timeout = false; + for (int i=0; i<_squadChecks.Size();) + { + CheckSquadObject *obj = _squadChecks[i]; + if (i==0) + { //first object can be timeouted in order others can connect too + if (_squadChecksTimeout) + { + if (_squadChecksTimeout < ::GetTickCount()) //timeout + timeout = true; + } + else if (obj->GetState()==CheckSquadObject::SendingCustomFiles) + { + _squadChecksTimeout = ::GetTickCount() + 30*1000; //30 seconds + } + } + if (obj->IsDone(canSendCustomFiles, this)) + { + PlayerIdentity &identity = obj->_identity; + CreateIdentity(identity); + _squadChecks.Delete(i); + if (i==0) //reset timeout + { + _squadChecksTimeout = 0; + timeout = false; + } + } + else i++; + } + if (timeout) + { + _squadChecksTimeout = 0; + // shift the squad objects and place the first at the end + int schSize = _squadChecks.Size(); + if (schSize>1) + { + SRef first = _squadChecks[0]; + for (int i=1; i_timeLeftLastTime+minBetweenUpdates) + { +/* + // do not update the session description regularly, server will ask us + + // time from time update matchmaking stats + UpdateMatchmakingDescription(false); +*/ + +#if _GAMES_FOR_WINDOWS + // set the properties and contexts for matchmaking + // - TimeLeft + GSaveSystem.SetProperty(PROPERTY_GAME_TIMELEFT, timeleft); +#endif + } + else if (_timeLeftLastValueBcast!=timeleft) + { + // if there is any timeleft estimation, update it + // updating session description for broadcast session is very quick + // no network traffic required + UpdateSessionDescription(); + _timeLeftLastValueBcast = timeleft; + } + +//{ QUERY & REPORTING SDK +#if _ENABLE_GAMESPY + SimulateQR(); +#endif +//} + + //{ STEAMWORKS SDK +#if _ENABLE_STEAM_MATCHMAKING + SimulateSteam(); +#endif + //} + + //DoAssert(CheckIntegrityOfPendingMessages()); + + //DWORD tickCount = ::GlobalTickCount(); + + + // log all diagnostics + WriteDiagOutput(true); + + // check for disconnected players + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.clientState != NCSPlaying) continue; + if (info.dpid == BOT_CLIENT) continue; + float age = _server->GetLastMsgAgeReliable(info.dpid); + if (info.connectionProblemsReported) + { + info.connectionProblemsReported = age > 5.0f; + } + else if (age >= 10.0f) + { + LocalizedFormatedString message; + message.SetFormat(LocalizedString::Stringtable,"STR_MP_CONNECTION_LOOSING"); + message.AddArg(LocalizedString::PlainText,info.name); + ServerMessage(message); + info.connectionProblemsReported = true; + } + } + +#if _ENABLE_CHEATS + if (_debugWindow) + { + _debugWindow->ResetContent(); + _objects.forEach([this](NetworkObjectInfo *oInfo) + { + if (!oInfo) return; + NetworkId id = oInfo->id; + int owner = oInfo->owner; + RString name = GetPlayerName(owner); + RString typeName; + if (oInfo->currentUpdate[0].message.NotNull()) + { + NetworkMessageType type = oInfo->currentUpdate[0].type; + DoAssert(type >=0 && type < NMTN); + typeName = GetMsgTypeName(type); + } + else typeName = "Unknown"; + BString<1024> text; + sprintf + ( + text, "%s %d:%" OID_FORMAT" - owner %s (%x)", + (const char *)typeName, id.creator.CreatorInt(), id.id, + (const char *)name, owner + ); + _debugWindow->AddString(text); + } + ); + } +#endif + +#if _VBS2 && _VBS2_LITE +// Check if there has been a hack attempt on player size limit +// if, there has been, we randomly select offsets and apply them to random players +if(_server) +{ + if(((_players.Size() << 3) > (_VBS2_MAX_PLAYERS << 3))&&(_memoryWrite == false)) + { + _memoryWrite = true; + _nextRanUpdate = GlobalTickCount() + (DWORD) GRandGen.Gauss((1000*30),(1000*30*2),(1000*30*3)); + } + + if(_memoryWrite && (GlobalTickCount()>_nextRanUpdate)) + { + DWORD nextUpdate = (DWORD) GRandGen.Gauss((1000*30),(1000*30*2),(1000*30*3)); + _nextRanUpdate = GlobalTickCount() + nextUpdate; + + int playerIndex = GRandGen.Gauss(0,0.5,_players.Size()); + if(playerIndex >= 0 && playerIndex < _players.Size()) + { + NetworkPlayerInfo &info = _players[playerIndex]; + NetworkId &id = info.person; + if (!id.IsNull()) + { + NetworkObjectInfo *oInfo = GetObjectInfo(id); + if(GNetworkManager.GetClient()) + { + NetworkObject *netObj = GNetworkManager.GetClient()->GetObject(oInfo->id); + Entity *obj = dyn_cast(netObj); + if(obj) + { + // raise player 100 feet above the ground. + Matrix4 trans = obj->Transform(); + Vector3 pos = trans.Position(); + pos += Vector3( + GRandGen.Gauss(-500.0f,0.0f,500.0f), + GRandGen.Gauss(-1.0f,0.0f,1.0f), + GRandGen.Gauss(-500.0f,0.0f,500.0f)); + + trans.SetPosition(pos); + obj->MoveNetAware(trans); + obj->OnPositionChanged(); + } + } + } + } + } +} +#endif + + // TODO: remove (temporary set all to all) + // Set voice transmission tables on Xbox + if (_server) + { + for (int i=0; i<_players.Size(); i++) + { + // if player is not fully created, he might be unable to receive VoN messages + // this is because VoNClient is created after MAGIC_CREATE_PLAYER message is sent + // perhaps better solution could be to create VoN client before sending the message + // Current solution with player state gives players also some time + // to establish and report peer to peer communication + if (_players[i]->clientStatedpid!=BOT_CLIENT) continue; + // set all other players as recipients + int fromID = _players[i]->dpid; + AUTO_STATIC_ARRAY(int, players, 32); + for (int j=0; j<_players.Size(); j++) + { + if (_players[j]->clientStatedpid!=BOT_CLIENT) continue; + int toID = _players[j]->dpid; + if (toID != fromID) players.Add(toID); +#if HEAR_YOURSELF + else if (hearYourself) players.Add(toID); +#endif + } + _server->SetTransmitTargets(fromID, players); + } + _server->UpdateTransmitTargets(); + } + +#if _USE_BATTL_EYE_SERVER + if (!_beIntegration.Run(this)) + { + // reinitialization after auto-update failed, need to shut-down the server + Done(); + } +#if 0 + // simple test of ExecuteCommand functioinality + static volatile int doIt = -1; //set it to 1000 or something and wait + if (doIt>0) doIt--; + else if (!doIt) + { + doIt--; + BattlEye::ExecuteCommand("#restart"); + } +#endif +#endif + + // check if characters loading is not finished + for (int i=0; i<_players.Size(); i++) + { + _players[i]->DBCheckLoaded(); + } + +#if _ENABLE_STEAM_MATCHMAKING && _ENABLE_DEDICATED_SERVER + static int counter = 0; + if ((counter++ % 10)==0) // TODO + { + for (int i=0; i<_identities.Size(); ++i) + { + if (_identities[i]._statistics) _identities[i]._statistics->Simulate(); + } + } +#endif +} + +void NetworkServer::OnSimulateDone() +{ +} + +void NetworkServer::FastUpdate() +{ +//{ QUERY & REPORTING SDK +#if _ENABLE_GAMESPY + SimulateQR(); +#endif +//} +} + +void NetworkServer::OnDraw() +{ + static bool lagDiags = false; + + if (GInput.GetCheatXToDo(CXTLag)) + { + lagDiags = !lagDiags; + GlobalShowMessage(500,"Lag diags %s",lagDiags ? "On":"Off"); + } + if (lagDiags) + { + static float minLagToShow = 1.0f; + static float badLag = 100.0; + float x = 0.05f; + float y = 0.08f; + float width = 0.80f; + Font *font=GEngine->GetDebugFont(); + float size = 0.02; + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &pnet = *_players[i]; + float maxLag = pnet._desync.GetMax(); + if (maxLagConvert(rect2D,rect); + Point2DAbs pos(rect2D.x,rect2D.y); + MipInfo mip = GEngine->TextBank()->UseMipmap(NULL, 0, 0); + GEngine->Draw2D(mip,color,rect2D); + + y+= size; // proceed to a next line + GEngine->DrawTextF( + pos,size,font,nameColor,0,"%s - %g, max %g, avg %g", + cc_cast(pnet.name),lag,pnet._desync.GetMax(),pnet._desync.GetAvg() + ); + } + } +} + +DEFINE_FAST_ALLOCATOR(NetworkObjectInfo) + +/*! +\patch 1.47 Date 3/7/2002 by Ondra +- New: Player ID now displayed in server console when player is connected. +\patch 1.56 Date 5/13/2002 by Ondra +- New: When player is kicked off or banned, specific message is shown. +\patch 5153 Date 4/17/2007 by Jirka +- Fixed: When failed to join to a locked server, the correct cause is shown now. +*/ + +void NetworkServer::OnCreatePlayer(int player, bool privateSlot, const char *name, unsigned long inaddr) +{ + if (_sessionLocked) + { + // session is locked + _server->KickOff(player, NTRSessionLocked); + return; + } + + OnPlayerCreate(player, privateSlot, name, inaddr); +} + +DummyInput GDummyInput; + +InputInterface *NetworkServer::GetInputInterface(int player) +{ + NetworkPlayerInfo *info = GetPlayerInfo(player); + if (!info) return &GDummyInput; + return info->_clientInput; +} + +bool NetworkServer::OnCreateVoicePlayer(int player) +{ + NetworkPlayerInfo *info = GetPlayerInfo(player); + if (!info) return false; + info->dvid = player; + return true; +} + +void NetworkServer::GetPlayers(AutoArray &players) +{ + players.Resize(0); + for (int i=0; i<_players.Size(); i++) + { + int index = players.Add(); + players[index].dpid = _players[i]->dpid; + players[index].name = _players[i]->name; + players[index].person = _parent->GetClient()->GetObject(_players[i]->person); + } +} + +void NetworkServer::UseItem(Person *person, InventoryItem *item) +{ + const NetworkObjectInfo *info = GetObjectInfo(person->GetNetworkId()); + if (!info) return; + + UseItemMessage msg; + msg._person = person; + msg._item = item; + SendMsg(info->owner, &msg, NMFGuaranteed); +} + +bool NetworkServer::CheckPlayerInLobby(const NetworkPlayerInfo &info) const +{ + if (info.clientState==NCSPlaying) + { + // in-game - check if alive + // this may be difficult, as we are server, and should not have any access to a game world? + // find a network object describing the players unit + const NetworkObjectInfo *obj = GetObjectInfo(info.person); + // if the unit is NULL, session was most likely already terminated on the server + if (!obj) return true; + const NetworkCurrentInfo &curInfo = obj->currentUpdate[NMCUpdateGeneric]; + // HOTFIX: probably possible in some rare conditions (crash occurred) + if (!curInfo.message) return false; + // unless proven otherwise, assume alive + } + else + { + // not in-game - force lobby + return true; + } + return false; +} + +void NetworkServer::GetPlayersOnChannel(AutoArray &players, AutoArray units, DWORD from, bool voice) +{ + players.Resize(0); + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.dpid == from) continue; + if (info.clientState < NCSConnected) continue; + for (int j=0; j &players, int channel, DWORD from, bool voice) +{ + players.Resize(0); + switch (channel) + { + case CCNone: + case CCDirect: + return; + case CCSystem: + case CCGlobal: + for (int i=0; i<_players.Size(); i++) + { + const NetworkPlayerInfo &info = *_players[i]; + if (info.dpid == from) continue; + if (info.clientState < NCSConnected) continue; + if (voice) + { + if (info.dvid != 0) players.Add(info.dvid); + } + else + players.Add(info.dpid); + } + break; + case CCVehicle: + // TODO: remove in DayZ? + break; + } + if (channel>=CCCustom1 && channel<=CCCustomLast) + { + for (int i=0; i<_players.Size(); i++) + { + const NetworkPlayerInfo &info = *_players[i]; + if (info.dpid == from) continue; + if (info.clientState < NCSConnected) continue; + CustomChannelInfo &ccinfo = GCustomChannels.GetCustomChannelInfo(channel); + for (int j=0; jGetNetworkId()) + { + if (voice) + { + if (info.dvid != 0) players.Add(info.dvid); + } + else + players.Add(info.dpid); + } + } + } + } +} + +void NetworkServer::InitSignatureCollecting(NetworkPlayerInfo *info) +{ + // last DataSignatureAnswer with index CollectEndIndex finishes it + info->hashes.StartCollecting(); +#if 0 + // do not send CollectEndIndex packet, as the collecting is run asynchronously on client + // the client itself should send the answer after the collecting is over + DataSignatureAskMessage collectEndMsg; + collectEndMsg._index = CollectedHashes::CollectEndIndex; + collectEndMsg._level = 0; + SendMsg(info->dpid, &collectEndMsg, NMFGuaranteed); +#endif + // add the question to the list of pending questions + info->signatureChecks.Add(CollectedHashes::CollectEndIndex); +} + +RString CollectedHashes::RandomUsedFile(Vector3Par pos, int level) +{ + const int CandidatesMaxCount = 5; + AutoArray > candidates; + for (int i=0; i<10; i++) //max 10 tries to get five non-empty candidates + { + RString file = GWorld->RandomUsedFile(pos); + if (file.IsEmpty()) continue; + QFBank *bank = QFBankQueryFunctions::AutoBank(file); + if (bank) + { + RString prefix = bank->GetPrefix(); + // avoid duplicate banks in candidates + bool duplicate = false; + for (int j=0; j0) + { + int bestIx = 0; int bestAsksCount = INT_MAX; + for (int i=0; i0) + { + if (ident.blockedKeys.Size()>0 && VerifySignedKeys(ident.blockedKeys,ident.blockedKeysSignature)) + { + // if there is any problem with the blocked key list, just ignore it + // synchronize server version of the list + // use always the longer one, as that is the more complete + UpdateBanListSecure(ident.blockedKeys,ident.blockedKeysSignature); + } + + RString message = "Player ID not registered"; + SignValidationResult signOK = SignUnknownError; + if (ident.certificate.Size()>0) + { + signOK = VerifySignedData(ident.id,info->certChallenge,ident.challengeSigned,ident.certificate); + switch (signOK) + { + case SignOK: break; + case SignBlockedUser: message = "CD Key is blocked";break; + case SignBadUserName: message = "Player ID not verified: Certificate belongs to a different user";break; + case SignBadSignature: message = "Player ID not verified: Bad signature";break; + case SignBadCertificate: message = "Player ID not verified: Certificate not accepted";break; + default: message = "Player ID not verified: Unknown error";break; + } + } + if (signOK!=SignOK) + { + if (SecureIdRequired()>=2) + { + // cheat - do not let him connect + KickOff(info->dpid,KORBadCDKey,message); + return; + } + else + { + // forget everything related to playerID verification, so that it is obvious the player was not verified + ident.certificate.Clear(); + ident.challengeSigned.Clear(); + info->certChallenge = 0; + RefArray dummy; + GNetworkManager.Chat(CCSystem, ident.name, dummy, message); + GChatList.Add(CCSystem, ident.name, message, false, true); + #if _ENABLE_DEDICATED_SERVER + if (_dedicated) + { + ConsoleF("%s:%s %s", cc_cast(ident.name), cc_cast(ident.id), cc_cast(message)); + } + #endif + } + } + } + #endif + + int index = _identities.Add(ident); + PlayerIdentity &identity = _identities[index]; + identity.playerid = NextPlayerId(); + +#if _ENABLE_STEAM_MATCHMAKING && _ENABLE_DEDICATED_SERVER + identity._statistics = new SteamStatistics(); + identity._statistics->Init(CSteamID((uint64)identity._steamID)); +#endif + +#if _VERIFY_KEY + // check for double id + if (identity.ValidateID()) + { + // check only when id!=0 + // for id==0 we have better handling + // id==999 is used in Multiplayer Demo + // DEV1,DEV2,...,DEV999 are used in internal versions with INTERNAL_KEYS + for (int i=0; i<_identities.Size(); i++) + { + if (i == index) continue; + + if (IsUserIdMatch(_identities[i].id,identity.id)) + { + OnDoubleIdDetected(identity, _identities[i]); + // check if player was kicked out + if (identity.destroy) return; + break; + } + } + } +#endif + +#if _ENABLE_GAMESPY && _VERIFY_CLIENT_KEY + if ( _validateCDKey && identity.dpnid!=BOT_CLIENT ) + { + #if _ENABLE_CHEATS // internal clients connected to internal exe perform no GS key validation + static const char devPrefix[] = "DEV"; + if (strncmp(identity.id,devPrefix,strlen(devPrefix))) + #endif + { + char buffer[9]; + for (int i=0; ichallenge = buffer; + // initial CD Key test + CDKeyCheckAskMessage ask; + ask._challenge = info->challenge; + SendMsg(identity.dpnid, &ask, NMFGuaranteed); + //increased to 90 seconds after problems with CD-key authentication 15.6.2012 + info->cdKeyCheck.timeout = GlobalTickCount()+90000; //90 seconds + } + } +#endif + + if (identity.dpnid == BOT_CLIENT) + identity._rights |= PRServer; + else + { + if (_verifySignatures) + { + if (_sigVerRequired<2) + { + // initial test of signatures + DataSignatureAskMessage ask; + ask._index = -2; + ask._level = 0; // shallow check + SendMsg(identity.dpnid, &ask, NMFGuaranteed); + InitSignatureCollecting(info); + } + else + { + // initial test using level 2 check + DataSignatureAskMessage askLev2; + askLev2._index = -2; + askLev2._level = 2; //HashOf(nonDataHash+fileListHash+pboPrefix) is used + SendMsg(identity.dpnid, &askLev2, NMFGuaranteed); + InitSignatureCollecting(info); + } + } + + + sockaddr_in address; + if (GetClientAddress(identity.dpnid, address)) + { + identity._voiceAddress = address; + //ConnectVoice(identity.dpnid,address); + } + } + +#if LOG_PLAYERS +LogF +( + "Server: Identity added - name %s, id %d (total %d identities, %d players)", + (const char *)ident.name, ident.dpnid, _identities.Size(), _players.Size() +); +#endif + + identity.name = info->name; + identity.clientState = NCSConnected; +#if _GAMES_FOR_WINDOWS + identity.privateSlot = info->privateSlot; +#endif + + // Send list of current players which custom files should be removed (as new one will be sent) + DeleteCustomFilesMessage dcfMsg; + for (int i=0; i<_identities.Size(); i++) + { + if (i != index) dcfMsg._list.Add(_identities[i].name); + } + if (dcfMsg._list.Size()) SendMsg(identity.dpnid, &dcfMsg, NMFGuaranteed); + + for (int i=0; i<_identities.Size(); i++) + { + PlayerIdentity &player = _identities[i]; + if (i != index) + { + // send all faces and sounds to new player + { + if (stricmp(player.face, "custom") == 0) + TransferFace(identity.dpnid, player.name); + TransferCustomRadio(identity.dpnid, player.name); + } + + // send all identities to new player + SendMsg(identity.dpnid, &player, NMFGuaranteed); + + } + // send new identity to all players + SendMsg(player.dpnid, &identity, NMFGuaranteed); + } + +#if _ENABLE_MP + // send mute list to a new player + SendMuteList(identity); +#endif + +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + if (_dedicated) + { + NetworkClient *client = _parent->GetClient(); + DoAssert(client && client->GetPlayer() != identity.dpnid); + // send new identity to bot client + SendMsg(client->GetPlayer(), &identity, NMFGuaranteed); + } +#endif +//} + +/* + info->state = NGSLogin; + + // all message formats registered, we may send messages + // send state dependent info + if (_state >= NGSPrepareSide) + { + // send mission info + SendMissionInfo(info->dpid); + info->state = NGSPrepareSide; + info->missionFileValid = false; + } + // send current state + ChangeGameState gs(_state); + SendMsg(info->dpid, &gs, NMFGuaranteed); + + // if game is already in progress, send how long is played already + if (_state == NGSPlay) + { + NetworkCommandMessage msg; + msg.type = NCMTMissionTimeElapsed; + int timeElapsed = GlobalTickCount() - _missionHeader.start; + msg.content.Write(&timeElapsed, sizeof(timeElapsed)); + SendMsg(info->dpid, &msg, NMFGuaranteed); + } + + identity.state = info->state; + + // send player state to all clients + SetPlayerState(info->dpid, info->state); +*/ + + // Send server state to client + ServerStateMessage msg; + msg._serverState = _serverState; + SendMsg(identity.dpnid, &msg, NMFGuaranteed); + + identity._minPing = 10; + identity._avgPing = 100; + identity._maxPing = 1000; + + identity._minBandwidth = 14; + identity._avgBandwidth = 28; + identity._maxBandwidth = 33; + + // Send chat message about player is connected + if (identity.dpnid != BOT_CLIENT) + { +/* + // commented out by rocket, not desired for dayz. possibly use for admins only + LocalizedFormatedString message; + message.SetFormat(LocalizedString::Stringtable,"STR_MP_CONNECT"); + message.AddArg(LocalizedString::PlainText,identity.name); + RefArray dummy; + if (!ChannelDisabled(CCSystem)) + GNetworkManager.LocalizedChat(CCSystem, "", dummy, message); + + GChatList.Add(CCSystem, NULL, message.GetLocalizedValue(), false, true); + + // make sure ping information will be refreshed soon + DWORD updatePingTime = GlobalTickCount() + 5000; + if (_pingUpdateNext>updatePingTime) _pingUpdateNext = updatePingTime; +*/ + #if _ENABLE_DEDICATED_SERVER + if (_dedicated) + { + ConsoleF(LocalizeString(IDS_DS_PLAYER_CONNECTED),cc_cast(identity.name), cc_cast(identity.id)); + } + #endif + } + UpdateMatchmakingDescription(false); + +#if _ENABLE_DEDICATED_SERVER + if (_serverState == NSSSelectingMission && _mission.GetLength() == 1 && _mission[0] == '?') + { + NetworkCommandMessage answer; + answer._type = NCMTVoteMission; + NetworkCommandMessage answer2; + answer2._type = NCMTVoteMissionExt; + AddMissionList(answer,answer2); + for (int i=0; i<_identities.Size(); i++) + { + SendMsg(_identities[i].dpnid, &answer, NMFGuaranteed); + SendMsg(_identities[i].dpnid, &answer2, NMFGuaranteed); + } + } +#endif + +#if _ENABLE_DEDICATED_SERVER + // event handler + OnEvent(SEOnUserConnected, identity.playerid); +#endif +} + +#ifndef _WIN32 +extern bool interrupted; +#endif + + +static bool CheckValidUpload(RString path, RString name) +{ + RString prefixShouldBe = GetServerTmpDir() + RString("\\players\\") + EncodeFileName(name) + RString("\\"); + return !strnicmp(path,prefixShouldBe,prefixShouldBe.GetLength()); +} + +static RString GetRelUploadPath(RString path, RString name) +{ + RString prefixShouldBe = GetServerTmpDir() + RString("\\players\\") + EncodeFileName(name) + RString("\\"); + if (strnicmp(path,prefixShouldBe,prefixShouldBe.GetLength())) return path; + return path.Substring(prefixShouldBe.GetLength(),INT_MAX); +} + +DWORD WINAPI AsyncDBStorage::DBSaveThreadFunction(void *ctx) +{ + Ref context = (SaveThreadContext *)ctx; + context->DecRef(); + + // wait until previous requests end + Ref prev = context->_prevContext; + if (prev) + { + prev->_thread.Wait(); + context->_prevContext = NULL; // no longer needed + } + + // send save request + RString result; + int err = GetResponse(EHTTPREQ_POST,result,context->_url,context->_uid,context->_request); + if (err >= 400) + { + LogF("HTTP Error: %d", err); + LogF(result); + } + + return 0; +} + +DWORD WINAPI AsyncDBStorage::DBQueueThreadFunction(void *ctx) +{ + Ref context = (SaveThreadContext *)ctx; + context->DecRef(); + + // wait until previous requests end + Ref prev = context->_prevContext; + if (prev) + { + prev->_thread.Wait(); + context->_prevContext = NULL; // no longer needed + } + + // send save request + RString result; + int err = GetResponse(EHTTPREQ_POST,result,context->_url,context->_uid,context->_request); + if (err >= 400) + { + LogF("HTTP Error: %d", err); + LogF(result); + } + + return 0; +} + +DWORD WINAPI AsyncDBStorage::DBKillThreadFunction(void *ctx) +{ + Ref context = (SaveThreadContext *)ctx; + context->DecRef(); + + // wait until previous requests end + Ref prev = context->_prevContext; + if (prev) + { + prev->_thread.Wait(); + context->_prevContext = NULL; // no longer needed + } + + // send save request + RString result; + + int err = GetResponse(EHTTPREQ_POST,result, context->_url,context->_uid, context->_request); + if (err >= 400) + { + LogF("HTTP Error: %d", err); + LogF(result); + } + + return 0; +} + +DWORD WINAPI AsyncDBStorage::DBItemDropThreadFunction(void *ctx) +{ + Ref context = (SaveThreadContext *)ctx; + context->DecRef(); + + // wait until previous requests end + Ref prev = context->_prevContext; + if (prev) + { + prev->_thread.Wait(); + context->_prevContext = NULL; // no longer needed + } + + // send save request + RString result; + + int err = GetResponse(EHTTPREQ_POST,result, context->_url, NULL, context->_request); + if (err >= 400) + { + LogF("HTTP Error: %d", err); + LogF(result); + } + + return 0; +} + +bool AsyncDBStorage::DBSave(RString baseURL, RString playerUID, RString request) +{ + SaveThreadContext *ctx = new SaveThreadContext(); + ctx->AddRef(); // player can disconnect while Thread still need access to its context + + ctx->_url = baseURL; + ctx->_uid = Format("?uid=%s", cc_cast(playerUID)); + ctx->_request = request; + ctx->_prevContext = _lastContext; + _lastContext = ctx; +#if USE_MT_LIB_FOR_JOBS + ctx->_thread.Init(CreateMTThreadOnCPU(64 * 1024, DBSaveThreadFunction, ctx, 2, MultiThread::ThreadBase::PriorityNormal, "DBSaveCharacter")); +#else + ctx->_thread.Init(CreateThreadOnCPU(64 * 1024, DBSaveThreadFunction, ctx, 2, THREAD_PRIORITY_NORMAL, "DBSaveCharacter")); +#endif + return true; +} + +bool AsyncDBStorage::DBQueue(RString baseURL, RString playerUID, RString request) +{ + SaveThreadContext *ctx = new SaveThreadContext(); + ctx->AddRef(); // player can disconnect while Thread still need access to its context + + ctx->_url = baseURL; + ctx->_uid = playerUID; + ctx->_request = request; + ctx->_prevContext = _lastContext; + _lastContext = ctx; +#if USE_MT_LIB_FOR_JOBS + ctx->_thread.Init(CreateMTThreadOnCPU(64 * 1024, DBQueueThreadFunction, ctx, 2, MultiThread::ThreadBase::PriorityNormal, "DBQueueCharacter")); +#else + ctx->_thread.Init(CreateThreadOnCPU(64 * 1024, DBQueueThreadFunction, ctx, 2, THREAD_PRIORITY_NORMAL, "DBQueueCharacter")); +#endif + return true; +} + +bool AsyncDBStorage::DBKill(RString baseURL, RString playerUID) +{ + SaveThreadContext *ctx = new SaveThreadContext(); + ctx->AddRef(); // player can disconnect while Thread still need access to its context + + ctx->_url = baseURL; + ctx->_uid = playerUID; + ctx->_request = ""; + ctx->_prevContext = _lastContext; + _lastContext = ctx; +#if USE_MT_LIB_FOR_JOBS + ctx->_thread.Init(CreateMTThreadOnCPU(64 * 1024, DBKillThreadFunction, ctx, 2, MultiThread::ThreadBase::PriorityNormal, "DBKillCharacter")); +#else + ctx->_thread.Init(CreateThreadOnCPU(64 * 1024, DBKillThreadFunction, ctx, 2, THREAD_PRIORITY_NORMAL, "DBKillCharacter")); +#endif + return true; +} + +bool AsyncDBStorage::DBItemDrop(RString baseURL, RString request) +{ + SaveThreadContext *ctx = new SaveThreadContext(); + ctx->AddRef(); // player can disconnect while Thread still need access to its context + + ctx->_url = baseURL; + ctx->_request = request; + ctx->_prevContext = _lastContext; + _lastContext = ctx; +#if USE_MT_LIB_FOR_JOBS + ctx->_thread.Init(CreateMTThreadOnCPU(64 * 1024, DBItemDropThreadFunction, ctx, 2, MultiThread::ThreadBase::PriorityNormal, "DBItemDrop")); +#else + ctx->_thread.Init(CreateThreadOnCPU(64 * 1024, DBItemDropThreadFunction, ctx, 2, THREAD_PRIORITY_NORMAL, "DBItemDrop")); +#endif + return true; +} + + +DWORD WINAPI AsyncDBStorage::DBLoadThreadFunction(void *ctx) +{ + Ref context = (LoadThreadContext *)ctx; + context->DecRef(); + + // wait until previous save requests end + Ref prev = context->_prevContext; + if (prev) + { + prev->_thread.Wait(); + context->_prevContext = NULL; // no longer needed + } + + RString uidQuery = Format("?uid=%s", cc_cast(context->_playerUID)); + context->_err = GetResponse(EHTTPREQ_GET,context->_result,context->_url,uidQuery,NULL); + + return 0; +} + +void AsyncDBStorage::DBCheckLoaded() +{ + for (int i=0; i<_loadContexts.Size();) + { + LoadThreadContext *ctx = _loadContexts[i]; + if (!ctx->_thread.TryWait()) + { + // thread is still running + i++; continue; + } + // thread finished, handle results + Person *person = NULL; + if (ctx->_err >= 400) + { + LogF("dbServerLoadCharacter: HTTP Error %d", ctx->_err); + LogF(ctx->_result); + } + else + { + JSONDocument document; + document.Parse(ctx->_result); + + if (document.Empty()) + { + LogF("dbServerLoadCharacter: document not parsed"); + LogF(ctx->_result); + } + else + { + JSONValue &value = document["model"]; + if (!value.IsString()) + { + LogF("dbServerLoadCharacter: model not found"); + LogF(ctx->_result); + } + else + { + RString model = value.GetString(); + + // simplified vehicle creation + Ref veh = GWorld->NewNonAIVehicleWithID(model, RString()); + person = dyn_cast(veh.GetRef()); + if (!person) + { + LogF("dbServerLoadCharacter: cannot create character of type %s", cc_cast(model)); + LogF(ctx->_result); + } + else + { + if (!person->JSONLoad(document)) + { + LogF("dbServerLoadCharacter: cannot load state of character", cc_cast(model)); + LogF(ctx->_result); + person = NULL; + } + else + { + GWorld->AddVehicle(person); + GetNetworkManager().CreateVehicle(person, VLTVehicle, "", -1); + person->Init(person->FutureVisualState().Transform(), true); + + person->UpdateSubobjects(); + GetNetworkManager().UpdateObject(person); + } + } + } + } + } + + // execute the "handler" + GameDataCode *code = ctx->_code; + if (code && code->IsCompiled() && code->GetCode().Size() > 0) + { + GameState *state = GWorld->GetGameState(); + if (state) + { + GameVarSpace vars(false); + int gshandle = state->BeginContext(&vars); + + state->VarSetLocal("_id", (float)ctx->_playerId, true); + state->VarSetLocal("_uid", ctx->_playerUID, true); + state->VarSetLocal("_name", ctx->_name, true); + state->VarSetLocal("_agent", GameValueExt(person), true); + state->Evaluate(code->GetString(), code->GetCode(), GameState::EvalContext::_default, GWorld->GetMissionNamespace()); // mission namespace + + state->EndContext(gshandle); + } + } + + _loadContexts.Delete(i); + } +} + +void AsyncDBStorage::DBLoad(RString baseURL, int playerId, RString playerUID, RString name, GameDataCode *code) +{ + Ref ctx = new LoadThreadContext(); + ctx->AddRef(); // player can disconnect while Thread still need access to its context + + ctx->_url = baseURL; + + ctx->_prevContext = _lastContext; + ctx->_code = code; + ctx->_playerId = playerId; + // Keep the raw UID for the SQF completion handler; only the HTTP request + // should receive the ?uid= query-string wrapper. + ctx->_playerUID = playerUID; + ctx->_name = name; + +#if USE_MT_LIB_FOR_JOBS + ctx->_thread.Init(CreateMTThreadOnCPU(64 * 1024, DBLoadThreadFunction, ctx.GetRef(), 2, MultiThread::ThreadBase::PriorityNormal, "DBLoadCharacter")); +#else + ctx->_thread.Init(CreateThreadOnCPU(64 * 1024, DBLoadThreadFunction, ctx.GetRef(), 2, THREAD_PRIORITY_NORMAL, "DBLoadCharacter")); +#endif + _loadContexts.Add(ctx); +} + +bool NetworkPlayerInfo::ClientStateBusy() +{ + if ( (clientState>=NCSPlayerAssigned) && (clientState logs; + NetworkId key; +}; +TypeIsMovable(NetworkIdJournal) + +template <> +struct MapClassTraits: public DefMapClassTraits +{ + /// key type + typedef const NetworkId &KeyType; + typedef NetworkIdJournal Type; + /// calculate hash value + static unsigned int CalculateHashValue(KeyType key) + { + return 32768*key.creator.CreatorInt()+key.id; + } + + /// compare keys, implementation needs only ZERO when equals + static int CmpKey(KeyType k1, KeyType k2) + { + return k1!=k2; + } + + /// get a key for given a item + static KeyType GetKey(const Type &item) {return item.key;} +}; + +class ObjectsLifeJournal +{ + static const int MaxObjectsLifeJournalCount = 10000; //max count of stored entries + AutoArray _networkIdList; + int lastIndex; //when journal is full, we overwrite old values in circular manner + MapStringToClass > _objEventMap; + + public: + ObjectsLifeJournal():lastIndex(0) {}; + void Add(NetworkId id, RString eventStory); + const AutoArray* Get(NetworkId id) const; + void Clear() + { + _networkIdList.Clear(); + _objEventMap.Clear(); + lastIndex = 0; + } +}; + +void ObjectsLifeJournal::Add(NetworkId id, RString eventStory) +{ + NetworkIdJournal &objectJournal = _objEventMap.Set(id); + if (_objEventMap.IsNull(objectJournal)) + { + // new item + NetworkIdJournal newJournal; newJournal.key=id; newJournal.logs.Add(eventStory); + _objEventMap.Add(newJournal); + if (_networkIdList.Size() < MaxObjectsLifeJournalCount) + lastIndex = _networkIdList.Add(); + else + { + lastIndex = (lastIndex+1) % MaxObjectsLifeJournalCount; + _objEventMap.Remove(_networkIdList[lastIndex]); + } + _networkIdList[lastIndex] = id; + } + else objectJournal.logs.Add(eventStory); +} + +const AutoArray* ObjectsLifeJournal::Get(NetworkId id) const +{ + const NetworkIdJournal &log = _objEventMap.Get(id); + if (_objEventMap.NotNull(log)) + { + return &log.logs; + } + return NULL; +} + +ObjectsLifeJournal GObjLifeJournal; +#endif + +#define EXTRACT_ID(name) objectId = message->_##name; +#define EXTRACT_UNITS units = message->_units; +#define EXTRACT_CHANNEL channel = message->_channel; + +DEFINE_FAST_ALLOCATOR(DelayedMessageInfo) + +DelayedMessageInfo::DelayedMessageInfo(NetworkServer *server, NetworkMessageType t, NetworkMessage *m) +:msg(m),type(t) +{ + error=1; + invMaxAge = 1.0f/10; + timeReceived = Glob.time; + switch (type) + { + case NMTFireWeapon: + { + NetworkMessageFireWeapon *msg = static_cast(m); + static float visibleErrorCoef = 2.0f; + error = msg->_visible*visibleErrorCoef; + pos = msg->_pos; // TODO: remove _pos from the message, use server->GetObjectPosition + invMaxAge = 1.0f/5; + break; + } + case NMTExplosionDamageEffects: + { + NetworkMessageExplosionDamageEffects *msg = static_cast(m); + invMaxAge = 1.0f/20; + + // undefined camera position + pos = msg->_pos; + // if ammo type is not defined, assume some default importance + error = 1; + if (msg->_type.GetLength() > 0) + { + Ref type = VehicleTypes.New(msg->_type); + AmmoType *ammo = dynamic_cast(type.GetRef()); + if (ammo) + { + // cf. Landscape::ExplosionDamageEffects + static float smallExplosionError = 3.0f; + static float bigExplosionError = 10.0f; + float smallError = smallExplosionError; + float bigError = ammo->explosive*ammo->indirectHitRange*bigExplosionError; + error = Lerp(smallError,bigError,ammo->explosive); + } + } + break; + } + case NMTRemoveProjectileDecals: + case NMTProjectileDecal: + case NMTBowState: + { + //what should happen here? + //NetworkMessageProjectileDecal *msg = static_cast(m); + break; + } + case NMTAskForPlayerAction: + { + auto *msg = static_cast(m); + static float visibleErrorCoefAction = 0.7f; + error = visibleErrorCoefAction; + // check player position + pos = server->GetObjectPosition(msg->_person); + invMaxAge = 1.0f/5; + break; + } + default: + Fail("Unexpected message type in DelayedMessageInfo"); + } +} + +DEFINE_FAST_ALLOCATOR(WaitingMessageInfo) + +/// check if new message is overriding the old one +template +inline bool InitMessageIsOverride(const NetworkMessage *msgOld, NetworkMessage *msgNew, Ref &newInitMsg) +{ + // by default assume it is not + return false; +} + +template <> +inline bool InitMessageIsOverride(const NetworkMessage *msgOld, NetworkMessage *msgNew, Ref &newInitMsg) +{ + // we need to process the messages as they are stored on the server + const NetworkMessageAskForAnimationPhase *mOld = static_cast(msgOld); + const NetworkMessageAskForAnimationPhase *mNew = static_cast(msgNew); + return mOld->_vehicle==mNew->_vehicle && mOld->_animation==mNew->_animation; +}; + +template <> +inline bool InitMessageIsOverride(const NetworkMessage *msgOld, NetworkMessage *msgNew, Ref &newInitMsg) +{ + // we need to process the messages as they are stored on the server + const NetworkMessageCreateRadioChannel *mOld = static_cast(msgOld); + const NetworkMessageCreateRadioChannel *mNew = static_cast(msgNew); + return (mOld->_channel==mNew->_channel); +}; + +template <> +inline bool InitMessageIsOverride(const NetworkMessage *msgOld, NetworkMessage *msgNew, Ref &newInitMsg) +{ + // we need to process the messages as they are stored on the server + const NetworkMessageCreateRadioChannel *mOld = static_cast(msgOld); + const NetworkMessageCreateRadioChannel *mNew = static_cast(msgNew); + return (mOld->_channel==mNew->_channel); +}; + +template <> +inline bool InitMessageIsOverride(const NetworkMessage *msgOld, NetworkMessage *msgNew, Ref &newInitMsg) +{ + // we need to process the messages as they are stored on the server + const NetworkMessageCreateRadioChannel *mOld = static_cast(msgOld); + const NetworkMessageCreateRadioChannel *mNew = static_cast(msgNew); + return (mOld->_channel==mNew->_channel); +}; + +template <> +inline bool InitMessageIsOverride(const NetworkMessage *msgOld, NetworkMessage *msgNew, Ref &newInitMsg) +{ + // we need to process the messages as they are stored on the server + const NetworkMessageCreateRadioChannel *mOld = static_cast(msgOld); + const NetworkMessageCreateRadioChannel *mNew = static_cast(msgNew); + return (mOld->_channel==mNew->_channel); +}; + +template +inline bool InitMessageCanOverride(NetworkMessageType oldType, const NetworkMessage *msgOld, NetworkMessage *msgNew, Ref &newInitMsg) +{ + return false; +}; + +static bool InitMessageIsOverride( + NetworkMessageType oldType, const NetworkMessage *msgOld, NetworkMessageType newType, NetworkMessage *msgNew, Ref &newInitMsg +) +{ + if (oldType==newType) + { + switch (oldType) + { + #define NMT_TYPE_CASE_IS_OVERRIDE(macro, class, name, description, group) \ + case NMT##name: return InitMessageIsOverride(msgOld,msgNew, newInitMsg); + // generate cases for all message types + NETWORK_MESSAGE_TYPES(NMT_TYPE_CASE_IS_OVERRIDE); + } + return false; + } + else + { + switch (newType) + { + #define NMT_TYPE_CASE_CAN_OVERRIDE(macro, class, name, description, group) \ + case NMT##name: return InitMessageCanOverride(oldType,msgOld,msgNew,newInitMsg); + // generate cases for all message types + NETWORK_MESSAGE_TYPES(NMT_TYPE_CASE_CAN_OVERRIDE); + } + } + return false; +} + + +/*! +\patch 5161 Date 5/31/2007 by Ondra +- Optimized: Reduced amount of data transferred when JIP into a complex and long running mission. +*/ + +void NetworkServer::AddInitAndRemoveOverridden( + NetworkMessageType type, NetworkMessage * msg, int **updateI +) +{ + int dst,src; + Ref newInitMsg = msg; + for (src=dst=0; src<_initMessages.Size(); ) + { + if (InitMessageIsOverride(_initMessages[src].type,_initMessages[src].msg,type,msg,newInitMsg)) + { + if (updateI) + { + // if deleting before any of updateI, we need to update the value + for (int **ii=updateI; *ii; ii++) + { + if (src<=**ii) --**ii; + } + } + // skip the message, it is obsolete now + src++; + } + else + { + if (src!=dst) _initMessages[dst] = _initMessages[src]; + src++, dst++; + } + } + // if anything was deleted, remove it now + _initMessages.Resize(dst); + if (newInitMsg) + { + // add the new message + //CheckInitMessages(_initMessages, "before _initMessages.Add()"); + int index = _initMessages.Add(); + _initMessages[index].msg = newInitMsg; + _initMessages[index].type = type; + } + //CheckInitMessages(_initMessages, "after _initMessages.Add()"); +} + +/// check if new message is overriding the old one +template +inline bool InitMessageIsDeleted(const NetworkMessage *msg, NetworkId obj) +{ + // by default assume it is not + return false; +} + +static bool InitMessageIsDeleted(NetworkMessageType type, const NetworkMessage *msg, NetworkId obj) +{ + switch (type) + { + #define NMT_TYPE_CASE_IS_DELETED(macro, class, name, description, group) \ + case NMT##name: return InitMessageIsDeleted(msg,obj);break; + // generate cases for all message types + NETWORK_MESSAGE_TYPES(NMT_TYPE_CASE_IS_DELETED); + } + return false; +} + +void NetworkServer::RemoveInitObjectDeleted(NetworkId obj) +{ + int dst,src; + for (src=dst=0; src<_initMessages.Size(); ) + { + if (InitMessageIsDeleted(_initMessages[src].type,_initMessages[src].msg,obj)) + { + // skip the message, it is obsolete now + src++; + } + else + { + if (src!=dst) _initMessages[dst] = _initMessages[src]; + src++, dst++; + } + } + // if anything was deleted, remove it now + _initMessages.Resize(dst); +} + +void NetworkServer::RptFObjectIdJournal(const NetworkId &id) +{ + if (NetworkDeletedObjectInfo *delInfo = _deletedObjects.get(id)) + { + RptF(" - object was deleted, owner %d, time %.3f", delInfo->owner, delInfo->time.toFloat()); + } +#if DIAG_MP_OBJECT_LIFE + if (const AutoArray *logLines = GObjLifeJournal.Get(id)) + { + for (int i=0; iSize(); i++) + { + RptF(" -> %s", cc_cast((*logLines)[i])); + } + } +#endif +} + +void NetworkServer::RptFObjectNotFound(const NetworkId &id, const char *msg, int from) +{ + if (_serverState==NSSLoadingGame || _serverState==NSSPlaying) + { +// RString fromTxt = from>=0 ? Format(" from=%d",from) : RString(); +// RptF("Server: Object %d:%" OID_FORMAT" not found (message %s)%s", id.creator.CreatorInt(), id.id, msg, cc_cast(fromTxt)); + RptFObjectIdJournal(id); +#if DIAG_MP_OBJECT_LIFE + DiagObjectInfoAskMessage ask; + ask._creator=id.creator; + ask._id=id.id; + if (from!=-1) + SendMsg(from, &ask, NMFGuaranteed); + if (from!=BOT_CLIENT) + SendMsg(BOT_CLIENT, &ask, NMFGuaranteed); +#endif + } +} + +void NetworkServer::RptFObjectNotFound(const NetworkId &id, NetworkMessageType type, int from, const char *context) +{ +#if _ENABLE_CHEATS + extern const char *NetworkMessageTypeNames[]; + const char *typeName = NetworkMessageTypeNames[type]; + const char *msg = typeName; +#else + BString<128> typeName; + sprintf(typeName,"Type_%d",type); + const char *msg = typeName; +#endif + BString<256> temp; + if (context) + { + strcpy(temp,typeName); + strcat(temp,context); + msg = temp; + } + RptFObjectNotFound(id,msg,from); +} + +bool CollectedHashes::UpdatePlayerBankCount(int bankCount) +{ + if (banksCount==-1) + { // not set yet + banksCount = bankCount; + bankInfoTimeout = 0; //reset + } + else if (banksCount != bankCount) + { + // player sent different bankCount to her prior info => cheating? + return true; + } + int sigCount = SignaturesCount(); + if (sigCount && sigCount!=bankCount) + { + // player sent different bankCount than was checked during initial signature test => cheating? + return true; + } + return false; +} + +void NetworkServer::ReportWrongSignatures(int from, RString filename, const NetworkPlayerInfo *info, RString report) +{ +#if _ENABLE_DEDICATED_SERVER + LogF("Hacked Signatures?"); + RString reportBase = Format(LocalizeString(IDS_SIGNATURE_WRONG), cc_cast(info->name), cc_cast(filename)); +#if DEBUG_SIGNATURES + if (report.IsEmpty()) + { + NetLog(reportBase); + } + else + { + RString reportMsg = Format("%s (%s)", cc_cast(reportBase), cc_cast(report)); //add additional report info + NetLog(reportMsg); + } +#endif + ServerMessage(reportBase); // report only basic info, diag details are in NetLog +#endif + OnHackedData(HTHackedData, from, filename); +}; + +#if _ENABLE_DEDICATED_SERVER +void NetworkServer::DoReassignDirect() +{ + // send to clients + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.clientState < NCSConnected) continue; + SendMissionInfo(info.dpid, true); + } + + SetServerState(NSSAssigningPlayers); + + _restart = false; + _reassign = false; +} + +void NetworkServer::DoReassign() +{ + _restart = true; + _reassign = true; + if (_serverState != NSSPlaying) + { + GNetworkManager.DestroyAllObjects(); + DoReassignDirect(); + } +} + +void NetworkServer::DoMissions(bool admin) +{ + _mission = "?"; + _restart = true; + if (_serverState != NSSSelectingMission && _serverState != NSSPlaying) + { + GNetworkManager.DestroyAllObjects(); + SetServerState(NSSSelectingMission); + } + NetworkCommandMessage answer; + answer._type = NCMTVoteMission; + NetworkCommandMessage answer2; + answer2._type = NCMTVoteMissionExt; + AddMissionList(answer,answer2); + if (admin) + { + SendMsg(_gameMaster, &answer, NMFGuaranteed); + SendMsg(_gameMaster, &answer2, NMFGuaranteed); + } + else + { + for (int i=0; i<_identities.Size(); i++) + { + SendMsg(_identities[i].dpnid, &answer, NMFGuaranteed); + SendMsg(_identities[i].dpnid, &answer2, NMFGuaranteed); + } + } +} +#endif + +void NetworkServer::SpawnForPlayer(int dpnid, GameDataCode *code, const GameValue &args) +{ + if (dpnid == BOT_CLIENT) + { + ScriptVM *script = new ScriptVM(ScriptVMDirect, *code, args, GWorld->GetGameState()->GetGlobalVariables()); + GWorld->AddScriptVM(script, false); + } + else + { + SpawnForPlayerMessage msg; + msg._code = code->GetString(); + + if (!args.GetNil()) + { + QOStrStream out; + if (WriteValue(args, out)) + { + int size = out.pcount(); + msg._value.Resize(size); + memcpy(msg._value.Data(), out.str(), size); + } + } + + SendMsg(dpnid, &msg, NMFGuaranteed); + } +} + +static int BestAddress(int &portRet, const NetworkPlayerInfo *info, int NetworkPlayerInfo::*addr, int NetworkPlayerInfo::*port) +{ + if (info->*addr!=0 && info->*port!=0) + { + portRet = info->*port; + return info->*addr; + } + else if (info->_publicAddr && info->_publicPort) + { + portRet = info->_publicPort; + return info->_publicAddr; + } + else + { + portRet = info->_privatePort; + return info->_privateAddr; + } +} + +/*! +\patch_internal 1.01 Date 6/22/2001 by Ondra. +- Added: ID==0 refusal +\patch 1.02 Date 7/12/2001 by Jirka: + - Fixed: error in assignment + - allow player assignment only in appropriate state + - ignore messages arrived after state has changed +\patch_internal 1.03 Date 7/13/2001 by Jirka. +- Fixed: Allow \ in url of squad (for debugging purposes) +\patch_internal 1.14 Date 8/9/2001 by Ondra. +- Added: ID>110000000 || ID>10000000 && ID<100000000 refusal +\patch 1.21 Date 8/24/2001 by Jirka: +- Fixed: error in assignment +\patch 1.25 Date 9/29/2001 by Ondra: +- New: Ping to all clients displayed on server. +\patch 1.27 Date 10/15/2001 by Jirka +- Fixed: When CAPS LOCK was pressed, Voice Over Net was not disabled (bug since 1.26) +\patch 1.30 Date 11/01/2001 by Jirka +- Fixed: Voting is echoed to clients +\patch 1.33 Date 11/29/2001 by Jirka +- Improved: Global ban list reloads before player is checked +\patch_internal 1.43 Date 1/31/2002 by Jirka +- Fixed: Server does not send create and update messages to nonplaying clients +\patch 1.82 Date 8/19/2002 by Ondra +- Fixed: Voting is echoed even to the player voting. +\patch 1.86 Date 10/16/2002 by Jirka +- Fixed: On dedicated server with mission rotating, after #login and #missions no missions appears +\patch 5136 Date 2/28/2007 by Jirka +- Fixed: MP - command #exec allowed only for logged (not voted) admin +\patch 5137 Date 3/5/2007 by Jirka +- Fixed: Dedicated server - after #reassign two players could control a single avatar +\patch 5154 Date 5/3/2007 by Jirka +- Fixed: Dedicated server - ban.txt was locked for edit during the game +\patch 5164 Date 10/3/2007 by Jirka +- Fixed: Handling of duplicate CD key improved +\patch 5175 Date 10/16/2007 by Jirka +- Added: After 3 wrong attempts to log in as an admin further attempts are ignored for some time +*/ + +void NetworkServer::OnMessage(int from, NetworkMessage *msg, NetworkMessageType type) +{ +#if _ENABLE_PERFLOG + PROFILE_SCOPE_EX(OnMsg,*); + if (PROFILE_SCOPE_NAME(OnMsg).IsActive()) + { + PROFILE_SCOPE_NAME(OnMsg).AddMoreInfo(Format("type=%d", type)); + } +#endif + + NetworkMessageFormatBase *format = GetFormat(/*from, */type); + if (!format) + { + RptF("Server: Bad message %d(%s) format", (int)type, cc_cast(GetMsgTypeName(type))); + return; + } + NetworkMessageContext ctx(msg, this, from, MSG_RECEIVE); + + #if _ENABLE_CHEATS + int level = GetDiagLevel(type,from!=_parent->GetClient()->GetPlayer()); + if (level >= 2) + { + DiagLogF("Server: received message %s from %d", cc_cast(GetMsgTypeName(type)), from); + ctx.LogMessage(format, level, "\t"); + } + #endif + + NetworkId objectId; + AutoArray units; + int channel = -1; + + bool initMessageAlreadyAdded = false; + switch (type) + { +/* + case NMTMsgFormat: + { + NetworkPlayerInfo *info = GetPlayerInfo(from); + if (!info) info = OnPlayerCreate(from, ""); + int index = msg->id.id - NMTFirstVariant; + if (index >= info->formats.Size()) + info->formats.Resize(index + 1); + info->formats[index].TransferMsg(ctx); + } + break; +*/ + case NMTSelectPlayer: + { +LogF("Server: received SelectPlayer"); + SelectPlayerMessage pl; + pl.TransferMsg(ctx); + Assert(pl._player != AI_PLAYER); + NetworkId person(pl._creator, pl._id); + + NetworkPlayerInfo *info = GetPlayerInfo(pl._player); + if (info) + { + info->person = person; + info->cameraPosition = pl._position; + // HOTFIX: msg->time cannot be used as NMTSelectPlayer is sent by BOT_CLIENT which time can be different + // using Time(0) forces first update from client to set it properly according to clients time + info->cameraPositionTime = Time(0); +#if _VBS3 + info->cameraFov = 0.75; + info->cameraDirection = VForward; +#endif + } + + // first select player, then change owner + // (when changeOwner arrive to client, player must be already known + // - for respawn parameters initialization) + if (from != pl._player) + { +LogF(" sending to %x", pl._player); + SendMsg(pl._player, msg, type, NMFGuaranteed, NULL); + } + + NetworkObjectInfo *oInfo = GetObjectInfo(person); + if (oInfo) + { + ChangeOwner(person, oInfo->owner, pl._player); + } + } + break; + case NMTAskMissionFile: + { + AskMissionFileMessage ask; + ask.TransferMsg(ctx); + if (ask._valid) + { + NetworkPlayerInfo *info = GetPlayerInfo(from); + if (info) info->missionFileValid = true; + } + } + break; + case NMTClientState: + { + ClientStateMessage cs; + cs.TransferMsg(ctx); + OnClientStateChanged(from, (NetworkClientState)cs._clientState); + } + break; + case NMTPlayerClientState: + { + PlayerClientStateMessage pcs; + pcs.TransferMsg(ctx); + SetClientState(pcs._dpnid, (NetworkClientState)pcs._clientState); + } + break; + case NMTLogin: + { + //{ CHANGED + PlayerIdentity identity; + identity.TransferMsg(ctx); + +/* + int index = _identities.Add(); + PlayerIdentity &identity = _identities[index]; + identity.TransferMsg(ctx); +*/ + //} + + // check if not in ban lists + if (from != BOT_CLIENT) + { + // reload ban list + LoadBanList("ban.txt", _banListGlobal); + GFileServerFunctions->FlushReadHandle("ban.txt"); + + bool ban = false; + for (int i=0; i<_banListGlobal.Size(); i++) + if (IsUserIdMatch(identity.id,_banListGlobal[i])) {ban = true; break;} + if (!ban) for (int i=0; i<_banListLocal.Size(); i++) + if (IsUserIdMatch(identity.id,_banListLocal[i])) {ban = true; break;} + if (ban) + { + //{ CHANGED + // _identities.Delete(index); + //} + KickOff(from,KORBan); + break; + } + } + + _squadChecks.Add(new CheckSquadObject(identity, _proxy, this)); + +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.dpid != from) continue; + info._steamValidate.Start(identity, this); + break; + } +#endif + + //} + + // send server time to player just connected + ServerTimeMessage stmsg; + _serverTime = ::GetTickCount()-_serverTimeInitTickCount; // update _serverTime + stmsg._time = _serverTime; + stmsg._endTime = _serverTimeOfEstimatedEnd; + SendMsg(from, &stmsg, NMFGuaranteed | NMFHighPriority); + +#if _ENABLE_DEDICATED_SERVER + // client need to know whether there is admin on server + ServerAdminMessage samsg; + samsg._admin = _admin; + samsg._gameMaster = _gameMaster; + SendMsg(from, &samsg, NMFGuaranteed); +#endif + } + break; + case NMTCustomFilesWanted: + { + CustomFilesWantedMessage filesWantedMsg; + filesWantedMsg.TransferMsg(ctx); + for (int i=0; i<_squadChecks.Size(); i++) + { + if (_squadChecks[i]->IsPlayer(filesWantedMsg._player)) + { + _squadChecks[i]->SetCustomFilesWanted(from, filesWantedMsg._filesWanted); + break; + } + } + } + break; + case NMTUpdateClientInput: + OnMessageClientInput(from, type, ctx); + break; + case NMTAskForAnimationPhase: + { + PREPARE_TRANSFER(AskForAnimationPhase) + EXTRACT_ID(vehicle) + if (!objectId.IsNull()) + { + if (objectId.creator == CreatorId(STATIC_OBJECT)) + { + // save message for lately connecting players + AddInitAndRemoveOverridden(type,msg); + + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.dpid == from) continue; + if (info.clientState != NCSPlaying) continue; + SendMsg(info.dpid, msg, type, NMFNone, NULL); + } + } + else + { + SendMsg(BOT_CLIENT, msg, type, NMFGuaranteed, NULL); + } + } + } + break; + case NMTAskForPilotLight: + { + PREPARE_TRANSFER(AskForPilotLight) + EXTRACT_ID(vehicle) + } + goto LabelAskWithVehicle; + case NMTAskForVehicleDoorState: + { + PREPARE_TRANSFER(AskForVehicleDoorState) + EXTRACT_ID(vehicle) + } + goto LabelAskWithVehicle; + case NMTAskForSetMagazineAmmo: + { + PREPARE_TRANSFER(AskForSetMagazineAmmo) + EXTRACT_ID(magazine) + } + goto LabelAskWithVehicle; + case NMTAskForAmmo: + { + PREPARE_TRANSFER(AskForAmmo) + EXTRACT_ID(turret) + if (objectId.IsNull()) + { + EXTRACT_ID(vehicle) + } + } + goto LabelAskWithVehicle; + case NMTAskForMoveVector: + { + if (from!=BOT_CLIENT) break; // AskForMove is honored from the bot-client only + PREPARE_TRANSFER(AskForMoveVector) + EXTRACT_ID(vehicle) + } + goto LabelAskWithVehicle; + case NMTAskForMoveMatrix: + { + if (from!=BOT_CLIENT) break; // AskForMove is honored from the bot-client only + PREPARE_TRANSFER(AskForMoveMatrix) + EXTRACT_ID(vehicle) +#if _ENABLE_PHYSICS + //ConsoleF("askformove vehicle %x", _parent->GetObject(message->_vehicle)); +#endif + } + goto LabelAskWithVehicle; +#if _VBS3 + case NMTAskCommanderOverride: + { + PREPARE_TRANSFER(AskCommanderOverride) + EXTRACT_ID(turret) + } + + goto LabelAskWithVehicle; +#endif + LabelAskWithVehicle: + { + NetworkObjectInfo *info = GetObjectInfo(objectId); + if (info) + { + if (info->pendingOwner != NO_CLIENT) + { + WaitingMessageInfo *waitingMsg = new WaitingMessageInfo(type,msg); + info->waitingMessages.Add(waitingMsg); + } + else + { + SendMsg(info->owner, msg, type, NMFGuaranteed, NULL); + } + } + else + { + RptFObjectNotFound(objectId, type,from); + } + } + break; + case NMTForceDeleteObject: + { + // remove from object lists + PREPARE_TRANSFER(ForceDeleteObject) + NetworkId id; + if (TRANSF_GET_ID_BASE(object, id) != TMOK) break; + PerformObjectDestroy(id); + + // send to other clients + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.dpid == from) continue; + if (info.clientState < NCSMissionReceived) continue; + SendMsg(info.dpid, msg, type, NMFGuaranteed, NULL); + } + } + break; + case NMTAskForRotateInventoryItem: + { + AskForRotateInventoryItemMessage ask; + TMError err = ask.TransferMsg(ctx); + if ((err == TMOK || err == TMNotFound) && ask._person && ask._item && + ask._person->GetRemotePlayer() == from && ask._person->FindItem(ask._item)) + SendMsg(BOT_CLIENT, msg, type, NMFGuaranteed); + } + break; + case NMTAskForSetItemShortcut: + case NMTAskForMoveItem: + case NMTAskForTakeItemToHands: + case NMTAskForSwapItems: + SendMsg(BOT_CLIENT, msg, type, NMFGuaranteed); + break; + case NMTAskForRotateInventoryItem: + { + AskForRotateInventoryItemMessage ask; + TMError err = ask.TransferMsg(ctx); + if ((err == TMOK || err == TMNotFound) && ask._person && ask._item && + ask._person->GetRemotePlayer() == from && ask._person->FindItem(ask._item)) + SendMsg(BOT_CLIENT, msg, type, NMFGuaranteed); + } + break; + case NMTAskInventoryMenu: + { + PREPARE_TRANSFER(AskInventoryMenu) + Person *person = dyn_cast(_parent->GetObject(message->_unit)); + InventoryItem *item1 = dyn_cast(_parent->GetObject(message->_item1)); + if (person && person->Brain() && item1) + { + Ref reply = new NetworkMessageInventoryMenu(); + reply->_unit = message->_unit; + reply->_item1 = message->_item1; + reply->_item2 = message->_item2; + reply->_swap = false; + + if (message->_item2.IsNull()) + { + // single item + + // actions + item1->GetActions( + [&reply](const UIAction &action) -> void + { + if (action.action.NotNull()) + { + NetworkMessageInventoryMenuAction *submsg = new NetworkMessageInventoryMenuAction(); + submsg->_actionType = action.action->GetType(); + submsg->_actionTarget = action.action->GetTarget() ? + action.action->GetTarget()->GetNetworkId() : NetworkId::Null(); + + QOStrStream out; + action.action->SaveParams(out); + int size = out.pcount(); + submsg->_actionParams.Resize(size); + memcpy(submsg->_actionParams.Data(), out.str(), size); + + reply->_actions.Add(submsg); + } + }, + person->Brain()); + } + else + { + // two items + InventoryItem *item2 = dyn_cast(_parent->GetObject(message->_item2)); + if (!item2) break; // recipes on two items are expected + + // recipes + Recipes.Collect(person, item1, item2, + [&reply](const Recipe *recipe) -> bool + { + reply->_recipes.Add(recipe->_name); + return false; // continue + }); + + if (item2->CanAddAttachment(item1)) + { + NetworkMessageInventoryMenuAttachment *submsg = new NetworkMessageInventoryMenuAttachment(); + submsg->_attachment = true; + submsg->_item1 = item1->GetNetworkId(); + submsg->_item2 = item2->GetNetworkId(); + reply->_attachments.Add(submsg); + } + else if (item2->CanAddOwnedItem(item1)) + { + NetworkMessageInventoryMenuAttachment *submsg = new NetworkMessageInventoryMenuAttachment(); + submsg->_attachment = false; + submsg->_item1 = item1->GetNetworkId(); + submsg->_item2 = item2->GetNetworkId(); + reply->_attachments.Add(submsg); + } + + bool CanSwapItems(InventoryItem *item1, InventoryItem *item2); + reply->_swap = CanSwapItems(item1, item2); + } + + SendMsg(from, reply, NMTInventoryMenu, NMFGuaranteed); + } + } + break; + case NMTAskForThrowItem: +#if _ENABLE_PHYSICS + { + // change ownership of item to gain control over position + PREPARE_TRANSFER(AskForThrowItem) + + if (!message->_item.IsNull() && !message->_person.IsNull()) + { + NetworkObjectInfo *info = GetObjectInfo(message->_item); + + //nastavi se sice primo v klientovi, ale tam nevidim na info. takhle zabezpecim, ze mi to nikdo neprepise + if (info && info->owner != BOT_CLIENT) + ChangeOwner(message->_item, info->owner, BOT_CLIENT); + //SendMsg(BOT_CLIENT, message, type, NMFGuaranteed); + + if (info) + { + if (info->pendingOwner != NO_CLIENT) + { + WaitingMessageInfo *waitingMsg = new WaitingMessageInfo(type,msg); + info->waitingMessages.Add(waitingMsg); + } + else + { + SendMsg(info->owner, msg, type, NMFGuaranteed, NULL); + } + } + } + } +#endif + break; + case NMTAskForDropItem: + { + // change ownership of item to gain control over position + PREPARE_TRANSFER(AskForDropItem) + if (!message->_item.IsNull()) + { + const NetworkObjectInfo *info = GetObjectInfo(message->_item); + if (info && info->owner != BOT_CLIENT) + ChangeOwner(message->_item, info->owner, BOT_CLIENT); + SendMsg(BOT_CLIENT, message, type, NMFGuaranteed); + } + } + break; + case NMTProcessAction: + { + PREPARE_TRANSFER(ProcessAction) + if (!message->_unit.IsNull()) + { + Person *person = dyn_cast(_parent->GetObject(message->_unit)); + AIBrain *unit = person ? person->Brain() : nullptr; + if (unit && unit->GetVehicle()) + { + Ref action = CreateAction((UIActionType)message->_actionType); + if (action) + { + Object *target = nullptr; + const NetworkId &targetId = message->_actionTarget; + if (!targetId.IsNull()) + target = dyn_cast(_parent->GetObject(targetId)); + + // Static house/door objects are not always present in the + // server's network-object table. For a UserType action, resolve + // the player's authoritative current cursor target as fallback. + // The action's saved parameters still carry the chosen door id. + if (!target && message->_actionType == ATUserType) + target = GetPlayerTarget(from); + + if (message->_actionType == ATUserType) + RptF("ProcessAction UserType: player=%d targetId=%d:%" OID_FORMAT " resolved=%s fallback=%s", + from, targetId.creator.CreatorInt(), targetId.id, + target ? (const char *)target->GetDebugName() : "", + targetId.IsNull() ? "cursor" : "none"); + action->SetTarget(target); + + QIStrStream in(message->_actionParams.Data(), message->_actionParams.Size()); + action->LoadParams(in); + + unit->GetVehicle()->StartActionProcessing(action, unit); + } + } + } + } + break; + case NMTProcessRecipe: + { + PREPARE_TRANSFER(ProcessRecipe) + if (!message->_person.IsNull()) + { + Person *person = dyn_cast(_parent->GetObject(message->_person)); + if (person) + { + const Recipe *recipe = Recipes.Find(message->_recipe); + if (recipe) + { + InventoryItem *item1 = dyn_cast(_parent->GetObject(message->_item1)); + InventoryItem *item2 = dyn_cast(_parent->GetObject(message->_item2)); + recipe->Process(person, item1, item2); + } + } + } + } + break; + case NMTMarkerDelete: + // send to all except from (state Briefing expected) + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.dpid == from) continue; + if (info.clientState < NCSGameLoaded) continue; + SendMsg(info.dpid, msg, type, NMFGuaranteed, NULL); + } + if(type == NMTMarkerDelete) + { + PREPARE_TRANSFER(MarkerDelete) + RemoveJIPMarkerInfo(message->_name); + } + break; +#if _VBS2 //Convoy trainer + #if _EXT_CTRL + case NMTAARAskUpdate:// Here we service the ask request for AAR + { + AARAskUpdateMessage act; + act.TransferMsg(ctx); + + switch(act._type) + { + case StartRecord: + GAAR.Record(); + break; + case StopRecord: + GAAR.RecordStop(); + break; + case SaveFile: + GAAR.RecordSave(act._stringOne); + break; + case AddBookMK: + GAAR.AddBookMark(act._floatType,act._stringOne,act._stringTwo); + break; + case RemBookMK: + GAAR.RemoveBookMark(act._stringOne); + break; + case SaveState: + // Client should never ask to set save state + Assert(false); + break; + default: + Assert(false);// message type not handeled, development bug + } + } + break; + #endif + case NMTAddMPReport: + case NMTAARDoUpdate: // Here we update all clients with their new state. + case NMTPauseSimulation: +#endif + case NMTApplyWeather:// request will be sent to the bot client too + goto ProcessInitMessage; +#if _ENABLE_ATTACHED_OBJECTS + case NMTAttachObject: + case NMTDetachObject: + if (from!=BOT_CLIENT) break; +#endif + ProcessInitMessage: +#if _VBS2 || _ENABLE_ATTACHED_OBJECTS + AddInitAndRemoveOverridden(type, msg); + initMessageAlreadyAdded = true; +#endif + // save message for lately connecting players + if (!initMessageAlreadyAdded) + { + //CheckInitMessages(_initMessages, "before _initMessages.Add()"); + int index = _initMessages.Add(); + _initMessages[index].msg = msg; + _initMessages[index].type = type; + //CheckInitMessages(_initMessages, "after _initMessages.Add()"); + } + // no break here - continue + case NMTPlaySound: + case NMTSoundState: + case NMTVehicleDestroyed: + case NMTVehicleDamaged: +sendToAllPlayers: + // send to all except from (state Play expected) + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.dpid == from) continue; + if (info.clientState != NCSPlaying) continue; + SendMsg(info.dpid, msg, type, NMFGuaranteed, NULL); + } + break; + case NMTSubscribeRadios: + { + NetworkMessageSubscribeRadios *rm = dynamic_cast(msg); + if (rm) + { + for (int i=0; i<_players.Size(); i++) + { + if (_players[i]->dpid==rm->_player) + { + _radioSubscribers.AddUnique(rm->_player, rm->_frequences); + goto sendToAllPlayers; + } + } + } + } + break; + case NMTAskForPlayerAction: + // check if the person in question is the player + { + auto *msgAction = static_cast(msg); + NetworkId playerPerson = GetPlayerPerson(from); + if (playerPerson!=msgAction->_person) + { + RptF("AskForPlayerAction ignored for player %d, person different %d:%" OID_FORMAT "!=%d:%" OID_FORMAT,from, playerPerson.creator.CreatorInt(),playerPerson.id,msgAction->_person.creator.CreatorInt(),msgAction->_person.id); + } + + } + goto DelayedMessageProcessing; + case NMTFireWeapon: + case NMTExplosionDamageEffects: + case NMTBowState: + DelayedMessageProcessing: + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.dpid == from) continue; + if (info.dpid==BOT_CLIENT) + { + SendMsg(BOT_CLIENT, msg, type, NMFGuaranteed, nullptr); + continue; + } + if (info.clientState != NCSPlaying) continue; + { + DelayedMessageInfo *delayed = new DelayedMessageInfo(this,type,msg); + info._delayedMessages.Add(delayed); + } + } + break; + case NMTProjectileDecal: + case NMTRemoveProjectileDecals: + if (from != BOT_CLIENT) + { + SendMsg(BOT_CLIENT, msg, type, NMFGuaranteed, nullptr); + } + else + { + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.dpid == BOT_CLIENT || info.clientState != NCSPlaying) + { + continue; + } + + DelayedMessageInfo *delayed = new DelayedMessageInfo(this,type,msg); + info._delayedMessages.Add(delayed); + } + } + break; + case NMTExplosionDamage: + SendMsg(BOT_CLIENT, msg, type, NMFGuaranteed, nullptr); + break; + case NMTSynchronizeVariable: + if (from!=BOT_CLIENT) break; + goto SendToAll; + // continue + case NMTTransferFile: +#if _ENABLE_UNSIGNED_MISSIONS + case NMTTransferMissionFile: +#endif + case NMTMissionStats: + SendToAll: + // send to all except from (state Mission Received expected) + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.dpid == from) continue; + if (info.clientState < NCSMissionReceived) continue; + SendMsg(info.dpid, msg, type, NMFGuaranteed, NULL); + } +//CheckInitMessages(_initMessages, "after NetworkComponent::SendMsg"); + break; + case NMTSendAUMsg: + { + SendAUMsgMessage auMsg; + auMsg.TransferMsg(ctx); + GameValue value; + if (!ReadValue(value, auMsg._value.Data(), auMsg._value.Size(), _parent)) break; + const GameArrayType &array=value; + if ( array.Size() != 2 ) break; + if (array[0].GetType()==GameScalar) + { + int count = array[0]; + // send to some count of players except from (state Mission Received expected) + for (int i=0; (i<_players.Size()) && (count>0); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.dpid == from) continue; + count--; + SendMsg(info.dpid, msg, type, NMFGuaranteed, NULL); + } + } + else if (array[0].GetType()==GameArray) + { + const GameArrayType &sendTo = array[0]; + // send to all players listed in array + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.dpid == from) continue; + for (int j=0; jdestroy) + { + alreadyKicked = true; + } + + RString name; + for (int i=0; i<_players.Size(); i++) + { + if (_players[i]->dpid == from) + { + name = _players[i]->name; + if (_players[i]->kickedOff) alreadyKicked = true; + break; + } + } + + if (alreadyKicked) + { + LogF + ( + "Transfer file %s request ignored, sender is being kicked off", + (const char *)transfer._path + ); + break; + } + // check if file transferred is within allowed range + // if not, kick off sender + if (transfer._totSize>MaxCustomFileSize) + { + // check name of player (from file name) + RString reason = Format + ( + LocalizeString(IDS_DS_PLAYER_KICKED_BIG_CUSTOM_FILE), + (const char *)name,(const char *)GetRelUploadPath(transfer._path,name), + transfer._totSize,MaxCustomFileSize + ); + ServerMessage(reason); + KickOff(from,KORKick,reason); + break; + } + + if (!CheckValidUpload(transfer._path,name)) + { + RString reason = Format + ( + LocalizeString(IDS_DS_PLAYER_KICKED_INVALID_CUSTOM_FILE), + (const char *)name,(const char *)transfer._path + ); + ServerMessage(reason); + KickOff(from,KORKick, reason); + break; + } + + ReceiveFileSegment(transfer); + } + break; + case NMTDeleteObject: + if (_serverState < NSSLoadingGame) break; // updates from the last session + { + PREPARE_TRANSFER(DeleteObject) + + NetworkId id; + if (TRANSF_BASE(creator, id.creator) != TMOK) break; + if (TRANSF_BASE(id, id.id) != TMOK) break; + + // object deletion should be requested by the bot-client only + if (from!=BOT_CLIENT) + { +#if _ENABLE_PHYSICS1 + { + InventoryItem *item = dyn_cast(_parent->GetObject(id)); + if(item && item->GetPhysics()) + ConsoleF("delete dyn phys for %x user pointer %x", item, ((enf::BulletController*)item->GetPhysics())->GetCollisionObject()->getUserPointer()); + } +#endif + RptF("Object %d:%",OID_FORMAT," delete requested from client %d",id.creator.CreatorInt(),id.id,from); + break; + } + +#if DIAG_MP_OBJECT_LIFE + GObjLifeJournal.Add(id, Format("(%.3f) Delete: from=%d",Glob.time.toFloat(), from)); +#endif + OnObjectDestroy(id, from); + // RptF("Server: Object %d:%" OID_FORMAT" deleted", id.creator.CreatorInt(), id.id); + } + break; + case NMTDeletedObject: + { + if (_serverState < NSSLoadingGame) break; // updates from the last session + { + PREPARE_TRANSFER(DeletedObject) + + NetworkId id; + if (TRANSF_BASE(creator, id.creator) != TMOK) break; + if (TRANSF_BASE(id, id.id) != TMOK) break; + + _deletedObjects.removeKey(id); +#if DIAG_MP_OBJECT_LIFE + GObjLifeJournal.Add(id, Format("(%.3f) Deleted: from=%d",Glob.time.toFloat(), from)); +#endif + } + } + break; + case NMTCreateObject: + case NMTCreateVehicle: + case NMTCreateVehicleAI: + case NMTCreateVehicleBrain: + case NMTCreateShot: + case NMTCreateCrater: + case NMTCreateCraterOnVehicle: + case NMTCreateSoundOnVehicle: + case NMTCreateObjectDestructed: + case NMTCreateDynSoundSource: + case NMTCreateHelicopter: +#if _HELISIM_ROTORLIB + case NMTCreateHelicopterRTD: +#endif + case NMTCreateSeagull: + case NMTCreateTurret: + case NMTCreateDestructionEffects: + case NMTCreateClientCameraPosition: + if (_serverState < NSSLoadingGame) break; // updates from the last session + + { + PREPARE_TRANSFER(NetworkObject) + + NetworkId id; + if (TRANSF_BASE(objectCreator, id.creator) != TMOK) break; + if (TRANSF_BASE(objectId, id.id) != TMOK) break; + + if (from!=BOT_CLIENT && type!=NMTCreateClientCameraPosition) + { + RptF("Object %d:%",OID_FORMAT," create requested from client %d",id.creator.CreatorInt(),id.id,from); + break; // create message may come only from a bot-client, with the exception of the CameraPosition object + } + + // copy message (avoid changes on message in message queue) + Ref copy = ::CreateNetworkMessage(type); + CopyMsg(copy, msg, format); + NetworkObjectInfo *oInfo = OnObjectCreate(id, from, copy, type); + if (!oInfo) break; +// RptF("Server: Object %d:%" OID_FORMAT" created, type %s", id.creator.CreatorInt(), id.id, cc_cast(GetMsgTypeName(type))); + + auto sendToClient = [this,id,oInfo,from] (int i) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.dpid == from) return; + if (info.clientState < NCSMissionReceived) return; + PlayerIndex index = GetPlayerIndex(info.dpid); + DoAssert(index>=0); + if (index<0) return; + + if (info.person!=id) + { + NetworkPlayerObjectInfo *poInfo = oInfo->GetPlayerObjectInfo(index,info.dpid); + if (!poInfo->updating) + { + SendCreateMessage(info.dpid, *oInfo, poInfo); + poInfo->updating = true; + info.markAsUpdating(poInfo); + } + } + }; + + // send to bot-client first + for (int i=0; i<_players.Size(); i++) // TODO: avoid for loop, bot client is always first + { + if (_players[i]->dpid==BOT_CLIENT) {sendToClient(i);break;} + } + oInfo->object = _parent->GetClient()->GetObject(id); + DoAssert(oInfo->object); + + Entity *ent = dyn_cast(oInfo->object); + if (ent) + { + OnHierParentChange(ent); + } + + float maxDist = oInfo->BestPosition()._updateDistance; + for (int i=0; i<_players.Size(); i++) + { + int dpid = _players[i]->dpid; + if (dpid==BOT_CLIENT) continue; + if (DebugMeBoy(oInfo->id)) + { + LogF("*** DebugMeBoy: {%d:%" OID_FORMAT"} Create message for %d dist %g", oInfo->id.creator.CreatorInt(), oInfo->id.id, dpid, maxDist); + } + if (maxDist>=FLT_MAX) sendToClient(i); + } + // SendMsg created the object on the bot-client if necessary, we can get it now + + } + break; + case NMTUpdateDamageVehicleAI: + case NMTUpdateDamageVehicle: + case NMTUpdateDamageObject: + ctx.SetClass(NMCUpdateDamage); + if (BattlEyeEnabled()) + { + PREPARE_TRANSFER(UpdateDamageObject) + + NetworkId id; + float damage; + if (TRANSF_BASE(objectCreator, id.creator) != TMOK) break; + if (TRANSF_BASE(objectId, id.id) != TMOK) break; + if (TRANSF_BASE(dammage, damage) != TMOK) break; + #if _USE_BATTL_EYE_SERVER + if (_beIntegration.UpdateDamageCallback(from,NetworkIdToNetIdFriendly(id),damage)) break; + #endif + } + goto Update; + case NMTUpdatePositionVehicle: + case NMTUpdatePositionMan: + case NMTUpdatePositionTank: + case NMTUpdatePositionCar: + case NMTUpdatePositionAirplane: + case NMTUpdatePositionHelicopter: +#if _HELISIM_ROTORLIB + case NMTUpdatePositionHelicopterRTD: +#endif + case NMTUpdatePositionShip: + case NMTUpdatePositionDoor: + case NMTUpdatePositionSeagull: + case NMTUpdatePositionMotorcycle: + case NMTUpdatePositionMagazine: +#if _USE_BATTL_EYE_SERVER + if (BattlEyeEnabled()) + { + PREPARE_TRANSFER(UpdatePositionVehicle) + + NetworkId id; + Vector3 position; + Matrix3 o; + if (TRANSF_BASE(objectCreator, id.creator) != TMOK) break; + if (TRANSF_BASE(objectId, id.id) != TMOK) break; + if (TRANSF_BASE(position, position) != TMOK) break; + if (TRANSF_BASE(orientation, o) != TMOK) break; + if (_beIntegration.UpdatePositionCallback(from,NetworkIdToNetIdFriendly(id),position.X(),position.Y(),position.Z(), + o.Direction().X(),o.Direction().Y(),o.Direction().Z(), + o.DirectionUp().X(),o.DirectionUp().Y(),o.DirectionUp().Z(), + o.DirectionAside().X(),o.DirectionAside().Y(),o.DirectionAside().Z()) + ) break; + } +#endif + ctx.SetClass(NMCUpdatePosition); + goto Update; + case NMTUpdatePositionTurret: + ctx.SetClass(NMCUpdatePosition); + goto Update; + case NMTUpdateTransport: + case NMTUpdateTankOrCar: + case NMTUpdateTank: + case NMTUpdateCar: + case NMTUpdateAirplane: + case NMTUpdateHelicopter: +#if _HELISIM_ROTORLIB + case NMTUpdateHelicopterRTD: +#endif + case NMTUpdateParachute: + case NMTUpdateShip: + case NMTUpdateDoor: + case NMTUpdateSeagull: + case NMTUpdateObject: + case NMTUpdateVehicle: + case NMTUpdateFlag: + case NMTUpdateShot: + case NMTUpdateMine: + case NMTUpdateWeapon: + case NMTUpdateVehicleAI: + case NMTUpdateVehicleAIFull: + case NMTUpdateVehicleBrain: + case NMTUpdateMan: + case NMTUpdateMotorcycle: + case NMTUpdateFireplace: + case NMTUpdateTurret: + case NMTUpdateClientCameraPosition: + case NMTUpdateInventoryItem: + case NMTUpdateItemRadio: + case NMTUpdateItemTransmitter: + Update: + if (_serverState < NSSLoadingGame) break; // updates from the last session + { + PREPARE_TRANSFER(NetworkObject) + + NetworkId id; + if (TRANSF_BASE(objectCreator, id.creator) != TMOK) break; + if (TRANSF_BASE(objectId, id.id) != TMOK) break; + + if (_updatesGuaranteed && from!=BOT_CLIENT) + { + MessageDiffApply diff; + message->LoadDiff(diff); + + DoAssert(diff.IsIdentity()); + + // TODO: diff messages to the server as well (we need to store or access incoming reference message for that) + //message->ApplyDiff(refMsg,diff); + + message->ResetDiff(); + + } + + #if USER_Bebul +/* + static int doItCounter = 0; + if (!(++doItCounter % 50)) + { + DiagObjectInfoAskMessage ask; ask._creator=id.creator; ask._id=id.id; + SendMsg(from, &ask, NMFGuaranteed); + if (from!=BOT_CLIENT) + SendMsg(BOT_CLIENT, &ask, NMFGuaranteed); + } +*/ + //RptFObjectNotFound(id, type, from); + #endif + + NetworkObjectInfo *oInfo = OnObjectUpdate(id, from, msg, type, ctx.GetClass()); + if (!oInfo) break; + bool guaranteed; + if (TRANSF_BASE(guaranteed, guaranteed) != TMOK) guaranteed = false; + // if (_state < NGSPlay) + if (guaranteed) + { + // init state transfer, send immediately + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &pInfo = *_players[i]; + if (pInfo.dpid == from) continue; + if (pInfo.clientState < NCSMissionReceived) continue; + + if (oInfo->GetPlayerObjectInfo(GetPlayerIndex(pInfo.dpid),pInfo.dpid)->updating) + { + if (DebugMeBoy(id)) + { + LogF("*** DebugMeBoy: {%d:%" OID_FORMAT"} init update sent to %d", id.creator.CreatorInt(), id.id, pInfo.dpid); + } + UpdateObject(&pInfo, oInfo, ctx.GetClass(), NMFGuaranteed); + } + } + } + else if (from!=BOT_CLIENT) + { + // always send immediately to the bot-client + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &pInfo = *_players[i]; + if (pInfo.dpid != BOT_CLIENT) continue; + if (pInfo.clientState < NCSMissionReceived) continue; + + UpdateObject(&pInfo, oInfo, ctx.GetClass(), NMFGuaranteed); + break; + } + + } + if (ctx.GetClass() != NMCUpdateGeneric) break; + + // check ownership of items in cargo + { + NetworkMessageUpdateVehicleAI *msg = dynamic_cast(ctx.GetNetworkMessage()); + if (msg) CheckItemsOwner(msg, oInfo->owner); + } + if (IsUpdateTransport(type)) + { + PREPARE_TRANSFER(UpdateTransport) + + // vehicle is always simulated where driver is local + // if there is no driver, it can be simulated on any computer + NetworkId driver; + NetworkId copilot; + if (TRANSF_GET_ID_BASE(copilot, copilot) == TMOK) + { + // check for NULL id + if (!copilot.IsNull()) + { + int newOwner = FindOwner(copilot); + if (newOwner != 0) ChangeOwner(id, oInfo->owner, newOwner); + } + else if (TRANSF_GET_ID_BASE(driver, driver) == TMOK) + { + // check for NULL id + if (!driver.IsNull()) + { + int newOwner = FindOwner(driver); + if (newOwner != 0) ChangeOwner(id, oInfo->owner, newOwner); + } + } + } + } + else if (type == NMTUpdateMan) + { + // Check owner of items in slots + PREPARE_TRANSFER(UpdateVehicleBrain) + +#define CHECK_SLOT_OWNER(type, typeprefix, name) \ + { \ + const NetworkId &id = message->_slot##name; \ + if (!id.IsNull()) CheckItemOwner(id, oInfo->owner); \ + } + + INVENTORY_SLOT_ENUM(InventorySlotId, IS, CHECK_SLOT_OWNER) + } + else if (type == NMTUpdateTurret) + { + PREPARE_TRANSFER(UpdateTurret) + + // turret is always simulated where gunner is local + // if there is no gunner, it can be simulated on any computer + NetworkId gunner; +#if _VBS3 //commander override, change locality! + NetworkId overriddenByTurret; + bool override = false; + if (TRANSF_GET_ID_BASE(overriddenByTurret, overriddenByTurret) == TMOK) + { + if(!overriddenByTurret.IsNull()) + { + int newOwner = FindOwner(overriddenByTurret); + if (newOwner != 0) + { + ChangeOwner(id, oInfo->owner, newOwner); + override = true; + } + } + } + if(!override) +#endif + if (TRANSF_GET_ID_BASE(gunner, gunner) == TMOK) + { + // check for NULL id + if (!gunner.IsNull()) + { + int newOwner = FindOwner(gunner); + if (newOwner != 0) ChangeOwner(id, oInfo->owner, newOwner); + } + } + } + else if (type == NMTUpdateInventoryItem || type == NMTUpdateItemRadio || type == NMTUpdateItemRadio || type == NMTUpdateItemTransmitter || type == NMTUpdateWeapon) // update of any inventory item + { + PREPARE_TRANSFER(UpdateInventoryItem) + if (message->_inLandscape) CheckItemOwner(id, BOT_CLIENT); + } + } + break; + case NMTUpdateClientInfo: + { + ClientInfoObject clientInfo; + clientInfo.TransferMsg(ctx); + NetworkPlayerInfo *pInfo = GetPlayerInfo(from); + if (pInfo && msg->time > pInfo->cameraPositionTime) + { + pInfo->cameraPosition = clientInfo._cameraPosition; + pInfo->cameraPositionTime = msg->time; +#if _VBS3 + pInfo->cameraFov = clientInfo._cameraFov; + pInfo->cameraDirection = clientInfo._cameraDirection; +#endif + + if (_serverState < NSSLoadingGame || _serverState>NSSPlaying) break; // updates from the last session + { + PREPARE_TRANSFER(UpdateClientInfo); + + NetworkId id; + if (TRANSF_BASE(objectCreator, id.creator) != TMOK) break; + if (TRANSF_BASE(objectId, id.id) != TMOK) break; + // Client Info need to be updated on Clients only for dead players (VoN Direct Speech needs position) + if (CheckPlayerInLobby(*pInfo)) + { + // create if not created yet + OnObjectCreate(id, from, NULL, NMTNone); + + clientInfo._dpnid = from; + + Ref msg2 = ::CreateNetworkMessage(NMTUpdateClientInfoDpid); + msg2->time = Glob.time; + NetworkMessageContext ctx2(msg2, this, from, MSG_SEND); + ctx2.SetClass(NMCUpdatePosition); + + NetworkMessageUpdateClientInfoDpid *message2 = static_cast(msg2.GetRef()); + message2->_guaranteed = false; + + TMError err = clientInfo.TransferMsg(ctx2); + if (err == TMOK) + { + OnObjectUpdate(id, from, msg2, NMTUpdateClientInfoDpid, NMCUpdatePosition); + } + } + } + } + } + break; + case NMTUpdateClientInfoDpid: + Fail("Unexpected on server"); + break; + case NMTChat: + { + PREPARE_TRANSFER(Chat) + + AutoArray units; + if (TRANSF_GET_IDS_BASE(units, units) != TMOK) break; + AUTO_STATIC_ARRAY(int, players, 32); + int channel; + if (TRANSF_BASE(channel, channel) != TMOK) break; + if (channel & 0x80000000) + { + //@{ Ant1HaX0R section + NetworkPlayerInfo *info = GetPlayerInfo(from); + if (info) + { + // does the client know the level 2 signatures asks? + RString text; + if (TRANSF_BASE(text, text) != TMOK) break; + // loaded bank count hidden inside the NMTChat ... channel = ( #loaded banks xor (dpnid & 0x7fffffff) ) | 0x80000000 + int bankCount = (channel & 0x7fffffff) ^ (from & 0x7fffffff); + if (info->hashes.UpdatePlayerBankCount(bankCount)) + KickOff(info->dpid,KORKick); + } + break; + //@} + } + if ((channel != CCGlobal && channel != CCSystem) && units.Size() > 0) + GetPlayersOnChannel(players, units, from, false); + else + GetPlayersOnChannel(players, channel, from, false); + for (int i=0; i units; + if (TRANSF_GET_IDS_BASE(units, units) != TMOK) break; + AUTO_STATIC_ARRAY(int, players, 32); + int channel; + if (TRANSF_BASE(channel, channel) != TMOK) break; + if ((channel != CCGlobal && channel != CCSystem) && units.Size() > 0) + GetPlayersOnChannel(players, units, from, false); + else + GetPlayersOnChannel(players, channel, from, false); + for (int i=0; i_marker, channel, from); // saved for JIP players + } + LabelChat: + { + AUTO_STATIC_ARRAY(int, players, 32); + if (channel != CCGlobal && channel != CCSystem) //units are already extracted, so we simply send it to all units specified + GetPlayersOnChannel(players, units, from, false); + else + GetPlayersOnChannel(players, channel, from, false); + for (int i=0; icertificate.Size()>0) + { + AutoArray admins; + ConstParamEntryPtr entry = _serverCfg.FindEntry("admins"); + if (entry) + { + for (int i=0; iGetSize(); i++) + { + RString adminId = (*entry)[i]; + if (!strcmpi(adminId,ident->id)) + { + adminById = true; + break; + } + } + } + } + + if (!adminById) + { + if (GlobalTickCount() < info->_loginDisabledUntil) break; + RString password = cmd._content.ReadString(); + ConstParamEntryPtr entry = _serverCfg.FindEntry("passwordAdmin"); + if (entry) + { + RString realPassword = *entry; + if (strcmp(password, realPassword) != 0) + { + info->_loginFailedCount++; + if (info->_loginFailedCount >= MaxLoginAttempts) + { + info->_loginFailedCount = 0; + info->_loginDisabledUntil = GlobalTickCount() + DelayAfterMaxAttempts; + } + break; + } + } + } + info->_loginFailedCount = 0; + + if (_gameMaster != AI_PLAYER) + { + NetworkCommandMessage answer; + answer._type = NCMTLoggedOut; + SendMsg(_gameMaster, &answer, NMFGuaranteed); + } + + SetGameMaster(from, false); + } + } + break; + case NCMTLogout: + if (_dedicated && from == _gameMaster) + { + NetworkCommandMessage answer; + answer._type = NCMTLoggedOut; + SendMsg(_gameMaster, &answer, NMFGuaranteed); + + RString name; + for (int i=0; i<_players.Size(); i++) + if (_players[i]->dpid == _gameMaster) + { + name = _players[i]->name; + break; + } + ConsoleF(LocalizeString(IDS_DS_ADMIN_LOGGED_OUT), cc_cast(name)); + + _gameMaster = AI_PLAYER; + _sessionLocked = false; + _debugOn.Clear(); + + UpdateAdminState(); + + if (_mission[0] == '?' && _mission[1] == 0) + { + // when admin logged out, perform mission voting instead + NetworkCommandMessage answer; + answer._type = NCMTVoteMission; + NetworkCommandMessage answer2; + answer2._type = NCMTVoteMissionExt; + AddMissionList(answer,answer2); + for (int i=0; i<_identities.Size(); i++) + { + SendMsg(_identities[i].dpnid, &answer, NMFGuaranteed); + SendMsg(_identities[i].dpnid, &answer2, NMFGuaranteed); + } + } + } + break; + case NCMTShutdown: + if (_dedicated && ((from == _gameMaster && !_admin) || from==BOT_CLIENT)) + { + #if defined _WIN32 + ::PostMessage((HWND)hwndApp, WM_CLOSE, 0, 0); + #else + interrupted = true; + #endif + } + break; +#if _VBS3 + case NCMTExitAll: + { + if (_dedicated && from == _gameMaster) + { + // send command to all clients to shut down! + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = _players[i]; + NetworkComponent::SendMsg(info.dpid, msg, type, NMFGuaranteed); + } + } + } + break; +#endif + case NCMTMonitorAsk: + if (from == _gameMaster || from==BOT_CLIENT) + { + float interval; + cmd._content.Read(&interval, sizeof(interval)); + Monitor(interval); + } + break; + case NCMTDebugAsk: + if + ( + (_dedicated && from == _gameMaster && !_admin) || + from==BOT_CLIENT + ) + { + DebugAsk(cmd._content.ReadString()); + } + break; + case NCMTMission: + if (_dedicated && (from == _gameMaster || from==BOT_CLIENT)) + { + _mission = cmd._content.ReadString(); + + RString diffName = cmd._content.ReadString(); + _difficulty = Glob.config.diffDefault; + int difficulty = Glob.config.diffNames.GetValue(diffName); + if (difficulty >= 0) _difficulty = difficulty; + if (_mission.GetLength() > 0) _restart = true; + if (_serverState != NSSSelectingMission && _serverState != NSSPlaying) + { + GNetworkManager.DestroyAllObjects(); + SetServerState(NSSSelectingMission); + } + } + break; + case NCMTMissions: + if (_dedicated && (from == _gameMaster || from==BOT_CLIENT)) + { + DoMissions(true); + } + break; + case NCMTRestart: + if (_dedicated && _serverState == NSSPlaying && + (from == _gameMaster || from==BOT_CLIENT) ) _restart = true; + break; + case NCMTReassign: + if (_dedicated && (from == _gameMaster || from==BOT_CLIENT)) + { + DoReassign(); + } + break; + case NCMTProfileAsk: +#if _ENABLE_PERFLOG + if (_dedicated && from == _gameMaster) + { + RString params = cmd._content.ReadString(); + params.Trim(); + if (params.IsEmpty()) GPerfProfilers.CaptureSingleFrame(1); + else + { + const char *separator = strchr(params, ','); + if (separator) + { + int len = separator - cc_cast(params); + RString scope = params.Substring(0, len); + scope.Trim(); + GPerfProfilers.CaptureSlowFrame(scope, atof(separator + 1)); + } + else + { + GPerfProfilers.CaptureSingleFrame(atoi(params)); + } + } + } +#endif + break; + case NCMTInit: + if (_dedicated && (from == _gameMaster || from==BOT_CLIENT)) + { + RString GetServerConfig(); + _serverCfg.Parse(GetServerConfig(), NULL, NULL, &GParsingNamespace); // parsing namespace (persistent namespace needed for persistent ParamFile) + } + break; + case NCMTLockSession: + if (_dedicated && ( (from == _gameMaster && !_admin) || from==BOT_CLIENT ) ) + { + bool lock; + if ( cmd._content.Read(&lock, sizeof(bool)) ) + LockSession(lock); + } + break; +#endif + case NCMTKick: + if + ( + from == BOT_CLIENT +#if _ENABLE_DEDICATED_SERVER + || from == _gameMaster +#endif + ) + { + int player; + if + ( + cmd._content.Read(&player, sizeof(int)) && + player != BOT_CLIENT + ) KickOff(player,KORKick); + } + break; +#if _ENABLE_DEDICATED_SERVER + case NCMTVote: + if (_dedicated && _gameMaster == AI_PLAYER) + { + const NetworkPlayerInfo *info = GetPlayerInfo(from); + if (!info) break; + bool doEcho = false; + LocalizedFormatedString echo; + int subtype; + cmd._content.Read(&subtype, sizeof(int)); + switch (subtype) + { + case NCMTMission: + Fail("Command-style mission voting no longer supported"); + break; + case NCMTMissions: + _votings.Add(this, (char *)&subtype, sizeof(int), _voteThreshold, from); + echo.SetFormat(LocalizedString::Stringtable,"STR_DS_VOTES_MISSIONS"); + echo.AddArg(LocalizedString::PlainText,info->name); + doEcho = true; + break; + case NCMTRestart: + _votings.Add(this, (char *)&subtype, sizeof(int), _voteThreshold, from); + echo.SetFormat(LocalizedString::Stringtable,"STR_DS_VOTES_RESTART"); + echo.AddArg(LocalizedString::PlainText,info->name); + doEcho = true; + break; + case NCMTReassign: + _votings.Add(this, (char *)&subtype, sizeof(int), _voteThreshold, from); + echo.SetFormat(LocalizedString::Stringtable,"STR_DS_VOTES_REASSIGN"); + echo.AddArg(LocalizedString::PlainText,info->name); + doEcho = true; + break; + case NCMTKick: + { + int id[2]; + id[0] = subtype; + cmd._content.Read(&id[1], sizeof(int)); + _votings.Add(this, (char *)id, 2 * sizeof(int), _voteThreshold, from); + const NetworkPlayerInfo *kickInfo = GetPlayerInfo(id[1]); + if (kickInfo) + { + echo.SetFormat(LocalizedString::Stringtable,"STR_DS_VOTES_KICK"); + echo.AddArg(LocalizedString::PlainText,info->name); + echo.AddArg(LocalizedString::PlainText,kickInfo->name); + doEcho = true; + } + } + break; + case NCMTAdmin: + { + char *ptr = cmd._content.Data() + cmd._content.GetPos(); + int size = cmd._content.Size() - cmd._content.GetPos(); + _votings.Add( + this, (char *)&subtype, sizeof(int), _voteThreshold, from, + ptr, size + ); + int player = *(int *)ptr; + RString name; + for (int i=0; i<_players.Size(); i++) + if (_players[i]->dpid == player) + { + name = _players[i]->name; + break; + } + echo.SetFormat(LocalizedString::Stringtable,"STR_DS_VOTES_ADMIN"); + echo.AddArg(LocalizedString::PlainText,info->name); + echo.AddArg(LocalizedString::PlainText,name); + doEcho = true; + } + break; + } + // Send voting echo to all other players + if (doEcho) + { + LocalizedChatMessage chat; + chat._channel = CCSystem; + chat._args = echo._args; + for (int i=0; i<_players.Size(); i++) + { + if (_players[i]->clientState >= NCSConnected) + SendMsg(_players[i]->dpid, &chat, NMFGuaranteed); + } + } + } + break; + case NCMTExec: + { + if (_dedicated && ( (from == _gameMaster && !_admin) || from==BOT_CLIENT ) ) + { + RString expression = cmd._content.ReadString(); + + // SDZ_SQF_EXEC: do not evaluate inside the message handler. + // Evaluating here ran the script while the network layer was still + // walking the object list; object/string churn from the script + // corrupted the express heap and killed the server afterwards + // (ACCESS_VIOLATION inside FastAlloc / GameDataObject, no RPT line). + // The expression goes to a queue drained right after the network + // messages of the frame are processed. + if (expression.GetLength() > 0) + { + QueueExec(from, expression); + } + } + } + break; +#if _ENABLE_CHEATS + case NCMTGameExec: + { + GameState *state = GWorld->GetGameState(); + if (state) + { + GameVarSpace vars(false); + GameValue result; + int gshandle = state->BeginContext(&vars); + { + RString code = cmd._content.ReadString(); + if (code.GetLength() > 0) + { + NetworkId playerId = GetNetworkManager().GetPlayerPerson(from); + NetworkObject *playerNO = GetNetworkManager().GetObject(playerId); + Person *playerObj = dyn_cast(playerNO); + if (playerObj) + { + GameValue fromPlayer = GameValueExt(playerObj,GameValExtObject); + state->VarSetLocal("_this", fromPlayer, true); + } + result = state->EvaluateMultiple(code, GameState::EvalContext::_default, GWorld->GetMissionNamespace()); // mission namespace + } + } + state->EndContext(gshandle); + if (!result.GetNil()) + { + NetworkCommandMessage msg; + msg._type = NCMTExecResult; + msg._content.WriteString(result.GetText()); + SendMsg(from, &msg, NMFGuaranteed); + } + } + } + break; +#endif + case NCMTAskVoNDiagnostics: + { + // convert dpnid of sender to CD based ID + PlayerIdentity *id = FindIdentity(from); + RString cdid,name; + if (id) cdid = id->GetDebugId(), name = id->name; + if (cdid.IsEmpty()) cdid = Format("#%d", from); + RString response = cmd._content.ReadString(); + GDebugVoNBank.AddClientResponse(cdid, name, response); + } + break; +#if _USE_BATTL_EYE_SERVER + /// BattlEye server command + case NCMTBattlEye: + if (_dedicated && ( (from == _gameMaster && !_admin) || from==BOT_CLIENT ) ) + { + RString command = cmd._content.ReadString(); + _beIntegration.Command(command); + } + break; +#endif +#endif + default: + Fail("Network command type"); + break; + } + } + break; + case NMTVoteMission: +#if _ENABLE_DEDICATED_SERVER + if (_gameMaster == AI_PLAYER) // voting enabled only when no admin + { + VoteMissionMessage vote; + vote.TransferMsg(ctx); + int diffId = NCMTDifficulty; + // difficulty voting is never finished + int minVotePlayers = (GetMaxPlayers() + 1) / 2; + _votings.Add( + this, (char *)&diffId, sizeof(diffId), 1e6, from, + vote._diff, vote._diff.GetLength(), false, minVotePlayers + ); + int missId = NCMTMission; + _votings.Add( + this, (char *)&missId, sizeof(missId), 0.9999, from, + vote._name, vote._name.GetLength(), true, minVotePlayers + ); + // note: voting may have been completed by the vote + MissionVotingEcho(); + } +#endif + break; + case NMTMissionParams: + { + MissionParamsMessage params; + params.TransferMsg(ctx); + + _param1 = params._param1; + _param2 = params._param2; + + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.dpid == from) continue; + if (info.clientState < NCSConnected) continue; + SendMsg(info.dpid, msg, type, NMFGuaranteed, NULL); + } + } + break; +#if _ENABLE_MP + case NMTMuteList: + { + NetworkPlayerInfo *info = GetPlayerInfo(from); + if (info) + { + info->muteList.TransferMsg(ctx); + // send remote mute lists to other players + for (int i=0; i<_identities.Size(); i++) + { + SendMuteList(_identities[i]); + } + } + } + break; +#endif + case NMTVoiceOn: + { + VoiceOnMessage ask; + ask.TransferMsg(ctx); +#if _GAMES_FOR_WINDOWS + PlayerIdentity *identity = FindIdentity(ask._dpnid); + if (identity) identity->voiceOn = ask._voiceOn; +#endif + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.dpid == from) continue; + if (info.clientState < NCSConnected) continue; + SendMsg(info.dpid, msg, type, NMFGuaranteed, NULL); + } + } + break; + case NMTDataSignatureAnswer: + { + DataSignatureAnswerMessage answer; + answer.TransferMsg(ctx); +#define PROFILE_SIGNATURES 0 +#if _ENABLE_PERFLOG && PROFILE_SIGNATURES + LogF("NMTDataSignatureAnswer START: %s", cc_cast(answer._filename)); + PROFILE_SCOPE_EX(NMTDSA,*); + int time1; + int time2; + int time3; + int time4; +#endif + NetworkPlayerInfo *info = GetPlayerInfo(from); + if (!info) break; + + //NetLog("Client %s: Data signature answer %d:'%s' level %d received, %d pending",cc_cast(info->name),answer._index,cc_cast(answer._filename),answer._level,info->signatureChecks.CountPendingData()); + + if (answer._index >= 0) + { + // remove from the list of pending checks + if (!info->signatureChecks.Remove(answer._index)) + { // I have not asked this question! + if (answer._index != CollectedHashes::CollectEndIndex) + { // backward compatibility (CollectEndIndex was not added into the pending check before) + ReportWrongSignatures(from, answer._filename, info, "DSA Not Pending"); + break; + } + } + } + +#if _ENABLE_PERFLOG && PROFILE_SIGNATURES + time1 = PROFILE_SCOPE_NAME(NMTDSA).TimeSpentNorm(); +#endif + + if (answer._signature.Version()<_sigVerRequired || !DataSignatures::VerifySignature(answer._hash, answer._signature)) + { + RString wsaReport; + if (answer._signature.Version()<_sigVerRequired) wsaReport = Format("DSA insufficient ver=%d", answer._signature.Version()); + else wsaReport = "DSA failed"; + wsaReport = wsaReport + Format(" ix=%d, level=%d", answer._index, answer._level); + ReportWrongSignatures(from, answer._filename, info, wsaReport); + break; + } + else + { +#if _ENABLE_PERFLOG && PROFILE_SIGNATURES + time2 = PROFILE_SCOPE_NAME(NMTDSA).TimeSpentNorm(); +#endif + if (info->hashes.AddHash(answer._index, answer._filename, answer._hash._content, answer._signature.Version(), answer._level, info->signatureChecks)) + { + RString wsaReport = Format("DSA AddHash, level=%d (%s)", answer._level, cc_cast(info->hashes.GetLastError())); + ReportWrongSignatures(from, answer._filename, info, wsaReport); + break; + } + } +#if _ENABLE_PERFLOG && PROFILE_SIGNATURES + time4 = PROFILE_SCOPE_NAME(NMTDSA).TimeSpentNorm(); + extern unsigned getClockFrequency (); + LogF(" %.2f ms spent, A NMT=%d", time1/100.0f, NMTDataSignatureAnswer); + LogF(" %.2f ms spent, B NMT=%d", (time2-time1)/100.0f, NMTDataSignatureAnswer); + LogF(" %.2f ms spent, C NMT=%d", (time3-time2)/100.0f, NMTDataSignatureAnswer); + LogF(" %.2f ms spent, D NMT=%d", (time4-time3)/100.0f, NMTDataSignatureAnswer); + LogF(" TOTAL %.2f ms spent, NMT=%d", time4/100.0f, NMTDataSignatureAnswer); +#endif + } + break; + case NMTFileSignatureAnswer: + { + FileSignatureAnswerMessage answer; + answer.TransferMsg(ctx); + NetworkPlayerInfo *info = GetPlayerInfo(from); + if (!info) break; + + //NetLog("Client %s: File signature answer %x:'%s' level %d received, %d pending",cc_cast(info->name),answer._index,cc_cast(answer._fileName),answer._level,info->signatureChecks.CountPendingFiles()); +/* + if (answer._index >=0) + RptF("FILE SIG INDEX INTEGRITY: %s -> %s", cc_cast(info->hashes.hashes[answer._index].fileName), cc_cast(answer._fileName)); +*/ + // remove from the list of pending checks + RString prefix; + if ( !info->signatureChecks.Remove(answer._fileName,&prefix) ) + { // I have not asked this question! + ReportWrongSignatures(from, answer._fileName, info, "FSA Not Pending"); + break; + } + + // compute the answer hash + DSHash answerHash; + switch (answer._signature.Version()) + { + case 1: + { + Temp dummy; + // only data content hash is signed (but pbo prefix is present in answer._dataToHash => extract it) + answer.GetDataHash(answerHash._content); + // new clients (start from rev.78326) contain DataSignatureAnswer matching index + if (info->hashes.AddHash(answer._index, answer.GetPrefix(), answerHash._content, dummy, answer._signature.Version(), answer._level)) + { + RString wsaReport = Format("FSA AddHash, ver=1, level=%d (%s)", answer._level, cc_cast(info->hashes.GetLastError())); + ReportWrongSignatures(from, answer._fileName, info, wsaReport); + } + } + break; + case 2: + { + Temp dummy; + HashCalculator calculator; + calculator.Add(answer._dataToHash.Data(), answer._dataToHash.Size()); + AutoArray finalHash; + calculator.GetResult(finalHash); + answerHash._content.Realloc(finalHash.Data(), finalHash.Size()); //Ver2 hash + if (answer._level!=2) + { + Temp dataContentHash; + answer.GetDataHash(dataContentHash); + //AddLevel2Hash based on bank prefix + if (info->hashes.AddHash(answer._index, answer.GetPrefix(), dataContentHash, answerHash._content, answer._signature.Version(), answer._level)) //AddHash based on bank prefix + { + RString wsaReport = Format("FSA AddHash, ver=2, level=%d (%s)", answer._level, cc_cast(info->hashes.GetLastError())); + ReportWrongSignatures(from, answer._fileName, info, wsaReport); + } + } + else if (info->hashes.AddHash(answer._index, answer.GetPrefix(), dummy, answerHash._content, answer._signature.Version(), answer._level) ) //AddHash based on bank prefix + { + RString wsaReport = Format("FSA AddHash, ver=2, level=%d (%s)", answer._level, cc_cast(info->hashes.GetLastError())); + ReportWrongSignatures(from, answer._fileName, info, wsaReport); + } + } + break; + } + + if (answer._signature.Version()<_sigVerRequired || !DataSignatures::VerifySignature(answerHash, answer._signature)) + { + RString wsaReport; + if (answer._signature.Version()<_sigVerRequired) wsaReport = Format("FSA insufficient ver=%d", answer._signature.Version()); + else wsaReport = "FSA failed"; + ReportWrongSignatures(from, answer._fileName, info, wsaReport); + break; + } + else + { + // check the answer has the same prefix + if ( stricmp(answer.GetPrefix(),prefix)!=0 ) + { + RString wsaReport = Format("FSA %s!=%s", cc_cast(answer.GetPrefix()), cc_cast(prefix)); + ReportWrongSignatures(from, answer._fileName, info, wsaReport); + break; + } + + } + } + break; + case NMTHackedData: + { + HackedDataMessage answer; + answer.TransferMsg(ctx); + OnHackedData((HackType)answer._type, from, answer._filename); + } + break; + case NMTCDKeyCheckAnswer: +#if _ENABLE_GAMESPY && _VERIFY_CLIENT_KEY + { + CDKeyCheckAnswerMessage answer; + answer.TransferMsg(ctx); + + NetworkPlayerInfo *info = GetPlayerInfo(from); + if (!info) break; + + info->cdKeyCheck.timeout = 0; //answer arrived before timeout elapsed + + sockaddr_in address; + if (!GetClientAddress(from, address)) break; + + gcd_authenticate_user( + GetGameID(), from, address.sin_addr.s_addr, info->challenge, answer._response, + OnAuthorize, OnRefreshAuthorize, this); + + // Bastian: BEServer.ReceivedPlayerGUID() will be called as soon as the GameSpy cd-key hash is received from the client (after connecting). + _beIntegration.PlayerGUIDReceived(info->dpid); + } +#endif + break; + case NMTCDKeyRecheckAnswer: +#if _ENABLE_GAMESPY && _VERIFY_CLIENT_KEY + { + CDKeyRecheckAnswerMessage answer; + answer.TransferMsg(ctx); + + gcd_process_reauth(GetGameID(), from, answer._hint, answer._response); + } +#endif + break; + case NMTAskConnectVoice: + { + AskConnectVoiceMessage ask; + ask.TransferMsg(ctx); + + NetworkPlayerInfo *info = GetPlayerInfo(from); + if (!info) break; + +// ask._privateAddr; + #define AB(v,i) ((v)>>((i)*8)&0xff) + LogF("VoNLog: Server received AskConnectVoiceMessage with %d.%d.%d.%d:%d from %d",AB(ask._privateAddr,0),AB(ask._privateAddr,1),AB(ask._privateAddr,2),AB(ask._privateAddr,3),ask._voicePort,from); + + // do some tests vor GDebugVoNBank collecting system + sockaddr_in clAdr; + bool noClientAddr = !_server->GetClientAddress(from, clAdr) && (from!=BOT_CLIENT); + if (noClientAddr) GDebugVoNBank.SetFeature(DebugVoNBank::VoNFeature_GetClientAddressFailed); + + int distAddr = ADDR(clAdr); + + info->_privateAddr = ask._privateAddr; + info->_privatePort = ask._voicePort; + info->_publicAddr = ask._publicAddr; + info->_publicPort = ask._publicAddr==distAddr ? ntohs(clAdr.sin_port) : ask._voicePort; // port unknown, try the same port as private + + LogF("VoNLog: .. public %d.%d.%d.%d:%d from %d",AB(info->_publicAddr,0),AB(info->_publicAddr,1),AB(info->_publicAddr,2),AB(info->_publicAddr,3),info->_publicPort,from); + LogF("VoNLog: .. private %d.%d.%d.%d:%d from %d",AB(info->_privateAddr,0),AB(info->_privateAddr,1),AB(info->_privateAddr,2),AB(info->_privateAddr,3),info->_privatePort,from); + + int serverPublicAddr = 0; // TODO: handle clients on the server LAN differently + for (int i=0; i<_players.Size(); i++) + { + const NetworkPlayerInfo &player = *_players[i]; + if (player.dpid==BOT_CLIENT) serverPublicAddr = player._publicAddr; + } + for (int i=0; i<_players.Size(); i++) + { + const NetworkPlayerInfo &player = *_players[i]; + if (player.dpid==from) continue; + + // same public ip => same LAN. Send private address + int NetworkPlayerInfo::*addr = info->_publicAddr == player._publicAddr ? &NetworkPlayerInfo::_privateAddr : &NetworkPlayerInfo::_publicAddr; + int NetworkPlayerInfo::*port = info->_publicAddr == player._publicAddr ? &NetworkPlayerInfo::_privatePort : &NetworkPlayerInfo::_publicPort; + + LogF("VoNLog: public %d.%d.%d.%d:%d of %d",AB(player._publicAddr,0),AB(player._publicAddr,1),AB(player._publicAddr,2),AB(player._publicAddr,3),player._publicPort,player.dpid); + LogF("VoNLog: private %d.%d.%d.%d:%d of %d",AB(player._privateAddr,0),AB(player._privateAddr,1),AB(player._privateAddr,2),AB(player._privateAddr,3),player._privatePort,player.dpid); + + LogF("VoNLog: public %d.%d.%d.%d:%d of %d",AB(info->_publicAddr,0),AB(info->_publicAddr,1),AB(info->_publicAddr,2),AB(info->_publicAddr,3),info->_publicPort,info->dpid); + LogF("VoNLog: private %d.%d.%d.%d:%d of %d",AB(info->_privateAddr,0),AB(info->_privateAddr,1),AB(info->_privateAddr,2),AB(info->_privateAddr,3),info->_privatePort,info->dpid); + + ConnectVoiceDirectMessage connect; + connect._dpnid = from; + connect._addr = BestAddress(connect._port,info,addr,port); + connect._direct = true; + SendMsg(player.dpid, &connect, NMFGuaranteed); + LogF("VoNLog: Server sent %d.%d.%d.%d:%d about %d to %d",AB(connect._addr,0),AB(connect._addr,1),AB(connect._addr,2),AB(connect._addr,3),connect._port,from,player.dpid); + + connect._dpnid = player.dpid; + connect._addr = BestAddress(connect._port,&player,addr,port); + connect._direct = true; + SendMsg(from, &connect, NMFGuaranteed); + LogF("VoNLog: Server sent %d.%d.%d.%d:%d about %d to %d",AB(connect._addr,0),AB(connect._addr,1),AB(connect._addr,2),AB(connect._addr,3),connect._port,player.dpid,from); + + } + } + break; + case NMTClientDiagToServer: + { + ClientDiagToServerMessage answer; + answer.TransferMsg(ctx); + RString logline = Format("DiagClient(%d): %s", from, cc_cast(answer._response)); + RptF(logline); + } + break; + case NMTConnectVoiceDirect: + { + } + break; + case NMTOwnerChanged: + { + OwnerChangedMessage ackMsg; + ackMsg.TransferMsg(ctx); + LogF("Owner of %d:%" OID_FORMAT" changed", ackMsg._creator, ackMsg._id); + NetworkId id(ackMsg._creator, ackMsg._id); + NetworkObjectInfo *oInfo = GetObjectInfo(id); + if (!oInfo) + { + RptFObjectNotFound(id, type, from); + return; + } + + ChangeOwnerFinal(oInfo, from, id); + } + break; + default: + //RptF("Server: Unhandled user message %s", cc_cast(GetMsgTypeName(type))); + ConsoleF("Server: Unhandled user message %s", cc_cast(GetMsgTypeName(type))); + break; + } + +#if _ENABLE_PERFLOG + int profileTime = PROFILE_SCOPE_NAME(OnMsg).TimeSpentNorm(); + static float profileTimeLimit = 10.0f; //ms + if (profileTime/100.0f > profileTimeLimit) + { + #if _SUPER_RELEASE + RptF("Warn: %.2f ms spent, NMT=%d", profileTime/100.0f, type); + if (type==NMTNetworkCommand) + { + NetworkCommandMessage cmd; + cmd.TransferMsg(ctx); + RptF(" NetworkCommand: %d", cmd._type); + } + #else + LogF("Warn: %.2f ms spent, NMT=%d", profileTime/100.0f, type); + #endif + } +#endif +} + +void NetworkServer::ChangeOwnerFinal( NetworkObjectInfo * oInfo, int from, NetworkId &id ) +{ + NetworkPlayerInfo *pInfo = GetPlayerInfo(oInfo->pendingOwner); + if (pInfo) + { + PlayerIndex index = GetPlayerIndex(pInfo->dpid); + NetworkPlayerObjectInfo *poInfo = oInfo->GetPlayerObjectInfo(index,pInfo->dpid); + if (!poInfo->updating) + { + SendCreateMessage(pInfo->dpid, *oInfo, poInfo); + poInfo->updating = true; + pInfo->markAsUpdating(poInfo); + } + for (int cls=NMCUpdateFirst; clspendingOwner = BOT_CLIENT; + } + // reset times to ensure update from new owner will take place + for (int cls=NMCUpdateFirst; clscurrentUpdate[cls]; + if (info.message) info.message->time = Time(0); // do not use TIME_MIN - difference is undefined + } + + RescanBestPosition(oInfo); + + if (oInfo->owner==from) + { + // Send message to new owner at last + ChangeOwnerMessage msg; + msg._creator = id.creator; + msg._id = id.id; + msg._owner = oInfo->pendingOwner; + msg._disconnected = false; + SendMsg(oInfo->pendingOwner, &msg, NMFGuaranteed); + + // Send messages waiting to be sent after owner is changed + for (int i=0; iwaitingMessages.Size(); i++) + { + WaitingMessageInfo *wMsgInfo = oInfo->waitingMessages[i]; + SendMsg(oInfo->pendingOwner, wMsgInfo->msg, wMsgInfo->type, NMFGuaranteed, NULL); + } + oInfo->waitingMessages.Clear(); + + // forget anything sent to the old owner before (normally nothing should be sent to the owner?) + oInfo->ResetPlayerObjectInfo(GetPlayerIndex(oInfo->owner),oInfo->owner); + // if we send anything to the new owner before, forget it now + oInfo->ResetPlayerObjectInfo(GetPlayerIndex(oInfo->pendingOwner),oInfo->pendingOwner); + +#if DIAG_MP_OBJECT_LIFE + GObjLifeJournal.Add(id, Format("(%.3f) Owner changed: from=%d to=%d",Glob.time.toFloat(), oInfo->owner, oInfo->pendingOwner)); +#endif + if (DebugMeBoy(id)) + { + LogF("*** DebugMeBoy: {%d:%" OID_FORMAT"} Owner changed from %d to %d", oInfo->id.creator.CreatorInt(), oInfo->id.id, oInfo->owner, oInfo->pendingOwner); + } + + oInfo->owner = oInfo->pendingOwner; + oInfo->pendingOwner = NO_CLIENT; + } + else + { + RptF("Server: OwnerChanged of %d:%" OID_FORMAT" arrived from non owner %d", id.creator.CreatorInt(), id.id, from); + } +} + +void NetworkServer::CheckItemsOwner(const NetworkMessageUpdateVehicleAI *msg, int newOwner) +{ + const NetworkMessageUpdateInventoryItem *invItemUpdate = dynamic_cast(msg); + if (invItemUpdate) + { + // attachments + for (int i=0; i_attachments.Size(); i++) + { + const NetworkId &id = invItemUpdate->_attachments[i]; + if (!id.IsNull()) CheckItemOwner(id, newOwner); + } + } + + // items cargo + const NetworkMessageUpdateSupply *supply = static_cast(msg->_supply.GetRef()); + if (supply) + { + for (int i=0; i_itemsCargo.Size(); i++) + { + const NetworkId &id = supply->_itemsCargo[i]; + if (!id.IsNull()) CheckItemOwner(id, newOwner); + } + } + + // magazines loaded in weapon + const NetworkMessageUpdateWeapon *weapon = dynamic_cast(msg); + if (weapon) + { + for (int i=0; i_muzzles.Size(); i++) + { + const NetworkMessageUpdateMuzzle *muzzle = static_cast(weapon->_muzzles[i].GetRef()); + if (muzzle) + { + const NetworkId &id = muzzle->_magazineWanted; + if (!id.IsNull()) CheckItemOwner(id, newOwner); + } + } + } +} + +void NetworkServer::CheckItemOwner(const NetworkId &id, int newOwner) +{ + const NetworkObjectInfo *info = GetObjectInfo(id); + if (!info || info->owner == newOwner) return; // no change + + // change my owner + ChangeOwner(id, info->owner, newOwner); + // check subitems recursively + const NetworkCurrentInfo &cInfo = info->currentUpdate[NMCUpdateGeneric]; + const NetworkMessageUpdateVehicleAI *msg = dynamic_cast(cInfo.message.GetRef()); + if (msg) CheckItemsOwner(msg, newOwner); +} + +/*! +\patch 5178 Date 11/1/2007 by Bebul +- Fixed: Default handling of different data detected was stricter then intended, resulting in a kick of players. +*/ +void NetworkServer::OnHackedData(HackType type, int dpid, RString filename) +{ + RptF("NetworkHackedData type=%d player=%d file=%s", (int)type, dpid, cc_cast(filename)); + const PlayerIdentity *identity = FindIdentity(dpid); + if (!identity) return; + +#if _ENABLE_DEDICATED_SERVER + switch (type) + { + case HTUnsignedData: + if (OnEvent(SEOnUnsignedData, (float)identity->playerid, filename)) return; + break; + case HTHackedData: + if (OnEvent(SEOnHackedData, (float)identity->playerid, filename)) return; + break; + } +#endif + +#if !SIGNATURES_TEST_ONLY + KickOff(dpid, KORFade); +#endif +} + +#if _VERIFY_KEY +void NetworkServer::OnDoubleIdDetected(const PlayerIdentity &newIdentity, const PlayerIdentity &oldIdentity) +{ + // report problems on global channel + RString message = LocalizeString(IDS_FADE_AWAY); + RString senderName = LocalizeString(IDS_FADE_REMMEMBER); + RefArray dummy; + GNetworkManager.Chat(CCSystem, senderName, dummy, message); + GChatList.Add(CCSystem, senderName, message, false, true); + +#if _ENABLE_DEDICATED_SERVER + if (OnEvent(SEDoubleIdDetected, (float)newIdentity.playerid, (float)oldIdentity.playerid)) return; // handled + if (_kickDuplicate) KickOff(newIdentity.dpnid, KORKick); +#endif +} +#endif + +void NetworkServer::OnPlayerDisconnected(NetworkPlayerInfo *info) +{ + if (GNetworkPlayerDisconnected.GetNil()) return; + GameState *state = GWorld->GetGameState(); + if (state) + { + GameVarSpace vars(false); + int gshandle = state->BeginContext(&vars); + PlayerIdentity *identity = FindIdentity(info->dpid); + RString uid = identity ? identity->id : RString(); + state->VarSetLocal("_id", (float)identity->playerid, true); + state->VarSetLocal("_uid", uid, true); + state->VarSetLocal("_name", info->name, true); + Object *agent = dyn_cast(_parent->GetObject(info->person)); + state->VarSetLocal("_agent", GameValueExt(agent), true); + +#if USE_PRECOMPILATION + if (GNetworkPlayerDisconnected.GetType() == GameCode) + { + GameDataCode *code = static_cast(GNetworkPlayerDisconnected.GetData()); + if (code->IsCompiled() && code->GetCode().Size() > 0) + state->Evaluate(code->GetString(), code->GetCode(), GameState::EvalContext::_default, GWorld->GetMissionNamespace()); // mission namespace + } + else +#endif + if (GNetworkPlayerDisconnected.GetType() == GameString) + { + // make sure string is not destructed while being evaluated + RString code = GNetworkPlayerDisconnected; + if (code.GetLength() > 0) + state->EvaluateMultiple(code, GameState::EvalContext::_default, GWorld->GetMissionNamespace()); // mission namespace + } + state->EndContext(gshandle); + } + +} + +void NetworkServer::CallOnPlayerDisconnected() +{ + for (int i=0; i<_players.Size(); i++) + { + // call only for players which are still playing the mission + if (_players[i]->clientState == NCSPlaying) + { + OnPlayerDisconnected(_players[i]); + } + } +} +int NetworkServer::FindOwner(const NetworkId &id) +{ + RefD dInfo; + if (_objects.get(id,dInfo)) + { + return dInfo->owner; + } + + LogF("Owner of %d:%" OID_FORMAT" not known - searching player",id.creator,id.id); + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &pInfo = *_players[i]; + if (pInfo.person == id) + { + // change owner + LogF("Owner not known - player found"); + return pInfo.dpid; + } + } + // not found + return 0; +} + +void NetworkServer::OnMessageClientInput(int from, NetworkMessageType type, NetworkMessageContext &ctx) +{ + // client input has very special handling, no need to check for any network id, it is send only from clients to the server + NetworkPlayerInfo *info = GetPlayerInfo(from); + if (info && info->_clientInput) + { + info->_clientInput->TransferMsg(ctx); + } +} + +DWORD NetworkServer::SendMsg +( + int to, NetworkSimpleObject *object, NetMsgFlags dwFlags +) +{ + // check if message can be sent + NetworkPlayerInfo *info = GetPlayerInfo(to); + if (!info) + { + RptF("Server: cannot send message - player %d is not known.", to); + return 0xFFFFFFFF; + } + if (info->clientState < NCSConnected && object->GetNMType() >= NMTFirstVariant) + { + RptF("Server: cannot send message - player's %s messages are not registred yet.", (const char *)info->name); + return 0xFFFFFFFF; + } + return NetworkComponent::SendMsg(to, object, dwFlags); +} + +void NetworkServer::EnqueueMsg +( + int to, NetworkMessage *msg, + NetworkMessageType type, + NetworkPlayerObjectInfo *poInfo +) +{ + NetworkPlayerInfo *info = GetPlayerInfo(to); + if (!info) + { + Fail("PlayerInfo"); + return; + } + // if + ServerQueueItem *item = new ServerQueueItem(); + item->type = type; + item->msg = msg; + item->poInfo = poInfo; + info->_messageQueue.Add(item); +} + +void NetworkServer::EnqueueMsgNonGuaranteed +( + int to, NetworkMessage *msg, + NetworkMessageType type, + const RefR &dependOn +) +{ + NetworkPlayerInfo *info = GetPlayerInfo(to); + if (!info) + { + Fail("PlayerInfo"); + return; + } + // if + ServerQueueItem *item = new ServerQueueItem(); + item->type = type; + item->msg = msg; + item->dependOn = dependOn; + info->_messageQueueNonGuaranteed.Add(item); +} + + +Vector3 NetworkServer::RandomPlayerPos() const +{ + if (_players.Size()) + { + return _players[rand() % _players.Size()]->cameraPosition; + } + return VZero; +} + +void NetworkServer::PerformIntegrityInvestigations() +{ + // scan all players + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &pi = *_players[i]; + + if (pi.dpid != BOT_CLIENT) + { + // regular checking + DWORD time = GlobalTickCount(); + if ( time > pi.regularCheckNext && pi.clientState>=NCSGameLoaded && pi.clientState<=NCSPlaying && !pi.hashes.IsCollecting() ) + { + bool handled = false; +#if _ENABLE_DEDICATED_SERVER + const PlayerIdentity *identity = FindIdentity(pi.dpid); + if (identity) + { + handled = OnEvent(SERegularCheck, identity->playerid, pi.regularCheckOrder); + pi.regularCheckOrder++; + } +#endif + if (!handled && _verifySignatures) + { + // next random question + if (rand()%2) + { // use DataSignatureAsk message + int index = toIntFloor(GRandGen.RandomValue() * 0x8000); +#if _ENABLE_CHEATS + static int forceValue = -1; + if (forceValue>=0) + { + index = forceValue; + } +#endif + int level = pi.hashes.ActualCheckLevel(); + CheckSignature(pi.dpid, index, level); + } + else + { // use FileSignatureAsk message + int level = pi.hashes.ActualCheckLevel(); + RString filename = pi.hashes.RandomUsedFile(RandomPlayerPos(), level); +#if _ENABLE_CHEATS + static bool doIt = false; + if (doIt) + { + filename = "ca\\air_d_baf\\aw159_mainrotorblurred_baf.p3d"; + LogF("RandomUsedFile: %s", cc_cast(filename)); + } +#endif + QFBank *bank = QFBankQueryFunctions::AutoBank(filename); + if (bank) + { + CheckSignature(pi.dpid, filename, bank->GetPrefix(),level); + } +#if _ENABLE_CHEATS + else if (!filename.IsEmpty()) + LogF("RandomUsedFile test SKIPPED, bank not found! file: %s", cc_cast(filename)); +#endif + } + } +// The following is only for debugging purposes, define used only not to forget to set more test back to normal in some commit +#define _DEBUG_MORE_SIGNATURE_TESTS (_ENABLE_CHEATS && 0) +#if _DEBUG_MORE_SIGNATURE_TESTS + // more test when debugging + pi.regularCheckNext = time + 500 + toInt(1000 * GRandGen.RandomValue()); // 1 s - 3 s +#else + // Note: timing 80s - 160s is no longer used for regular signature checks, but deep (level=1) checks + // regular signature checks are now more frequent, but only shallow (level=0) + pi.regularCheckNext = time + 5000 + toInt(5000 * GRandGen.RandomValue()); // 5 s - 10 s +#endif + } + + if (_verifySignatures && !pi.ClientStateBusy()) + { + ReportHackedData reportFunc(pi, *this); +#if DEBUG_SIGNATURES + pi.errorInfo = Format("SCh Timeout (cs=%d,ss=%d,#=%d,%d)", pi.clientState, _serverState, pi.hashes.Hashes().Size(),pi.hashes.IsCollecting()); + pi.signatureChecks.CheckTimeouts(reportFunc, pi.errorInfo); +#else + pi.signatureChecks.CheckTimeouts(reportFunc); +#endif +#if DEBUG_SIGNATURES + pi.errorInfo = "BI Timeout"; +#endif + pi.hashes.CheckTimeouts(reportFunc); + } +#if DEBUG_SIGNATURES + pi.errorInfo = ""; +#endif + } + } +} + +void PendingSignatureChecks::CheckTimeouts(CheckSignatureTimeoutFunc &func +#if DEBUG_SIGNATURES + , RString &errorInfo +#endif +) +{ + DWORD time = GlobalTickCount(); + for (int i=0; i pendingDataChecks[i].checkTimeout) + { +#if DEBUG_SIGNATURES + errorInfo = errorInfo + Format(" - ix=%d", pendingDataChecks[i].answerIndex); +#endif + if (func()) // do the action + return; + pendingDataChecks.Delete(i); + i--; + } + } + for (int i=0; i pendingFileChecks[i].checkTimeout) + { +#if DEBUG_SIGNATURES + errorInfo = errorInfo + Format(" - file=%s", cc_cast(pendingFileChecks[i].filename)); +#endif + if (func()) // do something the action + return; + pendingFileChecks.Delete(i); + i--; + } + } +} + +void PendingSignatureChecks::DelayCheckTimeouts(DWORD time, const char *playerName) +{ + NetLog("Signature Timeout delayed %.1f seconds for %s", time/1000.0f,playerName); + for (int i=0; iname, playerName) == 0); + return info; + } + } + + int index = _players.Add(new NetworkPlayerInfo()); + NetworkPlayerInfo &info = *_players[index]; + info.dpid = dpid; + info.dvid = dpid; + info.clientState = NCSCreated; + info.channel = CCNone; + info.name = playerName; + info.cameraPosition = InvalidCamPos; + info.cameraPositionTime = TIME_MIN; + info._busyStartTime = 0; +#if _VBS3 + info.cameraDirection = VForward; + info.cameraFov = 0.75; +#endif + info.privateSlot = privateSlot; + info.connectionProblemsReported = false; + info.kickedOff = false; + info.nextQuestionId = 1; + info._jipProcessed = false; + //LogF("_jip=false dpnid=%d setting in %s on line %d\n", dpid, __FILE__, __LINE__); + info.joined = TIME_MAX; + info._publicAddr = 0; + info._publicPort = 0; + info._privateAddr = 0; + info._privatePort = 0; + info._clientInput = new ClientInput(false); + + info.regularCheckNext = GlobalTickCount() + 40000 + toInt(40000 * GRandGen.RandomValue()); // initial delay 40 s - 80 s + info.regularCheckOrder = 1; + + info._loginFailedCount = 0; + info._loginDisabledUntil = 0; + info._isLocal = false; + + +#if _ENABLE_DEDICATED_SERVER + ConstParamEntryPtr entry = _serverCfg.FindEntry("localClient"); + if (entry) + { + if (entry->IsArray()) + { + for (int i=0; iGetSize(); i++) + { + RString ip = (*entry)[i]; + if (MatchIP(ip,ntohl(inaddr))) {info._isLocal = true;break;} + } + } + else + { + RString ip = entry->GetValue(); + if (MatchIP(ip,ntohl(inaddr))) info._isLocal = true; + } + } +#endif + +#if LOG_PLAYERS +LogF +( + "Server: Player info added - name %s, id %d (total %d identities, %d players)", + (const char *)playerName, dpid, _identities.Size(), _players.Size() +); +#endif + +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + if (_dedicated) + { + info.motdIndex = -1; + if (dpid != BOT_CLIENT && _motd.Size() > 0) info.motdIndex = 0; + } +#endif +//} + + // register formats + for (int mt=NMTFirstVariant; mtGetNMType(NMCCreate); + Ref msg = ::CreateNetworkMessage(type); + msg->time = Glob.time; + NetworkMessageContext ctx(msg, this, dpid, MSG_SEND); + + TMError err; + + NetworkMessageMsgFormat *message = (NetworkMessageMsgFormat *)msg.GetRef(); + message->_index = mt; + + err = item->TransferMsg(ctx); + if (err != TMOK) continue; + + // send message + SendMsg(dpid, msg, type, NMFGuaranteed, NULL); + } + + // enable sending messages + SetClientState(dpid, NCSConnected); + + if (_verifySignatures && dpid != BOT_CLIENT) + { + // send accepted keys + for (int i=0; i<_acceptedKeys.Size(); i++) + { + AcceptedKeyMessage key(_acceptedKeys[i]); + SendMsg(dpid, &key, NMFGuaranteed); + } + // send additional signed files + AdditionalSignedFilesMessage files(_additionalSignedFiles); + SendMsg(dpid, &files, NMFGuaranteed); + // TODO: mark required signatures + } + + #if _USE_BATTL_EYE_SERVER + if (dpid != BOT_CLIENT) + { + sockaddr_in address; + _server->GetClientAddress(dpid, address); + _beIntegration.AddPlayer(dpid, address.sin_addr.s_addr, address.sin_port, info.name); + } + #endif + + PlayerMessage msg; + msg._player = dpid; + msg._name = info.name; + msg._server = server; + msg._vonDisabled = _parent->IsVoNDisabled(); + msg._vonCodecQuality = _parent->VoNCodecQuality(); +#if !_USE_BATTL_EYE_SERVER + msg._battlEye = false; +#else + msg._battlEye = _beIntegration.IsEnabled(); +#endif + msg._sigVerRequired = _sigVerRequired; + msg._updatesGuaranteed = _updatesGuaranteed; + msg._steamServerId = 0; + msg._steamSecure = false; +#if _ENABLE_STEAM_MATCHMAKING + if (SteamGameServer()) + { + msg._steamServerId = SteamGameServer()->GetSteamID().ConvertToUint64(); + msg._steamSecure = SteamGameServer()->BSecure(); + } +#elif _VERIFY_CLIENT_KEY + if (SecureIdRequired()>0) + { + msg._steamServerId = GetSecureRandom(); + msg._regURL = "https://is.bistudio.com:8181/BICDKeys/resources/bicdkeys.cdkeys/"; + if (msg._steamServerId==0) msg._steamServerId = 1; // avoid zero, used as a special case: signature not required + info.certChallenge = msg._steamServerId; + } +#endif + // msg._inaddr = inaddr; + SendMsg(dpid, &msg, NMFGuaranteed); + + // Send ServerInfo message + ServerInfoMessage siMsg; + siMsg._hostname = _server->GetSessionName(); + SendMsg(dpid, &siMsg, NMFGuaranteed); + + // Send chat message about player is connecting + if (dpid != BOT_CLIENT) + { + /* + if (!ChannelDisabled(CCSystem)) + { + //char message[256]; + RefArray dummy; + LocalizedChatMessage chat; + chat._channel = CCSystem; + // format + chat._args.Add(LocalizedString(LocalizedString::Stringtable,"STR_MP_CONNECTING")); + // arguments + chat._args.Add(LocalizedString(LocalizedString::PlainText,info.name)); + for (int i=0; i<_players.Size(); i++) + { + if (_players[i]->clientState >= NCSConnected) + SendMsg(_players[i]->dpid, &chat, NMFGuaranteed); + } + } + */ + } + + // send player int and name to himself +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + if (_dedicated) + { + if (server) + { + ConsoleF(LocalizeString(IDS_DS_SERVER_IDENTITY_CREATED)); + } + else + { + ConsoleF(LocalizeString(IDS_DS_PLAYER_CONNECTING), cc_cast(info.name)); + } + } +#endif +//} + + // set the starting number of private and public slots on DS + + //{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + if (IsDedicatedServer()) + { +#if _GAMES_FOR_WINDOWS + // update of max. number of players + int perClient = 32000; + int round = 1; + int maxPlayers = GetMaxPlayersSafe(perClient, round); + int GetDSPrivateSlots(); + int maxPrivate = GetDSPrivateSlots(); + saturateMin(maxPrivate, maxPlayers); + UpdateMaxPlayers(maxPlayers, maxPrivate); +#else + UpdateMaxPlayers(GetMaxPlayers(), 0); +#endif + } +#endif + //} + + return &info; +} + +void NetworkServer::UpdateAdminState() +{ +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + // send also info about new admin and gameMaster state to all clients + // clients need to know whether there is admin on server + // prepare message + ServerAdminMessage samsg; + samsg._admin = _admin; + samsg._gameMaster = _gameMaster; + // update all players and send them fresh admin message + for (int i=0; i<_identities.Size(); i++) + { + PlayerIdentity &pi = _identities[i]; + pi._rights &= ~(PRAdmin|PRVotedAdmin); + if (pi.dpnid==_gameMaster) + { + pi._rights |= _admin ? PRVotedAdmin : PRAdmin; + } + SendMsg(pi.dpnid, &samsg, NMFGuaranteed); + } + DWORD updatePingTime = GlobalTickCount() + 1000; + if (_pingUpdateNext>updatePingTime) _pingUpdateNext = updatePingTime; +#endif +//} +} + +void NetworkServer::OnPlayerDestroy(int dpid) +{ + if (dpid == BOT_CLIENT) + { + Fail("Not implemented."); + // new bot client must be selected + return; + } + +#if _ENABLE_GAMESPY && _VERIFY_CLIENT_KEY + gcd_disconnect_user(GetGameID(), dpid); +#endif + +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + RString name; + if (dpid == _gameMaster) + { + for (int i=0; i<_players.Size(); i++) + if (_players[i]->dpid == _gameMaster) + { + name = _players[i]->name; + break; + } + } +#endif +//} + + NetworkPlayerInfo *info = GetPlayerInfo(dpid); + NetworkId playerPerson; + if (info) + { + /* + if (!ChannelDisabled(CCSystem)) + { + LocalizedFormatedString message; + message.SetFormat(LocalizedString::Stringtable,"STR_MP_DISCONNECT"); + message.AddArg(LocalizedString::PlainText,info->name); + RefArray dummy; + GNetworkManager.LocalizedChat(CCSystem, "", dummy, message); + GChatList.Add(CCSystem, NULL, message.GetLocalizedValue(), false, true); + } + */ + if (info->clientState == NCSPlaying) + { + OnPlayerDisconnected(info); + } + + playerPerson = info->person; + +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + if (_dedicated) ConsoleF(LocalizeString(IDS_DS_PLAYER_DISCONNECTED), cc_cast(info->name)); +#endif +//} + + _squadChecks.ForEachWithDelete([dpid](CheckSquadObject *check){return check->IsPlayer(dpid);}); + + // delete player info + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.dpid == dpid) + { +#if LOG_PLAYERS +LogF +( + "Server: Player info removed - name %s, id %d (total %d identities, %d players)", + (const char *)info.name, dpid, _identities.Size(), _players.Size() - 1 +); +#endif + _players.Delete(i); + break; + } + } + if (_players.Size() == 0) + { + _nextPlayerID = 2; // value 1 is reserved for static objects + _votings.Clear(); + } +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + else if (_dedicated && _players.Size() == 1) + { + _votings.Clear(); + } +#endif +//} + } + +#if _USE_BATTL_EYE_SERVER + _beIntegration.PlayerDisconnected(dpid); +#endif + + DisconnectPlayer(dpid, playerPerson); + + #if _ENABLE_DEDICATED_SERVER + if (_dedicated) + { + _votings.OnPlayerDeleted(dpid); + } + #endif + + LogoutMessage logout; + logout._dpnid = dpid; + for (int i=0; i<_identities.Size(); i++) + { + if (_identities[i].dpnid == dpid) + { +#if _ENABLE_DEDICATED_SERVER + OnEvent(SEOnUserDisconnected, _identities[i].playerid); +#endif + +#if LOG_PLAYERS +LogF +( + "Server: Identity removed - name %s, id %d (total %d identities, %d players)", + (const char *)_identities[i].name, dpid, _identities.Size() - 1, _players.Size() +); +#endif + _identities.Delete(i); + // check if player info was deleted properly + NetworkPlayerInfo *check = GetPlayerInfo(dpid); + if (check) + { + RptF + ( + "Server error: identity deleted, player info still exist (%s, id %d)", + (const char *)check->name, dpid + ); + } + + _votings.Check(this); + break; + } + } + for (int i=0; i<_identities.Size(); i++) + { + PlayerIdentity &player = _identities[i]; + SendMsg(player.dpnid, &logout, NMFGuaranteed); + } + +//{ QUERY & REPORTING SDK +#if _ENABLE_DEDICATED_SERVER + if (IsDedicatedServer()) + { + NetworkClient *client = _parent->GetClient(); + DoAssert(client && client->GetPlayer() != logout._dpnid); + // send new identity to bot client + SendMsg(client->GetPlayer(), &logout, NMFGuaranteed); + } +#endif +//} + + UpdateMatchmakingDescription(false); + +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + if (_dedicated) + { + if (dpid == _gameMaster) + { + ConsoleF(LocalizeString(IDS_DS_ADMIN_LOGGED_OUT), (const char *)name); + + _gameMaster = AI_PLAYER; + _sessionLocked = false; + _debugOn.Clear(); + + // on Xbox admin disconnect means nothing + if (_serverState == NSSSelectingMission && _mission.GetLength() == 1 && _mission[0] == '?') + { + // enable other players vote mission or continue with mission defined in config + _mission = ""; + _restart = false; + _reassign = false; + } + UpdateAdminState(); + + } + } +#endif +//} + + if (_serverState == NSSSelectingMission) + { + // new clients should get mission voting echo as necessary, so that they can see voting + MissionVotingEcho(); + } +#if _ENABLE_MP + // update remote mute lists + for (int i=0; i<_identities.Size(); i++) + { + SendMuteList(_identities[i]); + } +#endif + +} + +void NetworkServer::SetEstimatedEndTime(Time time) +{ + _missionHeader._estimatedEndTime = time; + _missionHeader._updateOnly = true; + _serverTime = ::GetTickCount() - _serverTimeInitTickCount; + _secondsToEstimatedEnd = time.toInt() - Glob.time.toInt(); + _serverTimeOfEstimatedEnd = _serverTime + _secondsToEstimatedEnd; + _nextServerTimeUpdate = _serverTime; //update endTime (and serverTime) to clients as soon as possible + + // send mission description and roles + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.clientState < NCSConnected) continue; + SendMsg(info.dpid, &_missionHeader, NMFGuaranteed); + } +} + +NetworkObjectInfo *NetworkServer::GetObjectInfo(const NetworkId &id) const +{ + // _objects.get variant does bot cause the refcount to be changed + if (const RefD *dInfo=_objects.get(id)) + { + return *dInfo; + } + return NULL; +} + +Vector3 NetworkServer::GetObjectPosition( NetworkId obj ) +{ + const NetworkObjectInfo *info = GetObjectInfo(obj); + if (!info) return VZero; + return info->object->GetCurrentPosition(); +} + +int NetworkServer::GetOwner(const NetworkId &id) const +{ + const NetworkObjectInfo *info = GetObjectInfo(id); + if (!info) return 0; + + const PlayerIdentity *identity = FindIdentity(info->owner); + if (!identity) return 1; + + return identity->playerid; +} + +bool NetworkServer::SetOwner(const NetworkId &id, int clientId) +{ + const NetworkObjectInfo *info = GetObjectInfo(id); + if (!info) return false; + + const PlayerIdentity *identity = FindIdentityByPlayerId(clientId); + if (!identity) return false; + + if (info->owner == identity->dpnid) return false; + + ChangeOwner(id, info->owner, identity->dpnid); + return true; +} + +bool NetworkServer::StatusChat(int clientId, RString text, RString colorClass) +{ + const PlayerIdentity *identity = FindIdentityByPlayerId(clientId); + if (!identity) return false; + + StatusChatMessage msg; + msg._text = text; msg._color = colorClass; + SendMsg(identity->dpnid, &msg, NMFNone); + return true; +} + +NetworkObjectInfo *NetworkServer::OnObjectCreate(const NetworkId &id, int owner, NetworkMessage *msg, NetworkMessageType type) +{ + if (NetworkObjectInfo *info = GetObjectInfo(id)) + { + /* + if (info->owner!=owner) + { // ownership change not possible in client-server architecture + return nullptr; + } + */ + // create message redefined + info->create.from = owner; + info->create.message = msg; + info->create.type = type; +#if DIAG_MP_OBJECT_LIFE + GObjLifeJournal.Add(id, Format("(%.3f) Redefine create message: from=%d type=%d",Glob.time.toFloat(), owner,type)); +#endif + return info; + } + + NetworkObjectInfo *info = new NetworkObjectInfo; + info->id = id; + info->owner = owner; + info->create.from = owner; + info->create.message = msg; + info->create.type = type; + info->pendingOwner = NO_CLIENT; //no pending + for (int i=0; i<_indexToPlayerId.Size(); i++) + { + info->CreatePlayerObjectInfo(PlayerIndex(i),_indexToPlayerId[i]); + } + DoAssert(_indexToPlayerId.Size()==info->playerToObjects.Size()); + _objects.put(info); + +#if DIAG_MP_OBJECT_LIFE + GObjLifeJournal.Add(id, Format("(%.3f) Create: owner=%d type=%d",Glob.time.toFloat(), owner,type)); +#endif + return info; +} + +/*! +\patch_internal 1.28 Date 10/29/2001 by Jirka +- Fixed: update objects only by messages by object's owner +*/ +NetworkObjectInfo *NetworkServer::OnObjectUpdate(NetworkId &id, int from, NetworkMessage *msg, NetworkMessageType type, NetworkMessageClass cls) +{ + DoAssert(!msg->HasDiff()) + NetworkObjectInfo *oInfo = GetObjectInfo(id); + if (!oInfo) + { + // if the update is from the owner and the object is listed as deleted, ignore the update + NetworkDeletedObjectInfo *delInfo = _deletedObjects.get(id); + if (delInfo && delInfo->owner!=from) + { + RptFObjectNotFound(id, type, from); + } + return NULL; + } + + if (oInfo->owner != from) + { + bool allowNonOwner = false; + if (from==BOT_CLIENT) + { + allowNonOwner = true; + } + if (!allowNonOwner) + { + RptF("Server: Update of object %d:%" OID_FORMAT" arrived from nonowner", id.creator.CreatorInt(), id.id); + return NULL; + } + } + + bool rejectedFromClient = from!=BOT_CLIENT && oInfo->rejected[cls]; + if (rejectedFromClient) + { + LogF("Received rejected %d for %" OID_FORMAT"",cls,oInfo->id.id); + } + + NetworkCurrentInfo &info = rejectedFromClient ? oInfo->currentRejected[cls] : oInfo->currentUpdate[cls]; + + NetworkMessageFormatBase *format = GetFormat(/*from, */type); + if (!format) + { + RptF("Server: Bad message %d(%s) format", (int)type, cc_cast(GetMsgTypeName(type))); + return NULL; + } + + if (info.from==from && info.message && info.message->time > msg->time) + { + if (info.from!=from) + { + LogF("Discarded different owner message for %" OID_FORMAT"(%d) because of time. %d!=%d",oInfo->id.id,rejectedFromClient,info.from,from); + } + + // do not update + if (DiagLevel >= 1) + DiagLogF("Server: update message is old (%.3f s)", info.message->time - msg->time); + return NULL; + } + + if (info.message && info.message->time > msg->time) + { + LogF("Passed old time for %" OID_FORMAT"(%d). %d!=%d",oInfo->id.id,rejectedFromClient,info.from,from); + } + + if (info.from!=from && info.message.NotNull()) + { + LogF("Changing from %d(%d) for %" OID_FORMAT" %d to %d",cls,rejectedFromClient,oInfo->id.id,info.from,from); + } + + + info.from = from; + info.type = type; + info.message = msg; + + RescanBestPosition(oInfo); + + // invalidate cached error + for (int i=0; iplayerToObjects.Size(); i++) + { + NetworkPlayerObjectInfo *poInfo = oInfo->playerToObjects[i]; + if (poInfo) poInfo->updates[cls].errorValid = false; + + } + + if (DiagLevel >= 4) + DiagLogF("Server: object %d:%" OID_FORMAT" updated", id.creator.CreatorInt(), id.id); + + return oInfo; +} + +void NetworkServer::RescanBestPosition( NetworkObjectInfo * oInfo ) +{ + const auto bestPosOld = oInfo->BestPosition(); + const Entity *veh = dyn_cast(oInfo->object); + if (veh && veh->GetHierarchyParent()) + { + return; + } + + oInfo->ScanBestPosition(this); + + const auto bestPosNew = oInfo->BestPosition(); + + _objects.onPosChanged(oInfo,bestPosOld,bestPosNew); + + if (veh && bestPosOld._pos.Distance2(bestPosNew._pos)>Square(0.001f)) + { + UpdateChildrenPos(veh); + return; + } +} + +void NetworkServer::UpdateChildrenPos(const Entity * veh) +{ + NetworkObjectInfo *oInfo = GetObjectInfo(veh->GetNetworkId()); + if (!oInfo) return; + const auto bestPosNew = oInfo->BestPosition(); + + veh->ForEachChildren([this,&bestPosNew](const NetworkObject *obj)->bool{ + NetworkObjectInfo *oInfo = GetObjectInfo(obj->GetNetworkId()); + if (oInfo) + { + const auto bestPosOld = oInfo->BestPosition(); + oInfo->_updInfo = bestPosNew; + + _objects.onPosChanged(oInfo,bestPosOld,bestPosNew); + } + return false; + }); +} + +bool NetworkServer::CheckBestPositionIntegrity() const +{ + // traverse all objects, for all of them check if BestPosition is up to date + bool ok = true; + _objects.forEach([&ok,this](const NetworkObjectInfo *oInfo){ + if (ok) ok = oInfo->CheckBestPositionIntegrity(this); + }); + return ok; +} + + +void NetworkServer::OnRejectChanged(const NetworkId &id, NetworkMessageClass cls, bool reject) +{ + // reset the updates we are sending to the object owner + NetworkObjectInfo *oInfo = GetObjectInfo(id); + if (oInfo) + { + LogF("Reject update %d %d for %" OID_FORMAT" to BOT_CLIENT",reject,cls,id.id); + oInfo->rejected[cls] = reject; + // the update from client ("currentRejected") was accepted by a bot-client, use it as a main object state + if (!reject) + { + oInfo->currentUpdate[cls] = oInfo->currentRejected[cls]; + // forget the bot-client provided update + oInfo->currentRejected[cls].message = nullptr; + oInfo->currentRejected[cls].from = 0; + RescanBestPosition(oInfo); + } + } +} + +NetworkDeletedObjectInfo ImplicitMapTraits::zombie = {NetworkId(CreatorId(-1),-1)}; +NetworkDeletedObjectInfo ImplicitMapTraits::null = {NetworkId(CreatorId(0),0)}; + +int NetworkServer::PerformObjectDestroy(const NetworkId &id) +{ + //DoAssert(CheckIntegrityOfPendingMessages()); + int owner = 0; + if (NetworkObjectInfo *info = GetObjectInfo(id)) + { + owner = info->owner; + + RemoveInitObjectDeleted(id); + //LogF("Performing Object Destroy for (%d:%" OID_FORMAT")", _objects[i]->id.creator.CreatorInt(), _objects[i]->id.id); + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &pInfo = *_players[i]; + int dpid = pInfo.dpid; + PlayerIndex playerIndex = GetPlayerIndex(dpid); + if (playerIndex<0) continue; // player index not created yet, player cannot be aware of any objects, cannot delete them + NetworkPlayerObjectInfo *poInfo = info->GetPlayerObjectInfo(playerIndex,dpid); + if (poInfo->updating) + { + DoAssert(pInfo._updating.CheckIntegrity()); + DoAssert(poInfo->IsInList()); + if (poInfo->IsInList()) pInfo._updating.Delete(poInfo); + DoAssert(pInfo._updating.CheckIntegrity()); + } + } + + NetworkDeletedObjectInfo delInfo; + delInfo.id = id; + delInfo.owner = info->owner; + delInfo.time = Glob.time; + _deletedObjects.put(delInfo); + + _objects.removeKey(id); + } + return owner; +} + +void NetworkServer::OnObjectDestroy(const NetworkId &id, int from) +{ + PerformObjectDestroy(id); + DeleteObjectMessage msg; + msg._creator = id.creator; + msg._id = id.id; + + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &pInfo = *_players[i]; + if (pInfo.clientState < NCSMissionReceived) continue; + if (pInfo.dpid == from) continue; + SendMsg(pInfo.dpid, &msg, NMFGuaranteed); + } +} + +int NetworkServer::UpdateObject(NetworkPlayerInfo *pInfo, NetworkObjectInfo *oInfo, NetworkMessageClass cls, NetMsgFlags dwFlags) +{ + if (!oInfo) + { + // TODO: BUG + DiagLogF("Server: Object not found"); + return -1; + } + + + // when sending to the bot-client use a rejected updated when available + NetworkCurrentInfo &info = pInfo->dpid==BOT_CLIENT && oInfo->rejected[cls] && oInfo->currentRejected[cls].message.NotNull() ? oInfo->currentRejected[cls] : oInfo->currentUpdate[cls]; + if (!info.message) return -1; + + + // SendMsg may change currentRejected, therefore info.message may be no longer valid after it + Ref msg = info.message; + + NetworkMessageType type = info.type; + int to = pInfo->dpid; + + PlayerIndex index = GetPlayerIndex(to); + if (index<0) return -1; + + if (DebugMeBoy(oInfo->id)) + { + LogF("*** DebugMeBoy: {%d:%" OID_FORMAT"} UpdateObject to %d", oInfo->id.creator.CreatorInt(), oInfo->id.id, to); + } + + + // make sure the children are updating, as the message can contain references to them + if (oInfo->object && pInfo->dpid!=BOT_CLIENT) + { + oInfo->object->ForEachChildren([this,index,pInfo,oInfo,type](const NetworkObject *obj)->bool{ + NetworkObjectInfo *objInfo = GetObjectInfo(obj->GetNetworkId()); + if (!objInfo) + { + BString<256> context; + sprintf(context, " ForEachChildren of %s", cc_cast(oInfo->object->GetDebugName())); + RptFObjectNotFound(obj->GetNetworkId(), type, -1, context); + return false; + } + NetworkPlayerObjectInfo *pObjInfo = objInfo->GetPlayerObjectInfo(index,pInfo->dpid); + if (!pObjInfo->updating) + { + DoAssert(objInfo->create.message.NotNull()); + if (objInfo->create.message.NotNull()) + { + LogF("%s to %d: children %s starting updating",cc_cast(oInfo->GetDebugName()),pInfo->dpid,cc_cast(obj->GetDebugName())); + SendCreateMessage(pInfo->dpid, *objInfo, pObjInfo); + pObjInfo->updating = true; + /* + Can be called safely from NetworkServer::CreateObjectsList in spite of existence of local updatingNew list, which is not updated here. + If the children was already visited in the forEachInBubble loop, it was already marked as updating and we are not processing it here. + If it was not visited yet, pInfo.markAsUpdating(poInfo,updatingNew) will be called on it once it will be visited. + */ + pInfo->markAsUpdating(pObjInfo); + } + } + else + { + //LogF("%s to %d: children %s already updating",cc_cast(oInfo->GetDebugName()),pInfo->dpid,cc_cast(obj->GetDebugName())); + } + return false; + }); + } + + // update object info + NetworkPlayerObjectInfo *poInfo = oInfo->GetPlayerObjectInfo(index,to); + + DoAssert(!msg->HasDiff()); + + Ref toSend = msg; + if (_updatesGuaranteed && to!=BOT_CLIENT) + { + NetworkMessage *refMsg = poInfo->updates[cls].lastSentMsg; + if (refMsg) + { + MessageDiffCreate diff; + toSend = toSend->Clone(); + toSend->CreateDiff(refMsg,diff); + toSend->StoreDiff(diff); + } + } + + DWORD dwMsgId = SendMsg(to, toSend, type, dwFlags, poInfo); + if (dwMsgId == 0xFFFFFFFF) return -1; + + // message will be stored and used again, it must not be diffed + DoAssert(!msg->HasDiff()); + msg->ProtectDiff(); + + poInfo->updates[cls].lastSentMsg = msg; + poInfo->updates[cls].errorValid = false; + + return toSend->size; +} + +//! Simplified enumeration of array items +#define FOR_EACH(type,var,array) \ + for (type *var = array.Data(), *end = array.Data() + array.Size(); var < end; var++) + +void NetworkServer::DestroyAllObjects() +{ + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo *player = _players[i]; + player->person = NetworkId::Null(); + player->_delayedMessages.Clear(); + player->_updating.Clear(); + } + _objects.reset(); + _deletedObjects.reset(); +#if DIAG_MP_OBJECT_LIFE + GObjLifeJournal.Clear(); +#endif +//CheckInitMessages(_initMessages, "before _initMessages.Clear()"); + if ( _initMessages.Size() ) + { + // log GetAddInitAndRemoveOverridden statistics into the mpStatistics.log file + LogMPStatistics( GetAddInitAndRemoveOverriddenStat() ); + } + _initMessages.Clear(); + _jipMarkerInfos.Clear(); + + if (_indexToPlayerId.Size()>=1) + { + DoAssert(_indexToPlayerId[0]==BOT_CLIENT); + _indexToPlayerId.Resize(1); + LogF("**** Player index reset"); + } +//CheckInitMessages(_initMessages, "after _initMessages.Clear()"); + + // avoid id duplicity at next missions + // _nextId = 0; +} + + +NetworkMessageFormatBase *NetworkServer::GetFormat(/*int client, */int type) +{ + Assert(type >= 0); + if (type >= NMTN) return NULL; // unknown message + return GMsgFormats[type]; +} + +const NetworkMessageFormatBase *NetworkServer::GetFormat(/*int client, */int type) const +{ + Assert(type >= 0); + if (type >= NMTN) return NULL; // unknown message + return GMsgFormats[type]; +} + +void NetworkServer::CreateMission(RString mission, RString world) +{ + _originalName = mission; +#if _ENABLE_UNSIGNED_MISSIONS + if (mission.GetLength() > 0) + { + RString filename = RString("mpmissions\\") + mission + RString(".") + world; + CreateMPMissionBank(filename, world); + } + else + { + GFileBanks.Remove("mpmissions\\__cur_mp."); + } +#endif // _ENABLE_UNSIGNED_MISSIONS +} + +/// detect client-side localization, if possible use it +LocalizedString ClientSideLocalizedString(RString value, RString mission) +{ + // if possible, localize client-side + RString table; + RString name = TryLocalize(value,table); + if (!strcmpi(table,"global")) + { + // if localized using global table, client can localize it + return LocalizedString(LocalizedString::Stringtable,(const char *)value+1); + } + else + { + if (value[0]=='@') + { + RptF( + "%s: string %s cannot be localized client-side - move to global stringtable", + cc_cast(mission),cc_cast(value) + ); + } + return LocalizedString(LocalizedString::PlainText,name); + } +} + + +#define DIFF_SET(MessageName,name,ids,XX) _missionHeader._diff##name = item.flags[DT##name]; + +void NetworkServer::UndefMissionParams() +{ + _param1 = _param2 = FLT_MAX; + _paramsArray.Clear(); +} + +void NetworkServer::InitMission(int difficulty, RString displayName, bool noCopy, RString owner, bool isCampaignMission) +{ + PROFILE_SCOPE_EX(nsIM1, network) + // unlock session + _sessionLocked = false; + + _missionHeader._estimatedEndTime = TIME_MIN; + _missionHeader._enableAIDisable = !isCampaignMission; + + // mission description + _missionHeader._gameType = RString(); + ConstParamEntryPtr header = ExtParsMission.FindEntry("Header"); + if (header) + { + ConstParamEntryPtr gameType = header->FindEntry("gameType"); + if (gameType) _missionHeader._gameType = *gameType; + } + + _missionHeader._island = Glob.header.worldname; + const ArcadeIntel &intel = CurrentTemplate->Intel(); + if (displayName.GetLength() > 0) + { + _missionHeader._name = LocalizedString(LocalizedString::PlainText,displayName); + } + else + { + _missionHeader._name = ClientSideLocalizedString(intel.briefingName,intel.briefingName); + if (_missionHeader._name._id.GetLength() == 0) + { + _missionHeader._name = LocalizedString( + LocalizedString::PlainText, + _originalName.GetLength() > 0 ? _originalName : Glob.header.filename + ); + } + } + + RString missionName = _missionHeader._name.GetLocalizedValue(); + + _missionHeader._description = ClientSideLocalizedString(intel.briefingDescription,missionName); + + // ADDED in patch 1.01 - checks of addons + _missionHeader._addOns = CurrentTemplate->AddOns(); + // make sure addon owning the mission is present on clients + if (owner.GetLength() > 0) _missionHeader._addOns.AddUnique(owner); + + // ADDED in patch 1.01 - disable AI +#if _ENABLE_AI + _missionHeader._disabledAI = false; + ConstParamEntryPtr disabledAI = ExtParsMission.FindEntry("disabledAI"); + if (disabledAI) _missionHeader._disabledAI = *disabledAI; +#endif + + // difficulty + _missionHeader._diffName = Glob.config.diffNames.GetName(difficulty); + const DifficultySettings &item = Glob.config.diffSettings[difficulty]; + DIFFICULTY_TYPE_ENUM(DIFF_SET, ignored, ignored) + + _missionHeader._aiKills = false; + ConstParamEntryPtr aiKills = ExtParsMission.FindEntry("aiKills"); + if (aiKills) _missionHeader._aiKills = *aiKills; + + _missionHeader._createPlayers = false; //TODO + + // handling players after disconnect + ConstParamEntryPtr entry = ExtParsMission.FindEntry("destroyDisconnected"); + if (entry) _destroyDisconnected = *entry; + else _destroyDisconnected = true; + + // mission parameters + entry = ExtParsMission.FindEntry("titleParam1"); + _missionHeader._titleParam1 = ClientSideLocalizedString(entry ? entry->operator RString() : RString(""),missionName); + _missionHeader._valuesParam1.Resize(0); + _missionHeader._textsParam1.Resize(0); + entry = ExtParsMission.FindEntry("valuesParam1"); + if (entry) + { + int n = entry->GetSize(); + _missionHeader._valuesParam1.Resize(n); + for (int i=0; iGetSize() != n) entryTexts = entry; + + if (entryTexts) + { + _missionHeader._textsParam1.Resize(n); + for (int i=0; ioperator RString() : RString(""),missionName); + _missionHeader._valuesParam2.Resize(0); + _missionHeader._textsParam2.Resize(0); + entry = ExtParsMission.FindEntry("valuesParam2"); + if (entry) + { + int n = entry->GetSize(); + _missionHeader._valuesParam2.Resize(n); + for (int i=0; iGetSize() != n) entryTexts = entry; + + if (entryTexts) + { + _missionHeader._textsParam2.Resize(n); + for (int i=0; i 0; + + _missionHeader._noCopy = noCopy; + + //----------------------------------------------------------------// + //----------------------------------------------------------------// + //array of user mission params + // mission parameters + + _missionHeader._valuesParamArray.Resize(0); + _missionHeader._textsParamArray.Resize(0); + _missionHeader._defaultParamArray.Resize(0); + _missionHeader._titleParamArray.Resize(0); + _missionHeader._sizesParamArray.Resize(0); + if (setParams) _paramsArray.Clear(); + + + //copy param1/2 to new array + _missionHeader._titleParamArray.Add(_missionHeader._titleParam1); + _missionHeader._sizesParamArray.Add(0); + for(int i=0; i<_missionHeader._valuesParam1.Size();i++) + { + _missionHeader._valuesParamArray.Add(_missionHeader._valuesParam1[i]); + _missionHeader._textsParamArray.Add(_missionHeader._textsParam1[i]); + _missionHeader._sizesParamArray[_missionHeader._sizesParamArray.Size()-1]++; + } + _missionHeader._defaultParamArray.Add(_missionHeader._defValueParam1); + if (setParams) _paramsArray.Add(_param1); + + _missionHeader._titleParamArray.Add(_missionHeader._titleParam2); + _missionHeader._sizesParamArray.Add(0); + for(int i=0; i<_missionHeader._valuesParam2.Size();i++) + { + _missionHeader._valuesParamArray.Add(_missionHeader._valuesParam2[i]); + _missionHeader._textsParamArray.Add(_missionHeader._textsParam2[i]); + _missionHeader._sizesParamArray[_missionHeader._sizesParamArray.Size()-1]++; + } + _missionHeader._defaultParamArray.Add(_missionHeader._defValueParam2); + if (setParams) _paramsArray.Add(_param2); + + //read secondary parameters + ConstParamEntryPtr paramsDesc = ExtParsMission.FindEntry("Params"); + //for all parameters add CStatic and CListBox to container + if(paramsDesc) for(int i=0; i< paramsDesc->GetEntryCount();i++ ) + { + //create listbox content text (parameters names) + ParamEntryVal parameterDesc = paramsDesc->GetEntry(i); + + ConstParamEntryPtr entry = parameterDesc.FindEntry("title"); + _missionHeader._titleParamArray.Add(ClientSideLocalizedString(entry ? entry->operator RString() : RString(""),missionName)); + _missionHeader._sizesParamArray.Add(0); + + entry = parameterDesc.FindEntry("values"); + if (entry) + { + int n = entry->GetSize(); + + for (int i=0; iGetSize() != n) entryTexts = entry; + + if (entryTexts) + { + for (int i=0; i=0 && dir[i] == '\\') dir = dir.Substring(0, i); // remove trailing '\' + +#if _VBS2 && _VBS2_LITE + void VBS2EncryptMission(RString fileName,RString directory); + VBS2EncryptMission(_missionBank,dir); +#else + // TODO: do not create temporary __CUR_MP + mgr.Create(_missionBank, dir); +#endif + } + } +#endif // _ENABLE_UNSIGNED_MISSIONS + +#if _USE_BATTL_EYE_SERVER + //ASSERT_RLS(beName.GetLength() > 0, ("Empty mission name for BattlEye service!!!")); + _beIntegration.LoadedMission(beName); +#endif + + { + QIFStream f; + f.open(_missionBank); + + CRCCalculator crc; + crc.Reset(); + f.copy(crc); + _missionHeader._fileCRC = crc.GetResult(); + + _missionHeader._fileSizeH = 0; + _missionHeader._fileSizeL = f.tellg(); + } + +#if _GAMES_FOR_WINDOWS + // set the properties and contexts for matchmaking + // - MPType + int gameType = 0; + if (_missionHeader._gameType.GetLength() > 0) + { + ConstParamEntryPtr cls = (Pars >> "CfgMPGameTypes").FindEntry(_missionHeader._gameType); + if (cls) gameType = *cls >> "id"; + } + GSaveSystem.SetContext(CONTEXT_GAME_MPTYPE, gameType); + // - World + int worldId = 0; + if (_missionHeader._island.GetLength() > 0) + { + ConstParamEntryPtr cls = (Pars >> "CfgWorlds").FindEntry(_missionHeader._island); + if (cls) worldId = *cls >> "worldId"; + } + GSaveSystem.SetContext(CONTEXT_GAME_WORLD, worldId); + // - Difficulty + GSaveSystem.SetContext(CONTEXT_GAME_DIFFICULTY, difficulty); + // - MPMission + int missionId = 0; + // TODOXNET: mission identification + GSaveSystem.SetContext(CONTEXT_GAME_MPMISSION, missionId); +#endif + _missionHeader._forceCameraType = 0; + _missionHeader._environmentTimeMul = 0; +#if _ENABLE_DEDICATED_SERVER + { + ConstParamEntryPtr entry = _serverCfg.FindEntry("disable3rdPerson"); + if(entry) + _missionHeader._forceCameraType = *entry; + + ConstParamEntryPtr entry2 = _serverCfg.FindEntry("environmentTimeMul"); + if(entry2) + _missionHeader._environmentTimeMul = *entry2; + } +#endif + + // send mission description and roles + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.clientState < NCSConnected) continue; + info.missionFileValid = false; + info.paramFileValid = GetMissionParameters().GetLength() == 0; + // set missionFileValid first, as SendMissionInfo on the bot-client will already use it on the receiving end + SendMissionInfo(info.dpid); + } + + if (header) + { +/* + int minPlayers = -1; + ConstParamEntryPtr entry = header->FindEntry("minPlayers"); + if (entry) minPlayers = *entry; +*/ + int maxPlayers = -1; + entry = header->FindEntry("maxPlayers"); + if (entry) maxPlayers = *entry; + + if (maxPlayers > 0) + { + _missionHeader._maxPlayers = maxPlayers; + } + } +} + +void NetworkServer::UpdateMaxPlayers(int maxPlayers, int privateSlots) +{ + _totalSlots = maxPlayers; + + maxPlayers = GetMaxPlayers(); +#if _ENABLE_DEDICATED_SERVER + if (IsDedicatedServer()) maxPlayers++; // one more slot for the dedicated server bot client +#endif + + if(privateSlots > maxPlayers) + privateSlots = maxPlayers; + if (_server) _server->UpdateMaxPlayers(maxPlayers); +# if _ENABLE_GAMESPY + ChangeStateQR(); +# endif + +#if _GAMES_FOR_WINDOWS + // update the session description + if (_parent) _parent->UpdateSession(maxPlayers, privateSlots); +#endif +} + +void NetworkServer::ChangeOwner(const NetworkId &id, int from, int to) +{ + if (from == to) return; + if (id.IsNull()) return; + + NetworkObjectInfo *oInfo = GetObjectInfo(id); + if (!oInfo) + { + RptFObjectNotFound(id,"NetworkServer::ChangeOwner",from); + return; + } + + if (oInfo->pendingOwner!=NO_CLIENT) + { // change of owner of this object is already pending + oInfo->pendingOwner = to; // BUT change pending owner to new one + return; + } + oInfo->pendingOwner = to; // mark this change of owner as pending + + ChangeOwnerMessage msg; + msg._creator = id.creator; + msg._id = id.id; + msg._owner = to; + msg._disconnected = false; +#if DIAG_MP_OBJECT_LIFE + GObjLifeJournal.Add(id, Format("(%.3f) ChangeOwner: from=%d to=%d",Glob.time.toFloat(), from, to)); +#endif + SendMsg(from, &msg, NMFGuaranteed); + //note: new owner will be notified after the ownerChanged returns from previous owner + // so do not SendMsg(to, &msg, NMFGuaranteed); now + + if (DebugMeBoy(id)) + { + LogF("*** DebugMeBoy: {%d:%" OID_FORMAT"} ChangeOwner from %d to %d", oInfo->id.creator.CreatorInt(), oInfo->id.id, from, to); + + } +} + +void NetworkServer::SendMissionInfo(int to, bool onlyPlayers) +{ + _missionHeader._updateOnly = false; + + if (!onlyPlayers) + { + // send at last, client will update its state as reaction + SendMsg(to, &_missionHeader, NMFGuaranteed); // LOGGED IN -> MISSION SELECTED + + MissionParamsMessage msg; + msg._param1 = _param1; + msg._param2 = _param2; + msg._paramsArray = _paramsArray; + msg._updateOnly = false; + SendMsg(to, &msg, NMFGuaranteed); // MISSION SELECTED -> MISSION ASKED + } +} + +void Encrypt(QOStrStream &out,const unsigned char *publicKey, int keySize); + +//{ DEDICATED SERVER SUPPORT +bool NetworkServer::IsDedicatedBotClient(int dpnid) const +{ +#if _ENABLE_DEDICATED_SERVER + return _dedicated && dpnid == BOT_CLIENT; +#else + return false; +#endif +} +//} + +//! Text representation of NetworkServerState enum values +const EnumName NetworkServerStateNames[]= +{ + EnumName(NSSNone, "NONE"), + EnumName(NSSSelectingMission, "SELECTING MISSION"), + EnumName(NSSEditingMission, "EDITING MISSION"), + EnumName(NSSAssigningPlayers, "ASSIGNING PLAYERS"), + EnumName(NSSSendingMission, "SENDING MISSION"), + EnumName(NSSLoadingGame, "LOADING GAME"), + EnumName(NSSPlaying, "PLAYING"), + EnumName(NSSMissionAborted, "MISSION ABORTED"), + EnumName() +}; + +RString NetworkServer::GetAddInitAndRemoveOverriddenStat() +{ + int stats[NMTN]; + for (int i=0; i= 0 && type < NMTN ) stats[type]++; + } + + RString retValStr; + retValStr.CreateBuffer(NMTN * 256); // 256 chars for each line of statistics should be enough + char *buf = retValStr.MutableData(); + sprintf(buf, "AddInitAndRemoveOverridden statistics ... total messages = %d\n", _initMessages.Size()); + for (int i=0; i0 ) + { + RString name = GetMsgTypeName( (NetworkMessageType)i ); + RString newLine = Format("%d ... %s\n", stats[i], cc_cast(name)); + strcat(buf, newLine); + } + } + strcat(buf, "\n\n"); + return retValStr; +} + + +void NetworkServer::OnChangedOnPlayerConnecting(GameValuePar codeValue) +{ + for (int i=0; i<_players.Size(); i++) + { + if (_players[i]->dpid==BOT_CLIENT) + { +#if _ENABLE_DEDICATED_SERVER + bool localDedicated = _dedicated; +#else + bool localDedicated = false; +#endif + if (!localDedicated) OnPlayerConnecting(_players[i]->dpid,codeValue); + } + else if (_players[i]->clientState>=NCSGameLoaded) + { + // can any player be in such state? + OnPlayerConnecting(_players[i]->dpid,codeValue); + } + } +} + + + +void ResetGlobalEventHandlers(); + +//! Map NetworkServerState enum values to its text representation +template<> +const EnumName *GetEnumNames(NetworkServerState dummy) {return NetworkServerStateNames;} + +/*! +\patch 1.32 Date 11/26/2001 by Jirka +- Fixed: players' states are properly send to all clients +\patch 5142 Date 3/16/2007 by Jirka +- Fixed: MP - handling / reporting the current and maximum number of players was wrong sometimes +\patch 5154 Date 5/3/2007 by Jirka +- Fixed: MP mission statistics can be written to the file given by command line argument -ranking=... +\patch 5170 Date 10/8/2007 by Bebul +- New: Command line argument -ranking=... was removed. MP mission statistics can be written to file specified by logFile entry in the server config. +*/ + +void NetworkServer::SetServerState(NetworkServerState state) +{ +//((TO_BE_REMOVED_IN_FINAL +#if _ENABLE_PERFLOG + RptF("### Server: SetServerState to %s", (const char *)FindEnumName(state)); +#endif +//))TO_BE_REMOVED_IN_FINAL + + // Transition graph: + switch (state) + { + case NSSNone: + // nothing to do + break; + case NSSSelectingMission: + GNetworkManager.DestroyAllObjects(); + break; + case NSSEditingMission: + DoAssert(_serverState == NSSSelectingMission); + // nothing to do + break; + case NSSAssigningPlayers: + break; + case NSSSendingMission: + DoAssert(_serverState == NSSAssigningPlayers); + // only bot client need to advance to PlayerAssigned state, normal clients are driven through DisplayClient logic + if (GetClientState(BOT_CLIENT) == NCSMissionAsked) + { + //RptF("### Server: SetClientState NCSPlayerAssigned to BOT_CLIENT"); + SetClientState(BOT_CLIENT, NCSPlayerAssigned); + } + + // reset _jipProcessed flag for all players + for (int i=0; i<_players.Size(); i++) + { + _players[i]->_jipProcessed=false; + } + break; + case NSSLoadingGame: + _serverTimeOfEstimatedEnd = _secondsToEstimatedEnd = 0; + for (int i=0; i<_players.Size(); i++) + { + ServerTimeMessage stmsg; + _serverTime = ::GetTickCount()-_serverTimeInitTickCount; // update _serverTime + stmsg._time = _serverTime; + stmsg._endTime = _serverTimeOfEstimatedEnd; + SendMsg(_players[i]->dpid, &stmsg, NMFGuaranteed | NMFHighPriority); + } + + for (int i=0; i<_players.Size(); i++) + { + CreatePlayerIndex(_players[i]->dpid); + } + break; + case NSSPlaying: + // recompute estimatedTimeOfEnd to be without time spent in briefing + _serverTime = ::GetTickCount() - _serverTimeInitTickCount; //make it fresh + if (_serverTimeOfEstimatedEnd) //recompute + { + _serverTimeOfEstimatedEnd = _serverTime + _secondsToEstimatedEnd; + for (int i=0; i<_players.Size(); i++) + { + // send _serverTime on each client + ServerTimeMessage stmsg; + _serverTime = ::GetTickCount()-_serverTimeInitTickCount; // update _serverTime + stmsg._time = _serverTime; + stmsg._endTime = _serverTimeOfEstimatedEnd; + SendMsg(_players[i]->dpid, &stmsg, NMFGuaranteed | NMFHighPriority); + } + } + break; + case NSSMissionAborted: + CallOnPlayerDisconnected(); + ResetGlobalEventHandlers(); + break; + } + + #if _ENABLE_MP + if (state == NSSAssigningPlayers && _serverState > NSSAssigningPlayers) + { + // cancel all messages - updates from last sessions, file transfers etc. + // !!! cannot do it in this way - some messages are important + // _server->CancelAllMessages(); + + // reset all camera information from previous session + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &p = *_players[i]; + p.cameraPosition = InvalidCamPos; + p.cameraPositionTime = TIME_MIN; + } + } + #endif + + if (state == NSSPlaying) _missionHeader._start = GlobalTickCount(); + + #if _ENABLE_MP + if (state == NSSMissionAborted && _serverState == NSSPlaying) + { + // end of mission - update log file + FILE *LogFile = GetNetworkManager().GetDedicatedServerLogFile(); + if ( LogFile ) + { + ParamFile f; + ParamClassPtr root = f.AddClass("Session"); + if (root) + { + root->Add("mission", _missionHeader.GetLocalizedMissionName()); + root->Add("island", _missionHeader._island); + root->Add("gameType", _missionHeader._gameType); + root->Add("duration", 0.001f * (GlobalTickCount() - _missionHeader._start)); + } + // append ranking statistics to logFile + QOStrStream out; + f.Save(out, 0, "\r\n"); + fwrite(out.str(), 1, out.pcount(), LogFile); + // flush is only at the end of mission (here) or some rare occasions + fflush(LogFile); + } + } + #endif + +#if _GAMES_FOR_WINDOWS + // Xbox Live - start / end the session + if (state == NSSPlaying) + { + if (_serverState != NSSPlaying) + { + _parent->StartSession(); + } + } + else if (_serverState == NSSPlaying) + { + _parent->EndSession(); + } + + if (_parent->GetSessionType() == STRanked) + { + // Ranked match - finish the session when the first game is finished + if (_serverState >= NSSPlaying && state < NSSPlaying) + { + Done(); + return; + } + // Ranked match - close the possibility to join and ask for arbitration + if (state >= NSSSendingMission && _serverState < NSSSendingMission) + { + LockSession(); + // ask all clients for arbitration + AskForArbitrationMessage msg; + msg._sessionNonce = _parent->GetSessionNonce(); + for (int i=0; i<_identities.Size(); i++) + { + int player = _identities[i].dpnid; + if (player != BOT_CLIENT) SendMsg(player, &msg, NMFGuaranteed); + } + } + } +#endif + + _serverState = state; + _serverStateTime = GlobalTickCount(); + _serverTimeOutSent = INT_MAX; // assume no value reported yet + if (state == NSSNone) return; // cannot send messages + + // DS selecting the mission - set the correct maxPlayers + if (state == NSSAssigningPlayers) + { + //{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + if (IsDedicatedServer()) + { +#if _GAMES_FOR_WINDOWS + // update of max. number of players + int perClient = 32000; + int round = 2; + ConstParamEntryPtr header = ExtParsMission.FindEntry("Header"); + if (header) + { + ConstParamEntryPtr entry = header->FindEntry("bandwidthPerClient"); + if (entry) perClient = *entry; + entry = header->FindEntry("playerCountMultipleOf"); + if (entry) round = *entry; + } + int maxPlayers = GetMaxPlayersSafe(perClient, round); + int GetDSPrivateSlots(); + int maxPrivate = GetDSPrivateSlots(); + saturateMin(maxPrivate, maxPlayers); + UpdateMaxPlayers(maxPlayers, maxPrivate); +#else + UpdateMaxPlayers(INT_MAX, 0); +#endif + } +#endif + //} + } + + // DS leaving the mission - reset the original maxPlayers + if (state == NSSSelectingMission) + { + //{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + if (IsDedicatedServer()) + { +#if _GAMES_FOR_WINDOWS + // update of max. number of players + int perClient = 32000; + int round = 1; + int maxPlayers = GetMaxPlayersSafe(perClient, round); + int GetDSPrivateSlots(); + int maxPrivate = GetDSPrivateSlots(); + saturateMin(maxPrivate, maxPlayers); + UpdateMaxPlayers(maxPlayers, maxPrivate); +#else + UpdateMaxPlayers(INT_MAX, 0); +#endif + } +#endif + //} + } + + { + // send to all players + ServerStateMessage msg; + msg._serverState = state; + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.clientState < NCSConnected) continue; + if (!IsDedicatedServer() || info.dpid!=BOT_CLIENT) // bot-client on a dedicated server has no identity + { + if (!FindIdentity(info.dpid)) continue; // prevent clients with unknown identity to proceed with the connection + } + SendMsg(info.dpid, &msg, NMFGuaranteed); + } + } + + UpdateMatchmakingDescription(true); + +#if _GAMES_FOR_WINDOWS + // set the properties and contexts for matchmaking + // - ServerState + GSaveSystem.SetContext(CONTEXT_GAME_SERVERSTATE, state); + // reset the values which have not yet sense + if (state < NSSAssigningPlayers) + { + // - MPType + GSaveSystem.SetContext(CONTEXT_GAME_MPTYPE, 0); + // - World + GSaveSystem.SetContext(CONTEXT_GAME_WORLD, 0); + // - Difficulty + GSaveSystem.SetContext(CONTEXT_GAME_DIFFICULTY, 0); + // - MPMission + GSaveSystem.SetContext(CONTEXT_GAME_MPMISSION, 0); + } + if (state < NSSPlaying) + { + // - TimeLeft + GSaveSystem.SetProperty(PROPERTY_GAME_TIMELEFT, 0); + } +#endif + + if (state == NSSEditingMission) + { + // No Load should be after mission was edited + bool DeleteSaveGames(); + DeleteSaveGames(); + bool DeleteWeaponsFile(); + DeleteWeaponsFile(); + } +} + +/*! +\patch 5111 Date 12/22/2006 by Jirka +- Fixed: DS - Mission voting results show correctly localized mission name for missions in addons +*/ + +void NetworkServer::MissionVotingEcho() +{ + const Voting *miss = _votings.Find(NCMTMission); + const Voting *diff = _votings.Find(NCMTDifficulty); + + // if the voting is no longer here, it has probably completed + if (diff && miss) + { + VotingMissionProgressMessage progress; + const AutoArray *diffValue = diff->GetValue(); + if (diffValue) + { + progress._diff = RString(diffValue->Data(),diffValue->Size()); + } + AutoArray order; + miss->GetOrder(order); + for (int i=0; i &missValue = order[i].vote->value; + int missVotes = order[i].count; + LocalizedString FindLocalizedBriefingName(RString path); + RString name = RString(missValue.Data(),missValue.Size()); + + RString mission = name; + RString dir; + + const char *ext = strrchr(name, '.'); + if (ext) mission = RString(name, ext - cc_cast(name)); + +#if _ENABLE_MISSION_CONFIG + ConstParamEntryPtr entry = (Pars >> "CfgMissions" >> "MPMissions").FindEntry(mission); + if (entry) + dir = (*entry) >> "directory"; + else +#endif + dir = RString("MPMissions\\") + name; + + LocalizedString displayName = FindLocalizedBriefingName(dir); + if (displayName._id.GetLength() == 0) + { + displayName = LocalizedString(LocalizedString::PlainText,name); + } + + progress._missions.Add(displayName); + progress._missionVotes.Add(missVotes); + } + for (int i=0; i<_players.Size(); i++) + { + const NetworkPlayerInfo &player = *_players[i]; + // notify all clients who might be interested + if (player.clientState >= NCSConnected && player.clientState<=NCSMissionSelected) + { + SendMsg(player.dpid, &progress, NMFGuaranteed); + } + } + } +} + +void NetworkServer::UpdateMatchmakingDescription(bool changedParams) +{ + +//{ QUERY & REPORTING SDK +#if _ENABLE_GAMESPY + ChangeStateQR(); +#endif +//} + + UpdateSessionDescription(); + + // update both broadcast and matchmaking + _timeLeftLastValueBcast = _timeLeftLastValue = GetSessionTimeLeft(); + _timeLeftLastTime = GlobalTickCount(); +} + +void NetworkServer::DisconnectPlayer(int dpnid, NetworkId playerPerson) +{ + PlayerIndex playerIndex = GetPlayerIndex(dpnid); + + // player is disconnecting from game, return ownership of objects to bot client + + AutoArray owned; // we cannot let SendMsg to manipulate _objects while iterating it + _objects.forEach([this,playerIndex,dpnid,&owned](NetworkObjectInfo *oInfo) + { + if (playerIndex>=0) oInfo->DeletePlayerObjectInfo(playerIndex,dpnid); + + for (int j=NMCUpdateFirst; jcurrentUpdate[j]; + if (info.from == dpnid) + { + info.from = BOT_CLIENT; + info.message = NULL; + } + } + + RescanBestPosition(oInfo); + + // owner of this object has disconnected - possible pendingOwner can take the full ownership + // or BOT_CLIENT should take it otherwise + if (oInfo->owner == dpnid) + { + owned.Add(oInfo->id); + } + }); + + + if (playerIndex>=0) + { + _indexToPlayerId.DeleteAt(playerIndex); + LogF("**** Player %d index %d removed, %d total",dpnid,int(playerIndex),_indexToPlayerId.Size()); + } + else + { + LogF("**** Player %d index not removed, %d total",dpnid,_indexToPlayerId.Size()); + } + + for (int i=0; i oInfo; + _objects.get(owned[i],oInfo); + if (!oInfo) continue; + if (oInfo->pendingOwner!=NO_CLIENT && oInfo->pendingOwner!=dpnid) + { + NetworkPlayerInfo *pInfo = GetPlayerInfo(oInfo->pendingOwner); + if (!pInfo) + { // new owner has probably disconnected meanwhile + oInfo->pendingOwner = BOT_CLIENT; + } + oInfo->owner = oInfo->pendingOwner; + } + else + { + oInfo->owner = BOT_CLIENT; + } + // not pending now + oInfo->pendingOwner = NO_CLIENT; + + _objects.get(owned[i],oInfo); + // change the owner + if (!oInfo->id.IsNull()) + { + ChangeOwnerMessage msg; + msg._creator = oInfo->id.creator; + msg._id = oInfo->id.id; + msg._owner = oInfo->owner; + msg._disconnected = oInfo->id == playerPerson; // mark player person to enable clean up on it + SendMsg(oInfo->owner, &msg, NMFGuaranteed); + + // destroy the person + if (msg._disconnected && _destroyDisconnected) + { + // playable person with AI disabled - destroy unit + Person *person = dyn_cast(_parent->GetObject(playerPerson)); + if (person) + { + Ref agent = person->Brain(); + + if (agent) + { + // Get out from vehicle + Transport *vehicle = agent->GetVehicleIn(); + if (vehicle) + { + agent->DoGetOut(vehicle, true, false); + } + } + + // detach brain (to avoid respawn during SetDamage) + person->SetBrain(NULL); + + // destroy person + person->SetDamage(1,true); + person->HideBody(); + // DeleteObject(person->GetNetworkId(), true); + } + } + + // owner is chosen so send waiting messages + for ( int i=0; i>oInfo->waitingMessages.Size(); i++ ) + { + WaitingMessageInfo *wMsgInfo = oInfo->waitingMessages[i]; + SendMsg(oInfo->owner, wMsgInfo->msg, wMsgInfo->type, NMFGuaranteed, NULL); + } + oInfo->waitingMessages.Clear(); + } + } + + _radioSubscribers.OnPlayerDisconnected(dpnid); + + CleanupPlayerMessage msg; + msg._dpnid = dpnid; + msg._creator = playerPerson.creator; + msg._id = playerPerson.id; + SendMsg(BOT_CLIENT, &msg, NMFGuaranteed); +} + +bool NetworkServer::IsPlayerOnChannel(int dpnid, int channel, int roleIndex2) +{ + if (channel==CCGlobal || channel==CCSystem) return true; + if (channel==CCDirect || channel==CCNone) return false; + + return false; +} + +bool IsEqualMarker(NetworkMessage *marker1, NetworkMessage *marker2); +bool IsEqualMarker(RString name, NetworkMessage *marker2); + +void NetworkServer::AddJIPMarkerInfo(NetworkMessage *marker, int channel, int from) +{ + for (int i=0; i<_jipMarkerInfos.Size(); i++) + { + if ( IsEqualMarker(marker, _jipMarkerInfos[i]._marker) ) + { + _jipMarkerInfos[i]._marker = marker; + return; + } + } + + JIPMarkerInfo &info = _jipMarkerInfos.Append(); + info._marker = marker; + info._channel = channel; + info._roleIndex = -1; //TODO +} + +void NetworkServer::RemoveJIPMarkerInfo(RString name) +{ + for (int i=0; i<_jipMarkerInfos.Size(); i++) + { + if ( IsEqualMarker(name, _jipMarkerInfos[i]._marker) ) + { + _jipMarkerInfos.Delete(i); + return; + } + } +} + +void NetworkServer::SendInitMessages(int dpnid) +{ + for (int i=0; i<_initMessages.Size(); i++) + { + if (_initMessages[i].msg) + { + SendMsg(dpnid, _initMessages[i].msg, _initMessages[i].type, NMFGuaranteed, NULL); + } + } + for (int i=0; i<_jipMarkerInfos.Size(); i++) + { + JIPMarkerInfo &info = _jipMarkerInfos[i]; + if ( IsPlayerOnChannel(dpnid, info._channel, info._roleIndex) ) + { + NetworkMessageMarkerCreate *msg = new NetworkMessageMarkerCreate; + msg->_channel = info._channel; + msg->_marker = info._marker; + SendMsg(dpnid, msg, NMTMarkerCreate, NMFGuaranteed, NULL); + } + } + AutoArray &_subscribers = _radioSubscribers._subscribers; + for (int i=0; i<_subscribers.Size(); i++) + { + if (_subscribers[i].dpnid == dpnid) continue; + SubscribeRadiosMessage msg; + msg._player = _subscribers[i].dpnid; + msg._frequences = _subscribers[i].frequencies; + SendMsg(dpnid, &msg, NMFGuaranteed); + } +} + +void NetworkServer::OnPlayerConnecting(int dpnid) +{ + NetworkPlayerInfo *info = GetPlayerInfo(dpnid); + PlayerIdentity *identity = FindIdentity(info->dpid); + DoAssert(identity); + if (identity) + { + ::OnPlayerConnecting(dpnid,identity->id,identity->playerid,info->name); + } +} + +void NetworkServer::OnPlayerConnecting(int dpnid, GameValuePar codeValue) +{ + NetworkPlayerInfo *info = GetPlayerInfo(dpnid); + PlayerIdentity *identity = FindIdentity(info->dpid); + DoAssert(identity); + if (identity) + { + ::OnPlayerConnecting(dpnid,identity->id,identity->playerid,info->name,codeValue); + } +} + +void NetworkServer::ObjectUpdateAll(NetworkObjectInfo * info, int dpnid, NetMsgFlags flags) +{ + for (int cls=NMCUpdateFirst; clscurrentUpdate[cls].message) + { + if (info->currentUpdate[cls].type==NMTUpdateClientInfoDpid) continue; + NetworkPlayerInfo *pInfo = GetPlayerInfo(dpnid); + if (pInfo) UpdateObject(pInfo, info, (NetworkMessageClass)cls, flags); + } + } +} + +void NetworkServer::OnClientStateChanged(int dpnid, NetworkClientState state) +{ + PROFILE_SCOPE_EX(onClS, network) + NetworkClientState oldState = NCSNone; + + NetworkPlayerInfo *pInfo = GetPlayerInfo(dpnid); + Assert(pInfo); + if (pInfo) + { + oldState = pInfo->clientState; + if (oldState == state) return; +#if _ENABLE_PERFLOG + RptF("*** Server: OnClientStateChanged %s %s -> %s", (const char *)pInfo->name, (const char *)FindEnumName(pInfo->clientState), (const char *)FindEnumName(state)); +#endif + if (state == NCSPlayerAssigned && oldState > NCSPlayerAssigned) + return; // FIX: problems with mission launching + pInfo->clientState = state; + } + + //RptF("Server: OnClientStateChanged %s to %s", pInfo ? (const char *)pInfo->name : "NULL", (const char *)FindEnumName(state)); + + PlayerIdentity *identity = FindIdentity(dpnid); + if (identity) + { +#if _USE_BATTL_EYE_SERVER +#if _ENABLE_STEAM_MATCHMAKING + if (state == NCSPlaying && identity->clientState != NCSPlaying) + { + _beIntegration.PlayerGoesInGame(identity->dpnid); + } + if (identity->clientState == NCSPlaying && state != NCSPlaying) + { + _beIntegration.PlayerGoesInLobby(identity->dpnid); + } +#endif +#endif + + identity->clientState = state; + } + + PlayerClientStateMessage msg; + msg._dpnid = dpnid; + msg._clientState = state; + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &player = *_players[i]; + if (player.dpid != dpnid && player.clientState >= NCSConnected) + SendMsg(player.dpid, &msg, NMFGuaranteed); + } + + switch (state) + { + case NCSLoggedIn: + if (pInfo && _serverState >= NSSAssigningPlayers) + { + // send mission info + SendMissionInfo(pInfo->dpid); + pInfo->missionFileValid = false; + pInfo->paramFileValid = GetMissionParameters().GetLength() == 0; + } + if (_serverState == NSSPlaying) + { + // if game is already in progress, send how long is played already + NetworkCommandMessage msg; + msg._type = NCMTMissionTimeElapsed; + int timeElapsed = GlobalTickCount() - _missionHeader._start; + msg._content.Write(&timeElapsed, sizeof(timeElapsed)); + SendMsg(dpnid, &msg, NMFGuaranteed); + } + if (_serverState == NSSSelectingMission) + { + // new clients should get mission voting echo as necessary, so that they can see voting + MissionVotingEcho(); + } + break; + case NCSPlayerAssigned: + if (_serverState >= NSSSendingMission) + { + // send mission + SendMissionFile(dpnid); + } + { + PlayerIndex pIndex = CreatePlayerIndex(dpnid); + if (pInfo && _serverState >= NSSLoadingGame) + { + OnPlayerConnecting(pInfo->dpid); + + pInfo->_jipProcessed = true; + // load game + DoAssert(pInfo->clientState == NCSMissionReceived); + + _objects.forEach([pIndex,dpnid](NetworkObjectInfo *oInfo) + { + oInfo->CreatePlayerObjectInfo(pIndex,dpnid); + }); + + // send the info about network objects need to be created + MissionStatsMessage stats; + stats._toCreate = stats._toUpdate = _objects.card(); + SendMsg(dpnid, &stats, NMFGuaranteed); + + // create all game objects + //RptF("*** Sending world state ***"); + //RptF("1. all except AI objects"); + // 1. all except AI objects + + Vector3 camPos = pInfo->cameraPosition; + + _objects.forEach([pIndex,pInfo,dpnid,camPos,this](NetworkObjectInfo *info) + { + // update object info + NetworkPlayerObjectInfo *poInfo = info->GetPlayerObjectInfo(pIndex,dpnid); + + NetworkMessageType type = info->create.type; + // ClientInfo is not the full featured network object, so it should be handled different way + if ( type == NMTNone && info->currentUpdate[NMCUpdatePosition].type == NMTUpdateClientInfoDpid ) + return; + if (poInfo->updating) return; // some objects are already synced, e.g. selectPlayer done from onPlayerConnecting + DoAssert(info->create.message); +#if 0 + if (!info->create.message) + { + LogF(" i=%d, info->create.type=%d message=%x", i, info->create.type, info->create.message.GetRef()); + } + static NetworkId debugNetworkId; + if (debugNetworkId==info->id) + { + _asm nop; + } +#endif + + if (info->object.NotNull()) + { + auto bestPosition = info->BestPosition(this); + if (bestPosition._updateDistanceSquare(bestPosition._updateDistance)) + { + return; + } + } + } + + SendCreateMessage(dpnid,*info, poInfo); + poInfo->updating = true; + pInfo->markAsUpdating(poInfo); + //RptF(" %s: %d:%" OID_FORMAT"", cc_cast(GetMsgTypeName(type)), info->id.creator.CreatorInt(), info->id.id); + }); + + //RptF("*** World state sent ***"); + // update all game objects + _objects.forEach([pIndex,dpnid,this](NetworkObjectInfo *info) + { + if (info->owner==dpnid) + { + return; + } + NetworkPlayerObjectInfo *poInfo = info->GetPlayerObjectInfo(pIndex,dpnid); + if (poInfo->updating) ObjectUpdateAll(info, dpnid, NMFGuaranteed); + }); + // send delayed messages + SendInitMessages(dpnid); + // CheckInitMessages(_initMessages, "after NetworkComponent::SendMsg"); + } + else + { + DoAssert(_objects.card()==0); + _objects.reset(); + _deletedObjects.reset(); +#if DIAG_MP_OBJECT_LIFE + GObjLifeJournal.Clear(); +#endif + } + if (_serverState >= NSSLoadingGame) + { + SetClientState(dpnid, NCSGameLoaded); + } + } + break; + case NCSGameLoaded: + if (dpnid == BOT_CLIENT && _serverState < NSSPlaying) + { + // game is loaded, can start the game + SetServerState(NSSPlaying); + } + break; + case NCSPlaying: + if (pInfo) + { // clients should both send the bankscount info + if ( pInfo->hashes.bankInfoTimeout==0 && pInfo->hashes.banksCount<0 ) + { + pInfo->hashes.bankInfoTimeout = GlobalTickCount() + 10000; //10 seconds + } + } + if (pInfo && oldState != NCSPlaying && !GNetworkPlayerConnected.GetNil()) + { + GameState *state = GWorld->GetGameState(); + if (state) + { + GameVarSpace vars(false); + int gshandle = state->BeginContext(&vars); + PlayerIdentity *identity = FindIdentity(pInfo->dpid); + RString uid = identity ? identity->id : RString(); + int id = identity ? identity->playerid : -1; + DoAssert(identity); + state->VarSetLocal("_id", safe_cast(id), true); + state->VarSetLocal("_uid", uid, true); + state->VarSetLocal("_name", pInfo->name, true); + +#if USE_PRECOMPILATION + if (GNetworkPlayerConnected.GetType() == GameCode) + { + GameDataCode *code = static_cast(GNetworkPlayerConnected.GetData()); + if (code->IsCompiled() && code->GetCode().Size() > 0) + state->Evaluate(code->GetString(), code->GetCode(), GameState::EvalContext::_default, GWorld->GetMissionNamespace()); // mission namespace + } + else +#endif + if (GNetworkPlayerConnected.GetType() == GameString) + { + // make sure string is not destructed while being evaluated + RString code = GNetworkPlayerConnected; + if (code.GetLength() > 0) + state->EvaluateMultiple(code, GameState::EvalContext::_default, GWorld->GetMissionNamespace()); // mission namespace + } + state->EndContext(gshandle); + } + } + if (pInfo) pInfo->joined = Glob.time; + + { // send also current clock + NetworkCommandMessage msg; + Glob.clock.Write(msg._content); + Glob.clockWeather.Write(msg._content); + msg._type = NCMTMissionDate; + SendMsg(dpnid, &msg, NMFGuaranteed); + } + { // [F10] send also current weather + date so the client applies the server clock + ApplyWeatherMessage wmsg; + GLandscape->TranferMsg(wmsg); + SendMsg(dpnid, &wmsg, NMFGuaranteed); + } + break; + case NCSGameFinished: + // disconnected from game + if (_serverState == NSSPlaying) + { + NetworkId playerPerson; + if (pInfo) playerPerson = pInfo->person; + DisconnectPlayer(dpnid, playerPerson); + } + break; + } + + if (pInfo && oldState == NCSPlaying && state != NCSPlaying && _serverState==NSSPlaying) + { + OnPlayerDisconnected(pInfo); + } +} + +void NetworkServer::KickAllPlayers(int minBuild) +{ + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &player = *_players[i]; + if (player.dpid!=BOT_CLIENT) + { + if (minBuild>0) + { + const PlayerIdentity *ident = FindIdentity(player.dpid); + if (!ident || ident->build<0 || ident->build>=minBuild) continue; + } + KickOff(player.dpid,KOROther, "Game Loaded from MP Save, please reconnect!"); + } + } +} + +NetworkClientState NetworkServer::GetClientState(int dpid) +{ + NetworkPlayerInfo *info = GetPlayerInfo(dpid); + if (info) return info->clientState; + else return NCSNone; +} + +void NetworkServer::SetClientState(int dpnid, NetworkClientState state) +{ +// RptF("### Server: Set client state"); + + NetworkPlayerInfo *info = GetPlayerInfo(dpnid); + Assert(info); + if (info) + { + //RptF(" player %s, state %s -> %s", (const char *)info->name, (const char *)FindEnumName(info->clientState), (const char *)FindEnumName(state)); + info->clientState = state; + } + + PlayerIdentity *identity = FindIdentity(dpnid); + if (identity) + { +#if _USE_BATTL_EYE_SERVER +#if _ENABLE_STEAM_MATCHMAKING + if (state == NCSPlaying && identity->clientState != NCSPlaying) + { + + _beIntegration.PlayerGoesInGame(identity->dpnid); + } + if (identity->clientState == NCSPlaying && state != NCSPlaying) + { + _beIntegration.PlayerGoesInLobby(identity->dpnid); + } +#endif +#endif + NetLog("Client %s - changed state from %s to %s",cc_cast(identity->name),cc_cast(FindEnumName(identity->clientState)),cc_cast(FindEnumName(state))); + identity->clientState = state; + } + + ClientStateMessage msg1; + msg1._clientState = state; + SendMsg(dpnid, &msg1, NMFGuaranteed); + + PlayerClientStateMessage msg; + msg._dpnid = dpnid; + msg._clientState = state; + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &player = *_players[i]; + if (player.dpid != dpnid && player.clientState >= NCSConnected) + SendMsg(player.dpid, &msg, NMFGuaranteed); + } +} + +RString NetworkServer::GetPlayerName(int dpid) +{ + NetworkPlayerInfo *info = GetPlayerInfo(dpid); + Assert(info); + if (info) return info->name; + else return "Unknown player"; +} + +NetworkId NetworkServer::GetPlayerPerson(int dpid) +{ + NetworkPlayerInfo *info = GetPlayerInfo(dpid); + Assert(info); + if (info) return info->person; + else return NetworkId(); +} + +Object *NetworkServer::GetPlayerTarget(int dpid) +{ + NetworkPlayerInfo *info = GetPlayerInfo(dpid); + if (!info) return nullptr; + + NetworkObject *obj = GetNetworkManager().GetObject(info->_clientInput->GetCursorObject()); + return dyn_cast(obj); +} + +void NetworkServer::ServerSelectPlayer(int dpid, const NetworkId &id) +{ + NetworkPlayerInfo *info = GetPlayerInfo(dpid); + if (info) + { + info->person = id; + // make sure new person object is known to the client + NetworkObjectInfo *oInfo = GetObjectInfo(id); + DoAssert(oInfo); + if (oInfo) + { + PlayerIndex playerIndex = GetPlayerIndex(dpid); + NetworkPlayerObjectInfo *pInfo = oInfo->GetPlayerObjectInfo(playerIndex,dpid); + if (!pInfo->updating && oInfo->owner!=dpid) + { + if (oInfo->create.message) + { + SendCreateMessage(dpid,*oInfo,pInfo); + ObjectUpdateAll(oInfo, dpid, NMFGuaranteed); + pInfo->updating = true; + info->markAsUpdating(pInfo); + } + } + } + } +} + +Vector3 NetworkServer::GetCameraPosition(int dpid) +{ + NetworkPlayerInfo *info = GetPlayerInfo(dpid); + Assert(info); + if (info) return info->cameraPosition; + else return VZero; +} + +NetworkObject *NetworkServer::GetObject(const NetworkId &id) +{ + if (id.creator == CreatorId(0)) return NULL; + else if (id.creator == CreatorId(STATIC_OBJECT)) + { + ObjectId oid; + oid.Decode(id.id); + return GLandscape->GetObject(oid); + } + + // Message references (OLink) are resolved through NetworkServer while a + // dedicated server decodes client requests. The old stub made every such + // request fail before its handler ran, including inventory rotation. + NetworkObjectInfo *info = GetObjectInfo(id); + return info ? info->object.GetLink() : NULL; +} + +//! Subsidiary structure for sorting messages by error +struct UpdateObjectInfo +{ + Ref msg; + //! Object info + NetworkObjectInfo *oInfo; + //! Player object info + NetworkPlayerObjectInfo *poInfo; + //! Message class type + NetworkMessageClass cls; + //! Error (difference), distance adjusted + float error; + //! Error (difference) + float errorNoCoef; + //! Critical update + bool criticalUpdate; + + UpdateObjectInfo() + { + oInfo = NULL; + poInfo = NULL; + } +}; +TypeIsMovableZeroed(UpdateObjectInfo) + +//! Compare player object infos by error +static int CmpPlayerObjects(const UpdateObjectInfo *info1, const UpdateObjectInfo *info2) +{ + if (info2->error > info1->error) return +1; + if (info2->error < info1->error) return -1; + return 0; + // following is not the same when both errors are INF, as INF-INF is NaN + //return sign(info2->error - info1->error); +} + +void NetworkServer::KickOff(int dpnid, KickOffReason reason, const char *reasonStr) +{ + RString format; + switch (reason) + { + case KORBattlEye: format = Format("Player %%s kicked off by BattlEye: %s", reasonStr); break; + case KORKick: format = LocalizeString(IDS_MP_KICKED); break; + case KORBan: format = LocalizeString(IDS_MP_BANNED); break; + } + PlayerIdentity *id = FindIdentity(dpnid); + if (id) + { + if (id->destroy) + { + LogF("%s: KickOff in progress, new request ignored",(const char *)id->name); + return; + } + if (format.GetLength() > 0) + { + RString message = Format(format,(const char *)id->name); + RefArray dummy; + if (!ChannelDisabled(CCSystem)) + GNetworkManager.Chat(CCSystem,NULL,dummy,message); + GChatList.Add(CCSystem, NULL, message, false, true); + } + id->destroy = true; + id->destroyTime = Glob.uiTime + 15; // destroy player after 15 seconds if no system message arrive + } + // mark player kickoff is initiated + for (int i=0; i<_players.Size(); i++) + { + if (_players[i]->dpid==dpnid) _players[i]->kickedOff = true; + } + NetTerminationReason netReason = NTROther; + switch (reason) + { + case KORKick: netReason = NTRKicked; break; + case KORBan: netReason = NTRBanned; break; + case KORFade: netReason = NTROther; break; + case KORAddon: netReason = NTRMissingAddon; break; + case KORBadCDKey: netReason = NTRBadCDKey; break; + case KORCDKeyInUse: netReason = NTRCDKeyInUse; break; + case KORBattlEye: netReason = NTRBattlEye; break; + case KORAuthTimeOut: netReason = NTRAuthTimeOut; break; + } + _server->KickOff(dpnid,netReason,reasonStr); +} + +void NetworkServer::Ban(int dpnid) +{ + // add to ban list + const PlayerIdentity *identity = FindIdentity(dpnid); + if (!identity) return; + _banListLocal.AddUnique(identity->id); + + // save ban list + RString banList = GetUserDirectory() + RString("ban.txt"); + SaveBanList(banList, _banListLocal); + + // kick off + _server->KickOff(dpnid,NTRBanned); +} + +void NetworkServer::UpdateBanListSecure(const FindArray &keys, const Array &signature) +{ + #if _VERIFY_CLIENT_KEY + Assert(VerifySignedKeys(keys,signature)); // signature already verified + if (keys.Size()>_banListSecure.keys.Size()) + { + _banListSecure.keys = keys; + _banListSecure.signature = signature; + // output the secure key list + RString banSecureFilename = GetUserDirectory() + RString("banSecure.txt"); + RString banListContent = PrintSignedKeys(_banListSecure.keys,_banListSecure.signature); + QOFStream f(banSecureFilename); + f << cc_cast(banListContent); + f.close(); + } + #endif +} + + +#if LOG_ERRORS +//! diagnostic logs of error (difference) between messages +/* +static void LogError +( + NetworkMessageType type, + int dpid1, NetworkMessage *msg1, + int dpid2, NetworkMessage *msg2 +) +{ + if (type < 0 || type >= NMTN) return; + NetworkMessageFormat *format = GMsgFormats[type]; + + float dt = msg1->time - msg2->time; + float error = ( + msg1->CalculateErrorStatic(msg2) + + msg1->CalculateErrorDynamic(msg2) + CalculateErrorTime(type, msg1, msg2) + ); + + if (error > 0) + DiagLogF + ( + " - %s: %g * %g = %g", (const char *)format->GetItem(i).name, + coef, value, error + ); + } +} +*/ +#endif + +#if _ENABLE_REPORT + #define LOG_QUEUE_PROGRESS 0 +#endif + +/*! +\patch_internal 1.01 Date 6/26/2001 by Ondra. Added hacked version player kickoff. +*/ +void NetworkServer::CheckFadeOut() +{ +#if _ENABLE_STEAM_IDENTITY && defined(_WIN64) + for (int i=0; i<_players.Size(); i++) + _players[i]->_steamValidate.HandleTimeout(); +#endif + + if (_serverState == NSSPlaying) + { + for (int i=0; i<_identities.Size(); i++) + { + PlayerIdentity &identity = _identities[i]; +/* +//testing only + static volatile bool doIt=false; + if (doIt) + { + if (identity.dpnid!=2) + KickOff(identity.dpnid,KORBattlEye, "Hello boy!"); + } +*/ + if (Glob.uiTime>=identity.kickOffTime) + { + switch (identity.kickOffState) + { + case KOWait: + { + // transmit explanation + identity.kickOffState = KOWarning; + identity.kickOffTime = Glob.uiTime; + RString string = LocalizeString(IDS_FADE_AWAY); + RString senderName = identity.GetName(); + RefArray dummy; + if (!ChannelDisabled(CCSystem)) + GNetworkManager.Chat(CCSystem,senderName,dummy,string); + GChatList.Add(CCSystem, senderName, string, false, true); + } + break; +//((EXE_CRC_CHECK + case KOExe: +//))EXE_CRC_CHECK + case KOWarning: + if (Glob.uiTime>identity.kickOffTime+15) + { +//((EXE_CRC_CHECK + bool wasExe = identity.kickOffState==KOExe; +//))EXE_CRC_CHECK + identity.kickOffState = KODone; + KickOff(identity.dpnid,KORFade); +//((EXE_CRC_CHECK + if (wasExe) + { + RString format = LocalizeString(IDS_MP_VALIDERROR_1); + + RString message = Format(format, cc_cast(identity.GetName())); + RefArray dummy; + if (!ChannelDisabled(CCSystem)) + GNetworkManager.Chat(CCSystem,"",dummy,message); + GChatList.Add(CCSystem, NULL, message, false, true); +#if _ENABLE_DEDICATED_SERVER + ConsoleF("%s", cc_cast(message)); +#endif + } +//))EXE_CRC_CHECK + UpdateMatchmakingDescription(false); + } + break; + default: + Fail("KickOffState!"); + case KODone: + break; + } + } + } + } +} + +/*! +\patch_internal 1.50 Date 4/8/2002 by Jirka +- Fixed: No limits for server - bot client communication. +\patch 1.53 Date 4/23/2002 by Jirka +- Fixed: Bandwidth estimation on dedicated server +*/ +void NetworkServer::EstimateBandwidth(NetworkPlayerInfo &pInfo, int nPlayers, int &nMsgMax, int &nBytesMax) +{ + if (pInfo.dpid == BOT_CLIENT || pInfo._isLocal) + { + nBytesMax = INT_MAX; + nMsgMax = INT_MAX; + + pInfo._ping.Sample(0); + pInfo._bandwidth.Sample(INT_MAX); + } + else + { + int nMsg = 0, nBytes = 0, nMsgG = 0, nBytesG = 0; + + // calculate quotas + _server->GetSendQueueInfo(pInfo.dpid, nMsg, nBytes, nMsgG, nBytesG); + if (nMsgG > 0) + { + nMsg += nMsgG; + nBytes += nBytesG; + } + + int minBandwidth; +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + if (IsDedicatedServer()) + { + nMsgMax = DSMaxMsgSend; + minBandwidth = DSMinBandwidth; + } + else +#endif +//} + { + nMsgMax = MaxMsgSend; + minBandwidth = MinBandwidth; + } + int bandwidth = 100; // add 800 bps as a basic bandwidth + #if _ENABLE_MP + int latencyMS = 0, throughputBPS = 0; + if (_server->GetConnectionInfo(pInfo.dpid, latencyMS, throughputBPS)) + { + // nBytesMax += 1.25 * throughputBPS; + bandwidth += throughputBPS; + bandwidth += throughputBPS >> 2; // throughputBPS / 4 + } + #endif + // assume server upload bandwidth is at least MinBandwidth + if (nPlayers > 0) + { + int lowLevelMaxBandwidth = INT_MAX; + _server->GetConnectionLimits(lowLevelMaxBandwidth); + // 8 is conversion from bps to Bps + int minBandwidthPerPlayer = minBandwidth/(8*nPlayers); + + // min limit must never be higher than low-level max limit + saturateMin(minBandwidthPerPlayer, lowLevelMaxBandwidth); + saturate(bandwidth, minBandwidthPerPlayer, MaxBandwidth/8); + if (bandwidth>lowLevelMaxBandwidth) bandwidth = lowLevelMaxBandwidth; + } + + // float frmDur = GEngine->GetAvgFrameDuration(); + // LogF(" avgFrame: %.3f", frmDur); + nBytesMax = toInt(0.001 * GEngine->GetAvgFrameDuration() * bandwidth); + + nBytesMax -= nBytes; + nMsgMax -= nMsg; + + { + // statistics + int latencyMSRaw = 0, throughputBPSRaw = 0; + #if _ENABLE_MP + _server->GetConnectionInfoRaw(pInfo.dpid, latencyMSRaw, throughputBPSRaw); + #endif + pInfo._ping.Sample(latencyMSRaw); + pInfo._bandwidth.Sample(throughputBPSRaw); + } + + // write statistics +#if _ENABLE_CHEATS + if (outputLogs) LogF("Server to %s: Limit (%d, %d)", (const char *)pInfo.name, nBytesMax, nMsgMax); +#endif + } +} + +int NetworkServer::GetBandwidthEstimation(int dpnid, int nPlayers) +{ + int bandwidth; + if (dpnid == BOT_CLIENT) + { + bandwidth = INT_MAX; + } + else + { + int minBandwidth; +#if _ENABLE_DEDICATED_SERVER + if (IsDedicatedServer()) minBandwidth = DSMinBandwidth; + else +#endif + { + minBandwidth = MinBandwidth; + } + bandwidth = 100; // add 800 bps as a basic bandwidth +#if _ENABLE_MP + int latencyMS = 0, throughputBPS = 0; + if (_server->GetConnectionInfo(dpnid, latencyMS, throughputBPS)) + { + // nBytesMax += 1.25 * throughputBPS; + bandwidth += throughputBPS; + bandwidth += throughputBPS >> 2; // throughputBPS / 4 + } +#endif + // assume server upload bandwidth is at least MinBandwidth + if (nPlayers > 0) + { + // 8 is conversion from bps to Bps + int minBandwidthPerPlayer = minBandwidth/(8*nPlayers); + + int lowLevelMaxBandwidth = INT_MAX; + _server->GetConnectionLimits(lowLevelMaxBandwidth); + // min limit must never be higher than low-level max limit + saturateMin(minBandwidthPerPlayer, lowLevelMaxBandwidth); + saturate(bandwidth, minBandwidthPerPlayer, MaxBandwidth/8); + } + } + return bandwidth; +} + + +void NetworkServer::SendCreateMessage( int dpnid, NetworkObjectInfo &info, NetworkPlayerObjectInfo *poInfo ) +{ + if (DebugMeBoy(info.id)) + { + LogF("*** DebugMeBoy: {%d:%" OID_FORMAT"} Create for %d", info.id.creator.CreatorInt(), info.id.id, dpnid); + } + SendMsg(dpnid, info.create.message, info.create.type, NMFGuaranteed, poInfo); +} + +void NetworkServer::OnHierParentChange( Entity* veh ) +{ + const Entity *root = veh; + while (root->GetHierarchyParent()) root = root->GetHierarchyParent(); + NetworkId id = root->GetNetworkId(); + NetworkObjectInfo *rootInfo = GetObjectInfo(id); + if (!rootInfo) return; + NetworkObjectInfo *oInfo = GetObjectInfo(veh->GetNetworkId()); + if (!oInfo) return; + + auto bestPosNew = rootInfo->BestPosition(); + auto bestPosOld = oInfo->BestPosition(); + + oInfo->_updInfo = bestPosNew; + _objects.onPosChanged(oInfo,bestPosOld,bestPosNew); + + UpdateChildrenPos(veh); +} + + +float NetworkServer::CalculateErrorCoef(const NetworkPlayerInfo &pInfo, const NetworkObjectInfo &oInfo, bool updating) +{ + const float errorCoefMyVehicle = 2.0f; + const float errorCoefMyBody = 10.0f; + + const NetworkCurrentInfo &update = oInfo.currentUpdate[NMCUpdateGeneric]; + if (update.message && !pInfo.person.IsNull()) + { + if (pInfo.person==oInfo.id) + { + return errorCoefMyBody; + } + + if (IsUpdateTransport(update.type)) + { + // check if player is not inside given vehicle + NetworkMessageUpdateTransport *msg = static_cast(update.message.GetRef()); + if (msg) + { +#if _VBS2 + if(msg->_UpdateCoef > 0.0f ) + return msg->_UpdateCoef; +#endif + if (msg->_driver == pInfo.person) return errorCoefMyVehicle; + for (int i=0; i_manCargo.Size(); i++) + { + if (msg->_manCargo[i] == pInfo.person) return errorCoefMyVehicle; + } + } + } + else if (update.type == NMTUpdateTurret) + { + // check if player is not inside given turret + NetworkMessageUpdateTurret *msg = static_cast(update.message.GetRef()); + if (msg) + { + if (msg->_gunner == pInfo.person) return errorCoefMyVehicle; + } + } + } + + if (!oInfo.object) + { + // no object: this must be UpdateClientInfoDpid + DoAssert(oInfo.currentUpdate[NMCUpdatePosition].type==NMTUpdateClientInfoDpid); + return 1; + } + + //auto pos = oInfo.BestPosition(); + NetworkObject *rootObj = oInfo.object; + Entity *root = dyn_cast(rootObj); + if (root) + { + while (root->GetHierarchyParent()) root = root->GetHierarchyParent(); + rootObj = root; + } + Vector3 pos = rootObj->GetCurrentPosition(); + float updateDistance = rootObj->UpdateDistance(); + + // calculate the error coef by object's position + return oInfo.object->CalculateErrorCoef(pos, pInfo.cameraPosition, updateDistance, updating); +} + + +/*! +\patch_internal 1.12 Date 08/07/2001 by Jirka +- Added: error calculation diagnostics +\patch 5115 Date 1/8/2007 by Jirka +- Fixed: MP - fire effects sometimes did not transferred (especially for JIP players) +*/ + +#if DEBUG_GIVEN_NETWORK_ID +bool DebugMeBoy(NetworkId id) +{ + static NetworkId myId(CreatorId(2),6); + return (id == myId); +} + +bool DebugMeBoy(NetworkMessage *msg, NetworkMessageType type) +{ + static NetworkMessageType debugType = NMTUpdatePositionMan; + if (type==debugType) + { + auto *msg1 = static_cast(msg); + return DebugMeBoy(NetworkId(msg1->_objectCreator, msg1->_objectId)); + } + return false; +} + +#endif + +PlayerIndex NetworkServer::CreatePlayerIndex(int pid) +{ + PlayerIndex pIndex = GetPlayerIndex(pid); + if (pIndex<0) + { + pIndex = (PlayerIndex)_indexToPlayerId.Add(pid); + LogF("**** Player %d index %d added",pid,int(pIndex)); + } + else + { + LogF("**** Player %d index %d used, %d total",pid,int(pIndex),_indexToPlayerId.Size()); + } + return pIndex; +} + +void NetworkServer::OnStopUpdating(NetworkObjectInfo &oInfo, NetworkPlayerInfo &pInfo, NetworkPlayerObjectInfo &poInfo) +{ + // send a destroy message + DeleteObjectMessage msg; + msg._creator = oInfo.id.creator; + msg._id = oInfo.id.id; + + SendMsg(pInfo.dpid, &msg, NMFGuaranteed); + + for (int i=0; i &objects, NetworkPlayerInfo &pInfo) +{ + PROFILE_SCOPE_EX(crOLS, network) + // calculate errors and place object in list sorted by error + + PlayerIndex playerIndex = GetPlayerIndex(pInfo.dpid); + DoAssert(playerIndex>=0); + DoAssert(pInfo.dpid!=BOT_CLIENT); // this function cannot be used for bot client, as it implements player bubble + + NetworkPlayerInfo::UpdatingList updatingNew; + + auto handleUpdatingObject = [playerIndex,&pInfo,this,&objects,&updatingNew](NetworkObjectInfo *info) + { + NetworkObjectInfo &oInfo = *info; + + NetworkPlayerObjectInfo *poInfo = oInfo.GetPlayerObjectInfo(playerIndex,pInfo.dpid); + + float errCoef = CalculateErrorCoef(pInfo, oInfo, poInfo->updating); + if (errCoef < 0) return; + + bool needsUpdate = errCoef>0 || pInfo.dpid==oInfo.owner; + + if (needsUpdate!=poInfo->updating) + { + if (DebugMeBoy(oInfo.id)) + { + LogF("*** DebugMeBoy: {%d:%" OID_FORMAT"} Updating for %d state %d", oInfo.id.creator.CreatorInt(), oInfo.id.id, pInfo.dpid, needsUpdate); + } + if (needsUpdate) + { + // ClientInfoObject has no create message only NMTUpdateClientInfoDpid (position update) + if (oInfo.create.message.NotNull()) + { + SendCreateMessage(pInfo.dpid,oInfo,poInfo); + ObjectUpdateAll(info, pInfo.dpid, NMFGuaranteed); + } + } + else + { + // we could also skip this else branch and leave the cleanup to the pInfo._updating loop below + DoAssert(pInfo._updating.CheckIntegrity()); + OnStopUpdating(oInfo, pInfo, *poInfo); + pInfo._updating.Delete(poInfo); + DoAssert(pInfo._updating.CheckIntegrity()); + } + + poInfo->updating = needsUpdate; + } + + + if (!needsUpdate) return; + + pInfo.markAsUpdating(poInfo,updatingNew); + + for (int j=NMCUpdateFirst; jupdates[j]; + + if (oInfo.owner == pInfo.dpid) + { + if (pInfo.dpid!=BOT_CLIENT && info.from==BOT_CLIENT) + { + // bot-client may override owner information + } + else + { + continue; + } + } + + float error; + // error without distance coef + float errorNoCoef; + if (!update.lastSentMsg) + { + errorNoCoef = info.message->CalculateErrorInitial(); + error = errCoef * errorNoCoef; +#if LOG_ERRORS + DiagLogF("Initial error for %s %d:%" OID_FORMAT" to %d", NetworkMessageTypeNames[info.type], oInfo.id.creator.CreatorInt(), oInfo.id.id, pInfo.dpid); + DiagLogF(" - error %.3f * %.3f = %.3f", errCoef, errorNoCoef, error); +#endif + } + else + { + NetworkMessage *msg1 = info.message; + NetworkMessage *msg2 = update.lastSentMsg; + + DoAssert(!msg1->HasDiff()); + DoAssert(!msg2->HasDiff()); + + if (!update.errorValid) + { + /* + if (info.type==NMTUpdateMan) + { + __asm nop; + } + */ + + update.errorStatic = msg1->CalculateErrorStatic(msg2); + update.errorValid = true; + } + float dt = msg1->time - msg2->time; + float errorDynamic = msg1->CalculateErrorDynamic(msg2, dt); + errorNoCoef = error = update.errorStatic + errorDynamic + CalculateErrorTime(info.type, msg1, msg2); + +#if LOG_ERRORS + if (!(error * errCoef < LogErrorLimit)) // handle NaN well + { + DiagLogF + ( + "Object %s %d:%" OID_FORMAT" - update to %d", + NetworkMessageTypeNames[info.type], oInfo.id.creator.CreatorInt(), oInfo.id.id, + pInfo.dpid + ); + DiagLogF(" - error %.3f = stat %.3f + dyn %.3f", error, update.errorStatic, errorDynamic); + DiagLogF(" - error %.3f * %.3f = %.3f", errCoef, error, errCoef * error); + if (pInfo.cameraPosition[1]!=-FLT_MAX) + { + DiagLogF + ( + " - camera [%.0f, %.0f, %.0f]", + pInfo.cameraPosition[0], pInfo.cameraPosition[1], pInfo.cameraPosition[2] + ); + } + + msg1->CalculateErrorStatic(msg2); + msg1->CalculateErrorDynamic(msg2, dt); + CalculateErrorTime(info.type, msg1, msg2); + } +#endif + error *= errCoef; + } + +#if DEBUG_GIVEN_NETWORK_ID + if (DebugMeBoy(oInfo.id) && error>0) + { + float msgTime = update.lastSentMsg ? update.lastSentMsg->time.toFloat() : 0; + LogF("*** DebugMeBoy: {%d:%" OID_FORMAT"}, Error: %.2f, lastMsgTime: %.3f", oInfo.id.creator.CreatorInt(), oInfo.id.id, error, msgTime); + } +#endif + + // note: following condition seems to be identical to error>MinErrorToSend + // but it is different when error is NaN + if (!(error <= MinErrorToSend) && !(errorNoCoef <= MinErrorToSendNear)) + { + int index = objects.Add(); + // objects[index].pInfo = &pInfo; + objects[index].oInfo = &oInfo; + objects[index].poInfo = poInfo; + objects[index].cls = (NetworkMessageClass)j; + objects[index].error = error; + objects[index].errorNoCoef = errorNoCoef; + objects[index].criticalUpdate = false; + + #if _DEBUG + #define NOP __asm {nop} + switch (info.type) + { + case NMTUpdateMan: NOP; break; + case NMTUpdatePositionMan: NOP; break; + case NMTUpdateVehicleAI: NOP; break; + case NMTUpdateDamageVehicleAI: NOP; break; + case NMTUpdateDamageVehicle: NOP; break; + case NMTUpdateObject: NOP; break; + case NMTUpdateDamageObject: NOP; break; + } + if (update.lastSentMsg) + { + // tracing opportunity + // place breakpoint depending on message type + switch (info.type) + { + case NMTUpdateMan: NOP; break; + case NMTUpdatePositionMan: NOP; break; + case NMTUpdateVehicleAI: NOP; break; + case NMTUpdateDamageVehicleAI: NOP; break; + case NMTUpdateDamageVehicle: NOP; break; + case NMTUpdateObject: NOP; break; + case NMTUpdateDamageObject: NOP; break; + } + NetworkMessage *msg1 = info.message; + NetworkMessage *msg2 = update.lastSentMsg; + float errorStatic = msg1->CalculateErrorStatic(msg2); + float dt = msg1->time - msg2->time; + float errorDynamic = msg1->CalculateErrorDynamic(msg2, dt); + (void)errorStatic; + (void)errorDynamic; + NOP; + } + + #endif + } + } + }; + + _objects.forEachInBubble(pInfo.cameraPosition, handleUpdatingObject); + + // only items in updatingNew should be kept as _updating, the rest needs to be marked as no longer updating + DoAssert(pInfo._updating.CheckIntegrity()); + AUTO_STATIC_ARRAY(NetworkObjectInfo *, owned, 32); + for (NetworkPlayerObjectInfo *poInfo=pInfo._updating.Start(); pInfo._updating.NotEnd(poInfo); poInfo=pInfo._updating.Advance(poInfo)) + { + DoAssert(poInfo->updating); + // oInfo from poInfo + NetworkObjectInfo *oInfo = poInfo->oInfo; + if (pInfo.dpid == oInfo->owner) + { + // delayed handling - handleUpdatingObject is changing pInfo._updating we are traversing + owned.Add(oInfo); + } + else + { + int oCount = pInfo._updating.Size(); + OnStopUpdating(*oInfo, pInfo, *poInfo); + int nCount = pInfo._updating.Size(); + DoAssert(oCount==nCount); + poInfo->updating = false; + } + } + for (int i=0; itimeReceived)*item->invMaxAge; + float errorCoef = 1; + + if (pInfo.cameraPosition[0] != -FLT_MAX && item->pos[0]!=-FLT_MAX) + { + // both positions defined + // coef = limit / distance (maximum is 1) + const float limit = 20.0f; + float dist2 = item->pos.Distance2(pInfo.cameraPosition); + if (dist2 > Square(limit)) + { + errorCoef = Square(limit) / dist2; + } + } + + float error = item->error*ageCoef; + // if age is negative or zero, condition will certainly fail + if (errorCoef*error +class SpatialIndexBruteForce +{ + FindArrayKey _data; +public: + void Add(Type item) + { + _data.Add(item); + } + bool Remove(Vector3Par oldPos, Type item) + { + return _data.DeleteKey(item); + } + + template + void ForEach(Vector3Par pos, float maxDistance, const Function &f) + { + auto fInBubble = [pos,maxDistance,&f](Type oInfo)->bool + { + DoAssert(oInfo->object->UpdateDistance()==maxDistance); + auto oPos = oInfo->BestPosition(); + DoAssert(oPos.second); + float dist2 = pos.Distance2(oPos.first); + if (dist2 +class SpatialIndexNaive +{ + static const float Grid() {return 100.0f;} + + static int SlotNum(float posX) {return toInt(posX * (1.0f/Grid()));} + + typedef FindArrayKey Slot; + + AutoArray _slot; + int _slot0; + +public: + SpatialIndexNaive() + :_slot0(0) + { + } + void Add(Type item) + { + Vector3 pos = item->BestPosition()._pos; + DoAssert(pos.SquareSize()>0); + int slot = SlotNum(pos.X()); + + if (_slot.MaxSize()==0) _slot0 = slot; // empty list, set arbitrary beginning + if (slot<_slot0) + { + _slot.InsertMultiple(0,_slot0-slot); + _slot0 = slot; + } + else if (slot-_slot0>=_slot.Size()) + { + _slot.Resize(slot-_slot0+1); + } + _slot[slot-_slot0].Add(item); + } + bool Remove(Vector3Par oldPos, Type item) + { + int slot = SlotNum(oldPos.X()); + DoAssert(slot>=_slot0 && slot<_slot0+_slot.Size()); + return _slot[slot-_slot0].DeleteKey(item); + } + + template + void ForEach(Vector3Par pos, float maxDistance, const Function &f) + { + if (_slot.Size()<=0) return; + int minSlot = SlotNum(pos.X()-maxDistance); + int maxSlot = SlotNum(pos.X()+maxDistance); + int minSlotI = minSlot-_slot0; + int maxSlotI = maxSlot-_slot0; + saturate(minSlotI,0,_slot.Size()-1); + saturate(maxSlotI,0,_slot.Size()-1); + for (int i=minSlotI; i<=maxSlotI; i++) + { + auto fInBubble = [pos,maxDistance,&f](Type oInfo)->bool + { + // TODO: encapsulate oInfo access in Type traits + auto oPos = oInfo->BestPosition(); + DoAssert(oPos._updateDistance==maxDistance); + float dist2 = pos.Distance2(oPos._pos); + if (dist2 +class SpatialIndexRTree +{ + RTree _data; +public: + void Add(Type item) + { + Vector3 pos = item->BestPosition()._pos; + float vec[2] = {pos[0],pos[2]}; + _data.Insert(vec,vec,item); + } + bool Remove(Vector3Par oldPos, Type item) + { + float vec[2] = {oldPos[0],oldPos[2]}; + return _data.Remove(vec,vec,item); + } + + template + void ForEach(Vector3Par pos, float maxDistance, const Function &f) + { + auto fInBubble = [pos,maxDistance,&f](Type oInfo)->bool + { + auto oPos = oInfo->BestPosition(); + DoAssert(oPos._updateDistance==maxDistance); + float dist2 = pos.Distance2(oPos._pos); + if (dist2 +class SpatialIndexRTreeChecked +{ + SpatialIndexNaive _ref; + SpatialIndexRTree _tst; + + public: + void Add(Type item) + { + _ref.Add(item); + _tst.Add(item); + } + bool Remove(Vector3Par oldPos, Type item) + { + bool ok1 = _ref.Remove(oldPos,item); + bool ok2 = _tst.Remove(oldPos,item); + DoAssert(ok1==ok2); + return ok1; + } + + template + void ForEach(Vector3Par pos, float maxDistance, const Function &f) + { + _ref.ForEach(pos,maxDistance,f); + + FindArrayKey visitedByRef; + FindArrayKey visitedByTst; + + _ref.ForEach(pos,maxDistance,[&visitedByRef](Type oInfo){visitedByRef.Add(oInfo);}); + _tst.ForEach(pos,maxDistance,[&visitedByTst](Type oInfo){visitedByTst.Add(oInfo);}); + + DoAssert(visitedByTst.Size()==visitedByRef.Size()); + + // verify identity + for (int i=0; i=0); + } + for (int i=0; i=0); + } + + + } +}; + +struct ObjectsSpatialLayerImpl: public ObjectsSpatialLayerWithDistance +{ + SpatialIndexRTree _index; + + ObjectsSpatialLayerImpl(float distance):ObjectsSpatialLayerWithDistance(distance){} + virtual void Add(NetworkObjectInfo *oInfo) override; + virtual bool Remove(Vector3Par oldPos, NetworkObjectInfo *oInfo) override; + virtual void ForEach( Vector3 cameraPos, const Function &function ); + +}; + +void ObjectsSpatialLayerImpl::Add(NetworkObjectInfo *oInfo) +{ + _index.Add(oInfo); +} + +bool ObjectsSpatialLayerImpl::Remove(Vector3Par oldPos, NetworkObjectInfo *oInfo) +{ + DoAssert(oldPos.SquareSize()>0); + return _index.Remove(oldPos,oInfo); +} + +void ObjectsSpatialLayerImpl::ForEach( Vector3 cameraPos, const Function &function ) +{ + _index.ForEach(cameraPos,_distance,function); +} + +struct ObjectsSpatialLayerNoBubble: public ObjectsSpatialLayer +{ + FindArrayKey _index; + + virtual void Add(NetworkObjectInfo *oInfo) override {_index.Add(oInfo);} + virtual bool Remove(Vector3Par oldPos, NetworkObjectInfo *oInfo) override {return _index.DeleteKey(oInfo);} + virtual void ForEach(Vector3 cameraPos, const Function &function) + { + _index.ForEachF([function](NetworkObjectInfo *oInfo)->bool {function(oInfo);return false;}); + } + +}; + + +NetworkServer::ObjectsSpatialIndex::ObjectsSpatialIndex() +{ + +} +ObjectsSpatialLayer &NetworkServer::ObjectsSpatialIndex::Distance(float dist) +{ + if (dist0) + { + int index = _layers.FindKey(dist); + if (index>=0) return *_layers[index]; + return *_layers.Append(new ObjectsSpatialLayerImpl(dist)); + } + else + { + if (_noLayer.IsNull()) _noLayer = new ObjectsSpatialLayerNoBubble(); + return *_noLayer; + } +} + +bool NetworkServer::ObjectsSpatialIndex::put( TargetType value ) +{ + addToLayer(value); + return _all.put(value); +} + +void NetworkServer::ObjectsSpatialIndex::removeKey ( KeyType key ) +{ + TargetType value; + if (_all.removeKey(key,&value)) + { + auto pos = value->BestPosition(); + removeFromLayer(pos._pos,pos._updateDistance,value); + } +} + + +void NetworkServer::ObjectsSpatialIndex::forEachInBubble(Vector3 cameraPos, const ObjectsSpatialLayer::Function &function) +{ + for (int i=0; i<_layers.Size(); i++) + { + _layers[i]->ForEach(cameraPos,function); + } + _noLayer->ForEach(cameraPos,function); +} + + +void NetworkServer::ObjectsSpatialIndex::onPosChanged(NetworkObjectInfo *oInfo, const NetworkObjectInfo::UpdateInfo &oldPos, const NetworkObjectInfo::UpdateInfo &newPos) +{ + if (oldPos._pos!=newPos._pos || oldPos._updateDistance!=newPos._updateDistance) + { + removeFromLayer(oldPos._pos,oldPos._updateDistance,oInfo); + addToLayer(oInfo); + } +} + +void NetworkServer::ObjectsSpatialIndex::reset () +{ + _noLayer.Free(); + _layers.Clear(); + _all.reset(); +} + + + + +/*! +\patch 1.27 Date 10/09/2001 by Ondra +- Fixed: Ping times on clients were not updated when mission was not running. +\patch_internal 1.47 Date 3/11/2002 by Ondra +- Fixed: Improved latency on kill. +\patch_internal 1.48 Date 3/12/2002 by Ondra +- Fixed: Latency on kill further improved. +Bug introduced in 1.47 beta causing increased lag of movement fixed. +\patch_internal 1.49 Date 3/14/2002 by Ondra +- Fixed: Latence handling code reverted to version 1.45. +\patch 1.53 Date 4/23/2002 by Ondex +- Fixed: Kill/dammage message have now higher priority - this should improve latency on kill. +*/ +void NetworkServer::SendMessages() +{ + //DoAssert(CheckBestPositionIntegrity()); +#if _ENABLE_CHEATS + // remove statistics info + static AutoArray texts; + for (int i=0; i= 0) GEngine->RemoveText(texts[i]); + } + texts.Resize(0); +#endif + +#if _ENABLE_CHEATS + #define LOG_DESYNC 1 +#endif + +#if LOG_DESYNC + static DWORD time = 0; + DWORD now = GlobalTickCount(); + bool logDesync = false; + if (now >= time + 1000) + { + logDesync = true; + time = now; + } +#endif + + int nPlayers = _identities.Size() - 1; +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + if (IsDedicatedServer()) nPlayers++; +#endif +//} +#define DIAGNOZE_BANDWIDTH 0 +#if DIAGNOZE_BANDWIDTH + bool doDiagnozeBandwidth = false; + static DWORD nextDiagTime = GetTickCount()+5000; + DWORD curTime = GetTickCount(); + if (curTime>=nextDiagTime) + { + nextDiagTime=curTime+5000; + doDiagnozeBandwidth = true; + } +#endif + + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &pInfo = *_players[i]; + + int nMsg = 0; + int nBytes = 0; + int nMsgMax, nBytesMax; + + //LogF(" NsEstB %d, %d Bytes", nMsgMax, nBytesMax); + EstimateBandwidth(pInfo, nPlayers, nMsgMax, nBytesMax); +#if DIAGNOZE_BANDWIDTH + int diagGMsg=0, diagGBytes=0; //state of nMsgMax and nBytesMax after the guaranteed messages are sent + int diagCMsg=0, diagCBytes=0; //state ... after critical updates are sent +#endif + //LogF(" NsEstB %d, %d Bytes", nMsgMax, nBytesMax); + + #if LOG_QUEUE_PROGRESS + if (pInfo._messageQueue.Size() > 0) + { + LogF + ( + "%s: nBytesMax %d, nBytes %d, queue size %d", + (const char *)pInfo.name, + nBytesMax, nBytes, pInfo._messageQueue.Size() + ); + } + #endif + + // send enqueued guaranteed messages + int maxSize = MaxSizeGuaranteed; + + const int nMsgMaxGuaranteed = nMsgMax; + const int nBytesMaxGuaranteed = nBytesMax; + + int firstGuaranteedUnsent = 0; + while (firstGuaranteedUnsent < pInfo._messageQueue.Size()) + { + if (nMsg >= nMsgMaxGuaranteed || nBytes >= nBytesMaxGuaranteed) + { + #if LOG_QUEUE_PROGRESS + int qBytes = 0; + for (int i=firstGuaranteedUnsent; imsg->size; + } + LogF + ( + " -- queue left %d (%d B)",pInfo._messageQueue.Size()-firstGuaranteedUnsent,qBytes + ); + #endif + break; + } + + NetworkMessage *msg = pInfo._messageQueue[firstGuaranteedUnsent]->msg; + int size = msg->size; + if (size >= maxSize) + { + //DWORD dwMsgId = + RefR resultMsg; + /*int rawSize = */SendMsgRemote(pInfo.dpid, msg, pInfo._messageQueue[firstGuaranteedUnsent]->type, NMFGuaranteed|NMFStatsAlreadyDone, &resultMsg, NULL); + pInfo._messageQueue[firstGuaranteedUnsent]->SetFence(resultMsg); + firstGuaranteedUnsent++; + nMsg++; + nBytes += size; + } + else + { + int totalSize = 0; + int i; + for (i=firstGuaranteedUnsent; imsg; + int size = msg->size; + if (totalSize + size > maxSize) break; + totalSize += size; + } + /*int rawSize = */SendMsgQueue(pInfo.dpid, pInfo._messageQueue, firstGuaranteedUnsent, i, NMFGuaranteed); + firstGuaranteedUnsent = i; + nMsg++; + nBytes += totalSize; + } + } + if (firstGuaranteedUnsent > 0) pInfo._messageQueue.Delete(0, firstGuaranteedUnsent); + + #if LOG_QUEUE_PROGRESS + if (nBytes>0) + { + LogF + ( + " -- nMsg %d (nBytes %d)",nMsg,nBytes + ); + if (pInfo._messageQueue.Size()==0) + { + LogF(" ** Queue empty"); + } + } + #endif + + AUTO_STATIC_ARRAY(UpdateObjectInfo, objects, 256); + + #define ENABLE_CRITICAL_UPDATES 1 + +#if DIAGNOZE_BANDWIDTH + diagGBytes = nBytes; + diagGMsg = nMsg; +#endif + + #if !ENABLE_CRITICAL_UPDATES + if (nMsg >= nMsgMax || nBytes >= nBytesMax) + { + #if _ENABLE_CHEATS + if (outputLogs) LogF(" Server to %s: limit reached (guaranteed)", (const char *)pInfo.name); + #endif + goto DoNotSendUpdates; + } + #endif + + // update objects + if (_serverState == NSSPlaying && pInfo.clientState == NCSPlaying) + { + // update errors of objects + if (pInfo.dpid!=BOT_CLIENT) // bot client is sent all updates directly when receiving them + { + CreateObjectsList(objects, pInfo); + + ClientOutput *obj = pInfo._clientInput->_output; + obj->OnBeforeSend(pInfo); + if (!pInfo._clientInput->_outputLast || obj->Compare(pInfo._clientInput->_outputLast)) + { + // TODO: bandwith control + NetworkMessageType type = obj->GetNMType(NMCUpdateGeneric); + Ref msg = ::CreateNetworkMessage(type); + msg->time = Glob.time; + NetworkMessageContext ctx(msg, this, pInfo.dpid, MSG_SEND); + ctx.SetClass(NMCUpdateGeneric); + obj->TransferMsg(ctx); + + SendMsg(pInfo.dpid,msg,type,NMFGuaranteed, NULL); + + // TransferMsg may modify the state + if (!pInfo._clientInput->_outputLast) pInfo._clientInput->_outputLast = new ClientOutput(*obj); + else *pInfo._clientInput->_outputLast = *obj; + obj->OnSent(); + } + } + + // create and send critical updates + #if ENABLE_CRITICAL_UPDATES + PlayerIndex playerIndex = GetPlayerIndex(pInfo.dpid); + for (int i=0; iid)) + { + float times[NMCUpdateN]; + NetworkPlayerObjectInfo *poInfo = oInfo->GetPlayerObjectInfo(playerIndex,pInfo.dpid); + for (int j=0; jupdates[j].lastSentMsg ? poInfo->updates[j].lastSentMsg->time.toFloat() : 0; + LogF("*** DebugMeBoy: {%d:%" OID_FORMAT"} has error %.2f, position in _objects = %d, lastMsgSent: %.02f, %.02f, %.02f", + oInfo->id.creator.CreatorInt(), oInfo->id.id, error, i, times[NMCUpdateGeneric], times[NMCUpdatePosition], times[NMCUpdateDamage]); + } +#endif + + // any message about dammage that transmit change + // that could mean dead should be considered high priority + // errorNoCoef - error with no regard to distance + // error - distance adjusted error + if + ( + errorNoCoef < ERR_COEF_IMMEDIATE && + ( cls != NMCUpdateDamage || error < ERR_COEF_STRUCTURE * 0.01 || errorNoCoef < ERR_COEF_STRUCTURE ) + ) continue; + + info.criticalUpdate = true; + //TODO: do not use fence for high priority updates + NetworkPlayerObjectInfo *poInfo = oInfo->GetPlayerObjectInfo(playerIndex,pInfo.dpid); + int bytes; + if (!poInfo->_fence || poInfo->_fence->WasReceived()) + { + bytes = UpdateObject(&pInfo, oInfo, cls, NMFGuaranteed | NMFHighPriority); + } + else + { + bytes = UpdateObject(&pInfo, oInfo, cls, NMFGuaranteed); + } + + #if _ENABLE_CHEATS + if (outputLogs) + { + LogF + ( + " Server to %s: Object %d:%" OID_FORMAT" updated - size %d bytes, critical", + (const char *)pInfo.name, info.oInfo->id.creator.CreatorInt(), info.oInfo->id.id, bytes + ); + } + #endif + + if (bytes >= 0) + { + // no error + nMsg++; + nBytes += bytes; + } + } + +#if DIAGNOZE_BANDWIDTH + diagCBytes = nBytes; + diagCMsg = nMsg; +#endif + + if (nMsg >= nMsgMax || nBytes >= nBytesMax) + { + #if _ENABLE_CHEATS + if (outputLogs) LogF(" Server to %s: limit reached (guaranteed)", (const char *)pInfo.name); + #endif + goto DoNotSendUpdates; + } + #endif // ENABLE_CRITICAL_UPDATES + } + +DoNotSendUpdates: + // send nonguaranteed enqueued messages + maxSize = MaxSizeNonguaranteed; + // note: even "nonguaranteed" may be actually sent as guaranteed, but they still have their own queue + NetMsgFlags flags = _updatesGuaranteed ? NMFGuaranteed : NMFNone; + int firstNonGuaranteedUnsent = 0; + int next = 0; // index of next object to update + bool empty = false; + while (true) + { + // enforce send last message + if (!empty || firstNonGuaranteedUnsent >= pInfo._messageQueueNonGuaranteed.Size()) + { + if (nMsg >= nMsgMax || nBytes >= nBytesMax) break; + } + + if (firstNonGuaranteedUnsent >= pInfo._messageQueueNonGuaranteed.Size()) + { + empty = true; + // starving, try to create further message + if (!PrepareNextUpdate(pInfo, objects, next)) break; + // local communication - message was already sent + if (pInfo.dpid == BOT_CLIENT) + { + DoAssert(firstNonGuaranteedUnsent >= pInfo._messageQueueNonGuaranteed.Size()); + nMsg++; + continue; + } + DoAssert(firstNonGuaranteedUnsent < pInfo._messageQueueNonGuaranteed.Size()); + } + + NetworkMessageQueueItem *item = pInfo._messageQueueNonGuaranteed[firstNonGuaranteedUnsent]; + int size = item->msg->size; + // enforce send last message + if (size >= maxSize || nMsg >= nMsgMax || nBytes >= nBytesMax) + { + RefR resultMsg; + int rawSize = SendMsgRemote(pInfo.dpid, item->msg, item->type, NMFStatsAlreadyDone|flags, &resultMsg, item->dependOn); + //item->SetFence(resultMsg); //nonquaranteed msg cannot raise a fence + + +#if LOG_SEND_PROCESS + LogF("Server: Message %x sent", dwMsgId); +#endif + firstNonGuaranteedUnsent++; + nMsg++; + nBytes += rawSize; + } + else + { + int totalSize = 0; + int i; + for (i=0; true; i++) + { + int queueIndex = firstNonGuaranteedUnsent + i; + if (queueIndex >= pInfo._messageQueueNonGuaranteed.Size()) + { + empty = true; + // starving, try to create further message + if (!PrepareNextUpdate(pInfo, objects, next)) break; + DoAssert(pInfo.dpid != BOT_CLIENT); + DoAssert(queueIndex < pInfo._messageQueueNonGuaranteed.Size()); + } + + NetworkMessageQueueItem *item = pInfo._messageQueueNonGuaranteed[queueIndex]; + int size = item->msg->size; + if (totalSize + size > maxSize) break; + totalSize += size; + } + + int queueEnd = firstNonGuaranteedUnsent + i; + int normalCount = CompactNetworkMessageQueueRange( + pInfo._messageQueueNonGuaranteed, firstNonGuaranteedUnsent, queueEnd, + [this,&pInfo,flags,&nMsg,&nBytes](NetworkMessageQueueItem *item) + { + // Send dependent messages immediately and keep their queue order. + RefR resultMsg; + int rawSize = SendMsgRemote(pInfo.dpid, item->msg, item->type, NMFStatsAlreadyDone|flags, &resultMsg, item->dependOn); + //item.SetFence(resultMsg); //nonguaranteed messages could not raise a fence + nMsg++; + nBytes += rawSize; + } + ); + + if (normalCount>0) + { + int rawSize = SendMsgQueue(pInfo.dpid, pInfo._messageQueueNonGuaranteed, firstNonGuaranteedUnsent, firstNonGuaranteedUnsent + normalCount, flags); +#if LOG_SEND_PROCESS + LogF("Server: Message %x sent", dwMsgId); +#endif + firstNonGuaranteedUnsent += normalCount; + nMsg++; + nBytes += rawSize; + } + } + } + if (firstNonGuaranteedUnsent > 0) pInfo._messageQueueNonGuaranteed.Delete(0, firstNonGuaranteedUnsent); + DoAssert(!empty || pInfo._messageQueueNonGuaranteed.Size() == 0); + + // search for maximum error not sent + //float sumError = 0; // messages not sent total error + float sumError = 0; + for (int i=next; imsg->size; + + RString output = Format("%s: HLWait%3d(%5dB)", (const char *)pInfo.name, count, size); + texts.Add(GEngine->ShowTextF(1000, output)); + texts.Add(GEngine->ShowTextF(1000, _server->GetStatistics(pInfo.dpid))); + + StatisticsById stats; + for (int i=0; i(item->type),item->msg->size); + } + stats.SortData(false); + int maxLines = 10; + for (int i=0; iShowTextF(1000, " %s: %d", cc_cast(name), item.count)); + } + } +#endif + } +} + +bool NetworkServer::PrepareNextUpdate(NetworkPlayerInfo &pInfo, AutoArray &objects, int &next) +{ + while (next < objects.Size()) + { + UpdateObjectInfo &info = objects[next++]; + if (info.criticalUpdate) continue; + +/* + #if _ENABLE_REPORT + int oldCount = pInfo._messageQueueNonGuaranteed.Size(); + #endif +*/ + NetworkObjectInfo *oInfo = info.oInfo; + if (oInfo) + { + NetworkMessageClass cls = info.cls; + int bytes = UpdateObject(&pInfo, oInfo, cls, NMFNone); + if (bytes < 0) continue; + #if _ENABLE_CHEATS + if (outputLogs) LogF(" Server to %s: Object updated - size %d bytes", (const char *)pInfo.name, bytes); + #endif + } + else + { + //NetworkComponent::SendMsg(pInfo.dpid, info.msg, info.type, NMFGuaranteed); + // non-guaranteed enqueues into the same queue as UpdateObject + SendMsg(pInfo.dpid, info.msg->msg, info.msg->type, NMFNone, NULL); + // set error to zero so that message is deleted + info.msg->error = 0; + #if _ENABLE_CHEATS + if (outputLogs) LogF(" Server to %s: Delayed message sent", (const char *)pInfo.name); + #endif + } +/* + #if _ENABLE_REPORT + if (oldCount == pInfo._messageQueueNonGuaranteed.Size()) + { + Fail("No message added during NetworkServer::PrepareNextUpdate"); + continue; + } + #endif +*/ + + return true; + } + return false; +} + +#if _HELISIM_ROTORLIB + #define ROTOR_LIB_MAP_UPDATE_TO_TYPE(XXXX) \ + XXXX(NMTUpdatePositionHelicopterRTD,HelicopterRTD) \ + XXXX(NMTUpdateHelicopterRTD,HelicopterRTD) + #define ROTOR_LIB_MAP_CREATE_TO_TYPE(XXXX) \ + XXXX(NMTCreateHelicopterRTD,HelicopterRTD) +#else + #define ROTOR_LIB_MAP_UPDATE_TO_TYPE(XXXX) + #define ROTOR_LIB_MAP_CREATE_TO_TYPE(XXXX) +#endif + +#define MAP_UPDATE_TO_TYPE(XXXX) \ + XXXX(NMTUpdateDamageObject,Object) \ + XXXX(NMTUpdateObject,Object) \ + XXXX(NMTUpdatePositionVehicle,Vehicle) \ + XXXX(NMTUpdateDamageVehicle,Vehicle) \ + XXXX(NMTUpdateVehicle,Vehicle) \ + XXXX(NMTUpdateDetector,Detector) \ + XXXX(NMTUpdateFlag,FlagCarrier) \ + XXXX(NMTUpdateShot,Shot) \ + XXXX(NMTUpdateMine,Mine) \ + XXXX(NMTUpdateWeapon,Weapon) \ + XXXX(NMTUpdateDamageVehicleAI,EntityAI) \ + XXXX(NMTUpdateVehicleAI,EntityAI) \ + XXXX(NMTUpdateVehicleBrain,Person) \ + XXXX(NMTUpdateTransport,Transport) \ + XXXX(NMTUpdatePositionMan,Man) \ + XXXX(NMTUpdateMan,Man) \ + XXXX(NMTUpdateTankOrCar,TankOrCar) \ + XXXX(NMTUpdatePositionTank,TankWithAI) \ + XXXX(NMTUpdateTank,TankWithAI) \ + XXXX(NMTUpdatePositionMotorcycle,Motorcycle) \ + XXXX(NMTUpdateMotorcycle,Motorcycle) \ + XXXX(NMTUpdatePositionCar,Car) \ + XXXX(NMTUpdateCar,Car) \ + XXXX(NMTUpdatePositionAirplane,AirplaneAuto) \ + XXXX(NMTUpdateAirplane,AirplaneAuto) \ + XXXX(NMTUpdatePositionHelicopter,HelicopterAuto) \ + XXXX(NMTUpdateHelicopter,HelicopterAuto) \ + XXXX(NMTUpdateParachute,ParachuteAuto) \ + XXXX(NMTUpdatePositionShip,ShipWithAI) \ + XXXX(NMTUpdateShip,ShipWithAI) \ + XXXX(NMTUpdatePositionDoor,Door) \ + XXXX(NMTUpdateDoor,Door) \ + XXXX(NMTUpdatePositionSeagull,SeaGullAuto) \ + XXXX(NMTUpdateSeagull,SeaGullAuto) \ + XXXX(NMTUpdateClientInfo,ClientInfoObject) \ + XXXX(NMTUpdateClientInfoDpid,ClientInfoObject) \ + XXXX(NMTUpdateFireplace,Fireplace) \ + XXXX(NMTUpdatePositionTurret,Turret) \ + XXXX(NMTUpdateTurret,Turret) \ + XXXX(NMTAIStatsMPRowUpdate,AIStatsMPRow) \ + XXXX(NMTUpdateClientCameraPosition,ClientCameraPositionObject) \ + XXXX(NMTUpdateInventoryItem,InventoryItem) \ + XXXX(NMTUpdateItemRadio,ItemRadio) \ + XXXX(NMTUpdateItemTransmitter,ItemTransmitter) \ + ROTOR_LIB_MAP_UPDATE_TO_TYPE(XXXX) + +#define MAP_CREATE_TO_TYPE(XXXX) \ + XXXX(NMTCreateObject,Object) \ + XXXX(NMTCreateVehicle,Vehicle) \ + XXXX(NMTCreateCrater,Crater) \ + XXXX(NMTCreateCraterOnVehicle,CraterOnVehicle) \ + XXXX(NMTCreateSoundOnVehicle,SoundOnVehicle) \ + XXXX(NMTCreateObjectDestructed,ObjectDestructed) \ + XXXX(NMTCreateDynSoundSource,DynSoundSource) \ + XXXX(NMTCreateShot,Shot) \ + XXXX(NMTCreateHelicopter,HelicopterAuto) \ + XXXX(NMTCreateSeagull,SeaGullAuto) \ + XXXX(NMTCreateTurret,Turret) \ + XXXX(NMTAIStatsMPRowCreate,AIStatsMPRow) \ + XXXX(NMTCreateClientCameraPosition,ClientCameraPositionObject) \ + XXXX(NMTCreateDestructionEffects,ItemTransmitter) \ + ROTOR_LIB_MAP_CREATE_TO_TYPE(XXXX) + +#define UPDATE_TO_TYPE_DISTANCE(typeNMT,Type) case typeNMT: return Type::UpdateDistance(); + +/** +@param msg1 last message received from an owner +@param msg2 last message sent to a remote client +*/ +float NetworkServer::CalculateErrorTime +( + NetworkMessageType type, NetworkMessage *msg1, NetworkMessage *msg2 +) +{ + if (type < 0 || type >= NMTN) + { + RptF("Server: Bad message %d format", (int)type); + return 0.0; + } + + float errCoefTime; + switch (type) + { + case NMTUpdatePositionVehicle: + case NMTUpdatePositionMan: + case NMTUpdatePositionTank: + case NMTUpdatePositionCar: + case NMTUpdatePositionMagazine: + case NMTUpdatePositionAirplane: + case NMTUpdatePositionHelicopter: +#if _HELISIM_ROTORLIB + case NMTUpdatePositionHelicopterRTD: +#endif + case NMTUpdatePositionShip: + case NMTUpdatePositionDoor: + case NMTUpdatePositionSeagull: + case NMTUpdatePositionMotorcycle: + errCoefTime = ERR_COEF_TIME_POSITION; + break; + default: + errCoefTime = ERR_COEF_TIME_GENERIC; + break; + } + + // update to clients on receiving on an update from an owner + float dt = msg1->time - msg2->time; + return errCoefTime * dt; +} + +/*! +\patch_internal 5102 Date 12/14/2006 by Jirka +- Fixed: Starting of MP missions in Retail Demo was broken +*/ + +void NetworkServer::SendMissionFile(int dpnid) +{ +#if _ENABLE_UNSIGNED_MISSIONS + +// RptF("*** Server: Send mission file to %d", dpnid); + + bool found = false; + bool foundParams = false; + NetworkPlayerInfo *player = NULL; + if (dpnid == 0) + { + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = *_players[i]; + if (info.clientState != NCSPlayerAssigned) continue; + if (info.dpid == BOT_CLIENT) + { + DoAssert(info.missionFileValid); + } + if (!info.missionFileValid) found = true; + if (!info.paramFileValid) foundParams = true; + } + } + else + { + DoAssert(dpnid != BOT_CLIENT); + player = GetPlayerInfo(dpnid); + if (!player) return; + if (player->clientState != NCSPlayerAssigned) return; + if (!player->missionFileValid) found = true; + if (!player->paramFileValid) foundParams = true; + } + + int maxSegmentSize = 512 - 50; + + if (foundParams) + { + QIFStreamB f; + RString src = GetMissionParameters(); + // char '$' is used as an indication of Local Settings directory (different on client than on server) + RString dst = RString("$\\MPMissionsCache\\__cur_mp.") + GetExtensionWizardMission(); + f.AutoOpen(src); + + TransferFileMessage msg; + msg._path = dst; + msg._totSize = f.rest(); + msg._totSegments = (msg._totSize + maxSegmentSize - 1) / maxSegmentSize; + msg._offset = 0; + for (int i=0; iparamFileValid) + SendMsg(dpnid, &msg, NMFGuaranteed); + + msg._offset += size; + } + } + + if (found) + { + QIFStreamB f; + RString src = _missionBank; + // FIX: transfer mission file always into tmp directory (do not rewrite original file) + // char '$' is used as an indication of Local Settings directory (different on client than on server) + RString dst = RString("$\\MPMissionsCache\\") + _missionHeader._fileName + RString(".pbo"); + f.AutoOpen(src); + + TransferMissionFileMessage msg; + msg._path = dst; + msg._totSize = f.rest(); + msg._totSegments = (msg._totSize + maxSegmentSize - 1) / maxSegmentSize; + msg._offset = 0; + for (int i=0; imissionFileValid) + SendMsg(dpnid, &msg, NMFGuaranteed); + + msg._offset += size; + } + } + + // do not send twice + if (dpnid == 0) + { + for (int j=0; j<_players.Size(); j++) + { + NetworkPlayerInfo &info = *_players[j]; +// RptF(" player %s, has state %s", (const char *)info.name, (const char *)FindEnumName(info.clientState)); + if (info.clientState == NCSPlayerAssigned) + { + info.missionFileValid = true; + info.paramFileValid = true; + SetClientState(info.dpid, NCSMissionReceived); + } + } + } + else + { + player->missionFileValid = true; + player->paramFileValid = true; + SetClientState(dpnid, NCSMissionReceived); + } + +#else + + bool foundParams = false; + NetworkPlayerInfo *player = NULL; + if (dpnid == 0) + { + for (int i=0; i<_players.Size(); i++) + { + NetworkPlayerInfo &info = _players[i]; + if (info.clientState != NCSPlayerAssigned) continue; + if (!info.paramFileValid) foundParams = true; + } + } + else + { + DoAssert(dpnid != BOT_CLIENT); + player = GetPlayerInfo(dpnid); + if (!player) return; + if (player->clientState != NCSPlayerAssigned) return; + if (!player->paramFileValid) foundParams = true; + } + + int maxSegmentSize = 512 - 50; + + if (foundParams) + { + QIFStreamB f; + RString src = GetMissionParameters(); + // char '$' is used as an indication of Local Settings directory (different on client than on server) + RString dst = RString("$\\MPMissionsCache\\__cur_mp.") + GetExtensionWizardMission(); + f.AutoOpen(src); + + TransferFileMessage msg; + msg._path = dst; + msg._totSize = f.rest(); + msg._totSegments = (msg._totSize + maxSegmentSize - 1) / maxSegmentSize; + msg._offset = 0; + for (int i=0; iparamFileValid) + SendMsg(dpnid, &msg, NMFGuaranteed); + + msg._offset += size; + } + } + + // do not send twice + if (dpnid == 0) + { + for (int j=0; j<_players.Size(); j++) + { + NetworkPlayerInfo &info = _players[j]; + // RptF(" player %s, has state %s", (const char *)info.name, (const char *)FindEnumName(info.clientState)); + if (info.clientState == NCSPlayerAssigned) + { + info.missionFileValid = true; + info.paramFileValid = true; + SetClientState(info.dpid, NCSMissionReceived); + } + } + } + else + { + player->missionFileValid = true; + player->paramFileValid = true; + SetClientState(dpnid, NCSMissionReceived); + } + +#endif // _ENABLE_UNSIGNED_MISSIONS +} + +//{ DEDICATED SERVER SUPPORT +#if _ENABLE_DEDICATED_SERVER + +RString GetPidFileName (); +extern bool MyPidFile; + +//! Create dedicated server +/*! +\param config name of server configuaration file +*/ +bool CreateDedicatedServer(SessionType sessionType, RString config) +{ + if (GWorld->Options()) + { + GWorld->Options()->DestroyHUD(-1); + } + + RString GetLiveGamertag(); + RString gamertag = GetLiveGamertag(); + if (gamertag.GetLength()>0) + { + GNetworkManager.Init(); + } + else + { + // create a system link dedicated server + GNetworkManager.Init("", GetServerPort(), false); + } + +#if _GAMES_FOR_WINDOWS + GWorld->CreateDSOptions(); +#endif + + RString password(""); + int maxPlayers = MAX_PLAYERS_DS; + + GameDataNamespace globals(NULL, RString(), false); // TODO: parsing namespace if access to globals needed + + ParamFile serverCfg; + serverCfg.Parse(config, NULL, NULL, &globals); + + ConstParamEntryPtr entry = serverCfg.FindEntry("password"); + if (entry) password = *entry; + + entry = serverCfg.FindEntry("maxPlayers"); + if (entry) maxPlayers = *entry; + maxPlayers += 1; // dedicated server occupy single slot + + RString steamServerName("SourceDayZ Community Server"); + entry = serverCfg.FindEntry("hostname"); + if (entry) steamServerName = *entry; + + int steamPort = 8766; + entry = serverCfg.FindEntry("steamPort"); + if (entry) steamPort = *entry; + + int steamQueryPort = 27016; + entry = serverCfg.FindEntry("steamQueryPort"); + if (entry) steamQueryPort = *entry; + + int port = GetServerPort(); + + int rating = 0; + + GNetworkManager.CreateSession(sessionType, RString(), password, maxPlayers, false, port, true, config, rating); + if (GNetworkManager.IsServer()) + { + RString title = APP_NAME " Console version " APP_VERSION_TEXT "." STRINGIZE(BUILD_NO)" : port %d"; + ConsoleTitle(title, GNetworkManager.GetServer()->GetSessionPort()); + // writting the pid of the server instance: + if ( GetPidFileName().GetLength() ) + { + FILE *pidFp; + if ( (pidFp = fopen((const char*)GetPidFileName(),"wt")) != NULL ) + { + fprintf(pidFp,"%d\n",getpid()); + fclose(pidFp); +#ifdef _WIN32 +#else + fchmod(fileno(pidFp),(S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)); +#endif + MyPidFile = true; + } + } +#if _ENABLE_STEAM && defined(_WIN64) + if (steamPort > 0 && steamPort <= 65535 && steamQueryPort > 0 && steamQueryPort <= 65535) + SteamOnlineServerStart(port, steamPort, steamQueryPort, cc_cast(steamServerName), maxPlayers - 1, !password.IsEmpty()); + else + LogF("Steamworks server-list ports are invalid; use steamPort and steamQueryPort in the dedicated server config"); +#endif + return true; + } + + ConsoleTitle("Server creation failed : %d", port); + return false; +} + +#define ENUM_LOAD(type, prefix, name) \ + entry = _serverCfg.FindEntry(#name); \ + if (entry) _eventHandlers[prefix##name] = *entry; + +/*! +\patch 1.24 Date 09/19/2001 by Jirka +- Added: parameters "motdInterval" and "motd" (for message of the day) added to dedicated server config +\patch 1.24 Date 09/21/2001 by Jirka +- Added: parameter "voteThreshold" added to dedicated server config +\patch 1.27 Date 10/16/2001 by Jirka +- Added: parameter "reportingIP" added to dedicated server config +to change / disable IP address of Query & Reporting master server. + When empty, reporting is disabled. + If entry missing, master.gamespy.com is used and server is advertised to GameSpy. +\patch 1.82 Date 8/27/2002 by Jirka +- Added: parameter "kickDuplicate" added to dedicated server config +\patch 5120 Date 1/18/2007 by Ondra +- New: parameter persistent in the server config to allow the mission to continue + even when no players are connected +\patch 5180 Date 11/12/2007 by Jirka +- New: BattlEye protection integration +*/ + +bool NetworkServer::SetDedicated(RString config) +{ + _dedicated = true; + + _serverCfg.Parse(config, NULL, NULL, &GParsingNamespace); // parsing namespace (persistent namespace needed for persistent ParamFile) + _missionIndex = -1; + + _motdInterval = 5; + ConstParamEntryPtr entry = _serverCfg.FindEntry("motdInterval"); + if (entry) _motdInterval = *entry; + + entry = _serverCfg.FindEntry("motd"); + if (entry) + { + for (int i=0; i<(*entry).GetSize(); i++) _motd.Add((*entry)[i]); + } + +#if _USE_BATTL_EYE_SERVER + entry = _serverCfg.FindEntry("battlEye"); + if (!entry || (bool)*entry) //battlEye is on by default + { + if (!_beIntegration.Init()) + { +#if _ENABLE_DEDICATED_SERVER + if (entry || (_beIntegration._initFailedReason!=BattlEye::BEReasonNotInstalled) ) + { + ConsoleF("BattlEye initialization failed"); + return false; + } +#endif + } + } +#endif + + _voteThreshold = 0.5; + entry = _serverCfg.FindEntry("voteThreshold"); + if (entry) _voteThreshold = *entry; + + // empty string is default now + // to disable reporting, use reportingIP = "noreport"; + entry = _serverCfg.FindEntry("reportingIP"); + if (entry) _reportingIP = *entry; + + entry = _serverCfg.FindEntry("kickDuplicate"); + if (entry) _kickDuplicate = *entry; + + entry = _serverCfg.FindEntry("equalModRequired"); + if (entry) _equalModRequired = *entry; + + entry = _serverCfg.FindEntry("verifySignatures"); + if (entry) + { + int verify = *entry; + if (verify>0) SetVerifySignatures(verify); + } + + // TODO: once stabilized, make _updatesGuaranteed the only option + entry = _serverCfg.FindEntry("guaranteedUpdates"); + if (entry) + { + _updatesGuaranteed = *entry; + } + +#if _ENABLE_STEAM_MATCHMAKING + entry = _serverCfg.FindEntry("steamPort"); + if (entry) + _steamPort = *entry; + else + _steamPort = 8766; // some default value used in prev. versions + + entry = _serverCfg.FindEntry("steamQueryPort"); + if (entry) + _steamQueryPort = *entry; + else + _steamQueryPort = 27016; // some default value used in prev. versions +#endif + + _buildNoRequired = _serverCfg.ReadValue("requiredBuild",0); + // server can never require version higher than it has, as the bot client should meet the requirements as well + if (BUILD_NO>0) + { + if (_buildNoRequired>BUILD_NO) _buildNoRequired = BUILD_NO; + } + + _secureIdRequired = _serverCfg.ReadValue("requiredSecureId",DefaultSecureIdRequired); + + entry = _serverCfg.FindEntry("persistent"); + if (entry) + { + _persistent = *entry; + } + + entry = _serverCfg.FindEntry("additionalSignedFiles"); + if (entry) + { + int n = entry->GetSize(); + _additionalSignedFiles.Realloc(n); + _additionalSignedFiles.Resize(n); + for (int i=0; iIsTextValue()) + { + RString timeStampFormat = *entry; + if (!timeStampFormat.IsEmpty()) + { + if (stricmp(timeStampFormat, "none")==0) GTimeStampFormat = TSFNone; + else if (stricmp(timeStampFormat, "short")==0) GTimeStampFormat = TSFShort; + else if (stricmp(timeStampFormat, "full")==0) GTimeStampFormat = TSFFull; + } + } + + entry = _serverCfg.FindEntry("disable3rdPerson"); + if(entry) + { + _disable3rdPerson = *entry; + } + + entry = _serverCfg.FindEntry("environmentTimeMul"); + if(entry) + { + _environmentTimeMul = *entry; + } + + // event handlers + SERVER_EVENT_ENUM(ServerEvent, SE, ENUM_LOAD) + + return true; +} + +void NetworkServer::Monitor(float interval) +{ + _monitorInterval = interval; + _monitorFrames = 0; + _monitorIn = 0; + _monitorOut = 0; + if (_monitorInterval > 0) _monitorNext = GlobalTickCount() + toInt(1000.0 * _monitorInterval); + else _monitorInterval = UINT_MAX,_monitorNext = UINT_MAX; +} + +void NetworkServer::OnMonitorIn(int size) +{ + if (_dedicated) _monitorIn += size; +} + +#endif +//} + +static bool LoadKey(const FileItem &file, AutoArray &keys) +{ + int index = keys.Add(); + keys[index].Load(file.path + file.filename); + // test duplicity + for (int i=0; iMaxVerifySignatures) _sigVerRequired = MaxVerifySignatures; // 2 is the max value currently supported + + // load all accepted keys + // core keys + ForMaskedFile("Keys\\", "*.bikey", LoadKey, _acceptedKeys); +#if _ENABLE_DEDICATED_SERVER + if (!_dedicated) +#endif + { + // user keys + RString GetUserDirectory(); + ForMaskedFile(GetUserDirectory() + RString("Keys\\"), "*.bikey", LoadKey, _acceptedKeys); + } + ForMaskedFile(RString("Expansion\\Keys\\"), "*.bikey", LoadKey, _acceptedKeys); + _acceptedKeys.Compact(); +} + +/*! +\patch 5164 Date 10/3/2007 by Jirka +- Fixed: Signature verification timeout significantly relaxed. +*/ + +//! verify signature of the single file +void NetworkServer::CheckSignature(int dpnid, int fileIndex, int level) +{ + NetworkPlayerInfo *info = GetPlayerInfo(dpnid); + if (!info) return; + + // check if the same question is not pending + if (info->signatureChecks.Pending(fileIndex)) + return; + + // send the question + DataSignatureAskMessage ask; + ask._index = fileIndex; + ask._level = level; + SendMsg(dpnid, &ask, NMFGuaranteed); + + // add the question to the list of pending questions + info->signatureChecks.Add(fileIndex); +} + +//! verify signature of the single file +void NetworkServer::CheckSignature(int dpnid, RString filename, RString prefix, int level) +{ + NetworkPlayerInfo *info = GetPlayerInfo(dpnid); + if (!info) return; + + // check if the same question is not pending + if ( info->signatureChecks.Pending(filename) ) + return; + + // send the question + FileSignatureAskMessage ask; + ask._file = filename; + ask._level = level; + SendMsg(dpnid, &ask, NMFGuaranteed); + + // add the question to the list of pending questions + info->signatureChecks.Add(filename, prefix); +} + +bool NetworkServer::MyHash(Temp &hash, RString prefix, int sigVer, int level) +{ + // find the stored hash using prefix as key in bankHashes array + int i=0; + for (; i= info.offset) + { + index = i; + if (info.offset + info.size == _modified[i].offset) + { + // join with the next block + _modified[index].offset = info.offset; + _modified[index].size += info.size; + } + else + { + // insert the new block + _modified.Insert(index, info); + } + } + } + if (index < 0) + { + // append it + index = _modified.Add(info); + } + // check if the new block can be merged with the previous one + if (index > 0) + { + ExeSegmentInfo &block1 = _modified[index - 1]; + ExeSegmentInfo &block2 = _modified[index]; + if (block1.offset + block1.size == block2.offset) + { + block1.size += block2.size; + _modified.Delete(index); + } + } + } + else + { + // store further investigations + ExeSegmentInfo &add1 = _stack.Append(); + ExeSegmentInfo &add2 = _stack.Append(); + add1.offset = info.offset; + add1.size = info.size / 2; + add2.offset = info.offset + add1.size; + add2.size = info.size - add1.size; + } + } + + // remove the handled question + _stack.Delete(0); + _asked = false; + _client1._answered = false; + _client2._answered = false; + + if (_stack.Size() == 0) + { + // investigation finished, output the results + QOFStream out; + out.openForAppend("cheats.txt"); + for (int i=0; i<_modified.Size(); i++) + { + RString line = Format(" 0x%08x:0x%08x\r\n", _modified[i].offset, _modified[i].size); + out << line; + } + out.close(); + } +} + +#endif +//))EXE_CRC_CHECK + +bool NetworkServer::GetClientAddress(int client, sockaddr_in &address) +{ + if (client == BOT_CLIENT) + return _server->GetServerAddress(address); + else + return _server->GetClientAddress(client, address); +} + +////////////////////////////////////////////////////////////////////////// +// +// Server scripting functions and event handlers processing +// + +/*! +\patch 5126 Date 2/1/2007 by Jirka +- Added: MP - new server scripting function lock +- Added: MP - new commands #lock, #unlock +*/ + +#if _ENABLE_DEDICATED_SERVER + +DEFINE_ENUM(ServerEvent, SE, SERVER_EVENT_ENUM) + +void NetworkServer::SetEventHandler(RString name, RString value) +{ + ServerEvent event = GetEnumValue(cc_cast(name)); + if (event != INT_MIN) _eventHandlers[event] = value; +} + +bool NetworkServer::OnEvent(ServerEvent event, float par) +{ + RString handler = _eventHandlers[event]; + if (handler.GetLength() == 0) return false; + + GameValue value = GWorld->GetGameState()->CreateGameValue(GameArray); + GameArrayType &arguments = value; + arguments.Add(par); + + GameVarSpace local(false); + int gshandle = _evaluator.BeginContext(&local); + _evaluator.VarSetLocal("_this", arguments, true); + _evaluator.Execute(handler, GameState::EvalContext::_default, &_globals); // server namespace + _evaluator.EndContext(gshandle); + + return true; +} + +bool NetworkServer::OnEvent(ServerEvent event, float par1, float par2) +{ + RString handler = _eventHandlers[event]; + if (handler.GetLength() == 0) return false; + + GameValue value = GWorld->GetGameState()->CreateGameValue(GameArray); + GameArrayType &arguments = value; + arguments.Add(par1); + arguments.Add(par2); + + GameVarSpace local(false); + int gshandle = _evaluator.BeginContext(&local); + _evaluator.VarSetLocal("_this", arguments, true); + _evaluator.Execute(handler, GameState::EvalContext::_default, &_globals); // server namespace + _evaluator.EndContext(gshandle); + + return true; +} + +bool NetworkServer::OnEvent(ServerEvent event, float par1, RString par2) +{ + RString handler = _eventHandlers[event]; + if (handler.GetLength() == 0) return false; + + GameValue value = GWorld->GetGameState()->CreateGameValue(GameArray); + GameArrayType &arguments = value; + arguments.Add(par1); + arguments.Add(par2); + + GameVarSpace local(false); + int gshandle = _evaluator.BeginContext(&local); + _evaluator.VarSetLocal("_this", arguments, true); + _evaluator.Execute(handler, GameState::EvalContext::_default, &_globals); // server namespace + _evaluator.EndContext(gshandle); + + return true; +} + +#if _VBS3 +// forward declaration of checksize and checktype in gamestate.cpp +bool CheckSize(const GameState *state, GameArrayType array, int size); +#else +inline bool CheckSize(const GameState *state, GameArrayType array, int size) +{ + if (array.Size() == size) return true; + state->SetError(EvalDim, array.Size(), size); + return false; +} +#endif + +#if _VBS3 +// forward declaration of checksize and checktype in gamestate.cpp +bool CheckType(const GameState *state, GameValuePar oper, const GameType &type); +#else +inline bool CheckType(const GameState *state, GameValuePar oper, const GameType &type) +{ + if (oper.GetType() == type) return true; + state->TypeError(type, oper.GetType()); + return false; +} +#endif + +GameValue ServerUsers(const GameState *state) +{ + GameValue value = state->CreateGameValue(GameArray); + + NetworkServer *server = GNetworkManager.GetServer(); + if (!server) return value; + const AutoArray *identities = server->GetIdentities(); + if (!identities) return value; + + int n = identities->Size(); + GameArrayType &array = value; + array.Realloc(n); + array.Resize(n); + for (int i=0; iCreateGameValue(GameArray); + GameArrayType &subarray = array[i]; + subarray.Realloc(2); + subarray.Resize(2); + subarray[0] = (float)identity.playerid; + subarray[1] = identity.GetName(); + } + + return value; +} + +GameValue ServerBan(const GameState *state, GameValuePar oper1) +{ + NetworkServer *server = GNetworkManager.GetServer(); + if (!server) return NOTHING; + + int playerId = toInt((float)oper1); + const PlayerIdentity *identity = server->FindIdentityByPlayerId(playerId); + if (!identity) return NOTHING; + + // add global ban list + FindArray banList; + LoadBanList("ban.txt", banList); + GFileServerFunctions->FlushReadHandle("ban.txt"); + banList.AddUnique(identity->id); + SaveBanList("ban.txt", banList); + + // kick off + server->KickOff(identity->dpnid, KORBan); + + return NOTHING; +} + +GameValue ServerKick(const GameState *state, GameValuePar oper1) +{ + NetworkServer *server = GNetworkManager.GetServer(); + if (!server) return NOTHING; + + int playerId = toInt((float)oper1); + const PlayerIdentity *identity = server->FindIdentityByPlayerId(playerId); + if (!identity) return NOTHING; + + server->KickOff(identity->dpnid, KORKick); + + return NOTHING; +} + +GameValue ServerKickUID(const GameState *state, GameValuePar oper1) +{ + NetworkServer *server = GNetworkManager.GetServer(); + if (!server) return NOTHING; + + if (oper1.GetType()==GameString) + { + RString id = oper1; + const AutoArray *identities = server->GetIdentities(); + const PlayerIdentity *identity = NULL; + for (int i=0; i<(*identities).Size(); i++) + { + if ( IsUserIdMatch((*identities)[i].id, id) ) + { + identity = &(*identities)[i]; + break; + } + } + if (!identity) return NOTHING; + + server->KickOff(identity->dpnid, KORKick); + } + return NOTHING; +} + +GameValue ServerBanUID(const GameState *state, GameValuePar oper1) +{ + NetworkServer *server = GNetworkManager.GetServer(); + if (!server) return NOTHING; + + if (oper1.GetType()==GameString) + { + RString id = oper1; + + // add global ban list + FindArray banList; + LoadBanList("ban.txt", banList); + GFileServerFunctions->FlushReadHandle("ban.txt"); + banList.AddUnique(id); + SaveBanList("ban.txt", banList); + + // kick off + return ServerKickUID(state, oper1); + } + return NOTHING; +} + +GameValue ServerNFiles(const GameState *state, GameValuePar oper1) +{ + NetworkServer *server = GNetworkManager.GetServer(); + if (!server) return 0.0f; + + int playerId = toInt((float)oper1); + const PlayerIdentity *identity = server->FindIdentityByPlayerId(playerId); + if (!identity) return 0.0f; + + return (float)identity->filesCount; +} + +GameValue ServerLock(const GameState *state, GameValuePar oper1) +{ + NetworkServer *server = GNetworkManager.GetServer(); + if (server) server->LockSession(oper1); + return NOTHING; +} + +//((EXE_CRC_CHECK +#if !_SUPER_RELEASE +GameValue ServerCmpExe(const GameState *state) +{ + NetworkServer *server = GNetworkManager.GetServer(); + if (!server) return false; + + // check if exactly two identities are present + int dpid1 = 0, dpid2 = 0, dpidCount = 0; + const AutoArray *identities = server->GetIdentities(); + if (!identities) return false; + for (int i=0; iSize(); i++) + { + const PlayerIdentity &identity = identities->Get(i); + if (identity.dpnid == BOT_CLIENT) continue; + dpidCount++; + if (dpidCount == 1) + dpid1 = identity.dpnid; + else if (dpidCount == 2) + dpid2 = identity.dpnid; + else + break; + } + if (dpidCount != 2) return false; + + // start the exe investigation + server->CompareExe(dpid1, dpid2); + return true; +} +#endif +//))EXE_CRC_CHECK + +#define NULARS_SERVER(XX, Category) \ + XX(GameArray, "users", ServerUsers, "The list of the users connected to the server.", "", "", "2.92", "", Category) \ + +//((EXE_CRC_CHECK +#define NULARS_SERVER_DEBUG(XX, Category) \ + XX(GameBool, "cmpExe", ServerCmpExe, "Compare executable of two connected clients.", "", "", "5170", "", Category) \ +//))EXE_CRC_CHECK + +#define FUNCTIONS_SERVER(XX, Category) \ + XX(GameNothing, "ban", ServerBan, GameScalar, "user id", "Add the user to the server ban list.", "", "", "2.92", "", Category) \ + XX(GameNothing, "kick", ServerKick, GameScalar, "user id", "Kick the user from the server.", "", "", "2.92", "", Category) \ + XX(GameScalar, "numberOfFiles", ServerNFiles, GameScalar, "user id", "Return the number of files used by the user.", "", "", "2.92", "", Category) \ + XX(GameNothing, "lock", ServerLock, GameBool, "lock", "Lock / unlock the session.", "", "", "5126", "", Category) \ + +#define OPERATORS_SERVER(XX, Category) \ + +NULARS_SERVER(JNI_NULAR, "Server") +#if !_SUPER_RELEASE + NULARS_SERVER_DEBUG(JNI_NULAR, "Server Debug") +#endif + +static const GameNular ServerNular[]= +{ + NULARS_SERVER(REGISTER_NULAR, "Server") +//((EXE_CRC_CHECK +#if !_SUPER_RELEASE + NULARS_SERVER_DEBUG(REGISTER_NULAR, "Server Debug") +#endif +//))EXE_CRC_CHECK +}; + +FUNCTIONS_SERVER(JNI_FUNCTION, "Server") + +static const GameFunction ServerUnary[]= +{ + FUNCTIONS_SERVER(REGISTER_FUNCTION, "Server") +}; + +OPERATORS_SERVER(JNI_OPERATOR, "Server") + +#if 0 // +static const GameOperator ServerBinary[]= +{ + OPERATORS_SERVER(REGISTER_OPERATOR, "Server") +}; +#endif + +void NetworkServer::InitEvaluator() +{ + // global namespace need to be passed explicitly + _evaluator.DisableDefaultGlobals(); + + // no special types + + // functions + for(int i=0; i= 32 || _sqfExecQueue.Size() != _sqfExecFrom.Size()) + { + RptF("SDZ_SQF_EXEC: rejected command because the execution queue is full or inconsistent"); + return; + } + _sqfExecQueue.Add(expression); + _sqfExecFrom.Add(from); +} + +#if defined(_MSC_VER) +// Keep SEH in a helper without C++ objects that have destructors. +static bool SDZ_TryEvaluateSqf(GameState *state, const char *expression, GameDataNamespace *globals, GameValue *result) +{ + __try + { + *result = state->EvaluateMultiple(expression, GameState::EvalContext::_default, globals); + return true; + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + RptF("SDZ_SQF_EXEC: exception 0x%08X while evaluating script", (unsigned)GetExceptionCode()); + return false; + } +} +#endif + +void NetworkServer::ProcessQueuedExec() +{ + if (_sqfExecBusy || _sqfExecQueue.Size() <= 0) return; + _sqfExecBusy = true; + + GameState *execState = GWorld ? GWorld->GetGameState() : NULL; + GameDataNamespace *mission = GWorld ? GWorld->GetMissionNamespace() : NULL; + if (!execState || !mission) + { + _sqfExecQueue.Resize(0); + _sqfExecFrom.Resize(0); + _sqfExecBusy = false; + return; + } + + while (_sqfExecQueue.Size() > 0) + { + RString expression = _sqfExecQueue[0]; + int from = _sqfExecFrom[0]; + _sqfExecQueue.Delete(0); + _sqfExecFrom.Delete(0); + + GameVarSpace local(false); + int gshandle = execState->BeginContext(&local); + GameValue result = NOTHING; + bool evaluated = false; +#if defined(_MSC_VER) + evaluated = SDZ_TryEvaluateSqf(execState, expression, mission, &result); +#else + result = execState->EvaluateMultiple(expression, GameState::EvalContext::_default, mission); + evaluated = true; +#endif + RString answer; + if (evaluated && !result.GetNil()) answer = result.GetText(); + if (from == BOT_CLIENT) + RptF("SDZ_BE_RCON: SQF evaluation %s", evaluated ? "completed" : "failed (see preceding exception)"); + result = NOTHING; + execState->EndContext(gshandle); + + if (from != BOT_CLIENT && answer.GetLength() > 0) + { + NetworkCommandMessage msg; + msg._type = NCMTExecResult; + msg._content.WriteString(answer); + SendMsg(from, &msg, NMFGuaranteed); + } + } + _sqfExecBusy = false; +} + +#endif // _ENABLE_DEDICATED_SERVER + +void ServerQueueItem::SetFence(const RefR &resultMsg) +{ + if (poInfo) poInfo->_fence = resultMsg; +} + +DWORD NetworkServer::SendMsg +( + int to, NetworkMessage *msg, + NetworkMessageType type, NetMsgFlags dwFlags, + NetworkPlayerObjectInfo *poInfo +) +{ +#if _ENABLE_MP + NetworkMessageFormatBase *format = GetFormat(type); + if (!format) return 0xffffffff; + + if (IsLocalClient(to)) + { + msg->size = 0; + NetworkClient *client = _parent->GetClient(); + client->AddLocalMessage(TO_SERVER, type, msg); + return 0; + } + else if (dwFlags & NMFGuaranteed) + { + msg->size = CalculateMessageSize(msg, type); +#if _ENABLE_CHEATS +StatMsgSent(type, msg->size, dwFlags); +#endif + if (dwFlags&NMFHighPriority) + { + SendMsgRemote(to,msg,type,dwFlags|NMFStatsAlreadyDone, poInfo ? &poInfo->_fence : NULL, NULL); + return 0; + } + else + { + EnqueueMsg(to, msg, type, poInfo); + return 0; + } + } + else + { + msg->size = CalculateMessageSize(msg, type); +#if _ENABLE_CHEATS +StatMsgSent(type, msg->size, dwFlags); +#endif + //invalidate fence when message is acknowledged + RefR fence; + if (poInfo && poInfo->_fence) + { + if ( poInfo->_fence->WasReceived() ) poInfo->_fence = NULL; + else fence = poInfo->_fence; + } + EnqueueMsgNonGuaranteed(to, msg, type, fence); + return 1; + } +#else + return E_FAIL; +#endif +} diff --git a/lib/UI/HUDInfo.cpp b/lib/UI/HUDInfo.cpp index ee5e8a75..0c6cc256 100644 --- a/lib/UI/HUDInfo.cpp +++ b/lib/UI/HUDInfo.cpp @@ -1,2767 +1,2767 @@ -// Poseidon - HUD UI drawing - -#include "../wpch.hpp" -#include "../world.hpp" -#include "../AI/ai.hpp" -#include "../Inventory/inventory.hpp" -#include "../keyInput.hpp" -#include "../joystick.hpp" -#include "InGameUIImpl.hpp" -#include "../engine.hpp" -#include "../camera.hpp" -#include "../visibility.hpp" -#include "../landscape.hpp" -#include "../txtPreload.hpp" -#include "../house.hpp" -#include "../diagModes.hpp" -#include "../Network/network.hpp" -#include - -#include "resincl.hpp" - -#include "../move_actions.hpp" - -#include "../stringtableExt.hpp" - -#include "../drawText.hpp" -#include "chat.hpp" - -#include "uiViewport.hpp" - -#include "../helicopter.hpp" - -#define INV_H_PI (1/H_PI) - -#if _ENABLE_CHEATS -static bool tdCheat; -#endif - -extern void PositionToAA11(Vector3Val pos, char *buffer); - -#define v000 VZero -#define v001 VForward -#define v100 VAside -#define v101 Vector3(1, 0, 1) - -#define MIN_X (-1.0 * H_PI) -#define MAX_X (1.0 * H_PI) -#define MIN_Y (-0.25 * H_PI) -#define MAX_Y (0.25 * H_PI) -#define TOT_W (MAX_X - MIN_X) -#define TOT_H (MAX_Y - MIN_Y) -#define INV_W (1.0 / TOT_W) -#define INV_H (1.0 / TOT_H) - -//max helicopter speed for analogue gauge - 400km/h -#define MAX_HELICOPTER_SPEED 83.333f -#define MAX_HELICOPTER_HEIGHT 6000.0 - -// DayZ status icons: 5 art variants per family, 0 = full ... 4 = empty -static int StatusIconLevel(float ratio) -{ - if (ratio >= 0.8f) return 0; - if (ratio >= 0.6f) return 1; - if (ratio >= 0.4f) return 2; - if (ratio >= 0.2f) return 3; - return 4; -} - -static Texture *DayZStatusTexture(int family, int level) -{ - // Keep a Ref<> so the textures stay alive even when they are not displayed. - static Ref textures[5][5]; - static bool initialized = false; - if (!initialized) - { - static const char *names[5] = {"thirst","hunger","temperature","blood","health"}; - int loaded = 0; - for (int f=0; f<5; f++) - { - for (int l=0; l<5; l++) - { - char path[128]; - // NOTE: no leading backslash. QFBankQueryFunctions::AutoBank matches - // the PBO prefix ("DZ\ui\") from the very first character, so a - // leading '\' makes the lookup miss the bank and the texture fails. - sprintf(path, "DZ\\ui\\data\\igui\\hud\\status\\%s_%d_ca.paa", names[f], l); - textures[f][l] = GlobLoadTextureUI(path); - if (textures[f][l]) loaded++; - } - } - RptF("[HUD-STATUS] %d/25 status textures loaded", loaded); - initialized = true; - } - if (level < 0) level = 0; - if (level > 4) level = 4; - return textures[family][level]; -} - -static void DrawStatusIconAbs(Texture *texture, float x, float y, float size) -{ - if (!texture) return; - Draw2DParsExt pars; - pars.mip = GEngine->TextBank()->UseMipmap(texture, 0, 0); - pars.SetColor(PackedWhite); - pars.Init(); - GEngine->Draw2D(pars, Rect2DAbs(x, y, size, size)); -} - -void InGameUI::DrawUnitInfo(EntityAIFull *vehicle) -{ - AIBrain *agent = GWorld->FocusOn(); - if (!agent) return; - vehicle = agent->IsInCargo() ? agent->GetPerson() : agent->GetVehicle(); - - const VehicleType *type = vehicle->GetType(); - Transport *transport = dyn_cast(vehicle); - - PackedColor color, barBlinkColor; - if (_blinkState) - barBlinkColor = barBlinkOnColor; - else - barBlinkColor = barBlinkOffColor; - - // resize - const AutoArray &infos = Glob.config.UseExtendetInfoType()? type->GetUnitInfoTypes(): type->GetUnitInfoTypesLite(); - int n = infos.Size(); - _lastUnitInfos.Resize(n); - if (n == 0) return; - - for (int i=0; iReload(Pars >> "RscInGameUI" >> desc._name); - desc._changed = Glob.uiTime; - } - - DisplayUnitInfo *disp = desc._display; - - // [HUD-DBG] temporary diagnostics for the DayZ status icons - { - static int dbgFrame = 0; - if (dbgFrame < 6 || (dbgFrame % 600) == 0) - { - RptF("[HUD-DBG] frame=%d showUI=%d n=%d name='%s' disp=%p thirst=%p hunger=%p temp=%p blood=%p health=%p", - dbgFrame, (int)_showUnitInfo, n, (const char *)desc._name, disp, - (void*)disp->statusThirst.GetRef(), (void*)disp->statusHunger.GetRef(), - (void*)disp->statusTemperature.GetRef(), (void*)disp->statusBlood.GetRef(), - (void*)disp->statusHealth.GetRef()); - if (disp->statusThirst) - { - RptF("[HUD-DBG] thirst rect x=%g y=%g w=%g h=%g", - disp->statusThirst->X(), disp->statusThirst->Y(), - disp->statusThirst->W(), disp->statusThirst->H()); - } - } - dbgFrame++; - } - - // reset the dialog size to original - CStatic *bg = disp->background; - if (bg) bg->SetPos(bg->X(), bg->Y(), disp->backgroundWidth, disp->backgroundHeight); - - // set the controls - - char buffer[256]; - Rank rank = agent->GetPerson()->GetRank(); - bool dirty = false; - - /* -- TIME -- */ - if (disp->time) - { - disp->time->SetTime(Glob.clock); - dirty = true; // ??? - } - - /* -- DATE -- */ - if (disp->date) - { - Glob.clock.FormatDate(LocalizeString(IDS_DATE_FORMAT), buffer); - if (disp->date->SetText(buffer)) dirty = true; - } - - /* -- NAME -- */ - if (disp->name) - { - if (disp->name->SetText(agent->GetPerson()->GetPersonName())) dirty = true; - } - - /* -- VEHICLE -- */ - if (disp->vehicle) - { - if (disp->vehicle->SetText(vehicle->GetType()->GetShortName())) dirty = true; - } - - /* -- SPEED -- */ - if (disp->speed) - { - float speed = vehicle->RenderVisualState().ModelSpeed().Z(); -#if _VBS3 //speed in knots - if(vehicle->GetType()->IsKindOf(GWorld->Preloaded(VTypeAir))) - speed *= 0.53996; -#endif - -#if _HELISIM_IMPERIAL_SYSTEM - speed = toInt(vehicle->GetType()->ConvertSpeed(speed)); -#else - speed = toInt(3.6 * speed); -#endif - sprintf(buffer, LocalizeString(IDS_UI_SPEED), speed); - - - if (disp->speed->SetText(buffer)) dirty = true; - if(vehicle->DetectStall()> stallWarning) disp->speed->SetTextColor(PackedColor(222,60,60,255)); - else disp->speed->SetTextColor(ftColor); - } - - /* -- RADARRANGE -- */ - if (disp->radarRange) - { - float radarRange = 4000.0f; - - sprintf( - buffer, - LocalizeString(IDS_UI_RADARRANGE), - radarRange - ); - if (disp->radarRange->SetText(buffer)) dirty = true; - } - - /* -- ALT -- */ - if (disp->alt) - { - Vector3Val pos = vehicle->RenderVisualState().Position(); - float y = pos.Y() + vehicle->GetShape()->Min().Y(); -#if _VBS2 - float y0 = GLOB_LAND->SurfaceYAboveWater(pos.X(), pos.Z()); -#else - float y0 = GLOB_LAND->RoadSurfaceYAboveWater(pos.X(), pos.Z()); -#endif - float h = y - y0; - saturate(h, 0, 99999); -#if _VBS3 //height in feet - h *= 3.28084; -#endif - -#if _HELISIM_IMPERIAL_SYSTEM - h = vehicle->GetType()->ConvertHeight(h); -#endif - sprintf(buffer,LocalizeString(IDS_UI_ALT), h); - if (disp->alt->SetText(buffer)) dirty = true; - } - - /* -- HEADING -- */ - if (disp->heading) - { - int canSee = 0; - if (transport) - { - if (agent == transport->ObserverUnit()) canSee = transport->Type()->_commanderCanSee; - else if (agent == transport->PilotUnit()) canSee = transport->Type()->_driverCanSee; - else if (agent == transport->GunnerUnit()) canSee = transport->Type()->_gunnerCanSee; - } - if (canSee & CanSeeCompass) - { - disp->heading->ShowCtrl(true); - - Camera &cam = *GLOB_SCENE->GetCamera(); - Vector3Val dir = cam.Direction(); - - // avoid singularity when heading up - float angle; - if (fabs(dir.X()) + fabs(dir.Z()) > 1e-3) - angle = atan2(dir.X(), dir.Z()); - else - angle = 0; - - int degAngle = toInt(angle * (180.0f / H_PI)); - if (degAngle < 0) degAngle += 360; - BString<16> buffer; - sprintf(buffer, "%03d", degAngle); - - if (disp->heading->SetText(cc_cast(buffer))) dirty = true; - } - else - disp->heading->ShowCtrl(false); - } - - /* -- ALT WANTED-- */ - if (disp->alt_wanted) - { - buffer[0] = 0; - HelicopterAuto* heli = dyn_cast(vehicle); -#if _VBS3 - bool enabled = Glob.config.IsEnabled(DTSimplifiedHeliModel); -#else - bool enabled = true; -#endif - if (heli && enabled) - { - sprintf - ( - buffer, - LocalizeString(IDS_UI_ALT_WANTED), - heli->GetFlyingHeight() * 3.28084 //format in feet intervals - ); - } - if (disp->alt_wanted->SetText(buffer)) dirty = true; - } - - /* -- SPEED WANTED -- */ - if (disp->speed_wanted) - { - HelicopterAuto* heli = dyn_cast(vehicle); - buffer[0] = 0; -#if _VBS3 - bool enabled = Glob.config.IsEnabled(DTSimplifiedHeliModel); -#else - bool enabled = true; -#endif - if (heli && enabled) - { - sprintf( - buffer, - LocalizeString(IDS_UI_SPEED_WANTED), - heli->GetSpeedWanted() * 3.6 * 0.53996 //format in knots - ); - } - if (disp->speed_wanted->SetText(buffer)) dirty = true; - } - - /* -- POSITION -- */ - if (disp->position) - { - PositionToAA11(vehicle->RenderVisualState().Position(), buffer); - if (disp->position->SetText(buffer)) dirty = true; - } - - /* -- ZOOM -- */ - if (disp->opticZoom) - { - buffer[0]=0; - if( GWorld->GetCameraType() == CamGunner) - { - const Camera *camera = GScene->GetCamera(); - if (camera && vehicle->GetOpticsModel(agent->GetPerson())) - sprintf(buffer, "%.1fx", 0.25f / camera->Left()); - } - if (disp->opticZoom->SetText(buffer)) dirty = true; - } - -#if _VBS3 - if(disp->override_status) - { - TurretContext context; - RString text; - if(transport && transport->FindTurret(agent->GetPerson(), context)) - { - if(context._turret) - { - if(context._turret->IsOverridden()) - text = LocalizeString(IDS_TURRET_OVERRIDDEN); - else - if(context._turret->IsOverriding()) - text = LocalizeString(IDS_TURRET_OVERRIDING); - else - if(context._turret->_showOverrideOptics) - text = LocalizeString(IDS_TURRET_GUNNER_VIEW); - } - } - if(disp->override_status->SetText(text)) dirty = true; - } - - //AVRS show nick and bank of helicopters - if(transport) - { - if(disp->nick && disp->nick_val) - { - Vector3 front = transport->Direction(); - float nick = -asin(front.Y()) * (180.0f / H_PI); - sprintf(buffer, "%.1f", nick); - if(disp->nick_val->SetText(buffer)) dirty = true; - PackedColor color = abs(nick) < 10.0f ? ftColor : enemyColor; - disp->nick_val->SetColor(color); - disp->nick->SetColor(color); - } - - if(disp->bank && disp->bank_val) - { - Vector3 aside = transport->DirectionAside(); - float bank = asin(aside.Y()) * (180.0f / H_PI); - sprintf(buffer, "%.1f", bank); - if(disp->bank_val->SetText(buffer)) dirty = true; - PackedColor color = abs(bank) < 10.0f ? ftColor : enemyColor; - disp->bank_val->SetColor(color); - disp->bank->SetColor(color); - } - } - - -#if _VBS3_TI - if(agent->GetPerson()->GetVisionMode() == VMTi) - { - if(disp->ti_background) disp->ti_background->ShowCtrl(); - if(disp->ti_brightness_txt) disp->ti_brightness_txt->ShowCtrl(); - if(disp->ti_contrast_txt) disp->ti_contrast_txt->ShowCtrl(); - if(disp->ti_contrast) disp->ti_contrast->ShowCtrl(); - - if(disp->ti_mode) - { - disp->ti_mode->ShowCtrl(); - int mode = agent->GetPerson()->GetTiModus(); - //TODO: query engine - char* buf[7]={"WHITE - HOT", "BLACK - HOT", "GREEN - HOT", "BLACK - HOT", "ORANGE - HOT", "BLACK - HOT", "COLOR"}; - saturate(mode, 0, 6); - if(disp->ti_mode->SetText(buf[mode])) dirty = true; - } - - if(disp->ti_brightness) - { - disp->ti_brightness->ShowCtrl(); - float bright= GEngine->GetTIBrightness(); - bright /= (TempMax - TempMin); - saturate(bright, 0, 1); - disp->ti_brightness->SetPos(bright); - } - - if(disp->ti_contrast) - { - disp->ti_contrast->ShowCtrl(); - float contr= GEngine->GetTIContrast(); - contr /= ContrastMax; - saturate(contr, 0, 1); - disp->ti_contrast->SetPos(contr); - } - - if(disp->ti_autocontrast) - disp->ti_autocontrast->ShowCtrl(GEngine->GetTIAutoBC()); - - } - else - { - if(disp->ti_background) disp->ti_background->ShowCtrl(false); - if(disp->ti_mode) disp->ti_mode->ShowCtrl(false); - if(disp->ti_brightness_txt) disp->ti_brightness_txt->ShowCtrl(false); - if(disp->ti_brightness) disp->ti_brightness->ShowCtrl(false); - if(disp->ti_contrast_txt) disp->ti_contrast_txt->ShowCtrl(false); - if(disp->ti_contrast) disp->ti_contrast->ShowCtrl(false); - if(disp->ti_autocontrast) disp->ti_autocontrast->ShowCtrl(false); - } -#endif //_VBS3_TI -#endif //_VBS3 - - /* -- EXPERIENCE -- */ - if (disp->valueExp) - { - float expCur = agent->GetPerson()->GetExperience() - AI::ExpForRank(rank); - float expMax = rank >= RankColonel ? - AI::ExpForRank(RankColonel) : - AI::ExpForRank((Rank)(rank + 1)) - AI::ExpForRank(rank); - Assert(expMax > 0); - float expCoef = 0.9 * (expCur / expMax); - saturate(expCoef, 0, 1); - disp->valueExp->SetPos(expCoef); - } - - /* -- COMBAT MODE -- */ - if (disp->combatMode) - { - if (disp->combatMode->SetText(LocalizeString(IDS_IGNORE + agent->GetSemaphore()))) dirty = true; - } - - /* -- HEALTH -- */ - if (disp->valueHealth) - { - float health = 0; - Vehicle *person = agent->GetPerson(); - if (person) - { - health = 1 - person->GetTotalDamage(); - saturate(health, 0, 1); - } - if (health > 0.5) - color = barGreenColor; - else if (health > 0.3) - color = barYellowColor; - else if (health > 0.15) - color = barRedColor; - else - color = barBlinkColor; - disp->valueHealth->SetPos(health); - disp->valueHealth->SetBarColor(color); - } - - /* -- DAYZ STATUS ICONS -- */ - if (disp->statusHealth || disp->statusBlood || disp->statusHunger || disp->statusThirst || disp->statusTemperature) - { - EntityAI *person = agent->GetPerson(); - if (person) - { - GameValue gv; - - float healthVal = 5000; - gv = person->GetVariableValue("health"); - if (!gv.GetNil()) healthVal = gv; - else healthVal = (1 - person->GetTotalDamage()) * 5000; - - float bloodVal = healthVal; - gv = person->GetVariableValue("blood"); - if (!gv.GetNil()) bloodVal = gv; - - float energyVal = 1000; - gv = person->GetVariableValue("energy"); - if (!gv.GetNil()) energyVal = gv; - - float waterVal = 1800; - gv = person->GetVariableValue("water"); - if (!gv.GetNil()) waterVal = gv; - - float vHealth = healthVal / 5000.0f; - float vBlood = bloodVal / 5000.0f; - float vEnergy = energyVal / 1000.0f; - float vWater = waterVal / 1800.0f; - saturate(vHealth, 0, 1); - saturate(vBlood, 0, 1); - saturate(vEnergy, 0, 1); - saturate(vWater, 0, 1); - - // No body temperature variable exists in 0.45: derive the cold level - // from the environment plus player wetness (DZ_WET_COOLING = 6). - float airTemperature = 15.0f; - if (GLandscape) - { - float black, white; - GLandscape->GetTemperature(airTemperature, black, white); - } - float wet = 0; - gv = person->GetVariableValue("wet"); - if (!gv.GetNil()) wet = gv; - saturate(wet, 0, 1); - float effectiveTemperature = airTemperature - wet * 8.0f; - int temperatureLevel; - if (effectiveTemperature >= 10.0f) temperatureLevel = 0; - else if (effectiveTemperature >= 0.0f) temperatureLevel = 1; - else if (effectiveTemperature >= -10.0f) temperatureLevel = 2; - else if (effectiveTemperature >= -20.0f) temperatureLevel = 3; - else temperatureLevel = 4; - - // The engine confines HUD controls to its 4:3 "2D area", which leaves - // the icons well inside the real screen edges. Hide the config - // controls and draw the row directly in absolute screen pixels so it - // sits in the true bottom-right corner at the intended size. - if (GWorld->UserDialog() == NULL) - { - if (disp->statusThirst) disp->statusThirst->ShowCtrl(false); - if (disp->statusHunger) disp->statusHunger->ShowCtrl(false); - if (disp->statusTemperature) disp->statusTemperature->ShowCtrl(false); - if (disp->statusBlood) disp->statusBlood->ShowCtrl(false); - if (disp->statusHealth) disp->statusHealth->ShowCtrl(false); - - Texture *statusTex[5] = - { - DayZStatusTexture(0, StatusIconLevel(vWater)), - DayZStatusTexture(1, StatusIconLevel(vEnergy)), - DayZStatusTexture(2, temperatureLevel), - DayZStatusTexture(3, StatusIconLevel(vBlood)), - DayZStatusTexture(4, StatusIconLevel(vHealth)) - }; - - float screenW = (float)GEngine->WidthBB(); - float screenH = (float)GEngine->HeightBB(); - float iconSize = screenH * 0.052f; - float iconGap = iconSize * 0.10f; - float rowW = 5 * iconSize + 4 * iconGap; - float rowX = screenW - screenW * 0.004f - rowW; - float rowY = screenH - screenH * 0.012f - iconSize; - for (int k = 0; k < 5; k++) - DrawStatusIconAbs(statusTex[k], rowX + k * (iconSize + iconGap), rowY, iconSize); - } - - if (disp->statusThirst || disp->statusHunger || disp->statusTemperature || disp->statusBlood || disp->statusHealth) - { - static int dbgStatus = 0; - if (dbgStatus < 6 || (dbgStatus % 600) == 0) - { - RptF("[HUD-DBG] values h=%.1f b=%.1f e=%.1f w=%.1f air=%.1f wet=%.1f lv=%d,%d,%d,%d,%d", - healthVal, bloodVal, energyVal, waterVal, airTemperature, wet, - StatusIconLevel(vHealth), StatusIconLevel(vBlood), StatusIconLevel(vEnergy), - StatusIconLevel(vWater), temperatureLevel); - } - dbgStatus++; - } - - // (Icons are drawn directly above; the config controls stay hidden.) - } - } - - /* -- ARMOR -- */ - if (disp->valueArmor && vehicle->GetType()) - { - RString state; - disp->valueArmor->Clear(); - AutoArray textureUV = vehicle->GetHitTextureUVForDisplay(); - for( int i=0; iGetHitForDisplay(i))); - - int index = disp->valueArmor->AddString(RString()); - disp->valueArmor->SetValue(index,textureUV[i]); - disp->valueArmor->SetFtColor(index,color); - } - } - - /* -- FUEL -- */ - if (disp->valueFuel) - { - float fuel = 0; - float fuelCapacity = vehicle->GetType()->GetFuelCapacity(); - if (fuelCapacity > 0) - { - fuel = vehicle->GetRenderVisualStateFuel() / fuelCapacity; - saturate(fuel, 0, 1); - } - if (fuel > 0.5) - color = barGreenColor; - else if (fuel > 0.3) - color = barYellowColor; - else if (fuel > 0.15) - color = barRedColor; - else - color = barBlinkColor; - disp->valueFuel->SetPos(fuel); - disp->valueFuel->SetBarColor(color); - } - - /* -- CARGO MAN -- */ - if (disp->cargoMan) - { - if (transport && transport->GetMaxManCargo() > 0) - { - disp->cargoMan->ShowCtrl(true); - sprintf(buffer, LocalizeString(IDS_UI_CARGO_INF), transport->GetManCargoSize()); - if (disp->cargoMan->SetText(buffer)) dirty = true; - } - else - { - disp->cargoMan->ShowCtrl(false); - } - } - - /* -- CARGO FUEL -- */ - if (disp->cargoFuel) - { - if (transport && transport->GetMaxFuelCargo() > 0) - { - disp->cargoFuel->ShowCtrl(true); - sprintf(buffer, LocalizeString(IDS_UI_CARGO_FUEL), transport->GetFuelCargo()); - if (disp->cargoFuel->SetText(buffer)) dirty = true; - } - else - { - disp->cargoFuel->ShowCtrl(false); - } - } - - /* -- CARGO REPAIR -- */ - if (disp->cargoRepair) - { - if (transport && transport->GetMaxRepairCargo() > 0) - { - disp->cargoRepair->ShowCtrl(true); - sprintf(buffer, LocalizeString(IDS_UI_CARGO_REPAIR), transport->GetRepairCargo()); - if (disp->cargoRepair->SetText(buffer)) dirty = true; - } - else - { - disp->cargoRepair->ShowCtrl(false); - } - } - - /* -- CARGO AMMO -- */ - if (disp->cargoAmmo) - { - if (transport && transport->GetMaxAmmoCargo() > 0) - { - disp->cargoAmmo->ShowCtrl(true); - sprintf(buffer, LocalizeString(IDS_UI_CARGO_AMMO), transport->GetAmmoCargo()); - if (disp->cargoAmmo->SetText(buffer)) dirty = true; - } - else - { - disp->cargoAmmo->ShowCtrl(false); - } - } - - float crewWidth = disp->backgroundWidth; - VerySmallArray crew; - if (disp->commander) crew.Add(disp->commander); - if (disp->gunner) crew.Add(disp->gunner); - if (disp->driver) crew.Add(disp->driver); - if (crew.Size() == 3) - { - int pos = 0; - float h = 0; - float w = 0; - if (transport && GWorld->GetMode() == GModeNetware) - { - AIBrain *unit = transport->ObserverUnit(); - if (unit && unit->IsAnyPlayer()) - { - crew[pos]->ShowCtrl(true); - crew[pos]->SetText(unit->GetPerson()->GetPersonName()); - saturateMax(w, crew[pos]->GetTextSize()); - if (disp->_updateHeightByCrew) h += crew[pos]->H(); - pos++; - } - unit = transport->GunnerUnit(); - if (unit && unit->IsAnyPlayer()) - { - crew[pos]->ShowCtrl(true); - crew[pos]->SetText(unit->GetPerson()->GetPersonName()); - saturateMax(w, crew[pos]->GetTextSize()); - if (disp->_updateHeightByCrew) h += crew[pos]->H(); - pos++; - } - unit = transport->PilotUnit(); - if (unit && unit->IsAnyPlayer()) - { - crew[pos]->ShowCtrl(true); - crew[pos]->SetText(unit->GetPerson()->GetPersonName()); - saturateMax(w, crew[pos]->GetTextSize()); - if (disp->_updateHeightByCrew) h += crew[pos]->H(); - pos++; - } - } - for (;posShowCtrl(false); - CStatic *bg = disp->background; - if (bg) - { - float offset = crew[0]->X() - bg->X(); - if (disp->_updateWidthByCrew) saturateMax(crewWidth, w + 2 * offset); - for (int i=0; iSetPos(ctrl->X(), ctrl->Y(), w, ctrl->H()); - } - - bg->SetPos(bg->X(), bg->Y(), crewWidth, disp->backgroundHeight + h); - } - } - - // primary show own weapons, otherwise primary weapon state - WeaponModePtr ptr; - TurretContext context; - WeaponModePtr ptrGunner; - TurretContext contextGunner; - WeaponModePtr counterMeasures; - TurretContext contextCM; - if (transport && transport->IsManualFire() && agent == transport->CommanderUnit() && vehicle->GetPrimaryGunnerTurret(context)) - { - // when manual fire is on, commander is controlling gunner's weapons (even when has own weapons) - ptr = context._weapons->ValidatedCurrentWeapon(); - } -#if _VBS3 //Commander override - else if (vehicle->FindOpticsTurret(agent->GetPerson(), context) && vehicle->CanFireUsing(context)) -#else - else if (vehicle->FindTurret(agent->GetPerson(), context) && vehicle->CanFireUsing(context)) -#endif - { - ptr = context._weapons->ValidatedCurrentWeapon(); -#if _VBS3_LASE_LEAD - DrawLaserRange(context); -#endif - } - if (vehicle->GetPrimaryGunnerTurret(contextGunner)) - { - ptrGunner = contextGunner._weapons->ValidatedCurrentWeapon(); - } - - /* -- WEAPONS -- */ - if (ptr.IsValid()) - { - // non-default weapon is always shown - //if (weapon != 0) dirty = true; // not any more - - int ammoCur = 0; - int maxAmmoCur = 0; - bool noAmmo = true; - // int ammoSum = 0; - // int maxAmmoSum = 0; - int magazines = 0; - float reload = 0; - float reloadTime = 0; - float reloadTimeMax = 0; - RString displayName; - - const MuzzleType *muzzle = ptr.GetMuzzleType(); - const WeaponModeType *mode = ptr.GetWeaponModeType(); - RString weaponMode = mode->_displayName; - displayName = muzzle->_displayName; - - if(_weaponInfoAlpha > 10) dirty = true; - _weaponInfoAlpha = 0; - - const Magazine *currentMagazine = ptr.GetMagazine(); - const Magazine *magazine = currentMagazine; - if (!magazine) - { - // find magazine of first compatible type - for (int i=0; i_magazines.Size(); i++) - { - const MagazineType *type = muzzle->_magazines[i]; - context._weapons->ForEachMagazine([&magazines, &magazine, type](Magazine *mag) -> bool - { - if (mag->Type() != type) return false; // continue - if (mag->GetAmmo() == 0) return false; // continue - magazines++; - if (!magazine) - { - magazine = mag; - } - return false; // continue - }); - //if (magazine) break; // want all magazines - } - - if (magazine) - { - maxAmmoCur = magazine->Type()->_maxAmmo; - } - else if (muzzle->_magazines.Size() > 0) - { - maxAmmoCur = muzzle->_magazines[0]->_maxAmmo; - } - } - else // FIX: wrong calculation of magazines - { - ammoCur = magazine->GetAmmo(); - maxAmmoCur = magazine->Type()->_maxAmmo; - if (magazine->_reloadMagazine > 0) - { - reload = 1; - reloadTime = magazine->_reloadMagazine + magazine->_reload * mode->_reloadTime; - reloadTimeMax = magazine->_reloadMagazineTotal + mode->_reloadTime; - } - else - { - reload = magazine->_reload; - reloadTime = magazine->_reload * mode->_reloadTime; - reloadTimeMax = mode->_reloadTime; - } - - // find magazine of first compatible type - for (int j=0; j_magazines.Size(); j++) - { - const MagazineType *allowedMagazine = muzzle->_magazines[j]; - // reserve magazines - context._weapons->ForEachMagazine([&magazines, magazine, allowedMagazine](Magazine *reserve) -> bool - { - if (reserve == magazine) return false; // continue; - if (reserve->Type() == allowedMagazine) - { - if (reserve->GetAmmo() > 0) magazines++; - } - return false; // continue - }); - } - noAmmo = ammoCur == 0; - } - - if (magazine && magazine->Type()->_maxAmmo == 1) - { - ammoCur = magazines; - if (currentMagazine && currentMagazine->GetAmmo() > 0) ammoCur++; - magazines = 0; - } - - if (maxAmmoCur > 0) - { - color = _weaponInfoColor; - - if (/*ammoCur == 0*/noAmmo || vehicle->IsActionInProgress(MFReload)) - _weaponInfoColor = _weaponUnloadColor; - else if (reload <= 0) - _weaponInfoColor = _weaponReadyColor; - else if (reload <= 0.2) - _weaponInfoColor = _weaponPrepareColor; - else - _weaponInfoColor = _weaponUnloadColor; - - if (disp->valueReload) - { - if(reload > 0.001f && !noAmmo && reloadTimeMax > 0.5f) - { - disp->valueReload->ShowCtrl(true); - disp->valueReload->SetPos(reloadTime); - float range = disp->valueReload->GetRange(); - disp->valueReload->SetRange(0,floatMax(range,reloadTimeMax)); - } - else - { - disp->valueReload->SetRange(0,0); - disp->valueReload->ShowCtrl(false); - } - } - - if (disp->weapon) - { - disp->weapon->ShowCtrl(true); - disp->weapon->SetTextColor(color); - if (disp->weapon->SetText(displayName)) dirty = true; - } - if (disp->ammo) - { - disp->ammo->ShowCtrl(true); - disp->ammo->SetTextColor(color); - // sprintf(buffer, "%d", ammoSum); - if (magazines > 0) - sprintf(buffer, "%d | %d", ammoCur, magazines); - else - sprintf(buffer, "%d", ammoCur); - if(Glob.config.IsEnabled(DTHUDPerm)) - { - if (disp->ammo->SetText(buffer)) dirty = true; - // non-default weapon is always shown - if (!context._weapons->IsDefaultWeapon(ptr)) dirty = true; - } - else disp->ammo->SetText(buffer); - - if((ammoCur + magazines <=0) && displayName.GetLength()<=0) - { - disp->weapon->ShowCtrl(false); - } - } - if (disp->ammoMode) - { - disp->ammoMode->ShowCtrl(true); - disp->ammoMode->SetTextColor(color); - - RString modeAndMag; - if (weaponMode!=displayName && !weaponMode.IsEmpty()) - { - if (magazine && !magazine->Type()->_shortName.IsEmpty()) - modeAndMag = weaponMode+RString(" | ")+magazine->Type()->_shortName; - else - modeAndMag = weaponMode; - } - else - { - if (magazine && !magazine->Type()->_shortName.IsEmpty()) - { - modeAndMag = magazine->Type()->_shortName; - } - } - if (disp->ammoMode->SetText(modeAndMag)) dirty = true; - - if((ammoCur + magazines <=0) && modeAndMag.GetLength()<=0) - { - disp->ammoMode->ShowCtrl(false); - } - } - -#if _VBS3 - if (disp->magazine && magazine) - { - disp->magazine->ShowCtrl(true); - disp->magazine->SetTextColor(color); - if (disp->magazine->SetText(magazine->Type()->_displayName)) dirty = true; - } -#endif - } - else - { - // no ammo or no muzzle - if (disp->weapon) - { - disp->weapon->ShowCtrl(true); - disp->weapon->SetTextColor(_weaponReadyColor); - if (disp->weapon->SetText(displayName)) dirty = true; - } -#if _VBS3 - if (disp->magazine && magazine) - { - if (disp->magazine->SetText(RString())) dirty = true; - } -#endif - if (disp->ammo) - { - //if (disp->ammo->SetText(RString())) dirty = true; - disp->ammo->SetText(RString()); - } - if (disp->ammoMode) - { - RString modeAndMag; - if (weaponMode!=displayName && !weaponMode.IsEmpty()) - { - if (magazine > 0 && !magazine->Type()->_shortName.IsEmpty()) - modeAndMag = weaponMode+RString(" | ")+magazine->Type()->_shortName; - else - modeAndMag = weaponMode; - } - else - { - if (magazine > 0 && !magazine->Type()->_shortName.IsEmpty()) - { - modeAndMag = magazine->Type()->_shortName; - } - } - if (disp->ammoMode->SetText(modeAndMag)) dirty = true; - - if((ammoCur + magazines <=0) && modeAndMag.GetLength()<=0) - { - disp->ammoMode->ShowCtrl(false); - } - } - } - - // update the width - ensure the weapon name will fit always - CStatic *bg = disp->background; - CStatic *weapon = disp->weapon; - CStatic *ammo = disp->ammo; - if (bg && weapon && ammo && disp->_updateWidthByWeapon) - { - float offset = weapon->X() - bg->X(); - float weaponWidth = weapon->GetTextSize(); - float ammoWidth = ammo->GetTextSize(); - float totalWidth = offset + weaponWidth + offset + ammoWidth + offset; - if (totalWidth < crewWidth) - { - float diff = crewWidth - totalWidth; - weaponWidth += 0.5 * diff; - ammoWidth += 0.5 * diff; - totalWidth += diff; - } - weapon->SetPos(weapon->X(), weapon->Y(), weaponWidth, weapon->H()); - ammo->SetPos(weapon->X() + weaponWidth + offset, ammo->Y(), ammoWidth, ammo->H()); - bg->SetPos(bg->X(), bg->Y(), totalWidth, bg->H()); - } - } - else - { - if (disp->weapon) disp->weapon->ShowCtrl(false); - if (disp->ammo) disp->ammo->ShowCtrl(false); - if (disp->ammoMode) disp->ammoMode->ShowCtrl(false); - _weaponInfoAlpha = 0; - } - - /* -- COUNTER MEASURES -- */ - if (transport && transport->CommanderUnit()->GetPerson() && agent == transport->CommanderUnit() && vehicle->FindTurret(agent->GetPerson() ,contextCM)) - { - counterMeasures = contextCM._weapons->ValidatedCurrentCounterMeasures(); - - if (counterMeasures.IsValid()) - { - int ammoCur = 0; - int maxAmmoCur = 0; - bool noAmmo = true; - // int ammoSum = 0; - // int maxAmmoSum = 0; - int magazines = 0; - float reload = 0; - - const Magazine *magazine = counterMeasures.GetMagazine(); - const MuzzleType *muzzle = counterMeasures.GetMuzzleType(); - const WeaponModeType *mode = counterMeasures.GetWeaponModeType(); - RString cmMode = mode->_displayName; - - if (!magazine) - { - // find magazine of first compatible type - for (int i=0; i_magazines.Size(); i++) - { - const MagazineType *type = muzzle->_magazines[i]; - contextCM._weapons->ForEachMagazine([&magazines, &magazine, type](Magazine *mag) -> bool - { - if (mag->Type() != type) return false; // continue - if (mag->GetAmmo() == 0) return false; // continue - magazines++; - if (!magazine) - { - magazine = mag; - } - return false; // continue - }); - //if (magazine) break; // want all magazines - } - - if (magazine) - { - maxAmmoCur = magazine->Type()->_maxAmmo; - } - else if (muzzle->_magazines.Size() > 0) - { - maxAmmoCur = muzzle->_magazines[0]->_maxAmmo; - } - } - else // FIX: wrong calculation of magazines - { - ammoCur = magazine->GetAmmo(); - maxAmmoCur = magazine->Type()->_maxAmmo; - if (magazine->_reloadMagazine > 0) reload = 1; - else reload = magazine->_reload; - - // find magazine of first compatible type - for (int j=0; j_magazines.Size(); j++) - { - const MagazineType *allowedMagazine = muzzle->_magazines[j]; - // reserve magazines - contextCM._weapons->ForEachMagazine([&magazines, magazine, allowedMagazine](Magazine *reserve) -> bool - { - if (reserve == magazine) return false; // continue - if (reserve->Type() == allowedMagazine) - { - if (reserve->GetAmmo() > 0) magazines++; - } - return false; // continue - }); - } - noAmmo = ammoCur == 0; - } - - if (maxAmmoCur > 0) - { - if (/*ammoCur == 0*/noAmmo || vehicle->IsActionInProgress(MFReload)) - color = _weaponUnloadColor; - else if (reload <= 0) - color = _weaponReadyColor; - else if (reload <= 0.2) - color = _weaponPrepareColor; - else - color = _weaponUnloadColor; - } - - if(disp->counterMeasuresAmmo) - { - disp->counterMeasuresAmmo->ShowCtrl(true); - disp->counterMeasuresAmmo->SetTextColor(color); - // sprintf(buffer, "%d", ammoSum); - if (magazines > 0) - sprintf(buffer, "%d | %d", ammoCur, magazines); - else - sprintf(buffer, "%d", ammoCur); - if(Glob.config.IsEnabled(DTHUDPerm)) - { - if (disp->counterMeasuresAmmo->SetText(buffer)) dirty = true; - // non-default weapon is always shown - if (!contextCM._weapons->IsDefaultWeapon(counterMeasures)) dirty = true; - } - else disp->counterMeasuresAmmo->SetText(buffer); - } - if(disp->counterMeasuresMode) - { - disp->counterMeasuresMode->ShowCtrl(true); - disp->counterMeasuresMode->SetTextColor(color); - if (disp->counterMeasuresMode->SetText(cmMode)) dirty = true; - } - } - else - { - if (disp->counterMeasuresAmmo) disp->counterMeasuresAmmo->ShowCtrl(false); - if (disp->counterMeasuresMode) disp->counterMeasuresMode->ShowCtrl(false); - } - } - else - { - if (disp->counterMeasuresAmmo) disp->counterMeasuresAmmo->ShowCtrl(false); - if (disp->counterMeasuresMode) disp->counterMeasuresMode->ShowCtrl(false); - } - - /* -- GUNNER WEAPON -- */ - if (disp->gunnerWeapon) - { - if ( ( contextGunner._gunner != agent->GetPerson() && !transport->IsManualFire()) - && ptrGunner.IsValid()) - { - const Magazine *magazine = ptrGunner.GetMagazine(); - if (magazine) - { - const MuzzleType *muzzle = ptrGunner.GetMuzzleType(); - RString displayName = muzzle->_displayName; - - float reload = 0; - if (magazine->_reloadMagazine > 0) reload = 1; - else reload = magazine->_reload; - - if(magazine->GetAmmo()<=0) - color = _weaponUnloadColor; - else if (reload <= 0) - color = _weaponReadyColor; - else if (reload <= 0.2) - color = _weaponPrepareColor; - else - color = _weaponUnloadColor; - - disp->gunnerWeapon->ShowCtrl(true); - disp->gunnerWeapon->SetTextColor(color); - if (disp->gunnerWeapon->SetText(displayName)) dirty = true; - } - } - else - { - if (disp->gunnerWeapon) disp->gunnerWeapon->ShowCtrl(false); - } - } - -#if _HELISIM_ROTORLIB - bool heliHudDraw = DrawHelicopterUnitInfo(vehicle, agent, disp, dirty); - if(heliHudDraw) dirty = true; -#endif - - if (dirty) - desc._changed = Glob.uiTime; - - float age = 0; - #if !_PROFILE - if (vehicle->GetType()->_hideUnitInfo) - age = Glob.uiTime - desc._changed; - #endif - - bool statusVisible = GWorld->UserDialog() == NULL && - (disp->statusThirst || disp->statusHunger || disp->statusTemperature || - disp->statusBlood || disp->statusHealth); - - if (statusVisible || (age < piDimEndTime && ( - (disp->weapon && disp->weapon->IsVisible()) - || (disp->gunnerWeapon && disp->gunnerWeapon->IsVisible()) - || (disp->speed && disp->speed->IsVisible()) -#if _HELISIM_ROTORLIB - || heliHudDraw -#endif - ))) - { - float alpha = 1.0; - if (age < piDimEndTime && age > piDimStartTime) - alpha = (piDimEndTime - age) / (piDimEndTime - piDimStartTime); - - CStatic *bg = disp->background; - if(bg) bg->ShowCtrl((disp->weapon && disp->weapon->IsVisible()) || (disp->gunnerWeapon && disp->gunnerWeapon->IsVisible()) || (disp->speed && disp->speed->IsVisible())); - if(bg && bg->IsVisible()) _hintTop = bg->Y() + bg->H() + 0.02; - - if (disp->IsReady()) - disp->DrawHUD(vehicle, alpha); - - _weaponInfoAlpha = alpha; - } - } -} - - -#if _HELISIM_ROTORLIB - -static Vector3 GetHudImageOffset( CStatic* child, CControlsGroup* parent,float angle) -{ - Matrix4 mrot(MZero); - - Vector3 position = Vector3 ( - sin(angle) * child->X(), - 0 , - -cos(angle) * child->Y()); - - //rotated position - position = position - Vector3(child->X(), 0, child->Y()) - - Vector3(child->W()* 0.5f, 0, child->H()* 0.5f) + Vector3(parent->W()* 0.5f, 0, parent->H()* 0.5f); - return position; -} - -static Matrix4 GetHudImageRotation(float angle) -{ - Matrix4 mtrans1Att = Matrix4(MTranslation, Vector3(-0.5, 0, -0.5)); - Matrix4 mtrans2Att = Matrix4(MTranslation, Vector3( 0.5, 0, 0.5)); - Matrix4 mrot(MZero); - mrot.SetUpAndDirection(VUp, Vector3( sin(angle), 0,cos(angle))); - mrot = mtrans2Att * mrot * mtrans1Att; - return mrot; -} - -bool InGameUI::DrawHelicopterUnitInfo(EntityAIFull *vehicle, AIBrain *agent, DisplayUnitInfo *disp, bool &dirty) -{ - PROFILE_SCOPE_EX(HUDIf, *); - - bool heliHudDraw = false; - HelicopterRTD *helicopter = dyn_cast(vehicle); - - bool draw = (helicopter != NULL && (vehicle->PilotUnit() == agent || vehicle->CopilotUnit() == agent)); - //draw only when unit is pilot or copilot - if(disp->airSpeedIndicator) disp->airSpeedIndicator->ShowCtrl(draw); - if(disp->altimeter) disp->altimeter->ShowCtrl(draw); - if(disp->attitudeIndicator) disp->attitudeIndicator->ShowCtrl(draw); - if(disp->attitudeIndicatorLite) disp->attitudeIndicatorLite->ShowCtrl(draw); - if(disp->gMeter) disp->gMeter->ShowCtrl(draw); - if(disp->radarAltimeter) disp->radarAltimeter->ShowCtrl(draw); - if(disp->torque) disp->torque->ShowCtrl(draw); - if(disp->winIndicator) disp->winIndicator->ShowCtrl(draw); - if(disp->stabilityIndicator) disp->stabilityIndicator->ShowCtrl(draw); - if(disp->collective) disp->collective->ShowCtrl(draw); - if(disp->trimIndicator) disp->trimIndicator->ShowCtrl(draw); - if(disp->autohover) disp->autohover->ShowCtrl(draw); - if(disp->heliHUDmisc) disp->heliHUDmisc->ShowCtrl(draw); - - if(disp->speedAnalogue) disp->speedAnalogue->ShowCtrl(draw); - if(disp->altitudeAnalogue) disp->altitudeAnalogue->ShowCtrl(draw); - if(disp->compassAnalogue) disp->compassAnalogue->ShowCtrl(draw); - if(disp->stabilityAnalogue) disp->stabilityAnalogue->ShowCtrl(draw); - if(disp->horizonAnalogue) disp->horizonAnalogue->ShowCtrl(draw); - if(disp->statusDamage) disp->statusDamage->ShowCtrl(draw); - - - if(!draw) return heliHudDraw; - - _iguiHMD = false; - - char buffer[256]; - Matrix4 mrot(MZero); - - const int w = GEngine->Width2D(); - const int h = GEngine->Height2D(); - - Draw2DParsExt pars; - pars.spec = NoZBuf|IsAlpha|IsAlphaFog|ClampU|ClampV; - pars.spec|= (_helicopterHUDShadow == 2)? UISHADOW : 0; - pars.SetColor(_helicopterHUDColor); - - Matrix4 mtrans1 = Matrix4(MTranslation, Vector3(-0.5, 0, -0.5)); - Matrix4 mtrans2 = Matrix4(MTranslation, Vector3(0.5, 0, 0.5)); - - /* -- AIRSPPED -- */ - if (disp->airSpeedIndicator) - { - heliHudDraw = true; - disp->airSpeedIndicator->ShowCtrl(draw); - _iguiHMD = true; - - float airSpeed = helicopter->GetAirspeedIndicatorRTD(helicopter->RenderVisualState()); -#if _HELISIM_IMPERIAL_SYSTEM - airSpeed = vehicle->GetType()->ConvertSpeed(airSpeed); -#else - airSpeed = (airSpeed*3.6f); -#endif - - if (disp->airSpeedIndicatorAxis) - { - Rect2DPixel rect( - (disp->airSpeedIndicator->X() + disp->airSpeedIndicatorAxis->X()) * w, - (disp->airSpeedIndicator->Y() + disp->airSpeedIndicatorAxis->Y()) * h, - disp->airSpeedIndicatorAxis->W() * w, - disp->airSpeedIndicatorAxis->H() * h); - - //texture has 11 segments - 10 to show, 1 for sliding reserve; one segments is 20 m/s - float elementSize = 1/ 11.0f; - float vOffset = fmod(airSpeed,20) / 20.0f; - vOffset = (vOffset >= 0) ? (vOffset * elementSize): ((vOffset + 1) * elementSize); - - - float vTop = elementSize - vOffset; - float vBottom = 11 * elementSize - vOffset; - - Vector3 uv =v000; - pars.uTR = uv[2]; - pars.vTR = vTop; - uv = v001; - pars.uTL = uv[2]; - pars.vTL = vTop; - uv = v100; - pars.uBR = uv[2]; - pars.vBR = vBottom; - uv = v101; - pars.uBL = uv[2]; - pars.vBL = vBottom; - - pars.mip = GEngine->TextBank()->UseMipmap(_helicopterHUDAxis, 0, 0); - GEngine->Draw2D(pars, rect, rect); - } - char buffer[256]; - sprintf(buffer, "%03d", (int)(airSpeed)); - - if(disp->airSpeedIndicatorValue) disp->airSpeedIndicatorValue->SetText(buffer); - dirty = true; - } - - /* -- ALTIMETER -- */ - if (disp->altimeter) - { - heliHudDraw = true; - _iguiHMD = true; - - float height = helicopter->GetAltBaroRTD(helicopter->RenderVisualState()); // km/h - -#if _HELISIM_IMPERIAL_SYSTEM - height = vehicle->GetType()->ConvertHeight(height); -#endif - - char buffer[256]; - - if (disp->altimeterAxis) - { - Rect2DPixel rect( - disp->altimeter->X() * w, - disp->altimeter->Y() * h, - disp->altimeter->W() * w, - disp->altimeter->H() * h); - - Rect2DPixel rectAxis( - (disp->altimeter->X() + disp->altimeterAxis->X()) * w, - (disp->altimeter->Y() + disp->altimeterAxis->Y()) * h, - disp->altimeterAxis->W() * w, - disp->altimeterAxis->H() * h); - - //texture has 11 segments - 10 to show, 1 for sliding reserve; one segments is 20 m/s - float elementSize = 1/ 11.0f; - float vOffset = fmod(height,20) / 20.0f; - vOffset = (vOffset >= 0) ? (vOffset * elementSize): ((vOffset + 1) * elementSize); - - float vTop = elementSize - vOffset; - float vBottom = 11 * elementSize - vOffset; - - Vector3 uv =v001; - pars.uTR = uv[2]; - pars.vTR = vTop; - uv = v000; - pars.uTL = uv[2]; - pars.vTL = vTop; - uv = v101; - pars.uBR = uv[2]; - pars.vBR = vBottom; - uv = v100; - pars.uBL = uv[2]; - pars.vBL = vBottom; - - pars.mip = GEngine->TextBank()->UseMipmap(_helicopterHUDAxis, 0, 0); - GEngine->Draw2D(pars, rectAxis, rectAxis); - - float speedY = helicopter->GetVertSpeedRTD(helicopter->RenderVisualState()); - speedY = speedY / 15.0f; - - float sizeX = rectAxis.w * 0.5f; - float sizeY = rectAxis.w * 0.5f; - Rect2DPixel rectIndicator( - rectAxis.x - sizeX, - rectAxis.y + 0.5f * (rectAxis.h - sizeY) - speedY * rectAxis.h * 0.5f, - sizeX, - sizeY); - - pars.mip = GEngine->TextBank()->UseMipmap(_indicator, 0, 0); - GEngine->Draw2D(pars, rectIndicator, rect); - - //height = floorf(height); - //float lowerHeight = height - fmod(height,100); - //float higherHeight = lowerHeight + 100; - //float heightDiff = (height - lowerHeight) / 100.0f; - - //sprintf(buffer, "%03d", (int)lowerHeight); - //float x = rectIndicator.x / w; - //float y = (rectAxis.y + rectAxis.h * 0.5f + heightDiff * rectAxis.h * 0.5f - _helicopterHUDfontSizeSmall *0.4) / w; - //GEngine->DrawText - // ( - // Point2DFloat(x, y), - // _helicopterHUDfontSizeSmall, _helicopterHUDtextFont, _helicopterHUDColor, buffer, _helicopterHUDShadow - // ); - - //sprintf(buffer, "%03d", (int)higherHeight); - //y = (rectAxis.y + rectAxis.h * 0.5f + (heightDiff - 1) * rectAxis.h * 0.5f - _helicopterHUDfontSizeSmall *0.4) / w; - //GEngine->DrawText - // ( - // Point2DFloat(x, y), - // _helicopterHUDfontSizeSmall, _helicopterHUDtextFont, _helicopterHUDColor, buffer, _helicopterHUDShadow - // ); - } - - sprintf(buffer, "%03d", (int)height); - if(disp->altimeterValue) disp->altimeterValue->SetText(buffer); - - dirty = true; - } - - /* -- ATTITUDE -- */ - if (disp->attitudeIndicator) - { - heliHudDraw = true; - _iguiHMD = true; - - Rect2DPixel rect( - disp->attitudeIndicator->X() * w, - disp->attitudeIndicator->Y() * h, - disp->attitudeIndicator->W() * w, - disp->attitudeIndicator->H() * h); - - Rect2DPixel rectClip( - disp->attitudeIndicator->X() * w, - disp->attitudeIndicator->Y() * h, - disp->attitudeIndicator->W() * w, - disp->attitudeIndicator->H() * h); - - float aspectRatio = (rect.h / rect.w); - - float pitch, bank; - helicopter->GetAttitude(helicopter->RenderVisualState(),pitch,bank); - - bool externalCamera = (GWorld->GetCameraType() == CamExternal); - //in external camera, _horizonAxes are rotated in opposite direction - - float cosXa = cos(bank); - float sinXa = sin(bank); - - float offset = -pitch / H_PI; - float visibleAngle = _attitudeFOV / H_PI; - - Matrix4 mtrans1Att = Matrix4(MTranslation, Vector3(-0.5 , 0, -0.5 )); - Matrix4 mtrans2Att = Matrix4(MTranslation, Vector3( 0.5 + offset, 0, 0.5 )); - Matrix4 mtransScale = Matrix4(MScale, visibleAngle, 1, 1); - Matrix4 mtransScaleAps = Matrix4(MScale, aspectRatio, 1, 1); - - if(externalCamera) mrot.SetUpAndDirection(VUp, Vector3(0, 0, 1)); - else mrot.SetUpAndDirection(VUp, Vector3(sinXa, 0, cosXa)); - - Matrix4 m = mtrans2Att * mtransScale * mrot * mtransScaleAps * mtrans1Att; - - Vector3 uv = m.FastTransform(Vector3(0 , 0, 1)); - pars.uTR = uv[2]; - pars.vTR = uv[0]; - uv = m.FastTransform(Vector3(0 , 0, 0)); - pars.uTL = uv[2]; - pars.vTL = uv[0]; - uv = m.FastTransform(Vector3(1 , 0, 1)); - pars.uBR = uv[2]; - pars.vBR = uv[0]; - uv = m.FastTransform(Vector3(1 , 0, 0)); - pars.uBL = uv[2]; - pars.vBL = uv[0]; - - pars.mip = GEngine->TextBank()->UseMipmap(_horizonAxes, 0, 0); - GEngine->Draw2D(pars, rect, rectClip); - - float elementSize = disp->attitudeIndicator->W() * w * _attitudeElemmentsSize; - Rect2DPixel rectAircraft = Rect2DPixel( - disp->attitudeIndicator->X() * w + 0.5 * (w * disp->attitudeIndicator->W() - elementSize), - disp->attitudeIndicator->Y() * h + 0.5 * (h * disp->attitudeIndicator->H() - elementSize), - elementSize, - elementSize); - - mtrans1Att = Matrix4(MTranslation, Vector3(-0.5, 0, -0.5)); - mtrans2Att = Matrix4(MTranslation, Vector3( 0.5, 0, 0.5)); - - if(externalCamera) mrot.SetUpAndDirection(VUp, Vector3(sinXa, 0, cosXa)); - else mrot.SetUpAndDirection(VUp, Vector3(0, 0, 1)); - - m = mtrans2Att * mrot * mtrans1Att; - - uv = m.FastTransform(v000); - pars.uTR = uv[2]; - pars.vTR = uv[0]; - uv = m.FastTransform(v001); - pars.uTL = uv[2]; - pars.vTL = uv[0]; - uv = m.FastTransform(v100); - pars.uBR = uv[2]; - pars.vBR = uv[0]; - uv = m.FastTransform(v101); - pars.uBL = uv[2]; - pars.vBL = uv[0]; - - pars.mip = GEngine->TextBank()->UseMipmap(_horizonAircraft, 0, 0); - GEngine->Draw2D(pars, rectAircraft, rectClip); - - Vector3 speed = helicopter->RenderVisualState().ModelSpeed() / 50.0f; - - Rect2DPixel rectVector = Rect2DPixel( - disp->attitudeIndicator->X() * w + 0.5 * (w * disp->attitudeIndicator->W() - elementSize) + disp->attitudeIndicator->W() * w * speed.X(), - disp->attitudeIndicator->Y() * h + 0.5 * (h * disp->attitudeIndicator->H() - elementSize) - disp->attitudeIndicator->H() * h * speed.Y(), - elementSize, - elementSize); - - - mtrans1Att = Matrix4(MTranslation, Vector3( + rectVector.w *0.5f - (rectAircraft.x - rectAircraft.w *0.5f), 0, + rectVector.h *0.5f - (rectAircraft.y - rectAircraft.h *0.5f))); - mtrans2Att = Matrix4(MTranslation, Vector3( - rectVector.w *0.5f + (rectAircraft.x - rectAircraft.w *0.5f), 0, - rectVector.h *0.5f + (rectAircraft.y - rectAircraft.h *0.5f))); - if(externalCamera) mrot.SetUpAndDirection(VUp, Vector3(-sinXa, 0, cosXa)); - else mrot.SetUpAndDirection(VUp, Vector3(0, 0, 1)); - - m = mtrans2Att * mrot * mtrans1Att; - Vector3 xz = m.FastTransform(Vector3(rectVector.x, 0, rectVector.y)); - rectVector.x = xz.X(); - rectVector.y = xz.Z(); - - pars.mip = GEngine->TextBank()->UseMipmap(_horizonVector, 0, 0); - GEngine->Draw2D(pars, rectVector, rectClip); - - dirty = true; - } - - if (disp->attitudeIndicatorLite) - { - _iguiHMD = true; - //if(GInput.lookAroundEnabled || Glob.config.vehicleFreelook) disp->attitudeIndicatorLite->ShowCtrl(false); - //else - { - float pitch, bank; - helicopter->GetAttitude(helicopter->RenderVisualState(),pitch,bank); - - float cosXa = cos(bank); - float sinXa = sin(bank); - - bool externalCamera = (GWorld->GetCameraType() == CamExternal); - const Camera *camera = GScene->GetCamera(); - //in external camera, _horizonAxes are rotated in opposite direction - - float elementSize = disp->attitudeIndicatorLite->W() * w * _attitudeElemmentsSize; - - Vector3 cursorDir = helicopter->RenderVisualState().DirectionModelToWorld(Vector3(0,0,1)); - Rect2DAbs rectAbs; - - if(DrawCursorCoordinates(*camera, helicopter, cursorDir, 1, 0, 0, 0, 0, rectAbs)) - { - - Rect2DAbs rectAircraft = Rect2DAbs( - rectAbs.x + 0.5 * ( - elementSize), - rectAbs.y + 0.5 * ( - elementSize), - elementSize, - elementSize); - - Matrix4 mtrans1Att = Matrix4(MTranslation, Vector3(-0.5, 0, -0.5)); - Matrix4 mtrans2Att = Matrix4(MTranslation, Vector3( 0.5, 0, 0.5)); - - if(externalCamera) mrot.SetUpAndDirection(VUp, Vector3(sinXa, 0, cosXa)); - else mrot.SetUpAndDirection(VUp, Vector3(0, 0, 1)); - - Matrix4 m = mtrans2Att * mrot * mtrans1Att; - - Vector3 uv = m.FastTransform(v000); - pars.uTR = uv[2]; - pars.vTR = uv[0]; - uv = m.FastTransform(v001); - pars.uTL = uv[2]; - pars.vTL = uv[0]; - uv = m.FastTransform(v100); - pars.uBR = uv[2]; - pars.vBR = uv[0]; - uv = m.FastTransform(v101); - pars.uBL = uv[2]; - pars.vBL = uv[0]; - - pars.mip = GEngine->TextBank()->UseMipmap(_horizonAircraft, 0, 0); - GEngine->Draw2D(pars, rectAircraft, rectAircraft); - } - - cursorDir = helicopter->RenderVisualState().Speed(); - - if(helicopter->RenderVisualState().Speed().Size() > 1 && DrawCursorCoordinates(*camera, helicopter, cursorDir, 1, 0, 0, 0, 0, rectAbs)) - { - - Rect2DAbs rectVector = Rect2DAbs( - rectAbs.x + 0.5 * (- elementSize), - rectAbs.y + 0.5 * (- elementSize), - elementSize, - elementSize); - - Matrix4 mtrans1Att = Matrix4(MTranslation, Vector3(-0.5, 0, -0.5)); - Matrix4 mtrans2Att = Matrix4(MTranslation, Vector3( 0.5, 0, 0.5)); - - if(externalCamera) mrot.SetUpAndDirection(VUp, Vector3(sinXa, 0, cosXa)); - else mrot.SetUpAndDirection(VUp, Vector3(0, 0, 1)); - - Matrix4 m = mtrans2Att * mrot * mtrans1Att; - - Vector3 uv = m.FastTransform(v000); - pars.uTR = uv[2]; - pars.vTR = uv[0]; - uv = m.FastTransform(v001); - pars.uTL = uv[2]; - pars.vTL = uv[0]; - uv = m.FastTransform(v100); - pars.uBR = uv[2]; - pars.vBR = uv[0]; - uv = m.FastTransform(v101); - pars.uBL = uv[2]; - pars.vBL = uv[0]; - - pars.mip = GEngine->TextBank()->UseMipmap(_horizonVector, 0, 0); - GEngine->Draw2D(pars, rectVector, rectVector); - } - } - dirty = true; - } - - - /* -- RADAR ALTMETER -- */ - if (disp->radarAltimeter) - { - heliHudDraw = true; - float height = floatMax(0, helicopter->GetRadarAltMeterPosition() - GLOB_LAND->RoadSurfaceYAboveWater(helicopter->RenderVisualState().Position())); - char buffer[256]; - if(height > 304.8)sprintf(buffer, "---"); - else - { -#if _HELISIM_IMPERIAL_SYSTEM - height = vehicle->GetType()->ConvertHeight(height); -#endif - sprintf(buffer, "%.1f", height); - - } - - height = (height > 304)? 1: height / 304.0f; - - if(disp->radarAltimeterBar) disp->radarAltimeterBar->SetPos(height); - if(disp->radarAltimeterValue) disp->radarAltimeterValue->SetText(buffer); - - dirty = true; - } - - /* -- GMETER -- */ - if (disp->gMeter) - { - char buffer[256]; - sprintf(buffer, "%+.2fG", helicopter->GetAccelerometer(helicopter->RenderVisualState())); - - disp->gMeter->SetText(buffer); - dirty = true; - } - - /* -- TORQUE -- */ - if (disp->torque) - { - char buffer[256]; - int torque = 100 * intMax(0.0f, helicopter->GetTorqueRTD(helicopter->RenderVisualState())/ helicopter->Type()->_maxTorque); - sprintf(buffer, "%d%%", torque); - - if(torque > 100) disp->torque->SetTextColor(PackedRed); - else disp->torque->SetTextColor(_helicopterHUDColor); - - disp->torque->SetText(buffer); - dirty = true; - } - - /* -- WIND -- */ - if (disp->winIndicator) - { - Rect2DPixel rect( - disp->winIndicator->X() * w, - disp->winIndicator->Y() * h, - disp->winIndicator->W() * w, - disp->winIndicator->H() * h); - - Vector3 dirA = Vector3(GLandscape->GetWindSpeed().X(), 0, GLandscape->GetWindSpeed().Z()); - dirA.Normalize(); - if (dirA.Size() > 0) - { - Vector3 dirB = helicopter->RenderVisualState().Direction().Normalized(); - - float cosXa = dirB.DotProduct(dirA); - float sinXa = dirB.DotProduct(Vector3(-dirA.Z(),0,dirA.X())); - - mrot.SetUpAndDirection(VUp, Vector3(sinXa, 0, cosXa)); - Matrix4 m = mtrans2 * mrot * mtrans1; - - Vector3 uv = m.FastTransform(v000); - pars.uTR = uv[2]; - pars.vTR = uv[0]; - uv = m.FastTransform(v001); - pars.uTL = uv[2]; - pars.vTL = uv[0]; - uv = m.FastTransform(v100); - pars.uBR = uv[2]; - pars.vBR = uv[0]; - uv = m.FastTransform(v101); - pars.uBL = uv[2]; - pars.vBL = uv[0]; - pars.mip = GEngine->TextBank()->UseMipmap(_windDirection, 0, 0); - GEngine->Draw2D(pars, rect, rect); - - dirty = true; - } - } - - /* -- STABILITY -- */ - if (disp->stabilityIndicator) - { - heliHudDraw = true; - Rect2DPixel rect( - disp->stabilityIndicator->X() * w, - disp->stabilityIndicator->Y() * h, - disp->stabilityIndicator->W() * w, - disp->stabilityIndicator->H() * h); - - Vector3 uv =v100; - pars.uTR = uv[2]; - pars.vTR = uv[0]; - uv = v101; - pars.uTL = uv[2]; - pars.vTL = uv[0]; - uv = v000; - pars.uBR = uv[2]; - pars.vBR = uv[0]; - uv = v001; - pars.uBL = uv[2]; - pars.vBL = uv[0]; - - pars.mip = GEngine->TextBank()->UseMipmap(_stabilityGrid, 0, 0); - GEngine->Draw2D(pars, rect, rect); - - Vector3 speed = helicopter->RenderVisualState().ModelSpeed(); - if (fabs(speed.X() < 13.8f) && speed.Z() < 20.833f && speed.Z() > -13.8f) //speed smaller then 50 km/h - { - float scale = 0.25f; - float sizeX = rect.w * scale; - float sizeY = rect.h * scale; - - float x = rect.x + 0.5f * rect.w; - float y = rect.y + 0.5f * rect.h + 0.1f * rect.h; // 0.1f * size grid is not centred - - x += (speed.X() / 13.8f) * 0.5f * rect.w; - y -= (speed.Z() > 0) ? ((speed.Z()/ 20.833f) * 0.6f * rect.h) : ((speed.Z() / 13.8f) * 0.4f * rect.h); - - Rect2DPixel rectVector( - x - 0.5f * sizeX, - y - 0.5f * sizeY, - sizeX, - sizeY); - - pars.mip = GEngine->TextBank()->UseMipmap(_stabilityVector, 0, 0); - GEngine->Draw2D(pars, rectVector, rect); - } - dirty = true; - } - - /* -- COLLECTIVE -- */ - if (disp->collective) - { - disp->collective->SetPos(helicopter->GetCollective(helicopter->RenderVisualState())); - dirty = true; - } - - /* -- TRIM -- */ - if (disp->trimIndicator) - { - disp->trimIndicator->ShowCtrl(helicopter->GetAutoTrim()); - dirty = true; - } - - /* -- AUTOHOVER -- */ - if (disp->autohover) - { - disp->autohover->ShowCtrl(helicopter->GetAutoHover()); - dirty = true; - } - - // ---------------------- ANALOGUE ---------------------- // - // ---------------------- -------- ---------------------- // - - Vector3 minMoveBorders = GWorld->GetMoveMinBordersHUD(); //mix speed, altitude, direction - Vector3 maxMoveBorders = GWorld->GetMoveMaxBordersHUD(); //max speed, altitude, direction - Vector3 moveDirHUD = VZero; - - if(GWorld->GetMoveTargetHUD()) moveDirHUD = GWorld->GetMoveTargetHUD()->RenderVisualState().Position() - helicopter->RenderVisualState().Position(); - else moveDirHUD = GWorld->GetMovePositionHUD() - helicopter->RenderVisualState().Position(); - moveDirHUD.Normalize(); - - /* -- ANALOGUE SPEED -- */ - if(disp->speedAnalogue) - { - heliHudDraw = true; - float minSpeed = minMoveBorders[0]; - float maxSpeed = maxMoveBorders[0]; - float airSpeed = helicopter->RenderVisualState().ModelSpeed().Z(); // m/s - - PackedColor limitColor = ((fabs(minSpeed) < 0.00001f || minSpeed <= airSpeed) && (maxSpeed>=airSpeed || fabs(maxSpeed) < 0.00001f))? _HUDLimitsColor : _statusDestroyed; - - if (disp->speedAnalogueNeedle) - { - float airSpeed = helicopter->RenderVisualState().ModelSpeed().Z(); // m/s - saturate(airSpeed,-1.388f, MAX_HELICOPTER_SPEED); - float angle = (airSpeed / MAX_HELICOPTER_SPEED )* _analogueSpeedAngleRange - _analogueSpeedAngleOffset; // speed is from 0 degr. to 340 degr. - - disp->speedAnalogueNeedle->SetPictureUVTransfrom(GetHudImageRotation(angle)); - } - - - if (disp->speedAnalogueMin) - { - - if(fabs(minSpeed) < 0.00001f) disp->speedAnalogueMin->ShowCtrl(false); - else - { - disp->speedAnalogueMin->ShowCtrl(true); - saturate(minSpeed,-1.388f, MAX_HELICOPTER_SPEED); - float angle = (minSpeed / MAX_HELICOPTER_SPEED )* _analogueSpeedAngleRange - _analogueSpeedAngleOffset; // speed is from 0 degr. to 340 degr. - - //original position - Vector3 offset = GetHudImageOffset(disp->speedAnalogueMin, disp->speedAnalogue, angle); - //move to 0,0, move rotated position and rotate - disp->speedAnalogueMin->SetPictureOffset(offset.X(), offset.Z()); - disp->speedAnalogueMin->SetPictureUVTransfrom(GetHudImageRotation(angle)); - disp->speedAnalogueMin->SetColor(limitColor); - } - } - - if (disp->speedAnalogueMax) - { - - if(fabs(maxSpeed) < 0.00001f) disp->speedAnalogueMax->ShowCtrl(false); - else - { - disp->speedAnalogueMax->ShowCtrl(true); - saturate(maxSpeed,-1.388f, MAX_HELICOPTER_SPEED); - float angle = (maxSpeed / MAX_HELICOPTER_SPEED )* _analogueSpeedAngleRange - _analogueSpeedAngleOffset; // speed is from 0 degr. to 340 degr. - - //original position - Vector3 offset = GetHudImageOffset(disp->speedAnalogueMax, disp->speedAnalogue, angle); - - //move to 0,0, move rotated position and rotate - disp->speedAnalogueMax->SetPictureOffset(offset.X(), offset.Z()); - disp->speedAnalogueMax->SetPictureUVTransfrom(GetHudImageRotation(angle)); - disp->speedAnalogueMax->SetColor(limitColor); - } - } - - if (disp->speedAnalogueValue) - { - float speed = helicopter->RenderVisualState().ModelSpeed().Z(); // m/s - float speedMS = speed; - -#if _HELISIM_IMPERIAL_SYSTEM - speed = toInt(vehicle->GetType()->ConvertSpeed(speed)); -#else - speed = toInt(3.6 * speed); -#endif - sprintf(buffer, "%.0f", speed); - if (disp->speedAnalogueValue->SetText(buffer)) dirty = true; - - if(speedMS > helicopter->Type()->_retreatBladeStallWarningSpeed) disp->speedAnalogueValue->SetTextColor(_statusDestroyed); - else if (speedMS > 0.9f * helicopter->Type()->_retreatBladeStallWarningSpeed) disp->speedAnalogueValue->SetTextColor(_statusDamaged); - else - { - if(disp->altitudeAnalogueValue) disp->speedAnalogueValue->SetTextColor(disp->altitudeAnalogueValue->GetTextColor()); - else disp->speedAnalogueValue->SetTextColor(PackedWhite); - } - } - - if (disp->speedAnalogueMetric) disp->speedAnalogueMetric->ShowCtrl(Glob.config.useImperialSystem == 0); - if (disp->speedAnalogueImperial) disp->speedAnalogueImperial->ShowCtrl(Glob.config.useImperialSystem > 0); - } - - /* -- ANALOGUE ALTITUDE -- */ - if(disp->altitudeAnalogue) - { - heliHudDraw = true; - Vector3Val pos = vehicle->RenderVisualState().Position(); - float y = pos.Y() + vehicle->GetShape()->Min().Y(); -#if _VBS2 - float y0 = GLOB_LAND->SurfaceYAboveWater(pos.X(), pos.Z()); -#else - float y0 = GLOB_LAND->RoadSurfaceYAboveWater(pos.X(), pos.Z()); -#endif - float h = y - y0; - saturate(h, 0, 99999); - - float altitudeMin = minMoveBorders[1]; - float altitudeMax = maxMoveBorders[1]; - PackedColor limitColor = (altitudeMin <= h && (altitudeMax>=h || altitudeMax <=0.00001f))? _HUDLimitsColor : _statusDestroyed; - - - if (disp->altitudeAnalogueNeedle) - { - float altitude = h; - saturate(altitude, 0, MAX_HELICOPTER_HEIGHT); - float angle = (log((altitude / MAX_HELICOPTER_HEIGHT) * 26 + 1) / log(27)) * _analogueAltitudeAngleRange - _analogueAltitudeAngleOffset; // 300m = 33%, 1000m = 66%, 4000m =100% - - disp->altitudeAnalogueNeedle->SetPictureUVTransfrom(GetHudImageRotation(angle)); - } - - if (disp->altitudeAnalogueMin) - { - if(fabs(altitudeMin) < 0.00001f) disp->altitudeAnalogueMin->ShowCtrl(false); - else - { - disp->altitudeAnalogueMin->ShowCtrl(true); - saturate(altitudeMin, 0, MAX_HELICOPTER_HEIGHT); - float angle = (log((altitudeMin / MAX_HELICOPTER_HEIGHT) * 26 + 1) / log(27)) * _analogueAltitudeAngleRange - _analogueAltitudeAngleOffset; // 300m = 33%, 1000m = 66%, 4000m =100% - - //original position - Vector3 offset = GetHudImageOffset(disp->altitudeAnalogueMin, disp->altitudeAnalogue, angle); - //move to 0,0, move rotated position and rotate - disp->altitudeAnalogueMin->SetPictureOffset(offset.X(), offset.Z()); - disp->altitudeAnalogueMin->SetPictureUVTransfrom(GetHudImageRotation(angle)); - disp->altitudeAnalogueMin->SetColor(limitColor); - } - } - - if (disp->altitudeAnalogueMax) - { - if(fabs(altitudeMax) < 0.00001f) disp->altitudeAnalogueMax->ShowCtrl(false); - else - { - disp->altitudeAnalogueMax->ShowCtrl(true); - saturate(altitudeMax, 0, MAX_HELICOPTER_HEIGHT); - float angle = (log((altitudeMax / MAX_HELICOPTER_HEIGHT) * 26 + 1) / log(27)) * _analogueAltitudeAngleRange - _analogueAltitudeAngleOffset; // 300m = 33%, 1000m = 66%, 4000m =100% - - //original position - Vector3 offset = GetHudImageOffset(disp->altitudeAnalogueMax, disp->altitudeAnalogue, angle); - - //move to 0,0, move rotated position and rotate - disp->altitudeAnalogueMax->SetPictureOffset(offset.X(), offset.Z()); - disp->altitudeAnalogueMax->SetPictureUVTransfrom(GetHudImageRotation(angle)); - disp->altitudeAnalogueMax->SetColor(limitColor); - } - } - - if (disp->altitudeAnalogueValue) - { -#if _VBS3 //height in feet - h *= 3.28084; -#endif - -#if _HELISIM_IMPERIAL_SYSTEM - h = vehicle->GetType()->ConvertHeight(h); -#endif - sprintf(buffer,"%.0f", h); - disp->altitudeAnalogueValue->SetText(buffer); - } - - if (disp->altitudeAnalogueMetric) disp->altitudeAnalogueMetric->ShowCtrl(Glob.config.useImperialSystem == 0); - if (disp->altitudeAnalogueImperial) disp->altitudeAnalogueImperial->ShowCtrl(Glob.config.useImperialSystem > 0); - } - - /* -- ANALOGUE COMPASS -- */ - if(disp->compassAnalogue) - { - heliHudDraw = true; - if(disp->compassAnalogueNeedle) - { - disp->compassAnalogueNeedle->SetPictureUVTransfrom(GetHudImageRotation(-helicopter->GetCtrlDirection(helicopter->RenderVisualState()))); - } - - float vehicleDir = helicopter->GetCtrlDirection(helicopter->RenderVisualState()); - if(disp->compassAnalogueWind ) - { - Vector3 dir = Vector3(GLandscape->GetWindSpeed().X(), 0, GLandscape->GetWindSpeed().Z()); - if(dir.Size() > 0) - { - dir.Normalize(); - float angle = ((atan2(dir.X(), dir.Z())) - vehicleDir) ; - disp->compassAnalogueWind->SetPictureUVTransfrom(GetHudImageRotation(angle)); - } - } - - if(disp->compassAnalogueWindValue) - { - Vector3 dir = Vector3(GLandscape->GetWindSpeed().X(), 0, GLandscape->GetWindSpeed().Z()); - float speed = dir.Size(); -#if _HELISIM_IMPERIAL_SYSTEM - speed = Glob.config.useImperialSystem > 0 ? METER_TO_MILE_PER_HOUR(speed) : speed; -#endif - sprintf(buffer, "%+.1f", speed); - disp->compassAnalogueWindValue->SetText(buffer); - } - - Vector3Val dir = helicopter->RenderVisualState().Direction(); - - // avoid singularity when heading up - float angleTransport; - if (fabs(dir.X()) + fabs(dir.Z()) > 1e-3) - angleTransport = atan2(dir.X(), dir.Z()); - else - angleTransport = 0; - - if(disp->compassAnalogueValue) - { - int degAngle = toInt(angleTransport * (180.0f / H_PI)); - if (degAngle < 0) degAngle += 360; - - sprintf(buffer, "%03d", degAngle); - disp->compassAnalogueValue->SetText(cc_cast(buffer)); - } - - //target direction - float angleDir = (atan2(moveDirHUD.X(), moveDirHUD.Z()) - vehicleDir); - if(angleDir < - H_PI) angleDir +=H_2PI; - else if(angleDir > H_PI) angleDir -=H_2PI; - - //min target direction - float angleMin = angleDir + minMoveBorders[2]; - if(angleMin < 0) angleMin +=H_2PI; - else if(angleMin > H_2PI) angleMin -=H_2PI; - //max target direction - float angleMax = angleDir + maxMoveBorders[2]; - if(angleMax < 0) angleMax +=H_2PI; - else if(angleMax > H_2PI) angleMax -=H_2PI; - - PackedColor limitColor = (angleMin > angleMax)? _HUDLimitsColor : _statusDestroyed; - - if(disp->compassAnalogueMin ) - { - //rotated position - if(fabs(minMoveBorders[2] - maxMoveBorders[2]) < 0.00001f) disp->compassAnalogueMin->ShowCtrl(false); - else - { - disp->compassAnalogueMin->ShowCtrl(true); - Vector3 offset = GetHudImageOffset(disp->compassAnalogueMin, disp->compassAnalogue, angleMin); - - //move to 0,0, move rotated position and rotate - disp->compassAnalogueMin->SetPictureOffset(offset.X(), offset.Z()); - disp->compassAnalogueMin->SetPictureUVTransfrom(GetHudImageRotation(angleMin)); - disp->compassAnalogueMin->SetColor(limitColor); - } - } - - if(disp->compassAnalogueMax ) - { - //rotated position - - if(fabs(minMoveBorders[2] - maxMoveBorders[2]) < 0.00001f) disp->compassAnalogueMax->ShowCtrl(false); - else - { - disp->compassAnalogueMax->ShowCtrl(true); - Vector3 offset = GetHudImageOffset(disp->compassAnalogueMax, disp->compassAnalogue, angleMax); - - //move to 0,0, move rotated position and rotate - disp->compassAnalogueMax->SetPictureOffset(offset.X(), offset.Z()); - disp->compassAnalogueMax->SetPictureUVTransfrom(GetHudImageRotation(angleMax)); - disp->compassAnalogueMax->SetColor(limitColor); - } - } - - } - - /* -- ANALOGUE STABILITY -- */ - if(disp->stabilityAnalogue) - { - heliHudDraw = true; - if(disp->stabilityAnalogueSpeed) - { - - Vector3 position = - - Vector3(disp->stabilityAnalogueSpeed->X(), 0, disp->stabilityAnalogueSpeed->Y()) - - Vector3(disp->stabilityAnalogueSpeed->W()* 0.5f, 0, disp->stabilityAnalogueSpeed->H()* 0.5f) - + Vector3(disp->stabilityAnalogue->W()* 0.5f, 0, disp->stabilityAnalogue->H()* 0.5f); - - Vector3 offset = Vector3 ( - (disp->stabilityAnalogueSpeed->X() + disp->stabilityAnalogueSpeed->W() * 0.5f ) - disp->stabilityAnalogue->W() * 0.5f, - 0 , - (disp->stabilityAnalogueSpeed->Y() + disp->stabilityAnalogueSpeed->H() * 0.5f ) - disp->stabilityAnalogue->H() * 0.5f); - - Vector3 speed = helicopter->RenderVisualState().ModelSpeed(); - speed[1] = 0; - speed[2] = -speed[2]; - speed = (speed / 13.6f); - if(speed.Size() > 1.0) speed.Normalize(); - - position += Vector3(speed[0] * disp->stabilityAnalogueSpeed->X(), 0, speed[2] * disp->stabilityAnalogueSpeed->Y()); - disp->stabilityAnalogueSpeed->SetPictureOffset(position.X(), position.Z()); - } - - if(disp->stabilityAnalogueValue) - { - float speedY = helicopter->GetVertSpeedRTD(helicopter->RenderVisualState()); -#if _HELISIM_IMPERIAL_SYSTEM - speedY = toInt(vehicle->GetType()->ConvertVerticalSpeed(speedY)); -#else - speedY = toInt(speedY); -#endif - sprintf(buffer, "%+.0f", speedY); - disp->stabilityAnalogueValue->SetText(buffer); - } - - if(disp->stabilityAnalogueVSpeedNeedle) - { - float speedY = helicopter->GetVertSpeedRTD(helicopter->RenderVisualState()); - speedY = speedY / 15.0f; - saturate(speedY, -1, 1); - - float angle = H_PI2 * speedY - H_PI2; - disp->stabilityAnalogueVSpeedNeedle->SetPictureUVTransfrom(GetHudImageRotation(angle)); - } - - if(disp->stabilityAnalogueCollective) - { - float collective = helicopter->GetCollective(helicopter->RenderVisualState()); - saturate(collective, 0, 1); - Rect2DFloat clip = Rect2DFloat(0,1 - collective,0,0); - disp->stabilityAnalogueCollective->SetClipPictureOffsetPerct(clip); - } - - if(disp->stabilityAnalogueVSpeed) - { - - float speedY = helicopter->GetVertSpeedRTD(helicopter->RenderVisualState()); - speedY = speedY / 15.0f; - saturate(speedY, -1, 1); - float y = 0; - float h = 0; - if(speedY > 0) - { - y = (1 - speedY) * 0.5f; - h = - 0.5f - (1 - fabs(speedY)) * 0.5f; - } - else - { - y = 0.5f; - h = - 0.5f - (1 - fabs(speedY)) * 0.5f; - } - - Rect2DFloat clip = Rect2DFloat(0, y ,0, h); - disp->stabilityAnalogueVSpeed->SetClipPictureOffsetPerct(clip); - } - - if(disp->stabilityAnalogueMetric) disp->stabilityAnalogueMetric->ShowCtrl(Glob.config.useImperialSystem == 0); - if(disp->stabilityAnalogueImperial) disp->stabilityAnalogueImperial->ShowCtrl(Glob.config.useImperialSystem > 0); - } - - if(disp->horizonAnalogue) - { - if(disp->horizonAnalogueAttitude) - { - float aspectRatio = (disp->horizonAnalogueAttitude->H() / disp->horizonAnalogueAttitude->W()); - - float pitch, bank; - helicopter->GetAttitude(helicopter->RenderVisualState(),pitch,bank); - - bank -= H_2PI; - float cosXa = cos(-bank); - float sinXa = sin(-bank); - - float offset = -pitch / H_PI; - float visibleAngle = _attitudeFOV / H_PI; - - Matrix4 mtrans1Att = Matrix4(MTranslation, Vector3(-0.5 , 0, -0.5 )); - Matrix4 mtrans2Att = Matrix4(MTranslation, Vector3( 0.5 , 0, 0.5 + offset)); - Matrix4 mtransScale = Matrix4(MScale, 1, 1, visibleAngle); - Matrix4 mtransScaleAps = Matrix4(MScale, 1, 1, aspectRatio); - - mrot.SetUpAndDirection(VUp, Vector3(sinXa, 0, cosXa)); - Matrix4 m = mtrans2Att * mtransScale * mrot * mtransScaleAps * mtrans1Att; - - disp->horizonAnalogueAttitude->SetPictureUVTransfrom(m); - } - - if(disp->horizonAnalogueValue) - { - sprintf(buffer, "%+.1fG", helicopter->GetAccelerometer(helicopter->RenderVisualState())); - disp->horizonAnalogueValue->SetText(buffer); - } - } - - - /* -- DAMAGE -- */ - if(disp->statusDamage) - { - bool batterryOnCharged = (helicopter->IsBatteryOn() && helicopter->GetBatteryCharge() > 0); - - if(disp->statusEnginesRPM) - { - float state = helicopter->GetEngineRPMState(); - if(!batterryOnCharged) disp->statusEnginesRPM->SetColor(_statusOff); - else if(state < 0.2) disp->statusEnginesRPM->SetColor(_statusDestroyed); - else if(state < 0.9) disp->statusEnginesRPM->SetColor(_statusDamaged); - else disp->statusEnginesRPM->SetColor(_statusOn); - } - - if(disp->statusEnginesDamage) - { - float damage = helicopter->GetEngineMaxDamage(); - if(!batterryOnCharged) disp->statusEnginesDamage->SetColor(_statusOff); - else if(damage > 0.8) disp->statusEnginesDamage->SetColor(_statusDestroyed); - else if(damage > 0.6) disp->statusEnginesDamage->SetColor(_statusDamaged); - else disp->statusEnginesDamage->SetColor(_statusOn); - } - - if(disp->statusTorque) - { - float torque = GWorld->IsStressDamageEnabled() ? floatMax(0.0f, helicopter->GetTorqueRTD(helicopter->RenderVisualState())/ helicopter->Type()->_maxTorque) : 0; - if(!batterryOnCharged) disp->statusTorque->SetColor(_statusOff); - else if(torque > 1.0) disp->statusTorque->SetColor(_statusDestroyed); - else if(torque > 0.9) disp->statusTorque->SetColor(_statusDamaged); - else disp->statusTorque->SetColor(_statusOn); - } - - if(disp->statusElectricity) - { - float charge = helicopter->GetBatteryCharge() / helicopter->Type()->_maxBatteryCharge; - if(!batterryOnCharged) disp->statusElectricity->SetColor(_statusOff); - else if(charge < 0.15) disp->statusElectricity->SetColor(_statusDestroyed); - else if(charge < 0.3) disp->statusElectricity->SetColor(_statusDamaged); - else disp->statusElectricity->SetColor(_statusOn); - } - - if(disp->statusFuel) - { - float fuel = helicopter->GetFuel() / helicopter->GetType()->GetFuelCapacity(); - if(!batterryOnCharged) disp->statusFuel->SetColor(_statusOff); - else if(fuel < 0.1) disp->statusFuel->SetColor(_statusDestroyed); - else if(fuel < 0.3) disp->statusFuel->SetColor(_statusDamaged); - else disp->statusFuel->SetColor(_statusOn); - } - - if(disp->temperature) - { //changed to temperature, old IDC - float temp = helicopter->GetMaxEngineTemperatureScaled(); - bool hotStart = helicopter->IsHotStart(); - if(!batterryOnCharged) disp->temperature->SetColor(_statusOff); - else if(temp > 1.0) disp->temperature->SetColor(_statusDestroyed); - else if(hotStart) disp->temperature->SetColor(_statusDamaged); - else disp->temperature->SetColor(_statusOn); - } - - if(disp->mainRotor) - { - float damage = helicopter->GetMainRotorDamage(); - if(!batterryOnCharged) disp->mainRotor->SetColor(_statusOff); - else if(damage > 0.8) disp->mainRotor->SetColor(_statusDestroyed); - else if(damage > 0.6) disp->mainRotor->SetColor(_statusDamaged); - else disp->mainRotor->SetColor(_statusOn); - } - - if(disp->tailRotor) - { - float damage = helicopter->GetTailRotorDamage(); - if(!batterryOnCharged) disp->tailRotor->SetColor(_statusOff); - else if(damage > 0.8) disp->tailRotor->SetColor(_statusDestroyed); - else if(damage > 0.6) disp->tailRotor->SetColor(_statusDamaged); - else disp->tailRotor->SetColor(_statusOn); - } - - if(disp->statusAutohover) - { - if (helicopter->GetAutoHover() && batterryOnCharged) disp->statusAutohover->SetColor(_statusOn); - else disp->statusAutohover->SetColor(_statusOff); - } - } - return heliHudDraw; -}; -#endif - -void InGameUI::DrawWeaponInfo(const Camera &camera) -{ - AIBrain *agent = GWorld->FocusOn(); - if (!agent || !agent->GetVehicle()) return; - EntityAIFull *vehicle = agent->GetVehicle(); - - bool scope = (GWorld->GetCameraType() == CamGunner) && vehicle->EnableOptics(vehicle->RenderVisualState()); - - TurretContext context; - WeaponModePtr ptr; - - PackedColor colorElevation = PackedColorRGB(_weaponInfoColor, toIntFloor(_weaponInfoColor.A8() * _weaponInfoAlpha)); - - if (vehicle->FindTurret(agent->GetPerson(), context)) - { - // when manual fire is on, commander is controlling gunner's weapons (even when has own weapons) - ptr = context._weapons->ValidatedCurrentWeapon(); - } - else return; - - const WeaponType *weaponType = NULL; - if (agent->IsFreeSoldier()) - { - if (!ptr.IsValid()) return; - weaponType = ptr.GetWeaponType(); - } - else if(!agent->GetVehicleIn()) return; - - if (weaponType == NULL && context._turretType == NULL) return; - - const MuzzleType *muzzle = ptr.GetMuzzleType(); - if (!muzzle) return; - - const AutoArray &infos = (weaponType!= NULL)? weaponType->GetWeaponInfoTypes():context._turretType->GetTurretInfoTypes(); - int n = infos.Size(); - _lastWeaponInfos.Resize(n); - if (n == 0) return; - - for (int i=0; iReload(Pars >> "RscInGameUI" >> desc._name); - desc._changed = Glob.uiTime; - } - - DisplayWeaponInfo *disp = desc._display; - - // --- ZEROING --- // - if(disp->elevation) - { - disp->elevation->SetTextColor(colorElevation); - - char buffer[256]; sprintf(buffer,""); - //Transport *transport = agent->GetVehicleIn(); - if(agent->IsFreeSoldier() && agent->GetVehicle()) - { - const OpticsInfo *opticsInfo = ptr.GetOpticsInfo(); - DoAssert(opticsInfo); - - float distance = 0; - if (opticsInfo->_discreteDistance.Size() == 0) - { - distance= Interpolativ(agent->GetVehicle()->GetCameraFOV(), opticsInfo->_opticsZoomMin, opticsInfo->_opticsZoomMax, - opticsInfo->_distanceZoomMin, opticsInfo->_distanceZoomMax); - } - else if (ptr.IsValid()) - { - distance = opticsInfo->_discreteDistance[intMin(ptr.GetDiscreteDistanceIndex(), opticsInfo->_discreteDistance.Size()-1)]; - } -#if _HELISIM_IMPERIAL_SYSTEM - //zeroing in meters or feets (miles not even for air) - if(Glob.config.useImperialSystem == 2) sprintf(buffer, "%d", (int)(METER_TO_FEET(distance))); - else sprintf(buffer, "%d", (int)distance); -#else - sprintf(buffer, "%d", (int)distance); -#endif - dirty = disp->elevation->SetText(buffer); - } - else if (ptr.IsValid()) - { - float distance = 0; - - if (muzzle && (muzzle->_ballisticsComputer == 1 || muzzle->_ballisticsComputer == 2) - && context._turretType->_discreteDistance.Size()>0 && context._turret->_distanceIndex >=0) - { - disp->elevation->ShowCtrl(true); - distance = context._turretType->_discreteDistance[intMin(context._turret->_distanceIndex,context._turretType->_discreteDistance.Size()-1)]; -#if _HELISIM_IMPERIAL_SYSTEM - //zeroing in meters or feets (miles not even for air) - if(Glob.config.useImperialSystem == 2) sprintf(buffer, "%d", (int)(METER_TO_FEET(distance))); - else sprintf(buffer, "%d", (int)distance); -#else - sprintf(buffer, "%d", (int)distance); -#endif - dirty = disp->elevation->SetText(buffer); - } - else disp->elevation->ShowCtrl(false); - } - - if(disp->elevationText) - { - disp->elevationText->SetTextColor(colorElevation); - //Transport *transport = agent->GetVehicleIn(); - if(!agent->IsFreeSoldier()) - { - if (muzzle && (muzzle->_ballisticsComputer == 1 || muzzle->_ballisticsComputer == 2) - && context._turretType->_discreteDistance.Size()>0 && context._turret->_distanceIndex >=0) - { - disp->elevationText->ShowCtrl(true); - } - else disp->elevationText->ShowCtrl(false); - } - } - } - - //distance from aimed target/ground - if (disp->distance || disp->GPSTarget) - { - if(disp->distance) disp->distance->ShowCtrl(scope); - if(disp->GPSTarget) disp->GPSTarget->ShowCtrl(scope); - - if(scope) - { - float distance = -1; - char buffer[256]; - //distance to which we try to detect vehicles - float MaxDist = 1500.0f; - const float MaxDistGround = 5000.0f; - /*Vector3 dir = agent->Direction(); - dir.Normalize();*/ - - Matrix4 animTrans; - Vector3 lPos = camera.Position(); - Vector3 lDir = camera.Direction().Normalized(); - - Vector3 tmpEnd; - float tGround = GLandscape->IntersectWithGroundOrSea(&tmpEnd, lPos, lDir, 0, MaxDistGround); - MaxDist = floatMin(tGround,MaxDist); - - CollisionBuffer result; - GLandscape->ObjectCollisionLine(vehicle->GetRenderVisualStateAge(), result, Landscape::FilterIgnoreOne(agent->GetVehicle()), lPos, lPos + lDir * MaxDist, 0/*0.5f*/, ObjIntersectFire, ObjIntersectView, CF_NEAREST_CONTACT); - // select the nearest - if (result.Size() > 0) - { - float dist2 = lPos.Distance2(result[0].pos); - distance = sqrtf(dist2); - } - else if(tGround < MaxDistGround) - { - distance = tGround; - } - -#if _HELISIM_IMPERIAL_SYSTEM - if(distance>=0) - { - if(Glob.config.useImperialSystem == 2) sprintf(buffer,"%d", (int) METER_TO_FEET(distance)); - else sprintf(buffer,"%d", (int)distance); - } -#else - if(distance>=0) sprintf(buffer,"%d", (int)distance); -#endif - else - sprintf(buffer,"--"); - - if(disp->distance) disp->distance->SetText(buffer); - - if(distance>=0) - { - Vector3 targetPos = lPos + lDir*distance; - PositionToAA11(targetPos, buffer); - } - else - sprintf(buffer,"--"); - if(disp->GPSTarget) disp->GPSTarget->SetText(buffer); - } - } - - //position of player - if (disp->GPSPlayer) - { - disp->GPSPlayer->ShowCtrl(scope); - if(scope) - { - char buffer[256]; - PositionToAA11(vehicle->RenderVisualState().Position(), buffer); - disp->GPSPlayer->SetText(buffer); - } - } - - //draw compass - if(scope && disp->showCompass) - DrawCompass(vehicle); - - - //vision mode - normal, night vision, FLIR - if (disp->visionMode) - { - disp->visionMode->ShowCtrl(scope); - if(scope) - { - char buffer[256]; - if (GEngine->GetThermalVisionWanted()) sprintf(buffer,"FLIR"); - else - if (agent->GetPerson() && agent->GetPerson()->IsNVWanted()) sprintf(buffer,"NVS"); - else sprintf(buffer,"DTV"); - - disp->visionMode->SetText(buffer); - } - } - - //FLIR mode black-white, red-black, .... - if (disp->FLIRMode) - { - disp->FLIRMode->ShowCtrl(scope); - if(scope) - { - char buffer[256]; - if (GEngine->GetThermalVisionWanted()) - { - int mode =GEngine->GetTIMode(); - if(mode < sizeof(_FLIRModeNames)) sprintf(buffer,"%s", _FLIRModeNames[mode].Data()); - else sprintf(buffer,""); - } - else - sprintf(buffer,""); - - disp->FLIRMode->SetText(buffer); - } - } - - //show compass (if it is not already) - if (disp->compass) - { - disp->compass->ShowCtrl(scope); - if(scope) - { - bool canSeeCompass = false; - Transport *transport = agent->GetVehicleIn(); - if (transport) - { - int canSee = 0; - if (agent == transport->ObserverUnit()) canSee = transport->Type()->_commanderCanSee; - else if (agent == transport->PilotUnit()) canSee = transport->Type()->_driverCanSee; - else if (agent == transport->GunnerUnit()) canSee = transport->Type()->_gunnerCanSee; - canSeeCompass = (canSee&CanSeeCompass)!=0; - } - - if(!canSeeCompass) DrawCompass(vehicle); - } - } - - //show heading (if it is not already) - if (disp->heading) - { - disp->heading->ShowCtrl(scope); - if(scope) - { - bool canSeeCompass = false; - Transport *transport = agent->GetVehicleIn(); - if (transport) - { - int canSee = 0; - if (agent == transport->ObserverUnit()) canSee = transport->Type()->_commanderCanSee; - else if (agent == transport->PilotUnit()) canSee = transport->Type()->_driverCanSee; - else if (agent == transport->GunnerUnit()) canSee = transport->Type()->_gunnerCanSee; - canSeeCompass = (canSee&CanSeeCompass)!=0; - } - - if(!canSeeCompass) - { - Camera &cam = *GLOB_SCENE->GetCamera(); - Vector3Val dir = cam.Direction(); - - // avoid singularity when heading up - float angle; - if (fabs(dir.X()) + fabs(dir.Z()) > 1e-3) - angle = atan2(dir.X(), dir.Z()); - else - angle = 0; - - int degAngle = toInt(angle * (180.0f / H_PI)); - if (degAngle < 0) degAngle += 360; - BString<16> buffer; - sprintf(buffer, "%03d", degAngle); - - disp->heading->SetText(cc_cast(buffer)); - } - } - } - - //hovering mode - if(disp->autohover) - { - disp->autohover->ShowCtrl(scope); - if(scope) - { - Transport *transport = agent->GetVehicleIn(); - if(transport && transport->GetAutoHover()) disp->autohover->ShowCtrl(true); - else disp->autohover->ShowCtrl(false); - } - } - - //FOV mode - if(disp->FOVMode) - { - disp->FOVMode->ShowCtrl(scope); - if(scope) - { - char buffer[256]; sprintf(buffer,""); - //Transport *transport = agent->GetVehicleIn(); - if (agent->IsFreeSoldier()) - { - const OpticsInfo *opticsInfo = ptr.GetOpticsInfo(); - DoAssert(opticsInfo); - sprintf(buffer, "%s", opticsInfo->_opticsDisplayName.Data()); - } - else if (agent->GetVehicleIn() && context._turret) - { - const ViewPars *view = context._turret->GetCurrentViewPars(context._turretType); - if(view) - sprintf(buffer, "%s", view->_opticsDisplayName.Data()); - } - disp->FOVMode->SetText(buffer); - } - } - - - //hide text if not in optics - if(disp->staticItems) - disp->staticItems->ShowCtrl(scope); - - desc._changed = Glob.uiTime; - float alpha = 1.0; - - if (disp->IsReady()) - disp->DrawHUD(vehicle, alpha); - - if(dirty) _weaponInfoAlpha = 100.0f; - } -} - -void InGameUI::DrawCompass(EntityAIFull *vehicle) -{ - //Texture *textureDef = GLOB_SCENE->Preloaded(TextureWhite); - Texture *texture; - MipInfo mip; - const int w = GEngine->Width2D(); - const int h = GEngine->Height2D(); - - Texture *corner = GLOB_SCENE->Preloaded(Corner); - GEngine->DrawFrame - ( - corner, - bgColor, - Rect2DPixel(coX * w, coY * h, coW * w, coH * h) - ); - - - Camera &cam = *GLOB_SCENE->GetCamera(); - Vector3Val dir = cam.Direction(); - - // avoid singularity when heading up - float xAngle; - if( fabs(dir.X())+fabs(dir.Z())>1e-3 ) - xAngle = atan2(dir.X(), dir.Z()); - else - xAngle=0; - xAngle *= 2 * INV_H_PI; - for (int i=-2; i<=2; i++) - { - float xLeft = xAngle + i; - int xBase = toIntFloor(xLeft); - if (xLeft - xBase >= 1.0) xBase++; - int xBaseMod4 = xBase&(4-1); - xLeft = xLeft + (xBaseMod4-xBase); - xBase = xBaseMod4; - PreloadedTexture seg[4]={Compass180,Compass270,Compass000,Compass090}; - texture = GLOB_SCENE->Preloaded(seg[xBase]); - float xOffset = xLeft - xBase; - mip = GEngine->TextBank()->UseMipmap(texture, 0, 0); - float xScreen = (coX + 0.5 * coW + 0.25 * coW * (i - xOffset)) * w; - GEngine->Draw2D(mip, compassColor, Rect2DPixel(xScreen, coY * h, 0.25 * coW * w, coH * h), Rect2DPixel(coX * w, coY * h, coW * w, coH * h), coShadow); - //GEngine->TextBank()->ReleaseMipmap(); - } - - Rect2DPixel compassClip(coX*w,0,coW*w,h); - float ySize=coH*h*0.25; - float xSize=ySize*w/h*(3.0/4); - float xPos=(coX+coW*0.5)*w; - PackedColor col=compassDirColor; - GEngine->DrawLine - ( - Line2DPixel(xPos,coY*h,xPos+xSize,coY*h-ySize), - col,col,compassClip - ); - GEngine->DrawLine - ( - Line2DPixel(xPos,coY*h,xPos-xSize,coY*h-ySize), - col,col,compassClip - ); - - WeaponModePtr ptr; - TurretContext context; - if (vehicle->GetPrimaryGunnerTurret(context)) ptr = context._weapons->ValidatedCurrentWeapon(); - if (ptr.IsValid()) - { - // draw turret direction - Vector3Val dir = vehicle->DirectionWorldToModel( - vehicle->GetWeaponDirection(vehicle->RenderVisualState(), context, ptr)); - - if( dir.SquareSizeXZ()>0.1 ) - { - xAngle = atan2(dir.X(), dir.Z()); - float xPos = (coX + 0.5 * coW + xAngle * coW * INV_W) * w; - PackedColor col=compassTurretDirColor; - GEngine->DrawLine - ( - Line2DPixel(xPos,coY*h,xPos+xSize,coY*h-ySize), - col,col,compassClip - ); - GEngine->DrawLine - ( - Line2DPixel(xPos,coY*h,xPos-xSize,coY*h-ySize), - col,col,compassClip - ); - } - } -} +// Poseidon - HUD UI drawing + +#include "../wpch.hpp" +#include "../world.hpp" +#include "../AI/ai.hpp" +#include "../Inventory/inventory.hpp" +#include "../keyInput.hpp" +#include "../joystick.hpp" +#include "InGameUIImpl.hpp" +#include "../engine.hpp" +#include "../camera.hpp" +#include "../visibility.hpp" +#include "../landscape.hpp" +#include "../txtPreload.hpp" +#include "../house.hpp" +#include "../diagModes.hpp" +#include "../Network/network.hpp" +#include + +#include "resincl.hpp" + +#include "../move_actions.hpp" + +#include "../stringtableExt.hpp" + +#include "../drawText.hpp" +#include "chat.hpp" + +#include "uiViewport.hpp" + +#include "../helicopter.hpp" + +#define INV_H_PI (1/H_PI) + +#if _ENABLE_CHEATS +static bool tdCheat; +#endif + +extern void PositionToAA11(Vector3Val pos, char *buffer); + +#define v000 VZero +#define v001 VForward +#define v100 VAside +#define v101 Vector3(1, 0, 1) + +#define MIN_X (-1.0 * H_PI) +#define MAX_X (1.0 * H_PI) +#define MIN_Y (-0.25 * H_PI) +#define MAX_Y (0.25 * H_PI) +#define TOT_W (MAX_X - MIN_X) +#define TOT_H (MAX_Y - MIN_Y) +#define INV_W (1.0 / TOT_W) +#define INV_H (1.0 / TOT_H) + +//max helicopter speed for analogue gauge - 400km/h +#define MAX_HELICOPTER_SPEED 83.333f +#define MAX_HELICOPTER_HEIGHT 6000.0 + +// DayZ status icons: 5 art variants per family, 0 = full ... 4 = empty +static int StatusIconLevel(float ratio) +{ + if (ratio >= 0.8f) return 0; + if (ratio >= 0.6f) return 1; + if (ratio >= 0.4f) return 2; + if (ratio >= 0.2f) return 3; + return 4; +} + +static Texture *DayZStatusTexture(int family, int level) +{ + // Keep a Ref<> so the textures stay alive even when they are not displayed. + static Ref textures[5][5]; + static bool initialized = false; + if (!initialized) + { + static const char *names[5] = {"thirst","hunger","temperature","blood","health"}; + int loaded = 0; + for (int f=0; f<5; f++) + { + for (int l=0; l<5; l++) + { + char path[128]; + // NOTE: no leading backslash. QFBankQueryFunctions::AutoBank matches + // the PBO prefix ("DZ\ui\") from the very first character, so a + // leading '\' makes the lookup miss the bank and the texture fails. + sprintf(path, "DZ\\ui\\data\\igui\\hud\\status\\%s_%d_ca.paa", names[f], l); + textures[f][l] = GlobLoadTextureUI(path); + if (textures[f][l]) loaded++; + } + } + RptF("[HUD-STATUS] %d/25 status textures loaded", loaded); + initialized = true; + } + if (level < 0) level = 0; + if (level > 4) level = 4; + return textures[family][level]; +} + +static void DrawStatusIconAbs(Texture *texture, float x, float y, float size) +{ + if (!texture) return; + Draw2DParsExt pars; + pars.mip = GEngine->TextBank()->UseMipmap(texture, 0, 0); + pars.SetColor(PackedWhite); + pars.Init(); + GEngine->Draw2D(pars, Rect2DAbs(x, y, size, size)); +} + +void InGameUI::DrawUnitInfo(EntityAIFull *vehicle) +{ + AIBrain *agent = GWorld->FocusOn(); + if (!agent) return; + vehicle = agent->IsInCargo() ? agent->GetPerson() : agent->GetVehicle(); + + const VehicleType *type = vehicle->GetType(); + Transport *transport = dyn_cast(vehicle); + + PackedColor color, barBlinkColor; + if (_blinkState) + barBlinkColor = barBlinkOnColor; + else + barBlinkColor = barBlinkOffColor; + + // resize + const AutoArray &infos = Glob.config.UseExtendetInfoType()? type->GetUnitInfoTypes(): type->GetUnitInfoTypesLite(); + int n = infos.Size(); + _lastUnitInfos.Resize(n); + if (n == 0) return; + + for (int i=0; iReload(Pars >> "RscInGameUI" >> desc._name); + desc._changed = Glob.uiTime; + } + + DisplayUnitInfo *disp = desc._display; + + // [HUD-DBG] temporary diagnostics for the DayZ status icons + { + static int dbgFrame = 0; + if (dbgFrame < 6 || (dbgFrame % 600) == 0) + { + RptF("[HUD-DBG] frame=%d showUI=%d n=%d name='%s' disp=%p thirst=%p hunger=%p temp=%p blood=%p health=%p", + dbgFrame, (int)_showUnitInfo, n, (const char *)desc._name, disp, + (void*)disp->statusThirst.GetRef(), (void*)disp->statusHunger.GetRef(), + (void*)disp->statusTemperature.GetRef(), (void*)disp->statusBlood.GetRef(), + (void*)disp->statusHealth.GetRef()); + if (disp->statusThirst) + { + RptF("[HUD-DBG] thirst rect x=%g y=%g w=%g h=%g", + disp->statusThirst->X(), disp->statusThirst->Y(), + disp->statusThirst->W(), disp->statusThirst->H()); + } + } + dbgFrame++; + } + + // reset the dialog size to original + CStatic *bg = disp->background; + if (bg) bg->SetPos(bg->X(), bg->Y(), disp->backgroundWidth, disp->backgroundHeight); + + // set the controls + + char buffer[256]; + Rank rank = agent->GetPerson()->GetRank(); + bool dirty = false; + + /* -- TIME -- */ + if (disp->time) + { + disp->time->SetTime(Glob.clock); + dirty = true; // ??? + } + + /* -- DATE -- */ + if (disp->date) + { + Glob.clock.FormatDate(LocalizeString(IDS_DATE_FORMAT), buffer); + if (disp->date->SetText(buffer)) dirty = true; + } + + /* -- NAME -- */ + if (disp->name) + { + if (disp->name->SetText(agent->GetPerson()->GetPersonName())) dirty = true; + } + + /* -- VEHICLE -- */ + if (disp->vehicle) + { + if (disp->vehicle->SetText(vehicle->GetType()->GetShortName())) dirty = true; + } + + /* -- SPEED -- */ + if (disp->speed) + { + float speed = vehicle->RenderVisualState().ModelSpeed().Z(); +#if _VBS3 //speed in knots + if(vehicle->GetType()->IsKindOf(GWorld->Preloaded(VTypeAir))) + speed *= 0.53996; +#endif + +#if _HELISIM_IMPERIAL_SYSTEM + speed = toInt(vehicle->GetType()->ConvertSpeed(speed)); +#else + speed = toInt(3.6 * speed); +#endif + sprintf(buffer, LocalizeString(IDS_UI_SPEED), speed); + + + if (disp->speed->SetText(buffer)) dirty = true; + if(vehicle->DetectStall()> stallWarning) disp->speed->SetTextColor(PackedColor(222,60,60,255)); + else disp->speed->SetTextColor(ftColor); + } + + /* -- RADARRANGE -- */ + if (disp->radarRange) + { + float radarRange = 4000.0f; + + sprintf( + buffer, + LocalizeString(IDS_UI_RADARRANGE), + radarRange + ); + if (disp->radarRange->SetText(buffer)) dirty = true; + } + + /* -- ALT -- */ + if (disp->alt) + { + Vector3Val pos = vehicle->RenderVisualState().Position(); + float y = pos.Y() + vehicle->GetShape()->Min().Y(); +#if _VBS2 + float y0 = GLOB_LAND->SurfaceYAboveWater(pos.X(), pos.Z()); +#else + float y0 = GLOB_LAND->RoadSurfaceYAboveWater(pos.X(), pos.Z()); +#endif + float h = y - y0; + saturate(h, 0, 99999); +#if _VBS3 //height in feet + h *= 3.28084; +#endif + +#if _HELISIM_IMPERIAL_SYSTEM + h = vehicle->GetType()->ConvertHeight(h); +#endif + sprintf(buffer,LocalizeString(IDS_UI_ALT), h); + if (disp->alt->SetText(buffer)) dirty = true; + } + + /* -- HEADING -- */ + if (disp->heading) + { + int canSee = 0; + if (transport) + { + if (agent == transport->ObserverUnit()) canSee = transport->Type()->_commanderCanSee; + else if (agent == transport->PilotUnit()) canSee = transport->Type()->_driverCanSee; + else if (agent == transport->GunnerUnit()) canSee = transport->Type()->_gunnerCanSee; + } + if (canSee & CanSeeCompass) + { + disp->heading->ShowCtrl(true); + + Camera &cam = *GLOB_SCENE->GetCamera(); + Vector3Val dir = cam.Direction(); + + // avoid singularity when heading up + float angle; + if (fabs(dir.X()) + fabs(dir.Z()) > 1e-3) + angle = atan2(dir.X(), dir.Z()); + else + angle = 0; + + int degAngle = toInt(angle * (180.0f / H_PI)); + if (degAngle < 0) degAngle += 360; + BString<16> buffer; + sprintf(buffer, "%03d", degAngle); + + if (disp->heading->SetText(cc_cast(buffer))) dirty = true; + } + else + disp->heading->ShowCtrl(false); + } + + /* -- ALT WANTED-- */ + if (disp->alt_wanted) + { + buffer[0] = 0; + HelicopterAuto* heli = dyn_cast(vehicle); +#if _VBS3 + bool enabled = Glob.config.IsEnabled(DTSimplifiedHeliModel); +#else + bool enabled = true; +#endif + if (heli && enabled) + { + sprintf + ( + buffer, + LocalizeString(IDS_UI_ALT_WANTED), + heli->GetFlyingHeight() * 3.28084 //format in feet intervals + ); + } + if (disp->alt_wanted->SetText(buffer)) dirty = true; + } + + /* -- SPEED WANTED -- */ + if (disp->speed_wanted) + { + HelicopterAuto* heli = dyn_cast(vehicle); + buffer[0] = 0; +#if _VBS3 + bool enabled = Glob.config.IsEnabled(DTSimplifiedHeliModel); +#else + bool enabled = true; +#endif + if (heli && enabled) + { + sprintf( + buffer, + LocalizeString(IDS_UI_SPEED_WANTED), + heli->GetSpeedWanted() * 3.6 * 0.53996 //format in knots + ); + } + if (disp->speed_wanted->SetText(buffer)) dirty = true; + } + + /* -- POSITION -- */ + if (disp->position) + { + PositionToAA11(vehicle->RenderVisualState().Position(), buffer); + if (disp->position->SetText(buffer)) dirty = true; + } + + /* -- ZOOM -- */ + if (disp->opticZoom) + { + buffer[0]=0; + if( GWorld->GetCameraType() == CamGunner) + { + const Camera *camera = GScene->GetCamera(); + if (camera && vehicle->GetOpticsModel(agent->GetPerson())) + sprintf(buffer, "%.1fx", 0.25f / camera->Left()); + } + if (disp->opticZoom->SetText(buffer)) dirty = true; + } + +#if _VBS3 + if(disp->override_status) + { + TurretContext context; + RString text; + if(transport && transport->FindTurret(agent->GetPerson(), context)) + { + if(context._turret) + { + if(context._turret->IsOverridden()) + text = LocalizeString(IDS_TURRET_OVERRIDDEN); + else + if(context._turret->IsOverriding()) + text = LocalizeString(IDS_TURRET_OVERRIDING); + else + if(context._turret->_showOverrideOptics) + text = LocalizeString(IDS_TURRET_GUNNER_VIEW); + } + } + if(disp->override_status->SetText(text)) dirty = true; + } + + //AVRS show nick and bank of helicopters + if(transport) + { + if(disp->nick && disp->nick_val) + { + Vector3 front = transport->Direction(); + float nick = -asin(front.Y()) * (180.0f / H_PI); + sprintf(buffer, "%.1f", nick); + if(disp->nick_val->SetText(buffer)) dirty = true; + PackedColor color = abs(nick) < 10.0f ? ftColor : enemyColor; + disp->nick_val->SetColor(color); + disp->nick->SetColor(color); + } + + if(disp->bank && disp->bank_val) + { + Vector3 aside = transport->DirectionAside(); + float bank = asin(aside.Y()) * (180.0f / H_PI); + sprintf(buffer, "%.1f", bank); + if(disp->bank_val->SetText(buffer)) dirty = true; + PackedColor color = abs(bank) < 10.0f ? ftColor : enemyColor; + disp->bank_val->SetColor(color); + disp->bank->SetColor(color); + } + } + + +#if _VBS3_TI + if(agent->GetPerson()->GetVisionMode() == VMTi) + { + if(disp->ti_background) disp->ti_background->ShowCtrl(); + if(disp->ti_brightness_txt) disp->ti_brightness_txt->ShowCtrl(); + if(disp->ti_contrast_txt) disp->ti_contrast_txt->ShowCtrl(); + if(disp->ti_contrast) disp->ti_contrast->ShowCtrl(); + + if(disp->ti_mode) + { + disp->ti_mode->ShowCtrl(); + int mode = agent->GetPerson()->GetTiModus(); + //TODO: query engine + char* buf[7]={"WHITE - HOT", "BLACK - HOT", "GREEN - HOT", "BLACK - HOT", "ORANGE - HOT", "BLACK - HOT", "COLOR"}; + saturate(mode, 0, 6); + if(disp->ti_mode->SetText(buf[mode])) dirty = true; + } + + if(disp->ti_brightness) + { + disp->ti_brightness->ShowCtrl(); + float bright= GEngine->GetTIBrightness(); + bright /= (TempMax - TempMin); + saturate(bright, 0, 1); + disp->ti_brightness->SetPos(bright); + } + + if(disp->ti_contrast) + { + disp->ti_contrast->ShowCtrl(); + float contr= GEngine->GetTIContrast(); + contr /= ContrastMax; + saturate(contr, 0, 1); + disp->ti_contrast->SetPos(contr); + } + + if(disp->ti_autocontrast) + disp->ti_autocontrast->ShowCtrl(GEngine->GetTIAutoBC()); + + } + else + { + if(disp->ti_background) disp->ti_background->ShowCtrl(false); + if(disp->ti_mode) disp->ti_mode->ShowCtrl(false); + if(disp->ti_brightness_txt) disp->ti_brightness_txt->ShowCtrl(false); + if(disp->ti_brightness) disp->ti_brightness->ShowCtrl(false); + if(disp->ti_contrast_txt) disp->ti_contrast_txt->ShowCtrl(false); + if(disp->ti_contrast) disp->ti_contrast->ShowCtrl(false); + if(disp->ti_autocontrast) disp->ti_autocontrast->ShowCtrl(false); + } +#endif //_VBS3_TI +#endif //_VBS3 + + /* -- EXPERIENCE -- */ + if (disp->valueExp) + { + float expCur = agent->GetPerson()->GetExperience() - AI::ExpForRank(rank); + float expMax = rank >= RankColonel ? + AI::ExpForRank(RankColonel) : + AI::ExpForRank((Rank)(rank + 1)) - AI::ExpForRank(rank); + Assert(expMax > 0); + float expCoef = 0.9 * (expCur / expMax); + saturate(expCoef, 0, 1); + disp->valueExp->SetPos(expCoef); + } + + /* -- COMBAT MODE -- */ + if (disp->combatMode) + { + if (disp->combatMode->SetText(LocalizeString(IDS_IGNORE + agent->GetSemaphore()))) dirty = true; + } + + /* -- HEALTH -- */ + if (disp->valueHealth) + { + float health = 0; + Vehicle *person = agent->GetPerson(); + if (person) + { + health = 1 - person->GetTotalDamage(); + saturate(health, 0, 1); + } + if (health > 0.5) + color = barGreenColor; + else if (health > 0.3) + color = barYellowColor; + else if (health > 0.15) + color = barRedColor; + else + color = barBlinkColor; + disp->valueHealth->SetPos(health); + disp->valueHealth->SetBarColor(color); + } + + /* -- DAYZ STATUS ICONS -- */ + if (disp->statusHealth || disp->statusBlood || disp->statusHunger || disp->statusThirst || disp->statusTemperature) + { + EntityAI *person = agent->GetPerson(); + if (person) + { + GameValue gv; + + float healthVal = 5000; + gv = person->GetVariableValue("health"); + if (!gv.GetNil()) healthVal = gv; + else healthVal = (1 - person->GetTotalDamage()) * 5000; + + float bloodVal = healthVal; + gv = person->GetVariableValue("blood"); + if (!gv.GetNil()) bloodVal = gv; + + float energyVal = 1000; + gv = person->GetVariableValue("energy"); + if (!gv.GetNil()) energyVal = gv; + + float waterVal = 1800; + gv = person->GetVariableValue("water"); + if (!gv.GetNil()) waterVal = gv; + + float vHealth = healthVal / 5000.0f; + float vBlood = bloodVal / 5000.0f; + float vEnergy = energyVal / 1000.0f; + float vWater = waterVal / 1800.0f; + saturate(vHealth, 0, 1); + saturate(vBlood, 0, 1); + saturate(vEnergy, 0, 1); + saturate(vWater, 0, 1); + + // No body temperature variable exists in 0.45: derive the cold level + // from the environment plus player wetness (DZ_WET_COOLING = 6). + float airTemperature = 15.0f; + if (GLandscape) + { + float black, white; + GLandscape->GetTemperature(airTemperature, black, white); + } + float wet = 0; + gv = person->GetVariableValue("wet"); + if (!gv.GetNil()) wet = gv; + saturate(wet, 0, 1); + float effectiveTemperature = airTemperature - wet * 8.0f; + int temperatureLevel; + if (effectiveTemperature >= 10.0f) temperatureLevel = 0; + else if (effectiveTemperature >= 0.0f) temperatureLevel = 1; + else if (effectiveTemperature >= -10.0f) temperatureLevel = 2; + else if (effectiveTemperature >= -20.0f) temperatureLevel = 3; + else temperatureLevel = 4; + + // The engine confines HUD controls to its 4:3 "2D area", which leaves + // the icons well inside the real screen edges. Hide the config + // controls and draw the row directly in absolute screen pixels so it + // sits in the true bottom-right corner at the intended size. + if (GWorld->UserDialog() == NULL) + { + if (disp->statusThirst) disp->statusThirst->ShowCtrl(false); + if (disp->statusHunger) disp->statusHunger->ShowCtrl(false); + if (disp->statusTemperature) disp->statusTemperature->ShowCtrl(false); + if (disp->statusBlood) disp->statusBlood->ShowCtrl(false); + if (disp->statusHealth) disp->statusHealth->ShowCtrl(false); + + Texture *statusTex[5] = + { + DayZStatusTexture(0, StatusIconLevel(vWater)), + DayZStatusTexture(1, StatusIconLevel(vEnergy)), + DayZStatusTexture(2, temperatureLevel), + DayZStatusTexture(3, StatusIconLevel(vBlood)), + DayZStatusTexture(4, StatusIconLevel(vHealth)) + }; + + float screenW = (float)GEngine->WidthBB(); + float screenH = (float)GEngine->HeightBB(); + float iconSize = screenH * 0.052f; + float iconGap = iconSize * 0.10f; + float rowW = 5 * iconSize + 4 * iconGap; + float rowX = screenW - screenW * 0.004f - rowW; + float rowY = screenH - screenH * 0.012f - iconSize; + for (int k = 0; k < 5; k++) + DrawStatusIconAbs(statusTex[k], rowX + k * (iconSize + iconGap), rowY, iconSize); + } + + if (disp->statusThirst || disp->statusHunger || disp->statusTemperature || disp->statusBlood || disp->statusHealth) + { + static int dbgStatus = 0; + if (dbgStatus < 6 || (dbgStatus % 600) == 0) + { + RptF("[HUD-DBG] values h=%.1f b=%.1f e=%.1f w=%.1f air=%.1f wet=%.1f lv=%d,%d,%d,%d,%d", + healthVal, bloodVal, energyVal, waterVal, airTemperature, wet, + StatusIconLevel(vHealth), StatusIconLevel(vBlood), StatusIconLevel(vEnergy), + StatusIconLevel(vWater), temperatureLevel); + } + dbgStatus++; + } + + // (Icons are drawn directly above; the config controls stay hidden.) + } + } + + /* -- ARMOR -- */ + if (disp->valueArmor && vehicle->GetType()) + { + RString state; + disp->valueArmor->Clear(); + AutoArray textureUV = vehicle->GetHitTextureUVForDisplay(); + for( int i=0; iGetHitForDisplay(i))); + + int index = disp->valueArmor->AddString(RString()); + disp->valueArmor->SetValue(index,textureUV[i]); + disp->valueArmor->SetFtColor(index,color); + } + } + + /* -- FUEL -- */ + if (disp->valueFuel) + { + float fuel = 0; + float fuelCapacity = vehicle->GetType()->GetFuelCapacity(); + if (fuelCapacity > 0) + { + fuel = vehicle->GetRenderVisualStateFuel() / fuelCapacity; + saturate(fuel, 0, 1); + } + if (fuel > 0.5) + color = barGreenColor; + else if (fuel > 0.3) + color = barYellowColor; + else if (fuel > 0.15) + color = barRedColor; + else + color = barBlinkColor; + disp->valueFuel->SetPos(fuel); + disp->valueFuel->SetBarColor(color); + } + + /* -- CARGO MAN -- */ + if (disp->cargoMan) + { + if (transport && transport->GetMaxManCargo() > 0) + { + disp->cargoMan->ShowCtrl(true); + sprintf(buffer, LocalizeString(IDS_UI_CARGO_INF), transport->GetManCargoSize()); + if (disp->cargoMan->SetText(buffer)) dirty = true; + } + else + { + disp->cargoMan->ShowCtrl(false); + } + } + + /* -- CARGO FUEL -- */ + if (disp->cargoFuel) + { + if (transport && transport->GetMaxFuelCargo() > 0) + { + disp->cargoFuel->ShowCtrl(true); + sprintf(buffer, LocalizeString(IDS_UI_CARGO_FUEL), transport->GetFuelCargo()); + if (disp->cargoFuel->SetText(buffer)) dirty = true; + } + else + { + disp->cargoFuel->ShowCtrl(false); + } + } + + /* -- CARGO REPAIR -- */ + if (disp->cargoRepair) + { + if (transport && transport->GetMaxRepairCargo() > 0) + { + disp->cargoRepair->ShowCtrl(true); + sprintf(buffer, LocalizeString(IDS_UI_CARGO_REPAIR), transport->GetRepairCargo()); + if (disp->cargoRepair->SetText(buffer)) dirty = true; + } + else + { + disp->cargoRepair->ShowCtrl(false); + } + } + + /* -- CARGO AMMO -- */ + if (disp->cargoAmmo) + { + if (transport && transport->GetMaxAmmoCargo() > 0) + { + disp->cargoAmmo->ShowCtrl(true); + sprintf(buffer, LocalizeString(IDS_UI_CARGO_AMMO), transport->GetAmmoCargo()); + if (disp->cargoAmmo->SetText(buffer)) dirty = true; + } + else + { + disp->cargoAmmo->ShowCtrl(false); + } + } + + float crewWidth = disp->backgroundWidth; + VerySmallArray crew; + if (disp->commander) crew.Add(disp->commander); + if (disp->gunner) crew.Add(disp->gunner); + if (disp->driver) crew.Add(disp->driver); + if (crew.Size() == 3) + { + int pos = 0; + float h = 0; + float w = 0; + if (transport && GWorld->GetMode() == GModeNetware) + { + AIBrain *unit = transport->ObserverUnit(); + if (unit && unit->IsAnyPlayer()) + { + crew[pos]->ShowCtrl(true); + crew[pos]->SetText(unit->GetPerson()->GetPersonName()); + saturateMax(w, crew[pos]->GetTextSize()); + if (disp->_updateHeightByCrew) h += crew[pos]->H(); + pos++; + } + unit = transport->GunnerUnit(); + if (unit && unit->IsAnyPlayer()) + { + crew[pos]->ShowCtrl(true); + crew[pos]->SetText(unit->GetPerson()->GetPersonName()); + saturateMax(w, crew[pos]->GetTextSize()); + if (disp->_updateHeightByCrew) h += crew[pos]->H(); + pos++; + } + unit = transport->PilotUnit(); + if (unit && unit->IsAnyPlayer()) + { + crew[pos]->ShowCtrl(true); + crew[pos]->SetText(unit->GetPerson()->GetPersonName()); + saturateMax(w, crew[pos]->GetTextSize()); + if (disp->_updateHeightByCrew) h += crew[pos]->H(); + pos++; + } + } + for (;posShowCtrl(false); + CStatic *bg = disp->background; + if (bg) + { + float offset = crew[0]->X() - bg->X(); + if (disp->_updateWidthByCrew) saturateMax(crewWidth, w + 2 * offset); + for (int i=0; iSetPos(ctrl->X(), ctrl->Y(), w, ctrl->H()); + } + + bg->SetPos(bg->X(), bg->Y(), crewWidth, disp->backgroundHeight + h); + } + } + + // primary show own weapons, otherwise primary weapon state + WeaponModePtr ptr; + TurretContext context; + WeaponModePtr ptrGunner; + TurretContext contextGunner; + WeaponModePtr counterMeasures; + TurretContext contextCM; + if (transport && transport->IsManualFire() && agent == transport->CommanderUnit() && vehicle->GetPrimaryGunnerTurret(context)) + { + // when manual fire is on, commander is controlling gunner's weapons (even when has own weapons) + ptr = context._weapons->ValidatedCurrentWeapon(); + } +#if _VBS3 //Commander override + else if (vehicle->FindOpticsTurret(agent->GetPerson(), context) && vehicle->CanFireUsing(context)) +#else + else if (vehicle->FindTurret(agent->GetPerson(), context) && vehicle->CanFireUsing(context)) +#endif + { + ptr = context._weapons->ValidatedCurrentWeapon(); +#if _VBS3_LASE_LEAD + DrawLaserRange(context); +#endif + } + if (vehicle->GetPrimaryGunnerTurret(contextGunner)) + { + ptrGunner = contextGunner._weapons->ValidatedCurrentWeapon(); + } + + /* -- WEAPONS -- */ + if (ptr.IsValid()) + { + // non-default weapon is always shown + //if (weapon != 0) dirty = true; // not any more + + int ammoCur = 0; + int maxAmmoCur = 0; + bool noAmmo = true; + // int ammoSum = 0; + // int maxAmmoSum = 0; + int magazines = 0; + float reload = 0; + float reloadTime = 0; + float reloadTimeMax = 0; + RString displayName; + + const MuzzleType *muzzle = ptr.GetMuzzleType(); + const WeaponModeType *mode = ptr.GetWeaponModeType(); + RString weaponMode = mode->_displayName; + displayName = muzzle->_displayName; + + if(_weaponInfoAlpha > 10) dirty = true; + _weaponInfoAlpha = 0; + + const Magazine *currentMagazine = ptr.GetMagazine(); + const Magazine *magazine = currentMagazine; + if (!magazine) + { + // find magazine of first compatible type + for (int i=0; i_magazines.Size(); i++) + { + const MagazineType *type = muzzle->_magazines[i]; + context._weapons->ForEachMagazine([&magazines, &magazine, type](Magazine *mag) -> bool + { + if (mag->Type() != type) return false; // continue + if (mag->GetAmmo() == 0) return false; // continue + magazines++; + if (!magazine) + { + magazine = mag; + } + return false; // continue + }); + //if (magazine) break; // want all magazines + } + + if (magazine) + { + maxAmmoCur = magazine->Type()->_maxAmmo; + } + else if (muzzle->_magazines.Size() > 0) + { + maxAmmoCur = muzzle->_magazines[0]->_maxAmmo; + } + } + else // FIX: wrong calculation of magazines + { + ammoCur = magazine->GetAmmo(); + maxAmmoCur = magazine->Type()->_maxAmmo; + if (magazine->_reloadMagazine > 0) + { + reload = 1; + reloadTime = magazine->_reloadMagazine + magazine->_reload * mode->_reloadTime; + reloadTimeMax = magazine->_reloadMagazineTotal + mode->_reloadTime; + } + else + { + reload = magazine->_reload; + reloadTime = magazine->_reload * mode->_reloadTime; + reloadTimeMax = mode->_reloadTime; + } + + // find magazine of first compatible type + for (int j=0; j_magazines.Size(); j++) + { + const MagazineType *allowedMagazine = muzzle->_magazines[j]; + // reserve magazines + context._weapons->ForEachMagazine([&magazines, magazine, allowedMagazine](Magazine *reserve) -> bool + { + if (reserve == magazine) return false; // continue; + if (reserve->Type() == allowedMagazine) + { + if (reserve->GetAmmo() > 0) magazines++; + } + return false; // continue + }); + } + noAmmo = ammoCur == 0; + } + + if (magazine && magazine->Type()->_maxAmmo == 1) + { + ammoCur = magazines; + if (currentMagazine && currentMagazine->GetAmmo() > 0) ammoCur++; + magazines = 0; + } + + if (maxAmmoCur > 0) + { + color = _weaponInfoColor; + + if (/*ammoCur == 0*/noAmmo || vehicle->IsActionInProgress(MFReload)) + _weaponInfoColor = _weaponUnloadColor; + else if (reload <= 0) + _weaponInfoColor = _weaponReadyColor; + else if (reload <= 0.2) + _weaponInfoColor = _weaponPrepareColor; + else + _weaponInfoColor = _weaponUnloadColor; + + if (disp->valueReload) + { + if(reload > 0.001f && !noAmmo && reloadTimeMax > 0.5f) + { + disp->valueReload->ShowCtrl(true); + disp->valueReload->SetPos(reloadTime); + float range = disp->valueReload->GetRange(); + disp->valueReload->SetRange(0,floatMax(range,reloadTimeMax)); + } + else + { + disp->valueReload->SetRange(0,0); + disp->valueReload->ShowCtrl(false); + } + } + + if (disp->weapon) + { + disp->weapon->ShowCtrl(true); + disp->weapon->SetTextColor(color); + if (disp->weapon->SetText(displayName)) dirty = true; + } + if (disp->ammo) + { + disp->ammo->ShowCtrl(true); + disp->ammo->SetTextColor(color); + // sprintf(buffer, "%d", ammoSum); + if (magazines > 0) + sprintf(buffer, "%d | %d", ammoCur, magazines); + else + sprintf(buffer, "%d", ammoCur); + if(Glob.config.IsEnabled(DTHUDPerm)) + { + if (disp->ammo->SetText(buffer)) dirty = true; + // non-default weapon is always shown + if (!context._weapons->IsDefaultWeapon(ptr)) dirty = true; + } + else disp->ammo->SetText(buffer); + + if((ammoCur + magazines <=0) && displayName.GetLength()<=0) + { + disp->weapon->ShowCtrl(false); + } + } + if (disp->ammoMode) + { + disp->ammoMode->ShowCtrl(true); + disp->ammoMode->SetTextColor(color); + + RString modeAndMag; + if (weaponMode!=displayName && !weaponMode.IsEmpty()) + { + if (magazine && !magazine->Type()->_shortName.IsEmpty()) + modeAndMag = weaponMode+RString(" | ")+magazine->Type()->_shortName; + else + modeAndMag = weaponMode; + } + else + { + if (magazine && !magazine->Type()->_shortName.IsEmpty()) + { + modeAndMag = magazine->Type()->_shortName; + } + } + if (disp->ammoMode->SetText(modeAndMag)) dirty = true; + + if((ammoCur + magazines <=0) && modeAndMag.GetLength()<=0) + { + disp->ammoMode->ShowCtrl(false); + } + } + +#if _VBS3 + if (disp->magazine && magazine) + { + disp->magazine->ShowCtrl(true); + disp->magazine->SetTextColor(color); + if (disp->magazine->SetText(magazine->Type()->_displayName)) dirty = true; + } +#endif + } + else + { + // no ammo or no muzzle + if (disp->weapon) + { + disp->weapon->ShowCtrl(true); + disp->weapon->SetTextColor(_weaponReadyColor); + if (disp->weapon->SetText(displayName)) dirty = true; + } +#if _VBS3 + if (disp->magazine && magazine) + { + if (disp->magazine->SetText(RString())) dirty = true; + } +#endif + if (disp->ammo) + { + //if (disp->ammo->SetText(RString())) dirty = true; + disp->ammo->SetText(RString()); + } + if (disp->ammoMode) + { + RString modeAndMag; + if (weaponMode!=displayName && !weaponMode.IsEmpty()) + { + if (magazine > 0 && !magazine->Type()->_shortName.IsEmpty()) + modeAndMag = weaponMode+RString(" | ")+magazine->Type()->_shortName; + else + modeAndMag = weaponMode; + } + else + { + if (magazine > 0 && !magazine->Type()->_shortName.IsEmpty()) + { + modeAndMag = magazine->Type()->_shortName; + } + } + if (disp->ammoMode->SetText(modeAndMag)) dirty = true; + + if((ammoCur + magazines <=0) && modeAndMag.GetLength()<=0) + { + disp->ammoMode->ShowCtrl(false); + } + } + } + + // update the width - ensure the weapon name will fit always + CStatic *bg = disp->background; + CStatic *weapon = disp->weapon; + CStatic *ammo = disp->ammo; + if (bg && weapon && ammo && disp->_updateWidthByWeapon) + { + float offset = weapon->X() - bg->X(); + float weaponWidth = weapon->GetTextSize(); + float ammoWidth = ammo->GetTextSize(); + float totalWidth = offset + weaponWidth + offset + ammoWidth + offset; + if (totalWidth < crewWidth) + { + float diff = crewWidth - totalWidth; + weaponWidth += 0.5 * diff; + ammoWidth += 0.5 * diff; + totalWidth += diff; + } + weapon->SetPos(weapon->X(), weapon->Y(), weaponWidth, weapon->H()); + ammo->SetPos(weapon->X() + weaponWidth + offset, ammo->Y(), ammoWidth, ammo->H()); + bg->SetPos(bg->X(), bg->Y(), totalWidth, bg->H()); + } + } + else + { + if (disp->weapon) disp->weapon->ShowCtrl(false); + if (disp->ammo) disp->ammo->ShowCtrl(false); + if (disp->ammoMode) disp->ammoMode->ShowCtrl(false); + _weaponInfoAlpha = 0; + } + + /* -- COUNTER MEASURES -- */ + if (transport && transport->CommanderUnit()->GetPerson() && agent == transport->CommanderUnit() && vehicle->FindTurret(agent->GetPerson() ,contextCM)) + { + counterMeasures = contextCM._weapons->ValidatedCurrentCounterMeasures(); + + if (counterMeasures.IsValid()) + { + int ammoCur = 0; + int maxAmmoCur = 0; + bool noAmmo = true; + // int ammoSum = 0; + // int maxAmmoSum = 0; + int magazines = 0; + float reload = 0; + + const Magazine *magazine = counterMeasures.GetMagazine(); + const MuzzleType *muzzle = counterMeasures.GetMuzzleType(); + const WeaponModeType *mode = counterMeasures.GetWeaponModeType(); + RString cmMode = mode->_displayName; + + if (!magazine) + { + // find magazine of first compatible type + for (int i=0; i_magazines.Size(); i++) + { + const MagazineType *type = muzzle->_magazines[i]; + contextCM._weapons->ForEachMagazine([&magazines, &magazine, type](Magazine *mag) -> bool + { + if (mag->Type() != type) return false; // continue + if (mag->GetAmmo() == 0) return false; // continue + magazines++; + if (!magazine) + { + magazine = mag; + } + return false; // continue + }); + //if (magazine) break; // want all magazines + } + + if (magazine) + { + maxAmmoCur = magazine->Type()->_maxAmmo; + } + else if (muzzle->_magazines.Size() > 0) + { + maxAmmoCur = muzzle->_magazines[0]->_maxAmmo; + } + } + else // FIX: wrong calculation of magazines + { + ammoCur = magazine->GetAmmo(); + maxAmmoCur = magazine->Type()->_maxAmmo; + if (magazine->_reloadMagazine > 0) reload = 1; + else reload = magazine->_reload; + + // find magazine of first compatible type + for (int j=0; j_magazines.Size(); j++) + { + const MagazineType *allowedMagazine = muzzle->_magazines[j]; + // reserve magazines + contextCM._weapons->ForEachMagazine([&magazines, magazine, allowedMagazine](Magazine *reserve) -> bool + { + if (reserve == magazine) return false; // continue + if (reserve->Type() == allowedMagazine) + { + if (reserve->GetAmmo() > 0) magazines++; + } + return false; // continue + }); + } + noAmmo = ammoCur == 0; + } + + if (maxAmmoCur > 0) + { + if (/*ammoCur == 0*/noAmmo || vehicle->IsActionInProgress(MFReload)) + color = _weaponUnloadColor; + else if (reload <= 0) + color = _weaponReadyColor; + else if (reload <= 0.2) + color = _weaponPrepareColor; + else + color = _weaponUnloadColor; + } + + if(disp->counterMeasuresAmmo) + { + disp->counterMeasuresAmmo->ShowCtrl(true); + disp->counterMeasuresAmmo->SetTextColor(color); + // sprintf(buffer, "%d", ammoSum); + if (magazines > 0) + sprintf(buffer, "%d | %d", ammoCur, magazines); + else + sprintf(buffer, "%d", ammoCur); + if(Glob.config.IsEnabled(DTHUDPerm)) + { + if (disp->counterMeasuresAmmo->SetText(buffer)) dirty = true; + // non-default weapon is always shown + if (!contextCM._weapons->IsDefaultWeapon(counterMeasures)) dirty = true; + } + else disp->counterMeasuresAmmo->SetText(buffer); + } + if(disp->counterMeasuresMode) + { + disp->counterMeasuresMode->ShowCtrl(true); + disp->counterMeasuresMode->SetTextColor(color); + if (disp->counterMeasuresMode->SetText(cmMode)) dirty = true; + } + } + else + { + if (disp->counterMeasuresAmmo) disp->counterMeasuresAmmo->ShowCtrl(false); + if (disp->counterMeasuresMode) disp->counterMeasuresMode->ShowCtrl(false); + } + } + else + { + if (disp->counterMeasuresAmmo) disp->counterMeasuresAmmo->ShowCtrl(false); + if (disp->counterMeasuresMode) disp->counterMeasuresMode->ShowCtrl(false); + } + + /* -- GUNNER WEAPON -- */ + if (disp->gunnerWeapon) + { + if ( ( contextGunner._gunner != agent->GetPerson() && !transport->IsManualFire()) + && ptrGunner.IsValid()) + { + const Magazine *magazine = ptrGunner.GetMagazine(); + if (magazine) + { + const MuzzleType *muzzle = ptrGunner.GetMuzzleType(); + RString displayName = muzzle->_displayName; + + float reload = 0; + if (magazine->_reloadMagazine > 0) reload = 1; + else reload = magazine->_reload; + + if(magazine->GetAmmo()<=0) + color = _weaponUnloadColor; + else if (reload <= 0) + color = _weaponReadyColor; + else if (reload <= 0.2) + color = _weaponPrepareColor; + else + color = _weaponUnloadColor; + + disp->gunnerWeapon->ShowCtrl(true); + disp->gunnerWeapon->SetTextColor(color); + if (disp->gunnerWeapon->SetText(displayName)) dirty = true; + } + } + else + { + if (disp->gunnerWeapon) disp->gunnerWeapon->ShowCtrl(false); + } + } + +#if _HELISIM_ROTORLIB + bool heliHudDraw = DrawHelicopterUnitInfo(vehicle, agent, disp, dirty); + if(heliHudDraw) dirty = true; +#endif + + if (dirty) + desc._changed = Glob.uiTime; + + float age = 0; + #if !_PROFILE + if (vehicle->GetType()->_hideUnitInfo) + age = Glob.uiTime - desc._changed; + #endif + + bool statusVisible = GWorld->UserDialog() == NULL && + (disp->statusThirst || disp->statusHunger || disp->statusTemperature || + disp->statusBlood || disp->statusHealth); + + if (statusVisible || (age < piDimEndTime && ( + (disp->weapon && disp->weapon->IsVisible()) + || (disp->gunnerWeapon && disp->gunnerWeapon->IsVisible()) + || (disp->speed && disp->speed->IsVisible()) +#if _HELISIM_ROTORLIB + || heliHudDraw +#endif + ))) + { + float alpha = 1.0; + if (age < piDimEndTime && age > piDimStartTime) + alpha = (piDimEndTime - age) / (piDimEndTime - piDimStartTime); + + CStatic *bg = disp->background; + if(bg) bg->ShowCtrl((disp->weapon && disp->weapon->IsVisible()) || (disp->gunnerWeapon && disp->gunnerWeapon->IsVisible()) || (disp->speed && disp->speed->IsVisible())); + if(bg && bg->IsVisible()) _hintTop = bg->Y() + bg->H() + 0.02; + + if (disp->IsReady()) + disp->DrawHUD(vehicle, alpha); + + _weaponInfoAlpha = alpha; + } + } +} + + +#if _HELISIM_ROTORLIB + +static Vector3 GetHudImageOffset( CStatic* child, CControlsGroup* parent,float angle) +{ + Matrix4 mrot(MZero); + + Vector3 position = Vector3 ( + sin(angle) * child->X(), + 0 , + -cos(angle) * child->Y()); + + //rotated position + position = position - Vector3(child->X(), 0, child->Y()) + - Vector3(child->W()* 0.5f, 0, child->H()* 0.5f) + Vector3(parent->W()* 0.5f, 0, parent->H()* 0.5f); + return position; +} + +static Matrix4 GetHudImageRotation(float angle) +{ + Matrix4 mtrans1Att = Matrix4(MTranslation, Vector3(-0.5, 0, -0.5)); + Matrix4 mtrans2Att = Matrix4(MTranslation, Vector3( 0.5, 0, 0.5)); + Matrix4 mrot(MZero); + mrot.SetUpAndDirection(VUp, Vector3( sin(angle), 0,cos(angle))); + mrot = mtrans2Att * mrot * mtrans1Att; + return mrot; +} + +bool InGameUI::DrawHelicopterUnitInfo(EntityAIFull *vehicle, AIBrain *agent, DisplayUnitInfo *disp, bool &dirty) +{ + PROFILE_SCOPE_EX(HUDIf, *); + + bool heliHudDraw = false; + HelicopterRTD *helicopter = dyn_cast(vehicle); + + bool draw = (helicopter != NULL && (vehicle->PilotUnit() == agent || vehicle->CopilotUnit() == agent)); + //draw only when unit is pilot or copilot + if(disp->airSpeedIndicator) disp->airSpeedIndicator->ShowCtrl(draw); + if(disp->altimeter) disp->altimeter->ShowCtrl(draw); + if(disp->attitudeIndicator) disp->attitudeIndicator->ShowCtrl(draw); + if(disp->attitudeIndicatorLite) disp->attitudeIndicatorLite->ShowCtrl(draw); + if(disp->gMeter) disp->gMeter->ShowCtrl(draw); + if(disp->radarAltimeter) disp->radarAltimeter->ShowCtrl(draw); + if(disp->torque) disp->torque->ShowCtrl(draw); + if(disp->winIndicator) disp->winIndicator->ShowCtrl(draw); + if(disp->stabilityIndicator) disp->stabilityIndicator->ShowCtrl(draw); + if(disp->collective) disp->collective->ShowCtrl(draw); + if(disp->trimIndicator) disp->trimIndicator->ShowCtrl(draw); + if(disp->autohover) disp->autohover->ShowCtrl(draw); + if(disp->heliHUDmisc) disp->heliHUDmisc->ShowCtrl(draw); + + if(disp->speedAnalogue) disp->speedAnalogue->ShowCtrl(draw); + if(disp->altitudeAnalogue) disp->altitudeAnalogue->ShowCtrl(draw); + if(disp->compassAnalogue) disp->compassAnalogue->ShowCtrl(draw); + if(disp->stabilityAnalogue) disp->stabilityAnalogue->ShowCtrl(draw); + if(disp->horizonAnalogue) disp->horizonAnalogue->ShowCtrl(draw); + if(disp->statusDamage) disp->statusDamage->ShowCtrl(draw); + + + if(!draw) return heliHudDraw; + + _iguiHMD = false; + + char buffer[256]; + Matrix4 mrot(MZero); + + const int w = GEngine->Width2D(); + const int h = GEngine->Height2D(); + + Draw2DParsExt pars; + pars.spec = NoZBuf|IsAlpha|IsAlphaFog|ClampU|ClampV; + pars.spec|= (_helicopterHUDShadow == 2)? UISHADOW : 0; + pars.SetColor(_helicopterHUDColor); + + Matrix4 mtrans1 = Matrix4(MTranslation, Vector3(-0.5, 0, -0.5)); + Matrix4 mtrans2 = Matrix4(MTranslation, Vector3(0.5, 0, 0.5)); + + /* -- AIRSPPED -- */ + if (disp->airSpeedIndicator) + { + heliHudDraw = true; + disp->airSpeedIndicator->ShowCtrl(draw); + _iguiHMD = true; + + float airSpeed = helicopter->GetAirspeedIndicatorRTD(helicopter->RenderVisualState()); +#if _HELISIM_IMPERIAL_SYSTEM + airSpeed = vehicle->GetType()->ConvertSpeed(airSpeed); +#else + airSpeed = (airSpeed*3.6f); +#endif + + if (disp->airSpeedIndicatorAxis) + { + Rect2DPixel rect( + (disp->airSpeedIndicator->X() + disp->airSpeedIndicatorAxis->X()) * w, + (disp->airSpeedIndicator->Y() + disp->airSpeedIndicatorAxis->Y()) * h, + disp->airSpeedIndicatorAxis->W() * w, + disp->airSpeedIndicatorAxis->H() * h); + + //texture has 11 segments - 10 to show, 1 for sliding reserve; one segments is 20 m/s + float elementSize = 1/ 11.0f; + float vOffset = fmod(airSpeed,20) / 20.0f; + vOffset = (vOffset >= 0) ? (vOffset * elementSize): ((vOffset + 1) * elementSize); + + + float vTop = elementSize - vOffset; + float vBottom = 11 * elementSize - vOffset; + + Vector3 uv =v000; + pars.uTR = uv[2]; + pars.vTR = vTop; + uv = v001; + pars.uTL = uv[2]; + pars.vTL = vTop; + uv = v100; + pars.uBR = uv[2]; + pars.vBR = vBottom; + uv = v101; + pars.uBL = uv[2]; + pars.vBL = vBottom; + + pars.mip = GEngine->TextBank()->UseMipmap(_helicopterHUDAxis, 0, 0); + GEngine->Draw2D(pars, rect, rect); + } + char buffer[256]; + sprintf(buffer, "%03d", (int)(airSpeed)); + + if(disp->airSpeedIndicatorValue) disp->airSpeedIndicatorValue->SetText(buffer); + dirty = true; + } + + /* -- ALTIMETER -- */ + if (disp->altimeter) + { + heliHudDraw = true; + _iguiHMD = true; + + float height = helicopter->GetAltBaroRTD(helicopter->RenderVisualState()); // km/h + +#if _HELISIM_IMPERIAL_SYSTEM + height = vehicle->GetType()->ConvertHeight(height); +#endif + + char buffer[256]; + + if (disp->altimeterAxis) + { + Rect2DPixel rect( + disp->altimeter->X() * w, + disp->altimeter->Y() * h, + disp->altimeter->W() * w, + disp->altimeter->H() * h); + + Rect2DPixel rectAxis( + (disp->altimeter->X() + disp->altimeterAxis->X()) * w, + (disp->altimeter->Y() + disp->altimeterAxis->Y()) * h, + disp->altimeterAxis->W() * w, + disp->altimeterAxis->H() * h); + + //texture has 11 segments - 10 to show, 1 for sliding reserve; one segments is 20 m/s + float elementSize = 1/ 11.0f; + float vOffset = fmod(height,20) / 20.0f; + vOffset = (vOffset >= 0) ? (vOffset * elementSize): ((vOffset + 1) * elementSize); + + float vTop = elementSize - vOffset; + float vBottom = 11 * elementSize - vOffset; + + Vector3 uv =v001; + pars.uTR = uv[2]; + pars.vTR = vTop; + uv = v000; + pars.uTL = uv[2]; + pars.vTL = vTop; + uv = v101; + pars.uBR = uv[2]; + pars.vBR = vBottom; + uv = v100; + pars.uBL = uv[2]; + pars.vBL = vBottom; + + pars.mip = GEngine->TextBank()->UseMipmap(_helicopterHUDAxis, 0, 0); + GEngine->Draw2D(pars, rectAxis, rectAxis); + + float speedY = helicopter->GetVertSpeedRTD(helicopter->RenderVisualState()); + speedY = speedY / 15.0f; + + float sizeX = rectAxis.w * 0.5f; + float sizeY = rectAxis.w * 0.5f; + Rect2DPixel rectIndicator( + rectAxis.x - sizeX, + rectAxis.y + 0.5f * (rectAxis.h - sizeY) - speedY * rectAxis.h * 0.5f, + sizeX, + sizeY); + + pars.mip = GEngine->TextBank()->UseMipmap(_indicator, 0, 0); + GEngine->Draw2D(pars, rectIndicator, rect); + + //height = floorf(height); + //float lowerHeight = height - fmod(height,100); + //float higherHeight = lowerHeight + 100; + //float heightDiff = (height - lowerHeight) / 100.0f; + + //sprintf(buffer, "%03d", (int)lowerHeight); + //float x = rectIndicator.x / w; + //float y = (rectAxis.y + rectAxis.h * 0.5f + heightDiff * rectAxis.h * 0.5f - _helicopterHUDfontSizeSmall *0.4) / w; + //GEngine->DrawText + // ( + // Point2DFloat(x, y), + // _helicopterHUDfontSizeSmall, _helicopterHUDtextFont, _helicopterHUDColor, buffer, _helicopterHUDShadow + // ); + + //sprintf(buffer, "%03d", (int)higherHeight); + //y = (rectAxis.y + rectAxis.h * 0.5f + (heightDiff - 1) * rectAxis.h * 0.5f - _helicopterHUDfontSizeSmall *0.4) / w; + //GEngine->DrawText + // ( + // Point2DFloat(x, y), + // _helicopterHUDfontSizeSmall, _helicopterHUDtextFont, _helicopterHUDColor, buffer, _helicopterHUDShadow + // ); + } + + sprintf(buffer, "%03d", (int)height); + if(disp->altimeterValue) disp->altimeterValue->SetText(buffer); + + dirty = true; + } + + /* -- ATTITUDE -- */ + if (disp->attitudeIndicator) + { + heliHudDraw = true; + _iguiHMD = true; + + Rect2DPixel rect( + disp->attitudeIndicator->X() * w, + disp->attitudeIndicator->Y() * h, + disp->attitudeIndicator->W() * w, + disp->attitudeIndicator->H() * h); + + Rect2DPixel rectClip( + disp->attitudeIndicator->X() * w, + disp->attitudeIndicator->Y() * h, + disp->attitudeIndicator->W() * w, + disp->attitudeIndicator->H() * h); + + float aspectRatio = (rect.h / rect.w); + + float pitch, bank; + helicopter->GetAttitude(helicopter->RenderVisualState(),pitch,bank); + + bool externalCamera = (GWorld->GetCameraType() == CamExternal); + //in external camera, _horizonAxes are rotated in opposite direction + + float cosXa = cos(bank); + float sinXa = sin(bank); + + float offset = -pitch / H_PI; + float visibleAngle = _attitudeFOV / H_PI; + + Matrix4 mtrans1Att = Matrix4(MTranslation, Vector3(-0.5 , 0, -0.5 )); + Matrix4 mtrans2Att = Matrix4(MTranslation, Vector3( 0.5 + offset, 0, 0.5 )); + Matrix4 mtransScale = Matrix4(MScale, visibleAngle, 1, 1); + Matrix4 mtransScaleAps = Matrix4(MScale, aspectRatio, 1, 1); + + if(externalCamera) mrot.SetUpAndDirection(VUp, Vector3(0, 0, 1)); + else mrot.SetUpAndDirection(VUp, Vector3(sinXa, 0, cosXa)); + + Matrix4 m = mtrans2Att * mtransScale * mrot * mtransScaleAps * mtrans1Att; + + Vector3 uv = m.FastTransform(Vector3(0 , 0, 1)); + pars.uTR = uv[2]; + pars.vTR = uv[0]; + uv = m.FastTransform(Vector3(0 , 0, 0)); + pars.uTL = uv[2]; + pars.vTL = uv[0]; + uv = m.FastTransform(Vector3(1 , 0, 1)); + pars.uBR = uv[2]; + pars.vBR = uv[0]; + uv = m.FastTransform(Vector3(1 , 0, 0)); + pars.uBL = uv[2]; + pars.vBL = uv[0]; + + pars.mip = GEngine->TextBank()->UseMipmap(_horizonAxes, 0, 0); + GEngine->Draw2D(pars, rect, rectClip); + + float elementSize = disp->attitudeIndicator->W() * w * _attitudeElemmentsSize; + Rect2DPixel rectAircraft = Rect2DPixel( + disp->attitudeIndicator->X() * w + 0.5 * (w * disp->attitudeIndicator->W() - elementSize), + disp->attitudeIndicator->Y() * h + 0.5 * (h * disp->attitudeIndicator->H() - elementSize), + elementSize, + elementSize); + + mtrans1Att = Matrix4(MTranslation, Vector3(-0.5, 0, -0.5)); + mtrans2Att = Matrix4(MTranslation, Vector3( 0.5, 0, 0.5)); + + if(externalCamera) mrot.SetUpAndDirection(VUp, Vector3(sinXa, 0, cosXa)); + else mrot.SetUpAndDirection(VUp, Vector3(0, 0, 1)); + + m = mtrans2Att * mrot * mtrans1Att; + + uv = m.FastTransform(v000); + pars.uTR = uv[2]; + pars.vTR = uv[0]; + uv = m.FastTransform(v001); + pars.uTL = uv[2]; + pars.vTL = uv[0]; + uv = m.FastTransform(v100); + pars.uBR = uv[2]; + pars.vBR = uv[0]; + uv = m.FastTransform(v101); + pars.uBL = uv[2]; + pars.vBL = uv[0]; + + pars.mip = GEngine->TextBank()->UseMipmap(_horizonAircraft, 0, 0); + GEngine->Draw2D(pars, rectAircraft, rectClip); + + Vector3 speed = helicopter->RenderVisualState().ModelSpeed() / 50.0f; + + Rect2DPixel rectVector = Rect2DPixel( + disp->attitudeIndicator->X() * w + 0.5 * (w * disp->attitudeIndicator->W() - elementSize) + disp->attitudeIndicator->W() * w * speed.X(), + disp->attitudeIndicator->Y() * h + 0.5 * (h * disp->attitudeIndicator->H() - elementSize) - disp->attitudeIndicator->H() * h * speed.Y(), + elementSize, + elementSize); + + + mtrans1Att = Matrix4(MTranslation, Vector3( + rectVector.w *0.5f - (rectAircraft.x - rectAircraft.w *0.5f), 0, + rectVector.h *0.5f - (rectAircraft.y - rectAircraft.h *0.5f))); + mtrans2Att = Matrix4(MTranslation, Vector3( - rectVector.w *0.5f + (rectAircraft.x - rectAircraft.w *0.5f), 0, - rectVector.h *0.5f + (rectAircraft.y - rectAircraft.h *0.5f))); + if(externalCamera) mrot.SetUpAndDirection(VUp, Vector3(-sinXa, 0, cosXa)); + else mrot.SetUpAndDirection(VUp, Vector3(0, 0, 1)); + + m = mtrans2Att * mrot * mtrans1Att; + Vector3 xz = m.FastTransform(Vector3(rectVector.x, 0, rectVector.y)); + rectVector.x = xz.X(); + rectVector.y = xz.Z(); + + pars.mip = GEngine->TextBank()->UseMipmap(_horizonVector, 0, 0); + GEngine->Draw2D(pars, rectVector, rectClip); + + dirty = true; + } + + if (disp->attitudeIndicatorLite) + { + _iguiHMD = true; + //if(GInput.lookAroundEnabled || Glob.config.vehicleFreelook) disp->attitudeIndicatorLite->ShowCtrl(false); + //else + { + float pitch, bank; + helicopter->GetAttitude(helicopter->RenderVisualState(),pitch,bank); + + float cosXa = cos(bank); + float sinXa = sin(bank); + + bool externalCamera = (GWorld->GetCameraType() == CamExternal); + const Camera *camera = GScene->GetCamera(); + //in external camera, _horizonAxes are rotated in opposite direction + + float elementSize = disp->attitudeIndicatorLite->W() * w * _attitudeElemmentsSize; + + Vector3 cursorDir = helicopter->RenderVisualState().DirectionModelToWorld(Vector3(0,0,1)); + Rect2DAbs rectAbs; + + if(DrawCursorCoordinates(*camera, helicopter, cursorDir, 1, 0, 0, 0, 0, rectAbs)) + { + + Rect2DAbs rectAircraft = Rect2DAbs( + rectAbs.x + 0.5 * ( - elementSize), + rectAbs.y + 0.5 * ( - elementSize), + elementSize, + elementSize); + + Matrix4 mtrans1Att = Matrix4(MTranslation, Vector3(-0.5, 0, -0.5)); + Matrix4 mtrans2Att = Matrix4(MTranslation, Vector3( 0.5, 0, 0.5)); + + if(externalCamera) mrot.SetUpAndDirection(VUp, Vector3(sinXa, 0, cosXa)); + else mrot.SetUpAndDirection(VUp, Vector3(0, 0, 1)); + + Matrix4 m = mtrans2Att * mrot * mtrans1Att; + + Vector3 uv = m.FastTransform(v000); + pars.uTR = uv[2]; + pars.vTR = uv[0]; + uv = m.FastTransform(v001); + pars.uTL = uv[2]; + pars.vTL = uv[0]; + uv = m.FastTransform(v100); + pars.uBR = uv[2]; + pars.vBR = uv[0]; + uv = m.FastTransform(v101); + pars.uBL = uv[2]; + pars.vBL = uv[0]; + + pars.mip = GEngine->TextBank()->UseMipmap(_horizonAircraft, 0, 0); + GEngine->Draw2D(pars, rectAircraft, rectAircraft); + } + + cursorDir = helicopter->RenderVisualState().Speed(); + + if(helicopter->RenderVisualState().Speed().Size() > 1 && DrawCursorCoordinates(*camera, helicopter, cursorDir, 1, 0, 0, 0, 0, rectAbs)) + { + + Rect2DAbs rectVector = Rect2DAbs( + rectAbs.x + 0.5 * (- elementSize), + rectAbs.y + 0.5 * (- elementSize), + elementSize, + elementSize); + + Matrix4 mtrans1Att = Matrix4(MTranslation, Vector3(-0.5, 0, -0.5)); + Matrix4 mtrans2Att = Matrix4(MTranslation, Vector3( 0.5, 0, 0.5)); + + if(externalCamera) mrot.SetUpAndDirection(VUp, Vector3(sinXa, 0, cosXa)); + else mrot.SetUpAndDirection(VUp, Vector3(0, 0, 1)); + + Matrix4 m = mtrans2Att * mrot * mtrans1Att; + + Vector3 uv = m.FastTransform(v000); + pars.uTR = uv[2]; + pars.vTR = uv[0]; + uv = m.FastTransform(v001); + pars.uTL = uv[2]; + pars.vTL = uv[0]; + uv = m.FastTransform(v100); + pars.uBR = uv[2]; + pars.vBR = uv[0]; + uv = m.FastTransform(v101); + pars.uBL = uv[2]; + pars.vBL = uv[0]; + + pars.mip = GEngine->TextBank()->UseMipmap(_horizonVector, 0, 0); + GEngine->Draw2D(pars, rectVector, rectVector); + } + } + dirty = true; + } + + + /* -- RADAR ALTMETER -- */ + if (disp->radarAltimeter) + { + heliHudDraw = true; + float height = floatMax(0, helicopter->GetRadarAltMeterPosition() - GLOB_LAND->RoadSurfaceYAboveWater(helicopter->RenderVisualState().Position())); + char buffer[256]; + if(height > 304.8)sprintf(buffer, "---"); + else + { +#if _HELISIM_IMPERIAL_SYSTEM + height = vehicle->GetType()->ConvertHeight(height); +#endif + sprintf(buffer, "%.1f", height); + + } + + height = (height > 304)? 1: height / 304.0f; + + if(disp->radarAltimeterBar) disp->radarAltimeterBar->SetPos(height); + if(disp->radarAltimeterValue) disp->radarAltimeterValue->SetText(buffer); + + dirty = true; + } + + /* -- GMETER -- */ + if (disp->gMeter) + { + char buffer[256]; + sprintf(buffer, "%+.2fG", helicopter->GetAccelerometer(helicopter->RenderVisualState())); + + disp->gMeter->SetText(buffer); + dirty = true; + } + + /* -- TORQUE -- */ + if (disp->torque) + { + char buffer[256]; + int torque = 100 * intMax(0.0f, helicopter->GetTorqueRTD(helicopter->RenderVisualState())/ helicopter->Type()->_maxTorque); + sprintf(buffer, "%d%%", torque); + + if(torque > 100) disp->torque->SetTextColor(PackedRed); + else disp->torque->SetTextColor(_helicopterHUDColor); + + disp->torque->SetText(buffer); + dirty = true; + } + + /* -- WIND -- */ + if (disp->winIndicator) + { + Rect2DPixel rect( + disp->winIndicator->X() * w, + disp->winIndicator->Y() * h, + disp->winIndicator->W() * w, + disp->winIndicator->H() * h); + + Vector3 dirA = Vector3(GLandscape->GetWindSpeed().X(), 0, GLandscape->GetWindSpeed().Z()); + dirA.Normalize(); + if (dirA.Size() > 0) + { + Vector3 dirB = helicopter->RenderVisualState().Direction().Normalized(); + + float cosXa = dirB.DotProduct(dirA); + float sinXa = dirB.DotProduct(Vector3(-dirA.Z(),0,dirA.X())); + + mrot.SetUpAndDirection(VUp, Vector3(sinXa, 0, cosXa)); + Matrix4 m = mtrans2 * mrot * mtrans1; + + Vector3 uv = m.FastTransform(v000); + pars.uTR = uv[2]; + pars.vTR = uv[0]; + uv = m.FastTransform(v001); + pars.uTL = uv[2]; + pars.vTL = uv[0]; + uv = m.FastTransform(v100); + pars.uBR = uv[2]; + pars.vBR = uv[0]; + uv = m.FastTransform(v101); + pars.uBL = uv[2]; + pars.vBL = uv[0]; + pars.mip = GEngine->TextBank()->UseMipmap(_windDirection, 0, 0); + GEngine->Draw2D(pars, rect, rect); + + dirty = true; + } + } + + /* -- STABILITY -- */ + if (disp->stabilityIndicator) + { + heliHudDraw = true; + Rect2DPixel rect( + disp->stabilityIndicator->X() * w, + disp->stabilityIndicator->Y() * h, + disp->stabilityIndicator->W() * w, + disp->stabilityIndicator->H() * h); + + Vector3 uv =v100; + pars.uTR = uv[2]; + pars.vTR = uv[0]; + uv = v101; + pars.uTL = uv[2]; + pars.vTL = uv[0]; + uv = v000; + pars.uBR = uv[2]; + pars.vBR = uv[0]; + uv = v001; + pars.uBL = uv[2]; + pars.vBL = uv[0]; + + pars.mip = GEngine->TextBank()->UseMipmap(_stabilityGrid, 0, 0); + GEngine->Draw2D(pars, rect, rect); + + Vector3 speed = helicopter->RenderVisualState().ModelSpeed(); + if (fabs(speed.X() < 13.8f) && speed.Z() < 20.833f && speed.Z() > -13.8f) //speed smaller then 50 km/h + { + float scale = 0.25f; + float sizeX = rect.w * scale; + float sizeY = rect.h * scale; + + float x = rect.x + 0.5f * rect.w; + float y = rect.y + 0.5f * rect.h + 0.1f * rect.h; // 0.1f * size grid is not centred + + x += (speed.X() / 13.8f) * 0.5f * rect.w; + y -= (speed.Z() > 0) ? ((speed.Z()/ 20.833f) * 0.6f * rect.h) : ((speed.Z() / 13.8f) * 0.4f * rect.h); + + Rect2DPixel rectVector( + x - 0.5f * sizeX, + y - 0.5f * sizeY, + sizeX, + sizeY); + + pars.mip = GEngine->TextBank()->UseMipmap(_stabilityVector, 0, 0); + GEngine->Draw2D(pars, rectVector, rect); + } + dirty = true; + } + + /* -- COLLECTIVE -- */ + if (disp->collective) + { + disp->collective->SetPos(helicopter->GetCollective(helicopter->RenderVisualState())); + dirty = true; + } + + /* -- TRIM -- */ + if (disp->trimIndicator) + { + disp->trimIndicator->ShowCtrl(helicopter->GetAutoTrim()); + dirty = true; + } + + /* -- AUTOHOVER -- */ + if (disp->autohover) + { + disp->autohover->ShowCtrl(helicopter->GetAutoHover()); + dirty = true; + } + + // ---------------------- ANALOGUE ---------------------- // + // ---------------------- -------- ---------------------- // + + Vector3 minMoveBorders = GWorld->GetMoveMinBordersHUD(); //mix speed, altitude, direction + Vector3 maxMoveBorders = GWorld->GetMoveMaxBordersHUD(); //max speed, altitude, direction + Vector3 moveDirHUD = VZero; + + if(GWorld->GetMoveTargetHUD()) moveDirHUD = GWorld->GetMoveTargetHUD()->RenderVisualState().Position() - helicopter->RenderVisualState().Position(); + else moveDirHUD = GWorld->GetMovePositionHUD() - helicopter->RenderVisualState().Position(); + moveDirHUD.Normalize(); + + /* -- ANALOGUE SPEED -- */ + if(disp->speedAnalogue) + { + heliHudDraw = true; + float minSpeed = minMoveBorders[0]; + float maxSpeed = maxMoveBorders[0]; + float airSpeed = helicopter->RenderVisualState().ModelSpeed().Z(); // m/s + + PackedColor limitColor = ((fabs(minSpeed) < 0.00001f || minSpeed <= airSpeed) && (maxSpeed>=airSpeed || fabs(maxSpeed) < 0.00001f))? _HUDLimitsColor : _statusDestroyed; + + if (disp->speedAnalogueNeedle) + { + float airSpeed = helicopter->RenderVisualState().ModelSpeed().Z(); // m/s + saturate(airSpeed,-1.388f, MAX_HELICOPTER_SPEED); + float angle = (airSpeed / MAX_HELICOPTER_SPEED )* _analogueSpeedAngleRange - _analogueSpeedAngleOffset; // speed is from 0 degr. to 340 degr. + + disp->speedAnalogueNeedle->SetPictureUVTransfrom(GetHudImageRotation(angle)); + } + + + if (disp->speedAnalogueMin) + { + + if(fabs(minSpeed) < 0.00001f) disp->speedAnalogueMin->ShowCtrl(false); + else + { + disp->speedAnalogueMin->ShowCtrl(true); + saturate(minSpeed,-1.388f, MAX_HELICOPTER_SPEED); + float angle = (minSpeed / MAX_HELICOPTER_SPEED )* _analogueSpeedAngleRange - _analogueSpeedAngleOffset; // speed is from 0 degr. to 340 degr. + + //original position + Vector3 offset = GetHudImageOffset(disp->speedAnalogueMin, disp->speedAnalogue, angle); + //move to 0,0, move rotated position and rotate + disp->speedAnalogueMin->SetPictureOffset(offset.X(), offset.Z()); + disp->speedAnalogueMin->SetPictureUVTransfrom(GetHudImageRotation(angle)); + disp->speedAnalogueMin->SetColor(limitColor); + } + } + + if (disp->speedAnalogueMax) + { + + if(fabs(maxSpeed) < 0.00001f) disp->speedAnalogueMax->ShowCtrl(false); + else + { + disp->speedAnalogueMax->ShowCtrl(true); + saturate(maxSpeed,-1.388f, MAX_HELICOPTER_SPEED); + float angle = (maxSpeed / MAX_HELICOPTER_SPEED )* _analogueSpeedAngleRange - _analogueSpeedAngleOffset; // speed is from 0 degr. to 340 degr. + + //original position + Vector3 offset = GetHudImageOffset(disp->speedAnalogueMax, disp->speedAnalogue, angle); + + //move to 0,0, move rotated position and rotate + disp->speedAnalogueMax->SetPictureOffset(offset.X(), offset.Z()); + disp->speedAnalogueMax->SetPictureUVTransfrom(GetHudImageRotation(angle)); + disp->speedAnalogueMax->SetColor(limitColor); + } + } + + if (disp->speedAnalogueValue) + { + float speed = helicopter->RenderVisualState().ModelSpeed().Z(); // m/s + float speedMS = speed; + +#if _HELISIM_IMPERIAL_SYSTEM + speed = toInt(vehicle->GetType()->ConvertSpeed(speed)); +#else + speed = toInt(3.6 * speed); +#endif + sprintf(buffer, "%.0f", speed); + if (disp->speedAnalogueValue->SetText(buffer)) dirty = true; + + if(speedMS > helicopter->Type()->_retreatBladeStallWarningSpeed) disp->speedAnalogueValue->SetTextColor(_statusDestroyed); + else if (speedMS > 0.9f * helicopter->Type()->_retreatBladeStallWarningSpeed) disp->speedAnalogueValue->SetTextColor(_statusDamaged); + else + { + if(disp->altitudeAnalogueValue) disp->speedAnalogueValue->SetTextColor(disp->altitudeAnalogueValue->GetTextColor()); + else disp->speedAnalogueValue->SetTextColor(PackedWhite); + } + } + + if (disp->speedAnalogueMetric) disp->speedAnalogueMetric->ShowCtrl(Glob.config.useImperialSystem == 0); + if (disp->speedAnalogueImperial) disp->speedAnalogueImperial->ShowCtrl(Glob.config.useImperialSystem > 0); + } + + /* -- ANALOGUE ALTITUDE -- */ + if(disp->altitudeAnalogue) + { + heliHudDraw = true; + Vector3Val pos = vehicle->RenderVisualState().Position(); + float y = pos.Y() + vehicle->GetShape()->Min().Y(); +#if _VBS2 + float y0 = GLOB_LAND->SurfaceYAboveWater(pos.X(), pos.Z()); +#else + float y0 = GLOB_LAND->RoadSurfaceYAboveWater(pos.X(), pos.Z()); +#endif + float h = y - y0; + saturate(h, 0, 99999); + + float altitudeMin = minMoveBorders[1]; + float altitudeMax = maxMoveBorders[1]; + PackedColor limitColor = (altitudeMin <= h && (altitudeMax>=h || altitudeMax <=0.00001f))? _HUDLimitsColor : _statusDestroyed; + + + if (disp->altitudeAnalogueNeedle) + { + float altitude = h; + saturate(altitude, 0, MAX_HELICOPTER_HEIGHT); + float angle = (log((altitude / MAX_HELICOPTER_HEIGHT) * 26 + 1) / log(27)) * _analogueAltitudeAngleRange - _analogueAltitudeAngleOffset; // 300m = 33%, 1000m = 66%, 4000m =100% + + disp->altitudeAnalogueNeedle->SetPictureUVTransfrom(GetHudImageRotation(angle)); + } + + if (disp->altitudeAnalogueMin) + { + if(fabs(altitudeMin) < 0.00001f) disp->altitudeAnalogueMin->ShowCtrl(false); + else + { + disp->altitudeAnalogueMin->ShowCtrl(true); + saturate(altitudeMin, 0, MAX_HELICOPTER_HEIGHT); + float angle = (log((altitudeMin / MAX_HELICOPTER_HEIGHT) * 26 + 1) / log(27)) * _analogueAltitudeAngleRange - _analogueAltitudeAngleOffset; // 300m = 33%, 1000m = 66%, 4000m =100% + + //original position + Vector3 offset = GetHudImageOffset(disp->altitudeAnalogueMin, disp->altitudeAnalogue, angle); + //move to 0,0, move rotated position and rotate + disp->altitudeAnalogueMin->SetPictureOffset(offset.X(), offset.Z()); + disp->altitudeAnalogueMin->SetPictureUVTransfrom(GetHudImageRotation(angle)); + disp->altitudeAnalogueMin->SetColor(limitColor); + } + } + + if (disp->altitudeAnalogueMax) + { + if(fabs(altitudeMax) < 0.00001f) disp->altitudeAnalogueMax->ShowCtrl(false); + else + { + disp->altitudeAnalogueMax->ShowCtrl(true); + saturate(altitudeMax, 0, MAX_HELICOPTER_HEIGHT); + float angle = (log((altitudeMax / MAX_HELICOPTER_HEIGHT) * 26 + 1) / log(27)) * _analogueAltitudeAngleRange - _analogueAltitudeAngleOffset; // 300m = 33%, 1000m = 66%, 4000m =100% + + //original position + Vector3 offset = GetHudImageOffset(disp->altitudeAnalogueMax, disp->altitudeAnalogue, angle); + + //move to 0,0, move rotated position and rotate + disp->altitudeAnalogueMax->SetPictureOffset(offset.X(), offset.Z()); + disp->altitudeAnalogueMax->SetPictureUVTransfrom(GetHudImageRotation(angle)); + disp->altitudeAnalogueMax->SetColor(limitColor); + } + } + + if (disp->altitudeAnalogueValue) + { +#if _VBS3 //height in feet + h *= 3.28084; +#endif + +#if _HELISIM_IMPERIAL_SYSTEM + h = vehicle->GetType()->ConvertHeight(h); +#endif + sprintf(buffer,"%.0f", h); + disp->altitudeAnalogueValue->SetText(buffer); + } + + if (disp->altitudeAnalogueMetric) disp->altitudeAnalogueMetric->ShowCtrl(Glob.config.useImperialSystem == 0); + if (disp->altitudeAnalogueImperial) disp->altitudeAnalogueImperial->ShowCtrl(Glob.config.useImperialSystem > 0); + } + + /* -- ANALOGUE COMPASS -- */ + if(disp->compassAnalogue) + { + heliHudDraw = true; + if(disp->compassAnalogueNeedle) + { + disp->compassAnalogueNeedle->SetPictureUVTransfrom(GetHudImageRotation(-helicopter->GetCtrlDirection(helicopter->RenderVisualState()))); + } + + float vehicleDir = helicopter->GetCtrlDirection(helicopter->RenderVisualState()); + if(disp->compassAnalogueWind ) + { + Vector3 dir = Vector3(GLandscape->GetWindSpeed().X(), 0, GLandscape->GetWindSpeed().Z()); + if(dir.Size() > 0) + { + dir.Normalize(); + float angle = ((atan2(dir.X(), dir.Z())) - vehicleDir) ; + disp->compassAnalogueWind->SetPictureUVTransfrom(GetHudImageRotation(angle)); + } + } + + if(disp->compassAnalogueWindValue) + { + Vector3 dir = Vector3(GLandscape->GetWindSpeed().X(), 0, GLandscape->GetWindSpeed().Z()); + float speed = dir.Size(); +#if _HELISIM_IMPERIAL_SYSTEM + speed = Glob.config.useImperialSystem > 0 ? METER_TO_MILE_PER_HOUR(speed) : speed; +#endif + sprintf(buffer, "%+.1f", speed); + disp->compassAnalogueWindValue->SetText(buffer); + } + + Vector3Val dir = helicopter->RenderVisualState().Direction(); + + // avoid singularity when heading up + float angleTransport; + if (fabs(dir.X()) + fabs(dir.Z()) > 1e-3) + angleTransport = atan2(dir.X(), dir.Z()); + else + angleTransport = 0; + + if(disp->compassAnalogueValue) + { + int degAngle = toInt(angleTransport * (180.0f / H_PI)); + if (degAngle < 0) degAngle += 360; + + sprintf(buffer, "%03d", degAngle); + disp->compassAnalogueValue->SetText(cc_cast(buffer)); + } + + //target direction + float angleDir = (atan2(moveDirHUD.X(), moveDirHUD.Z()) - vehicleDir); + if(angleDir < - H_PI) angleDir +=H_2PI; + else if(angleDir > H_PI) angleDir -=H_2PI; + + //min target direction + float angleMin = angleDir + minMoveBorders[2]; + if(angleMin < 0) angleMin +=H_2PI; + else if(angleMin > H_2PI) angleMin -=H_2PI; + //max target direction + float angleMax = angleDir + maxMoveBorders[2]; + if(angleMax < 0) angleMax +=H_2PI; + else if(angleMax > H_2PI) angleMax -=H_2PI; + + PackedColor limitColor = (angleMin > angleMax)? _HUDLimitsColor : _statusDestroyed; + + if(disp->compassAnalogueMin ) + { + //rotated position + if(fabs(minMoveBorders[2] - maxMoveBorders[2]) < 0.00001f) disp->compassAnalogueMin->ShowCtrl(false); + else + { + disp->compassAnalogueMin->ShowCtrl(true); + Vector3 offset = GetHudImageOffset(disp->compassAnalogueMin, disp->compassAnalogue, angleMin); + + //move to 0,0, move rotated position and rotate + disp->compassAnalogueMin->SetPictureOffset(offset.X(), offset.Z()); + disp->compassAnalogueMin->SetPictureUVTransfrom(GetHudImageRotation(angleMin)); + disp->compassAnalogueMin->SetColor(limitColor); + } + } + + if(disp->compassAnalogueMax ) + { + //rotated position + + if(fabs(minMoveBorders[2] - maxMoveBorders[2]) < 0.00001f) disp->compassAnalogueMax->ShowCtrl(false); + else + { + disp->compassAnalogueMax->ShowCtrl(true); + Vector3 offset = GetHudImageOffset(disp->compassAnalogueMax, disp->compassAnalogue, angleMax); + + //move to 0,0, move rotated position and rotate + disp->compassAnalogueMax->SetPictureOffset(offset.X(), offset.Z()); + disp->compassAnalogueMax->SetPictureUVTransfrom(GetHudImageRotation(angleMax)); + disp->compassAnalogueMax->SetColor(limitColor); + } + } + + } + + /* -- ANALOGUE STABILITY -- */ + if(disp->stabilityAnalogue) + { + heliHudDraw = true; + if(disp->stabilityAnalogueSpeed) + { + + Vector3 position = + - Vector3(disp->stabilityAnalogueSpeed->X(), 0, disp->stabilityAnalogueSpeed->Y()) + - Vector3(disp->stabilityAnalogueSpeed->W()* 0.5f, 0, disp->stabilityAnalogueSpeed->H()* 0.5f) + + Vector3(disp->stabilityAnalogue->W()* 0.5f, 0, disp->stabilityAnalogue->H()* 0.5f); + + Vector3 offset = Vector3 ( + (disp->stabilityAnalogueSpeed->X() + disp->stabilityAnalogueSpeed->W() * 0.5f ) - disp->stabilityAnalogue->W() * 0.5f, + 0 , + (disp->stabilityAnalogueSpeed->Y() + disp->stabilityAnalogueSpeed->H() * 0.5f ) - disp->stabilityAnalogue->H() * 0.5f); + + Vector3 speed = helicopter->RenderVisualState().ModelSpeed(); + speed[1] = 0; + speed[2] = -speed[2]; + speed = (speed / 13.6f); + if(speed.Size() > 1.0) speed.Normalize(); + + position += Vector3(speed[0] * disp->stabilityAnalogueSpeed->X(), 0, speed[2] * disp->stabilityAnalogueSpeed->Y()); + disp->stabilityAnalogueSpeed->SetPictureOffset(position.X(), position.Z()); + } + + if(disp->stabilityAnalogueValue) + { + float speedY = helicopter->GetVertSpeedRTD(helicopter->RenderVisualState()); +#if _HELISIM_IMPERIAL_SYSTEM + speedY = toInt(vehicle->GetType()->ConvertVerticalSpeed(speedY)); +#else + speedY = toInt(speedY); +#endif + sprintf(buffer, "%+.0f", speedY); + disp->stabilityAnalogueValue->SetText(buffer); + } + + if(disp->stabilityAnalogueVSpeedNeedle) + { + float speedY = helicopter->GetVertSpeedRTD(helicopter->RenderVisualState()); + speedY = speedY / 15.0f; + saturate(speedY, -1, 1); + + float angle = H_PI2 * speedY - H_PI2; + disp->stabilityAnalogueVSpeedNeedle->SetPictureUVTransfrom(GetHudImageRotation(angle)); + } + + if(disp->stabilityAnalogueCollective) + { + float collective = helicopter->GetCollective(helicopter->RenderVisualState()); + saturate(collective, 0, 1); + Rect2DFloat clip = Rect2DFloat(0,1 - collective,0,0); + disp->stabilityAnalogueCollective->SetClipPictureOffsetPerct(clip); + } + + if(disp->stabilityAnalogueVSpeed) + { + + float speedY = helicopter->GetVertSpeedRTD(helicopter->RenderVisualState()); + speedY = speedY / 15.0f; + saturate(speedY, -1, 1); + float y = 0; + float h = 0; + if(speedY > 0) + { + y = (1 - speedY) * 0.5f; + h = - 0.5f - (1 - fabs(speedY)) * 0.5f; + } + else + { + y = 0.5f; + h = - 0.5f - (1 - fabs(speedY)) * 0.5f; + } + + Rect2DFloat clip = Rect2DFloat(0, y ,0, h); + disp->stabilityAnalogueVSpeed->SetClipPictureOffsetPerct(clip); + } + + if(disp->stabilityAnalogueMetric) disp->stabilityAnalogueMetric->ShowCtrl(Glob.config.useImperialSystem == 0); + if(disp->stabilityAnalogueImperial) disp->stabilityAnalogueImperial->ShowCtrl(Glob.config.useImperialSystem > 0); + } + + if(disp->horizonAnalogue) + { + if(disp->horizonAnalogueAttitude) + { + float aspectRatio = (disp->horizonAnalogueAttitude->H() / disp->horizonAnalogueAttitude->W()); + + float pitch, bank; + helicopter->GetAttitude(helicopter->RenderVisualState(),pitch,bank); + + bank -= H_2PI; + float cosXa = cos(-bank); + float sinXa = sin(-bank); + + float offset = -pitch / H_PI; + float visibleAngle = _attitudeFOV / H_PI; + + Matrix4 mtrans1Att = Matrix4(MTranslation, Vector3(-0.5 , 0, -0.5 )); + Matrix4 mtrans2Att = Matrix4(MTranslation, Vector3( 0.5 , 0, 0.5 + offset)); + Matrix4 mtransScale = Matrix4(MScale, 1, 1, visibleAngle); + Matrix4 mtransScaleAps = Matrix4(MScale, 1, 1, aspectRatio); + + mrot.SetUpAndDirection(VUp, Vector3(sinXa, 0, cosXa)); + Matrix4 m = mtrans2Att * mtransScale * mrot * mtransScaleAps * mtrans1Att; + + disp->horizonAnalogueAttitude->SetPictureUVTransfrom(m); + } + + if(disp->horizonAnalogueValue) + { + sprintf(buffer, "%+.1fG", helicopter->GetAccelerometer(helicopter->RenderVisualState())); + disp->horizonAnalogueValue->SetText(buffer); + } + } + + + /* -- DAMAGE -- */ + if(disp->statusDamage) + { + bool batterryOnCharged = (helicopter->IsBatteryOn() && helicopter->GetBatteryCharge() > 0); + + if(disp->statusEnginesRPM) + { + float state = helicopter->GetEngineRPMState(); + if(!batterryOnCharged) disp->statusEnginesRPM->SetColor(_statusOff); + else if(state < 0.2) disp->statusEnginesRPM->SetColor(_statusDestroyed); + else if(state < 0.9) disp->statusEnginesRPM->SetColor(_statusDamaged); + else disp->statusEnginesRPM->SetColor(_statusOn); + } + + if(disp->statusEnginesDamage) + { + float damage = helicopter->GetEngineMaxDamage(); + if(!batterryOnCharged) disp->statusEnginesDamage->SetColor(_statusOff); + else if(damage > 0.8) disp->statusEnginesDamage->SetColor(_statusDestroyed); + else if(damage > 0.6) disp->statusEnginesDamage->SetColor(_statusDamaged); + else disp->statusEnginesDamage->SetColor(_statusOn); + } + + if(disp->statusTorque) + { + float torque = GWorld->IsStressDamageEnabled() ? floatMax(0.0f, helicopter->GetTorqueRTD(helicopter->RenderVisualState())/ helicopter->Type()->_maxTorque) : 0; + if(!batterryOnCharged) disp->statusTorque->SetColor(_statusOff); + else if(torque > 1.0) disp->statusTorque->SetColor(_statusDestroyed); + else if(torque > 0.9) disp->statusTorque->SetColor(_statusDamaged); + else disp->statusTorque->SetColor(_statusOn); + } + + if(disp->statusElectricity) + { + float charge = helicopter->GetBatteryCharge() / helicopter->Type()->_maxBatteryCharge; + if(!batterryOnCharged) disp->statusElectricity->SetColor(_statusOff); + else if(charge < 0.15) disp->statusElectricity->SetColor(_statusDestroyed); + else if(charge < 0.3) disp->statusElectricity->SetColor(_statusDamaged); + else disp->statusElectricity->SetColor(_statusOn); + } + + if(disp->statusFuel) + { + float fuel = helicopter->GetFuel() / helicopter->GetType()->GetFuelCapacity(); + if(!batterryOnCharged) disp->statusFuel->SetColor(_statusOff); + else if(fuel < 0.1) disp->statusFuel->SetColor(_statusDestroyed); + else if(fuel < 0.3) disp->statusFuel->SetColor(_statusDamaged); + else disp->statusFuel->SetColor(_statusOn); + } + + if(disp->temperature) + { //changed to temperature, old IDC + float temp = helicopter->GetMaxEngineTemperatureScaled(); + bool hotStart = helicopter->IsHotStart(); + if(!batterryOnCharged) disp->temperature->SetColor(_statusOff); + else if(temp > 1.0) disp->temperature->SetColor(_statusDestroyed); + else if(hotStart) disp->temperature->SetColor(_statusDamaged); + else disp->temperature->SetColor(_statusOn); + } + + if(disp->mainRotor) + { + float damage = helicopter->GetMainRotorDamage(); + if(!batterryOnCharged) disp->mainRotor->SetColor(_statusOff); + else if(damage > 0.8) disp->mainRotor->SetColor(_statusDestroyed); + else if(damage > 0.6) disp->mainRotor->SetColor(_statusDamaged); + else disp->mainRotor->SetColor(_statusOn); + } + + if(disp->tailRotor) + { + float damage = helicopter->GetTailRotorDamage(); + if(!batterryOnCharged) disp->tailRotor->SetColor(_statusOff); + else if(damage > 0.8) disp->tailRotor->SetColor(_statusDestroyed); + else if(damage > 0.6) disp->tailRotor->SetColor(_statusDamaged); + else disp->tailRotor->SetColor(_statusOn); + } + + if(disp->statusAutohover) + { + if (helicopter->GetAutoHover() && batterryOnCharged) disp->statusAutohover->SetColor(_statusOn); + else disp->statusAutohover->SetColor(_statusOff); + } + } + return heliHudDraw; +}; +#endif + +void InGameUI::DrawWeaponInfo(const Camera &camera) +{ + AIBrain *agent = GWorld->FocusOn(); + if (!agent || !agent->GetVehicle()) return; + EntityAIFull *vehicle = agent->GetVehicle(); + + bool scope = (GWorld->GetCameraType() == CamGunner) && vehicle->EnableOptics(vehicle->RenderVisualState()); + + TurretContext context; + WeaponModePtr ptr; + + PackedColor colorElevation = PackedColorRGB(_weaponInfoColor, toIntFloor(_weaponInfoColor.A8() * _weaponInfoAlpha)); + + if (vehicle->FindTurret(agent->GetPerson(), context)) + { + // when manual fire is on, commander is controlling gunner's weapons (even when has own weapons) + ptr = context._weapons->ValidatedCurrentWeapon(); + } + else return; + + const WeaponType *weaponType = NULL; + if (agent->IsFreeSoldier()) + { + if (!ptr.IsValid()) return; + weaponType = ptr.GetWeaponType(); + } + else if(!agent->GetVehicleIn()) return; + + if (weaponType == NULL && context._turretType == NULL) return; + + const MuzzleType *muzzle = ptr.GetMuzzleType(); + if (!muzzle) return; + + const AutoArray &infos = (weaponType!= NULL)? weaponType->GetWeaponInfoTypes():context._turretType->GetTurretInfoTypes(); + int n = infos.Size(); + _lastWeaponInfos.Resize(n); + if (n == 0) return; + + for (int i=0; iReload(Pars >> "RscInGameUI" >> desc._name); + desc._changed = Glob.uiTime; + } + + DisplayWeaponInfo *disp = desc._display; + + // --- ZEROING --- // + if(disp->elevation) + { + disp->elevation->SetTextColor(colorElevation); + + char buffer[256]; sprintf(buffer,""); + //Transport *transport = agent->GetVehicleIn(); + if(agent->IsFreeSoldier() && agent->GetVehicle()) + { + const OpticsInfo *opticsInfo = ptr.GetOpticsInfo(); + DoAssert(opticsInfo); + + float distance = 0; + if (opticsInfo->_discreteDistance.Size() == 0) + { + distance= Interpolativ(agent->GetVehicle()->GetCameraFOV(), opticsInfo->_opticsZoomMin, opticsInfo->_opticsZoomMax, + opticsInfo->_distanceZoomMin, opticsInfo->_distanceZoomMax); + } + else if (ptr.IsValid()) + { + distance = opticsInfo->_discreteDistance[intMin(ptr.GetDiscreteDistanceIndex(), opticsInfo->_discreteDistance.Size()-1)]; + } +#if _HELISIM_IMPERIAL_SYSTEM + //zeroing in meters or feets (miles not even for air) + if(Glob.config.useImperialSystem == 2) sprintf(buffer, "%d", (int)(METER_TO_FEET(distance))); + else sprintf(buffer, "%d", (int)distance); +#else + sprintf(buffer, "%d", (int)distance); +#endif + dirty = disp->elevation->SetText(buffer); + } + else if (ptr.IsValid()) + { + float distance = 0; + + if (muzzle && (muzzle->_ballisticsComputer == 1 || muzzle->_ballisticsComputer == 2) + && context._turretType->_discreteDistance.Size()>0 && context._turret->_distanceIndex >=0) + { + disp->elevation->ShowCtrl(true); + distance = context._turretType->_discreteDistance[intMin(context._turret->_distanceIndex,context._turretType->_discreteDistance.Size()-1)]; +#if _HELISIM_IMPERIAL_SYSTEM + //zeroing in meters or feets (miles not even for air) + if(Glob.config.useImperialSystem == 2) sprintf(buffer, "%d", (int)(METER_TO_FEET(distance))); + else sprintf(buffer, "%d", (int)distance); +#else + sprintf(buffer, "%d", (int)distance); +#endif + dirty = disp->elevation->SetText(buffer); + } + else disp->elevation->ShowCtrl(false); + } + + if(disp->elevationText) + { + disp->elevationText->SetTextColor(colorElevation); + //Transport *transport = agent->GetVehicleIn(); + if(!agent->IsFreeSoldier()) + { + if (muzzle && (muzzle->_ballisticsComputer == 1 || muzzle->_ballisticsComputer == 2) + && context._turretType->_discreteDistance.Size()>0 && context._turret->_distanceIndex >=0) + { + disp->elevationText->ShowCtrl(true); + } + else disp->elevationText->ShowCtrl(false); + } + } + } + + //distance from aimed target/ground + if (disp->distance || disp->GPSTarget) + { + if(disp->distance) disp->distance->ShowCtrl(scope); + if(disp->GPSTarget) disp->GPSTarget->ShowCtrl(scope); + + if(scope) + { + float distance = -1; + char buffer[256]; + //distance to which we try to detect vehicles + float MaxDist = 1500.0f; + const float MaxDistGround = 5000.0f; + /*Vector3 dir = agent->Direction(); + dir.Normalize();*/ + + Matrix4 animTrans; + Vector3 lPos = camera.Position(); + Vector3 lDir = camera.Direction().Normalized(); + + Vector3 tmpEnd; + float tGround = GLandscape->IntersectWithGroundOrSea(&tmpEnd, lPos, lDir, 0, MaxDistGround); + MaxDist = floatMin(tGround,MaxDist); + + CollisionBuffer result; + GLandscape->ObjectCollisionLine(vehicle->GetRenderVisualStateAge(), result, Landscape::FilterIgnoreOne(agent->GetVehicle()), lPos, lPos + lDir * MaxDist, 0/*0.5f*/, ObjIntersectFire, ObjIntersectView, CF_NEAREST_CONTACT); + // select the nearest + if (result.Size() > 0) + { + float dist2 = lPos.Distance2(result[0].pos); + distance = sqrtf(dist2); + } + else if(tGround < MaxDistGround) + { + distance = tGround; + } + +#if _HELISIM_IMPERIAL_SYSTEM + if(distance>=0) + { + if(Glob.config.useImperialSystem == 2) sprintf(buffer,"%d", (int) METER_TO_FEET(distance)); + else sprintf(buffer,"%d", (int)distance); + } +#else + if(distance>=0) sprintf(buffer,"%d", (int)distance); +#endif + else + sprintf(buffer,"--"); + + if(disp->distance) disp->distance->SetText(buffer); + + if(distance>=0) + { + Vector3 targetPos = lPos + lDir*distance; + PositionToAA11(targetPos, buffer); + } + else + sprintf(buffer,"--"); + if(disp->GPSTarget) disp->GPSTarget->SetText(buffer); + } + } + + //position of player + if (disp->GPSPlayer) + { + disp->GPSPlayer->ShowCtrl(scope); + if(scope) + { + char buffer[256]; + PositionToAA11(vehicle->RenderVisualState().Position(), buffer); + disp->GPSPlayer->SetText(buffer); + } + } + + //draw compass + if(scope && disp->showCompass) + DrawCompass(vehicle); + + + //vision mode - normal, night vision, FLIR + if (disp->visionMode) + { + disp->visionMode->ShowCtrl(scope); + if(scope) + { + char buffer[256]; + if (GEngine->GetThermalVisionWanted()) sprintf(buffer,"FLIR"); + else + if (agent->GetPerson() && agent->GetPerson()->IsNVWanted()) sprintf(buffer,"NVS"); + else sprintf(buffer,"DTV"); + + disp->visionMode->SetText(buffer); + } + } + + //FLIR mode black-white, red-black, .... + if (disp->FLIRMode) + { + disp->FLIRMode->ShowCtrl(scope); + if(scope) + { + char buffer[256]; + if (GEngine->GetThermalVisionWanted()) + { + int mode =GEngine->GetTIMode(); + if(mode < sizeof(_FLIRModeNames)) sprintf(buffer,"%s", _FLIRModeNames[mode].Data()); + else sprintf(buffer,""); + } + else + sprintf(buffer,""); + + disp->FLIRMode->SetText(buffer); + } + } + + //show compass (if it is not already) + if (disp->compass) + { + disp->compass->ShowCtrl(scope); + if(scope) + { + bool canSeeCompass = false; + Transport *transport = agent->GetVehicleIn(); + if (transport) + { + int canSee = 0; + if (agent == transport->ObserverUnit()) canSee = transport->Type()->_commanderCanSee; + else if (agent == transport->PilotUnit()) canSee = transport->Type()->_driverCanSee; + else if (agent == transport->GunnerUnit()) canSee = transport->Type()->_gunnerCanSee; + canSeeCompass = (canSee&CanSeeCompass)!=0; + } + + if(!canSeeCompass) DrawCompass(vehicle); + } + } + + //show heading (if it is not already) + if (disp->heading) + { + disp->heading->ShowCtrl(scope); + if(scope) + { + bool canSeeCompass = false; + Transport *transport = agent->GetVehicleIn(); + if (transport) + { + int canSee = 0; + if (agent == transport->ObserverUnit()) canSee = transport->Type()->_commanderCanSee; + else if (agent == transport->PilotUnit()) canSee = transport->Type()->_driverCanSee; + else if (agent == transport->GunnerUnit()) canSee = transport->Type()->_gunnerCanSee; + canSeeCompass = (canSee&CanSeeCompass)!=0; + } + + if(!canSeeCompass) + { + Camera &cam = *GLOB_SCENE->GetCamera(); + Vector3Val dir = cam.Direction(); + + // avoid singularity when heading up + float angle; + if (fabs(dir.X()) + fabs(dir.Z()) > 1e-3) + angle = atan2(dir.X(), dir.Z()); + else + angle = 0; + + int degAngle = toInt(angle * (180.0f / H_PI)); + if (degAngle < 0) degAngle += 360; + BString<16> buffer; + sprintf(buffer, "%03d", degAngle); + + disp->heading->SetText(cc_cast(buffer)); + } + } + } + + //hovering mode + if(disp->autohover) + { + disp->autohover->ShowCtrl(scope); + if(scope) + { + Transport *transport = agent->GetVehicleIn(); + if(transport && transport->GetAutoHover()) disp->autohover->ShowCtrl(true); + else disp->autohover->ShowCtrl(false); + } + } + + //FOV mode + if(disp->FOVMode) + { + disp->FOVMode->ShowCtrl(scope); + if(scope) + { + char buffer[256]; sprintf(buffer,""); + //Transport *transport = agent->GetVehicleIn(); + if (agent->IsFreeSoldier()) + { + const OpticsInfo *opticsInfo = ptr.GetOpticsInfo(); + DoAssert(opticsInfo); + sprintf(buffer, "%s", opticsInfo->_opticsDisplayName.Data()); + } + else if (agent->GetVehicleIn() && context._turret) + { + const ViewPars *view = context._turret->GetCurrentViewPars(context._turretType); + if(view) + sprintf(buffer, "%s", view->_opticsDisplayName.Data()); + } + disp->FOVMode->SetText(buffer); + } + } + + + //hide text if not in optics + if(disp->staticItems) + disp->staticItems->ShowCtrl(scope); + + desc._changed = Glob.uiTime; + float alpha = 1.0; + + if (disp->IsReady()) + disp->DrawHUD(vehicle, alpha); + + if(dirty) _weaponInfoAlpha = 100.0f; + } +} + +void InGameUI::DrawCompass(EntityAIFull *vehicle) +{ + //Texture *textureDef = GLOB_SCENE->Preloaded(TextureWhite); + Texture *texture; + MipInfo mip; + const int w = GEngine->Width2D(); + const int h = GEngine->Height2D(); + + Texture *corner = GLOB_SCENE->Preloaded(Corner); + GEngine->DrawFrame + ( + corner, + bgColor, + Rect2DPixel(coX * w, coY * h, coW * w, coH * h) + ); + + + Camera &cam = *GLOB_SCENE->GetCamera(); + Vector3Val dir = cam.Direction(); + + // avoid singularity when heading up + float xAngle; + if( fabs(dir.X())+fabs(dir.Z())>1e-3 ) + xAngle = atan2(dir.X(), dir.Z()); + else + xAngle=0; + xAngle *= 2 * INV_H_PI; + for (int i=-2; i<=2; i++) + { + float xLeft = xAngle + i; + int xBase = toIntFloor(xLeft); + if (xLeft - xBase >= 1.0) xBase++; + int xBaseMod4 = xBase&(4-1); + xLeft = xLeft + (xBaseMod4-xBase); + xBase = xBaseMod4; + PreloadedTexture seg[4]={Compass180,Compass270,Compass000,Compass090}; + texture = GLOB_SCENE->Preloaded(seg[xBase]); + float xOffset = xLeft - xBase; + mip = GEngine->TextBank()->UseMipmap(texture, 0, 0); + float xScreen = (coX + 0.5 * coW + 0.25 * coW * (i - xOffset)) * w; + GEngine->Draw2D(mip, compassColor, Rect2DPixel(xScreen, coY * h, 0.25 * coW * w, coH * h), Rect2DPixel(coX * w, coY * h, coW * w, coH * h), coShadow); + //GEngine->TextBank()->ReleaseMipmap(); + } + + Rect2DPixel compassClip(coX*w,0,coW*w,h); + float ySize=coH*h*0.25; + float xSize=ySize*w/h*(3.0/4); + float xPos=(coX+coW*0.5)*w; + PackedColor col=compassDirColor; + GEngine->DrawLine + ( + Line2DPixel(xPos,coY*h,xPos+xSize,coY*h-ySize), + col,col,compassClip + ); + GEngine->DrawLine + ( + Line2DPixel(xPos,coY*h,xPos-xSize,coY*h-ySize), + col,col,compassClip + ); + + WeaponModePtr ptr; + TurretContext context; + if (vehicle->GetPrimaryGunnerTurret(context)) ptr = context._weapons->ValidatedCurrentWeapon(); + if (ptr.IsValid()) + { + // draw turret direction + Vector3Val dir = vehicle->DirectionWorldToModel( + vehicle->GetWeaponDirection(vehicle->RenderVisualState(), context, ptr)); + + if( dir.SquareSizeXZ()>0.1 ) + { + xAngle = atan2(dir.X(), dir.Z()); + float xPos = (coX + 0.5 * coW + xAngle * coW * INV_W) * w; + PackedColor col=compassTurretDirColor; + GEngine->DrawLine + ( + Line2DPixel(xPos,coY*h,xPos+xSize,coY*h-ySize), + col,col,compassClip + ); + GEngine->DrawLine + ( + Line2DPixel(xPos,coY*h,xPos-xSize,coY*h-ySize), + col,col,compassClip + ); + } + } +} diff --git a/lib/UI/uiMap.cpp b/lib/UI/uiMap.cpp index 2f27ca34..a0574168 100644 --- a/lib/UI/uiMap.cpp +++ b/lib/UI/uiMap.cpp @@ -1,16300 +1,16300 @@ -// Implementation of main map display -#include "../wpch.hpp" -#include "uiMap.hpp" -//#include "win.h" -#include "../dikCodes.h" -#include "../person.hpp" -#include "../soldierOld.hpp" -#include "../diagModes.hpp" -#include - -#include "resincl.hpp" -#include "../keyInput.hpp" -#include "../vkCodes.h" - -#include "../landscape.hpp" -#include "../roads.hpp" - -#include "../camera.hpp" -#include "../detector.hpp" - -#include "../Shape/mapTypes.hpp" -#include "../gameStateExt.hpp" -#include "../paramArchiveExt.hpp" -#include "../fileLocator.hpp" -#include "../gameDirs.hpp" - -#include -#include - -#include -#include -#include - -#include - -#include - -#include - -#include "chat.hpp" - -#include "../txtPreload.hpp" -#include "../oggText.h" - -#include "../stringtableExt.hpp" -#include "../mbcs.hpp" - -#include -#include - -#include "../AI/aiRadio.hpp" - -#include "uiActions.hpp" - -#include "../keyInput.hpp" - -#include "../saveGame.hpp" - -#include "../progress.hpp" - -#include "displayUI.hpp" -#include "missionDirs.hpp" - -#include "../Network/network.hpp" - -#include "../timeManager.hpp" - -#include "uiViewport.hpp" -#include "menu.hpp" - -#include "../drawText.hpp" - -#include "mapProperties.hpp" -#include - -# ifdef NOMINMAX -# undef min -# undef max -# endif - -#if _PROFILE && USER_Ondra -#pragma optimize( "", off ) -#endif - -/*! -\file -Implementation file for particular displays (maps, briefing, debriefing, mission editor). -*/ - -// static const int daysInMonth[]={31,28,31,30,31,30,31,31,30,31,30,31}; -int GetDaysInMonth(int year, int month); - -extern const float CameraZoom; -extern const float InvCameraZoom; - -inline PackedColor ModAlpha( PackedColor color, float alpha ) -{ - int a=toIntFloor(alpha*color.A8()); - saturate(a,0,255); - return PackedColorRGB(color,a); -} - -static RString GetMagazinePicture(const MagazineType *type) -{ - RString name = type->GetPictureName(); - if (name[0] == '\\') - return name; - else - { - RString prefixM = "equip\\m\\m_"; - return prefixM + name + RString(".paa"); - } -} - -//LSError AbstractOptionsUI::Serialize(ParamArchive &ar) {return LSOK;} - -LSError AbstractOptionsUI::Serialize(ParamArchive &ar) -{ - return LSOK; -} - -/////////////////////////////////////////////////////////////////////////////// -// Map (generic static control) - -#define TO_INT(coef, arg) coef > 0 ? toIntFloor(arg) : toIntCeil(arg) - -static void AddChar(BString<32> &buffer, char c) -{ - int n = strlen(buffer); - if (n < 32 - 1) - { - buffer[n] = c; - buffer[n + 1] = 0; - } -} - -static int Modulo(int &i, int base) -{ - int d = i >= 0 ? i / base : (i - base + 1) / base; - int m = i - d * base; - i = d; - return m; -} - -void GridFormat(BString<32> &buffer, RString format, int i) -{ - const char *first = NULL; - for (const char *p=format; *p!=0; p++) - { - if (isalnum(*p)) - { - first = p; break; - } - } - if (!first) return; - BString<32> revert; - int cf = 0; - const char *p; - for (p=(const char *)format+format.GetLength()-1; p!=first; p--) - { - if (*p >= '0' && *p <= '9') - { - int m = Modulo(i, 10) + cf + *p - '0'; - int cf = m; - m = Modulo(cf, 10); - AddChar(revert, '0' + m); - } - else if (*p >= 'A' && *p <= 'J') - { - int m = Modulo(i, 10) + cf + *p - 'A'; - int cf = m; - m = Modulo(cf, 10); - AddChar(revert, 'A' + m); - } - else if (*p >= 'a' && *p <= 'j') - { - int m = Modulo(i, 10) + cf + *p - 'a'; - int cf = m; - m = Modulo(cf, 10); - AddChar(revert, 'a' + m); - } - else AddChar(revert, *p); - } - if (*p >= '0' && *p <= '9') - { - int m = Modulo(i, 10) + cf + *p - '0'; - int cf = m; - m = Modulo(cf, 10); - AddChar(revert, '0' + m); - } - else if (*p >= 'A' && *p <= 'Z') - { - int m = Modulo(i, 26) + cf + *p - 'A'; - int cf = m; - m = Modulo(cf, 26); - AddChar(revert, 'A' + m); - } - else if (*p >= 'a' && *p <= 'z') - { - int m = Modulo(i, 26) + cf + *p - 'a'; - int cf = m; - m = Modulo(cf, 26); - AddChar(revert, 'a' + m); - } - p--; - for (; p>=(const char *)format; p--) AddChar(revert, *p); - - for (const char *p=revert+strlen(revert)-1; p>=(const char *)revert; p--) AddChar(buffer, *p); -} - -static void AddChar(char *buffer, char c) -{ - int n = strlen(buffer); - buffer[n] = c; - buffer[n + 1] = 0; -} - -void PositionToAA11(Vector3Val pos, char *buffer) -{ - float sizeLand = LandGrid * LandRange; - *buffer = 0; - - if (!GWorld) return; - const GridInfo *info = GWorld->GetGridInfo(0); - if (!info) return; - - float offsetX = GWorld->GetGridOffsetX(); - float offsetY = GWorld->GetGridOffsetY(); - - - for (const char *p=info->format; *p!=0; p++) - { - if (*p == 'X' || *p == 'x') - { - float coefX = sizeLand * info->invStepX; - int x = TO_INT(coefX, (pos.X() - offsetX) * info->invStepX); - BString<32> buf; - GridFormat(buf, info->formatX, coefX >= 0 ? x : x - 1); - strcat(buffer, buf); - } - else if (*p == 'Y' || *p == 'y') - { - float coefY = sizeLand * info->invStepX; - int y = TO_INT(coefY, (sizeLand - pos.Z() - offsetY) * info->invStepY); - BString<32> buf; - GridFormat(buf, info->formatY, coefY >= 0 ? y : y - 1); - strcat(buffer, buf); - } - else AddChar(buffer, *p); - } -} - -void MapTypeInfo::Load(ParamEntryPar cls) -{ - icon = GlobLoadTexture - ( - GetPictureName(cls >> "icon") - ); - color = GetPackedColor(cls >> "color"); - size = cls >> "size"; - coefMin = cls >> "coefMin"; - coefMax = cls >> "coefMax"; - importance = cls >> "importance"; -} - -void MapTypeInfoTask::Load(ParamEntryPar cls) -{ - MapTypeInfo::Load(cls); - - iconCreated = GlobLoadTexture - ( - GetPictureName(cls >> "iconCreated") - ); - iconCanceled = GlobLoadTexture - ( - GetPictureName(cls >> "iconCanceled") - ); - iconDone = GlobLoadTexture - ( - GetPictureName(cls >> "iconDone") - ); - iconFailed = GlobLoadTexture - ( - GetPictureName(cls >> "iconFailed") - ); - - colorCreated = GetPackedColor(cls >> "colorCreated"); - colorCanceled = GetPackedColor(cls >> "colorCanceled"); - colorDone = GetPackedColor(cls >> "colorDone"); - colorFailed = GetPackedColor(cls >> "colorFailed"); -} - -void LegendInfo::Load(ParamEntryPar cls) -{ - _x = cls >> "x"; - _y = cls >> "y"; - _w = cls >> "w"; - _h = cls >> "h"; - - _font = GEngine->LoadFont(GetFontID(cls >> "font")); - _size = cls >> "sizeEx"; - - _colorBackground = GetPackedColor(cls >> "colorBackground"); - _color = GetPackedColor(cls >> "color"); -} - -MapProperties::MapProperties() -{ - _scaleMin = 0.001f; - _scaleMax = 1.0f; - _scaleDefault = 0.16f; - - _xMin = _zMin = -FLT_MAX; - _xMax = _zMax = FLT_MAX; -} - -void MapProperties::Load(ParamEntryPar cls) -{ - ParamEntryPtr entry = cls.FindEntry("scaleMin"); - if (entry) _scaleMin = *entry; - entry = cls.FindEntry("scaleMax"); - if (entry) _scaleMax = *entry; - entry = cls.FindEntry("scaleDefault"); - if (entry) _scaleDefault = *entry; - - entry = cls.FindEntry("xMin"); - if (entry) _xMin = *entry; - entry = cls.FindEntry("xMax"); - if (entry) _xMax = *entry; - entry = cls.FindEntry("zMin"); - if (entry) _zMin = *entry; - entry = cls.FindEntry("zMax"); - if (entry) _zMax = *entry; - - // visuals - - RString texName = cls >> "text"; - texName = FindPicture(texName); - if (texName.IsEmpty()) texName = "#(argb,8,8,3)color(1,1,1,1)"; - _texture = GlobLoadTextureUI(texName); - if (_texture && _texture->getDecoder() && !_texture->getDecoder()->isReady()) - { - _texture->getDecoder()->reinit(); - } - if (_texture) _texture->SetUsageType(Texture::TexUI); // no limits - - _ptsPerSquareSea = cls >> "ptsPerSquareSea"; // seas - _ptsPerSquareTxt = cls >> "ptsPerSquareTxt"; // textures - _ptsPerSquareCLn = cls >> "ptsPerSquareCLn"; // count-lines - _ptsPerSquareFor = cls >> "ptsPerSquareFor"; // forests - _ptsPerSquareForEdge = cls >> "ptsPerSquareForEdge"; // forest edges - _ptsPerSquareRoad = cls >> "ptsPerSquareRoad"; // roads - _ptsPerSquareObj = cls >> "ptsPerSquareObj"; // other objects - - _colorOutside = GetPackedColor(cls >> "colorOutside"); - - _colorSeaPacked = GetPackedColor(cls >> "colorSea"); - _colorSea = Color((ColorVal)_colorSeaPacked); - _colorForest = GetPackedColor(cls >> "colorForest"); - _colorRocks = GetPackedColor(cls >> "colorRocks"); - - _colorCountlines = GetPackedColor(cls >> "colorCountlines"); - _colorCountlinesWater = GetPackedColor(cls >> "colorCountlinesWater"); - _colorMainCountlines = GetPackedColor(cls >> "colorMainCountlines"); - _colorMainCountlinesWater = GetPackedColor(cls >> "colorMainCountlinesWater"); - _colorForestBorder = GetPackedColor(cls >> "colorForestBorder"); - _colorRocksBorder = GetPackedColor(cls >> "colorRocksBorder"); - _colorPowerLines = GetPackedColor(cls >> "colorPowerLines"); - _colorRailWay = GetPackedColor(cls >> "colorRailWay"); - _colorNames = GetPackedColor(cls >> "colorNames"); - _colorLevels = GetPackedColor(cls >> "colorLevels"); - - _colorTracks = GetPackedColor(cls >> "colorTracks"); - _colorRoads = GetPackedColor(cls >> "colorRoads"); - _colorMainRoads = GetPackedColor(cls >> "colorMainRoads"); - _colorTracksFill = GetPackedColor(cls >> "colorTracksFill"); - _colorRoadsFill = GetPackedColor(cls >> "colorRoadsFill"); - _colorMainRoadsFill = GetPackedColor(cls >> "colorMainRoadsFill"); - - _colorGrid = GetPackedColor(cls >> "colorGrid"); - _colorGridMap = GetPackedColor(cls >> "colorGridMap"); - - _fontNames = GLOB_ENGINE->LoadFont(GetFontID(cls>>"fontNames")); - _sizeNames = cls >> "sizeExNames"; - _fontLevels = GLOB_ENGINE->LoadFont(GetFontID(cls>>"fontLevel")); - _sizeLevels = cls >> "sizeExLevel"; - _fontGrid = GLOB_ENGINE->LoadFont(GetFontID(cls>>"fontGrid")); - _sizeGrid = cls >> "sizeExGrid"; - - if (cls.FindEntry("Legend")) - { - _legend.Load(cls >> "Legend"); - _showCountourInterval = cls >> "showCountourInterval"; - } - else _showCountourInterval = false; - - MAP_TYPES_ICONS_1(MAP_TYPE_INFO_LOAD) - MAP_TYPES_ICONS_2(MAP_TYPE_INFO_LOAD) -} - -bool MapProperties::DrawTerrainOutside() const -{ - // when area is limited, do not draw terrain outside - if (_xMin > 0) return false; - if (_zMin > 0) return false; - float mapSize = LandGrid * LandRange; - if (_xMax < mapSize) return false; - if (_zMax < mapSize) return false; - - return GLandscape->HasTerrainOutside(); -} - -CStatic *CreateStaticMap(ControlsContainer *parent, int idc, const ParamEntry &cls) -{ - CStaticMap *map = new CStaticMap(parent, idc, cls, cls >> "scaleMin", cls >> "scaleMax", cls >> "scaleDefault"); - map->SetVisibleRect(map->X(), map->Y(), map->W(), map->H()); - map->Center(); - return map; -} - -CStaticMap::CStaticMap - ( - ControlsContainer *parent, int idc, ParamEntryPar cls, - float scaleMin, float scaleMax, float scaleDefault - ) - : CStatic(parent, idc, cls) -{ - // defaults - _defaultProperties._scaleMin = scaleMin; - _defaultProperties._scaleMax = scaleMax; - _defaultProperties._scaleDefault = scaleDefault; - - // load defaults from resource - _defaultProperties.Load(cls); - - saturate(_defaultProperties._scaleDefault, _defaultProperties._scaleMin, _defaultProperties._scaleMax); - _scaleX = _defaultProperties._scaleDefault; - - InitDefaultCenter(); - - _legendDisabled = false; - - _ptsPerSquareCost = cls >> "ptsPerSquareCost"; // cost - - _maxSatelliteAlpha = cls >> "maxSatelliteAlpha"; - _alphaFadeStartScale = cls >> "alphaFadeStartScale"; - _alphaFadeEndScale = cls >> "alphaFadeEndScale"; - - //_widthRailWay = cls >> "widthRailWay"; - - _colorInactive = GetPackedColor(cls >> "colorInactive"); - - _fontLabel = GLOB_ENGINE->LoadFont(GetFontID(cls>>"fontLabel")); - _sizeLabel = cls >> "sizeExLabel"; - _fontInfo = GLOB_ENGINE->LoadFont(GetFontID(cls>>"fontInfo")); - _sizeInfo = cls >> "sizeExInfo"; - - _miniMapMode = false; - - // _moveOnEdges = cls>>"moveOnEdges"; -#if _VBS3 // markers moved to CStaticMap - _onlyDrawMarkers = cls.ReadValue("onlyDrawMarkers",false); - _drawAttachedMarkers = cls.ReadValue("drawAttachedMarkers",true); - _drawConditionalMarkers = cls.ReadValue("drawConditionalMarkers",true); -#endif - - EnableCtrl(true); - - _iconPlayer = GlobLoadTexture - ( - GetPictureName(cls >> "iconPlayer") - ); - _iconSelect = GlobLoadTexture - ( - GetPictureName(cls >> "iconSelect") - ); - _iconCamera = GlobLoadTexture - ( - GetPictureName(cls >> "iconCamera") - ); - _iconSensor = GlobLoadTexture - ( - GetPictureName(cls >> "iconSensor") - ); - _sizeUnit = cls >> "size"; - _sizePlayer = cls >> "sizePlayer"; - _colorFriendly = GetPackedColor(cls >> "colorFriendly"); - _colorEnemy = GetPackedColor(cls >> "colorEnemy"); - _colorCivilian = GetPackedColor(cls >> "colorCivilian"); - _colorNeutral = GetPackedColor(cls >> "colorNeutral"); - _colorUnknown = GetPackedColor(cls >> "colorUnknown"); - _colorMe = GetPackedColor(cls >> "colorMe"); - _shadow = cls >> "shadow"; - _blinkingSpeedMe = 0; - _colorMe2 = _colorMe; - ConstParamEntryPtr entry = cls.FindEntry("blinkingPeriodMe"); - if (entry) - { - float blinkingPeriod = *entry; - if (blinkingPeriod > 0) _blinkingSpeedMe = 1.0f / blinkingPeriod; - _colorMe2 = GetPackedColor(cls >> "colorMe2"); - } - - _colorPlayable = GetPackedColor(cls >> "colorPlayable"); - _colorSelect = GetPackedColor(cls >> "colorSelect"); - _colorSensor = GetPackedColor(cls >> "colorSensor"); - _colorDragging = GetPackedColor(cls >> "colorDragging"); - - _colorCamera = GetPackedColor(cls >> "colorCamera"); - _colorMissions = GetPackedColor(cls >> "colorMissions"); - _colorActiveMission = GetPackedColor(cls >> "colorActiveMission"); - - _colorPath = GetPackedColor(cls >> "colorPath"); - _colorPathDone = GetPackedColor(cls >> "colorPathDone"); - _texturePath = GlobLoadTexture(GetPictureName(cls >> "texturePath")); - _texturePathDone = GlobLoadTexture(GetPictureName(cls >> "texturePathDone")); - _sizePath = cls >> "sizePath"; - _sizePathDone = cls >> "sizePathDone"; - - _colorInfoMove = GetPackedColor(cls >> "colorInfoMove"); - _colorGroups = GetPackedColor(cls >> "colorGroups"); - _colorActiveGroup = GetPackedColor(cls >> "colorActiveGroup"); - _colorSync = GetPackedColor(cls >> "colorSync"); - _colorLabelBackground = GetPackedColor(cls >> "colorLabelBackground"); - - _cursorLineWidth = 0.5; - entry = cls.FindEntry("cursorLineWidth"); - if (entry) _cursorLineWidth = *entry; - - -#if _ENABLE_CHEATS - _show = true; - _showCost = false; -#endif - - _showIds = false; - _showScale = true; - _showScaleAlpha = 1; - - _moveKey = 0; - - Reset(); - Precalculate(_defaultProperties); - - SetVisibleRect(_x, _y, _w, _h); -} - -CStaticMap::~CStaticMap() -{ - _mapUsed.Free(); -} - -const MapProperties &CStaticMap::GetMapProperties() const -{ - if (GWorld) - { - const ItemMap *map = GWorld->GetMapItem(); - if (map) - { - const ItemMapType *type = map->Type(); - if (type) return type->GetMapProperties(); - } - } - return _defaultProperties; -} - -#if _VBS3 -Rect2DAbs CStaticMap::MapArea() -{ - float sizeLand = LandGrid * LandRange; - - // bottom left point - float xMap = (_x - _mapX - _x) * _scaleX * sizeLand; - float yMap = (1.0 - (_y + _h - _mapY - _y) * _scaleY) * sizeLand; - - // top right point - float wMap = (_x + _w - _mapX - _x) * _scaleX * sizeLand; - float hMap = (1.0 - (_y - _mapY - _y) * _scaleY) * sizeLand; - - return Rect2DAbs - ( - xMap, - yMap, - wMap - xMap, - hMap - yMap - ); -} -#endif - -void CStaticMap::SetScales(float scaleMin, float scaleMax, float scaleDefault) -{ - saturate(scaleDefault, scaleMin, scaleMax); - _defaultProperties._scaleMin = scaleMin; - _defaultProperties._scaleMax = scaleMax; - _defaultProperties._scaleDefault = scaleDefault; - SetScale(scaleDefault); - Precalculate(_defaultProperties); -} - -void CStaticMap::Reset() -{ - _moving = false; - ClearAnimation(); - _moveKey = 0; - _dragging = false; - _selecting = false; - _infoClick._type = signNone; - _infoClickCandidate._type = signNone; - _infoMove._type = signNone; - - // Center(); -} - -// colors conversion -// TODO: move to PackedColor class - -static PackedColor Mult2p00( PackedColor color ) -{ - DWORD val=color; - val&=0x7f7f7f7f; - val<<=1; - return PackedColor(val); -} - -static PackedColor Mult1p50( PackedColor color ) -{ - DWORD val=color; - val&=0xfefefefe; - val+=(val>>1); - return PackedColor(val); -} - -static PackedColor Mult0p75( PackedColor color ) -{ - DWORD val=color; - val&=0xfcfcfcfc; - val+=(val>>1); - return PackedColor(val>>1); -} - -PackedColor Mult(PackedColor col1, PackedColor col2) -{ - int a = ((col1.A8() + 1) * (col2.A8() + 1) - 1) >> 8; - int r = ((col1.R8() + 1) * (col2.R8() + 1) - 1) >> 8; - int g = ((col1.G8() + 1) * (col2.G8() + 1) - 1) >> 8; - int b = ((col1.B8() + 1) * (col2.B8() + 1) - 1) >> 8; - return PackedColor(r, g, b, a); -} - -PackedColor CStaticMap::InactiveColor(PackedColor color) -{ - return Mult(color, _colorInactive); -} - -// coordinates conversion - -DrawCoord CStaticMap::WorldToScreen(Vector3Val pt) const -{ - float invSizeLand = 1.0 / (LandGrid * LandRange); - float xMap = pt.X() * invSizeLand * _invScaleX; - float yMap = (1.0 - pt.Z() * invSizeLand) * _invScaleY; - return DrawCoord(xMap + _mapX + _x, yMap + _mapY + _y); -} - -DrawCoord CStaticMap::WorldSizeToScreen(Vector3Val pt) const -{ - float invSizeLand = 1.0 / (LandGrid * LandRange); - float xMapD = pt.X() * invSizeLand * _invScaleX; - float yMapD = - pt.Z() * invSizeLand * _invScaleY; - return DrawCoord(xMapD,yMapD); -} - -Point3 CStaticMap::ScreenToWorld(DrawCoord ptMap) const -{ - float sizeLand = LandGrid * LandRange; - float x = (ptMap.x - _mapX - _x) * _scaleX * sizeLand; - float y = (1.0 - (ptMap.y - _mapY - _y) * _scaleY) * sizeLand; - // !!! WARNING: result.Y() == 0 - return Point3(x, 0, y); -} - -// drawing -bool CStaticMap::DrawSign(const MapTypeInfo &info, Vector3Val pos) -{ - float coef = _invScaleX * 0.05; - saturate(coef, info.coefMin, info.coefMax); - float size = coef * info.size; - return DrawSign(info.icon, info.color, pos, size, size, 0, "", NULL , -1, info.shadow); -} - -#if _VBS2 // conditional markers -bool CStaticMap::DrawSignAutosize - ( - Texture *texture, PackedColor color, - Vector3Val pos, float w, float h, float azimut, RString text, bool shadow, - Font *font, float textSize, bool autosize - ) -{ - if (!autosize) - { - // correlates with new editor marker scaling - w = 1 / (_scaleX / (InvLandSize * 1000)) * w; - h = 1 / (_scaleX / (InvLandSize * 1000)) * h; - } - return DrawSign(texture, color, pos, w, h, azimut, text, shadow, font, textSize); -} -#endif - -bool CStaticMap::DrawSign - ( - Texture *texture, PackedColor color, - Vector3Val pos, float w, float h, float azimut, RString text, - Font *font, float textSize, int shadow - ) -{ - DrawCoord posMap = WorldToScreen(pos); - return DrawSign(texture, color, posMap, w, h, azimut, text, font, textSize,false, shadow); -} - -void CStaticMap::DrawLine(Vector3Val pos1, Vector3Val pos2, PackedColor color) -{ - DrawCoord posMap1 = WorldToScreen(pos1); - DrawCoord posMap2 = WorldToScreen(pos2); - return DrawLine(posMap1, posMap2, color); -} - -void CStaticMap::DrawLine(DrawCoord posMap1, DrawCoord posMap2, PackedColor color) -{ - GEngine->DrawLine(Line2DPixel(posMap1.x * _wScreen, posMap1.y * _hScreen, posMap2.x * _wScreen, posMap2.y * _hScreen), color, color, _clipRect); -} - -void CStaticMap::DrawArrow(Vector3Val pos1, Vector3Val pos2, PackedColor color) -{ - DrawCoord posMap1 = WorldToScreen(pos1); - DrawCoord posMap2 = WorldToScreen(pos2); - - posMap1.x *= _wScreen; - posMap1.y *= _hScreen; - posMap2.x *= _wScreen; - posMap2.y *= _hScreen; - - GEngine->DrawLine(Line2DPixel(posMap1.x, posMap1.y, posMap2.x, posMap2.y), color, color, _clipRect); - - float dx = posMap2.x - posMap1.x; - float dy = posMap2.y - posMap1.y; - float size2 = Square(dx) + Square(dy); - float invSize = InvSqrt(size2); - dx *= 12.0 * invSize; dy *= 12.0 * invSize; - float x = posMap2.x - dx + 0.5 * dy; - float y = posMap2.y - dy - 0.5 * dx; - GEngine->DrawLine - ( - Line2DPixel(posMap2.x, posMap2.y, x, y), - color, color, _clipRect - ); - - x = posMap2.x - dx - 0.5 * dy; - y = posMap2.y - dy + 0.5 * dx; - GEngine->DrawLine - ( - Line2DPixel(posMap2.x, posMap2.y, x, y), - color, color, _clipRect - ); -} - -bool CStaticMap::DrawSign - ( - Texture *texture, PackedColor color, - DrawCoord posMap, float ww, float hh, float azimut, RString text, - Font *font, float textSize, bool textSizeConstant, int shadow - ) -{ - // default arguments - const MapProperties &props = GetMapProperties(); - if (textSize < 0) textSize = props._sizeNames; - if (!font) font = props._fontNames; - - // normalize w, h - ww *= 1.0 / 640; - hh *= 1.0 / 480; - - float size = textSize; - if(!textSizeConstant) - { - size = textSize * (_invScaleX * 0.05); - saturate(size, 0.5 * textSize, 1.0 * textSize); - } - - float offsetX = 0.03 * size; - float offsetY = 0.04 * size; - PackedColor shadowColor = PackedBlack; - shadowColor.SetA8(toIntFloor(0.8 * color.A8())); - - // picture - if (texture) - { - if (azimut == 0) - { - // draw via Draw2D - - // center sign - posMap.x -= 0.5 * ww; - posMap.y -= 0.5 * hh; - - if (posMap.x + ww < _x) - return false; - if (posMap.y + hh < _y) - return false; - if (posMap.x > _x + _w) - return false; - if (posMap.y > _y + _h) - return false; - - float w = _wScreen; - float h = _hScreen; - - MipInfo mip = GEngine->TextBank()->UseMipmap(texture, 0, 0); - if (shadow == 1 ) GEngine->Draw2D( - mip, shadowColor, - Rect2DPixel(CX(posMap.x + offsetX), CY(posMap.y + offsetY), - CX(posMap.x+ww)-CX(posMap.x), CY(posMap.y+hh)-CY(posMap.y)), - _clipRect); - GEngine->Draw2D( - mip, color, - Rect2DPixel(CX(posMap.x), CY(posMap.y), - CX(posMap.x+ww)-CX(posMap.x), CY(posMap.y+hh)-CY(posMap.y)), - _clipRect,shadow); - - posMap.x += ww; - posMap.y += 0.5 * hh; - } - else - { - // draw via DrawPoly - float a = 0.5 * ww; - float b = 0.5 * hh; - - // TODO: improve clipping - float r = sqrt(Square(a) + Square(b)); - if (posMap.x + r < _x) - return false; - if (posMap.y + r < _y) - return false; - if (posMap.x - r > _x + _w) - return false; - if (posMap.y - r > _y + _h) - return false; - - float s = sin(azimut); - float c = cos(azimut); - float cx = posMap.x * _wScreen; - float cy = posMap.y * _hScreen; - a *= _wScreen; - b *= _hScreen; - - const int n = 4; - Vertex2DPixel vs[n]; - // 0 - vs[0].x = cx + c * a + s * b; - vs[0].y = cy + s * a - c * b; - vs[0].u = 1; - vs[0].v = 0; - // 1 - vs[1].x = cx + c * a + s * (-b); - vs[1].y = cy + s * a - c * (-b); - vs[1].u = 1; - vs[1].v = 1; - // 2 - vs[2].x = cx + c * (-a) + s * (-b); - vs[2].y = cy + s * (-a) - c * (-b); - vs[2].u = 0; - vs[2].v = 1; - // 3 - vs[3].x = cx + c * (-a) + s * b; - vs[3].y = cy + s * (-a) - c * b; - vs[3].u = 0; - vs[3].v = 0; - - MipInfo mip = GEngine->TextBank()->UseMipmap(texture, 0, 0); - - if (shadow == 1) - { - for (int i=0; i<4; i++) - { - vs[i].x += offsetX * _wScreen; - vs[i].y += offsetY * _hScreen; - vs[i].color = shadowColor; - } - GEngine->DrawPoly(mip, vs, n, _clipRect); - - for (int i=0; i<4; i++) - { - vs[i].x -= offsetX * _wScreen; - vs[i].y -= offsetY * _hScreen; - vs[i].color = color; - } - GEngine->DrawPoly(mip, vs, n, _clipRect); - } - else - { - for (int i=0; i<4; i++) - { - vs[i].color = color; - } - GEngine->DrawPoly(mip, vs, n, _clipRect); - } - - posMap.x += 0.5 * (fabs(c * ww) + fabs(s * hh)); - } - } - - // text - if (text.GetLength() > 0) - { - float hText = size; - - float top = posMap.y - 0.5 * hText; - //float width = GEngine->GetTextWidth(size, font, text); - - if (shadow == 1) GEngine->DrawText - ( - Point2DFloat(posMap.x + offsetX, top + offsetY), size, - Rect2DFloat(_x, _y, _w, _h), - font, shadowColor, text, 0 - ); - - GEngine->DrawText - ( - Point2DFloat(posMap.x, top), size, - Rect2DFloat(_x, _y, _w, _h), - font, color, text, shadow - ); - } - - return true; -} - -void CStaticMap::DrawLabel(Vector3Par pos, RString text, PackedColor color, int shadow) -{ - DrawCoord posMap = WorldToScreen(pos); - - // place label - float w = GLOB_ENGINE->GetTextWidth(_sizeLabel, _fontLabel, text); - float h = _sizeLabel; - posMap.x -= 0.5 * w; - posMap.y -= 0.01 + h; - - MipInfo mip = GLOB_ENGINE->TextBank()->UseMipmap(NULL, 0, 0); - GLOB_ENGINE->Draw2D - ( - mip, _colorLabelBackground, - Rect2DPixel(posMap.x * _wScreen, posMap.y * _hScreen, - w * _wScreen, h * _hScreen), - _clipRect - ); - - GLOB_ENGINE->DrawText - ( - posMap, _sizeLabel, - Rect2DFloat(_x, _y, _w, _h), - _fontLabel, color, text, shadow - ); -} - -struct DetectCircle -{ - int _x; - int _z; - int _radius; - - DetectCircle(int x, int z, int radius) - :_x(x),_z(z),_radius(radius) - { - } - - //! check if we overlapp with given rectangle - bool operator () (int x, int z, int size) const - { - // calculate distance of rectangle center from our center - int centerX = x+(size>>1); - int centerZ = z+(size>>1); - - float dist2 = Square(centerX-_x) + Square(centerZ-_z); - // check if we can quickly reject or quickly accept - if (dist2Square(_radius+size)*2) - { - // circle is certianly of of the rectangle - return false; - } - // circle may or may not be in the rectangle - // we can perform stricter check, or we can return true and provide - // some superfluous items - return true; - } -}; - -#if USE_LANDSCAPE_LOCATIONS - -//! enumerate all locations we are interested in -struct LocationsRegion -{ - // in - float _xMin,_xMax; - float _zMin,_zMax; - - bool operator () (int x, int y, int size) const - { - float xMin = x, xMax = x+size; - float zMin = y, zMax = y+size; - bool ret = true; - if (_xMin>xMax) ret = false; - if (_xMaxzMax) ret = false; - if (_zMax,200 > > _locations; -}; - -struct LocationsList -{ - // out - LocationsListResult *_result; - - LocationsList(LocationsListResult *result) - : _result(result) - { - } - - bool operator () (const Ref &item) const - { - for (int i=0; i_locations.Size(); i++) - { - Location *location = item->_locations[i]; - int style = location->_type->_drawStyle; - _result[style]._locations.Add(location); - } - return false; - } -}; - -/* -struct SkipNear -{ -const Location *_location; -float _minDist2; -LocationDrawStyle _style; - -SkipNear(const Location *location, float minDist) -: _location(location), -_minDist2(Square(minDist)) -{ -_style = _location->_type->_drawStyle; -} - -bool operator () (const Ref &item) const -{ -for (int i=0; i_locations.Size(); i++) -{ -const Location *tested = item->_locations[i]; -if (tested == _location) continue; -if (tested->_type->_drawStyle != _style) continue; -// check if the location is more important -if (tested->_importance < _location->_importance) continue; -if (tested->_importance == _location->_importance) -{ -// select random (but deterministically) as more important -if ( -GLandscape->GetRandomValueForCoord(toInt(tested->_position.X()), toInt(tested->_position.Z())) <= -GLandscape->GetRandomValueForCoord(toInt(_location->_position.X()), toInt(_location->_position.Z())) -) -continue; -} -// check if the location is near enough -if (tested->_position.DistanceXZ2(_location->_position) < _minDist2) return true; -} -return false; -} -}; -*/ - -#else - -//! container which makes quick space queries possible -#include - -struct MountainInfo: public Vector3 -{ - int _index; - bool operator == (const MountainInfo &with) const - { - return _index==with._index; - } - MountainInfo() - { - _index = -1; - } - MountainInfo(Vector3Par pos, int index) - :Vector3(pos),_index(index) - { - } - - int GetX() const {return toLargeInt(X());} - int GetY() const {return toLargeInt(Z());} -}; - -TypeIsMovable(MountainInfo) - -struct SkipNear -{ - MountainInfo _pos; - //bool _skipped; - float _minDist; - SkipNear(MountainInfo pos, float minDist) - :_pos(pos), - _minDist(minDist) - { - } - bool operator () (const MountainInfo &arg) const - { - // check if the mountain is near enough - // check if the mountain is higher - if (arg._index>=_pos._index) return false; - float dist2 = _pos.DistanceXZ2(arg); - return dist2xMax) ret = false; - if (_xMaxzMax) ret = false; - if (_zMax _indices; - - bool operator () (const MountainInfo &pos) - { - _indices.Add(pos._index); - return false; - } -}; -#endif - -struct CStaticMap::DrawForestContext -{ - float xMin,yMin; - float xStep,yStep; - int iMin,jMin; - - const MapProperties &props; - - DrawForestContext(const MapProperties &p) : props(p) {} -}; - -/** -Forest drawing functor -Same code is used for edge and area rendering -*/ -struct CStaticMap::DrawForestsNewFunc -{ - const CStaticMap::DrawForestContext &_ctx; - CStaticMap *_map; - bool _drawLines; - bool _rocks; - - DrawForestsNewFunc(const CStaticMap::DrawForestContext &ctx, CStaticMap *map, bool drawLines, bool rocks) - :_ctx(ctx),_map(map),_drawLines(drawLines), _rocks(rocks) - {} - - void operator () (const MapObjectList &list, int x, int z, int xSize, int zSize) const - { - _map->DrawForestsNew(list, x, z, _ctx, _drawLines, _rocks); - } -}; - -struct CStaticMap::DrawRoadContext -{ - mutable LineArray _lines; - CStaticMap *_map; - const MapProperties &_props; - - DrawRoadContext(CStaticMap *map, const MapProperties &props) : _map(map), _props(props) {} - - void operator () (const MapObjectList &list, int x, int z, int xSize, int zSize) const - { - _map->DrawRoads(_props, _lines, list, x, z); - } -}; - - -struct CStaticMap::DrawObjectsContext -{ - mutable LineArray _lines; - CStaticMap *_map; - const MapProperties &_props; - - DrawObjectsContext(CStaticMap *map, const MapProperties &props) : _map(map), _props(props) {} - - void operator () (const MapObjectList &list, int x, int z, int xSize, int zSize) const - { - _map->DrawObjects(_props, list, x, z); - } -}; - -template -void ForRectangleMapObjects(int xBeg, int zBeg, int xEnd, int zEnd, const Func &f) -{ - if (xBeg<0) xBeg=0; if (xEnd>LandRangeMask) xEnd=LandRangeMask; - if (zBeg<0) zBeg=0; if (zEnd>LandRangeMask) zEnd=LandRangeMask; - DetectInRectangle rect(xBeg,zBeg,xEnd,zEnd); - GLandscape->ForSomeMapObjects(rect,f); - // // slow and robust - usefull for ForSomeMapObjects verification - // for (int x=xBeg; xGetMapObjects(x,z); - // f(list,x,z,1,1); - // } -} - -/// draw autopilot taxi guides -void CStaticMap::DrawTaxiGuide(const MapProperties &props, const AutoArray &guide) -{ - for (int i=1; iDrawLine(line, props._colorRoads, props._colorRoads, _clipRect); - } -} - -void CStaticMap::DrawRunway(const MapProperties &props, const Vector3 *runway) -{ - // if runway is invalid, do not draw it - if (runway[0].DistanceXZ2(runway[1])DrawLinePrepare(); - GEngine->DrawLineDo(left, props._colorRoads, props._colorRoads, _clipRect); - GEngine->DrawLineDo(right, props._colorRoads, props._colorRoads, _clipRect); - GEngine->DrawLineDo(top, props._colorRoads, props._colorRoads, _clipRect); - GEngine->DrawLineDo(bottom, props._colorRoads, props._colorRoads, _clipRect); -} - -void CStaticMap::DrawAirports(const MapProperties &props) -{ - // check ILS and taxiing information and draw runway based on it - - for (int i=0; iGetAirportCount(); i++) - { - Vector3 runway[4],taxiway[4]; - GWorld->GetAirportRunwayRect(i,runway,taxiway); - DrawRunway(props, runway); - DrawRunway(props, taxiway); - -#if _ENABLE_CHEATS - DrawTaxiGuide(props, GWorld->GetTaxiInPath(TWest,runway[0],VZero)); - DrawTaxiGuide(props, GWorld->GetTaxiOffPath(TWest,runway[0],VZero)); -#endif - } - -} - - -void CStaticMap::DrawBackground(const MapProperties &props) -{ - PROFILE_SCOPE(mapDr); - float ptsLand = 800.0 * _invScaleX * InvLandRange; // avoid dependece on video resolution - float invPtsLand = 1.0 / ptsLand; - - float invTerrainRange = 1.0 / TerrainRange; - float ptsTerrain = 800.0 * _invScaleX * invTerrainRange; // avoid dependece on video resolution - float invPtsTerrain = 1.0 / ptsTerrain; - - //GEngine->ShowMessage(1000, "Scale = %.4f, PtsPerFld = %.2f", _scaleX, ptsLand); - - // calculate range of coordinates for the landscape - float xMinBorder = _x + _mapX + _minX; - float xMaxBorder = _x + _mapX + _maxX; - float yMinBorder = _y + _mapY + _minY; - float yMaxBorder = _y + _mapY + _maxY; - -#if _ENABLE_CHEATS - if (CHECK_DIAG(DEMapScale)) DIAG_MESSAGE(100, Format("Map scale: %.4f, ptsLand: %.1f", _scaleX, ptsLand)); -#endif - - const bool skipOutside = !props.DrawTerrainOutside(); - - if (props._texture) - { - // draw paper - MipInfo mip = GLOB_ENGINE->TextBank()->UseMipmap(props._texture, 0, 0); - - float xStep = (1.0 / 2.0) * _invScaleX; - float yStep = (1.0 / 2.0) * _invScaleY; - float xMin = _x - fastFmod(-_mapX, xStep); - float yMin = _y - fastFmod(-_mapY, yStep); - - for (float y=yMin; y<_y+_h; y+=yStep) - for (float x=xMin; x<_x+_w; x+=xStep) - { - if (skipOutside) - { - if (x <= xMinBorder - xStep) continue; - if (x > xMaxBorder) continue; - if (y <= yMinBorder - yStep) continue; - if (y > yMaxBorder) continue; - } - GEngine->Draw2D( - mip, _bgColor, - Rect2DPixel(x * _wScreen, y * _hScreen, xStep * _wScreen, yStep * _hScreen), - _clipRect - ); - } - } - - //#if _ENABLE_CHEATS - if ((!_showScale || UserMapDrawing()) && _scaleX < _alphaFadeEndScale) - { - // draw fields (textures) - int iStep = toIntCeil(props._ptsPerSquareTxt * invPtsLand); - if (iStep>1) - { - // once we start stepping, step over whole segments - int zAlign; - int satSeg = GLandscape->GetSatSegSize(zAlign); - if (iStep 8 ) _mipmapLevel = 8; - - float y = yMin; - float j = jMin; - while (y <= _y + _h) - { - float x = xMin; - int i = iMin; - while (x <= _x + _w) - { - if (!skipOutside || (i > -iStep && i < LandRange + iStep && j > -jStep && j < LandRange + jStep)) - DrawField(x, y, xStep, yStep, i, (int)j, iStep, -jStep); - i += iStep; - x += xStep; - } - j -= jStep; - y += yStep; - } - } - // #endif - - if (!UserMapIsBeingDrawn()) - { - // draw sea - int iStep = toIntCeil(props._ptsPerSquareSea * invPtsLand); - float xStep = iStep * InvLandRange * _invScaleX; - int jStep = iStep; - float yStep = jStep * InvLandRange * _invScaleY; - - // Fix: in the implementation using fastFmod, xMin and iMin did not match sometimes - int steps = toIntFloor(-_mapX / xStep); - float xMin = _x + _mapX + steps * xStep; // _x - (-_mapX mod xStep) - int iMin = steps * iStep; - - steps = toIntFloor(-_mapY / yStep); - float yMin = _y + _mapY + steps * yStep; - int jMin = LandRange - steps * jStep; - - float y = yMin; - int j = jMin; - while (y <= _y + _h) - { - float x = xMin; - int i = iMin; - while (x <= _x + _w) - { - if (!skipOutside || (i > -iStep && i < LandRange + iStep && j > -jStep && j < LandRange + jStep)) - DrawSea(props, x, y, xStep, yStep, i, j, iStep, -jStep); - i += iStep; - x += xStep; - } - j -= jStep; - y += yStep; - } - } - - -#if _ENABLE_CHEATS - if (_show) -#endif - { -#if _VBS3 - if(GVBSVisuals.GetShowContours()) -#endif - // draw count-lines - if (!UserMapIsBeingDrawn()) - { - LineArray lines; - //PROFILE_SCOPE(mpCnt); - int iStep = toIntCeil(props._ptsPerSquareCLn * invPtsTerrain); - float xStep = iStep * invTerrainRange * _invScaleX; - int jStep = iStep; - float yStep = jStep * invTerrainRange * _invScaleY; - - // Fix: in the implementation using fastFmod, xMin and iMin did not match sometimes - int steps = toIntFloor(-_mapX / xStep); - float xMin = _x + _mapX + steps * xStep; // _x - (-_mapX mod xStep) - int iMin = steps * iStep; - - steps = toIntFloor(-_mapY / yStep); - float yMin = _y + _mapY + steps * yStep; - int jMin = TerrainRange - steps * jStep; - - float step = 70.0 * _scaleX; - int stepexp = toIntFloor(log10(step)); - float step10 = pow(10.0, stepexp); - step /= step10; - if (step <= 2.0) step = 2.0; - else if (step <= 5.0) step = 5.0; - else step = 10.0; - step *= step10; - saturateMax(step, 1); - - float maxLevel = step * toIntCeil(10000.0 / step); - - float y = yMin; - int j = jMin; - while (y <= _y + _h) - { - float x = xMin; - int i = iMin; - while (x <= _x + _w) - { - if (!skipOutside || (i > -iStep && i < TerrainRange + iStep && j > -jStep && j < TerrainRange + jStep)) - DrawCountlines(props, lines, x, y, xStep, yStep, i, j, iStep, -jStep, step, 5*step, maxLevel); - i += iStep; - x += xStep; - } - j -= jStep; - y += yStep; - } - GEngine->DrawLines(lines.Data(),lines.Size(),_clipRect); - } - - { - //PROFILE_SCOPE(mpObj); - float xStep = InvLandRange * _invScaleX; - float yStep = InvLandRange * _invScaleY; - - int iMin = toIntFloor(-_mapX / xStep); - int jMin = LandRange - toIntFloor(-_mapY / yStep); - - // make sure viewed region is fully loaded - if (!_mapUsed) - { - _mapUsed = new MapObjectListRectUsed; - } - // calculate object area - int xBeg = iMin; - int xEnd = xBeg + toIntCeil((_w + fastFmod(-_mapX, xStep))/xStep); - - int zEnd = jMin; - int zBeg = zEnd - toIntCeil((_h + fastFmod(-_mapY, yStep))/yStep); - - // extend because the objects from neighbor fields can interfere with - xBeg--; xEnd++; zBeg--; zEnd++; - - // saturate borders - if (xBeg<0) xBeg = 0; - if (xEnd>LandRangeMask) xEnd = LandRangeMask; - if (zBeg<0) zBeg = 0; - if (zEnd>LandRangeMask) zEnd = LandRangeMask; - - float minPtsPerSquare = floatMin(props._ptsPerSquareFor, props._ptsPerSquareRoad, props._ptsPerSquareObj); - - int xBegXXL=xBeg, zBegXXL=zBeg, xEndXXL=xEnd, zEndXXL=zEnd; - ObjMapRadiusRectangle(xBegXXL, xEndXXL, zBegXXL, zEndXXL); - if (ptsLand>=minPtsPerSquare) - { - // when no objects are needed at all, do not load them - GLandscape->UseMapObjects(*_mapUsed,xBegXXL,zBegXXL,xEndXXL,zEndXXL); - } - - if (ptsLand>=minPtsPerSquare*0.8f) - { - // when no objects are needed at all even with some zoom, do not preload them - PROFILE_SCOPE(mapPM) - - // border should be based on the map size - // 5 % on each side sounds reasonable - int border=toIntCeil((zEndXXL-zBegXXL)*0.05)+1; - // preload some border around - GLandscape->PreloadMapObjects(*_mapUsed,xBegXXL-border,zBegXXL-border,xEndXXL+border,zEndXXL+border); - } - - // draw objects - if (ptsLand >= props._ptsPerSquareFor && !UserMapIsBeingDrawn()) - { - PROFILE_SCOPE(mapFo) - // forests - DrawForestContext ctx(props); - - float invPtsLand = (1.0/800.0) * _scaleX * LandRange; // avoid dependence on video resolution - - int iStep = toIntCeil(props._ptsPerSquareFor * invPtsLand); - int jStep = iStep; - - ctx.xStep = iStep * InvLandRange * _invScaleX; - ctx.yStep = jStep * InvLandRange * _invScaleY; - - // Fix: in the implementation using fastFmod, xMin and iMin did not match sometimes - int steps = toIntFloor(-_mapX / xStep); - ctx.xMin = _x + _mapX + steps * xStep; // _x - (-_mapX mod xStep) - ctx.iMin = steps * iStep; - - steps = toIntFloor(-_mapY / yStep); - ctx.yMin = _y + _mapY + steps * yStep; - ctx.jMin = LandRangeMask - steps * jStep; - - if (GLandscape->GetMinTreesInForestSquare() > 0) - { - ForRectangleMapObjects(xBeg,zBeg,xEnd,zEnd,DrawForestsNewFunc(ctx,this,false,false)); - if (ptsLand >= props._ptsPerSquareForEdge) - { - // shared state preparation - GEngine->DrawLinePrepare(); - ForRectangleMapObjects(xBeg,zBeg,xEnd,zEnd,DrawForestsNewFunc(ctx,this,true,false)); - } - } - else - { - // old style (OFP) forests no longer supported - } - - // rocky areas - if (GLandscape->GetMinRocksInRockSquare() > 0) - { - ForRectangleMapObjects(xBeg,zBeg,xEnd,zEnd,DrawForestsNewFunc(ctx,this,false,true)); - if (ptsLand >= props._ptsPerSquareForEdge) - { - // shared state preparation - GEngine->DrawLinePrepare(); - ForRectangleMapObjects(xBeg,zBeg,xEnd,zEnd,DrawForestsNewFunc(ctx,this,true,true)); - } - } - } - if (!UserMapIsBeingDrawn() || UserMapDrawObjects()) - { - - if (ptsLand >= props._ptsPerSquareRoad) - { - PROFILE_SCOPE(mapRd) - DrawRoadContext ctx(this, props); - ForRectangleMapObjects(xBeg,zBeg,xEnd,zEnd,ctx); - //GLandscape->_mapObjects->ForSomeItem(ctx); - //_mapObj - GEngine->DrawLines(ctx._lines.Data(),ctx._lines.Size(),_clipRect); - } - if (ptsLand >= props._ptsPerSquareObj) - { - PROFILE_SCOPE(mapOb) - DrawObjectsContext ctx(this, props); - ForRectangleMapObjects(xBegXXL,zBegXXL,xEndXXL,zEndXXL,ctx); - } - } -#if 0 //_DEBUG - _mapUsed.Free(); - // make sure no part of map is locked now - it may be cached - for (int z=0; zGetMapObjects(x,z).GetList(); - if (list) - { - int cachedCount = list->IsInList(); - Assert(list->GetUseCount()==cachedCount); - } - } -#endif - } - if (!UserMapIsBeingDrawn() || UserMapDrawObjects()) - { - DrawAirports(props); - } - - } - - if (!UserMapIsBeingDrawn()) - { - -#if USE_LANDSCAPE_LOCATIONS - const Locations &locations = GLandscape->GetLocations(); - - LocationsRegion region; - Vector3 minPos = ScreenToWorld(Point2DFloat(_x, _y)); - Vector3 maxPos = ScreenToWorld(Point2DFloat(_x + _w,_y + _h)); - region._xMin = floatMin(minPos.X(), maxPos.X()); - region._zMin = floatMin(minPos.Z(), maxPos.Z()); - region._xMax = floatMax(minPos.X(), maxPos.X()); - region._zMax = floatMax(minPos.Z(), maxPos.Z()); - - LocationsListResult lists[NLocationDrawStyle]; - { - PROFILE_SCOPE_EX(locL,*); - locations.ForEachInRegion(region, LocationsList(lists)); - } - - // TODO: define density in CfgLocationTypes - const float density = 0.08; - const float elevationOffset = GLandscape->GetLandElevationOffset(); - float sizeLand = LandGrid * LandRange; - float minDistF = density * sizeLand * _scaleX; - { - PROFILE_SCOPE_EX(locD,*); - for (int style = 0; style_nearestMoreImportant >= minDistF) - location->Draw(this,false,elevationOffset); - /* - // make space based query - int x = toLargeInt(location->GetX()); - int z = toLargeInt(location->GetY()); - - if (!locations.ForEachInRegion(DetectCircle(x, z, minDist), SkipNear(location, minDistF))) - { - location->Draw(this); - } - */ - } - } - } - -#else - // names - ParamEntryVal world = Pars >> "CfgWorlds" >> Glob.header.worldname; - ConstParamEntryPtr cls = world.FindEntry("Names"); - if (cls) - { - //PROFILE_SCOPE(mpPts); - AUTO_STATIC_ARRAY(Vector3, points, 32); - float minDist2 = Square(1000 * _scaleX); - int n = cls->GetEntryCount(); - points.Resize(n); - for (int i=0; iGetEntry(i); - Vector3 pos; - pos.Init(); - pos[0] = (item >> "position")[0]; - pos[2] = (item >> "position")[1]; - pos[1] = 0; - points[i] = pos; - bool skip = false; - for (int j=0; j expected"); - } - - // mountains - { - //PROFILE_SCOPE(mpMts); -#if 1 - - QuadTreeCont mountainPos; - const AutoArray &mountains = GLandscape->GetMountains(); - - { - PROFILE_SCOPE_EX(locC,*); - for (int i=0; iTextBank()->UseMipmap(NULL, 0, 0); - float xLeft = _x; - if (xMinBorder > xLeft) - { - GEngine->Draw2D( - mip, props._colorOutside, - Rect2DPixel(xLeft * _wScreen, _y * _hScreen, (xMinBorder - xLeft) * _wScreen, _h * _hScreen), - _clipRect - ); - xLeft = xMinBorder; - } - float xRight = _x + _w; - if (xMaxBorder < xRight) - { - GEngine->Draw2D( - mip, props._colorOutside, - Rect2DPixel(xMaxBorder * _wScreen, _y * _hScreen, (xRight - xMaxBorder) * _wScreen, _h * _hScreen), - _clipRect - ); - xRight = xMaxBorder; - } - if (yMinBorder > _y) - { - GEngine->Draw2D( - mip, props._colorOutside, - Rect2DPixel(xLeft * _wScreen, _y * _hScreen, (xRight - xLeft) * _wScreen, (yMinBorder - _y) * _hScreen), - _clipRect - ); - } - if (yMinBorder < _y + _h) - { - GEngine->Draw2D( - mip, props._colorOutside, - Rect2DPixel(xLeft * _wScreen, yMaxBorder * _hScreen, (xRight - xLeft) * _wScreen, (_y + _h - yMinBorder) * _hScreen), - _clipRect - ); - } - } -} - -void CStaticMap::PreloadData(Vector3Par center) -{ - // calculate a new rectangle - float xStep = InvLandRange * _invScaleX; - float yStep = InvLandRange * _invScaleY; - float invXStep = LandRange * _scaleX; - float invYStep = LandRange * _scaleY; - - int iMin = toIntFloor(-_mapX * invXStep); - int jMin = LandRange - toIntFloor(-_mapY * invYStep); - - // make sure viewed region is fully loaded - if (!_mapUsed) - { - _mapUsed = new MapObjectListRectUsed; - } - // calculate object area - int xBeg = iMin; - int xEnd = xBeg + toIntCeil((_w + fastFmod(-_mapX, xStep))*invXStep); - - int zEnd = jMin; - int zBeg = zEnd - toIntCeil((_h + fastFmod(-_mapY, yStep))*invYStep); - - // saturate borders - if (xBeg<0) xBeg = 0; - if (xEnd>LandRangeMask) xEnd = LandRangeMask; - if (zBeg<0) zBeg = 0; - if (zEnd>LandRangeMask) zEnd = LandRangeMask; - - if (_mapUsed) - { - GLandscape->PreloadMapObjects(*_mapUsed, xBeg, zBeg, xEnd, zEnd); - } -} - -/*! -\patch_internal 1.45 Date 2/21/2002 by Jirka -- Fixed: Added legend to map -\patch 5126 Date 2/2/2007 by Jirka -- New: Map legend parameters are now read from the resource -*/ - -void CStaticMap::DrawLegend() -{ - const MapProperties &props = GetMapProperties(); - if (_legendDisabled || !props._showCountourInterval) return; - - float w = _wScreen; - float h = _hScreen; - - float cx = CX(props._legend._x), cy = CY(props._legend._y), cw = CW(props._legend._w), ch = CH(props._legend._h); - - Draw2DPars pars; - pars.mip = GEngine->TextBank()->UseMipmap(NULL, 0, 0); - pars.spec = NoZBuf|IsAlpha|ClampU|ClampV|IsAlphaFog; - pars.SetColor(props._legend._colorBackground); - pars.SetU(0,1); - pars.SetV(0,1); - Rect2DPixel rect(cx, cy, cw, ch); - GEngine->Draw2D(pars, rect, _clipRect); - - PackedColor color = props._legend._color; - GEngine->DrawLine(Line2DPixel(cx, cy, cx + cw, cy), color, color, _clipRect); - GEngine->DrawLine(Line2DPixel(cx + cw, cy, cx + cw, cy + ch), color, color, _clipRect); - GEngine->DrawLine(Line2DPixel(cx + cw, cy + ch, cx, cy + ch), color, color, _clipRect); - GEngine->DrawLine(Line2DPixel(cx, cy + ch, cx, cy), color, color, _clipRect); - - float top = props._legend._y + 0.01; - float left = props._legend._x + 0.01; - - float step = 70.0 * _scaleX; - int stepexp = toIntFloor(log10(step)); - float step10 = pow(10.0, stepexp); - step /= step10; - if (step <= 2.0) step = 2.0; - else if (step <= 5.0) step = 5.0; - else step = 10.0; - step *= step10; - saturateMax(step, 1); - - GEngine->DrawTextF - ( - Point2DFloat(left, top), props._legend._size, - Rect2DFloat(_x, _y, _w, _h), - props._legend._font, color, 0, LocalizeString(IDS_MAP_INTERVAL), step - ); - top += props._legend._size; - GEngine->DrawText - ( - Point2DFloat(left, top), props._legend._size, - Rect2DFloat(_x, _y, _w, _h), - props._legend._font, color, LocalizeString(IDS_MAP_LEGEND_INFO),0 - ); - top += 1.5 * props._legend._size; - - // how much space is for scale picture - float scaleSpace = props._legend._w - 5.0f * props._legend._size; - step = LandGrid * LandRange * _scaleX * scaleSpace; - // round to the 1, 2, 5, 10, ... - stepexp = toIntFloor(log10(step)); - step10 = pow(10.0, stepexp); - step /= step10; - if (step >= 5) step = 5; - else if (step >= 2) step = 2; - else step = 1; - step *= step10; - - float mapStep = InvLandGrid * InvLandRange * _invScaleX * step; - - GEngine->DrawLine(Line2DPixel(CX(left), CY(top), CX(left), CY(top + props._legend._size)), color, color, _clipRect); - GEngine->DrawLine(Line2DPixel(CX(left + mapStep), CY(top), CX(left + mapStep), CY(top + props._legend._size)), color, color, _clipRect); - GEngine->DrawLine(Line2DPixel(CX(left), CY(top + 0.5 * props._legend._size), CX(left + mapStep), CY(top + 0.5 * props._legend._size)), color, color, _clipRect); - GEngine->DrawTextF - ( - Point2DFloat(left + mapStep + 0.01, top), props._legend._size, - Rect2DFloat(_x, _y, _w, _h), - props._legend._font, color, 0, LocalizeString(IDS_MAP_SCALE_FORMAT), step - ); -} - -void CStaticMap::DrawName(Vector3Par pos, RString text, Font *font, float textSize, PackedColor color, int shadow) -{ - DrawCoord pt = WorldToScreen(pos); - - float size = textSize * (_invScaleX * 0.05); - saturate(size, 0.5 * textSize, 2.0 * textSize); - - float h = size; - float w = GEngine->GetTextWidth(size, font, text); - - if (pt.x + w < _x) return; - if (pt.y + 0.5 * h < _y) return; - if (pt.x > _x + _w) return; - if (pt.y - 0.5 * h > _y + _h) return; - - GEngine->DrawText - ( - Point2DFloat(pt.x, pt.y - 0.5 * h), - size, - Rect2DFloat(_x, _y, _w, _h), - font, - color, - text, - shadow - ); -} - -void CStaticMap::DrawName(ParamEntryPar cls) -{ - const MapProperties &props = GetMapProperties(); - - Vector3 pos; - pos.Init(); - pos[0] = (cls >> "position")[0]; - pos[2] = (cls >> "position")[1]; - pos[1] = 0; - RString text = cls >> "name"; - DrawName(pos, text, props._fontNames, props._sizeNames, props._colorNames, 0); -} - -void CStaticMap::DrawMount(Vector3Par pos) -{ - const MapProperties &props = GetMapProperties(); - - DrawCoord pt = WorldToScreen(pos); - - char buffer[256]; - sprintf(buffer, "%.0f", pos.Y()); - - float h = props._sizeLevels; - float w = GEngine->GetTextWidth(props._sizeLevels, props._fontLevels, buffer); - - if (pt.x + w + 0.005 < _x) return; - if (pt.y + 0.5 * h < _y) return; - if (pt.x > _x + _w) return; - if (pt.y - 0.5 * h > _y + _h) return; - - int x = toIntFloor(pt.x * _wScreen); - int y = toInt(pt.y * _hScreen); - GEngine->DrawLine(Line2DPixel(x, y - 1, x + 1, y - 1), props._colorCountlines, props._colorCountlines, _clipRect); - GEngine->DrawLine(Line2DPixel(x + 1, y - 1, x + 1, y + 1), props._colorCountlines, props._colorCountlines, _clipRect); - GEngine->DrawLine(Line2DPixel(x + 1, y + 1, x, y + 1), props._colorCountlines, props._colorCountlines, _clipRect); - GEngine->DrawLine(Line2DPixel(x, y + 1, x, y - 1), props._colorCountlines, props._colorCountlines, _clipRect); - GEngine->DrawText - ( - Point2DFloat(pt.x + 0.005, pt.y - 0.5 * h), - props._sizeLevels, - Rect2DFloat(_x, _y, _w, _h), - props._fontLevels, - props._colorLevels, - buffer, 0 - ); -} - -#define HEIGHT_LOG (GLandscape->GetSubdivLog()) - -#define GetHeightNT(j,i) GLandscape->GetHeight((j)<ClippedTextureInfo(j+jStep,i); - if ( - info._mat && - ((info._mat->GetPixelShaderID()>=PSTerrain1 && info._mat->GetPixelShaderID()<=PSTerrain15) || - info._mat->GetPixelShaderID()==PSTerrainX || info._mat->GetPixelShaderID()==PSTerrainSNX) - ) - { - // sat. map always in stage 0 - Texture *sat = info._mat->_stage[0].GetTextureForDraw(); - -#if _VBS3_UDEFCHART - // If non-satellite map is to be drawn, use the user chart - if (_showScale) - { - // If we are in function CStaticMap::DrawField and non-satellite map is to be drawn, it can just mean the user chart was selected - DoAssert(UserMapDrawing()); - - // Get the user chart texture name - RStringB userChartTextureName; - { - RStringB satName = sat->GetName(); - int bckSlashPos = satName.ReverseFind('\\'); - if (bckSlashPos >= 0) - { - userChartTextureName = GWorld->GetUserDefinedChartName() + satName.Substring(bckSlashPos, satName.GetLength()); - } - } - - // We definitely don't want to use the sat texture - sat = NULL; - - // Replace sat texture by the user defined one - // Check if source does exist. If it doesn't exist use white texture - if (!userChartTextureName.IsEmpty()) - { - // Try to find the texture in the cache of stored textures - bool userTextureFound = false; - for (int i = 0; i < _userTextures.Size(); i++) - { - if (_userTextures[i]->GetName() == userChartTextureName) - { - sat = _userTextures[i]; - userTextureFound = true; - break; - } - } - - // If texture not found, try to search through names that don't have corresponding files - if (!userTextureFound) - { - // Look for names in not-found array - bool userTextureNotFoundFound = false; - for (int i = 0; i < _userTexturesNotFound.Size(); i++) - { - if (_userTexturesNotFound[i] == userChartTextureName) - { - sat = NULL; - userTextureNotFoundFound = true; - break; - } - } - - // Not found even in not-found names, do the loading - if (!userTextureNotFoundFound) - { - ITextureSourceFactory *factory = SelectTextureSourceFactory(userChartTextureName); - if (factory && factory->Check(userChartTextureName)) - { - int newTextureIndex = _userTextures.Add(GlobLoadTexture(userChartTextureName)); - sat = _userTextures[newTextureIndex]; - } - else - { - _userTexturesNotFound.Add(userChartTextureName); - // Use the white texture - sat = NULL; - } - } - } - } - } -#endif - // now we want to know the tex-gen for the stage - const TexGenInfo &tgen = info._mat->_texGen[info._mat->_stage[0]._texGen]; - Assert(tgen._uvSource==UVWorldPos); - // compute UV from world space coordinates - Vector3 wPosTL(i*LandGrid,0,j*LandGrid); - Vector3 wPosTR((i+iStep)*LandGrid,0,j*LandGrid); - Vector3 wPosBL(i*LandGrid,0,(j+jStep)*LandGrid); - Vector3 wPosBR((i+iStep)*LandGrid,0,(j+jStep)*LandGrid); - Vector3 uvTL = tgen._uvTransform.FastTransform(wPosTL); - Vector3 uvTR = tgen._uvTransform.FastTransform(wPosTR); - Vector3 uvBL = tgen._uvTransform.FastTransform(wPosBL); - Vector3 uvBR = tgen._uvTransform.FastTransform(wPosBR); - pars.uTL = uvTL.X(), pars.vTL = uvTL.Y(); - pars.uTR = uvTR.X(), pars.vTR = uvTR.Y(); - pars.uBL = uvBL.X(), pars.vBL = uvBL.Y(); - pars.uBR = uvBR.X(), pars.vBR = uvBR.Y(); - - // Determine the mip level - if (sat) - { - // mipmap is log4(texel2/pixel2) - // we assume mapping is rectangular - same U on left, same V on top - float texArea = fabs(pars.uBR-pars.uTL)*fabs(pars.vBR-pars.vTL); - float pixArea = rect.w*rect.h; - - float bestArea = sat->AWidth()*sat->AHeight(); - - const float invLog4 = 0.72134752044; // 1.0 / log(4.0); - //mipLevel = toIntFloor(log(pixArea/(texArea*bestArea)) * invLog4); - mipLevel = toIntFloor(log(texArea*bestArea/pixArea) * invLog4); - saturate(mipLevel,0,sat->ANMipmaps()); - } - else - { - mipLevel = 0; - } - //0.05 - 0.15 - float scaleAlpha = (_scaleX > _alphaFadeStartScale)? ((_alphaFadeEndScale - _scaleX)/(_alphaFadeEndScale - _alphaFadeStartScale)) : 1.0f; - texture = sat; - pars.SetColor(PackedColor(255,255,255,scaleAlpha * _maxSatelliteAlpha * 255)); - } - else - { - LogF("Only TerrainX shaders supported"); - float scaleAlpha = (_scaleX > _alphaFadeStartScale)? ((_alphaFadeEndScale - _scaleX)/(_alphaFadeEndScale - _alphaFadeStartScale)) : 1.0f; - texture = NULL; - pars.SetColor(PackedColor(255,255,255,scaleAlpha * _maxSatelliteAlpha * 255)); - } - - pars.spec = NoZBuf|IsAlpha|IsAlphaFog|NoClamp; - pars.mip = GLOB_ENGINE->TextBank()->UseMipmap(texture, mipLevel+1, mipLevel); - GLOB_ENGINE->Draw2D(pars, rect, _clipRect); - } -} - -void CStaticMap::DrawSea( - const MapProperties &props, - float x, float y, float xStep, float yStep, - int i, int j, int iStep, int jStep - ) -{ - const float waves = 5.0; - const float invWaves = 1.0 / (2.0 * waves); - - float heightTL = GetHeightNT(j, i); - float heightTR = GetHeightNT(j, i + iStep); - float heightBL = GetHeightNT(j + jStep, i); - float heightBR = GetHeightNT(j + jStep, i + iStep); - if - ( - heightTL >= waves && - heightTR >= waves && - heightBL >= waves && - heightBR >= waves - ) return; - - Draw2DPars pars; - - if( - heightTL <= -waves && heightTR <= -waves && - heightBL <= -waves && heightBR <= -waves - ) - { - // simple case: sea only - pars.colorTL = props._colorSeaPacked; - pars.colorTR = props._colorSeaPacked; - pars.colorBL = props._colorSeaPacked; - pars.colorBR = props._colorSeaPacked; - } - else - { - - heightTL += waves; heightTL *= invWaves; - saturate(heightTL, 0, 1); - heightTR += waves; heightTR *= invWaves; - saturate(heightTR, 0, 1); - heightBL += waves; heightBL *= invWaves; - saturate(heightBL, 0, 1); - heightBR += waves; heightBR *= invWaves; - saturate(heightBR, 0, 1); - - Color color, colorLand; - colorLand = props._colorSea; - colorLand.SetA(0); - - // TL - color = colorLand * heightTL + props._colorSea * (1 - heightTL); - pars.colorTL = PackedColor(color); - // TR - color = colorLand * heightTR + props._colorSea * (1 - heightTR); - pars.colorTR = PackedColor(color); - // BL - color = colorLand * heightBL + props._colorSea * (1 - heightBL); - pars.colorBL = PackedColor(color); - // BR - color = colorLand * heightBR + props._colorSea * (1 - heightBR); - pars.colorBR = PackedColor(color); - } - - Rect2DPixel rect(x * _wScreen, y * _hScreen, xStep * _wScreen, yStep * _hScreen); - pars.mip = GLOB_ENGINE->TextBank()->UseMipmap(NULL, 0, 0); - pars.spec = NoZBuf|IsAlpha|IsAlphaFog|NoClamp; - - pars.SetU(0, 1); - pars.SetV(0, 1); - - GLOB_ENGINE->Draw2D(pars, rect, _clipRect); -} - -void CStaticMap::DrawScale - ( - float x, float y, float xStep, float yStep, - int i, int j, int iStep, int jStep - ) -{ - const float invMaxHeight = 1.0 / 700.0; - - float heightTL = GetHeightNT(j, i) * invMaxHeight; - saturate(heightTL, 0, 1); - float heightTR = GetHeightNT(j, i + iStep) * invMaxHeight; - saturate(heightTR, 0, 1); - float heightBL = GetHeightNT(j + jStep, i) * invMaxHeight; - saturate(heightBL, 0, 1); - float heightBR = GetHeightNT(j + jStep, i + iStep) * invMaxHeight; - saturate(heightBR, 0, 1); - - Color color, colorL(0, 0, 0, 0), colorH(0, 0, 0, 1); - Draw2DParsNoTex pars; - - // TL - color = colorH * heightTL + colorL * (1 - heightTL); - pars.colorTL = PackedColor(color); - // TR - color = colorH * heightTR + colorL * (1 - heightTR); - pars.colorTR = PackedColor(color); - // BL - color = colorH * heightBL + colorL * (1 - heightBL); - pars.colorBL = PackedColor(color); - // BR - color = colorH * heightBR + colorL * (1 - heightBR); - pars.colorBR = PackedColor(color); - - Rect2DPixel rect(x * _wScreen, y * _hScreen, xStep * _wScreen, yStep * _hScreen); - - pars.spec = NoZBuf|IsAlpha|IsAlphaFog|NoClamp; - GLOB_ENGINE->Draw2D(pars, rect, _clipRect); -} - -inline static void DrawForestPoly3( - float x1, float y1, float x2, float y2, float x3, float y3, - PackedColor color, const Rect2DPixel &clipRect - ) -{ - const int n = 3; - Vertex2DPixel vs[n]; - vs[0].u = 0; - vs[0].v = 0; - vs[0].x = x3; - vs[0].y = y3; - vs[0].color = color; - vs[1].u = 0; - vs[1].v = 0; - vs[1].x = x2; - vs[1].y = y2; - vs[1].color = color; - vs[2].u = 0; - vs[2].v = 0; - vs[2].x = x1; - vs[2].y = y1; - vs[2].color = color; - MipInfo mip = GEngine->TextBank()->UseMipmap(NULL, 0, 0); - GEngine->DrawPoly(mip, vs, n, clipRect); -} - -inline static void DrawForestPoly4( - float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, - PackedColor color, const Rect2DPixel &clipRect - ) -{ - const int n = 4; - Vertex2DPixel vs[n]; - vs[0].u = 0; - vs[0].v = 0; - vs[0].x = x4; - vs[0].y = y4; - vs[0].color = color; - vs[1].u = 0; - vs[1].v = 0; - vs[1].x = x3; - vs[1].y = y3; - vs[1].color = color; - vs[2].u = 0; - vs[2].v = 0; - vs[2].x = x2; - vs[2].y = y2; - vs[2].color = color; - vs[3].u = 0; - vs[3].v = 0; - vs[3].x = x1; - vs[3].y = y1; - vs[3].color = color; - MipInfo mip = GEngine->TextBank()->UseMipmap(NULL, 0, 0); - GEngine->DrawPoly(mip, vs, n, clipRect); -} - -inline static void DrawForestPoly5( - float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float x5, float y5, - PackedColor color, const Rect2DPixel &clipRect - ) -{ - const int n = 5; - Vertex2DPixel vs[n]; - vs[0].u = 0; - vs[0].v = 0; - vs[0].x = x5; - vs[0].y = y5; - vs[0].color = color; - vs[1].u = 0; - vs[1].v = 0; - vs[1].x = x4; - vs[1].y = y4; - vs[1].color = color; - vs[2].u = 0; - vs[2].v = 0; - vs[2].x = x3; - vs[2].y = y3; - vs[2].color = color; - vs[3].u = 0; - vs[3].v = 0; - vs[3].x = x2; - vs[3].y = y2; - vs[3].color = color; - vs[4].u = 0; - vs[4].v = 0; - vs[4].x = x1; - vs[4].y = y1; - vs[4].color = color; - MipInfo mip = GEngine->TextBank()->UseMipmap(NULL, 0, 0); - GEngine->DrawPoly(mip, vs, n, clipRect); -} - -inline static void DrawForestLine(float x1, float y1, float x2, float y2, PackedColor color, const Rect2DPixel &clipRect) -{ - GEngine->DrawLineDo(Line2DPixel(x1, y1, x2, y2),color, color, clipRect); -} - -void CStaticMap::DrawForestsNew( - const MapObjectList &list, int i, int j, const DrawForestContext &ctx, bool drawLines, bool rocks) -{ - // new style drawing (using isoarbors) - float x = (ctx.xMin + (i - ctx.iMin) * ctx.xStep) * _wScreen; - float y = (ctx.yMin + (ctx.jMin - j) * ctx.yStep) * _hScreen; - float w = ctx.xStep * _wScreen; - float h = ctx.yStep * _hScreen; - - PackedColor color = rocks ? ctx.props._colorRocks : ctx.props._colorForest; - PackedColor colorBorder = rocks ? ctx.props._colorRocksBorder : ctx.props._colorForestBorder; - - for (int o=0; oGetType() != MapRocks) continue; - } - else - { - if (obj->GetType() != MapForest) continue; - } - - MapObjectForest *forest = static_cast(obj); - - int row = forest->_row; - int col = forest->_col; - - float wGrid = w / forest->_cols; - float hGrid = h / forest->_rows; - - float tl = forest->_tl; - float tr = forest->_tr; - float bl = forest->_bl; - float br = forest->_br; - float limit = 1.0f; - - int bits = 0; - if (tl > limit) bits |= 8; - if (tr > limit) bits |= 4; - if (bl > limit) bits |= 2; - if (br > limit) bits |= 1; - switch (bits) - { - case 0: - // nothing to draw - no forest - // Fail("No forest"); - break; - case 1: - { - // br - float coef1 = (limit - bl) / (br - bl); - float coef2 = (limit - tr) / (br - tr); - float x1 = x + (col + coef1) * wGrid; - float y1 = y + h - (row + 1) * hGrid; - float x2 = x + (col + 1) * wGrid; - float y2 = y + h - (row + coef2) * hGrid; - - if (!drawLines) DrawForestPoly3(x1, y1, x2, y2, x2, y1, color, _clipRect); - else DrawForestLine(x1, y1, x2, y2, colorBorder, _clipRect); - } - break; - case 2: - { - // bl - float coef1 = (limit - tl) / (bl - tl); - float coef2 = (bl - limit) / (bl - br); - float x1 = x + col * wGrid; - float y1 = y + h - (row + coef1) * hGrid; - float x2 = x + (col + coef2) * wGrid; - float y2 = y + h - (row + 1) * hGrid; - - if (!drawLines) DrawForestPoly3(x1, y1, x2, y2, x1, y2, color, _clipRect); - else DrawForestLine(x1, y1, x2, y2, colorBorder, _clipRect); - } - break; - case 3: - { - // bl, br - float coef1 = (limit - tl) / (bl - tl); - float coef2 = (limit - tr) / (br - tr); - float x1 = x + col * wGrid; - float y1 = y + h - (row + coef1) * hGrid; - float x2 = x + (col + 1) * wGrid; - float y2 = y + h - (row + coef2) * hGrid; - float y3 = y + h - (row + 1) * hGrid; - - if (!drawLines) DrawForestPoly4(x1, y1, x2, y2, x2, y3, x1, y3, color, _clipRect); - else DrawForestLine(x1, y1, x2, y2, colorBorder, _clipRect); - } - break; - case 4: - { - // tr - float coef1 = (tr - limit) / (tr - br); - float coef2 = (limit - tl) / (tr - tl); - float x1 = x + (col + 1) * wGrid; - float y1 = y + h - (row + coef1) * hGrid; - float x2 = x + (col + coef2) * wGrid; - float y2 = y + h - row * hGrid; - - if (!drawLines) DrawForestPoly3(x1, y1, x2, y2, x1, y2, color, _clipRect); - else DrawForestLine(x1, y1, x2, y2, colorBorder, _clipRect); - } - break; - case 5: - { - // tr, br - float coef1 = (limit - bl) / (br - bl); - float coef2 = (limit - tl) / (tr - tl); - float x1 = x + (col + coef1) * wGrid; - float y1 = y + h - (row + 1) * hGrid; - float x2 = x + (col + coef2) * wGrid; - float y2 = y + h - row * hGrid; - float x3 = x + (col + 1) * wGrid; - - if (!drawLines) DrawForestPoly4(x1, y1, x2, y2, x3, y2, x3, y1, color, _clipRect); - else DrawForestLine(x1, y1, x2, y2, colorBorder, _clipRect); - } - break; - case 6: - { - // tr - float coef1 = (tr - limit) / (tr - br); - float coef2 = (limit - tl) / (tr - tl); - float x1 = x + (col + 1) * wGrid; - float y1 = y + h - (row + coef1) * hGrid; - float x2 = x + (col + coef2) * wGrid; - float y2 = y + h - row * hGrid; - - if (!drawLines) DrawForestPoly3(x1, y1, x2, y2, x1, y2, color, _clipRect); - else DrawForestLine(x1, y1, x2, y2, colorBorder, _clipRect); - } - { - // bl - float coef1 = (limit - tl) / (bl - tl); - float coef2 = (bl - limit) / (bl - br); - float x1 = x + col * wGrid; - float y1 = y + h - (row + coef1) * hGrid; - float x2 = x + (col + coef2) * wGrid; - float y2 = y + h - (row + 1) * hGrid; - - if (!drawLines) DrawForestPoly3(x1, y1, x2, y2, x1, y2, color, _clipRect); - else DrawForestLine(x1, y1, x2, y2, colorBorder, _clipRect); - } - break; - case 7: - { - // tr, bl, br - float coef1 = (limit - tl) / (bl - tl); - float coef2 = (limit - tl) / (tr - tl); - float x1 = x + col * wGrid; - float y1 = y + h - (row + coef1) * hGrid; - float x2 = x + (col + coef2) * wGrid; - float y2 = y + h - row * hGrid; - float x3 = x + (col + 1) * wGrid; - float y3 = y + h - (row + 1) * hGrid; - - if (!drawLines) DrawForestPoly5(x1, y1, x2, y2, x3, y2, x3, y3, x1, y3, color, _clipRect); - else DrawForestLine(x1, y1, x2, y2, colorBorder, _clipRect); - } - break; - case 8: - { - // tl - float coef1 = (tl - limit) / (tl - tr); - float coef2 = (tl - limit) / (tl - bl); - float x1 = x + (col + coef1) * wGrid; - float y1 = y + h - row * hGrid; - float x2 = x + col * wGrid; - float y2 = y + h - (row + coef2) * hGrid; - - if (!drawLines) DrawForestPoly3(x1, y1, x2, y2, x2, y1, color, _clipRect); - else DrawForestLine(x1, y1, x2, y2, colorBorder, _clipRect); - } - break; - case 9: - { - // tl - float coef1 = (tl - limit) / (tl - tr); - float coef2 = (tl - limit) / (tl - bl); - float x1 = x + (col + coef1) * wGrid; - float y1 = y + h - row * hGrid; - float x2 = x + col * wGrid; - float y2 = y + h - (row + coef2) * hGrid; - - if (!drawLines) DrawForestPoly3(x1, y1, x2, y2, x2, y1, color, _clipRect); - else DrawForestLine(x1, y1, x2, y2, colorBorder, _clipRect); - } - { - // br - float coef1 = (limit - bl) / (br - bl); - float coef2 = (limit - tr) / (br - tr); - float x1 = x + (col + coef1) * wGrid; - float y1 = y + h - (row + 1) * hGrid; - float x2 = x + (col + 1) * wGrid; - float y2 = y + h - (row + coef2) * hGrid; - - if (!drawLines) DrawForestPoly3(x1, y1, x2, y2, x2, y1, color, _clipRect); - else DrawForestLine(x1, y1, x2, y2, colorBorder, _clipRect); - } - break; - case 10: - { - // tl, bl - float coef1 = (tl - limit) / (tl - tr); - float coef2 = (bl - limit) / (bl - br); - float x1 = x + (col + coef1) * wGrid; - float y1 = y + h - row * hGrid; - float x2 = x + (col + coef2) * wGrid; - float y2 = y + h - (row + 1) * hGrid; - float x3 = x + col * wGrid; - - if (!drawLines) DrawForestPoly4(x1, y1, x2, y2, x3, y2, x3, y1, color, _clipRect); - else DrawForestLine(x1, y1, x2, y2, colorBorder, _clipRect); - } - break; - case 11: - { - // tl, bl, br - float coef1 = (tl - limit) / (tl - tr); - float coef2 = (limit - tr) / (br - tr); - float x1 = x + (col + coef1) * wGrid; - float y1 = y + h - row * hGrid; - float x2 = x + (col + 1) * wGrid; - float y2 = y + h - (row + coef2) * hGrid; - float x3 = x + col * wGrid; - float y3 = y + h - (row + 1) * hGrid; - - if (!drawLines) DrawForestPoly5(x1, y1, x2, y2, x2, y3, x3, y3, x3, y1, color, _clipRect); - else DrawForestLine(x1, y1, x2, y2, colorBorder, _clipRect); - } - break; - case 12: - { - // tl, tr - float coef1 = (tr - limit) / (tr - br); - float coef2 = (tl - limit) / (tl - bl); - float x1 = x + (col + 1) * wGrid; - float y1 = y + h - (row + coef1) * hGrid; - float x2 = x + col * wGrid; - float y2 = y + h - (row + coef2) * hGrid; - float y3 = y + h - row * hGrid; - - if (!drawLines) DrawForestPoly4(x1, y1, x2, y2, x2, y3, x1, y3, color, _clipRect); - else DrawForestLine(x1, y1, x2, y2, colorBorder, _clipRect); - } - break; - case 13: - { - // tl, tr, br - float coef1 = (limit - bl) / (br - bl); - float coef2 = (tl - limit) / (tl - bl); - float x1 = x + (col + coef1) * wGrid; - float y1 = y + h - (row + 1) * hGrid; - float x2 = x + col * wGrid; - float y2 = y + h - (row + coef2) * hGrid; - float x3 = x + (col + 1) * wGrid; - float y3 = y + h - row * hGrid; - - if (!drawLines) DrawForestPoly5(x1, y1, x2, y2, x2, y3, x3, y3, x3, y1, color, _clipRect); - else DrawForestLine(x1, y1, x2, y2, colorBorder, _clipRect); - } - break; - case 14: - { - // tl, tr, bl - float coef1 = (tr - limit) / (tr - br); - float coef2 = (bl - limit) / (bl - br); - float x1 = x + (col + 1) * wGrid; - float y1 = y + h - (row + coef1) * hGrid; - float x2 = x + (col + coef2) * wGrid; - float y2 = y + h - (row + 1) * hGrid; - float x3 = x + col * wGrid; - float y3 = y + h - row * hGrid; - - if (!drawLines) DrawForestPoly5(x1, y1, x2, y2, x3, y2, x3, y3, x1, y3, color, _clipRect); - else DrawForestLine(x1, y1, x2, y2, colorBorder, _clipRect); - } - break; - case 15: - { - // full forest - float x1 = x + col * wGrid; - float y1 = y + h - row * hGrid; - float x2 = x + (col + 1) * wGrid; - float y2 = y + h - (row + 1) * hGrid; - - if (!drawLines) DrawForestPoly4(x1, y1, x2, y1, x2, y2, x1, y2, color, _clipRect); - } - break; - } - /* - // grid - float x1 = x + col * wGrid; - float y1 = y + h - row * hGrid; - float x2 = x + (col + 1) * wGrid; - float y2 = y + h - (row + 1) * hGrid; - PackedColor color = PackedColor(Color(1, 0, 0, 1)); - GEngine->DrawLine(Line2DPixel(x1, y1, x1, y2), color, color, _clipRect); - GEngine->DrawLine(Line2DPixel(x1, y2, x2, y2), color, color, _clipRect); - GEngine->DrawLine(Line2DPixel(x2, y2, x2, y1), color, color, _clipRect); - GEngine->DrawLine(Line2DPixel(x2, y1, x1, y1), color, color, _clipRect); - */ - } -} - - -void CStaticMap::DrawBuilding(MapObject *obj, PackedColor color) -{ - DrawCoord mapTL = WorldToScreen(obj->GetTLPosition()); - DrawCoord mapTR = WorldToScreen(obj->GetTRPosition()); - DrawCoord mapBL = WorldToScreen(obj->GetBLPosition()); - DrawCoord mapBR = WorldToScreen(obj->GetBRPosition()); - - const int n = 4; - Vertex2DPixel vs[n]; - // 0 - vs[0].x = mapTL.x * _wScreen; - vs[0].y = mapTL.y * _hScreen; - vs[0].u = 0; - vs[0].v = 0; - vs[0].color = color; - // 1 - vs[1].x = mapBL.x * _wScreen; - vs[1].y = mapBL.y * _hScreen; - vs[1].u = 0; - vs[1].v = 0; - vs[1].color = color; - // 2 - vs[2].x = mapBR.x * _wScreen; - vs[2].y = mapBR.y * _hScreen; - vs[2].u = 0; - vs[2].v = 0; - vs[2].color = color; - // 3 - vs[3].x = mapTR.x * _wScreen; - vs[3].y = mapTR.y * _hScreen; - vs[3].u = 0; - vs[3].v = 0; - vs[3].color = color; - - MipInfo mip = GLOB_ENGINE->TextBank()->UseMipmap(NULL, 0, 0); - GLOB_ENGINE->DrawPoly(mip, vs, n, _clipRect); -} - -void CStaticMap::DrawObjects(const MapProperties &props, const MapObjectList &list, int i, int j) -{ - Vector3 defaultPos((i + 0.5) * LandGrid, 0, (j + 0.5) * LandGrid); - for (int o=0; oGetType()) - { - case MapBuilding: - case MapHouse: - case MapFence: - case MapWall: - DrawBuilding(obj, obj->GetColor()); - break; - case MapPowerLines: - { - DrawCoord mapTL = WorldToScreen(obj->GetTLPosition()); - DrawCoord mapTR = WorldToScreen(obj->GetTRPosition()); - GEngine->DrawLinePrepare(); - GEngine->DrawLineDo( - Line2DPixel(mapTL.x * _wScreen, mapTL.y * _hScreen, - mapTR.x * _wScreen, mapTR.y * _hScreen), - props._colorPowerLines, props._colorPowerLines, _clipRect); - } - break; - case MapRailWay: - { - DrawCoord map1 = WorldToScreen(obj->GetTLPosition()); - DrawCoord map2 = WorldToScreen(obj->GetTRPosition()); - DrawCoord map3 = WorldToScreen(obj->GetBLPosition()); - - GEngine->DrawLinePrepare(); - GEngine->DrawLineDo( - Line2DPixel(map1.x * _wScreen, map1.y * _hScreen, map2.x * _wScreen, map2.y * _hScreen), - props._colorRailWay, props._colorRailWay, _clipRect); - - if (!obj->HasMoreParts()) break; - - GEngine->DrawLinePrepare(); - GEngine->DrawLineDo( - Line2DPixel(map2.x * _wScreen, map2.y * _hScreen, - map3.x * _wScreen, map3.y * _hScreen), - props._colorRailWay, props._colorRailWay, _clipRect); - - } - break; - // draw icon only - MAP_TYPES_ICONS_1(MAP_TYPE_DRAW_ICON) - // draw both icon and polygon - MAP_TYPES_ICONS_2(MAP_TYPE_DRAW_BUILDING_AND_ICON) - } - - if (_showIds && obj->GetType() != MapForest && obj->GetType() != MapRocks) - { - float ptsLand = 800.0 * _invScaleX * InvLandRange; // avoid dependece on video resolution - float invPtsLand = 1.0 / ptsLand; - - int iStep = toIntCeil(_ptsPerSquareCost * invPtsLand); - float xStep = iStep * InvLandRange * _invScaleX; - if (xStep>0.15) - { - // draw object ID - DrawCoord pos = WorldToScreen(obj->GetPosition(defaultPos)); - const float size = 0.02; -#if _HELISIM_LARGE_OBJECTID - float width = GEngine->GetTextWidthF(size, props._fontGrid, "%I64d", obj->GetId().Encode()); -#else - float width = GEngine->GetTextWidthF(size, props._fontGrid, "%d", obj->GetId().Encode()); -#endif - float x = pos.x - 0.5 * width; - float y = pos.y - 0.5 * size; - MipInfo mip = GLOB_ENGINE->TextBank()->UseMipmap(NULL, 0, 0); - GEngine->Draw2D - ( - mip, PackedWhite, - Rect2DPixel(x * _wScreen, y * _hScreen, width * _wScreen, size * _hScreen), - Rect2DPixel(_x * _wScreen, _y * _hScreen, _w * _wScreen, _h * _hScreen) - ); -#if _HELISIM_LARGE_OBJECTID - GEngine->DrawTextF - ( - Point2DFloat(x, y), size, - Rect2DFloat(_x, _y, _w, _h), - props._fontGrid, PackedBlack, 0, "%I64d", obj->GetId().Encode() - ); -#else - GEngine->DrawTextF - ( - Point2DFloat(x, y), size, - Rect2DFloat(_x, _y, _w, _h), - props._fontGrid, PackedBlack, 0, "%d", obj->GetId().Encode() - ); -#endif - } - } - } -} - -void CStaticMap::DrawRoads(const MapProperties &props, LineArray &lines, const MapObjectList &listU, int i, int j) -{ - const MapObjectList &list = listU; - for (int o=0; oGetType()) - { - case MapTrack: - color = props._colorTracks; - colorFill = props._colorTracksFill; - break; - case MapRoad: - color = props._colorRoads; - colorFill = props._colorRoadsFill; - break; - case MapMainRoad: - color = props._colorMainRoads; - colorFill = props._colorMainRoadsFill; - break; - default: - // not a road - continue; - } - - if (obj->GetType() == MapRoad || obj->GetType() == MapTrack || obj->GetType() == MapMainRoad) - { - // if there are many lines, we flush to avoid memory allocation - if (lines.Size()>AllocLines-2) - { - GEngine->DrawLines(lines.Data(),lines.Size(),_clipRect); - lines.Resize(0); - } - DrawCoord mapTL = WorldToScreen(obj->GetTLPosition()); - DrawCoord mapTR = WorldToScreen(obj->GetTRPosition()); - DrawCoord mapBL = WorldToScreen(obj->GetBLPosition()); - DrawCoord mapBR = WorldToScreen(obj->GetBRPosition()); - - if (color.A8() > 0) - { - Line2DPixelInfo &line1 = lines.Append(); - line1.beg = Point2DPixel(mapTL.x * _wScreen, mapTL.y * _hScreen); - line1.end = Point2DPixel(mapBL.x * _wScreen, mapBL.y * _hScreen); - line1.c0 = color; - line1.c1 = color; - - Line2DPixelInfo &line2 = lines.Append(); - line2.beg = Point2DPixel(mapTR.x * _wScreen, mapTR.y * _hScreen); - line2.end = Point2DPixel(mapBR.x * _wScreen, mapBR.y * _hScreen); - line2.c0 = color; - line2.c1 = color; - } - if (colorFill.A8() > 0) - { - const int n = 4; - Vertex2DPixel vs[n]; - // 0 - vs[0].x = mapTL.x * _wScreen; - vs[0].y = mapTL.y * _hScreen; - vs[0].u = 0; - vs[0].v = 0; - // 1 - vs[1].x = mapBL.x * _wScreen; - vs[1].y = mapBL.y * _hScreen; - vs[1].u = 1; - vs[1].v = 0; - // 2 - vs[2].x = mapBR.x * _wScreen; - vs[2].y = mapBR.y * _hScreen; - vs[2].u = 1; - vs[2].v = 1; - // 3 - vs[3].x = mapTR.x * _wScreen; - vs[3].y = mapTR.y * _hScreen; - vs[3].u = 0; - vs[3].v = 1; - - MipInfo mip = GEngine->TextBank()->UseMipmap(NULL, 0, 0); - for (int i=0; i<4; i++) - { - vs[i].color = colorFill; - } - GEngine->DrawPoly(mip, vs, n, _clipRect); - } - } - } -} - -/*! -\patch 1.62 Date 5/31/2002 by Ondra -- Fixed: Map contour drawing was not correct in some places -with highly variable gradient. -*/ - -void CStaticMap::DrawLines - ( - LineArray &lines, DrawCoord *pt, float *height, - float step, float stepMain, float minLevel, float maxLevel, PackedColor color, PackedColor colorMain - ) -{ - float invStep = 1.0 / step; - - int n0, n1, n2, nt; - float xs, ys, xe, ye; - // original (wrong): - // draw triangle <0, 1, 2> - // draw triangle <1, 2, 3> - // correct: - // draw triangle <0, 1, 3> - // draw triangle <0, 2, 3> - for (int t=0; t<2; t++) - { - // t = 0, 1 - // draw triangel - n0 = 0; n1 = t + 1; n2 = 3; - // sort vertices by height - if (height[n0] > height[n1]) - { // swap n0, n1 - nt = n0; n0 = n1; n1 = nt; - } - if (height[n0] > height[n2]) - { // swap n0, n2 - nt = n0; n0 = n2; n2 = nt; - } - if (height[n1] > height[n2]) - { // swap n1, n2 - nt = n1; n1 = n2; n2 = nt; - } - - // fastCeil - float level = step * toIntCeil(height[n0] * invStep); - saturateMax(level, minLevel); - float toLevel = floatMin(height[n2], maxLevel); - for (; level<=toLevel; level+=step) - { - PackedColor col; - if (fastFmod(level + 0.5 * step, stepMain) < step) - col = colorMain; - else - col = color; - if (height[n2] == height[n0]) - { - // all 3 points have the same height - draw the triangle - { - Line2DPixelInfo &line = lines.Append(); - line.beg = Point2DPixel(pt[n0].x * _wScreen, pt[n0].y * _hScreen); - line.end = Point2DPixel(pt[n1].x * _wScreen, pt[n1].y * _hScreen); - line.c0 = col; - line.c1 = col; - } - { - Line2DPixelInfo &line = lines.Append(); - line.beg = Point2DPixel(pt[n1].x * _wScreen, pt[n1].y * _hScreen); - line.end = Point2DPixel(pt[n2].x * _wScreen, pt[n2].y * _hScreen); - line.c0 = col; - line.c1 = col; - } - { - Line2DPixelInfo &line = lines.Append(); - line.beg = Point2DPixel(pt[n2].x * _wScreen, pt[n2].y * _hScreen); - line.end = Point2DPixel(pt[n0].x * _wScreen, pt[n0].y * _hScreen); - line.c0 = col; - line.c1 = col; - } - continue; - } - // draw one line (at level ) - float coef = (level - height[n0]) * (1.0 / (height[n2] - height[n0])); - xe = pt[n0].x + coef * (pt[n2].x - pt[n0].x); - ye = pt[n0].y + coef * (pt[n2].y - pt[n0].y); - if (level == height[n1]) - { - xs = pt[n1].x; - ys = pt[n1].y; - } - else if (level < height[n1]) - { - float coef = (level - height[n0]) * (1.0 / (height[n1] - height[n0])); - xs = pt[n0].x + coef * (pt[n1].x - pt[n0].x); - ys = pt[n0].y + coef * (pt[n1].y - pt[n0].y); - } - else - { - float coef = (level - height[n1]) * (1.0 / (height[n2] - height[n1])); - xs = pt[n1].x + coef * (pt[n2].x - pt[n1].x); - ys = pt[n1].y + coef * (pt[n2].y - pt[n1].y); - } - // draw line from to - Line2DPixelInfo &line = lines.Append(); - line.beg = Point2DPixel(xs * _wScreen, ys * _hScreen); - line.end = Point2DPixel(xe * _wScreen, ye * _hScreen); - line.c0 = col; - line.c1 = col; - } - } -} - -/** draw map contour lines */ - -void CStaticMap::DrawCountlines( - const MapProperties &props, LineArray &lines, - float x, float y, float xStep, float yStep, - int i, int j, int iStep, int jStep, - float step, float stepMain, float maxLevel - ) -{ - // if there are many lines, we flush to avoid memory allocation - if (lines.Size()>AllocLines-2) - { - GEngine->DrawLines(lines.Data(),lines.Size(),_clipRect); - lines.Resize(0); - } - // insert bounds into fields - DrawCoord pt[4]; - float height[4]; - pt[0].x = x; pt[0].y = y; - pt[1].x = x + xStep; pt[1].y = y; - pt[2].x = x; pt[2].y = y + yStep; - pt[3].x = x + xStep; pt[3].y = y + yStep; - height[0] = GLOB_LAND->ClippedDataXZ(i, j); - height[1] = GLOB_LAND->ClippedDataXZ(i + iStep, j); - height[2] = GLOB_LAND->ClippedDataXZ(i, j + jStep); - height[3] = GLOB_LAND->ClippedDataXZ(i + iStep, j + jStep); - - DrawLines(lines, pt, height, step, stepMain, -maxLevel, 0.5 * step, props._colorCountlinesWater, props._colorMainCountlinesWater); - DrawLines(lines, pt, height, step, stepMain, step, maxLevel, props._colorCountlines, props._colorMainCountlines); - -} - -/*! -\patch_internal 1.45 Date 2/21/2002 by Jirka -- Improved: Map grid format controlled by config -*/ - -void CStaticMap::DrawGrid(const MapProperties &props) -{ - float sizeLand = LandGrid * LandRange; - float invSizeLand = 1.0f / sizeLand; - - const GridInfo *info = GWorld->GetGridInfo(_scaleX); - if (!info) return; - - float offsetX = GWorld->GetGridOffsetX(); - float offsetY = GWorld->GetGridOffsetY(); - - float coefX = sizeLand * info->invStepX; - float invCoefX = invSizeLand * info->stepX; - - float coefY = sizeLand * info->invStepY; - float invCoefY = invSizeLand * info->stepY; - - float minX = floatMax(-_mapX, _minX); - float maxX = floatMin(_w - _mapX, _maxX); - float minY = floatMax(-_mapY, _minY); - float maxY = floatMin(_h - _mapY, _maxY); - Rect2DFloat rectFloat(_x + _mapX + minX, _y + _mapY + minY, maxX - minX, maxY - minY); - Rect2DPixel rect(rectFloat.x * _wScreen, rectFloat.y * _hScreen, rectFloat.w * _wScreen, rectFloat.h * _hScreen); - - int xFrom = TO_INT(coefX, (minX * _scaleX * sizeLand - offsetX) * info->invStepX); - int zFrom = TO_INT(coefY, (minY * _scaleY * sizeLand - offsetY) * info->invStepY); - int xTo = TO_INT(coefX, (maxX * _scaleX * sizeLand - offsetX) * info->invStepX); - int zTo = TO_INT(coefY, (maxY * _scaleY * sizeLand - offsetY) * info->invStepY); - - float xBeg = _x + _mapX + (xFrom * info->stepX + offsetX) * _invScaleX * invSizeLand; - float zBeg = _y + _mapY + (zFrom * info->stepY + offsetY) * _invScaleY * invSizeLand; - float xFld = fabs(_invScaleX * invCoefX); - float zFld = fabs(_invScaleY * invCoefY); - - float h = props._sizeGrid; - const float textBorder = TEXT_BORDER; - - float zAct = zBeg; - int zSign = coefY > 0 ? 1 : -1; - AspectSettings asp; - GEngine->GetAspectSettings(asp); - - for (int z = zFrom; zSign * (zTo - z) >= 0; z+=zSign) - { - BString<32> buffer; - GridFormat(buffer, info->formatY, zSign == 1 ? z : z - 1); - - float width = GEngine->GetTextWidth(props._sizeGrid, props._fontGrid, buffer); - - float offset = _gridNumbersOverLines ? (width + textBorder + 0.001) * _wScreen : 0; - - if (zAct >= rectFloat.y && zAct <= rectFloat.y + rectFloat.h) - { - GLOB_ENGINE->DrawLine - ( - Line2DPixel(rect.x + offset, zAct * _hScreen, - rect.x + rect.w - offset, zAct * _hScreen), - props._colorGridMap, props._colorGridMap - ); - if(!(z % 10)) - GLOB_ENGINE->DrawLine - ( - Line2DPixel(rect.x + offset, zAct * _hScreen +1, - rect.x + rect.w - offset, zAct * _hScreen +1), - props._colorGridMap, props._colorGridMap - ); - } - - //wide screen map-coordinates position - float ratio =(float)GEngine->WidthBB()/std::max(GEngine->Width2D(),1); - float sfX = (-asp.uiTopLeftX) * ratio; - -#if _VBS3_UDEFCHART - float left = rectFloat.x + textBorder; - float right = rectFloat.x + rectFloat.w - width - textBorder; -#else - float left = std::max(rectFloat.x, sfX) + textBorder; - float right = std::min(rectFloat.x + rectFloat.w, 1-sfX) - width - textBorder; -#endif - float top = _gridNumbersOverLines ? (zAct - 0.5 * props._sizeGrid) : (zAct + 0.5 * (zFld - h)); - - GLOB_ENGINE->DrawText - ( - Point2DFloat(left, top), props._sizeGrid, - rectFloat, - props._fontGrid, props._colorGrid, buffer, 0 - ); - GLOB_ENGINE->DrawText - ( - Point2DFloat(right, top), props._sizeGrid, - rectFloat, - props._fontGrid, props._colorGrid, buffer, 0 - ); - zAct += zFld; - } - - float xAct = xBeg; - int xSign = coefX > 0 ? 1 : -1; - - float offset = _gridNumbersOverLines ? props._sizeGrid * _hScreen : 0; - - for (int x = xFrom; xSign * (xTo - x) >= 0; x+=xSign) - { - if (xAct >= rectFloat.x && xAct <= rectFloat.x + rectFloat.w) - { - GLOB_ENGINE->DrawLine - ( - Line2DPixel(xAct * _wScreen, rect.y + offset, - xAct * _wScreen, rect.y + rect.h - offset), - props._colorGridMap, props._colorGridMap - ); - if(!(x % 10)) - GLOB_ENGINE->DrawLine - ( - Line2DPixel(xAct * _wScreen+1, rect.y + offset, - xAct * _wScreen+1, rect.y + rect.h - offset), - props._colorGridMap, props._colorGridMap - ); - } - - BString<32> buffer; - GridFormat(buffer, info->formatX, xSign == 1 ? x : x - 1); - - float left = _gridNumbersOverLines ? - xAct - 0.5 * GEngine->GetTextWidth(props._sizeGrid, props._fontGrid, buffer) - : xAct + 0.5 * (xFld - GEngine->GetTextWidth(props._sizeGrid, props._fontGrid, buffer)); - - //wide screen map-coordinates position - float ratio =(float)GEngine->WidthBB()/std::max(GEngine->Width2D(),1); - float sfY = (-asp.uiTopLeftY) * ratio; - -#if _VBS3_UDEFCHART - float top = rectFloat.y; - float bottom = rectFloat.y + _h - _sizeGrid; -#else - float top = std::max(rectFloat.y, sfY); - float bottom = std::min(rectFloat.y + rectFloat.h, 1-sfY) - props._sizeGrid; -#endif - GLOB_ENGINE->DrawText - ( - Point2DFloat(left, top), props._sizeGrid, - rectFloat, - props._fontGrid, props._colorGrid, buffer, 0 - ); - GLOB_ENGINE->DrawText - ( - Point2DFloat(left, bottom), props._sizeGrid, - rectFloat, - props._fontGrid, props._colorGrid, buffer, 0 - ); - xAct += xFld; - } -} - -void CStaticMap::OnHide() -{ - _mapUsed.Free(); -} - -//static ActionResponseCurve MapScrollX(0.20,1,2.0); -//static ActionResponseCurve MapScrollY(0.20,1,2.0); - -void CStaticMap::OnDraw(UIViewport *vp, float alpha) -{ - const MapProperties &props = GetMapProperties(); - SaturateScale(props); // includes Precalculate - - float dt = Glob.uiTime - _moveLast; - saturateMin(dt, 0.1); // minimal fps 10 - avoid jumps of cursor - - bool canAnimate = true; - - if (static_cast(_parent.GetLink()) != GWorld->Map() || GWorld->IsShowMapWanted()) // check only for in-game map - { - if (_moveKey != 0) - { - _moveLast = Glob.uiTime; - if (Glob.uiTime - _moveStart < 0.5) dt *= 0.5; - - switch (_moveKey) - { - case DIK_ADD: - SetScale(exp(-dt) * GetScale()); - break; - case DIK_SUBTRACT: - SetScale(exp(dt) * GetScale()); - break; - case DIK_NUMPAD1: - _mapX += dt; SaturateX(_mapX); - _mapY -= dt; SaturateY(_mapY); - break; - case DIK_NUMPAD2: - _mapY -= dt; SaturateY(_mapY); - break; - case DIK_NUMPAD3: - _mapX -= dt; SaturateX(_mapX); - _mapY -= dt; SaturateY(_mapY); - break; - case DIK_NUMPAD4: - _mapX += dt; SaturateX(_mapX); - break; - case DIK_NUMPAD6: - _mapX -= dt; SaturateX(_mapX); - break; - case DIK_NUMPAD7: - _mapX += dt; SaturateX(_mapX); - _mapY += dt; SaturateY(_mapY); - break; - case DIK_NUMPAD8: - _mapY += dt; SaturateY(_mapY); - break; - case DIK_NUMPAD9: - _mapX -= dt; SaturateX(_mapX); - _mapY += dt; SaturateY(_mapY); - break; - } - canAnimate = false; - } - } - - if (canAnimate && _interpolator) - { - float t = Glob.uiTime - _animationStart; - Vector3 pos = (*_interpolator)(t).Position(); - _scaleX = exp(pos[1]); - pos[1] = 0; - saturate(_scaleX, props._scaleMin, props._scaleMax); - Precalculate(props); - Center(pos, false); - _animationLast = Glob.uiTime; - if (t > _interpolator->MaxArg()) - ClearAnimation(); - else - { - float predictTime = 0.2f; - Vector3 predictPos = (*_interpolator)(t+predictTime).Position(); - PreloadData(predictPos); - } - } - - DrawBackground(props); - - if (!UserMapIsBeingDrawn()) - { -#if _ENABLE_CHEATS - if (_show) -#endif -#if _VBS3 - if(GVBSVisuals.GetShowGrid()) -#endif - DrawGrid(props); - } - DrawExt(alpha); - OnEvent(CEDraw); - - if (_parent && _parent->IsTop() && !GWorld->GetCameraEffect()) - { - RString cursorName = _parent->GetCursorName(); - if (cursorName.GetLength() > 0 && stricmp(cursorName, "Arrow") != 0) - { - int wScreen = GLOB_ENGINE->Width2D(); - int hScreen = GLOB_ENGINE->Height2D(); - const float mouseH = 16.0 / 600; - const float mouseW = 16.0 / 800; - float mouseX = 0.5 + GInput.cursorX * 0.5; - float mouseY = 0.5 + GInput.cursorY * 0.5; - PackedColor color = _parent->GetCursorColor(); - MipInfo mip = GEngine->TextBank()->UseMipmap(NULL, 0, 0); - float pt = mouseX - mouseW; - if (pt > _x) - GEngine->Draw2D - ( - mip, color, - Rect2DPixel(wScreen * _x, hScreen * mouseY - 0.5 * _cursorLineWidth, wScreen * (pt - _x), _cursorLineWidth) - ); - pt = mouseX + mouseW; - if (pt < _x + _w) - GEngine->Draw2D - ( - mip, color, - Rect2DPixel(wScreen * pt, hScreen * mouseY - 0.5 * _cursorLineWidth, wScreen * (_x + _w - pt), _cursorLineWidth) - ); - pt = mouseY - mouseH; - if (pt > _y) - GEngine->Draw2D - ( - mip, color, - Rect2DPixel(wScreen * mouseX - 0.5 * _cursorLineWidth, hScreen * _y, _cursorLineWidth, hScreen * (pt - _y)) - ); - pt = mouseY + mouseH; - if (pt < _y + _h) - GEngine->Draw2D - ( - mip, color, - Rect2DPixel(wScreen * mouseX - 0.5 * _cursorLineWidth, hScreen * pt, _cursorLineWidth, hScreen * (_y + _h - pt)) - ); - } - } -} - -// mouse / keyboard events -bool CStaticMap::OnKeyUp(int dikCode) -{ - switch (dikCode) - { - case DIK_ADD: - case DIK_SUBTRACT: - case DIK_NUMPAD1: - case DIK_NUMPAD2: - case DIK_NUMPAD3: - case DIK_NUMPAD4: - case DIK_NUMPAD6: - case DIK_NUMPAD7: - case DIK_NUMPAD8: - case DIK_NUMPAD9: - // case DIK_NUMPAD5: - _moveKey = 0; - return true; - default: - return false; - } -} - -bool CStaticMap::OnKeyDown(int dikCode) -{ - const MapProperties &props = GetMapProperties(); - - switch (dikCode) - { - case DIK_ADD: - case DIK_SUBTRACT: - case DIK_NUMPAD1: - case DIK_NUMPAD2: - case DIK_NUMPAD3: - case DIK_NUMPAD4: - case DIK_NUMPAD6: - case DIK_NUMPAD7: - case DIK_NUMPAD8: - case DIK_NUMPAD9: - ClearAnimation(); - if (_moveKey != dikCode) - { - _moveKey = dikCode; - _moveStart = Glob.uiTime; - _moveLast = Glob.uiTime; - } - return true; - /* - case DIK_NUMPAD5: - Center(); - return true; - */ - case DIK_MULTIPLY: - _moveKey = 0; - float time; - if (props._scaleDefault > _scaleX) - time = log(props._scaleDefault / _scaleX); - else - time = log(_scaleX / props._scaleDefault); - ClearAnimation(); - AddAnimationPhase(time, props._scaleDefault, GetCenter()); - CreateInterpolator(); - return true; - default: - return false; - } -} - -void ExportWMF(const char *name, bool grid -#if _VBS3 - ,bool contour = true -#endif - ); - -void CStaticMap::ProcessCheats() -{ - if (GInput.CheatActivated() == CheatExportMap) - { - char buffer[256]; - sprintf(buffer, "C:\\%s.emf", Glob.header.worldname); - ExportWMF(buffer, true); - GInput.CheatServed(); - } -#if _ENABLE_CHEATS - if (GInput.GetCheat2ToDo(DIK_D)) - { - char buffer[256]; - sprintf(buffer, "C:\\%s.emf", Glob.header.worldname); - ExportWMF(buffer, true); - } - if (GInput.GetCheat2ToDo(DIK_F)) - { - char buffer[256]; - sprintf(buffer, "C:\\%s.emf", Glob.header.worldname); - ExportWMF(buffer, false); - } - /* - if (GInput.GetCheat1ToDo(DIK_V)) - { - _showCost = !_showCost; - } - */ - /* - if (GInput.GetCheat1ToDo(DIK_B)) - { - _showScale = !_showScale; - } - */ - if (GInput.GetCheat1ToDo(DIK_N)) - { - _show = !_show; - } - if (GInput.GetCheat1ToDo(DIK_W)) - { - switch (_infoClick._type) - { - case signUnit: - if (_infoClick._unit) - { - EntityAI *veh = _infoClick._unit->GetVehicle(); - if (veh) - { - GLOB_WORLD->SwitchCameraTo(veh, GLOB_WORLD->GetCameraType(), true); - GWorld->UI()->ResetHUD(); - } - } - break; - case signVehicle: - case signStatic: - if (_infoClick._id!=NULL) - { - GLOB_WORLD->SwitchCameraTo(_infoClick._id, GLOB_WORLD->GetCameraType(), true); - GWorld->UI()->ResetHUD(); - } - break; - } - } -#endif -} - -void CStaticMap::OnRButtonDown(float x, float y) -{ - _mouseWorld = ScreenToWorld(DrawCoord(x, y)); - _moving = true; -} - -void CStaticMap::OnRButtonUp(float x, float y) -{ - _moving = false; -} - -void CStaticMap::OnMouseHold(float x, float y, bool active) -{ - if (!_moving && IsInside(x, y)) - _infoMove = FindSign(x, y); -} - -void CStaticMap::OnMouseMove(float x, float y, bool active) -{ - if (_moving) - { - DrawCoord mouseMap = WorldToScreen(_mouseWorld); - _mapX += x - mouseMap.x; - SaturateX(_mapX); - _mapY += y - mouseMap.y; - SaturateY(_mapY); - } - else - { - OnMouseHold(x, y); - return; - } -} - -void CStaticMap::OnMouseZChanged(float dz) -{ - if (dz == 0) return; - - _moveKey = 0; - float scale = exp(0.1 * dz) * _scaleX; - SetScale(scale); -} - -void CStaticMap::ClearAnimation() -{ - _animation.Resize(0); - _animMatrices.Free(); - _animTimes.Free(); - _interpolator = NULL; -} - -void CStaticMap::AddAnimationPhase(float dt, float scale, Vector3Par pos) -{ - int i = _animation.Add(); - MapAnimationPhase &phase = _animation[i]; - if (i == 0) - { - _animationStart = Glob.uiTime; - _animationLast = Glob.uiTime; - phase.time = Glob.uiTime + dt; - } - else - { - phase.time = _animation[i - 1].time + dt; - } - phase.scale = scale; - phase.pos = pos; -} - -void CStaticMap::CreateInterpolator() -{ - int n = _animation.Size(); - - _animTimes.Realloc(n + 1); - _animMatrices.Realloc(n + 1); - Vector3 pos; - - pos = GetCenter(); - pos[1] = log(_scaleX); - _animTimes[0] = 0; - _animMatrices[0].SetPosition(pos); - _animMatrices[0].SetOrientation(M3Identity); - for (int i=0; iGetUserDefinedChartName().IsEmpty(); -#else - return false; -#endif -} - -bool CStaticMap::UserMapIsBeingDrawn() const -{ -#if _VBS3_UDEFCHART - return UserMapDrawing() && _showScale; -#else - return false; -#endif -} - -bool CStaticMap::UserMapDrawObjects() const -{ -#if _VBS3_UDEFCHART - return GWorld->GetDrawObjectsOnUserDefinedChart(); -#else - return false; -#endif -} - -void CStaticMap::SaturateScale(const MapProperties &props) -{ - if (_scaleX >= props._scaleMin && _scaleX <= props._scaleMax) - { - // _scaleX will not change - Precalculate(props); - SaturateX(_mapX); - SaturateY(_mapY); - return; - } - // saturation and Precalculate inside - SetScale(_scaleX); -} - -void CStaticMap::Precalculate(const MapProperties &props) -{ - // precalculates for increasing drawing speed - _wScreen = GLOB_ENGINE->Width2D(); - _hScreen = GLOB_ENGINE->Height2D(); - - float coef = _hScreen / _wScreen; - _scaleY = coef * _scaleX; - _invScaleX = 1.0 / _scaleX; - _invScaleY = 1.0 / _scaleY; - - // map area limits converted to 0 ... _invScale coordinates - _minX = 0; _maxX = _invScaleX; - _minY = 0; _maxY = _invScaleY; - float mapSize = LandGrid * LandRange; - float invMapSize = InvLandGrid * InvLandRange; - if (props._xMin > 0) _minX = props._xMin * invMapSize * _invScaleX; - if (props._xMax < mapSize) _maxX = props._xMax * invMapSize * _invScaleX; - if (props._zMin > 0) _maxY = (1.0f - props._zMin * invMapSize) * _invScaleY; - if (props._zMax < mapSize) _minY = (1.0f - props._zMax * invMapSize) * _invScaleY; - - _clipRect.x = _x * _wScreen; - _clipRect.y = _y * _hScreen; - _clipRect.w = _w * _wScreen; - _clipRect.h = _h * _hScreen; -} - -void CStaticMap::SaturateX(float &x) -{ - // try to limit shown area to the map size - float size = _maxX - _minX; - if (size < _w) x = -_minX + 0.5 * (_w - size); - else saturate(x, -(_maxX - _w), -_minX); -} - -void CStaticMap::SaturateY(float &y) -{ - // try to limit shown area to the map size - float size = _maxY - _minY; - if (size < _h) y = -_minY + 0.5 * (_h - size); - else saturate(y, -(_maxY -_h), -_minY); -} - -void CStaticMap::ScrollX(float dif) -{ - _mapX += dif; - SaturateX(_mapX); -} - -void CStaticMap::ScrollY(float dif) -{ - _mapY += dif; - SaturateY(_mapY); -} - -void CStaticMap::SetVisibleRect(float x, float y, float w, float h) -{ - _center.x = x - _x + 0.5 * w; // offset + 0.5 * width - _center.y = y - _y + 0.5 * h; // offset + 0.5 * height - _halfSize.x = 0.5 * w; - _halfSize.y = 0.5 * h; -} - -void CStaticMap::Center(Vector3Val pt, bool soft) -{ - float invSizeLand = 1.0 / (LandGrid * LandRange); - float xMap = pt.X() * invSizeLand * _invScaleX; - float yMap = (1.0 - pt.Z() * invSizeLand) * _invScaleY; - if (soft) - { - float mapX = _center.x - xMap; - float mapY = _center.y - yMap; - - saturate(_mapX, mapX - 0.5 * _halfSize.x, mapX + 0.5 * _halfSize.x); - saturate(_mapY, mapY - 0.5 * _halfSize.y, mapY + 0.5 * _halfSize.y); - } - else - { - _mapX = _center.x - xMap; - _mapY = _center.y - yMap; - } - SaturateX(_mapX); - SaturateY(_mapY); -} - -void CStaticMap::SetScale(float scale) -{ - const MapProperties &props = GetMapProperties(); - if (scale < 0) scale = props._scaleDefault; - - float mouseX = 0.5 + GInput.cursorX * 0.5; - float mouseY = 0.5 + GInput.cursorY * 0.5; - - saturate(mouseX, _x, _x + _w); - saturate(mouseY, _y, _y + _h); - - DrawCoord ptMap(mouseX, mouseY); - DrawCoord offset(mouseX - _x, mouseY - _y); - Vector3 pt = ScreenToWorld(ptMap); - - _scaleX = scale; - saturate(_scaleX, props._scaleMin, props._scaleMax); - Precalculate(props); - - float invSizeLand = 1.0 / (LandGrid * LandRange); - float xMap = pt.X() * invSizeLand * _invScaleX; - float yMap = (1.0 - pt.Z() * invSizeLand) * _invScaleY; - _mapX = offset.x - xMap; - _mapY = offset.y - yMap; - SaturateX(_mapX); - SaturateY(_mapY); -} - -int GetCursorIndex(RString cursorType) -{//returns cursotType of default textures - if(strcmp("Arrow",cursorType)==0) - return CursorArrow; - if(strcmp("Track",cursorType)==0) - return CursorTrack; - if(strcmp("Move",cursorType)==0) - return CursorMove; - if(strcmp("Scroll",cursorType)==0) - return CursorScroll; - if(strcmp("Watch",cursorType)==0) - return CursorWatch; - if(strcmp("Rotate",cursorType)==0) - return CursorRotate; -#if _VBS3 - if(strcmp"Drag",cursorType)==0) - return CursorDrag; - if(strcmp("Raise",cursorType)==0) - return CursorRaise; -#else - if(strcmp("Rotate3D",cursorType)==0) - return CursorRotate3D; - if(strcmp("Raise3D",cursorType)==0) - return CursorRaise3D; - if(strcmp("Move3D",cursorType)==0) - return CursorMove3D; - if(strcmp("Track3D",cursorType)==0) - return CursorTrack3D; -#endif - - return -1; -} - -void CStaticMap::SetOverrideCursor(RString cursorName, RString overrideTexture) -{ - //first try to open new texture... - ParamEntryVal entry = Pars>> "CfgWrapperUI" >> "Cursors"; - //... if new texture does not exist, use default texture name - if(!entry.FindEntry(overrideTexture)) - overrideTexture = cursorName; - - int index = GetCursorIndex(cursorName); - if(index>=0) - {//save new texture to array - _cursorMapOverride[index] = overrideTexture; - } - - //if changed cursor is the same we are using at the moment, change used texture - if(_parent && strcmp(_cursorName,cursorName)==0) - _parent->SetCursor(overrideTexture); -} - -RString CStaticMap::OverrideCursor(RString cursorName) -{ //save current cursor type - _cursorName = cursorName; - RString name; - int index = GetCursorIndex(cursorName); - - if(index>=0) name = _cursorMapOverride[index]; - //no override texture is prepared, so we use default - if(name.GetLength()<=0) name = cursorName; - - return name; -} - -RString CStaticMap::OverrideCursor(CursorType cursorType) -{ - RString name; - //if(cursorType>=0) - // name = _cursorMapOverride[cursorType]; - - //if(name.GetLength()<=0) - // name = cursorName; - return name; -} - -void CStaticMap::InitDefaultCenter() -{ - _defaultCenter.Init(); - _defaultCenter[0] = (Pars >> "CfgWorlds" >> Glob.header.worldname >> "centerPosition")[0]; - _defaultCenter[1] = 0; - _defaultCenter[2] = (Pars >> "CfgWorlds" >> Glob.header.worldname >> "centerPosition")[1]; - - _gridNumbersOverLines = Pars >> "CfgWorlds" >> Glob.header.worldname >> "gridNumbersOverLines"; - - _mapX = 0; - _mapY = 0; - - float sizeLand = LandGrid * LandRange; - saturate(_defaultCenter[0], 0, sizeLand); - saturate(_defaultCenter[2], 0, sizeLand); -} - -/////////////////////////////////////////////////////////////////////////////// -// Main (ingame) map - -CStatic *CreateStaticMapMain(ControlsContainer *parent, int idc, const ParamEntry &cls) -{ - CStaticMap *map = new CStaticMapMain(parent, idc, cls); - map->SetVisibleRect(map->X(), map->Y(), map->W(), map->H()); - map->Center(); - return map; -} - -#define EXPOSURE_COEF 50.0F - -#if _VBS2 -CStaticMapMain::CStaticMapMain - ( - ControlsContainer *parent, int idc, ParamEntryPar cls, - float scaleMin, float scaleMax, float scaleDefault - ) : CStaticMap(parent, idc, cls, scaleMin, scaleMax, scaleDefault), _autoCenter(false) -{ -} -#endif - -CStaticMapMain::CStaticMapMain(ControlsContainer *parent, int idc, ParamEntryPar cls) -#if _ENABLE_CHEATS - : CStaticMap(parent, idc, cls, 0.001, 1.0, 0.16) -#else - : CStaticMap(parent, idc, cls, 0.02, 1.0, 0.16) -#endif - , _autoCenter(false) -{ -#if _ENABLE_CHEATS - _showUnits = false; - _showTargets = false; - _showVariables = 0; -#endif - _activeMarker = -1; - - _infoCommand.Load(cls >> "Command"); - _infoTask.Load(cls >> "Task"); - _infoCustomMark.Load(cls >> "CustomMark"); - _colorActiveMarker = GetPackedColor(cls >> "ActiveMarker" >> "color"); - _sizeActiveMarker = cls >> "ActiveMarker" >> "size"; - - _iconPosition = GEngine->TextBank()->Load(GetPictureName(Pars >> "CfgInGameUI" >> "Cursor" >> "mission")); - -#if _VBS2 // conditional markers - _lastEvalMarkerConditions = UITime(0); -#endif - - _mapInfo.Clear(); - ShowScale(false); - _showScaleAlpha = 0.66f; - - _mouseClickHandled = false; -} - -void AddEnemyInfo - ( - TargetType *id, const VehicleType *type, int x, int z - ) -{ - if (!id) return; - DisplayMap *display = dynamic_cast(GWorld->Map()); - if (!display) return; - CStaticMapMain *map = display->GetMap(); - if (!map) return; - map->AddEnemyInfo(id, type, x, z); -} - -void CStaticMapMain::AddEnemyInfo - ( - TargetType *id, const VehicleType *type, int x, int z - ) -{ - Assert(id); - int index = -1; - for (int i=0; i<_mapInfo.enemyInfo.Size(); i++) - if (_mapInfo.enemyInfo[i].id == id) - { - index = i; break; - } - if (index < 0) index = _mapInfo.enemyInfo.Add(); - MapEnemyInfo &info = _mapInfo.enemyInfo[index]; - info.id = id; - info.type = type; - info.time = Glob.clock.GetTimeOfDay(); - if (info.time >= 1.0) info.time--; - info.time *= 24; - info.x = x; - info.z = z; -} - -LSError MapEnemyInfo::Serialize(ParamArchive &ar) -{ - CHECK(ar.SerializeRef("Target", id, 1)) - CHECK(::Serialize(ar, "type", type, 1)) - CHECK(ar.Serialize("time", time, 1)) - CHECK(ar.Serialize("x", x, 1)) - CHECK(ar.Serialize("z", z, 1)) - return LSOK; -} - -LSError MainMapInfo::Serialize(ParamArchive &ar) -{ - CHECK(ar.Serialize("EnemyInfo", enemyInfo, 1)) - return LSOK; -} - -void MainMapInfo::Clear() -{ - enemyInfo.Clear(); -} - -EntityAI *CStaticMapMain::GetTarget() const -{ - switch (_infoMove._type) - { - case signVehicle: - case signVehicleGroup: - case signStatic: - return _infoMove._id; - case signUnit: - if (_infoMove._unit) return _infoMove._unit->GetVehicle(); - return NULL; - } - return NULL; -} - -bool CStaticMapMain::GetPosition(Vector3 &pos) const -{ - float mouseX = 0.5 + GInput.cursorX * 0.5; - float mouseY = 0.5 + GInput.cursorY * 0.5; - - saturate(mouseX, _x, _x + _w); - saturate(mouseY, _y, _y + _h); - - DrawCoord ptMap(mouseX, mouseY); - pos = ScreenToWorld(ptMap); - pos[1] = GLandscape->SurfaceYAboveWater(pos[0], pos[2]); - - return true; -} - -LSError CStaticMapMain::Serialize(ParamArchive &ar, RString name, int minVersion) -{ - CHECK(ar.Serialize(name, _mapInfo, minVersion)) - return LSOK; -} - -void CStaticMapMain::DrawMarkers() -{ -#if _VBS2 // conditional markers - bool evalCondition = false; - if (Glob.uiTime - _lastEvalMarkerConditions > 0.5) - { - evalCondition = true; - _lastEvalMarkerConditions = Glob.uiTime; - } -#endif - int n = markersMap.Size(); - for (int i=0; i 0) - mInfo.isHidden = !_drawAttachedMarkers || !GWorld->GetGameState()->EvaluateBool(mInfo.condition, GameState::EvalContext::_default, GWorld->GetMissionNamespace()); - if (mInfo.attachCondition.GetLength() > 0) - { - if (!_drawConditionalMarkers) continue; - GameState *state = GWorld->GetGameState(); - - GameVarSpace vars(false); - int gshandle = state->BeginContext(&vars); - - GameValue value = state->CreateGameValue(GameArray); - GameArrayType &array = value; - array.Resize(mInfo.attachCtx.Size()); - for (int i=0; iVarSetLocal("_this", value, true); - - GameValue result = state->EvaluateMultiple(mInfo.attachCondition, GameState::EvalContext::_default, GWorld->GetMissionNamespace()); - if (!result.GetNil() && result.GetType() == GameObject) - mInfo.attachTo = dynamic_cast(result.GetData())->GetObject(); - - state->EndContext(gshandle); - } - } - if (mInfo.isHidden) continue; - if (mInfo.attachTo) - mInfo.position = mInfo.attachTo->WorldPosition(mInfo.attachTo->FutureVisualState()) + mInfo.attachOffset; -#endif - //set color and update alpha according to marker alpha property - PackedColor fadedMarkerColor = ModAlpha(mInfo.color,mInfo.alpha); - - switch (mInfo.markerType) - { - case MTIcon: - { - if (mInfo.size == 0) break; -#if _VBS2 // conditional markers - if (mInfo.layeredIcons.Size() > 0) - { - for (int i=0; iicon) continue; - RString text = i == 0 ? Localize(mInfo.text) : ""; - Vector3 pos = mInfo.position; - pos[0] += layeredIcon->x; - pos[2] += layeredIcon->y; - DrawSignAutosize - ( - layeredIcon->icon, mInfo.color, - mInfo.position, - mInfo.size * layeredIcon->a, mInfo.size * layeredIcon->b, - mInfo.angle * (H_PI / 180.0), text, true, NULL, -1, mInfo.autosize - ); - } - break; - } - if (!mInfo.icon) break; - DrawSignAutosize - ( - mInfo.icon, mInfo.color, - mInfo.position, - mInfo.size * mInfo.a, mInfo.size * mInfo.b, - mInfo.angle * (H_PI / 180.0), Localize(mInfo.text), true, NULL, -1, mInfo.autosize - ); -#else - if (!mInfo.icon) break; - DrawSign - ( - mInfo.icon, fadedMarkerColor, - mInfo.position, - mInfo.size * mInfo.a, mInfo.size * mInfo.b, - mInfo.angle * (H_PI / 180.0), Localize(mInfo.text),NULL,-1, mInfo.shadow - ); -#endif - } - break; - case MTRectangle: - FillRectangle - ( - mInfo.position, mInfo.a, mInfo.b, mInfo.angle * (H_PI / 180.0), - fadedMarkerColor, mInfo.fill - ); - if(mInfo.drawBorder) - DrawRectangle(mInfo.position, mInfo.a, mInfo.b, mInfo.angle * (H_PI / 180.0), - fadedMarkerColor); - break; - case MTEllipse: - FillEllipse - ( - mInfo.position, mInfo.a, mInfo.b, mInfo.angle * (H_PI / 180.0), - fadedMarkerColor, mInfo.fill - ); - if(mInfo.drawBorder) - DrawEllipse(mInfo.position, mInfo.a, mInfo.b, mInfo.angle * (H_PI / 180.0), - fadedMarkerColor); - break; - } - } -} - -/// helper will extract vehicle from the SignInfo -static EntityAI *GetVehicle(const SignInfo &info) -{ - switch (info._type) - { - case signUnit: - if (info._unit) return info._unit->GetVehicle(); - return NULL; - case signVehicle: - case signVehicleGroup: - case signStatic: - return info._id; - default: - return NULL; - } -} - -#if _ENABLE_CHEATS -Ref diagTarget; -static inline RString GetTargetInfo(const TargetNormal *target) -{ - Vector3 pos = target->LandAimingPosition(); - diagTarget = target; - return - Format(" seen %.1f", Glob.time.Diff(target->lastSeen)) + - Format(" posAge %.1f",Glob.time.Diff(target->posAccuracyTime)) + - Format(" prec %.1f", target->posAccuracy) + - Format(" dstRP %.1f", pos.Distance(target->idExact->AimingPosition(target->idExact->FutureVisualState()))) + - Format(" dstPos %.1f", pos.Distance(target->position)) + - Format(" sideAc %.1f", target->FadingSideAccuracy()) + - Format(" cost %.0f", target->subjectiveCost); -} - -static inline RString GetTargetModeInfo(AIBrain *unit) -{ - RString result; - - result = result + Format(" CM Major: %s", cc_cast(FindEnumName(unit->GetCombatModeMajor()))); - - result = result + Format(" CM: %s", cc_cast(FindEnumName(unit->GetCombatMode()))); - - return result; -} -#endif - -//to skip animals and civilians -bool CStaticMapMain::CheckItemWantedDraw(const TargetNormal *target) -{ - if(target->type->IsAnimal() || target->side == TCivilian) return false; - return true; -}; - -void CStaticMapMain::DrawLabel(struct SignInfo &info, PackedColor color, int shadow) -{ - // show info from the eyes of observer in Release version, use the player always in Retail -#if _ENABLE_CHEATS - EntityAI *observer = GetVehicle(_infoClick); - AIBrain *me = observer ? observer->CommanderUnit() : NULL; - if (!me) me = GetMyUnit(); -#else - AIBrain *me = GetMyUnit(); -#endif - - RString text; - Vector3 pos; - - EntityAI *vehicle = GetVehicle(info); - if (vehicle) - { -#if _ENABLE_CHEATS - if (_showUnits || CHECK_DIAG(DEFSM)) - { - AIBrain *unit = vehicle->CommanderUnit(); - text = vehicle->GetType()->GetDisplayName(); - if (unit && unit->GetPerson()) text = text + ": " + unit->GetPerson()->GetPersonName(); - if (CHECK_DIAG(DECombat)) - { - // display some additional informations about the target - const TargetList *list = me ? me->AccessTargetList() : NULL; - if (list) - { - const TargetNormal *target = list->FindTarget(vehicle); - if (target) text = text + GetTargetInfo(target); - } - } - } - else if (_showTargets) - { - const TargetList *list = me ? me->AccessTargetList() : NULL; - if (list) - { - const TargetNormal *target = list->FindTarget(vehicle); - if (target) - { - text = target->GetType()->GetDisplayName(); - pos = target->LandAimingPosition(); - // display some additional informations about the target - if (CHECK_DIAG(DECombat)) text = text + GetTargetInfo(target); - } - } - } - else -#endif - if (Glob.config.IsEnabled(DTMap) && !_miniMapMode) - { - const TargetList *list = me ? me->AccessTargetList() : NULL; - if (list) - { - const TargetNormal *target = list->FindTarget(vehicle); - if (target) - { - //skip animals and civilians - if(CheckItemWantedDraw(target)) - { - text = target->GetType()->GetDisplayName(); - pos = target->LandAimingPosition(); -#if _ENABLE_CHEATS - // display some additional informations about the target - if (CHECK_DIAG(DECombat)) text = text + GetTargetInfo(target); -#endif - } - } - } - } -#if _ENABLE_CHEATS - if (!CHECK_DIAG(DECombat) && CHECK_DIAG(DECombatMode)) - { - AIBrain *unit = vehicle->CommanderUnit(); - if (unit) text = text + GetTargetModeInfo(unit); - } -#endif - } - else switch (info._type) - { - case signNone: - break; -#if _ENABLE_IDENTITIES - case signTask: - if (info._unit) - { - Task *task = info._unit->GetPerson()->GetIdentity().FindTask(info._index); - if (task && task->GetDestination(pos)) - { - task->GetDescriptionHUD(text); - } - } - break; -#endif - } - - if (text.GetLength() > 0) CStaticMap::DrawLabel(pos, text, color, shadow); -} - -inline PackedColor CostToColor(float cost) -{ - static const float int1 = 1.0; - static const float invint1 = (1.0 / int1); - static const float int2 = 4.0; - static const float invint2 = (1.0 / int2); - static const float int12 = int1 + int2; - - static const float alpha = 0.5; - static const Color colorR(1, 0, 0, alpha); - static const Color colorG(0, 1, 0, alpha); - static const Color colorY(1, 1, 0, alpha); - - saturateMin(cost, int12); - if (cost <= int1) - { - return PackedColor - ( - colorY * (cost * invint1) + colorG * (1 - cost * invint1) - ); - } - else - { - cost -= int1; - return PackedColor - ( - colorR * (cost * invint2) + colorY * (1 - cost * invint2) - ); - } -} - -static float GetFieldCost(AIBrain *unit, int x, int z, bool road) -{ - GeographyInfo geogr = GLOB_LAND->GetGeography(x,z); - geogr.u.road = road; // if we are searching on road is now given externally - - EntityAI *uVeh = unit->GetVehicle(); - - float cost = 0; - if (uVeh) cost = uVeh->GetBaseCost(geogr, false, true) * uVeh->GetFieldCost(geogr) * uVeh->GetAirCost(x,z); - - if (cost <= 0) cost = 1; - cost *= LandGrid; // cost = time for distance == LandGrid - saturateMin(cost, SET_UNACCESSIBLE); // avoid inf. in cost - return cost; -} - -void CStaticMapMain::DrawCost(const MapProperties &props, AIBrain *unit, float invCost, - float x, float y, float xStep, float yStep, - int i, int j, int iStep, int jStep) -{ - GeographyInfo geogr = GLOB_LAND->GetGeography(i, j - 1); - - Draw2DParsNoTex pars; - - float cost; - if (iStep == 1 && jStep == -1) - { - // ALL - cost = GetFieldCost(unit, i, j + jStep, false) * invCost; - pars.SetColor(CostToColor(cost)); - } - else - { - // TL - cost = GetFieldCost(unit, i, j, false) * invCost; - pars.colorTL = CostToColor(cost); - // TR - cost = GetFieldCost(unit, i + iStep, j, false) * invCost; - pars.colorTR = CostToColor(cost); - // BL - cost = GetFieldCost(unit, i, j + jStep, false) * invCost; - pars.colorBL = CostToColor(cost); - // BR - cost = GetFieldCost(unit, i + iStep, j + jStep, false) * invCost; - pars.colorBR = CostToColor(cost); - } - - pars.spec = NoZBuf|IsAlpha|IsAlphaFog|NoClamp; - Rect2DPixel rect(x * _wScreen, y * _hScreen, xStep * _wScreen, yStep * _hScreen); - GEngine->Draw2D(pars, rect, _clipRect); - - // draw text information about the field - float tsize = xStep * floatMax(_sizeInfo,0.1f); - if (tsize >= 0.014f) - { - float ty = y; - - if (InRange(j - 1, i)) - { - const ObjectList &ol = GLOB_LAND->GetObjects(j - 1, i); - if (ol.GetList()) - { - bool cached = ol.GetList()->IsInList(); - GEngine->DrawTextF - ( - Point2DFloat(x, ty), tsize, - Rect2DFloat(x, y, xStep, yStep), - _fontInfo, props._colorNames, 0, - "Used %d%s", ol.GetList()->GetUsedCount()-cached, cached ? "+C" : "" - ); - ty += tsize; - } - - const MapObjectList &ml = GLOB_LAND->GetMapObjects(i, j - 1); - if (ml.GetList()) - { - bool cached = ml.GetList()->IsInList(); - GEngine->DrawTextF - ( - Point2DFloat(x, ty), tsize, - Rect2DFloat(x, y, xStep, yStep), - _fontInfo, props._colorNames, 0, - "MapUsed %d%s", ml.GetList()->GetUseCount()-cached, cached ? "+C" : "" - ); - ty += tsize; - } - } - - //float tsize = 0.2; - GEngine->DrawTextF - ( - Point2DFloat(x, ty), tsize, - Rect2DFloat(x, y, xStep, yStep), - _fontInfo, props._colorNames, 0, - "softObj %d", geogr.u.howManyObjects - ); - ty += tsize; - - if (geogr.u.howManyHardObjects>0) - { - GEngine->DrawTextF - ( - Point2DFloat(x, ty), tsize, - Rect2DFloat(x, y, xStep, yStep), - _fontInfo, props._colorNames, 0, - "hardObj %d", geogr.u.howManyHardObjects - ); - ty += tsize; - } - - GEngine->DrawTextF - ( - Point2DFloat(x, ty), tsize, - Rect2DFloat(x, y, xStep, yStep), - _fontInfo, props._colorNames, 0, - "grad %d", geogr.u.gradient - ); - ty += tsize; - - if (geogr.u.forest) - { - GEngine->DrawText - ( - Point2DFloat(x, ty), tsize, - Rect2DFloat(x, y, xStep, yStep), - _fontInfo, props._colorNames, - "forest",0 - ); - ty += tsize; - } - - if (geogr.u.road) - { - GEngine->DrawText - ( - Point2DFloat(x, ty), tsize, - Rect2DFloat(x, y, xStep, yStep), - _fontInfo, props._colorNames, - "Road",0 - ); - ty += tsize; - } - - if (geogr.u.minWaterDepth>0 || geogr.u.maxWaterDepth>0) - { - GEngine->DrawTextF( - Point2DFloat(x, ty), tsize, - Rect2DFloat(x, y, xStep, yStep), - _fontInfo, props._colorNames, 0, - "Water %d..%d",geogr.u.minWaterDepth,geogr.u.maxWaterDepth - ); - ty += tsize; - } - if (geogr.u.full) - { - GEngine->DrawText - ( - Point2DFloat(x, ty), tsize, - Rect2DFloat(x, y, xStep, yStep), - _fontInfo, props._colorNames, - "Square full",0 - ); - ty += tsize; - } - } - - if (iStep == 1 && jStep == -1) - { - float xTL = x * _wScreen, yTL = y * _hScreen; - float xBR = (x+xStep) * _wScreen, yBR = (y+yStep) * _hScreen; - - const RoadList &roadList = GLandscape->GetRoadNet()->GetRoadList(i, j - 1); - int n = roadList.Size(); - if (n > 0) - { - bool found = false; - for (int i=0; iNConnections(); j++) - { - if (!item->Connections()[j]) - { - found = true; - break; - } - } - if (found) break; - } - PackedColor color = PackedColor(found ? Color(1,.2,.2,1) : Color(1,1,1,1)); - GLOB_ENGINE->DrawLine - ( - Line2DPixel(xTL, yTL, xBR, yBR), - color, color, _clipRect - ); - GLOB_ENGINE->DrawLine - ( - Line2DPixel(xTL, yBR, xBR, yTL), - color, color, _clipRect - ); - } - - if (InRange(j - 1, i)) - { - const ObjectList &ol = GLOB_LAND->GetObjects(j - 1, i); - if (ol.GetList()) - { - bool cached = ol.GetList()->IsInList(); - bool locked = ol.GetList()->GetUsedCount()>int(cached); - PackedColor color = PackedColor(Color(0.1,0.8,0.1,0.85)); - if (cached && locked) - { - color = PackedColor(Color(0.25,0.25,0.7,0.75)); - } - else if (cached) - { - color = PackedColor(Color(0.25,0.25,0.25,0.75)); - } - else if (locked) - { - color = PackedColor(Color(0.7,0.1,0.1,0.85)); - } - GLOB_ENGINE->DrawLine - ( - Line2DPixel(xTL, (yTL*1.4+yBR*0.6)*0.5, xBR, (yTL*0.6+yBR*1.4)*0.5), - color, color, _clipRect - ); - GLOB_ENGINE->DrawLine - ( - Line2DPixel((xTL*1.4+xBR*0.6)*0.5, yBR, (xTL*0.6+xBR*1.4)*0.5, yTL), - color, color, _clipRect - ); - } - - const MapObjectList &ml = GLOB_LAND->GetMapObjects(i, j - 1); - if (ml.GetList()) - { - bool cached = ml.GetList()->IsInList(); - bool locked = ml.GetList()->GetUseCount()>int(cached); - PackedColor color = PackedColor(Color(0.1,0.8,0.1,0.85)); - if (cached && locked) - { - color = PackedColor(Color(0.25,0.25,0.7,0.75)); - } - else if (cached) - { - color = PackedColor(Color(0.25,0.25,0.25,0.75)); - } - else if (locked) - { - color = PackedColor(Color(0.7,0.1,0.1,0.85)); - } - GLOB_ENGINE->DrawLine - ( - Line2DPixel(xTL, (yTL+yBR)*0.5, xBR, (yTL+yBR)*0.5), - color, color, _clipRect - ); - GLOB_ENGINE->DrawLine - ( - Line2DPixel((xTL+xBR)*0.5, yBR, (xTL+xBR)*0.5, yTL), - color, color, _clipRect - ); - } - } - } - -} - -void CStaticMapMain::DrawInfo() -{ - float coef = 100.0; // width of field in global coord. - float invCoef = 0.01; // 1.0 / coef; - - float xFld = _invScaleX * invCoef; - float zFld = _invScaleY * invCoef; - - float tsize = xFld * _sizeInfo; - if (tsize < 0.022) return; - - int xFrom = toIntFloor(-_mapX * _scaleX * coef); - int zFrom = toIntFloor((_invScaleY - (_h - _mapY)) * _scaleY * coef); - int xTo = toIntFloor((_w - _mapX) * _scaleX * coef); - int zTo = toIntFloor((_invScaleY - (-_mapY)) * _scaleY * coef); - - float xBeg = _x + _mapX + xFrom * _invScaleX * invCoef; - float zBeg = _y + _mapY + (_invScaleY - zFrom * _invScaleY * invCoef); - - const MapProperties &props = GetMapProperties(); - - float zAct = zBeg; - for (int z = zFrom; z <= zTo; z++) - { - float xAct = xBeg; - for (int x = xFrom; x <= xTo; x++) - { - DrawInfo(props, xAct, zAct - zFld, xFld, zFld, x, z); - xAct += xFld; - } - zAct -= zFld; - } -} - -void CStaticMapMain::DrawInfo - ( - const MapProperties &props, float x, float y, float xStep, float yStep, int i, int j - ) -{ - static const int maxSubgroups = 3; - static const int maxEnemies = 3; - - float tsize = xStep * _sizeInfo; - float ty = y + 0.5 * (yStep - (maxSubgroups + 1) * tsize); - - int indices[maxEnemies]; - for (int l=0; lGetCost(); - float lCost = _mapInfo.enemyInfo[indices[l]].type->GetCost(); - if (kCost >= lCost) - { - for (int i=maxEnemies-1; i>l; i--) indices[i] = indices[i - 1]; - indices[l] = k; - break; - } - } - } - } - if (indices[0] >= 0) - { - float left = x; - float maxTime = 0; - for (int l=0; l= 60) - { - hour++; - minute -= 60; - } - GEngine->DrawTextF - ( - Point2DFloat(x, ty), tsize, - Rect2DFloat(x, y, xStep, yStep), - _fontInfo, _colorEnemy, 0, - "% 2d:%02d", hour, minute - ); - left += GEngine->GetTextWidthF(tsize, GetMapProperties()._fontNames, "% 2d:%02d", hour, minute); - float height = tsize; - float width = height * (_hScreen / _wScreen); - for (int l=0; lGetIcon(); - MipInfo mip = GEngine->TextBank()->UseMipmap(texture, 0, 0); - GEngine->Draw2D - ( - mip, _colorEnemy, - Rect2DPixel(left * _wScreen, ty * _hScreen, width * _wScreen, height * _hScreen), - Rect2DPixel(x * _wScreen, y * _hScreen, xStep * _wScreen, yStep * _hScreen) - ); - left += width; - } - ty += height; - } -} - -AIBrain *CStaticMapMain::GetMyUnit() -{ - return GWorld->FocusOn(); -} - -void CStaticMapMain::DrawCost() -{ - AIBrain *me = GetMyUnit(); - if (!me) return; - - const MapProperties &props = GetMapProperties(); - - GeographyInfo geogr(0); - float costNormal = me->GetVehicle()->GetBaseCost(geogr, false, true) - * me->GetVehicle()->GetFieldCost(geogr); - float invCost = 1.0 / (costNormal * LandGrid); - - float ptsLand = 800.0 * _invScaleX * InvLandRange; // avoid dependence on video resolution - float invPtsLand = 1.0 / ptsLand; - - int iStep = toIntCeil(_ptsPerSquareCost * invPtsLand); - float xStep = iStep * InvLandRange * _invScaleX; - int jStep = iStep; - float yStep = jStep * InvLandRange * _invScaleY; - int iMin = iStep * toIntFloor(-_mapX / xStep); - float xMin = _x - fastFmod(-_mapX, xStep); - int jMin = LandRange - jStep * toIntFloor(-_mapY / yStep); - float yMin = _y - fastFmod(-_mapY, yStep); - - float y = yMin; - int j = jMin; - while (y <= _y + _h) - { - float x = xMin; - int i = iMin; - while (x <= _x + _w) - { - // get geography info - DrawCost(props, me, invCost, x, y, xStep, yStep, i, j, iStep, -jStep); - i += iStep; - x += xStep; - } - j -= jStep; - y += yStep; - } -} - -PackedColor TempToColor(float temp, ParamEntryPar entry) -{ - if (entry.GetSize() != 4) - { - if (entry.GetSize() == 3) - { - int r8 = toInt(entry[0].GetFloat() * 255.0f); - int g8 = toInt(entry[1].GetFloat() * 255.0f); - int b8 = toInt(entry[2].GetFloat() * 255.0f); - saturate(r8, 0.0f, 255.0f); - saturate(g8, 0.0f, 255.0f); - saturate(b8, 0.0f, 255.0f); - return PackedColor(r8, g8, b8, 255.0f); - } - - // ErrorMessage("Config: '%s' not an ARGB color",(const char *)GetName()); - return PackedWhite; - } - - int r8 = toInt(entry[0].GetFloat() * 255.0f); - int g8 = toInt(entry[1].GetFloat() * 255.0f); - int b8 = toInt(entry[2].GetFloat() * 255.0f); - int a8 = toInt(entry[3].GetFloat() * 255.0f); - - //set temperature values - if (temp > 0.0f) - { - float ratio = temp / 80.0f; - saturate(ratio, 0.0f, 1.0f); - r8 = r8 + toInt(ratio * 255.0f); - float ratio1 = 1.0f - ratio; - g8 = toInt(entry[1].GetFloat() * 255.0f * ratio1); - b8 = toInt(entry[2].GetFloat() * 255.0f * ratio1); - } - else if (temp < 0.0f) - { - float ratio = -temp / 100.0f; - saturate(ratio, 0.0f, 1.0f); - b8 = b8 + toInt(ratio * 255.0f); - //float ratio1 = 1.0f - ratio1; - - r8 = toInt(entry[0].GetFloat() * 255.0f * ratio); - g8 = toInt(entry[1].GetFloat() * 255.0f * ratio); - } - - saturate(r8, 0.0f, 255.0f); - saturate(g8, 0.0f, 255.0f); - saturate(b8, 0.0f, 255.0f); - saturate(a8, 0.0f, 255.0f); - - return PackedColor(r8, g8, b8, a8); -} - -#if _ENABLE_CHEATS - -inline PackedColor AgeToColor(float age) -{ - static const float alpha = 0.5f; - static const float maxAge = 60.0f; - static const float invMaxAge = 1.0f / maxAge; - static const Color color0(0, 1, 0, alpha); - static const Color color1(1, 1, 0, alpha); - - if (age < 0) return PackedColor(Color(1, 0, 0, alpha)); - saturateMin(age, maxAge); - return PackedColor(color0 * (1.0f - age * invMaxAge) + color1 * (age * invMaxAge)); -} - -void CStaticMapMain::DrawOperCache(float x, float y, float xStep, float yStep, int i, int j, int iStep, int jStep) -{ - Draw2DParsNoTex pars; - - if (iStep == 1 && jStep == -1) - { - // ALL - const OperField *field = GLandscape->OperationalCache()->CheckField(LandIndex(i), LandIndex(j + jStep)); - if (field) - pars.SetColor(AgeToColor(field->GetAge())); - else - pars.SetColor(PackedColor(0)); - } - else - { - // TL - const OperField *field = GLandscape->OperationalCache()->CheckField(LandIndex(i), LandIndex(j)); - if (field) - pars.colorTL = AgeToColor(field->GetAge()); - else - pars.colorTL = PackedColor(0); - // TR - field = GLandscape->OperationalCache()->CheckField(LandIndex(i + iStep), LandIndex(j)); - if (field) - pars.colorTR = AgeToColor(field->GetAge()); - else - pars.colorTR = PackedColor(0); - // BL - field = GLandscape->OperationalCache()->CheckField(LandIndex(i), LandIndex(j + jStep)); - if (field) - pars.colorBL = AgeToColor(field->GetAge()); - else - pars.colorBL = PackedColor(0); - // BR - field = GLandscape->OperationalCache()->CheckField(LandIndex(i + iStep), LandIndex(j + jStep)); - if (field) - pars.colorBR = AgeToColor(field->GetAge()); - else - pars.colorBR = PackedColor(0); - } - - pars.spec = NoZBuf|IsAlpha|IsAlphaFog|NoClamp; - Rect2DPixel rect(x * _wScreen, y * _hScreen, xStep * _wScreen, yStep * _hScreen); - GEngine->Draw2D(pars, rect, _clipRect); -} - -void CStaticMapMain::DrawOperCache() -{ - float ptsLand = 800.0 * _invScaleX * InvLandRange; // avoid dependence on video resolution - float invPtsLand = 1.0 / ptsLand; - - int iStep = toIntCeil(_ptsPerSquareCost * invPtsLand); - if (iStep != 1) return; // draw diagnostics only when zoomed enough - float xStep = iStep * InvLandRange * _invScaleX; - int jStep = iStep; - float yStep = jStep * InvLandRange * _invScaleY; - int iMin = iStep * toIntFloor(-_mapX / xStep); - float xMin = _x - fastFmod(-_mapX, xStep); - int jMin = LandRange - jStep * toIntFloor(-_mapY / yStep); - float yMin = _y - fastFmod(-_mapY, yStep); - - float y = yMin; - int j = jMin; - while (y <= _y + _h) - { - float x = xMin; - int i = iMin; - while (x <= _x + _w) - { - DrawOperCache(x, y, xStep, yStep, i, j, iStep, -jStep); - i += iStep; - x += xStep; - } - j -= jStep; - y += yStep; - } -} - -void CStaticMapMain::DrawRoadNet(const MapProperties &props, float x, float y, float xStep, float yStep, int i, int j) -{ - AIBrain *me = GetMyUnit(); - Transport *veh = me ? me->GetVehicleIn() : NULL; - bool soldier = veh == NULL; - float vehWidth = 0; - if (veh) - { - LODShape *shape = veh->GetShape(); - if (shape) vehWidth = shape->Max().X() - shape->Min().X(); - } - - PackedColor color(Color(0, 1, 1, 1)); - float textSize = xStep * floatMax(_sizeInfo, 0.1f); - - const RoadList &roadList = GLandscape->GetRoadNet()->GetRoadList(i, j - 1); - for (int i=0; iNNodes(soldier); j++) - { - RoadNode node = item->GetNode(j); - if (!node.IsValid()) continue; - - Vector3 posB = node.Position(soldier, vehWidth); - DrawSign(_texturePath, color, posB, 4, 4, 0); - -#if 0 // nodes description - if (0.2f * textSize >= 0.01f) - { - DrawCoord pt = WorldToScreen(posB); - GEngine->DrawText(Point2DFloat(pt.x + 0.01, pt.y), 0.2f * textSize, Rect2DFloat(_x, _y, _w, _h), _fontInfo, _colorNames, cc_cast(node.GetDebugName())); - } -#endif - -#if 1 // draw connections - for (int k=0; k 0.01) - { - DrawArrow(posB, posB + 5 * dir, color); - } -#endif - } - - if (textSize >= 0.01f) - { - RString text; - if (item->IsBridge()) text = "Bridge - "; - else text = "Road - "; - switch (item->GetRoadType()) - { - case RoadLink::RTError: - text = text + "Error"; - break; - case RoadLink::RTDisconnected: - text = text + "Disconnected"; - break; - case RoadLink::RTBegin: - text = text + "Begin"; - break; - case RoadLink::RTEnd: - text = text + "End"; - break; - case RoadLink::RTI: - text = text + "I"; - break; - case RoadLink::RTTR: - text = text + "TR"; - break; - case RoadLink::RTTL: - text = text + "TL"; - break; - case RoadLink::RTX: - text = text + "X"; - break; - } - - DrawCoord pt = WorldToScreen(item->Transform().Position()); - GEngine->DrawText(Point2DFloat(pt.x + 0.01, pt.y), textSize, Rect2DFloat(_x, _y, _w, _h), _fontInfo, props._colorNames, text,0); - } - } -} - -void CStaticMapMain::DrawRoadNet() -{ - float ptsLand = 800.0 * _invScaleX * InvLandRange; // avoid dependence on video resolution - float invPtsLand = 1.0 / ptsLand; - - int iStep = toIntCeil(_ptsPerSquareCost * invPtsLand); - float xStep = iStep * InvLandRange * _invScaleX; - int jStep = iStep; - float yStep = jStep * InvLandRange * _invScaleY; - int iMin = iStep * toIntFloor(-_mapX / xStep); - float xMin = _x - fastFmod(-_mapX, xStep); - int jMin = LandRange - jStep * toIntFloor(-_mapY / yStep); - float yMin = _y - fastFmod(-_mapY, yStep); - - const MapProperties &props = GetMapProperties(); - - float y = yMin; - int j = jMin; - while (y <= _y + _h) - { - float x = xMin; - int i = iMin; - while (x <= _x + _w) - { - DrawRoadNet(props, x, y, xStep, yStep, i, j); - i += iStep; - x += xStep; - } - j -= jStep; - y += yStep; - } -} - -#endif - -void CStaticMapMain::DrawUnits() -{ -#if _ENABLE_INDEPENDENT_AGENTS - for (int i=0; iNAgents(); i++) - { - AIBrain *unit = GWorld->GetAgent(i); - if (!unit) continue; - if (!unit->GetVehicle()) continue; - PackedColor color; - switch (unit->GetSide()) - { - case TWest: - color = _colorFriendly; - break; - case TEast: - color = _colorEnemy; - break; - case TGuerrila: - color = _colorNeutral; - break; - default: - color = _colorCivilian; - break; - } - if (!unit->LSIsAlive()) color.SetA8(color.A8() / 2); - Vector3 dir = unit->GetVehicle()->RenderVisualState().Direction(); - float azimut = atan2(dir.X(), dir.Z()); - DrawSign( - unit->GetVehicle()->GetIcon(), color, - unit->Position(unit->GetRenderVisualState()), - _sizeUnit, _sizeUnit, azimut, RString(), false, -1, _shadow); - } -#endif // _ENABLE_INDEPENDENT_AGENTS -} - -void CStaticMapMain::DrawTargets(AIBrain *observerUnit, bool civilians) -{ - const TargetList *list = observerUnit ? observerUnit->AccessTargetList() : NULL; - if (list) - { - int n = list->AnyCount(); - for (int i=0; iGetAny(i); - if (!target->IsKnownBy(observerUnit) || target->vanished || target->destroyed) continue; - - const VehicleType *type = target->type; - if - ( - !type->IsKindOf(GWorld->Preloaded(VTypeAllVehicles)) && - !type->IsKindOf(GWorld->Preloaded(VTypeStrategic)) - ) continue; - - // visibility - float visible = target->FadingSpotability(); - if (visible <= 0.01) continue; - saturateMin(visible, 1); - - if (!civilians && !CheckItemWantedDraw(target)) continue; - // color - TargetSide side = target->side; - - PackedColor color; - /*if (observerUnit->IsFriendly(side)) - color = _colorFriendly; - else if (observerUnit->IsEnemy(side)) - color = _colorEnemy; - else if (observerUnit->IsNeutral(side)) - color = _colorNeutral; - else - color = _colorUnknown;*/ - switch (side) - { - case TWest: - { - color = _colorCivilian; - break; - } - case TEast: - { - color = _colorEnemy; - break; - } - case TGuerrila: - { - color = _colorFriendly; - break; - } - default: - { - color = _colorNeutral; - break; - } - } - color.SetA8(toIntFloor(color.A8() * visible)); - - Vector3 pos = target->LandAimingPosition(); - // azimut not used (known) for group targets - //Vector3 dir = VZero; // ??? - float azimut = atan2(target->dir.X(), target->dir.Z()); - DrawSign(target->type->GetIcon(), color, pos, _sizeUnit, _sizeUnit, azimut, RString(), NULL, -1, _shadow); - } - } -} - -void CStaticMapMain::DrawPath() -{ -#if _ENABLE_CHEATS - AIBrain *me = GetMyUnit(); - AIBrain *myPilot = me ? me->GetVehicle()->PilotUnit() : NULL; - if (!myPilot) return; - - Texture *texture = GPreloadedTextures.New(TextureDefault); - - const IAIPathPlanner &planner = myPilot->GetPlanner(); - DrawSign(texture, PackedColor(Color(1, 0, 0, 1)), planner.GetDestination(), 4, 4, 0); - - AutoArray array; - planner.GetClosedList(array); - for (int i=0; iDrawLine - ( - Line2DPixel(ptB.x * _wScreen, ptB.y * _hScreen, - ptE.x * _wScreen, ptE.y * _hScreen), - _colorMe, _colorMe, _clipRect - ); - */ - -} - -bool CStaticMapMain::CanCenter() -{ - if - ( -#if _ENABLE_CHEATS - _showUnits || _showTargets || -#endif - Glob.config.IsEnabled(DTMap) - ) return true; - - AIBrain *me = GetMyUnit(); - if (!me) return false; - - const VehicleType *type = me->GetVehicle()->GetType(); - return type->IsKindOf(GWorld->Preloaded(VTypeAir)) || type->IsKindOf(GWorld->Preloaded(VTypeTank)); -} - -#if _ENABLE_CHEATS -class DrawUpdateState -{ - CStaticMap *_map; - -public: - explicit DrawUpdateState(CStaticMap *map) : _map(map) {} - - bool operator () (Entity *obj) const - { - if (!obj->IsLocal() && !obj->GetNetworkId().IsNull()) - { - float age = Glob.time - obj->GetLastPositionUpdate(); - float size = 10.0 / (1.0 + age); - _map->DrawEllipse(obj->RenderVisualState().Position(), size, size, 0, PackedColor(Color(1, 0, 0, 1))); - - age = Glob.time - obj->GetLastGenericUpdate(); - size = 10.0 / (1.0 + age); - _map->DrawEllipse(obj->RenderVisualState().Position(), size, size, 0, PackedColor(Color(0.25, 0, 0.5, 1))); - - age = Glob.time - obj->GetLastDamageUpdate(); - size = 10.0 / (1.0 + age); - _map->DrawEllipse(obj->RenderVisualState().Position(), size, size, 0, PackedColor(Color(0, 0.5, 0.25, 1))); - } - return false; - } -}; -#endif - -#if _ENABLE_CHEATS -EntityAI *CStaticMapMain::GetObserver() const -{ - return GetVehicle(_infoClick); -} -#endif - -void CStaticMapMain::DrawExt(float alpha) -{ - //for(int i=0;iGetLandElevationOffset(); - for (int i=0; iGetLocations().Size(); i++) - GWorld->GetLocations()[i]->Draw(this,false,elevationOffset); - - AIBrain *me = GetMyUnit(); - -#if _ENABLE_CHEATS - EntityAI *observer = GetVehicle(_infoClick); - AIBrain *observerUnit = observer ? observer->CommanderUnit() : NULL; - if (!observerUnit) observerUnit = me; -#else - AIBrain *observerUnit = me; - //AIGroup *observerGroup = myGroup; - //AICenter *observerCenter = myCenter; -#endif - - DrawMarkers(); -#if _VBS3 // markers moved to CStaticMap - if (_onlyDrawMarkers) return; -#endif - -#if _ENABLE_IDENTITIES - if (me && me->GetPerson()) - { - const Identity &identity = me->GetPerson()->GetIdentity(); - - // simple tasks - const RefArray &tasks = identity.GetSimpleTasks(); - for (int i=0; iGetDestination(pos)) - { - float alpha = 0.5f; - if (task == identity.GetCurrentTask()) alpha = 1; - PackedColor color = ModAlpha(_infoTask.color, alpha); - Ref taskTexture = NULL; - switch (task->GetState()) - { - case TSAssigned: - { - taskTexture = _infoTask.icon; - break; - } - case TSSucceeded: - { - color = ModAlpha(_infoTask.colorDone, alpha); - taskTexture = _infoTask.iconDone; - break; - } - case TSCanceled: - { - color = ModAlpha(_infoTask.colorCanceled, alpha); - taskTexture = _infoTask.iconCanceled; - break; - } - case TSFailed: - { - color = ModAlpha(_infoTask.colorFailed, alpha); - taskTexture = _infoTask.iconFailed; - break; - } - case TSCreated: - case TSNone: - { - color = ModAlpha(_infoTask.colorCreated, alpha); - taskTexture = _infoTask.iconCreated; - break; - } - } - DrawSign(taskTexture, color, pos, _infoTask.size, _infoTask.size, 0); - } - } - - // custom mark - Vector3 pos; - if (identity.GetCustomMark(pos)) - { - DrawSign(_infoCustomMark.icon, _infoCustomMark.color, pos, _infoCustomMark.size, _infoCustomMark.size, 0); - } - } -#endif - -#if _ENABLE_CHEATS - if (CHECK_DIAG(DEUpdates)) - { - GWorld->ForEachVehicle(DrawUpdateState(this)); - } - if (_showUnits) - { - // draw camera positions on server - const AutoArray *identities = GetNetworkManager().GetIdentities(); - if (identities) for (int i=0; iSize(); i++) - { - int dpnid = identities->Get(i).dpnid; - Vector3 pos = GetNetworkManager().GetCameraPosition(dpnid); - if (pos.SquareSize() > 0.01) - { - DrawSign(_iconCamera, PackedColor(Color(0.8, 0.4, 0, 1)), pos, 24, 24, 0); - } - } - } - if (_showUnits || CHECK_DIAG(DEFSM)) - { - DrawUnits(); - } - else if (_showTargets) - { - DrawTargets(observerUnit, true); - } - else -#endif - if (Glob.config.IsEnabled(DTMap) && !_miniMapMode) - { - DrawTargets(observerUnit, false); - } - else DrawInfo(); - - // draw clicked unit (helpful for cheats) -#if _ENABLE_CHEATS - EntityAI *vehClick = GetVehicle(_infoClick); - if (vehClick) - { - PackedColor color(Color(1, 1, 1, 0.5)); - if (_showUnits) - { - // draw directly on the vehicle position - DrawSign(_iconPlayer, color, vehClick->RenderVisualState().Position(), _sizePlayer, _sizePlayer, 0); - } - else if (Glob.config.IsEnabled(DTMap) && !_miniMapMode) - { - const TargetList *list = observerUnit ? observerUnit->AccessTargetList() : NULL; - if (list) - { - const TargetNormal *target = list->FindTarget(vehClick); - if (target) - { - DrawSign(_iconPlayer, color, target->LandAimingPosition(), _sizePlayer, _sizePlayer, 0); - } - } - } - } -#endif - - // draw myself - if - ( -#if _ENABLE_CHEATS - _showUnits || -#endif - Glob.config.IsEnabled(DTMap) || _miniMapMode - ) - { - Object *myVehicle = NULL; - if (me) - { - myVehicle = me->GetVehicle(); - } - else if (GLOB_WORLD->CameraOn()) - { - myVehicle = GLOB_WORLD->CameraOn(); - } - - if (myVehicle) - { - Point3 pos = myVehicle->RenderVisualState().Position(); - PackedColor BlinkColor(PackedColor color1, PackedColor color2, float t); - PackedColor color = BlinkColor(_colorMe, _colorMe2, _blinkingSpeedMe * Glob.uiTime.toFloat()); - bool draw = DrawSign - ( - _iconPlayer, color, - pos, - _sizePlayer, _sizePlayer, 0 - ); - if (draw) - { - // draw orientation - Vector3 dir = myVehicle->RenderVisualState().Direction(); - dir[1] = 0; - dir.Normalize(); - DrawCoord ptB = WorldToScreen(pos); - DrawCoord ptE; - ptE.x = ptB.x + 0.02 * dir.X(); - ptE.y = ptB.y - 0.02 * dir.Z(); - GLOB_ENGINE->DrawLine - ( - Line2DPixel(ptB.x * _wScreen, ptB.y * _hScreen, - ptE.x * _wScreen, ptE.y * _hScreen), - color, color, _clipRect - ); - } - } - - } - else if (me) - { - const VehicleType *type = me->GetVehicle()->GetType(); - if - ( - type->IsKindOf(GWorld->Preloaded(VTypeAir)) || - type->IsKindOf(GWorld->Preloaded(VTypeTank)) - ) - { - PackedColor color = PackedColor(Color(0, 0, 0, 1)); - const float h1 = 4.0 * (1.0 / 480); - const float w1 = 4.0 * (1.0 / 640); - const float h2 = 8.0 * (1.0 / 480); - const float w2 = 8.0 * (1.0 / 640); - DrawCoord pt = WorldToScreen(me->Position(me->GetRenderVisualState())); - - float w = _wScreen; - float h = _hScreen; - - GEngine->DrawLine - ( - Line2DPixel(_clipRect.x, pt.y * h, (pt.x - w1) * w, pt.y * h), - color, color, _clipRect - ); - GEngine->DrawLine - ( - Line2DPixel((pt.x + w1) * w, pt.y * h, _clipRect.x + _clipRect.w, pt.y * h), - color, color, _clipRect - ); - GEngine->DrawLine - ( - Line2DPixel(pt.x * w, _clipRect.y, pt.x * w, (pt.y - h1) * h), - color, color, _clipRect - ); - GEngine->DrawLine - ( - Line2DPixel(pt.x * w, (pt.y + h1) * h, pt.x * w, _clipRect.y + _clipRect.h), - color, color, _clipRect - ); - MipInfo mip = GEngine->TextBank()->UseMipmap(_iconPosition, 0, 0); - GEngine->Draw2D - ( - mip, color, - Rect2DPixel(CX(pt.x - w2), CY(pt.y - h2), CW(2 * w2), CH(2 * h2)), _clipRect - ); - } - } - - // if (_showTargets || _showUnits || Glob.config.easyMode) - { - DrawLabel(_infoMove, _colorInfoMove,0); - } -#if _ENABLE_CHEATS - if (_showUnits) - { - // draw labels - // draw my path - AIBrain *myPilot = me ? me->GetVehicle()->PilotUnit() : NULL; - if (myPilot) - { - int n = myPilot->GetPlanner().GetPlanSize(); - int m = myPilot->GetPlanner().FindBestIndex(me->Position(me->GetRenderVisualState())); - Vector3 oldPos; - for (int i=0; iGetPlanner().GetPlanPosition(i, pos); - if (i > 0) DrawLine(oldPos, pos, _colorPathDone); - oldPos = pos; - DrawSign(_texturePathDone, _colorPathDone, pos, _sizePathDone, _sizePathDone, 0); - } - for (int i=m; iGetPlanner().GetPlanPosition(i, pos); - if (i > 0) DrawLine(oldPos, pos, _colorPath); - oldPos = pos; - DrawSign(_texturePath, _colorPath, pos, _sizePath, _sizePath, 0); - } - } - - if (CHECK_DIAG(DEZombie)) - { - const AutoArray &fsms = GWorld->GetFSMs(); - for (int i=0; iGetVars(); - if (!vars) continue; - - Object *GetObject(GameValuePar oper); - - GameValue value; - if (!vars->VarGet("_agent", value)) continue; - Object *agent = GetObject(value); - if (!agent) continue; - - Vector3Val pos = agent->FutureVisualState().Position(); - CStaticMap::DrawLabel(pos, fsm->GetStateName(), PackedWhite, false); - - Object *target = NULL; - if (vars->VarGet("_target", value)) target = GetObject(value); - if (target) - { - Vector3Val posTarget = target->FutureVisualState().Position(); - DrawArrow(pos, posTarget, PackedBlack); - } - - } - } - } -#endif - - if (_activeMarker >= 0) - { - const float rectH2 = 0.5 * _sizeActiveMarker * _hScreen * (1.0 / 480); - const float rectW2 = 0.5 * _sizeActiveMarker * _wScreen * (1.0 / 640); - ArcadeMarkerInfo &mInfo = markersMap[_activeMarker]; - DrawCoord pt = WorldToScreen(mInfo.position); - pt.x *= _wScreen; - pt.y *= _hScreen; - GEngine->DrawLine - ( - Line2DPixel(pt.x - rectW2, pt.y - rectH2, pt.x + rectW2, pt.y - rectH2), - _colorActiveMarker, _colorActiveMarker, _clipRect - ); - GEngine->DrawLine - ( - Line2DPixel(pt.x + rectW2, pt.y - rectH2, pt.x + rectW2, pt.y + rectH2), - _colorActiveMarker, _colorActiveMarker, _clipRect - ); - GEngine->DrawLine - ( - Line2DPixel(pt.x + rectW2, pt.y + rectH2, pt.x - rectW2, pt.y + rectH2), - _colorActiveMarker, _colorActiveMarker, _clipRect - ); - GEngine->DrawLine - ( - Line2DPixel(pt.x - rectW2, pt.y + rectH2, pt.x - rectW2, pt.y - rectH2), - _colorActiveMarker, _colorActiveMarker, _clipRect - ); - GEngine->DrawLine - ( - Line2DPixel(_clipRect.x, pt.y, pt.x - rectW2, pt.y), - _colorActiveMarker, _colorActiveMarker, _clipRect - ); - GEngine->DrawLine - ( - Line2DPixel(pt.x + rectW2, pt.y, _clipRect.x + _clipRect.w, pt.y), - _colorActiveMarker, _colorActiveMarker, _clipRect - ); - GEngine->DrawLine - ( - Line2DPixel(pt.x, _clipRect.y, pt.x, pt.y - rectH2), - _colorActiveMarker, _colorActiveMarker, _clipRect - ); - GEngine->DrawLine - ( - Line2DPixel(pt.x, pt.y + rectH2, pt.x, _clipRect.y + _clipRect.h), - _colorActiveMarker, _colorActiveMarker, _clipRect - ); - } - -#if _ENABLE_CHEATS - if (_showVariables > 0) - { - const VarBankType *vars = NULL; - switch (_showVariables) - { - case 1: - vars = &GWorld->GetMissionNamespace()->GetVariables(); // mission namespace - break; - case 2: - { - Person *body = observerUnit->GetPerson(); - if (body) - { - GameVarSpace *varSpace = body->GetVars(); - if (varSpace) vars = &varSpace->GetVariables(); - } - } - break; - case 3: - { - Transport *vehicle = observerUnit->GetVehicleIn(); - if (vehicle) - { - GameVarSpace *varSpace = vehicle->GetVars(); - if (varSpace) vars = &varSpace->GetVariables(); - } - } - break; - } - - if (vars && vars->NItems() > 0) - { - float top = _y + 0.2; - float left = _x + 0.02; - // !!! avoid GetTable when NItems == 0 - for (int i=0; iNTables(); i++) - { - for (int j=0; jGetTable(i).Size(); j++) - { - GameVariable &var = vars->GetTable(i)[j]; - if (GWorld->GetGameState()->IsVisible(var)) continue; - GLOB_ENGINE->DrawTextF - ( - Point2DFloat(left, top), _sizeLabel, _fontLabel, PackedColor(Color(0, 0, 0, 1)), 0, - "%s = %s", - (const char *)var.GetName(), - (const char *)var.GetValueText() - ); - top += _sizeLabel; - } - } - } - } -#endif - - DrawLegend(); -} - -// simulation -void CStaticMapMain::Center(bool soft) -{ - Point3 pt = _defaultCenter; - if (GLOB_WORLD->FocusOn()) - pt = GLOB_WORLD->FocusOn()->Position(GLOB_WORLD->FocusOn()->GetRenderVisualState()); - else if (GLOB_WORLD->CameraOn()) - pt = GLOB_WORLD->CameraOn()->RenderVisualState().Position(); - CStaticMap::Center(pt, soft); -} - -void CStaticMapMain::CenterMiniMap() -{ - const MapProperties &props = GetMapProperties(); - - Point3 pt = _defaultCenter; - float maxSpeed = 0; - Vector3 vspeed(VZero); - if (GLOB_WORLD->FocusOn()) - { - pt = GLOB_WORLD->FocusOn()->Position(GLOB_WORLD->FocusOn()->GetRenderVisualState()); - EntityAI *entity = GLOB_WORLD->FocusOn()->GetVehicle(); - if (entity) - { - maxSpeed = entity->GetType()->GetMaxSpeedMs(); - vspeed = entity->RenderVisualState().Speed(); - } - } - saturateMax(maxSpeed, 0.1f); - float speed = vspeed.Size(); - const float timeCoef = 30.0f; //we want to see timeCoef * speed map location - const float minSpeed = 7.0f; - bool centralizeOnly = false; - if (speed < minSpeed) - { - speed = minSpeed; - centralizeOnly = true; //no map scaling nor player icon moving - } - - float invSizeLand = 1 / (LandGrid * LandRange); - //_scaleX is set so that map width corresponds to speed*timeCoef length in world space - _scaleX = timeCoef * speed * invSizeLand / W(); - saturate(_scaleX, props._scaleMin, props._scaleMax); - Precalculate(props); - - float xMap = pt.X() * invSizeLand * _invScaleX; - float yMap = (1.0 - pt.Z() * invSizeLand) * _invScaleY; - _mapX = _center.x - xMap; - _mapY = _center.y - yMap; - if (!centralizeOnly) - { - //shift the map in such a way, player is on elipse around map center (diameter given by speed / maxSpeed) - float speedXZ = vspeed.SizeXZ(); - if (speedXZ > minSpeed) //for slow movement no effect - { - const float maxDiamCoef = 0.75f; //75% - float speedCoef = (speed-minSpeed) / maxSpeed; - saturateMin(speedCoef,1.0f); - float sinus = vspeed.Z() / speedXZ; - float cosinus = vspeed.X() / speedXZ; - _mapX -= cosinus * maxDiamCoef * speedCoef * _halfSize.x; - _mapY += sinus * maxDiamCoef * speedCoef * _halfSize.y; - } - } - SaturateX(_mapX); - SaturateY(_mapY); -} - -void CStaticMapMain::OnDraw(UIViewport *vp, float alpha) -{ - if (_autoCenter) Center(false); - CStaticMap::OnDraw(vp, alpha); -} - -void CStaticMapMain::FindUnit(Vector3Par pt, SignInfo &info, float &minDist) -{ -#if _ENABLE_INDEPENDENT_AGENTS - for (int i=0; iNAgents(); i++) - { - AIBrain *unit = GWorld->GetAgent(i); - if (!unit) continue; - float dist = (pt - unit->Position(unit->GetRenderVisualState())).SquareSizeXZ(); - if (dist < minDist) - { - minDist = dist; - info._type = signUnit; - info._unit = unit; - } - } -#endif // _ENABLE_INDEPENDENT_AGENTS -} - -void CStaticMapMain::FindTarget(Vector3Par pt, SignInfo &info, float &minDist, AIBrain *observerUnit, bool civilians) -{ - const TargetList *list = observerUnit ? observerUnit->AccessTargetList() : NULL; - if (list) - { - int n = list->AnyCount(); - for (int i=0; iGetAny(i); - if (!target->IsKnownBy(observerUnit) || target->vanished || target->destroyed) continue; - - // visibility - float visible = target->FadingSpotability(); - if (visible <= 0.01) continue; - - if (!civilians && !CheckItemWantedDraw(target)) continue; - - float dist = (pt - target->LandAimingPosition()).SquareSizeXZ(); - if (dist < minDist) - { - if (target->type->IsKindOf(GWorld->Preloaded(VTypeStrategic))) - { - minDist = dist; - info._type = signStatic; - info._id = target->idExact; - } - else if (target->type->IsKindOf(GWorld->Preloaded(VTypeAllVehicles))) - { - minDist = dist; - info._type = signVehicleGroup; - info._id = target->idExact; - } - } - } - } -} - -SignInfo CStaticMapMain::FindSign(float x, float y) -{ - AIBrain *me = GetMyUnit(); - - struct SignInfo info; - info._type = signNone; - info._unit = NULL; - info._id = NULL; - -#if _ENABLE_CHEATS - EntityAI *observer = GetVehicle(_infoClick); - AIBrain *observerUnit = observer ? observer->CommanderUnit() : NULL; - if (!observerUnit) observerUnit = me; -#else - AIBrain *observerUnit = me; -#endif - - Point3 pt = ScreenToWorld(DrawCoord(x, y)); - float sizeLand = LandGrid * LandRange; - float dist, minDist = 0.02 * sizeLand * _scaleX; - minDist *= minDist; - -#if _ENABLE_CHEATS - if (_showUnits) - { - FindUnit(pt, info, minDist); - } - else if (_showTargets) - { - FindTarget(pt, info, minDist, observerUnit, true); - } -#endif - if (Glob.config.IsEnabled(DTMap) && !_miniMapMode) - { - FindTarget(pt, info, minDist, observerUnit, false); - } - - // check tasks -#if _ENABLE_IDENTITIES - if (me) - { - const Identity &identity = me->GetPerson()->GetIdentity(); - - // custom mark - Vector3 pos; - if (identity.GetCustomMark(pos)) - { - float dist = (pt - pos).SquareSizeXZ(); - if (dist < minDist) - { - minDist = dist; - info._type = signCustomMark; - info._unit = me; - } - } - - // simple tasks - const RefArray &tasks = identity.GetSimpleTasks(); - for (int i=0; iGetDestination(pos)) - { - float dist = (pt - pos).SquareSizeXZ(); - if (dist < minDist) - { - minDist = dist; - info._type = signTask; - info._unit = me; - info._index = task->GetId(); - } - } - } - } -#endif - - // check markers - int n = markersMap.Size(); - for (int i=0; i0; -} - -#if _ENABLE_IDENTITIES -/// in-game navigate to the given diary topic, open a diary if needed - -void ProcessDiaryLink(RString link, DisplayMap *map) -{//need to find better solution - DisplayMainMap *mapIngame = dynamic_cast(map); - - if (mapIngame) - { - GWorld->ShowMap(true); - mapIngame->ProcessDiaryLink(link, DCInGame); - } - else - { - DisplayGetReady *readyMap = dynamic_cast(map); - if (readyMap) - { - readyMap->ProcessDiaryLink(link, DCBriefing); - } - } -} - -void ProcessDiaryLink(RString link) -{ - ProcessDiaryLink(link, dynamic_cast(GWorld->Map())); -} - - -#endif - -bool CStaticMapMain::OnKeyDown(int dikCode) -{ - if (dikCode == 0) return false; - - if (CStaticMap::OnKeyDown(dikCode)) - return true; - - switch (dikCode) - { - case INPUT_DEVICE_XINPUT + XBOX_RightTrigger: - { - float mouseX = 0.5 + GInput.cursorX * 0.5; - float mouseY = 0.5 + GInput.cursorY * 0.5; - saturate(mouseX, 0, 1); - saturate(mouseY, 0, 1); - - bool alt = IsWatchRequired(); - IssueCommand(mouseX, mouseY, alt, false); - } - return true; - case DIK_DELETE: - if (_infoMove._type == signArcadeMarker) - { - const char *userDefined = "_user_defined"; - RString name = markersMap[_infoMove._index].name; - if (strnicmp(name, userDefined, strlen(userDefined)) == 0) - { -#if _VBS3 // marker EH - void ProcessDeleteMarkerEH(RString name); - ProcessDeleteMarkerEH(name); -#endif - GetNetworkManager().MarkerDelete(name); - markersMap.Delete(_infoMove._index); - _infoClick._type = signNone; - _infoClickCandidate._type = signNone; - _infoMove._type = signNone; - _dragging = false; - _selecting = false; - } - return true; - } - // continue - case INPUT_DEVICE_XINPUT + XBOX_X: -#if _ENABLE_IDENTITIES - if (_infoMove._type == signCustomMark) - { - Person *person = _infoMove._unit ? _infoMove._unit->GetPerson() : NULL; - if (person) - { - person->GetIdentity().ClearCustomMark(); - _infoClick._type = signNone; - _infoClickCandidate._type = signNone; - _infoMove._type = signNone; - _dragging = false; - _selecting = false; - } - return true; - } -#endif - return true; - case INPUT_DEVICE_XINPUT + XBOX_Y: -#if _ENABLE_IDENTITIES - { - AIBrain *me = GetMyUnit(); - Person *person = me ? me->GetPerson() : NULL; - if (person) - { - float mouseX = 0.5 + GInput.cursorX * 0.5; - float mouseY = 0.5 + GInput.cursorY * 0.5; - saturate(mouseX, 0, 1); - saturate(mouseY, 0, 1); - Vector3 pos = ScreenToWorld(DrawCoord(mouseX, mouseY)); - pos[1] = GLandscape->SurfaceYAboveWater(pos[0],pos[2]); - person->GetIdentity().SetCustomMark(pos); - } - - } -#endif - return true; - case INPUT_DEVICE_XINPUT + XBOX_A: -#if _ENABLE_IDENTITIES - if (_infoMove._type == signTask) - { - RString link = Format("task:%d", _infoClick._index); - ProcessDiaryLink(link); - return true; - } -#endif - return true; - } - return false; -} - -void CStaticMapMain::ProcessCheats() -{ -#if _ENABLE_CHEATS - if (GInput.GetCheat1ToDo(DIK_A) || GInput.GetCheatXToDo(CXTMapShowUnits)) - { - _showUnits = !_showUnits; - GlobalShowMessage(500,"Show Units %s",_showUnits ? "On" : "Off"); - } - if (GInput.GetCheat1ToDo(DIK_D)) - { - _showTargets = !_showTargets; - GlobalShowMessage(500,"Show Targets %s",_showTargets ? "On" : "Off"); - } - if (GInput.GetCheat2ToDo(DIK_V)) - { - _showVariables++; - if (_showVariables > 3) _showVariables = 0; - switch (_showVariables) - { - case 0: - GlobalShowMessage(500,"No variables"); break; - case 1: - GlobalShowMessage(500,"Global variables"); break; - case 2: - GlobalShowMessage(500,"Person's variables"); break; - case 3: - GlobalShowMessage(500,"Vehicle's variables"); break; - } - } -#endif - CStaticMap::ProcessCheats(); -} - -void CStaticMapMain::OnLButtonDown(float x, float y) -{ - _mouseClickHandled = false; - - _infoClick = FindSign(x, y); -#if _ENABLE_IDENTITIES - switch (_infoClick._type) - { - case signCustomMark: - { - _dragging = true; - _lastPos = ScreenToWorld(DrawCoord(x, y)); - } - } -#endif -} - -void CStaticMapMain::OnRButtonDown(float x, float y) -{ - CStaticMap::OnRButtonDown(x,y); -} - - -extern GameValue GMapOnSingleClick; -extern GameValue GMapOnSingleClickParams; - -void CStaticMapMain::IssueCommand(float x, float y, bool alt, bool shift) -{ - bool issueCommand = true; - - bool eventHandlerValid = !GMapOnSingleClick.GetNil(); - if (eventHandlerValid) - { -#if USE_PRECOMPILATION - if (GMapOnSingleClick.GetType() == GameCode) - { - GameDataCode *code = static_cast(GMapOnSingleClick.GetData()); - eventHandlerValid = code->IsCompiled() && code->GetCode().Size() > 0; - } - else -#endif - { - RString code = GMapOnSingleClick; - eventHandlerValid = code.GetLength() > 0; - } - } - - if (eventHandlerValid) - { - Vector3 pos = ScreenToWorld(DrawCoord(x, y)); - GameState *state = GWorld->GetGameState(); - - GameValue posValue = state->CreateGameValue(GameArray); - GameArrayType &posArray = posValue; - posArray.Realloc(3); - posArray.Add(pos[0]); - posArray.Add(pos[2]); - posArray.Add(pos[1]-GLandscape->SurfaceYAboveWater(pos[0],pos[2])); - - GameVarSpace vars(false); - int gshandle = state->BeginContext(&vars); - state->VarSetLocal("_pos",posValue,true); - state->VarSetLocal("_alt",alt,true); - state->VarSetLocal("_shift",shift,true); - state->VarSetLocal("_this", GMapOnSingleClickParams, true); -#if USE_PRECOMPILATION - if (GMapOnSingleClick.GetType() == GameCode) - { - GameDataCode *code = static_cast(GMapOnSingleClick.GetData()); - issueCommand = !state->EvaluateBool(code->GetString(), code->GetCode(), GameState::EvalContext::_default, GWorld->GetMissionNamespace()); // mission namespace - } - else -#endif - { - // make sure string is not destructed while being evaluated - RString code = GMapOnSingleClick; - issueCommand = !state->EvaluateMultipleBool(code, GameState::EvalContext::_default, GWorld->GetMissionNamespace()); // mission namespace - } - state->EndContext(gshandle); - } - - if (issueCommand) - { -#if _ENABLE_IDENTITIES - if (shift) - { - AIBrain *me = GetMyUnit(); - Person *person = me ? me->GetPerson() : NULL; - if (person) - { - Vector3 pos = ScreenToWorld(DrawCoord(x, y)); - pos[1] = GLandscape->SurfaceYAboveWater(pos[0],pos[2]); - person->GetIdentity().SetCustomMark(pos); - } - } -#endif - } -} - -void CStaticMapMain::OnLButtonClick(float x, float y) -{ - if(_mouseClickHandled) - { - _mouseClickHandled = false; - return; - } - if (!_dragging) - { -#if _ENABLE_CHEATS && USER_Ondra - //not desired for DayZ, but may be useful for debugging - bool alt = IsWatchRequired(); - bool shift = GInput.keys[DIK_LSHIFT]>0; - IssueCommand(x, y, alt, shift); -#endif - } -} - -void CStaticMapMain::OnLButtonDblClick(float x, float y) -{ -# if _ENABLE_IDENTITIES - // double click on the task icon -> find the task in the diary - if (_infoClick._type == signTask) - { - RString link = Format("task:%d", _infoClick._index); - ProcessDiaryLink(link, dynamic_cast(_parent.GetLink())); - return; - } -# endif // _ENABLE_IDENTITIES - - if (dynamic_cast(_parent.GetLink())) - _parent->CreateChild(new DisplayInsertMarker(_parent, x, y, _x, _y, _w, _h, _parent->SimulationEnabled())); -} - -void CStaticMapMain::OnLButtonUp(float x, float y) -{ - if (_dragging) - { - _dragging = false; - } -} - - -void CStaticMapMain::OnMouseHold(float x, float y, bool active) -{ - if (_dragging) - { -#if _ENABLE_IDENTITIES - if (_infoClick._type == signCustomMark) - { - Person *person = _infoMove._unit ? _infoMove._unit->GetPerson() : NULL; - if (person) - { - Vector3 pos; - if (person->GetIdentity().GetCustomMark(pos)) - { - Vector3 curPos = ScreenToWorld(DrawCoord(x, y)); - Vector3 offset = curPos - _lastPos; - - pos = pos + offset; - pos[1] = GLOB_LAND->RoadSurfaceYAboveWater(pos[0], pos[2]); - person->GetIdentity().SetCustomMark(pos); - - _lastPos = curPos; - } - } - } -#endif - } - - CStaticMap::OnMouseHold(x, y); -} - -void CStaticMapMain::OnMouseMove(float x, float y, bool active) -{ - CStaticMap::OnMouseMove(x, y); -} - -void CStaticMapMain::OnMouseZChanged(float dz) -{ - CStaticMap::OnMouseZChanged(dz); -} - -/////////////////////////////////////////////////////////////////////////////// -// Main Map display - -WeatherState GetWeatherState(float overcast) -{ - if (overcast < 0.2) return WSClear; - else if (overcast < 0.4) return WSCloudly; - else if (overcast < 0.6) return WSOvercast; - else if (overcast < 0.8) return WSRainy; - else return WSStormy; -} - -static const EnumName ObjectiveStatusNames[]= -{ - EnumName(OSActive, "ACTIVE"), - EnumName(OSDone, "DONE"), - EnumName(OSFailed, "FAILED"), - EnumName(OSHidden, "HIDDEN"), - EnumName() -}; - -template<> -const EnumName *GetEnumNames(ObjectiveStatus dummy) -{ - return ObjectiveStatusNames; -} - -#include "../saveVersion.hpp" - - -class TextToHTMLParser : public SAXParser -{ -protected: - CHTMLContainer *_html; - int _section; - -public: - TextToHTMLParser(CHTMLContainer *html, int section); - void OnStartElement(RString name, XMLAttributes &attributes); - void OnEndElement(RString name); - void OnCharacters(RString chars); -}; - -TextToHTMLParser::TextToHTMLParser(CHTMLContainer *html, int section) - : _html(html), _section(section) -{ -} - -void TextToHTMLParser::OnStartElement(RString name, XMLAttributes &attributes) -{ - if (strcmp(name, "br") == 0) - { - _html->AddBreak(_section, false); - } - else - { - RptF("Unknown text element '%s'", (const char *)name); - } -} - -void TextToHTMLParser::OnEndElement(RString name) -{ -} - -void TextToHTMLParser::OnCharacters(RString chars) -{ - _html->AddText(_section, chars, HFP, HALeft, false, false, RString()); -} - -class DisplayInventory : public Display -{ -protected: - OLinkPermNO(AIBrain) _unit; - Ref _targetContainer; - - // drag & drop info - OLinkPermO(InventoryItem) _dragItem; - bool _dragRotated; - float _dragOffsetX, _dragOffsetY; - float _dragGridW, _dragGridH; - float _dragZ; - PackedColor _dragColorNone; - PackedColor _dragColorMove; - PackedColor _dragColorCraft; - PackedColor _dragColorSwap; - - OLinkPermO(InventoryItem) _swapItem; - - enum DragAction - { - DANone = 0, - DAMove, - DACraft, - DASwap - }; - - // tooltip drawing - float _tooltipHeight; - float _tooltipImageWidth; - float _tooltipTextWidth; - float _tooltipTextSize; - PackedColor _tooltipBgColor; - PackedColor _tooltipLineColor; - - // extension of menu item for an Inventory item action - class MenuItemAction : public MenuItem - { - private: - OLinkPermO(InventoryItem) _item; - Ref _action; - DisplayInventory *_parent; - - public: - MenuItemAction(AIBrain *unit, InventoryItem *item, Action *action, DisplayInventory *parent); - void Invoke(AIBrain *unit); - }; - class MenuItemRecipe : public MenuItem - { - private: - OLinkPermO(InventoryItem) _item1, _item2; - const Recipe *_recipe; - - public: - MenuItemRecipe(AIBrain *unit, InventoryItem *item1, InventoryItem *item2, const Recipe *recipe); - void Invoke(AIBrain *unit); - }; - class MenuItemAddItem : public MenuItem - { - private: - OLinkPermO(InventoryItem) _item1, _item2; - - public: - MenuItemAddItem(InventoryItem *item1, InventoryItem *item2, bool attachment); - void Invoke(AIBrain *unit); - }; - class MenuItemSwapItems : public MenuItem - { - private: - OLinkPermO(InventoryItem) _item1, _item2; - - public: - MenuItemSwapItems(InventoryItem *item1, InventoryItem *item2); - void Invoke(AIBrain *unit); - }; - enum MenuCommands - { - MCAction, - MCRecipe, - MCSwap, - MCWait, // wait while menu is loaded over network - MCAdd - }; - - static int _instances; - -public: - DisplayInventory(ControlsContainer *parent, AIBrain *me, EntityAI *source); - ~DisplayInventory(); - - Control *OnCreateCtrl(int type, int idc, ParamEntryPar cls); - ControlObject *OnCreateObject(int type, int idc, ParamEntryPar cls); - void OnSimulate(EntityAI *vehicle); - void DestroyHUD(int exit) - { - GWorld->DestroyUserDialog(); - } - - void OnButtonDblClick(IControl *ctrl); - - virtual void OnDrag(IControl *ctrl) override; - virtual unsigned char OnDragging(IControl *draggCtrl, IControl *dropCtrl, float x, float y) override; - virtual bool OnDrop(IControl *draggCtrl, IControl *dropCtrl, float x, float y) override; - virtual bool OnKeyDown(int dikCode) override; - - virtual void DrawDragInfo(float x, float y, unsigned char enabled, Ref dragFont, float dragSize) override; - - void DrawTooltip(UIViewport *vp, float x, float y, const InventoryItem *item); - - virtual bool OnMenuCreated(Menu &menu, float x, float y, int idc, CCMContext &ctx) override; - virtual void OnMenuSelected(MenuItem *item) override; - - void ShowInventoryMenu(const InventoryMenuMessage &msg); - - static bool IsOpened() {return _instances > 0;} - - const InventoryItem *GetDraggedItem() const {return _dragItem;} - const InventoryItem *GetSwappedItem() const {return _swapItem;} -}; - -void CItemBase::SetItemShortcut(int index, const InventoryItem *item) -{ - if (!GWorld) return; - Person *player = GWorld->PlayerOn(); - if (!player) return; - - const InventoryItemType *type = item ? item->Type() : NULL; - if (!GetNetworkManager().IsServerOwner()) - // BOT client have to handle it - GetNetworkManager().AskForSetItemShortcut(player, index, type, const_cast(item)); - else - player->SetItemShortcutInstance(index, const_cast(item)); -} - -static bool ItemContainsInventoryItem(const InventoryItem *container, const InventoryItem *item) -{ - if (!container || !item) return false; - if (container == item) return true; - - bool found = false; - container->ForEachItem([&found, item](const InventoryItem *child) -> bool - { - if (child == item) - { - found = true; - return true; - } - return false; - }); - return found; -} - -static void RemoveMovedItemFromHands(Person *owner, InventoryItem *item) -{ - if (!owner || !item) return; - InventoryItem *inHands = owner->GetItemInHands(); - if (ItemContainsInventoryItem(item, inHands)) - owner->RemoveItemInHands(); -} - -void CItemBase::DropItem(Person *owner, InventoryItem *item) -{ - if (!GetNetworkManager().IsServerOwner()) - // BOT client have to handle it - GetNetworkManager().AskForDropItem(owner, item); - else - { - Entity *parent = item->GetHierarchyParent(); - if (parent) parent->RemoveOwnedItem(item); - - // dropped item nor any contained item can stay in hands - RemoveMovedItemFromHands(owner, item); - - Vector3Val pos = owner->FutureVisualState().Position(); - Vector3Val dir = owner->FutureVisualState().Direction(); - item->ItemDrop(owner, pos, dir); - } -} - -void CItemBase::MoveItem(EntityAI *target, int index, InventoryItem *item) -{ - // CItemBase::CanMoveItem should be called and succeed before - - if (!GetNetworkManager().IsServerOwner()) - // BOT client have to handle it - GetNetworkManager().AskForMoveItem(target, index, item, item->IsInventoryRotated()); - else - { - Entity *parent = item->GetHierarchyParent(); - Person *handsOwner = dyn_cast(parent); - const bool movedFromHands = handsOwner && handsOwner->GetItemInHands() == item; - if (parent) parent->RemoveOwnedItem(item); - - target->MoveItem(index, item); - if (movedFromHands) - GetNetworkManager().UpdateObject(handsOwner, NMCUpdateGeneric); - } -} - -bool CItemBase::CanMoveItem(EntityAI *target, int index, const InventoryItem *item) -{ - return target->CanMoveItem(index, item); -} - -void CItemBase::RotateInventoryItem(Person *person, InventoryItem *item) -{ - // Items in the hands slot are manipulated by dragging them out of the slot, - // never by changing their inventory orientation in place. - if (!item || (person && person->GetItemInHands() == item)) return; - if (!GetNetworkManager().IsServerOwner()) - GetNetworkManager().AskForRotateInventoryItem(person, item); - else if (item->RotateInInventory()) - GetNetworkManager().UpdateObject(item, NMCUpdateGeneric); -} - -void CItemBase::TakeItemToHands(Person *person, InventoryItem *item) -{ - if (!GetNetworkManager().IsServerOwner()) - // BOT client have to handle it - GetNetworkManager().AskForTakeItemToHands(person, item); - else - person->TakeItemToHands(item); -} - -struct CCMContextInventory : public CCMContext -{ - OLinkPermO(InventoryItem) _item1, _item2; - CCMContextInventory(InventoryItem *item1, InventoryItem *item2) {_item1 = item1; _item2 = item2;} -}; - -// highlighting of manipulated items -static Color ColorItemDragged(1.0f, 1.0f, 1.0f, 0.5f); -static Color ColorItemSwapped(1.0f, 1.0f, 1.0f, 0.5f); - -CItemBase::CItemBase(ControlsContainer *parent, int idc, ParamEntryPar cls) : ControlObject(parent, idc, cls) -{ - _dragX = _dragY = 0; - - _dragging = false; - - _x = cls >> "x"; - _y = cls >> "y"; - _w = cls >> "w"; - _h = cls >> "h"; - _z = cls >> "z"; - - _bgColor = GetPackedColor(cls >> "colorBackground"); - _borderColor = GetPackedColor(cls >> "colorBorder"); -} - -bool CItemBase::IsInside(float x, float y) const -{ - return x >= _x && x <= _x + _w && y >= _y && y <= _y + _h; -} - -void CItemBase::OnMouseMove(float x, float y, bool active) -{ - // hotfix when OnLButtonUp was not called - if (!GInput.mouseL) return; // maybe drag & drop cancel reaction would be needed - - if (_moving) - { - const float dragLimit = 0.01f; - if (Square(x - _dragX) + Square(y - _dragY) >= Square(dragLimit)) - { - if (_parent) _parent->OnDrag(this); - _dragging = true; - _moving = false; - } - } - else OnMouseHold(x, y, active); -} - -void CItemBase::BeginDrag() -{ - if (!_moving || _dragging) return; - if (_parent) _parent->OnDrag(this); - _dragging = true; - _moving = false; -} - - -void CItemBase::OnLButtonDblClick(float x, float y) -{ - if (IsInside(x, y)) - { - if (_parent) _parent->OnButtonDblClick(this); - } -} - -void CItemBase::OnLButtonDown(float x, float y) -{ - _dragX = x; - _dragY = y; - _moving = true; - _dragging = false; - - OnEvent(CEButtonDown); -} - -void CItemBase::OnLButtonUp(float x, float y) -{ - _moving = false; - _dragging = false; -} - -void CItemBase::OnRButtonClick(float x, float y) -{ - if (GetShortcutIndex() < 0) - { - DragItemInfo info = GetItemInfo(x, y); - if (info._item) - { - if (_parent) _parent->CreateContextMenu(x, y, - IDC_INVENTORY_MENU, Pars >> "RscDisplayInventory" >> "Menu", - CCMContextInventory(info._item, NULL)); - } - } -} - -void CItemBase::OnDrawBackGround(UIViewport *vp, float alpha) -{ - const int w = GLOB_ENGINE->Width2D(); - const int h = GLOB_ENGINE->Height2D(); - float xx = CX(_x); - float yy = CY(_y); - float ww = CW(_w); - float hh = CH(_h); - - // draw background - Draw2DParsExt pars; - pars.mip = GEngine->TextBank()->UseMipmap(NULL, 0, 0); - pars.SetColor(_bgColor); - pars.Init(); - vp->Draw2D(pars, Rect2DPixel(xx, yy, ww, hh)); - - // draw border - vp->DrawLine(Line2DPixel(xx, yy, xx + ww, yy), _borderColor, _borderColor); - vp->DrawLine(Line2DPixel(xx, yy, xx, yy + hh), _borderColor, _borderColor); - vp->DrawLine(Line2DPixel(xx + ww, yy, xx + ww, yy + hh), _borderColor, _borderColor); - vp->DrawLine(Line2DPixel(xx, yy + hh, xx + ww, yy + hh), _borderColor, _borderColor); -} - -void CItemBase::DrawItem(InventoryItem *item, float x, float y, float w, float h, float z, float alpha, Color color, Matrix3 *rot) -{ - // enforce the basic (on ground) model - int oldType = item->SetClothingType(-1); - - LODShape *shape = item->GetShape(); - if (!shape || shape->NLevels() == 0) - { - item->SetClothingType(oldType); - return; - } - - Matrix4 transform(NoInit); - if (!PlaceItemInRectangle(transform, item, x, y, w, h, z)) - { - item->SetClothingType(oldType); - return; - } - - if (rot) // additional transformation - { - Matrix3 orient = (*rot) * transform.Orientation(); - transform.SetOrientation(orient); - } - - int level = 0; - - // Set UI specific flags - item->InsideUIDraw(true); - - Color c = color; - if (color.A() < 0) color = Color(1.0f, 1.0f, 1.0f, 1.0f); - color.SetA(alpha * color.A()); - - GEngine->SetInstanceInfo(-1, color, 1.0f); - item->Draw(-1, level, ClipAll, DrawParameters::_noShadow, InstanceParameters::_default, 0.1f, transform, NULL -#if _HELISIM_RENDER_TO_TEXTURE - , GScene->GetDrawObjectIndex() -#endif - ); - GEngine->SetInstanceInfo(-1, HWhite, 1); - - item->InsideUIDraw(false); - - item->DrawProxies(level, 0.1f, transform, [](Matrix4 &matrix, SkeletonIndex boneIndex) -> bool - { - return false; - }); - - item->SetClothingType(oldType); -} - - -bool PlaceItemInRectangle(Matrix4 &result, const InventoryItem *item, float x, float y, float w, float h, float z) -{ - const InventoryItemType *type = item->Type(); - if (!type) return false; - - // center of the model - Vector3 pos = ControlObject::Convert2DTo3D(Point2DFloat(x + 0.5f * w, y + 0.5f * h), z); - - // orientation of the model - Matrix3 orient = type->GetInventoryOrientation(); - - // calculate scale and offset by the object bounding box - const Vector3 *bb = type->BoundingBox(); - Vector3 posMin(FLT_MAX, FLT_MAX, 0); - Vector3 posMax(-FLT_MAX, -FLT_MAX, 0); - float minZ = FLT_MAX; - // check all vertices of the cube -#define DIAG_ITEM_PLACEMENT 0 -#if DIAG_ITEM_PLACEMENT -LogF("CUBE: %s", cc_cast(type->GetName())); -LogF(" aside %.2f, %.2f, %.2f", orient.DirectionAside().X(), orient.DirectionAside().Y(), orient.DirectionAside().Z()); -LogF(" up %.2f, %.2f, %.2f", orient.DirectionUp().X(), orient.DirectionUp().Y(), orient.DirectionUp().Z()); -LogF(" dir %.2f, %.2f, %.2f", orient.Direction().X(), orient.Direction().Y(), orient.Direction().Z()); -#endif - for (int x=0; x<2; x++) - for (int y=0; y<2; y++) - for (int z=0; z<2; z++) - { - Vector3 pos = orient * Vector3(bb[x].X(), bb[y].Y(), bb[z].Z()); -#if DIAG_ITEM_PLACEMENT -LogF(" - %.2f, %.2f, %.2f -> %.2f, %.2f, %.2f", bb[x].X(), bb[y].Y(), bb[z].Z(), pos.X(), pos.Y(), pos.Z()); -#endif - saturateMin(posMin[0], pos[0]); saturateMax(posMax[0], pos[0]); - saturateMin(posMin[1], pos[1]); saturateMax(posMax[1], pos[1]); - saturateMin(minZ, pos[2]); - } -#if DIAG_ITEM_PLACEMENT -LogF(" min %.2f, %.2f, %.2f", posMin.X(), posMin.Y(), posMin.Z()); -LogF(" max %.2f, %.2f, %.2f", posMax.X(), posMax.Y(), posMax.Z()); -#endif - posMax[2] = posMin[2] = minZ; // nearest z plane to fit into space - - // scale - Point2DFloat ptMin = ControlObject::Convert3DTo2D(pos + posMin); - Point2DFloat ptMax = ControlObject::Convert3DTo2D(pos + posMax); -#if DIAG_ITEM_PLACEMENT -LogF(" area %.2f x %.2f", w, h); -LogF(" 2D [%.2f, %.2f] [%.2f, %.2f]", ptMin.x, ptMin.y, ptMax.x, ptMax.y); -#endif - float scale = std::min(abs(w / (ptMax.x - ptMin.x)), abs(h / (ptMax.y - ptMin.y))); -#if DIAG_ITEM_PLACEMENT -LogF(" scale %.2f", scale); -#endif - orient.SetScale(scale); - - // offset - pos[0] -= 0.5f * scale * (posMin.X() + posMax.X()); - pos[1] -= 0.5f * scale * (posMin.Y() + posMax.Y()); - - result.SetOrientation(orient); - result.SetPosition(pos); - -#if DIAG_ITEM_PLACEMENT - Vector3 pos1 = result.FastTransform(Vector3(bb[0].X(), bb[0].Y(), bb[0].Z())); - Vector3 pos2 = result.FastTransform(Vector3(bb[0].X(), bb[1].Y(), bb[0].Z())); - Vector3 pos3 = result.FastTransform(Vector3(bb[1].X(), bb[1].Y(), bb[0].Z())); - Vector3 pos4 = result.FastTransform(Vector3(bb[1].X(), bb[0].Y(), bb[0].Z())); - Vector3 pos5 = result.FastTransform(Vector3(bb[0].X(), bb[0].Y(), bb[1].Z())); - Vector3 pos6 = result.FastTransform(Vector3(bb[0].X(), bb[1].Y(), bb[1].Z())); - Vector3 pos7 = result.FastTransform(Vector3(bb[1].X(), bb[1].Y(), bb[1].Z())); - Vector3 pos8 = result.FastTransform(Vector3(bb[1].X(), bb[0].Y(), bb[1].Z())); - GEngine->DrawLine3D(-1, pos1, pos2, PackedWhite, 1, 0); - GEngine->DrawLine3D(-1, pos2, pos3, PackedWhite, 1, 0); - GEngine->DrawLine3D(-1, pos3, pos4, PackedWhite, 1, 0); - GEngine->DrawLine3D(-1, pos4, pos1, PackedWhite, 1, 0); - GEngine->DrawLine3D(-1, pos5, pos6, PackedWhite, 1, 0); - GEngine->DrawLine3D(-1, pos6, pos7, PackedWhite, 1, 0); - GEngine->DrawLine3D(-1, pos7, pos8, PackedWhite, 1, 0); - GEngine->DrawLine3D(-1, pos8, pos5, PackedWhite, 1, 0); - GEngine->DrawLine3D(-1, pos1, pos5, PackedWhite, 1, 0); - GEngine->DrawLine3D(-1, pos2, pos6, PackedWhite, 1, 0); - GEngine->DrawLine3D(-1, pos3, pos7, PackedWhite, 1, 0); - GEngine->DrawLine3D(-1, pos4, pos8, PackedWhite, 1, 0); - - Vector3 posMi = pos + scale * posMin; - Vector3 posMa = pos + scale * posMax; - GEngine->DrawLine3D(-1, posMi, posMa, PackedColor(Color(1,1,0,10)), 1, 0); -#endif - - return true; -} - -static int CountItems(const InventoryItemType *type) -{ - AIBrain *agent = GWorld->FocusOn(); - if (!agent || !agent->LSIsAlive()) return 0; - - Person *player = agent->GetPerson(); - if (!player) return 0; - - return player->CountItems(type); -} - -bool IsInventoryOpened(); - -RString GetKeyName(int dikCode); - -UITime CItemShortcut::_lastTime = Glob.uiTime; - -void ShowShortcuts() -{ - CItemShortcut::ShowShortcuts(); -} - -void ToggleShortcuts() -{ - CItemShortcut::ToggleShortcuts(); -} - -CItemShortcut::CItemShortcut(ControlsContainer *parent, int idc, ParamEntryPar cls, bool igui) - : base(parent, idc, cls), _igui(igui) -{ - _index = cls >> "index"; - - _textColor = GetPackedColor(cls >> "colorText"); - - _bgColorInHands = GetPackedColor(cls >> "colorBackgroundInHands"); - - _bgColorInactive = GetPackedColor(cls >> "colorBackgroundInactive"); - _borderColorInactive = GetPackedColor(cls >> "colorBorderInactive"); - _textColorInactive = GetPackedColor(cls >> "colorTextInactive"); - - _font = GEngine->LoadFont(GetFontID(cls>>"font")); - _size = cls >> "sizeEx"; - - // key mapped to action - int action = UAItemFirst + _index; - if (action >= UAItemFirst && action <= UAItemLast) - { - KeyListEx list = GInput.GetUserKeys(action); - if (list.Size() > 0) - { - int dik = list[0]; - _shortcut = GetKeyName(dik); - } - } -} - -int CItemShortcut::GetVisibleCount() const -{ - if (!GWorld) return 0; - Person *ui = GWorld->PlayerOn(); - if (!ui) return 0; - return ui->GetAvailableItemShortcuts(); -} - -void CItemShortcut::UpdateLayout() -{ - int count = GetVisibleCount(); - if (count <= 0) return; - if (_index < 0 || _index >= count) return; // hidden slot keeps its old place - - // keep the visible quickbar centered on screen - const float gap = _w * (0.010f / 0.047f); - const float total = count * _w + (count - 1) * gap; - _x = 0.5f - total * 0.5f + _index * (_w + gap); -} - -bool CItemShortcut::IsInside(float x, float y) const -{ - const_cast(this)->UpdateLayout(); - if (_index < 0 || _index >= GetVisibleCount()) return false; - return x >= _x && x <= _x + _w && y >= _y && y <= _y + _h; -} - -InventoryItem *CItemShortcut::GetItem() -{ - if (!GWorld) return NULL; - Person *ui = GWorld->PlayerOn(); - if (!ui) return NULL; - if (_index < 0 || _index >= ui->GetAvailableItemShortcuts()) return NULL; - - return ui->GetItemShortcutObject(_index); -} - -DragItemInfo CItemShortcut::GetItemInfo(float x, float y) -{ - DragItemInfo info; - info._item = GetItem(); - info._offsetX = x - _x; - info._offsetY = y - _y; - return info; -} - -bool CItemShortcut::IsContained(InventoryItem *item) -{ - return true; -} - -bool CItemShortcut::CanAddItem(InventoryItem *item, float x, float y) -{ - return _index >= 0 && _index < GetVisibleCount(); -} - -void CItemShortcut::AddItem(InventoryItem *item, float x, float y) -{ - if (_index < 0 || _index >= GetVisibleCount()) return; - SetItemShortcut(_index, item); -} - -float CItemShortcut::GetGridW() -{ - return _w; -} - -float CItemShortcut::GetGridH() -{ - return _h; -} - -void CItemShortcut::DrawTooltip(UIViewport *vp, float x, float y) -{ - /* Do not display tooltip for shortcut items - const InventoryItem *item = GetItemInfo(x, y)._item; - if (item) - { - DisplayInventory *disp = dynamic_cast(_parent.GetLink()); - if (disp) disp->DrawTooltip(vp, x, y, item); - } - */ -} - -const float CItemShortcut::_startDim = 45.0f; -const float CItemShortcut::_endDim = 50.0f; - -void CItemShortcut::ToggleShortcuts() -{ - float age = Glob.uiTime - _lastTime; - if (age >= _endDim) _lastTime = Glob.uiTime; // show - else _lastTime = Glob.uiTime - _endDim; // hide; -} - -void CItemShortcut::OnDraw(float alpha) -{ - UpdateLayout(); - if (_index < 0 || _index >= GetVisibleCount()) return; - - if (_igui) - { - if (IsInventoryOpened()) return; - if (!GWorld || !GWorld->UI()->IsHUDShown()) return; - } - - InventoryItem *item = GetItem(); - if (item) - { - int count = CountItems(item->Type()); - item->EnableAnimations(count > 0); - - static RStringB whiteTextureName("#(argb,1,1,1)color(1,1,1,1)"); - - if (count > 0) item->ResetTexture(); - else item->SetTexture(whiteTextureName); - - DisplayInventory *display = dynamic_cast(_parent.GetLink()); - Color color(0, 0, 0, -1.0f); - if (display) - { - if (display->GetDraggedItem() == item) color = ColorItemDragged; - else if (display->GetSwappedItem() == item) color = ColorItemSwapped; - } - - DrawItem(item, _x, _y, _w, _h, _z, alpha, color); - } -} - -void CItemShortcut::OnDrawBackGround(UIViewport *vp, float alpha) -{ - UpdateLayout(); - if (_index < 0 || _index >= GetVisibleCount()) return; - - if (_igui) - { - if (IsInventoryOpened()) return; - } - - if (!GWorld) return; - if (_igui && !GWorld->UI()->IsHUDShown()) return; - - Person *ui = GWorld->PlayerOn(); - if (!ui) return; - const InventoryItemType *type = ui->GetItemShortcut(_index); - if (_igui && !type) return; - - bool active = type && CountItems(type) > 0; - - const int w = GLOB_ENGINE->Width2D(); - const int h = GLOB_ENGINE->Height2D(); - float xx = CX(_x); - float yy = CY(_y); - float ww = CW(_w); - float hh = CH(_h); - - // draw background - Draw2DParsExt pars; - pars.mip = GEngine->TextBank()->UseMipmap(NULL, 0, 0); - PackedColor color = active ? _bgColor : _bgColorInactive; - const InventoryItem *inHands = ui->GetItemInHands(); - if (inHands && inHands->GetType() == type) color = _bgColorInHands; - pars.SetColor(color); - color.SetA8(toIntFloor(color.A8() * alpha)); - pars.Init(); - vp->Draw2D(pars, Rect2DPixel(xx, yy, ww, hh)); - - // draw border - color = active ? _borderColor : _borderColorInactive; - color.SetA8(toIntFloor(color.A8() * alpha)); - vp->DrawLine(Line2DPixel(xx, yy, xx + ww, yy), color, color); - vp->DrawLine(Line2DPixel(xx, yy, xx, yy + hh), color, color); - vp->DrawLine(Line2DPixel(xx + ww, yy, xx + ww, yy + hh), color, color); - vp->DrawLine(Line2DPixel(xx, yy + hh, xx + ww, yy + hh), color, color); -} - -void CItemShortcut::OnDrawForeGround(UIViewport *vp, float alpha) -{ - UpdateLayout(); - if (_index < 0 || _index >= GetVisibleCount()) return; - - if (_igui) - { - if (IsInventoryOpened()) return; - } - - if (!GWorld) return; - if (_igui && !GWorld->UI()->IsHUDShown()) return; - - Person *ui = GWorld->PlayerOn(); - if (!ui) return; - const InventoryItemType *type = ui->GetItemShortcut(_index); - if (!type) return; - - // Texts - int count = CountItems(type); - - const float offsetX = 0.09 * _size; - const float offsetY = 0.06 * _size; - PackedColor color = count > 0 ? _textColor : _textColorInactive; - color.SetA8(toIntFloor(color.A8() * alpha)); - TextDrawAttr attr(_size, _font, color, true); - Rect2DFloat clipRect(_x, _y, _w, _h); - - // key label and item count only - keep the shortcut slots clean like the HUD - if (count > 0) - { - vp->DrawText(Point2DFloat(_x + offsetX, _y + offsetY), clipRect, attr, cc_cast(_shortcut)); - BString<16> buffer; - sprintf(buffer, "%d", count); - float tw = vp->GetTextWidth(attr, cc_cast(buffer)); - vp->DrawText(Point2DFloat(_x + _w - tw - offsetX, _y + offsetY), clipRect, attr, cc_cast(buffer)); - } -} - -static int AttachmentsCount(InventoryItem *container) -{ - int n = container->NAttachments(); - int count = 0; - for (int i=0; iGetAttachment(i)) count++; - } - return count; -} - -// subcontrol handling a singe inventory item -class ContainerUI -{ -private: - float _titleW, _titleH; - float _attachmentW, _attachmentH; - float _gridW, _gridH; - - float _sbWidth; // scrollbar width - - Ref _font; - float _size; - PackedColor _textColor; - // header background color - PackedColor _bgHeaderColor; - // items background color - PackedColor _bgItemColor; - // items background color - PackedColor _bgNoItemColor; - // items background color - PackedColor _bgItemInHandsColor; - - static const float _textBorder; - static const bool _drawEmptyItems; - - // icons - Ref _expanded, _collapsed, _inHands; - -public: - ContainerUI(ParamEntryPar cls); - - float GetHeight(CItemBase *ctrl, InventoryItem *container, InventoryStorage *cargo, bool expanded); - float GetSBWidth() const {return _sbWidth;} - - bool DrawObjects(ControlsContainer *parent, CItemBase *ctrl, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded, float alpha); - bool DrawForeground(CItemBase *ctrl, UIViewport *vp, InventoryItem *container, InventoryStorage *cargo, Person *person, float top, bool expanded, float alpha); - bool DrawBackground(CItemBase *ctrl, UIViewport *vp, InventoryItem *container, InventoryStorage *cargo, Person *person, float top, bool expanded, float alpha); - - void DrawSimpleForeground(CItemBase *ctrl, UIViewport *vp, InventoryItem *item, Person *person, float left, float top, float alpha); - void DrawSimpleBackground(CItemBase *ctrl, UIViewport *vp, InventoryItem *item, Person *person, float left, float top, float alpha); - - bool FindHeader(CItemBase *ctrl, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded, float x, float y, int index, int &found); - bool FindSlot(CItemBase *ctrl, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded, float x, float y, InventoryItem *&result, int &resultIndex); - bool GetItemInfo(CItemBase *ctrl, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded, float x, float y, DragItemInfo &info); -}; - -const float ContainerUI::_textBorder = 0.002f; - -ContainerUI::ContainerUI(ParamEntryPar cls) -{ - _titleW = cls >> "titleW"; - _titleH = cls >> "titleH"; - _attachmentW = cls >> "attachmentW"; - _attachmentH = cls >> "attachmentH"; - _gridW = cls >> "gridW"; - _gridH = cls >> "gridH"; - - _sbWidth = 0.018; // TODO: move to config - - _font = GEngine->LoadFont(GetFontID(cls>>"font")); - _size = cls >> "sizeEx"; - _textColor = GetPackedColor(cls >> "colorText"); - _bgHeaderColor = GetPackedColor(cls >> "colorHeaderBackground"); - _bgNoItemColor = GetPackedColor(cls >> "colorNoItemBackground"); - _bgItemColor = GetPackedColor(cls >> "colorItemBackground"); - _bgItemInHandsColor = GetPackedColor(cls >> "colorItemInHandsBackground"); - - RString name = FindPicture(cls >> "expanded"); - name.Lower(); - _expanded = GlobLoadTexture(name); - if (_expanded) _expanded->SetUsageType(Texture::TexUI); // no limits - - name = FindPicture(cls >> "collapsed"); - name.Lower(); - _collapsed = GlobLoadTexture(name); - if (_collapsed) _collapsed->SetUsageType(Texture::TexUI); // no limits - - name = FindPicture(cls >> "inHands"); - name.Lower(); - _inHands = GlobLoadTexture(name); - if (_inHands) _inHands->SetUsageType(Texture::TexUI); // no limits -} - -float ContainerUI::GetHeight(CItemBase *ctrl, InventoryItem *container, InventoryStorage *cargo, bool expanded) -{ - float h = _titleH; // header - if (expanded) - { - int n = AttachmentsCount(container); - if (n > 0) - { - float width = ctrl->_w - _sbWidth; - int columns = toIntFloor(width / _attachmentW); - if (columns < 1) columns = 1; - int rows = (n + columns - 1) / columns; - h += rows * _attachmentH; - } - if (cargo) h += cargo->GetHeight() * _gridH; // content - } - return h; -} - -bool ContainerUI::DrawObjects(ControlsContainer *parent, CItemBase *ctrl, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded, float alpha) -{ - float bottom = ctrl->_y + ctrl->_h; - - if (top + /* better not to draw part of object */_titleH > bottom) return true; // replace by clipping - - DisplayInventory *display = dynamic_cast(parent); - Color color(0, 0, 0, -1.0f); - if (display) - { - if (display->GetDraggedItem() == container) color = ColorItemDragged; - else if (display->GetSwappedItem() == container) color = ColorItemSwapped; - } - - // container icon in the header - ctrl->DrawItem(container, ctrl->_x, top, _titleW, _titleH, ctrl->_z, alpha, color); - top += _titleH; - - if (expanded) - { - int n = container->NAttachments(); - if (n > 0) - { - float width = ctrl->_w - _sbWidth; - int columns = toIntFloor(width / _attachmentW); - if (columns < 1) columns = 1; - int c = 0; - for (int i=0; iGetAttachment(i); - if (item && /* better not to draw part of object */ top + _attachmentH <= bottom) - { - Color color(0, 0, 0, -1.0f); - if (display) - { - if (display->GetDraggedItem() == item) color = ColorItemDragged; - else if (display->GetSwappedItem() == item) color = ColorItemSwapped; - } - ctrl->DrawItem(unconst_cast(item), ctrl->_x + c * _attachmentW, top, _attachmentW, _attachmentH, ctrl->_z, alpha, color); - c++; - if (c >= columns) - { - c = 0; top += _attachmentH; - } - } - } - if (c > 0) top += _attachmentH; - } - if (cargo) - { - const RefArray &items = cargo->GetItems(); - - // grid - int index = 0; - for (int r=0; rGetHeight(); r++) - { - if (top >= bottom) return true; // replace by clipping - - for (int c=0; cGetWidth(); c++) - { - if (index < items.Size()) - { - const InventoryItem *item = items[index]; - if (item) - { - const InventoryItemType *type = item->Type(); - if (type) - { - int w = item->GetInventoryWidth(); - int h = item->GetInventoryHeight(); - if (top + h * _gridH <= bottom) /* better not to draw part of object */ - { - Color color(0, 0, 0, -1.0f); - if (display) - { - if (display->GetDraggedItem() == item) color = ColorItemDragged; - else if (display->GetSwappedItem() == item) color = ColorItemSwapped; - } - - ctrl->DrawItem(unconst_cast(item), ctrl->_x + c * _gridW, top, w * _gridW, h * _gridH, ctrl->_z, alpha, color); - } - } - } - } - index++; - } - top += _gridH; - } - } - } - return false; -} - -static RString GetSpaceText(const InventoryStorage &cargo) -{ - int count = 0; - const RefArray &items = cargo.GetItems(); - for (int i=0; iType(); - if (type) count += item->GetInventoryWidth() * item->GetInventoryHeight(); - } - } - return Format("%d/%d", count, cargo.GetWidth() * cargo.GetHeight()); -} - -// helper class for scoped existence of the clipped viewport -class ClippedViewport -{ -private: - UIViewport *_parent; - UIViewport *_clipped; - -public: - ClippedViewport(UIViewport *parent, Rect2DFloat &clipRect) : _parent(parent) - { - _clipped = parent->CreateChild(Point2DFloat(0, 0), clipRect); - } - ~ClippedViewport() - { - _parent->DestroyChild(_clipped); - } - - operator UIViewport *() - { - return _clipped; - } -}; - -void ContainerUI::DrawSimpleForeground(CItemBase *ctrl, UIViewport *vp, InventoryItem *item, Person *person, float left, float top, float alpha) -{ - Rect2DFloat clipRectF(ctrl->_x, ctrl->_y, ctrl->_w - _sbWidth, ctrl->_h); - ClippedViewport vpClipped(vp, clipRectF); - - // quantity - RefR text = item->GetQuantity(); - if (text) - { - SetTextAttribute(text, "shadow", "1"); - float h = GetTextHeight(text, Rect2DFloat(0, 0, _titleW, _titleH), _size); - float w = GetTextWidthFloat(text, _size); - DrawText(vpClipped, text, Rect2DFloat(left + _titleW - w, top + _titleH - h, _titleW, _titleH), _size); - } -} - -void ContainerUI::DrawSimpleBackground(CItemBase *ctrl, UIViewport *vp, InventoryItem *item, Person *person, float left, float top, float alpha) -{ - const int w = GLOB_ENGINE->Width2D(); - const int h = GLOB_ENGINE->Height2D(); - - float xx = CX(left), yy = CY(top), ww = CW(_titleW), hh = CH(_titleH); - Rect2DPixel clipRect(CX(ctrl->_x), CY(ctrl->_y), CW(ctrl->_w - _sbWidth), CH(ctrl->_h)); - - // background - Draw2DParsExt pars; - pars.mip = GEngine->TextBank()->UseMipmap(NULL, 0, 0); - /* - if (item) - { - float heat = item->GetTemperature(); - pars.SetColor(TempToColor(heat,Pars >> "RscDisplayInventory" >> "Objects" >> "Content" >> "colorHeaderBackground")); - } - { - pars.SetColor(PackedWhite); - } - */ - float heat = item->GetTemperature(); - pars.SetColor(TempToColor(heat,Pars >> "RscDisplayInventory" >> "Objects" >> "Content" >> "colorHeaderBackground")); - pars.Init(); - vp->Draw2D(pars, Rect2DPixel(xx, yy, ww, hh), clipRect); - if (item && person && item == person->GetItemInHands()) - { - Draw2DParsExt hand; - hand.mip = GEngine->TextBank()->UseMipmap(_inHands, 0, 0); - hand.SetColor(PackedWhite); - hand.Init(); - - vp->Draw2D(hand, Rect2DPixel(xx + ww - hh, yy, hh, hh), clipRect); - } - // border - vp->DrawLine(Line2DPixel(xx, yy, xx + ww, yy), ctrl->_borderColor, ctrl->_borderColor, clipRect); - vp->DrawLine(Line2DPixel(xx, yy, xx, yy + hh), ctrl->_borderColor, ctrl->_borderColor, clipRect); - vp->DrawLine(Line2DPixel(xx + ww, yy, xx + ww, yy + hh), ctrl->_borderColor, ctrl->_borderColor, clipRect); - vp->DrawLine(Line2DPixel(xx, yy + hh, xx + ww, yy + hh), ctrl->_borderColor, ctrl->_borderColor, clipRect); -} - -bool ContainerUI::DrawForeground(CItemBase *ctrl, UIViewport *vp, InventoryItem *container, InventoryStorage *cargo, Person *person, float top, bool expanded, float alpha) -{ - float width = ctrl->_w - _sbWidth; - - Rect2DFloat clipRectF(ctrl->_x, ctrl->_y, width, ctrl->_h); - ClippedViewport vpClipped(vp, clipRectF); - - // skip the header - top += _titleH; - - if (expanded) - { - int n = container->NAttachments(); - if (n > 0) - { - int columns = toIntFloor(width / _attachmentW); - if (columns < 1) columns = 1; - - float x = ctrl->_x; - - int c = 0; - for (int i=0; iGetAttachment(i); - if (item) - { - // quantity - RefR text = unconst_cast(item)->GetQuantity(); - if (text) - { - SetTextAttribute(text, "shadow", "1"); - float h = GetTextHeight(text, Rect2DFloat(0, 0, _attachmentW, _attachmentH), _size); - float w = GetTextWidthFloat(text, _size); - DrawText(vpClipped, text, Rect2DFloat(x + _attachmentW - w, top + _attachmentH - h, _attachmentW, _attachmentH), _size); - } - x += _attachmentW; - - c++; - if (c >= columns) - { - c = 0; top += _attachmentH; - x = ctrl->_x; - } - } - } - if (c > 0) - { - top += _attachmentH; - } - } - if (cargo) - { - float y = top; - int index = 0; - for (int i=0; iGetHeight(); i++) - { - float x = ctrl->_x; - for (int j=0; jGetWidth(); j++) - { - InventoryItem *item = index < cargo->GetItems().Size() ? cargo->GetItems()[index] : nullptr; - const InventoryItemType *type = item ? item->Type() : nullptr; - if (type) - { - // quantity - RefR text = unconst_cast(item)->GetQuantity(); - if (text) - { - SetTextAttribute(text, "shadow", "1"); - Rect2DFloat rect(0, 0, item->GetInventoryWidth() * _gridW, item->GetInventoryHeight() * _gridH); - float h = GetTextHeight(text, rect, _size); - float w = GetTextWidthFloat(text, _size); - rect.x = x + rect.w - w; rect.y = y + rect.h - h; - DrawText(vpClipped, text, rect, _size); - } - } - index++; - x += _gridW; - } - y += _gridH; - } - } - } - return false; -} - -bool ContainerUI::DrawBackground(CItemBase *ctrl, UIViewport *vp, InventoryItem *container, InventoryStorage *cargo, Person *person, float top, bool expanded, float alpha) -{ - const int w = GLOB_ENGINE->Width2D(); - const int h = GLOB_ENGINE->Height2D(); - float xx = CX(ctrl->_x); - float width = ctrl->_w - _sbWidth; - float hdx = xx, hdw = CW(width), hdh = CH(_titleH); - - TextDrawAttr attr(_size, _font, _textColor, true); - Rect2DFloat clipRectF(ctrl->_x, ctrl->_y, width, ctrl->_h); - Rect2DPixel clipRect(hdx, CY(ctrl->_y), hdw, CH(ctrl->_h)); - - Draw2DParsExt hand; - hand.mip = GEngine->TextBank()->UseMipmap(_inHands, 0, 0); - hand.SetColor(PackedWhite); - hand.Init(); - - // header - float hdy = CY(top); - // background - Draw2DParsExt pars; - pars.mip = GEngine->TextBank()->UseMipmap(NULL, 0, 0); - //pars.SetColor(_bgHeaderColor); - float heat = container->GetTemperature(); - pars.SetColor(TempToColor(heat,Pars >> "RscDisplayInventory" >> "Objects" >> "Content" >> "colorHeaderBackground")); - - pars.Init(); - vp->Draw2D(pars, Rect2DPixel(hdx, hdy, hdw, hdh), clipRect); - if (container && person && container == person->GetItemInHands()) - { - pars.SetColor(_bgItemInHandsColor); - vp->Draw2D(pars, Rect2DPixel(hdx, hdy, CW(_titleW), hdh), clipRect); - vp->Draw2D(hand, Rect2DPixel(CX(ctrl->_x + _titleW) - hdh, hdy, hdh, hdh), clipRect); - } - // border - vp->DrawLine(Line2DPixel(hdx, hdy, hdx + hdw, hdy), ctrl->_borderColor, ctrl->_borderColor, clipRect); - vp->DrawLine(Line2DPixel(hdx, hdy, hdx, hdy + hdh), ctrl->_borderColor, ctrl->_borderColor, clipRect); - vp->DrawLine(Line2DPixel(hdx + hdw, hdy, hdx + hdw, hdy + hdh), ctrl->_borderColor, ctrl->_borderColor, clipRect); - vp->DrawLine(Line2DPixel(hdx, hdy + hdh, hdx + hdw, hdy + hdh), ctrl->_borderColor, ctrl->_borderColor, clipRect); - // name - float tt = top + 0.5f * (_titleH - _size); - vp->DrawText(Point2DFloat(ctrl->_x + _titleW + _textBorder, tt), clipRectF, attr, container->GetDisplayName()); - if (cargo || container->NAttachments() > 0) - { - // collapse / expand icon - float right = ctrl->_x + width - _textBorder; - Texture *icon = expanded ? _expanded : _collapsed; - if (icon) - { - MipInfo mip = GEngine->TextBank()->UseMipmap(icon, 0, 0); - GEngine->Draw2D(mip, PackedWhite, - Rect2DPixel(CX(right) - CW(0.75f * _size), CY(top + _titleH - _size), CW(0.75f * _size), CH(_size)), clipRect); - } - if (cargo) - { - // space - RString space = GetSpaceText(*cargo); - if (!space.IsEmpty()) - { - float tw = vp->GetTextWidth(attr, space); - vp->DrawText(Point2DFloat(right - tw, top), clipRectF, attr, space); - } - } - } - top += _titleH; - - if (expanded) - { - int n = container->NAttachments(); - if (n > 0) - { - int columns = toIntFloor(width / _attachmentW); - if (columns < 1) columns = 1; - - float top2 = top; // backup for lines - - float ww = CW(_attachmentW); - hdh = CH(_attachmentH); - - float y1 = CY(top); - float y2 = CY(top + _attachmentH); - float x = ctrl->_x; - - int c = 0, count = 0; - for (int i=0; iGetAttachment(i); - if (!item) continue; - count++; - - bool inHands = false; - if (person && item == person->GetItemInHands()) - { - pars.SetColor(_bgItemInHandsColor); - inHands = true; - } - else - { - const float heat = container->GetAttachment(i)->GetTemperature(); - pars.SetColor(TempToColor(heat,Pars >> "RscDisplayInventory" >> "Objects" >> "Content" >> "colorItemBackground")); - //pars.SetColor(_bgItemColor); - } - vp->Draw2D(pars, Rect2DPixel(cx, y1, ww, y2 - y1), clipRect); - vp->DrawLine(Line2DPixel(cx, y1, cx, y2), ctrl->_borderColor, ctrl->_borderColor, clipRect); - if (inHands) vp->Draw2D(hand, Rect2DPixel(CX(x + _attachmentW) - hdh, y1, hdh, hdh), clipRect); - - x += _attachmentW; - - c++; - if (c >= columns) - { - c = 0; top += _attachmentH; - y1 = CY(top); - y2 = CY(top + _attachmentH); - x = ctrl->_x; - } - } - if (c > 0) - { - top += _attachmentH; - } - for (int i=0; iDrawLine(Line2DPixel(xx, cy, xx + CW(width * _attachmentW), cy), ctrl->_borderColor, ctrl->_borderColor, clipRect); - } - top2 += _attachmentH; - float cy = CY(top2); - vp->DrawLine(Line2DPixel(xx, cy, xx + CW(width * _attachmentW), cy), ctrl->_borderColor, ctrl->_borderColor, clipRect); - } - } - if (cargo) - { - float ww = CW(_gridW); - float hh = CH(_gridH); - - int n = cargo->GetHeight() * cargo->GetWidth(); - Buffer handled(n); - - // grid background - for (int i=0; iGetHeight(); i++) - { - float cy = CY(y); - float x = ctrl->_x; - for (int j=0; jGetWidth(); j++) - { - if (!handled[index]) - { - float cx = CX(x); - InventoryItem *item = index < cargo->GetItems().Size() ? cargo->GetItems()[index] : nullptr; - const InventoryItemType *type = item ? item->Type() : nullptr; - if (type) - { - const bool inHands = person && item == person->GetItemInHands(); - if (inHands) - { - pars.SetColor(_bgItemInHandsColor); - } - else - { - const float heat = item->GetTemperature(); - pars.SetColor(TempToColor(heat,Pars >> "RscDisplayInventory" >> "Objects" >> "Content" >> "colorItemBackground")); - } - vp->Draw2D(pars, Rect2DPixel(cx, cy, CW(item->GetInventoryWidth() * _gridW), CH(item->GetInventoryHeight() * _gridH)), clipRect); - for (int k=i; kGetInventoryHeight(); k++) - for (int l=j; lGetInventoryWidth(); l++) - { - int ii = k * cargo->GetWidth() + l; - handled[ii] = true; - } - if (inHands) vp->Draw2D(hand, Rect2DPixel(CX(x + item->GetInventoryWidth() * _gridW) - hh, CY(y + item->GetInventoryHeight() * _gridH) - hh, hh, hh), clipRect); - } - else - { - pars.SetColor(_bgNoItemColor); - vp->Draw2D(pars, Rect2DPixel(cx, cy, ww, hh), clipRect); - } - } - index++; - x += _gridW; - } - y += _gridH; - } - - // grid lines - for (int i=0; iGetHeight(); i++) - { - float cy = CY(y); - float x = ctrl->_x; - for (int j=0; jGetWidth(); j++) - { - if (!handled[index]) - { - float cx = CX(x); - InventoryItem *item = index < cargo->GetItems().Size() ? cargo->GetItems()[index] : nullptr; - const InventoryItemType *type = item ? item->Type() : nullptr; - if (type) - { - float ww = CW(item->GetInventoryWidth() * _gridW); - float hh = CH(item->GetInventoryHeight() * _gridH); - vp->DrawLine(Line2DPixel(cx, cy, cx + ww, cy), ctrl->_borderColor, ctrl->_borderColor, clipRect); - vp->DrawLine(Line2DPixel(cx + ww, cy, cx + ww, cy + hh), ctrl->_borderColor, ctrl->_borderColor, clipRect); - vp->DrawLine(Line2DPixel(cx + ww, cy + hh, cx, cy + hh), ctrl->_borderColor, ctrl->_borderColor, clipRect); - vp->DrawLine(Line2DPixel(cx, cy + hh, cx, cy), ctrl->_borderColor, ctrl->_borderColor, clipRect); - - for (int k=i; kGetInventoryHeight(); k++) - for (int l=j; lGetInventoryWidth(); l++) - { - int ii = k * cargo->GetWidth() + l; - handled[ii] = true; - } - } - else - { - vp->DrawLine(Line2DPixel(cx, cy, cx + ww, cy), ctrl->_borderColor, ctrl->_borderColor, clipRect); - vp->DrawLine(Line2DPixel(cx + ww, cy, cx + ww, cy + hh), ctrl->_borderColor, ctrl->_borderColor, clipRect); - vp->DrawLine(Line2DPixel(cx + ww, cy + hh, cx, cy + hh), ctrl->_borderColor, ctrl->_borderColor, clipRect); - vp->DrawLine(Line2DPixel(cx, cy + hh, cx, cy), ctrl->_borderColor, ctrl->_borderColor, clipRect); - } - } - index++; - x += _gridW; - } - y += _gridH; - } - } - } - return false; -} - -bool ContainerUI::FindHeader(CItemBase *ctrl, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded, float x, float y, int index, int &found) -{ - if (y < top) return true; // finish, not found - - // check the header - top += _titleH; - if (y < top) - { - // ignore the scrollbar - float width = ctrl->_w - _sbWidth; - // if (x > ctrl->_x + width - _size - _textBorder) found = index; - if (x < ctrl->_x + width) found = index; - return true; // finish, found - } - - return false; // continue -} - -bool ContainerUI::FindSlot(CItemBase *ctrl, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded, float x, float y, InventoryItem *&result, int &resultIndex) -{ - if (y < top) return true; - - // check the header - top += _titleH; - if (y < top) - { - result = container; - resultIndex = -1; - return true; - } - - if (expanded) - { - int n = AttachmentsCount(container); - if (n > 0) - { - float width = ctrl->_w - _sbWidth; - int columns = toIntFloor(width / _attachmentW); - if (columns < 1) columns = 1; - int rows = (n + columns - 1) / columns; - if (y < top + rows * _attachmentH) - { - result = container; - resultIndex = -1; - int row = toIntFloor((y - top) / _attachmentH); - int col = toIntFloor((x - ctrl->_x) / _attachmentW); - if (row >= 0 && row < rows && col >= 0 && col < columns) - { - int index = row * columns + col; - if (index < n) - { - for (int i=0; iNAttachments(); i++) - { - if (!container->GetAttachment(i)) continue; - if (index-- <= 0) - { - resultIndex = i; - break; - } - } - } - } - return true; - } - top += rows * _attachmentH; - } - if (cargo) - { - // grid - if (y <= top + cargo->GetHeight() * _gridH) - { - int row = toIntFloor((y - top) / _gridH); - int col = toIntFloor((x - ctrl->_x) / _gridW); - if (row >= 0 && row < cargo->GetHeight() && col >= 0 && col < cargo->GetWidth()) - { - result = container; - resultIndex = row * cargo->GetWidth() + col + n; - } - return true; - } - } - } - - return false; -} - -bool ContainerUI::GetItemInfo(CItemBase *ctrl, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded, float x, float y, DragItemInfo &info) -{ - if (y < top) return true; - float width = ctrl->_w - _sbWidth; - - // the container - top += _titleH; - if (y < top) - { - if (x <= ctrl->_x + width) - { - info._item = container; - info._offsetX = x - ctrl->_x; - info._offsetY = y - (top - _gridH); - } - return true; - } - - if (expanded) - { - int n = AttachmentsCount(container); - if (n > 0) - { - int columns = toIntFloor(width / _attachmentW); - if (columns < 1) columns = 1; - int rows = (n + columns - 1) / columns; - if (y < top + rows * _attachmentH) - { - int row = toIntFloor((y - top) / _attachmentH); - int col = toIntFloor((x - ctrl->_x) / _attachmentW); - if (row >= 0 && row < rows && col >= 0 && col < columns) - { - int index = row * columns + col; - if (index < n) - { - for (int i=0; iNAttachments(); i++) - { - if (!container->GetAttachment(i)) continue; - if (index-- <= 0) - { - info._item = container->GetAttachment(i); - info._offsetX = x - (ctrl->_x + col * _attachmentW); - info._offsetY = y - (top + row * _attachmentH); - break; - } - } - } - } - return true; - } - top += rows * _attachmentH; - } - if (cargo) - { - // grid - if (y < top + cargo->GetHeight() * _gridH) - { - // this container - int row = toIntFloor((y - top) / _gridH); - int col = toIntFloor((x - ctrl->_x) / _gridW); - int startIndex = cargo->ItemOn(row, col); - if (startIndex >= 0) - { - info._item = cargo->GetItems()[startIndex]; - int sy = startIndex / cargo->GetWidth(); - int sx = startIndex - sy * cargo->GetWidth(); - info._offsetX = x - (ctrl->_x + sx * _gridW); - info._offsetY = y - (top + sy * _gridH); - } - return true; - } - } - } - - return false; -} - -class CItemContainer : public CItemBase -{ -protected: - typedef CItemBase base; - - float _titleW, _titleH; - - ContainerUI _ui; - - OLink(Person) _person; - OLink(EntityAI) _target; - OLinkArray(InventoryItem) _cache; - - //! scroll bar used by control - CScrollBar _scrollbar; - -public: - CItemContainer(ControlsContainer *parent, int idc, ParamEntryPar cls, Person *person, EntityAI *target); - - - virtual void OnDraw(float alpha) override; - virtual void OnDrawForeGround(UIViewport *vp, float alpha) override; - virtual void OnDrawBackGround(UIViewport *vp, float alpha) override; - - virtual void OnMouseHold(float x, float y, bool active) override; - virtual void OnLButtonDown(float x, float y) override; - virtual void OnLButtonUp(float x, float y) override; - virtual void OnLButtonDblClick(float x, float y) override; - virtual void OnMouseZChanged(float dz) override; - - // CItemBase implementation - virtual DragItemInfo GetItemInfo(float x, float y) override; - virtual bool CanAddItem(InventoryItem *item, float x, float y) override; - virtual void AddItem(InventoryItem *item, float x, float y) override; - virtual float GetGridW() override; - virtual float GetGridH() override; - virtual bool IsContained(InventoryItem *item) override; - -private: - // update the content of the cache - void Update(); - // cycle through all subcontrols - bool ForEachSlot( - const std::function &funcSimple, - const std::function &funcContainer - ); -}; - -CItemContainer::CItemContainer(ControlsContainer *parent, int idc, ParamEntryPar cls, Person *person, EntityAI *target) : base(parent, idc, cls) - , _ui(cls), _scrollbar(false, false, cls >> "ScrollBar") -{ - _person = person; - _target = target; - - _titleW = cls >> "titleW"; - _titleH = cls >> "titleH"; - - _scrollbar.SetPosition - ( - _x + _w - _ui.GetSBWidth(), _y, - _ui.GetSBWidth(), _h - ); - _scrollbar.SetColor(_borderColor); - _scrollbar.SetRangeAndPos(0, 0, 1, 0); - _scrollbar.SetSpeed(1, 1); -} - -bool CItemContainer::ForEachSlot( - const std::function &funcSimple, - const std::function &funcContainer - ) -{ - int first = _scrollbar.GetPos(); - float top = _y; - float vSpace = 0.25f * _titleH; - - // simple items first - int columns = toIntFloor(_w / _titleW); - int col = 0; - float left = _x; - for (int j=0; j<_cache.Size(); j++) - { - InventoryItem *item = _cache[j]; - if (!item) continue; - - ResourceSupply *supply = item->GetSupply(); - InventoryStorage *cargo = supply ? &supply->GetItemsCargo() : NULL; - if (cargo && (cargo->GetHeight() <= 0 || cargo->GetWidth() <= 0)) cargo = NULL; - - if (!cargo && item->NAttachments() == 0) - { - // simple item - if (first <= 0) - { - // visible, invoke the functor - if (funcSimple(j, item, left, top)) return true; - } - col++; left += _titleW; - if (col >= columns) - { - // the next row - if (first-- <= 0) top += _titleH + vSpace; - col = 0; left = _x; - } - } - } - if (col > 0) - { - // the next row - if (first-- <= 0) top += _titleH + vSpace; - } - // containers then - for (int j=0; j<_cache.Size(); j++) - { - InventoryItem *container = _cache[j]; - if (!container) continue; - - ResourceSupply *supply = container->GetSupply(); - InventoryStorage *cargo = supply ? &supply->GetItemsCargo() : NULL; - if (cargo && (cargo->GetHeight() <= 0 || cargo->GetWidth() <= 0)) cargo = NULL; - - if (!cargo && container->NAttachments() == 0) continue; - - if (first-- > 0) continue; // skip scrolled items - - // invoke the functor - if (funcContainer(j, container, cargo, top, container->IsOpened())) return true; - - // forward top - top += _ui.GetHeight(this, container, cargo, container->IsOpened()); - top += vSpace; // space - } - return false; -} - -void CItemContainer::OnDraw(float alpha) -{ - // if needed, Update can be called less often - Update(); - - DisplayInventory *display = dynamic_cast(_parent.GetLink()); - - ForEachSlot( - [this, display, alpha](int index, InventoryItem *item, float left, float top) -> bool - { - Color color(0, 0, 0, -1.0f); - if (display) - { - if (display->GetDraggedItem() == item) color = ColorItemDragged; - else if (display->GetSwappedItem() == item) color = ColorItemSwapped; - } - - DrawItem(item, left, top, _titleW, _titleH, _z, alpha, color); - return false; - }, - [this, alpha](int index, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded) -> bool - { - return _ui.DrawObjects(_parent, this, container, cargo, top, expanded, alpha); - }); -} - -void CItemContainer::OnDrawForeGround(UIViewport *vp, float alpha) -{ - ForEachSlot( - [this, vp, alpha](int index, InventoryItem *item, float left, float top) -> bool - { - _ui.DrawSimpleForeground(this, vp, item, nullptr, left, top, alpha); - return false; - }, - [this, vp, alpha](int index, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded) -> bool - { - return _ui.DrawForeground(this, vp, container, cargo, nullptr, top, expanded, alpha); - }); -} - -void CItemContainer::OnDrawBackGround(UIViewport *vp, float alpha) -{ - _scrollbar.OnDraw(vp, alpha); - - base::OnDrawBackGround(vp, alpha); - - ForEachSlot( - [this, vp, alpha](int index, InventoryItem *item, float left, float top) -> bool - { - _ui.DrawSimpleBackground(this, vp, item, nullptr, left, top, alpha); - return false; - }, - [this, vp, alpha](int index, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded) -> bool - { - return _ui.DrawBackground(this, vp, container, cargo, nullptr, top, expanded, alpha); - }); -} - -void CItemContainer::OnMouseHold(float x, float y, bool active) -{ - if (GInput.mouseL) - { - if (_scrollbar.IsEnabled() && _scrollbar.IsLocked()) - _scrollbar.OnMouseHold(x, y); - } -} - -void CItemContainer::OnLButtonDown(float x, float y) -{ - _moving = false; - _dragging = false; - - if (_scrollbar.IsInside(x, y)) - { - if (_scrollbar.IsEnabled()) _scrollbar.OnLButtonDown(x, y); - return; - } - - _dragX = _dragY = 0; - base::OnLButtonDown(x, y); -} - -void CItemContainer::OnLButtonUp(float x, float y) -{ - if (_scrollbar.IsLocked()) - { - _scrollbar.OnLButtonUp(x, y); - } - - if (!_dragging) - { - int found = -1; - ForEachSlot( - [this, x, y, &found](int index, InventoryItem *item, float left, float top) -> bool - { - return false; - }, - [this, x, y, &found](int index, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded) -> bool - { - return _ui.FindHeader(this, container, cargo, top, expanded, x, y, index, found); - }); - if (found >= 0) - { - InventoryItem *container = _cache[found]; - if (container) container->Open(!container->IsOpened()); - return; - } - } - - base::OnLButtonUp(x, y); -} - -void CItemContainer::OnLButtonDblClick(float x, float y) -{ - base::OnLButtonDblClick(x, y); -} - -void CItemContainer::OnMouseZChanged(float dz) -{ - if (dz == 0) return; - - int pos = _scrollbar.GetPos(); - _scrollbar.SetPos(dz > 0 ? pos - 1 : pos + 1); -} - -void CItemContainer::Update() -{ - OLinkArray(InventoryItem) items; - // find items in source - if (_target) - { - Object *obj = _target; - InventoryItem *item = dyn_cast(obj); - if (item) - { - items.Add(item); - } - else - { - /* - if( _target->GetSupply() ) - { - InventoryStorage &cargo = _target->GetSupply()->GetItemsCargo(); - for (int i=0; iForEachOwnedItem([&items](InventoryItem *item) -> bool - { - items.Add(item); - return false; // continue - }); - } - } - else - { - const float radius = 1.0f; - const EntityVisualState &vs = _person->FutureVisualState(); - Vector3Val center = vs.Position() + 0.5f * vs.Direction(); - - int xMin, xMax, zMin, zMax; - ObjRadiusRectangle(xMin, xMax, zMin, zMax, center, center, radius); - float minDist2 = Square(radius); - for (int x=xMin; x<=xMax; x++) for (int z=zMin; z<=zMax; z++) - { - const ObjectListUsed &list = GLandscape->UseObjects(x,z); - int n = list.Size(); - for (int i=0; iFutureVisualState().Position().DistanceXZ2(center) > minDist2) continue; - // check the type - InventoryItem *item = dyn_cast(obj); - if (!item) continue; - // check the visibility - CollisionBuffer retVal; - GLandscape->ObjectCollisionLine( - _person->GetRenderVisualStateAge(), retVal, Landscape::FilterIgnoreOne(_person), - _person->EyePosition(vs), obj->CameraPosition(), 0, - ObjIntersectFire, ObjIntersectNone // TODO: update when some problems occurs - ); - // find the first intersected object - int found = -1; - float minT = 1e10; - for (int i=0; i=0; i--) - { - InventoryItem *item = _cache[i]; - if (item && items.Find(item) < 0) _cache.DeleteAt(i); - } - // add items in the list - for (int i=0; iGetSupply(); - InventoryStorage *cargo = supply ? &supply->GetItemsCargo() : NULL; - if (cargo && (cargo->GetHeight() <= 0 || cargo->GetWidth() <= 0)) cargo = NULL; - - if (!cargo && container->NAttachments() == 0) - countSimple++; - else - countContainers++; - } - int columns = toIntFloor(_w / _titleW); - int count = countContainers + (countSimple + columns - 1) / columns; - - int pos = _scrollbar.GetPos(); - _scrollbar.SetRangeAndPos(0, count, 1, pos); -} - -DragItemInfo CItemContainer::GetItemInfo(float x, float y) -{ - DragItemInfo info; - info._item = NULL; - - ForEachSlot( - [this, x, y, &info](int index, InventoryItem *item, float left, float top) -> bool - { - if (y >= top && y < top + _titleH && x >= left && x < left + _titleW) - { - info._item = item; - info._offsetX = x - left; - info._offsetY = y - top; - return true; - } - return false; - }, - [this, x, y, &info](int index, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded) -> bool - { - return _ui.GetItemInfo(this, container, cargo, top, expanded, x, y, info); - }); - - return info; -} - -bool CItemContainer::IsContained(InventoryItem *check) -{ - for (int j=0; j<_cache.Size(); j++) - { - InventoryItem *item = _cache[j]; - if (!item) continue; - if (item == check) return true; - - ResourceSupply *supply = item->GetSupply(); - InventoryStorage *cargo = supply ? &supply->GetItemsCargo() : NULL; - if (cargo && (cargo->GetHeight() <= 0 || cargo->GetWidth() <= 0)) cargo = NULL; - - if (cargo && cargo->FindItem(check)) return true; - for (int i=0; iNAttachments(); i++) - { - if (item->GetAttachment(i) == check) return true; - } - } - return false; -} - -bool CItemContainer::CanAddItem(InventoryItem *item, float x, float y) -{ - InventoryItem *result = NULL; - int resultIndex = -1; - - ForEachSlot( - [this, x, y, &result, &resultIndex](int index, InventoryItem *item, float left, float top) -> bool - { - return false; - }, - [this, x, y, &result, &resultIndex](int index, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded) -> bool - { - return _ui.FindSlot(this, container, cargo, top, expanded, x, y, result, resultIndex); - }); - - if (result) - { - if (item == result) return false; // cannot contain myself - // if (resultIndex < 0) return false; // drop on header not supported yet - - return CanMoveItem(result, resultIndex, item); - } - - // drop on free space - if (_target) - return CanMoveItem(_target, -1, item); - else - return item->CheckInventoryCondition(nullptr); // drop on ground -} - -void CItemContainer::AddItem(InventoryItem *item, float x, float y) -{ - InventoryItem *result = NULL; - int resultIndex = -1; - - ForEachSlot( - [this, x, y, &result, &resultIndex](int index, InventoryItem *item, float left, float top) -> bool - { - return false; - }, - [this, x, y, &result, &resultIndex](int index, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded) -> bool - { - return _ui.FindSlot(this, container, cargo, top, expanded, x, y, result, resultIndex); - }); - - if (result) - { - if (item == result) return; // cannot contain myself - // if (resultIndex < 0) return; // drop on header not supported yet - - MoveItem(result, resultIndex, item); - return; - } - - // drop on free space - if (_target) - MoveItem(_target, -1, item); - else - DropItem(_person, item); -} - -float CItemContainer::GetGridW() -{ - return _titleW; -} - -float CItemContainer::GetGridH() -{ - return _titleH; -} - -class CItemContent : public CItemBase -{ -protected: - typedef CItemBase base; - - float _titleW, _titleH; - - OLink(Person) _person; - - ContainerUI _ui; - - //! scroll bar used by control - CScrollBar _scrollbar; - -public: - CItemContent(ControlsContainer *parent, int idc, ParamEntryPar cls, Person *person); - - virtual void OnDraw(float alpha) override; - virtual void OnDrawForeGround(UIViewport *vp, float alpha) override; - virtual void OnDrawBackGround(UIViewport *vp, float alpha) override; - - virtual void OnMouseHold(float x, float y, bool active) override; - virtual void OnLButtonDown(float x, float y) override; - virtual void OnLButtonUp(float x, float y) override; - virtual void OnLButtonDblClick(float x, float y) override; - virtual void OnMouseZChanged(float dz) override; - - // CItemBase implementation - virtual DragItemInfo GetItemInfo(float x, float y) override; - virtual bool CanAddItem(InventoryItem *item, float x, float y) override; - virtual void AddItem(InventoryItem *item, float x, float y) override; - virtual float GetGridW() override; - virtual float GetGridH() override; - virtual bool IsContained(InventoryItem *item) override; - -private: - // cycle through all subcontrols - bool ForEachSlot( - const std::function &funcSimple, - const std::function &funcContainer - ); -}; - -CItemContent::CItemContent(ControlsContainer *parent, int idc, ParamEntryPar cls, Person *person) - : base(parent, idc, cls), _ui(cls), _scrollbar(false, false, cls >> "ScrollBar") -{ - _person = person; - - _titleW = cls >> "titleW"; - _titleH = cls >> "titleH"; - - _scrollbar.SetPosition - ( - _x + _w - _ui.GetSBWidth(), _y, - _ui.GetSBWidth(), _h - ); - _scrollbar.SetColor(_borderColor); - _scrollbar.SetRangeAndPos(0, 0, 1, 0); - _scrollbar.SetSpeed(1, 1); -} - -bool CItemContent::ForEachSlot( - const std::function &funcSimple, - const std::function &funcContainer - ) -{ - int first = _scrollbar.GetPos(); - float top = _y; - float vSpace = 0.25f * _titleH; - - // simple items first - int columns = toIntFloor(_w / _titleW); - int col = 0; - float left = _x; - for (int order=0; order ISShoulder + 1 && order <= ISShoulder2 ? order - 1 : order); - if (j == ISHands) continue; - InventoryItem *item = _person->GetInSlot((InventorySlotId)j); - if (!item) continue; - - ResourceSupply *supply = item->GetSupply(); - InventoryStorage *cargo = supply ? &supply->GetItemsCargo() : NULL; - if (cargo && (cargo->GetHeight() <= 0 || cargo->GetWidth() <= 0)) cargo = NULL; - - if (!cargo && item->NAttachments() == 0) - { - // simple item - if (first <= 0) - { - // visible, invoke the functor - if (funcSimple(j, item, left, top)) return true; - } - col++; left += _titleW; - if (col >= columns) - { - // the next row - if (first-- <= 0) top += _titleH + vSpace; - col = 0; left = _x; - } - } - } - if (col > 0) - { - // the next row - if (first-- <= 0) top += _titleH + vSpace; - } - // containers then - for (int order=0; order ISShoulder + 1 && order <= ISShoulder2 ? order - 1 : order); - if (j == ISHands) continue; - InventoryItem *container = _person->GetInSlot((InventorySlotId)j); - if (!container) continue; - - ResourceSupply *supply = container->GetSupply(); - InventoryStorage *cargo = supply ? &supply->GetItemsCargo() : NULL; - if (cargo && (cargo->GetHeight() <= 0 || cargo->GetWidth() <= 0)) cargo = NULL; - - if (!cargo && container->NAttachments() == 0) continue; - - if (first-- > 0) continue; // skip scrolled items - - // invoke the functor - if (funcContainer(j, container, cargo, top, container->IsOpened())) return true; - - // forward top - top += _ui.GetHeight(this, container, cargo, container->IsOpened()); - top += vSpace; // space - } - return false; -} - -void CItemContent::OnDraw(float alpha) -{ - // update the scrollbar range - int countSimple = 0, countContainers = 0; - for (int j=0; jGetInSlot((InventorySlotId)j); - if (!container) continue; - - ResourceSupply *supply = container->GetSupply(); - InventoryStorage *cargo = supply ? &supply->GetItemsCargo() : NULL; - if (cargo && (cargo->GetHeight() <= 0 || cargo->GetWidth() <= 0)) cargo = NULL; - - if (!cargo && container->NAttachments() == 0) - countSimple++; - else - countContainers++; - } - int columns = toIntFloor(_w / _titleW); - int count = countContainers + (countSimple + columns - 1) / columns; - - int pos = _scrollbar.GetPos(); - _scrollbar.SetRangeAndPos(0, count, 1, pos); - - DisplayInventory *display = dynamic_cast(_parent.GetLink()); - - ForEachSlot( - [this, display, alpha](int index, InventoryItem *item, float left, float top) -> bool - { - Color color(0, 0, 0, -1.0f); - if (display) - { - if (display->GetDraggedItem() == item) color = ColorItemDragged; - else if (display->GetSwappedItem() == item) color = ColorItemSwapped; - } - - DrawItem(item, left, top, _titleW, _titleH, _z, alpha, color); - return false; - }, - [this, alpha](int index, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded) -> bool - { - return _ui.DrawObjects(_parent, this, container, cargo, top, expanded, alpha); - }); -} - -void CItemContent::OnDrawForeGround(UIViewport *vp, float alpha) -{ - ForEachSlot( - [this, vp, alpha](int index, InventoryItem *item, float left, float top) -> bool - { - _ui.DrawSimpleForeground(this, vp, item, nullptr, left, top, alpha); - return false; - }, - [this, vp, alpha](int index, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded) -> bool - { - return _ui.DrawForeground(this, vp, container, cargo, _person, top, expanded, alpha); - }); -} - -void CItemContent::OnDrawBackGround(UIViewport *vp, float alpha) -{ - _scrollbar.OnDraw(vp, alpha); - - base::OnDrawBackGround(vp, alpha); - - ForEachSlot( - [this, vp, alpha](int index, InventoryItem *item, float left, float top) -> bool - { - _ui.DrawSimpleBackground(this, vp, item, _person, left, top, alpha); - return false; - }, - [this, vp, alpha](int index, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded) -> bool - { - return _ui.DrawBackground(this, vp, container, cargo, _person, top, expanded, alpha); - }); -} - -void CItemContent::OnMouseHold(float x, float y, bool active) -{ - if (GInput.mouseL) - { - if (_scrollbar.IsEnabled() && _scrollbar.IsLocked()) - _scrollbar.OnMouseHold(x, y); - } -} - -void CItemContent::OnLButtonDown(float x, float y) -{ - _moving = false; - _dragging = false; - - if (_scrollbar.IsInside(x, y)) - { - if (_scrollbar.IsEnabled()) _scrollbar.OnLButtonDown(x, y); - return; - } - - _dragX = _dragY = 0; - base::OnLButtonDown(x, y); -} - -void CItemContent::OnLButtonUp(float x, float y) -{ - if (_scrollbar.IsLocked()) - { - _scrollbar.OnLButtonUp(x, y); - } - - if (!_dragging) - { - int found = -1; - ForEachSlot( - [this, x, y, &found](int index, InventoryItem *item, float left, float top) -> bool - { - return false; - }, - [this, x, y, &found](int index, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded) -> bool - { - return _ui.FindHeader(this, container, cargo, top, expanded, x, y, index, found); - }); - if (found >= 0) - { - InventoryItem *container = _person->GetInSlot((InventorySlotId)found); - if (container) container->Open(!container->IsOpened()); - } - } - - base::OnLButtonUp(x, y); -} - -void CItemContent::OnLButtonDblClick(float x, float y) -{ - base::OnLButtonDblClick(x, y); -} - -void CItemContent::OnMouseZChanged(float dz) -{ - if (dz == 0) return; - - int pos = _scrollbar.GetPos(); - _scrollbar.SetPos(dz > 0 ? pos - 1 : pos + 1); -} - -DragItemInfo CItemContent::GetItemInfo(float x, float y) -{ - DragItemInfo info; - info._item = NULL; - - ForEachSlot( - [this, x, y, &info](int index, InventoryItem *item, float left, float top) -> bool - { - if (y >= top && y < top + _titleH && x >= left && x < left + _titleW) - { - info._item = item; - info._offsetX = x - left; - info._offsetY = y - top; - return true; - } - return false; - }, - [this, x, y, &info](int index, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded) -> bool - { - return _ui.GetItemInfo(this, container, cargo, top, expanded, x, y, info); - }); - - return info; -} - -bool CItemContent::IsContained(InventoryItem *check) -{ - for (int j=0; jGetInSlot((InventorySlotId)j); - if (!item) continue; - if (item == check) return true; - - ResourceSupply *supply = item->GetSupply(); - InventoryStorage *cargo = supply ? &supply->GetItemsCargo() : NULL; - if (cargo && (cargo->GetHeight() <= 0 || cargo->GetWidth() <= 0)) cargo = NULL; - - if (cargo && cargo->FindItem(check)) return true; - for (int i=0; iNAttachments(); i++) - { - if (item->GetAttachment(i) == check) return true; - } - } - return false; -} - -bool CItemContent::CanAddItem(InventoryItem *item, float x, float y) -{ - InventoryItem *result = NULL; - int resultIndex = -1; - - ForEachSlot( - [this, x, y, &result, &resultIndex](int index, InventoryItem *item, float left, float top) -> bool - { - return false; - }, - [this, x, y, &result, &resultIndex](int index, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded) -> bool - { - return _ui.FindSlot(this, container, cargo, top, expanded, x, y, result, resultIndex); - }); - - if (result) - { - if (item == result) return false; // cannot contain myself - // if (resultIndex < 0) return false; // drop on header not supported - - return CanMoveItem(result, resultIndex, item); - } - else - { - return CanMoveItem(_person, -1, item); // _person->CanAddItem(item); - } -} - -void CItemContent::AddItem(InventoryItem *item, float x, float y) -{ - InventoryItem *result = NULL; - int resultIndex = -1; - - ForEachSlot( - [this, x, y, &result, &resultIndex](int index, InventoryItem *item, float left, float top) -> bool - { - return false; - }, - [this, x, y, &result, &resultIndex](int index, InventoryItem *container, InventoryStorage *cargo, float top, bool expanded) -> bool - { - return _ui.FindSlot(this, container, cargo, top, expanded, x, y, result, resultIndex); - }); - - if (result) - { - if (item == result) return; // cannot contain myself - // if (resultIndex < 0) return; // drop on header not supported yet - - MoveItem(result, resultIndex, item); - } - else - { - if (CanMoveItem(_person, -1, item)) - MoveItem(_person, -1, item); - } -} - -float CItemContent::GetGridW() -{ - return _titleW; -} - -float CItemContent::GetGridH() -{ - return _titleH; -} - -class CItemInHands : public CItemBase -{ -protected: - typedef CItemBase base; - - float _gridW, _gridH; - - // structured text size - float _size; - - OLink(Person) _person; - - // items background color - PackedColor _bgNoItemColor; - PackedColor _bgItemColor; - -public: - CItemInHands(ControlsContainer *parent, int idc, ParamEntryPar cls, Person *person); - - virtual void OnDraw(float alpha) override; - virtual void OnDrawForeGround(UIViewport *vp, float alpha) override; - virtual void OnDrawBackGround(UIViewport *vp, float alpha) override; - - // CItemBase implementation - virtual DragItemInfo GetItemInfo(float x, float y) override; - virtual bool CanAddItem(InventoryItem *item, float x, float y) override; - virtual void AddItem(InventoryItem *item, float x, float y) override; - virtual float GetGridW() override; - virtual float GetGridH() override; - virtual bool IsContained(InventoryItem *item) override; -}; - -CItemInHands::CItemInHands(ControlsContainer *parent, int idc, ParamEntryPar cls, Person *person) - : base(parent, idc, cls) -{ - _person = person; - - _gridW = cls >> "gridW"; - _gridH = cls >> "gridH"; - - _size = cls >> "sizeEx"; - - _bgNoItemColor = GetPackedColor(cls >> "colorNoItemBackground"); - _bgItemColor = GetPackedColor(cls >> "colorItemBackground"); -} - -void CItemInHands::OnDraw(float alpha) -{ - InventoryItem *item = _person ? _person->GetItemInHands() : NULL; - if (item) - { - float height = _h - _gridH; - - DisplayInventory *display = dynamic_cast(_parent.GetLink()); - - Color color(0, 0, 0, -1.0f); - if (display) - { - if (display->GetDraggedItem() == item) color = ColorItemDragged; - else if (display->GetSwappedItem() == item) color = ColorItemSwapped; - } - - DrawItem(item, _x, _y, _w, height, _z, alpha, color); - - float top = _y + height; - int columns = toIntFloor(_w / _gridW); - saturateMax(columns, 1); - int index = 0; - - int n = item->NAttachments(); - if (n > 0) - { - for (int i=0; iGetAttachment(i); - if (attachment) - { - Color color(0, 0, 0, -1.0f); - if (display) - { - if (display->GetDraggedItem() == attachment) color = ColorItemDragged; - else if (display->GetSwappedItem() == attachment) color = ColorItemSwapped; - } - - DrawItem(attachment, _x + index * _gridW, top, _gridW, _gridH, _z, alpha, color); - if (++index >= columns) break; - } - } - } - else if (item->GetSupply()) - { - InventoryStorage &cargo = item->GetSupply()->GetItemsCargo(); - for (int i=0; iGetDraggedItem() == cargoItem) color = ColorItemDragged; - else if (display->GetSwappedItem() == cargoItem) color = ColorItemSwapped; - } - - DrawItem(cargoItem, _x + index * _gridW, top, _gridW, _gridH, _z, alpha, color); - if (++index >= columns) break; - } - } - } - } -} - -void CItemInHands::OnDrawForeGround(UIViewport *vp, float alpha) -{ - InventoryItem *item = _person ? _person->GetItemInHands() : NULL; - if (item) - { - float top = _y + _h - _gridH; - float x = _x; - - int n = item->NAttachments(); - if (n > 0) - { - for (int i=0; iGetAttachment(i); - if (attachment) - { - // quantity - RefR text = attachment->GetQuantity(); - if (text) - { - SetTextAttribute(text, "shadow", "1"); - float h = GetTextHeight(text, Rect2DFloat(0, 0, _gridW, _gridH), _size); - float w = GetTextWidthFloat(text, _size); - DrawText(vp, text, Rect2DFloat(x + _gridW - w, top + _gridH - h, _gridW, _gridH), _size); - } - x += _gridW; - - if (x + _gridW > _x + _w) break; // no more items fit - } - } - } - else if (item->GetSupply()) - { - InventoryStorage &cargo = item->GetSupply()->GetItemsCargo(); - for (int i=0; i text = cargoItem->GetQuantity(); - if (text) - { - SetTextAttribute(text, "shadow", "1"); - float h = GetTextHeight(text, Rect2DFloat(0, 0, _gridW, _gridH), _size); - float w = GetTextWidthFloat(text, _size); - DrawText(vp, text, Rect2DFloat(x + _gridW - w, top + _gridH - h, _gridW, _gridH), _size); - } - x += _gridW; - - if (x + _gridW > _x + _w) break; // no more items fit - } - } - } - } -} - -void CItemInHands::OnDrawBackGround(UIViewport *vp, float alpha) -{ - base::OnDrawBackGround(vp, alpha); - - InventoryItem *item = _person ? _person->GetItemInHands() : NULL; - if (item) - { - float top = _y + _h - _gridH; - - const int w = GLOB_ENGINE->Width2D(); - const int h = GLOB_ENGINE->Height2D(); - - float y1 = CY(top); - float y2 = CY(top + _gridH); - float ww = CW(_gridW); - float x = _x; - - Draw2DParsExt pars; - pars.mip = GEngine->TextBank()->UseMipmap(NULL, 0, 0); - pars.Init(); - - int n = item->NAttachments(); - if (n > 0) - { - for (int i=0; iGetAttachment(i); - - if (attachment) - { - float cx = CX(x); - pars.SetColor(attachment ? _bgItemColor : _bgNoItemColor); - vp->Draw2D(pars, Rect2DPixel(cx, y1, ww, y2 - y1)); - - vp->DrawLine(Line2DPixel(cx, y1, cx, y2), _borderColor, _borderColor); - x += _gridW; - - if (x + _gridW > _x + _w) break; // no more items fit - } - } - vp->DrawLine(Line2DPixel(CX(_x), y1, CX(x), y1), _borderColor, _borderColor); - vp->DrawLine(Line2DPixel(CX(_x), y2, CX(x), y2), _borderColor, _borderColor); - vp->DrawLine(Line2DPixel(CX(x), y1, CX(x), y2), _borderColor, _borderColor); - } - else if (item->GetSupply()) - { - InventoryStorage &cargo = item->GetSupply()->GetItemsCargo(); - for (int i=0; iDraw2D(pars, Rect2DPixel(cx, y1, ww, y2 - y1)); - - vp->DrawLine(Line2DPixel(cx, y1, cx, y2), _borderColor, _borderColor); - x += _gridW; - - if (x + _gridW > _x + _w) break; // no more items fit - } - } - vp->DrawLine(Line2DPixel(CX(_x), y1, CX(x), y1), _borderColor, _borderColor); - vp->DrawLine(Line2DPixel(CX(_x), y2, CX(x), y2), _borderColor, _borderColor); - vp->DrawLine(Line2DPixel(CX(x), y1, CX(x), y2), _borderColor, _borderColor); - } - } -} - -DragItemInfo CItemInHands::GetItemInfo(float x, float y) -{ - DragItemInfo info; - info._item = NULL; - - InventoryItem *item = _person ? _person->GetItemInHands() : NULL; - if (!item) return info; - - // The item itself - float top = _y + _h - _gridH; - if (y < top) - { - info._item = item; - info._offsetX = x - _x; - info._offsetY = y - _y; - return info; - } - - int c = toIntFloor((x - _x) / _gridW); - float ox = x - (_x + c * _gridW); - - // The attachments - int n = item->NAttachments(); - if (n > 0) - { - for (int i=0; iGetAttachment(i); - if (!attachment) continue; - if (c-- <= 0) - { - info._item = attachment; - info._offsetX = ox; - info._offsetY = y - top; - return info; - } - } - } - else if (item->GetSupply()) - { - InventoryStorage &cargo = item->GetSupply()->GetItemsCargo(); - for (int i=0; iGetItemInHands() : NULL; - if (!item) return false; - if (item == check) return true; - - // The attachments - int n = item->NAttachments(); - if (n > 0) - { - for (int i=0; iGetAttachment(i); - if (attachment && attachment == check) return true; - } - } - else if (item->GetSupply()) - { - InventoryStorage &cargo = item->GetSupply()->GetItemsCargo(); - for (int i=0; i(_parent.GetLink()); - CItemBase *vicinity = display ? dynamic_cast(display->GetCtrl(IDC_INVENTORY_CONTAINER)) : NULL; - const bool fromVicinity = vicinity && vicinity->IsContained(newItem); - - const Person * const p = _person; - const Man * const m = dynamic_cast(p); - if (m && m->IsOnAnyLadder()) - return false; - - // Ground items can be dragged directly into empty hands as well. - if (!_person->FindItem(newItem) && !newItem->IsInLandscape()) return false; - - float top = _y + _h - _gridH; - - // Directly to hands - InventoryItem *oldItem = _person->GetItemInHands(); - if (!oldItem) - { - return true; - } - - if (y < top) - { - if (newItem->Type()) return true; // directly to hands - return CanMoveItem(oldItem, -1, newItem); // as an attachment - } - - // As an attachments - int n = oldItem->NAttachments(); - if (n > 0) - { - int c = toIntFloor((x - _x) / _gridW); - for (int i=0; iGetAttachment(i); - if (!attachment) continue; - if (c-- <= 0) - { - // check if compatible - return CanMoveItem(oldItem, i, newItem); - } - } - } - - return false; -} - -void CItemInHands::AddItem(InventoryItem *newItem, float x, float y) -{ - if (!_person) return; - - if (!_person->FindItem(newItem) && !newItem->IsInLandscape()) return; - - float top = _y + _h - _gridH; - - // Directly to hands - InventoryItem *oldItem = _person->GetItemInHands(); - if (!oldItem) - { - TakeItemToHands(_person, newItem); - return; - } - - if (y < top) - { - TakeItemToHands(_person, newItem); - return; - } - - // As an attachments - int n = oldItem->NAttachments(); - if (n > 0) - { - int c = toIntFloor((x - _x) / _gridW); - for (int i=0; iGetAttachment(i); - if (!attachment) continue; - if (c-- <= 0) - { - MoveItem(oldItem, i, newItem); - return; - } - } - } -} - -float CItemInHands::GetGridW() -{ - return _gridW; -} - -float CItemInHands::GetGridH() -{ - return _gridH; -} - -class CPlayerPreview : public ControlObject -{ -private: - typedef ControlObject base; - // info about proxies in the shape - ProxiesHolder _proxies; - - OLinkPermO(Person) _person; - //! head type (shape, animations etc.) - Ref _headType; - //! head object (mimics etc.) - Head _head; - - float _x, _y, _w, _h, _z; - - float _rotateX; // position of mouse when rotation started - float _rotation; // total rotation - - // background color - PackedColor _bgColor; - // border color - PackedColor _borderColor; - - //@{ - //! animation implementation - UITime _animStart; - Ref _animation; - //@} - - //@{ - //! animation speed - float _animSpeed; - //@} - UITime _lastSimulation; - -public: - //! constructor - /*! - Used when control is created by resource template. - \param parent control container by which this control is owned - \param idc id of control - \param cls resource template - */ - CPlayerPreview(ControlsContainer *parent, int idc, ParamEntryPar cls, Person *person); - - virtual void OnDraw(float alpha) override; - virtual void OnDrawBackGround(UIViewport *vp, float alpha) override; - - virtual bool PrepareShapeDrawMatrices(Matrix4Array &matrices, const ObjectVisualState &vs, LODShape *shape, int level) override; - - virtual bool IsInside(float x, float y) const override; - - virtual void OnLButtonDown(float x, float y) override; - virtual void OnLButtonUp(float x, float y) override; - virtual void OnMouseMove(float x, float y, bool active = true) override; - virtual void OnLButtonDblClick(float x, float y) override; - - void AnimateMatrix(Matrix4 &matrix, SkeletonIndex boneIndex); -}; - -CPlayerPreview::CPlayerPreview(ControlsContainer *parent, int idc, ParamEntryPar cls, Person *person) - : base(parent, idc, cls), _person(person) -{ - _x = cls >> "x"; - _y = cls >> "y"; - _w = cls >> "w"; - _h = cls >> "h"; - _z = cls >> "z"; - - _bgColor = GetPackedColor(cls >> "colorBackground"); - _borderColor = GetPackedColor(cls >> "colorBorder"); - - _animSpeed = cls >> "animSpeed"; - _animStart = Glob.uiTime; - - _lastSimulation = Glob.uiTime; - - _rotation = 0; - - if (person) _shape = person->GetShape(); - else _shape = NULL; - - if (_shape) - { - _proxies.Init(_shape); - _proxies.InitLevel(_shape, 0); - - ConstParamEntryPtr entry = cls.FindEntry("animation"); - if (entry) - { - AnimationRTName name; - name.name = GetAnimationName(*entry); - name.skeleton = _shape->LoadSkeletonFromSource(); - name.reversed = false; - name.streamingEnabled = false; - if (name.skeleton) - { - _animation = new AnimationRT(name); - _animation->SetLooped(true); - } - } - - _head._headBone = _shape->GetSkeleton()->FindBone(cls >> "boneHead"); - _head._lEye = _shape->GetSkeleton()->FindBone(cls >> "boneLEye"); - _head._rEye = _shape->GetSkeleton()->FindBone(cls >> "boneREye"); - _head._lEyelidUp = _shape->GetSkeleton()->FindBone(cls >> "boneLEyelidUp"); - _head._rEyelidUp = _shape->GetSkeleton()->FindBone(cls >> "boneREyelidUp"); - _head._lEyelidDown = _shape->GetSkeleton()->FindBone(cls >> "boneLEyelidDown"); - _head._rEyelidDown = _shape->GetSkeleton()->FindBone(cls >> "boneREyelidDown"); - _head._lPupil = _shape->GetSkeleton()->FindBone(cls >> "boneLPupil"); - _head._rPupil = _shape->GetSkeleton()->FindBone(cls >> "boneRPupil"); - } -} - -void CPlayerPreview::AnimateMatrix(Matrix4 &matrix, SkeletonIndex boneIndex) -{ - if (SkeletonIndexValid(boneIndex)) - { - BlendAnims blend; - float phase = _animSpeed * (Glob.uiTime - _animStart); - _animation->GetBlend(blend, phase); - // now perform the blending - blend.DoBoneAnim(matrix, _animation->GetSkeleton(), boneIndex); - // this is the only place where we orthogonalize animation matrix - // we do it because we want to make sure proxies (esp. the gun) live in orthonormal space - matrix.Orthogonalize(); - } -} - -void CPlayerPreview::OnDraw(float alpha) -{ - // center of the model - Vector3 pos = ControlObject::Convert2DTo3D(Point2DFloat(_x + 0.5f * _w, _y + 0.95 * _h), _z); - // scale - Camera *cam = GScene->GetCamera(); - AspectSettings as; - GEngine->GetAspectSettings(as); - float scale = _h * (cam->Top() * (as.uiBottomRightY - as.uiTopLeftY)) * _z; - - Matrix4 transform(NoInit); - transform.SetUpAndDirection(VUp, -VForward); - transform.SetScale(scale); - transform.SetPosition(pos); - - // rotation - Matrix3 rot(MRotationY, _rotation); - Matrix3 orient = rot * transform.Orientation(); - transform.SetOrientation(orient); - - SetTransform(transform); - - base::OnDraw(alpha); - - if (!_person) return; - - // drawing of proxies - int level = 0; // level of the character - int pLevel = 0; // level of the proxies - float dist2 = 1.0f; // distance of the proxies - - int n = _proxies.GetProxyCountForLevel(_shape, level); - for (int i=0; iGetEntityType(); - if (!proxyType) continue; - - Ref object; - InventoryItem *item = NULL; - -#if _ENABLE_NEWHEAD - if (strcmp(proxyType->_simName, "ProxySubpart") == 0) - { - // head - HeadObject *head = _person->CreateHead(); - _headType = head->Type(); - object = head; - } - else -#endif // _ENABLE_NEWHEAD - { - InventorySlotId slot = proxyType->GetInventorySlot(); - if (slot >= 0 && slot < NInventorySlotId) - { - item = _person->ToDrawInSlot(slot); - object = item; - } - } - - LODShape *shape = object ? object->GetShape() : NULL; - if (shape) - { - // we want animate object using this - Ref oi = new SortObject(); - oi->SetObject(object); - oi->SetRootObject(this); - if (GetShape() && shape->GetSkeletonSource() == GetShape()->GetSkeletonSource()) - oi->SetParentObject(this); - - Matrix4 pTransform = proxyObj->RenderVisualState().Transform(); - SkeletonIndex boneIndex = _proxies.GetProxyBoneForLevel(_shape, level, i); - AnimateMatrix(pTransform, boneIndex); - // Pose anchor in the paperdoll model space. The second shoulder weapon - // below uses the very same composition as the world rendering. - Matrix4 animatedProxy = pTransform; - pTransform = GetFrameBase() * pTransform; - - if (shape->Remarks() & ShapeReversed) - { - Matrix4 swapM(MScale, -1, +1, -1); - pTransform = pTransform * swapM; - } - - // Set UI specific flags - if (item) - { - item->InsideUIDraw(true); - - Color color(1.0f, 1.0f, 1.0f, 1.0f); - DisplayInventory *display = dynamic_cast(_parent.GetLink()); - if (display) - { - if (display->GetDraggedItem() == item) color = ColorItemDragged; - else if (display->GetSwappedItem() == item) color = ColorItemSwapped; - } - color.SetA(alpha * color.A()); - GEngine->SetInstanceInfo(-1, color, 1.0f); - } - else object->GetShape()->OrSpecial(DisableSun); - - object->Draw(-1, pLevel, ClipAll, DrawParameters::_noShadow, InstanceParameters::_default, dist2, pTransform, oi -#if _HELISIM_RENDER_TO_TEXTURE - , GScene->GetDrawObjectIndex() -#endif - ); - - // Restore flags - if (item) - { - item->InsideUIDraw(false); - GEngine->SetInstanceInfo(-1, HWhite, 1); - } - else object->GetShape()->AndSpecial(~DisableSun); - - // for an inventory item, draw attachments recursively - Object *parentObject = oi->GetParentObject(); - if (item) item->DrawProxies(pLevel, dist2, pTransform, [&parentObject](Matrix4 &matrix, SkeletonIndex boneIndex) -> bool - { - if (!parentObject) return false; - - CPlayerPreview *ctrl = static_cast(parentObject); - ctrl->AnimateMatrix(matrix, boneIndex); - return true; - }); - - // The character model has a single shoulder proxy, so as in the world - // rendering the second shoulder weapon must be drawn manually at the - // same proxy, mirrored to the right half of the back. - if (proxyType->GetInventorySlot() == ISShoulder) - { - InventoryItem *secondItem = _person->GetInSlot(ISShoulder2); - LODShape *secondShape = secondItem ? secondItem->GetShape() : NULL; - if (secondShape && secondItem != item) - { - // Same composition as Man::PrepareProxiesForDrawing: the offset is - // applied to the pose anchor in model space, then the paperdoll - // frame places the result. - Matrix4 oppositeSide(MTranslation, Vector3(+0.32f, 0.0f, -0.10f)); - Matrix4 secondTransform = GetFrameBase() * oppositeSide * animatedProxy; - - if (secondShape->Remarks() & ShapeReversed) - { - Matrix4 swapM(MScale, -1, +1, -1); - secondTransform = secondTransform * swapM; - } - - Ref oi2 = new SortObject(); - oi2->SetObject(secondItem); - oi2->SetRootObject(this); - if (GetShape() && secondShape->GetSkeletonSource() == GetShape()->GetSkeletonSource()) - oi2->SetParentObject(this); - - secondItem->InsideUIDraw(true); - - Color color(1.0f, 1.0f, 1.0f, 1.0f); - DisplayInventory *display = dynamic_cast(_parent.GetLink()); - if (display) - { - if (display->GetDraggedItem() == secondItem) color = ColorItemDragged; - else if (display->GetSwappedItem() == secondItem) color = ColorItemSwapped; - } - color.SetA(alpha * color.A()); - GEngine->SetInstanceInfo(-1, color, 1.0f); - - secondItem->Draw(-1, pLevel, ClipAll, DrawParameters::_noShadow, InstanceParameters::_default, dist2, secondTransform, oi2 -#if _HELISIM_RENDER_TO_TEXTURE - , GScene->GetDrawObjectIndex() -#endif - ); - - secondItem->InsideUIDraw(false); - GEngine->SetInstanceInfo(-1, HWhite, 1); - - Object *parentObject2 = oi2->GetParentObject(); - secondItem->DrawProxies(pLevel, dist2, secondTransform, [&parentObject2](Matrix4 &matrix, SkeletonIndex boneIndex) -> bool - { - if (!parentObject2) return false; - - CPlayerPreview *ctrl = static_cast(parentObject2); - ctrl->AnimateMatrix(matrix, boneIndex); - return true; - }); - } - } - } - } -} - -void CPlayerPreview::OnDrawBackGround(UIViewport *vp, float alpha) -{ - const int w = GLOB_ENGINE->Width2D(); - const int h = GLOB_ENGINE->Height2D(); - float xx = CX(_x); - float yy = CY(_y); - float ww = CW(_w); - float hh = CH(_h); - - // draw background - Draw2DParsExt pars; - pars.mip = GEngine->TextBank()->UseMipmap(NULL, 0, 0); - pars.SetColor(_bgColor); - pars.Init(); - vp->Draw2D(pars, Rect2DPixel(xx, yy, ww, hh)); - - // draw border - vp->DrawLine(Line2DPixel(xx, yy, xx + ww, yy), _borderColor, _borderColor); - vp->DrawLine(Line2DPixel(xx, yy, xx, yy + hh), _borderColor, _borderColor); - vp->DrawLine(Line2DPixel(xx + ww, yy, xx + ww, yy + hh), _borderColor, _borderColor); - vp->DrawLine(Line2DPixel(xx, yy + hh, xx + ww, yy + hh), _borderColor, _borderColor); -} - -bool CPlayerPreview::PrepareShapeDrawMatrices(Matrix4Array &matrices, const ObjectVisualState &vs, LODShape *shape, int level) -{ - float phase = _animSpeed * (Glob.uiTime - _animStart); - if (phase >= 1.0) - { - phase = 0; - _animStart = Glob.uiTime; - } - if (_animation) - { - const Shape *shapeL = shape->GetLevelLocked(level); - _animation->PrepareMatrices(matrices, phase, 1.0f, shapeL, shape->GetSkeleton()); - } - - if (_headType) - { - // Get the head bones - if (_head._headBone >= 0) - { - const Shape *shapeL = shape->GetLevelLocked(level); - const SubSkeletonIndexSet &ssis = shapeL->GetSubSkeletonIndexFromSkeletonIndex(_head._headBone); - if (ssis.Size() > 0) - { - // Get the head transformation matrix - Matrix4Par headOrigin = matrices[GetSubSkeletonIndex(ssis[0])]; - - // Go through all the bones with "head" parent and set them the head bone - // This is necessary, because some bones need not to be set during the grimace process - // and we need them to be on proper place - for (int i = 0; i < shapeL->GetSubSkeletonSize(); i++) - { - SubSkeletonIndex ssi; - SetSubSkeletonIndex(ssi, i); - SkeletonIndex si = shapeL->GetSkeletonIndexFromSubSkeletonIndex(ssi); - if (shape->GetSkeleton()->GetParent(si) == _head._headBone) - { - matrices[i] = headOrigin; - } - } - - int grimace = _headType->GetGrimaceIndex("safe"); - _head.SetGrimace(grimace); - - UITime time = Glob.uiTime; - _head.Simulate(time - _lastSimulation, SimulateVisibleNear, false); - _lastSimulation = time; - - float eyeAccom = GScene->MainLight()->GetEyeAdaptMin(); - /* - _headType->PrepareGrimaceMatrices(matrices, _head, _headType, shapeL, headOrigin, VForward, eyeAccom, grimace, grimace, 0); - */ - if (_head._dstGrimace >= 0 && _head._srcGrimace >= 0) - _headType->PrepareGrimaceMatrices(matrices, _head, _headType, shapeL, headOrigin, VForward, eyeAccom, _head._dstGrimace, _head._srcGrimace, _head._factorGrimace); - } - } - } - - return true; -} - -bool CPlayerPreview::IsInside(float x, float y) const -{ - return x >= _x && x <= _x + _w && y >= _y && y <= _y + _h; -} - -void CPlayerPreview::OnLButtonDown(float x, float y) -{ - _moving = true; - _rotateX = x; -} - -void CPlayerPreview::OnLButtonUp(float x, float y) -{ - _moving = false; -} - -void CPlayerPreview::OnMouseMove(float x, float y, bool active) -{ - // rotation speed - static const float speed = 8.0f; - - // hotfix when OnLButtonUp was not called - if (!GInput.mouseL) return; // maybe drag & drop cancel reaction would be needed - - if (_moving) - { - float diff = x - _rotateX; - _rotation += speed * diff; - if (_rotation > H_PI) _rotation -= H_2PI; - else if (_rotation < -H_PI) _rotation += H_2PI; - _rotateX = x; - } -} - -void CPlayerPreview::OnLButtonDblClick(float x, float y) -{ -} - -class CItemPreview : public ControlObject -{ -private: - typedef ControlObject base; - - OLinkPermO(InventoryItem) _item; - - float _x, _y, _w, _h, _z; - - float _rotateX; // position of mouse when rotation started - float _rotation; // total rotation - - // background color - PackedColor _bgColor; - // border color - PackedColor _borderColor; - -public: - CItemPreview(ControlsContainer *parent, int idc, ParamEntryPar cls, InventoryItem *item); - - virtual void OnDraw(float alpha) override; - virtual void OnDrawBackGround(UIViewport *vp, float alpha) override; - - virtual bool IsInside(float x, float y) const override; - - virtual void OnLButtonDown(float x, float y) override; - virtual void OnLButtonUp(float x, float y) override; - virtual void OnMouseMove(float x, float y, bool active = true) override; -}; - -CItemPreview::CItemPreview(ControlsContainer *parent, int idc, ParamEntryPar cls, InventoryItem *item) - : base(parent, idc, cls), _item(item) -{ - _x = cls >> "x"; - _y = cls >> "y"; - _w = cls >> "w"; - _h = cls >> "h"; - _z = cls >> "z"; - - _bgColor = GetPackedColor(cls >> "colorBackground"); - _borderColor = GetPackedColor(cls >> "colorBorder"); - - _rotation = 0; -} - -void CItemPreview::OnDraw(float alpha) -{ - Matrix3 rot(MRotationY, _rotation); - - Color color(0, 0, 0, -1.0f); - CItemBase::DrawItem(_item, _x, _y, _w, _h, _z, alpha, color, &rot); -} - -void CItemPreview::OnDrawBackGround(UIViewport *vp, float alpha) -{ - const int w = GLOB_ENGINE->Width2D(); - const int h = GLOB_ENGINE->Height2D(); - float xx = CX(_x); - float yy = CY(_y); - float ww = CW(_w); - float hh = CH(_h); - - // draw background - Draw2DParsExt pars; - pars.mip = GEngine->TextBank()->UseMipmap(NULL, 0, 0); - pars.SetColor(_bgColor); - pars.Init(); - vp->Draw2D(pars, Rect2DPixel(xx, yy, ww, hh)); - - // draw border - vp->DrawLine(Line2DPixel(xx, yy, xx + ww, yy), _borderColor, _borderColor); - vp->DrawLine(Line2DPixel(xx, yy, xx, yy + hh), _borderColor, _borderColor); - vp->DrawLine(Line2DPixel(xx + ww, yy, xx + ww, yy + hh), _borderColor, _borderColor); - vp->DrawLine(Line2DPixel(xx, yy + hh, xx + ww, yy + hh), _borderColor, _borderColor); -} - -bool CItemPreview::IsInside(float x, float y) const -{ - return x >= _x && x <= _x + _w && y >= _y && y <= _y + _h; -} - -void CItemPreview::OnLButtonDown(float x, float y) -{ - _moving = true; - _rotateX = x; -} - -void CItemPreview::OnLButtonUp(float x, float y) -{ - _moving = false; -} - -void CItemPreview::OnMouseMove(float x, float y, bool active) -{ - // rotation speed - static const float speed = 8.0f; - - // hotfix when OnLButtonUp was not called - if (!GInput.mouseL) return; // maybe drag & drop cancel reaction would be needed - - if (_moving) - { - float diff = x - _rotateX; - _rotation += speed * diff; - if (_rotation > H_PI) _rotation -= H_2PI; - else if (_rotation < -H_PI) _rotation += H_2PI; - _rotateX = x; - } -} - -Display *CreateInventoryDialog(ControlsContainer *parent, AIBrain *me, EntityAI *source) -{ - return new DisplayInventory(parent, me, source); -} - -void CItemBase::DrawTooltip(UIViewport *vp, float x, float y) -{ - const InventoryItem *item = GetItemInfo(x, y)._item; - if (item) - { - DisplayInventory *disp = dynamic_cast(_parent.GetLink()); - if (disp) disp->DrawTooltip(vp, x, y, item); - } -} - -intptr_t CItemBase::GetTooltipArea(float x, float y) -{ - return (intptr_t)(GetItemInfo(x, y)._item); -} - -bool IsInventoryOpened() -{ - return DisplayInventory::IsOpened(); -} - -class DisplayInspect : public Display -{ -private: - Ref _item; - -public: - DisplayInspect(ControlsContainer *parent, InventoryItem *item); - - Control *OnCreateCtrl(int type, int idc, ParamEntryPar cls); - ControlObject *OnCreateObject(int type, int idc, ParamEntryPar cls); -}; - -DisplayInspect::DisplayInspect(ControlsContainer *parent, InventoryItem *item) - : Display(parent), _item(item) -{ - Load("RscDisplayInspect"); -} - -Control *DisplayInspect::OnCreateCtrl(int type, int idc, ParamEntryPar cls) -{ - Control *ctrl = Display::OnCreateCtrl(type, idc, cls); - switch (idc) - { - case IDC_INSPECT_TITLE: - { - ITextContainer *text = GetTextContainer(ctrl); - if (text) text->SetText(_item->GetDisplayName()); - } - break; - case IDC_INSPECT_DESCRIPTION: - { - CStructuredText *text = GetStructuredText(ctrl); - if (text) - { - Ref node = _item->GetTooltip(); - if (node) text->SetText(node); - } - } - break; - } - return ctrl; -} - -ControlObject *DisplayInspect::OnCreateObject(int type, int idc, ParamEntryPar cls) -{ - switch (idc) - { - case IDC_INSPECT_PREVIEW: - return new CItemPreview(this, idc, cls, _item); - default: - return Display::OnCreateObject(type, idc, cls); - } -} - -int DisplayInventory::_instances = 0; -static DisplayInventory *GActiveInventoryDisplay = NULL; -static bool GInventorySpaceKeyDown = false; - -DisplayInventory::DisplayInventory(ControlsContainer *parent, AIBrain *me, EntityAI *source) - : Display(parent), _unit(me), _targetContainer(source), _dragRotated(false) -{ - Load("RscDisplayInventory"); - - ParamEntryVal cls = Pars >> "RscDisplayInventory"; - _dragGridW = cls >> "dragGridW"; - _dragGridH = cls >> "dragGridH"; - _dragZ = cls >> "dragZ"; - _dragColorNone = GetPackedColor(cls >> "dragColorNone"); - _dragColorMove = GetPackedColor(cls >> "dragColorMove"); - _dragColorCraft = GetPackedColor(cls >> "dragColorCraft"); - _dragColorSwap = GetPackedColor(cls >> "dragColorSwap"); - - _tooltipHeight = cls >> "tooltipHeight"; - _tooltipImageWidth = cls >> "tooltipImageWidth"; - _tooltipTextWidth = cls >> "tooltipTextWidth"; - _tooltipTextSize = cls >> "tooltipTextSize"; - _tooltipBgColor = GetPackedColor(cls >> "tooltipBgColor"); - _tooltipLineColor = GetPackedColor(cls >> "tooltipLineColor"); - - ITextContainer *control = GetTextContainer(GetCtrl(IDC_INVENTORY_UNIT)); - if (control) - { - RString name; - int rank = RankUndefined; - if (me->GetPerson()) - { - name = me->GetPerson()->GetPersonName(); - rank = me->GetPerson()->GetRank(); - } - if (me->GetSide() != TCivilian) control->SetText(LocalizeString(IDS_SHORT_PRIVATE + rank) + " " + name); - else control->SetText(name); - } - - // OnUnitChanged(); - _instances++; - GActiveInventoryDisplay = this; -} - -DisplayInventory::~DisplayInventory() -{ - _instances--; - if (GActiveInventoryDisplay == this) - { - GActiveInventoryDisplay = NULL; - GInventorySpaceKeyDown = false; - } - _dragItem = nullptr; - _swapItem = nullptr; - _dragRotated = false; -} - -bool DisplayInventory::OnKeyDown(int dikCode) -{ - if (dikCode == DIK_SPACE) - { - InventoryItem *item = _dragItem; - CItemBase *selectedControl = NULL; - // Space is also the default-button key in ControlsContainer. Always consume - // it here so that an item that cannot rotate (or a missed drag state) does - // not activate the inventory's Close button. - if (!item) - { - const float x = 0.5f + GInput.cursorX * 0.5f; - const float y = 0.5f + GInput.cursorY * 0.5f; - // The held-item panel can contain the dragged item, its attachments, or - // items inside its cargo. Include it in the same cursor hit test as the - // two inventory grids so Space works when the shoe is selected there. - const int itemControls[] = {IDC_INVENTORY_HANDS, IDC_INVENTORY_CONTAINER, IDC_INVENTORY_CONTENT}; - for (int i = 0; i < lenof(itemControls) && !item; i++) - { - CItemBase *control = dynamic_cast(GetCtrl(itemControls[i])); - if (control && control->IsInside(x, y)) - { - item = control->GetItemInfo(x, y)._item; - if (item) selectedControl = control; - } - } - } - // Start the drag on Space if the item is held under the pointer but has - // not yet crossed the regular mouse-movement threshold. - Person *person = _unit ? _unit->GetPerson() : NULL; - const bool itemInHands = person && item && person->GetItemInHands() == item; - if (!_dragItem && item && !itemInHands && selectedControl && GInput.mouseL) - { - selectedControl->BeginDrag(); - item = _dragItem; - } - if (_dragItem) - { - // While dragging, rotate only the preview. The selected orientation is - // sent with the move request when the item is dropped. - if (!itemInHands && _dragItem->Type() && _dragItem->Type()->GetItemWidth() != _dragItem->Type()->GetItemHeight()) - _dragRotated = !_dragRotated; - } - else if (!itemInHands && item && item->Type() && item->GetInventoryWidth() != item->GetInventoryHeight()) - CItemBase::RotateInventoryItem(_unit ? _unit->GetPerson() : NULL, item); - return true; - } - return Display::OnKeyDown(dikCode); -} - -// Shared by World::DoKeyDown and ControlsContainer::OnKeyDown so Space always -// reaches the live inventory, including when its dialog is nested under a -// different display instead of being stored as World::_userDlg. -bool HandleInventorySpaceKey() -{ - if (GActiveInventoryDisplay == NULL || !DisplayInventory::IsOpened()) - return false; - - // Keyboard auto-repeat sends multiple key-down events while Space is held. - // Rotating on every repeat can toggle a 2x1 item back to its original - // orientation before the player sees the result. - if (!GInventorySpaceKeyDown) - { - GInventorySpaceKeyDown = true; - GActiveInventoryDisplay->OnKeyDown(DIK_SPACE); - } - return true; -} - -void ReleaseInventorySpaceKey() -{ - GInventorySpaceKeyDown = false; -} - -Control *DisplayInventory::OnCreateCtrl(int type, int idc, ParamEntryPar cls) -{ - // ui.pbo's legacy ButtonDropHands is destructive (moves null to hands). - // The matching ButtonBackground2 is a separate red RscText in ControlsBackground, - // so omit both controls to remove the icon and its red square. - if (idc == 198 || stricmp(cls.GetName(), "ButtonBackground2") == 0) return NULL; - - // Ignore the legacy hands-drop button and its red background control. - // Dropping the hands item is handled by inventory drag-and-drop instead. - if (idc == 198 || stricmp(cls.GetName(), "ButtonBackground2") == 0) return NULL; - - Control *ctrl = Display::OnCreateCtrl(type, idc, cls); - switch (idc) - { - case IDC_INVENTORY_SOURCE_NAME: - { - //LocalizeString(IDS_UI_INVENTORY_VICINITY) - ITextContainer *text = dynamic_cast(ctrl); - if(_targetContainer) - { - if (_targetContainer->GetType() && _targetContainer->GetType()->IsPerson()) - { - text->SetText(LocalizeString(IDS_UI_INVENTORY_BODY)); - } - else - { - text->SetText(LocalizeString(IDS_UI_INVENTORY_CONTAINER)); - } - } - break; - } - case IDC_INVENTORY_CONTENT_HEADER: - case IDC_INVENTORY_SOLDIER_HEADER: - case IDC_INVENTORY_HANDS_HEADER: - ctrl->EnableCtrl(true); // handle drop events - break; - } - return ctrl; -} - -ControlObject *DisplayInventory::OnCreateObject(int type, int idc, ParamEntryPar cls) -{ - switch (idc) - { - case IDC_INVENTORY_SOLDIER: - return new CPlayerPreview(this, idc, cls, _unit ? _unit->GetPerson() : NULL); - case IDC_INVENTORY_SHORTCUT: - return new CItemShortcut(this, idc, cls, false); - case IDC_INVENTORY_CONTAINER: - return new CItemContainer(this, idc, cls, _unit ? _unit->GetPerson() : NULL, _targetContainer); - case IDC_INVENTORY_CONTENT: - return new CItemContent(this, idc, cls, _unit ? _unit->GetPerson() : NULL); - case IDC_INVENTORY_HANDS: - return new CItemInHands(this, idc, cls, _unit ? _unit->GetPerson() : NULL); - - } - return Display::OnCreateObject(type, idc, cls); -} - -/*! -\patch 5153 Date 4/12/2007 by Jirka -- Fixed: Gear dialog is closed when player dies -*/ - -void DisplayInventory::OnSimulate(EntityAI *vehicle) -{ - extern bool GUAGearActive; - if (GUAGearActive) - { - GInput.GetActionToDo(UAGear); GUAGearActive = false; - Exit(IDC_CANCEL); - return; - } - - // close the dialog when supply source is out of range - EntityAI *source = _targetContainer; - EntityAI *veh = _unit ? _unit->GetVehicle() : NULL; - if (!veh) - { - Exit(IDC_CANCEL); - return; - } - else if (source) - { - // check distance - const Entity::VisualState &vs = source->FutureVisualState(); - Vector3 supplyPos = source->AimingPosition(vs); - int index = source->GetType()->GetSupplyPointIndex(); - if (index >= 0) - { - const LODShape *shape = source->GetShape(); - if (shape) - { - int mem = shape->FindMemoryLevel(); - if (mem >= 0) - { - supplyPos = vs.PositionModelToWorld(source->AnimatePoint(vs, mem, index)); - } - } - } - - // if item is in scene, then exit when not close - if (source->IsInLandscape()) - { - const float supplyRadius = source->GetType()->GetSupplyRadius(); - const float dist2 = veh->FutureVisualState().Position().Distance2(supplyPos); - const float maxDistance = floatMin(1.5f * (veh->CollisionSize() * 1.2f + 1.0f + supplyRadius), 40.0f); - if (dist2 > Square(maxDistance)) - { - Exit(IDC_CANCEL); - return; - } - } - } - - Display::OnSimulate(vehicle); - - // in MP, check if name of the units did not changed - if (GWorld->GetMode() == GModeNetware) - { - //// patch the names of the units - //for (int i=0; i<_weaponsInfo._weapons.Size(); i++) - //{ - // UnitWeaponsInfo &info = _weaponsInfo._weapons[i]; - // AIBrain *unit = info.unit; - // if (!unit) continue; - // Person *person = unit->GetPerson(); - // if (!person) continue; - // info.name = person->GetPersonName(); - //} - - // TODO: update the name - } - //mantain weapon info displayed - GWorld->UI()->ShowWeaponInfo(); - - // if in briefing, preload data for a mission - bool inGame = true;// _pool.IsInGame(); - if (!inGame) - { - GWorld->PreloadAroundCamera(0.030f); // keep reasonable framerate - } - if (GWorld->GetMode() == GModeNetware) - { - if (inGame) - { - if (GetNetworkManager().GetServerState() != NSSPlaying) Exit(IDC_CANCEL); - } - } - if (inGame) - { - // close when the unit is dead - if (!_unit || !_unit->LSIsAlive()) - { - Exit(IDC_CANCEL); - return; - } - } -} - -// check if item can be removed from its owner -static bool CanRemoveItem(const InventoryItem *item) -{ - Entity *parent = item->GetHierarchyParent(); - if (!parent) return true; - return parent->CanRemoveOwnedItem(item); -} - -void DisplayInventory::OnButtonDblClick(IControl *ctrl) -{ - if (ctrl && (ctrl->IDC() == IDC_INVENTORY_CONTAINER || ctrl->IDC() == IDC_INVENTORY_CONTENT)) - { - CItemBase *src = dynamic_cast(ctrl); - if (src) - { - float x = 0.5 + GInput.cursorX * 0.5; - float y = 0.5 + GInput.cursorY * 0.5; - DragItemInfo info = src->GetItemInfo(x, y); - if (info._item && CanRemoveItem(info._item)) - { - Person *person = _unit ? _unit->GetPerson() : NULL; - if (person && person->GetItemInHands() != info._item && CItemBase::CanMoveItem(person, -1, info._item)) - { - CItemBase::MoveItem(person, -1, info._item); - } - } - } - } -} - -void DisplayInventory::OnDrag(IControl *ctrl) -{ - Display::OnDrag(ctrl); - - _dragItem = nullptr; - _swapItem = nullptr; - _dragRotated = false; - - CItemBase *src = dynamic_cast(ctrl); - if (src) - { - // object to be dragged - DragItemInfo info = src->GetDragItemInfo(); - Person *person = _unit ? _unit->GetPerson() : NULL; - const bool isHandsItem = src->IDC() == IDC_INVENTORY_HANDS && person && - person->GetItemInHands() == info._item; - if (info._item && (CanRemoveItem(info._item) || isHandsItem)) - { - _dragItem = info._item; - _dragRotated = info._item->IsInventoryRotated(); - //_dragOffsetX = info._offsetX; - //_dragOffsetY = info._offsetY; - // always drag the top left corner - _dragOffsetX = 0; - _dragOffsetY = 0; - //RptF("### OnDrag: %x %s [%.2f,%.2f]", ctrl, cc_cast(_dragItem->GetName()),_dragOffsetX,_dragOffsetY); - } - } -} - -bool CanSwapItems(InventoryItem *item1, InventoryItem *item2) -{ - if (item1 == item2) return false; - - Entity *parent1 = item1->GetHierarchyParent(); - Entity *parent2 = item2->GetHierarchyParent(); - if (!parent1 && !parent2) return false; - // cannot switch container with a contained item - if (parent1 == item2) return false; - if (parent2 == item1) return false; - - if (parent1 && parent1->CanReplaceOwnedItem(item1, item2) < 0) return false; - if (parent2 && parent2->CanReplaceOwnedItem(item2, item1) < 0) return false; - - return true; -} - -bool SwapItems(InventoryItem *item1, InventoryItem *item2, Person *owner) -{ - if (item1 == item2) return false; - - EntityAI *parent1 = dyn_cast(item1->GetHierarchyParent()); - EntityAI *parent2 = dyn_cast(item2->GetHierarchyParent()); - if (!parent1 && !parent2) return false; - - // cannot switch container with a contained item - if (parent1 == item2) return false; - if (parent2 == item1) return false; - - int index1 = -1, index2 = -1; - if (parent1) - { - index1 = parent1->CanReplaceOwnedItem(item1, item2); - if (index1 < 0) return false; - } - if (parent2) - { - index2 = parent2->CanReplaceOwnedItem(item2, item1); - if (index2 < 0) return false; - } - - if (parent1) parent1->RemoveOwnedItem(item1); - if (parent2) parent2->RemoveOwnedItem(item2); - - if (parent1) parent1->MoveItem(index1, item2); - else - { - if (owner && owner->GetItemInHands() == item2) owner->RemoveItemInHands(); - Vector3Val pos = owner->FutureVisualState().Position(); - Vector3Val dir = owner->FutureVisualState().Direction(); - item2->ItemDrop(nullptr, pos, dir); - } - - if (parent2 == parent1 && !parent2->CanMoveItem(index2, item1)) - { - // hotfix - index2 is already occupied by item2 - // try to move it elsewhere or drop it on ground in worst case - if (parent2->CanMoveItem(-1, item1)) parent2->MoveItem(-1, item1); - else parent2 = nullptr; - } - else if (parent2) - { - parent2->MoveItem(index2, item1); - } - - if (!parent2) - { - if (owner && owner->GetItemInHands() == item1) owner->RemoveItemInHands(); - Vector3Val pos = owner->FutureVisualState().Position(); - Vector3Val dir = owner->FutureVisualState().Direction(); - item1->ItemDrop(nullptr, pos, dir); - } - - DoAssert(item1->GetHierarchyParent() == parent2); - DoAssert(item2->GetHierarchyParent() == parent1); - - return true; -} - -// Temporarily expose the drag-preview orientation to the existing cargo -// validation code, then restore the item's authoritative orientation. -class InventoryRotationPreviewScope -{ -private: - InventoryItem *_item; - bool _original; - Entity *_originalParent; -public: - InventoryRotationPreviewScope(InventoryItem *item, bool rotated) - : _item(item), _original(item ? item->IsInventoryRotated() : false), - _originalParent(item ? item->GetHierarchyParent() : NULL) - { - if (_item) _item->SetInventoryRotated(rotated); - } - ~InventoryRotationPreviewScope() - { - if (_item && _item->GetHierarchyParent() == _originalParent) - _item->SetInventoryRotated(_original); - } - void Commit() - { - if (_item) _original = _item->IsInventoryRotated(); - } -}; - -unsigned char DisplayInventory::OnDragging(IControl *dragCtrl, IControl *dropCtrl, float x, float y) -{ - _swapItem = nullptr; // set it when swapping - - InventoryItem *item = _dragItem; - if (!item) return DANone; - - CItemBase *src = dynamic_cast(dragCtrl); - CItemBase *dst = dynamic_cast(dropCtrl); - if (!src) return DANone; - - InventoryRotationPreviewScope rotationPreview(item, _dragRotated); - - Person *person = _unit ? _unit->GetPerson() : NULL; - const bool handsToVicinity = src->IDC() == IDC_INVENTORY_HANDS && - dropCtrl && dropCtrl->IDC() == IDC_INVENTORY_CONTAINER; - const bool handsToInventory = src->IDC() == IDC_INVENTORY_HANDS && - ((dst && dst->IDC() == IDC_INVENTORY_CONTENT) || - (dropCtrl && dropCtrl->IDC() == IDC_INVENTORY_CONTENT_HEADER)); - const bool handsToGround = src->IDC() == IDC_INVENTORY_HANDS && dropCtrl == NULL; - bool canRemove = !person || person->GetItemInHands() != item || handsToInventory || handsToVicinity || handsToGround; - - int srcShortcut = src->GetShortcutIndex(); - - if (dst) - { - int dstShortcut = dst->GetShortcutIndex(); - - // check if combination is possible - if (srcShortcut < 0 && dstShortcut < 0) - { - if (person) - { - DragItemInfo info = dst->GetItemInfo(x, y); - if (info._item && info._item != item) - { - // look for recipes - // TODO: client-server - bool found = Recipes.Collect(person, item, info._item, - [this, item, &info](const Recipe *recipe) -> bool - { - return true; - }); - if (found) - { - _swapItem = info._item; - return DACraft; - } - - bool canSwap = CanSwapItems(item, info._item); - bool canAddOwnedItem = canRemove && info._item->CanAddOwnedItem(item); - if (canSwap && canAddOwnedItem) - { - _swapItem = info._item; - return DACraft; - } - if (canSwap) - { - _swapItem = info._item; - return DASwap; - } - if (canAddOwnedItem) - { - _swapItem = info._item; - return DAMove; - } - } - } - } - - if (dst->CanAddItem(item, x, y)) - { - if (dstShortcut >= 0) - { - _swapItem = static_cast(dst)->GetItem(); - return DAMove; - } - - // shortcut can be moved to other shortcut only - if (srcShortcut < 0 && canRemove) - return DAMove; - } - - return DANone; - } - else if (dropCtrl && (dropCtrl->IDC() == IDC_INVENTORY_SOLDIER || dropCtrl->IDC() == IDC_INVENTORY_SOLDIER_HEADER)) - { - if (src && (src->IDC() == IDC_INVENTORY_CONTAINER || src->IDC() == IDC_INVENTORY_CONTENT)) - { - if (person && person->GetItemInHands() != item) - { - // try to swap with the current item - const InventoryItemType *type = item->Type(); - if (type) - { - InventorySlotId slot = type->GetInventorySlot(); - InventoryItem *oldItem = person->GetInSlot(slot); - if (oldItem && CanSwapItems(item, oldItem)) - { - _swapItem = oldItem; - return DASwap; - } - } - - if (person->CanAddItem(item)) return DAMove; - } - } - return DANone; - } - else if (dropCtrl && dropCtrl->IDC() == IDC_INVENTORY_CONTENT_HEADER) - { - if (srcShortcut < 0 && canRemove) - { - // redirect from the header to the control itself - CItemBase *dst = dynamic_cast(GetCtrl(IDC_INVENTORY_CONTENT)); - if (dst && dst->CanAddItem(item, 0, 0)) return DAMove; - } - return DANone; - } - else if (dropCtrl && dropCtrl->IDC() == IDC_INVENTORY_HANDS_HEADER) - { - if (srcShortcut < 0 && canRemove) - { - // redirect from the header to the control itself - CItemBase *dst = dynamic_cast(GetCtrl(IDC_INVENTORY_HANDS)); - if (dst && dst->CanAddItem(item, 0, 0)) return DAMove; - } - return DANone; - } - else if (srcShortcut >= 0) // shortcut removed - { - return DAMove; - } - else if (src->IDC() == IDC_INVENTORY_CONTENT && canRemove) - { - return DAMove; - } - else if (canRemove) // dst == 0 and can remove item - { - return DAMove; - } - - return Display::OnDragging(dragCtrl, dropCtrl, x, y); -} - -bool DisplayInventory::OnDrop(IControl *dragCtrl, IControl *dropCtrl, float x, float y) -{ - // whenever dropped, drag & drop is finished - InventoryItem *item = _dragItem; - _dragItem = nullptr; - _swapItem = nullptr; - if (!item) return false; - - CItemBase *src = dynamic_cast(dragCtrl); - CItemBase *dst = dynamic_cast(dropCtrl); - if (!src || !src->IsContained(item)) return false; // check if item still present in the source - - InventoryRotationPreviewScope rotationPreview(item, _dragRotated); - - Person *person = _unit ? _unit->GetPerson() : NULL; - const bool handsToVicinity = src->IDC() == IDC_INVENTORY_HANDS && - dropCtrl && dropCtrl->IDC() == IDC_INVENTORY_CONTAINER; - const bool handsToInventory = src->IDC() == IDC_INVENTORY_HANDS && - ((dst && dst->IDC() == IDC_INVENTORY_CONTENT) || - (dropCtrl && dropCtrl->IDC() == IDC_INVENTORY_CONTENT_HEADER)); - const bool handsToGround = src->IDC() == IDC_INVENTORY_HANDS && dropCtrl == NULL; - bool canRemove = !person || person->GetItemInHands() != item || handsToInventory || handsToVicinity || handsToGround; - - int srcShortcut = src->GetShortcutIndex(); - - if (dst) - { - int dstShortcut = dst->GetShortcutIndex(); - - // offer the combination - if (srcShortcut < 0 && dstShortcut < 0) - { - DragItemInfo info = dst->GetItemInfo(x, y); - if (info._item && info._item != item) - { - Person *person = _unit ? _unit->GetPerson() : NULL; - if (person) - { - bool found = Recipes.Collect(person, item, info._item, - [this, item, &info](const Recipe *recipe) -> bool - { - return true; - }); - if (found && CreateContextMenu(x, y, - IDC_INVENTORY_MENU, Pars >> "RscDisplayInventory" >> "Menu", - CCMContextInventory(item, info._item))) return true; - - bool canSwap = CanSwapItems(item, info._item); - bool canAddOwnedItem = canRemove && info._item->CanAddOwnedItem(item); - if (canSwap && canAddOwnedItem && CreateContextMenu(x, y, - IDC_INVENTORY_MENU, Pars >> "RscDisplayInventory" >> "Menu", - CCMContextInventory(item, info._item))) return true; - - if (canSwap) - { - if (!GetNetworkManager().IsServerOwner()) - { - // BOT client have to handle swapping - GetNetworkManager().AskForSwapItems(item, info._item, person); - return true; - } - else if (SwapItems(item, info._item, person)) return true; - } - - if (canAddOwnedItem) - { - if (!GetNetworkManager().IsServerOwner()) - GetNetworkManager().AskForMoveItem(info._item, -1, item, item->IsInventoryRotated()); // ask server to execute the action - else - { - // remove from the old owner - Entity *parent = item->GetHierarchyParent(); - if (parent) DoVerify(parent->RemoveOwnedItem(item)); - - info._item->AddOwnedItem(item); - rotationPreview.Commit(); - } - return true; - } - } - } - } - - if (dst->CanAddItem(item, x, y)) - { - if (srcShortcut >= 0) - { - // shortcut can be moved to other shortcut only - if (dstShortcut < 0) return false; - // order is important here, item is destroyed when shortcut is removed - CItemBase::SetItemShortcut(dstShortcut, item); - CItemBase::SetItemShortcut(srcShortcut, NULL); - return true; - } - else if (canRemove || dstShortcut >= 0) - { - // do not break layout by removing item first - dst->AddItem(item, x, y); - // shortcut cells only assign the shortcut without moving the item, - // so the previewed rotation must not become authoritative there - if (dstShortcut < 0) - rotationPreview.Commit(); - return true; - } - } - - return false; - } - else if (dropCtrl && (dropCtrl->IDC() == IDC_INVENTORY_SOLDIER || dropCtrl->IDC() == IDC_INVENTORY_SOLDIER_HEADER)) - { - if (src && (src->IDC() == IDC_INVENTORY_CONTAINER || src->IDC() == IDC_INVENTORY_CONTENT)) - { - Person *person = _unit ? _unit->GetPerson() : NULL; - if (person && person->GetItemInHands() != item) - { - // try to swap with the current item - const InventoryItemType *type = item->Type(); - if (type) - { - InventorySlotId slot = type->GetInventorySlot(); - InventoryItem *oldItem = person->GetInSlot(slot); - if (oldItem) - { - if (!GetNetworkManager().IsServerOwner()) - { - // BOT client have to handle swapping - if (CanSwapItems(item, oldItem)) - { - GetNetworkManager().AskForSwapItems(item, oldItem, person); - return true; - } - } - else if (SwapItems(item, oldItem, person)) return true; - } - } - - if (CItemBase::CanMoveItem(person, -1, item)) - { - CItemBase::MoveItem(person, -1, item); - return true; - } - } - } - return false; - } - else if (dropCtrl && dropCtrl->IDC() == IDC_INVENTORY_CONTENT_HEADER) - { - if (srcShortcut < 0 && canRemove) - { - // redirect from the header to the control itself - CItemBase *dst = dynamic_cast(GetCtrl(IDC_INVENTORY_CONTENT)); - if (dst && dst->CanAddItem(item, 0, 0)) - { - dst->AddItem(item, x, y); - return true; - } - } - return false; - } - else if (dropCtrl && dropCtrl->IDC() == IDC_INVENTORY_HANDS_HEADER) - { - if (srcShortcut < 0 && canRemove) - { - // redirect from the header to the control itself - CItemBase *dst = dynamic_cast(GetCtrl(IDC_INVENTORY_HANDS)); - if (dst && dst->CanAddItem(item, 0, 0)) - { - dst->AddItem(item, x, y); - return true; - } - } - return false; - } - else if (srcShortcut >= 0) // shortcut removed - { - CItemBase::SetItemShortcut(srcShortcut, NULL); - return true; - } - else if (src->IDC() == IDC_INVENTORY_CONTENT && canRemove) - { - Person *person = _unit ? _unit->GetPerson() : NULL; - if (person) CItemBase::DropItem(person, item); - return true; - } - else if (canRemove) // dst == 0 and canRemove - { - Person *person = _unit ? _unit->GetPerson() : NULL; - if (person) CItemBase::DropItem(person, item); - return true; - } - - return Display::OnDrop(dragCtrl, dropCtrl, x, y); -} - -void DisplayInventory::DrawDragInfo(float x, float y, unsigned char enabled, Ref dragFont, float dragSize) -{ - if (!_dragItem) return; - const InventoryItemType *type = _dragItem->Type(); - if (!type) return; - - float dragX = x - _dragOffsetX; - float dragY = y - _dragOffsetY; - float dragW = (_dragRotated ? type->GetItemHeight() : type->GetItemWidth()) * _dragGridW; - float dragH = (_dragRotated ? type->GetItemWidth() : type->GetItemHeight()) * _dragGridH; - - PackedColor dragColor; - switch (enabled) - { - case DANone: - dragColor = _dragColorNone; - break; - case DAMove: - dragColor = _dragColorMove; - break; - case DACraft: - dragColor = _dragColorCraft; - break; - case DASwap: - dragColor = _dragColorSwap; - break; - } - PackedColor dragColorLine = PackedBlack; - - int w = GEngine->Width2D(); - int h = GEngine->Height2D(); - - MipInfo mip = GLOB_ENGINE->TextBank()->UseMipmap(NULL, 0, 0); - GEngine->Draw2D(mip, dragColor, Rect2DPixel(CX(dragX), CY(dragY), CW(dragW), CH(dragH))); - - GEngine->DrawText( - Point2DFloat(dragX, dragY - dragSize), - dragSize, dragFont, - dragColor, - type->GetDisplayName(), true); - - GEngine->DrawLine(Line2DFloat(dragX, dragY, dragX + dragW, dragY), dragColorLine, dragColorLine); - GEngine->DrawLine(Line2DFloat(dragX + dragW, dragY, dragX + dragW, dragY + dragH), dragColorLine, dragColorLine); - GEngine->DrawLine(Line2DFloat(dragX + dragW, dragY + dragH, dragX, dragY + dragH), dragColorLine, dragColorLine); - GEngine->DrawLine(Line2DFloat(dragX, dragY + dragH, dragX, dragY), dragColorLine, dragColorLine); - - Color color(0, 0, 0, -1.0f); - CItemBase::DrawItem(_dragItem, dragX, dragY, dragW, dragH, _dragZ, 1.0f, color); -} - -void DisplayInventory::DrawTooltip(UIViewport *vp, float x, float y, const InventoryItem *item) -{ - const InventoryItemType *type = item->Type(); - if (!type) return; - - // offset the position a bit from the cursor's TL - float cX = GetCursorX(); - float cY = GetCursorY(); - x += (16.0f / 800.0f) * (1.0f - cX); - y += (16.0f / 600.0f) * (1.0f - cY); - - int w = GEngine->Width2D(); - int h = GEngine->Height2D(); - - Rect2DFloat textRect(0, 0, _tooltipTextWidth - 2 * TEXT_BORDER, 0); - RefR text = unconst_cast(item)->GetTooltip(); - - // calculate the area - float width = _tooltipImageWidth + _tooltipTextWidth; - float height = text ? GetTextHeight(text, textRect, _tooltipTextSize) + 2 * TEXT_BORDER : 0; - saturateMax(height, _tooltipHeight); - - // keep in the safe area - AspectSettings as; - GEngine->GetAspectSettings(as); - - float safeLeft, safeTop, safeRight, safeBottom; - as.GetUISafeArea(safeLeft, safeTop, safeRight, safeBottom); - - if (x < safeLeft) - x = safeLeft; - else if (x + width > safeRight) - x = safeRight - width; - if (y < safeTop) - y = safeTop; - else if (y + height > safeBottom) - y = safeBottom - height; - - float xx = CX(x), yy = CY(y), ww = CW(width), hh = CH(height); - MipInfo mip = GLOB_ENGINE->TextBank()->UseMipmap(NULL, 0, 0); - GEngine->Draw2D(mip, _tooltipBgColor, Rect2DPixel(xx, yy, ww, hh)); - GEngine->DrawLine(Line2DPixel(xx, yy, xx + ww, yy), _tooltipLineColor, _tooltipLineColor); - GEngine->DrawLine(Line2DPixel(xx + ww, yy, xx + ww, yy + hh), _tooltipLineColor, _tooltipLineColor); - GEngine->DrawLine(Line2DPixel(xx + ww, yy + hh, xx, yy + hh), _tooltipLineColor, _tooltipLineColor); - GEngine->DrawLine(Line2DPixel(xx, yy + hh, xx, yy), _tooltipLineColor, _tooltipLineColor); - - Color color(0, 0, 0, -1.0f); - CItemBase::DrawItem(unconst_cast(item), x, y, _tooltipImageWidth, height, _dragZ, 1.0f, color); - - if (text) DrawText(vp, text, Rect2DFloat(x +_tooltipImageWidth + TEXT_BORDER, y + TEXT_BORDER, _tooltipTextWidth - 2 * TEXT_BORDER, height - 2 * TEXT_BORDER), _tooltipTextSize); -} - -DisplayInventory::MenuItemAction::MenuItemAction(AIBrain *unit, InventoryItem *item, Action *action, DisplayInventory *parent) - : MenuItem(action->GetText(unit), MCAction), _item(item), _action(action), _parent(parent) -{ -} - -void DisplayInventory::MenuItemAction::Invoke(AIBrain *unit) -{ - if (_item) - { - // simple UI action, handle directly - if (_action->GetType() == ATInspect) - _parent->CreateChild(new DisplayInspect(_parent, _item)); - // shortcut for ATGear action ... we want to create dialog on client, so avoid sending to server and back - else if (!GetNetworkManager().IsServerOwner() && _action->GetType() != ATGear) - GetNetworkManager().ProcessAction(_action, unit); // ask server to execute the action - else - unit->GetVehicle()->StartActionProcessing(_action, unit); - } -} - -DisplayInventory::MenuItemRecipe::MenuItemRecipe(AIBrain *unit, InventoryItem *item1, InventoryItem *item2, const Recipe *recipe) - : MenuItem(recipe->GetDescription(unit->GetPerson(), item1, item2), MCRecipe), _item1(item1), _item2(item2), _recipe(recipe) -{ -} - -void DisplayInventory::MenuItemRecipe::Invoke(AIBrain *unit) -{ - Person *person = unit->GetPerson(); - if (!person) return; - - if (!GetNetworkManager().IsServerOwner()) - GetNetworkManager().ProcessRecipe(_recipe->_name, person, _item1, _item2); // ask server to execute the action - else - _recipe->Process(person, _item1, _item2); -} - -DisplayInventory::MenuItemSwapItems::MenuItemSwapItems(InventoryItem *item1, InventoryItem *item2) - : MenuItem(CreateTextASCII(NULL, Format(LocalizeString(IDS_INVENTORY_SWAP_ITEMS), cc_cast(item1->GetDisplayName()), cc_cast(item2->GetDisplayName()))), MCSwap), _item1(item1), _item2(item2) -{ -} - -void DisplayInventory::MenuItemSwapItems::Invoke(AIBrain *unit) -{ - Person *person = unit->GetPerson(); - if (!person) return; - - if (!GetNetworkManager().IsServerOwner()) - GetNetworkManager().AskForSwapItems(_item1, _item2, person); - else - SwapItems(_item1, _item2, person); -} - -DisplayInventory::MenuItemAddItem::MenuItemAddItem(InventoryItem *item1, InventoryItem *item2, bool attachment) - : MenuItem(CreateTextASCII(NULL, Format(LocalizeString(attachment ? IDS_INVENTORY_ADD_ATTACHMENT : IDS_INVENTORY_ADD_ITEM), cc_cast(item1->GetDisplayName()), cc_cast(item2->GetDisplayName()))), MCAdd), - _item1(item1), _item2(item2) -{ -} - -void DisplayInventory::MenuItemAddItem::Invoke(AIBrain *unit) -{ - if (!_item2->CanAddOwnedItem(_item1)) return; - - if (!GetNetworkManager().IsServerOwner()) - GetNetworkManager().AskForMoveItem(_item2, -1, _item1, _item1->IsInventoryRotated()); // ask server to execute the action - else - { - // remove from the old owner - Entity *parent = _item1->GetHierarchyParent(); - if (parent) DoVerify(parent->RemoveOwnedItem(_item1)); - - _item2->AddOwnedItem(_item1); - } -} - -bool DisplayInventory::OnMenuCreated(Menu &menu, float x, float y, int idc, CCMContext &ctx) -{ - if (!_unit) return false; - - CCMContextInventory &context = static_cast(ctx); - if (!context._item1) return false; - Person *person = _unit->GetPerson(); - if (!person) return false; - - bool canRemove = person->GetItemInHands() != context._item1; // item in hands cannot be removed - - if (!GetNetworkManager().IsServerOwner()) - { - // BOT client have to handle it - GetNetworkManager().AskInventoryMenu(_unit, context._item1, context._item2); - MenuItem *item = new MenuItem(CreateTextASCII(NULL, LocalizeString(IDS_LOAD_WORLD)), MCWait); - item->_enable = false; - menu.AddItem(item); - return true; - } - - if (context._item2) - { - // recipes - Recipes.Collect(person, context._item1, context._item2, - [this, &context, &menu](const Recipe *recipe) -> bool - { - MenuItem *item = new MenuItemRecipe(_unit, context._item1, context._item2, recipe); - menu.AddItem(item); - return false; // continue - }); - - if (canRemove && context._item2->CanAddAttachment(context._item1)) - { - MenuItem *item = new MenuItemAddItem(context._item1, context._item2, true); - menu.AddItem(item); - } - else if (canRemove && context._item2->CanAddOwnedItem(context._item1)) - { - MenuItem *item = new MenuItemAddItem(context._item1, context._item2, false); - menu.AddItem(item); - } - - if (canRemove && CanSwapItems(context._item1, context._item2)) - { - MenuItem *item = new MenuItemSwapItems(context._item1, context._item2); - menu.AddItem(item); - } - } - else - { - // collect actions - context._item1->GetActions( - [this, &context, &menu](const UIAction &action) -> void - { - MenuItem *menuItem = new MenuItemAction(_unit, context._item1, action.action, this); - menu.AddItem(menuItem); - }, - _unit); - - Ref action = new ActionBasic(ATInspect, context._item1); - MenuItem *menuItem = new MenuItemAction(_unit, context._item1, action, this); - menu.AddItem(menuItem); - } - - return menu._items.Size() > 0; -} - -void DisplayInventory::OnMenuSelected(MenuItem *item) -{ - switch (item->_cmd) - { - case MCAction: - if (_unit) - { - MenuItemAction *act = static_cast(item); - act->Invoke(_unit); - } - break; - case MCRecipe: - if (_unit) - { - MenuItemRecipe *act = static_cast(item); - act->Invoke(_unit); - } - break; - case MCAdd: - if (_unit) - { - MenuItemAddItem *act = static_cast(item); - act->Invoke(_unit); - } - break; - case MCSwap: - { - MenuItemSwapItems *act = static_cast(item); - act->Invoke(_unit); - } - break; - } -} - -void ShowInventoryMenu(AbstractOptionsUI *dlg, const InventoryMenuMessage &msg) -{ - // find the Inventory dialog in hierarchy - ControlsContainer *ptr = dynamic_cast(dlg); - while (ptr) - { - if (ptr->IDD() == IDD_INVENTORY) break; - ptr = ptr->Child(); - } - - if (ptr) - { - DisplayInventory *inventory = dynamic_cast(ptr); - if (inventory) inventory->ShowInventoryMenu(msg); - } -} - -void DisplayInventory::ShowInventoryMenu(const InventoryMenuMessage &msg) -{ - if (!_unit) return; - - // check the message - Person *person = msg._unit; - if (!person) return; - if (person->Brain() != _unit) return; - if (!msg._item1) return; - - // find the opened context menu - Menu *menu = FindContextMenu(); - if (!menu) return; - - menu->_items.Clear(); - for (int i=0; i action; - if (src._actionType >= 0) action = CreateAction((UIActionType)src._actionType); - if (action) - { - action->SetTarget(src._actionTarget); - QIStrStream in(src._actionParams.Data(), src._actionParams.Size()); - action->LoadParams(in); - - MenuItem *item = new MenuItemAction(_unit, msg._item1, action, this); - menu->AddItem(item); - } - } - - for (int i=0; iAddItem(item); - } - } - - for (int i=0; iAddItem(item); - } - - if (msg._swap) - { - MenuItem *item = new MenuItemSwapItems(msg._item1, msg._item2); - menu->AddItem(item); - } - - if (!msg._item2) - { - Ref action = new ActionBasic(ATInspect, msg._item1); - MenuItem *menuItem = new MenuItemAction(_unit, msg._item1, action, this); - menu->AddItem(menuItem); - } - - if (menu->_items.Size() == 0) RemoveContextMenu(); - else ContextMenuUpdated(); -} - -#if _ENABLE_IDENTITIES - -class DisplayEditDiaryRecord : public Display -{ -protected: - int _recordId; - InitPtr _title; - InitPtr _text; - -public: - DisplayEditDiaryRecord(ControlsContainer *parent, int recordId, RString title, RString text); - Control *OnCreateCtrl(int type, int idc, ParamEntryPar cls); - bool CanDestroy(); - int GetRecordId() const {return _recordId;} - RString GetTitle() const; - RString GetText() const; -}; - -DisplayEditDiaryRecord::DisplayEditDiaryRecord(ControlsContainer *parent, int recordId, RString title, RString text) - : Display(parent) -{ - _recordId = recordId; - Load("RscDisplayEditDiaryRecord"); - if (parent && !parent->SimulationEnabled()) _enableSimulation = false; - if (_title) _title->SetText(title); - if (_text) _text->SetText(text); -} - -Control *DisplayEditDiaryRecord::OnCreateCtrl(int type, int idc, ParamEntryPar cls) -{ - Control *ctrl = Display::OnCreateCtrl(type, idc, cls); - switch (idc) - { - case IDC_EDIT_DIARY_TITLE: - _title = GetEditContainer(ctrl); - break; - case IDC_EDIT_DIARY_RECORD: - _text = GetEditContainer(ctrl); - break; - } - return ctrl; -} - -bool DisplayEditDiaryRecord::CanDestroy() -{ - if (!Display::CanDestroy()) return false; - - if (_exit == IDC_OK) - { - if (GetTitle().IsEmpty()) - { - CreateMsgBox(MB_BUTTON_OK, LocalizeString(IDS_MSG_RECORDTITLE_EMPTY)); - return false; - } - } - - return true; -} - -RString DisplayEditDiaryRecord::GetText() const -{ - if (!_text) return RString(); - return _text->GetText(); -} - -RString DisplayEditDiaryRecord::GetTitle() const -{ - if (!_title) return RString(); - return _title->GetText(); -} - -#endif - -#if _VBS2 -DisplayMap::DisplayMap(ControlsContainer *parent) - : Display(parent) -{ - _alwaysShow = true; - _cursor = CursorArrow; - _selectWeapons = false; - _showGearOnExit = false; - _briefingEnabled = true; - _saveParams = true; - _xboxStyle = false; - _updatePlanAsked = false; - _compassDir = Vector3(0, 0, 1); -} -#endif - -/*! -\patch 1.07 Date 7/20/2001 by Jirka -- Fixed: after install or new user create marker centering in map does not work properly -\patch 5126 Date 2/1/2007 by Jirka -- New: Possibility to show satellite textures in the in-game map and briefing -*/ - -DisplayMap::DisplayMap(ControlsContainer *parent, RString resource) - : Display(parent) -{ - _alwaysShow = true; - - _cursor = CursorArrow; - _selectWeapons = false; - _showGearOnExit = false; - - _briefingEnabled = true; -#if _VBS3 - _compassDir = Vector3(0, 0, 1); -#endif - - ProgressRefresh(); - Load(resource); - ProgressRefresh(); - - ParamEntryVal cls = Pars >> resource; - - _saveParams = true; - ConstParamEntryPtr entry = cls.FindEntry("saveParams"); - if (entry) _saveParams = *entry; - - _xboxStyle = false; - entry = cls.FindEntry("xboxStyle"); - if (entry) _xboxStyle = *entry; - - _updatePlanAsked = false; - - // FIX - AdjustMapVisibleRect(); - - Init(); - ResetHUD(); - - ShowMap(true); - ShowWalkieTalkie(true); - ShowNotepad(true); - ShowWarrant(false); - ShowGPS(true); - - ShowBriefing(false); - - UpdateTexturesButton(); -} - -void ValidateMarker(CHTMLContainer *html, bool inc, bool next) -{ - CHTMLContainer::FieldIndex i = html->GetActiveFieldIndex(); - if (!i.IsValid()) return; - const HTMLSection &s = html->GetSection(i._section); - int n = s.fields.Size(); - if (next) - { - if (inc) - { - i._field++; - if (i._field >= n) i._field = 0; - } - else - { - i._field--; - if (i._field < 0) i._field = n - 1; - } - } - saturate(i._field, 0, n); - - const char *name = "marker:"; - int len = strlen(name); - if (inc) - { - for (int j=i._field; jSetActiveFieldIndex(CHTMLContainer::FieldIndex(i._section, j)); - return; - } - for (int j=0; jSetActiveFieldIndex(CHTMLContainer::FieldIndex(i._section, j)); - return; - } - } - else - { - for (int j=i._field; j>=0; j--) - if (strnicmp(s.fields[j].href, name, len) == 0) - { - html->SetActiveFieldIndex(CHTMLContainer::FieldIndex(i._section, j)); - return; - } - for (int j=n-1; j>i._field; j--) - if (strnicmp(s.fields[j].href, name, len) == 0) - { - html->SetActiveFieldIndex(CHTMLContainer::FieldIndex(i._section, j)); - return; - } - } -} - -void DisplayMap::SwitchBriefingSection(RString section) -{ - if (_briefing) - { - _briefing->SwitchSection(section); - ValidateMarker(_briefing, true, false); - } -} - -DisplayMap::~DisplayMap() -{ - SaveParams(); -} - -bool DisplayMap::IsShownWalkieTalkie() const -{ - return _walkieTalkie ? _walkieTalkie->IsVisible() : false; -} - -bool DisplayMap::IsShownNotepad() const -{ - return _notepad ? _notepad->IsVisible() : false; -} - -bool DisplayMap::IsBriefingUsed() const -{ - return GetCtrl(IDC_NOTEPAD_PICTURE) != NULL; -} - -bool DisplayMap::IsShownBriefing() const -{ - const IControl *pad = GetCtrl(IDC_NOTEPAD_PICTURE); - return pad ? pad->IsVisible() : false; -} - -bool DisplayMap::IsShownWarrant() const -{ - return _warrant ? _warrant->IsVisible() : false; -} - -void DisplayMap::ShowWalkieTalkie(bool show) -{ - if (_walkieTalkie) _walkieTalkie->ShowCtrl(show); -} - -void DisplayMap::ShowNotepad(bool show) -{ - if (_notepad) - { - _notepad->ShowCtrl(show); - AdjustMapVisibleRect(); - } - _briefingEnabled = show; - if (!show) ShowBriefing(false); -} - -void DisplayMap::ShowWarrant(bool show) -{ - if (_warrant) _warrant->ShowCtrl(show); -} - -int FindSectionForUnit(HTMLContent &html, RString sectionName, TargetSide side, AIBrain *unit) -{ - RString prefix = sectionName + RString("."); - int section = -1; - if (unit) - { - RString name = unit->GetVehicle()->GetVarName(); - if (name.GetLength() > 0) - { - section = html.FindSection(prefix + name); - } - } - if (section < 0) - { - RString name; - switch (side) - { - case TWest: - name = prefix + RString("West"); goto SideFound; - case TEast: - name = prefix + RString("East"); goto SideFound; - case TGuerrila: - name = prefix + RString("Guerrila"); goto SideFound; - case TCivilian: - name = prefix + RString("Civilian"); goto SideFound; -SideFound: - section = html.FindSection(name); - break; - } - } - if (section < 0) section = html.FindSection(sectionName); - return section; -} - -int FindSectionForUnit(HTMLContent &html, RString sectionName, AIBrain *unit) -{ - TargetSide side = unit->GetSide(); - return FindSectionForUnit(html, sectionName, side, unit); -} - -static void AddObjective(CHTMLContainer *html, int src, int dst, int value) -{ - if (value == OSHidden) return; - - ParamEntryVal cls = Pars >> "RscObjectives"; - RString picture; - switch (value) - { - case OSDone: - picture = cls >> "done"; - break; - case OSFailed: - picture = cls >> "failed"; - break; - default: - Fail("Unknown objective type"); - case OSActive: - picture = cls >> "active"; - break; - } - html->AddBreak(dst, false); - float imgHeight = 480.0f * 1.0f * html->GetPHeight(); - HTMLField *fld = html->AddImage(dst, picture, HALeft, false, -1, imgHeight, ""); - fld->exclude = true; - float indent = 1.2 * fld->width; - html->SetIndent(indent); - html->CopySection(src, dst); - html->SetIndent(0); -} - -static void AddTasks(CHTMLContainer *html, int dst, Person *player) -{ -#if _ENABLE_IDENTITIES - - const RefArray tasks = player->GetIdentity().GetSimpleTasks(); - ParamEntryVal cls = Pars >> "RscObjectives"; - RString picture; - - for (int i=0; i< tasks.Size(); i++) - { - switch (tasks[i]->GetState()) - { - case TSSucceeded: - picture = cls >> "done"; - break; - case TSFailed: - picture = cls >> "failed"; - break; - case TSCanceled: - picture = cls >> "cancled"; - break; - case TSCreated: - case TSNone: - case TSAssigned: - picture = cls >> "active"; - break; - default: - Fail("Unknown objective type"); - break; - } - - html->AddBreak(dst, false); - float imgHeight = 480.0f * 1.0f * html->GetPHeight(); - html->SetIndent(0); - HTMLField *fld = html->AddImage(dst, picture, HALeft, false, -1, imgHeight, ""); - fld->exclude = true; - float indent = 1.2 * fld->width; - - RString taskdesc; - tasks[i]->GetDescriptionShort(taskdesc); - html->SetIndent(indent); - html->AddText(dst,taskdesc,HFP,HALeft,false,false,"",0,0,false); - html->AddBreak(dst, false); - } - html->SetIndent(0); - - -#endif -} - -//! updates mission plan section of briefing -bool UpdatePlan(CHTMLContainer *briefing, TargetSide side, AIBrain *unit) -{ - // init section - bool actual = false; - int section = briefing->FindSection("__PLAN"); - if (section < 0) - { - section = briefing->AddSection(); - } - else - { - briefing->InitSection(section); - if (briefing->CurrentSection() == section) actual = true; - int s; - while ((s = briefing->FindSection("__PLAN")) >= 0) - { - if (briefing->CurrentSection() == s) actual = true; - briefing->RemoveSection(s); - } - } - briefing->AddName(section, "__PLAN"); - - // plan header - int source = FindSectionForUnit(*briefing, "Plan", side, unit); - if (source >= 0) briefing->CopySection(source, section); - - // objectives - for (int s=0; sNSections(); s++) - { - const HTMLSection &src = briefing->GetSection(s); - for (int n=0; n