From 799028753846a1630b0e388e3cba08165701cfe4 Mon Sep 17 00:00:00 2001 From: Arthurnashh Date: Mon, 23 Nov 2026 21:15:16 -0300 Subject: [PATCH] Persist vehicles and tents on the game server --- lib/gameStateExt.cpp | 373 ++++++++++++++++++ .../server/DayZLocalPersistence.ps1 | 286 ++++++++++++++ .../dz_worldPersist.sqf | 150 +++++++ .../dayz_Auto.ChernarusPlus/init.sqf | 3 + 4 files changed, 812 insertions(+) create mode 100644 release-assets/server/DayZLocalPersistence.ps1 create mode 100644 release-assets/server/MPMissions/dayz_Auto.ChernarusPlus/dz_worldPersist.sqf diff --git a/lib/gameStateExt.cpp b/lib/gameStateExt.cpp index 708bc5f8..fed85db7 100644 --- a/lib/gameStateExt.cpp +++ b/lib/gameStateExt.cpp @@ -18243,6 +18243,374 @@ int DBGetItemCount( void ) } +//----------------------------------------------------------------------------- +// World object persistence (vehicles / tents) +//----------------------------------------------------------------------------- + +static void DBWorldSaveState( EntityAI *veh, JSONValue &document, JSONAllocator &allocator ) +{ + // synchronized / stored variables (fuel, engine state, custom script vars) + // JSONSaveVariables creates document["state"] and fills state.vars. + veh->JSONSaveVariables(document, allocator); + + if (!document.HasMember("state")) + { + JSONValue state; + state.SetObject(); + document.AddMember("state", state, allocator); + } + + JSONValue &state = document["state"]; + if (!state.IsObject()) + return; + + // item cargo (tents and vehicles with itemsCargoSize) + ResourceSupply *supply = veh->GetSupply(); + if (supply) + { + JSONValue items; + items.SetArray(); + supply->ForEachItemCargo([&items, &allocator](const InventoryItem *item) -> bool + { + if (!item) return false; + + JSONValue value; + value.SetObject(); + value.AddMember("type", item->GetName(), allocator); + item->JSONSave(value, allocator); + items.PushBack(value, allocator); + return false; // continue + }, false /*avoid recursion*/); + + if (items.Size() > 0) + state.AddMember("items", items, allocator); + } + + float damage = veh->GetTotalDamage(); + if (damage > 0) + state.AddMember("damage", damage, allocator); +} + +static void DBWorldLoadState( EntityAI *veh, JSONValue &document ) +{ + if (!document.HasMember("state")) + return; + + JSONValue &state = document["state"]; + if (!state.IsObject()) + return; + + veh->JSONLoadVariables(document); + + if (state.HasMember("items")) + { + JSONValue &items = state["items"]; + ResourceSupply *supply = veh->GetSupply(); + if (supply && items.IsArray()) + { + for (rapidjson::SizeType i = 0; i < items.Size(); i++) + { + JSONValue &value = items[i]; + if (!value.IsObject() || !value.HasMember("type")) continue; + + JSONValue &vtype = value["type"]; + if (!vtype.IsString()) continue; + + Ref item = dyn_cast(GWorld->NewNonAIVehicleWithID(vtype.GetString(), RString())); + if (!item) continue; + if (!item->JSONLoad(value, NULL)) continue; + + GWorld->AddOutVehicle(item); + int index = supply->GetItemsCargo().CanAddItem(item); + if (index >= 0) + { + item->SetMoveOutDone(veh); + supply->GetItemsCargo().AddItem(veh, item, index); + } + } + } + } + + if (state.HasMember("damage")) + { + JSONValue &vdamage = state["damage"]; + if (vdamage.IsNumber()) + veh->SetDamage((float)vdamage.GetDouble(), true); + } + + if (document.HasMember("fuel")) + { + JSONValue &vfuel = document["fuel"]; + if (vfuel.IsNumber()) + veh->Refuel((float)vfuel.GetDouble() - veh->GetFuel()); + } +} + +static void DBWorldBuildBody( EntityAI *veh, JSONValue &document, JSONAllocator &allocator ) +{ + const Matrix4 &trans = veh->FutureVisualState().Transform(); + JSONAddMatrix4(document, "mt", trans, allocator); + + DBWorldSaveState(veh, document, allocator); + document.AddMember("fuel", veh->GetFuel(), allocator); +} + +static int DBWorldAddSync( EntityAI *veh ) +{ + RString url; + BuildServerRequest(ESERVLET_WORLD,url,"add"); + + JSONDocument document; + document.SetObject(); + JSONAllocator& allocator = document.GetAllocator(); + + document.AddMember( "type", veh->GetType()->GetName(), allocator ); + document.AddMember( "imp", 100, allocator ); + + DBWorldBuildBody(veh, document, allocator); + + JSONBuffer buffer; + JSONWriter writer(buffer); + document.Accept(writer); + + RString postData = buffer.GetString(); + RString result; + + int err = GetResponse(EHTTPREQ_POST,result,url,"?shard=11223344",postData); + if (err >= 400) + { + LogF("HTTP Error: %d", err); + LogF(result); + return 0; + } + + JSONDocument reply; + reply.Parse(result); + if (!reply.Empty() && reply.HasMember("id")) + { + JSONValue &vid = reply["id"]; + if (vid.IsInt()) + return vid.GetInt(); + } + + return 0; +} + +static bool DBWorldUpdateSync( int id, EntityAI *veh ) +{ + if (id <= 0 || !veh) + return false; + + RString url; + BuildServerRequest(ESERVLET_WORLD,url,"update"); + + JSONDocument document; + document.SetObject(); + JSONAllocator& allocator = document.GetAllocator(); + + document.AddMember( "item", id, allocator ); + + DBWorldBuildBody(veh, document, allocator); + + JSONBuffer buffer; + JSONWriter writer(buffer); + document.Accept(writer); + + RString postData = buffer.GetString(); + RString result; + + int err = GetResponse(EHTTPREQ_POST,result,url,"?shard=11223344",postData); + if (err >= 400) + { + LogF("HTTP Error: %d", err); + LogF(result); + return false; + } + + return true; +} + +GameValue DBWorldAdd( const GameState *state, GameValuePar oper1 ) +{ + if (!GetNetworkManager().IsServerOwner()) + { + state->AccessError("dbWorldAdd"); + return 0.0f; + } + + Object *obj = GetObject(oper1); + EntityAI *veh = dyn_cast(obj); + if (!veh) + return 0.0f; + + return (float)DBWorldAddSync(veh); +} + +GameValue DBWorldSave( const GameState *state, GameValuePar oper1 ) +{ + if (!GetNetworkManager().IsServerOwner()) + { + state->AccessError("dbWorldSave"); + return false; + } + + const GameArrayType &array = oper1; + if (array.Size() != 2) + { + state->SetError(EvalDim, array.Size(), 2); + return false; + } + + if (!CheckType(state, array[0], GameScalar)) return false; + if (!CheckType(state, array[1], GameObject)) return false; + + float fid = array[0]; + int id = (int)fid; + + Object *obj = GetObject(array[1]); + EntityAI *veh = dyn_cast(obj); + if (!veh) + return false; + + return DBWorldUpdateSync(id, veh); +} + +GameValue DBWorldRemove( const GameState *state, GameValuePar oper1 ) +{ + if (!GetNetworkManager().IsServerOwner()) + { + state->AccessError("dbWorldRemove"); + return false; + } + + float fid = oper1; + int id = (int)fid; + if (id <= 0) + return false; + + return DBRemoveItem(id); +} + +GameValue DBWorldList( const GameState *state ) +{ + RString url; + BuildServerRequest(ESERVLET_WORLD,url,"list"); + + RString result; + int err = GetResponse(EHTTPREQ_GET,result,url,"?shard=11223344",NULL); + if (err >= 400) + { + LogF("HTTP Error: %d", err); + LogF(result); + return state->CreateGameValue(GameArray); + } + + GameValue value = state->CreateGameValue(GameArray); + GameArrayType &array = value; + + JSONDocument document; + document.Parse(result); + if (!document.Empty() && document.HasMember("ids")) + { + JSONValue &ids = document["ids"]; + if (ids.IsArray()) + { + array.Resize(ids.Size()); + for (rapidjson::SizeType i = 0; i < ids.Size(); i++) + array[i] = (float)ids[i].GetInt(); + } + } + + return value; +} + +GameValue DBWorldSpawn( const GameState *state, GameValuePar oper1 ) +{ + if (!GetNetworkManager().IsServerOwner()) + { + state->AccessError("dbWorldSpawn"); + return GameValueExt(nullptr,GameValExtObject); + } + + float fid = oper1; + int id = (int)fid; + if (id <= 0) + return GameValueExt(nullptr,GameValExtObject); + + RString url; + BuildServerRequest(ESERVLET_WORLD,url,"get"); + + JSONDocument request; + request.SetObject(); + JSONAllocator& allocator = request.GetAllocator(); + request.AddMember( "item", id, allocator ); + + JSONBuffer buffer; + JSONWriter writer(buffer); + request.Accept(writer); + + RString postData = buffer.GetString(); + RString result; + + int err = GetResponse(EHTTPREQ_POST,result,url,NULL,postData); + if (err >= 400) + { + LogF("HTTP Error: %d", err); + LogF(result); + return GameValueExt(nullptr,GameValExtObject); + } + + JSONDocument document; + document.Parse(result); + if (document.Empty() || !document.HasMember("type")) + return GameValueExt(nullptr,GameValExtObject); + + JSONValue &vtype = document["type"]; + if (!vtype.IsString()) + return GameValueExt(nullptr,GameValExtObject); + + RString typeName = vtype.GetString(); + + if (!document.HasMember("pos")) + return GameValueExt(nullptr,GameValExtObject); + + JSONValue &arr = document["pos"]; + if (!arr.IsArray() || arr.Size() != 9) + return GameValueExt(nullptr,GameValExtObject); + + float x, y, z; + + x = arr[rapidjson::SizeType(0)].GetDouble(); + y = arr[rapidjson::SizeType(1)].GetDouble(); + z = arr[rapidjson::SizeType(2)].GetDouble(); + Vector3 pos(x,y,z); + + x = arr[rapidjson::SizeType(3)].GetDouble(); + y = arr[rapidjson::SizeType(4)].GetDouble(); + z = arr[rapidjson::SizeType(5)].GetDouble(); + Vector3 dir(x,y,z); + + x = arr[rapidjson::SizeType(6)].GetDouble(); + y = arr[rapidjson::SizeType(7)].GetDouble(); + z = arr[rapidjson::SizeType(8)].GetDouble(); + Vector3 up(x,y,z); + + Entity *veh = CreateVehicle( pos, typeName, false, true, ASpCanCollide, true, true, dir, up ); + if (!veh) + { + RptF("dbWorldSpawn: unable to create '%s' (id %d)", cc_cast(typeName), id); + return GameValueExt(nullptr,GameValExtObject); + } + + veh->SetInvisible(false); + + EntityAI *ai = dyn_cast(veh); + if (ai) + DBWorldLoadState(ai, document); + + return GameValueExt(veh); +} + //----------------------------------------------------------------------------- GameValue DBLoadHost( const GameState *state ) { @@ -28374,6 +28742,7 @@ GameValue MoveJPanel(const GameState *state, GameValuePar oper1) #endif #define NULARS_OFP(XX, Category) \ + XX(GameArray, "dbWorldList", DBWorldList, "Returns the ids of all persistent world objects (vehicles and tents). Works on game server only.", "_ids = dbWorldList", "", "SDZ", "", Category) \ XX(GameObject, "player", Player, "This is the person controlled by the player. In MP this value is different on each computer.", "alive player", "", "", "", Category) \ XX(GameArray, "players", ListPlayers, "List of all players on the server.","{_x globalChat 'I am here'}forEach players", "", "103584", "", Category) \ XX(GameBool, "isServer", IsServer, "Returns true if the computer is the server.", "", "", "2.92", "", Category) \ @@ -28949,6 +29318,10 @@ static const GameNular ExtNular[]= XX(GameBool, "dbKillCharacter", DBKillCharacter, GameString, "playerUID", "Kill character (zero it's aliveness in database).", "_bool = dbKillCharacter uid", "", "101171 DayZ", "", Category) \ XX(GameBool, "dbLoadCharacter", DBLoadCharacter, GameString, "playerUID", "Load character status and inventory from database.", "_bool = dbLoadCharacter uid", "", "101171 DayZ", "", Category) \ XX(GameBool, "dbSaveCharacter", DBSaveCharacter, GameString, "playerUID", "Save character status and inventory to database.", "_bool = dbSaveCharacter uid", "", "101171 DayZ", "", Category) \ + XX(GameScalar, "dbWorldAdd", DBWorldAdd, GameObject, "object", "Store a vehicle or tent in the world database and return its persistent id (0 on failure). Works on game server only.", "_id = dbWorldAdd myTent", "", "SDZ", "", Category) \ + XX(GameBool, "dbWorldSave", DBWorldSave, GameArray, "id, object", "Update position, state, fuel and cargo of a persistent world object.", "_ok = dbWorldSave [myId, myTent]", "", "SDZ", "", Category) \ + XX(GameBool, "dbWorldRemove", DBWorldRemove, GameScalar, "id", "Remove a persistent world object from the database.", "_ok = dbWorldRemove myId", "", "SDZ", "", Category) \ + XX(GameObject, "dbWorldSpawn", DBWorldSpawn, GameScalar, "id", "Create a persistent world object from the database and restore its state and cargo. Works on game server only.", "_obj = dbWorldSpawn myId", "", "SDZ", "", Category) \ XX(GameBool, "dbSaveInt", DBSaveInt, GameArray, "playerUID,Column,Value", "Save single column variable into database.", "_bool = dbSaveInt uid, column, value", "", "101171 DayZ", "", Category) \ XX(GameScalar, "dbLoadInt", DBLoadInt, GameArray, "playerUID,Column", "Load single column variable from database.", "_scalar = dbLoadInt uid, column", "", "101171 DayZ", "", Category) \ XX(GameNothing, "dbSelectHost", DBSelectHost, GameString, "Host URL", "Set custom server host adress.", "dbSelectHost http://url.com/", "", "101171 DayZ", "", Category) \ diff --git a/release-assets/server/DayZLocalPersistence.ps1 b/release-assets/server/DayZLocalPersistence.ps1 new file mode 100644 index 00000000..276179ff --- /dev/null +++ b/release-assets/server/DayZLocalPersistence.ps1 @@ -0,0 +1,286 @@ +param( + [Parameter(Mandatory=$true)][string]$Root +) + +$ErrorActionPreference = 'Stop' +$Root = [IO.Path]::GetFullPath($Root) +$profileDir = Join-Path $Root '!ConfigServer' +$playerDir = Join-Path $profileDir 'PlayerSaves' +$aliveDir = Join-Path $playerDir 'Alive' +$deadDir = Join-Path $playerDir 'Dead' +$logsDir = Join-Path $profileDir 'Logs' +$storageDir = Join-Path $Root 'storage_1\dayz_Auto.ChernarusPlus\000' +$worldFile = Join-Path $storageDir 'world-items.json' +$logFile = Join-Path $logsDir 'LocalPersistence.log' +$readyFile = Join-Path $logsDir 'LocalPersistence.ready' +$port = 28100 + +foreach ($dir in @($aliveDir, $deadDir, $logsDir, $storageDir)) { + [IO.Directory]::CreateDirectory($dir) | Out-Null +} + +function Write-StoreLog([string]$message) { + $line = '[{0}] {1}{2}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $message, [Environment]::NewLine + [IO.File]::AppendAllText($logFile, $line, [Text.Encoding]::UTF8) +} + +function Send-Response($context, [int]$status, [string]$body) { + $bytes = [Text.Encoding]::UTF8.GetBytes($body) + $context.Response.StatusCode = $status + $context.Response.ContentType = 'application/json; charset=utf-8' + $context.Response.ContentLength64 = $bytes.Length + $context.Response.OutputStream.Write($bytes, 0, $bytes.Length) + $context.Response.Close() +} + +function Get-RequestBody($request) { + $reader = [IO.StreamReader]::new($request.InputStream, $request.ContentEncoding) + try { return $reader.ReadToEnd() } finally { $reader.Dispose() } +} + +function Get-PlayerPath([string]$uid, [string]$state = 'Alive') { + if ([string]::IsNullOrWhiteSpace($uid)) { return $null } + $safe = [regex]::Replace($uid, '[^A-Za-z0-9_-]', '_') + $directory = if ($state -eq 'Dead') { $deadDir } else { $aliveDir } + return (Join-Path $directory ($safe + '.json')) +} + +function Test-PlayerAlive($record) { + if ($null -eq $record -or $null -eq $record.PSObject.Properties['alive']) { return $true } + try { return ([double]$record.alive -gt 0) } catch { return [bool]$record.alive } +} + +function Read-PlayerRecord([string]$uid) { + $alivePath = Get-PlayerPath $uid 'Alive' + $deadPath = Get-PlayerPath $uid 'Dead' + $legacyPath = Join-Path $playerDir (([regex]::Replace($uid, '[^A-Za-z0-9_-]', '_')) + '.json') + + $record = Read-JsonFile $alivePath + if ($null -ne $record) { return $record } + + # Migrate saves made by the previous flat PlayerSaves layout on first access. + $record = Read-JsonFile $legacyPath + if ($null -ne $record) { + $target = if (Test-PlayerAlive $record) { $alivePath } else { $deadPath } + Move-Item -LiteralPath $legacyPath -Destination $target -Force + return $record + } + + $record = Read-JsonFile $deadPath + return $record +} + +function Write-PlayerRecord([string]$uid, $record) { + $alivePath = Get-PlayerPath $uid 'Alive' + $deadPath = Get-PlayerPath $uid 'Dead' + $legacyPath = Join-Path $playerDir (([regex]::Replace($uid, '[^A-Za-z0-9_-]', '_')) + '.json') + $target = if (Test-PlayerAlive $record) { $alivePath } else { $deadPath } + Write-JsonFile $target $record + # Keep the last death record while a new living character is active. + if ($target -eq $deadPath -and (Test-Path -LiteralPath $alivePath -PathType Leaf)) { + Remove-Item -LiteralPath $alivePath -Force + } + if (Test-Path -LiteralPath $legacyPath -PathType Leaf) { Remove-Item -LiteralPath $legacyPath -Force } +} + +function Read-JsonFile([string]$path) { + if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { return $null } + $text = [IO.File]::ReadAllText($path, [Text.Encoding]::UTF8) + if ([string]::IsNullOrWhiteSpace($text)) { return $null } + return ($text | ConvertFrom-Json) +} + +function Write-JsonFile([string]$path, $value) { + $json = ConvertTo-Json -InputObject $value -Depth 100 -Compress + $temp = $path + '.tmp' + [IO.File]::WriteAllText($temp, $json, [Text.Encoding]::UTF8) + Move-Item -LiteralPath $temp -Destination $path -Force +} + +function Read-WorldItems { + if (-not (Test-Path -LiteralPath $worldFile -PathType Leaf)) { return @() } + $text = [IO.File]::ReadAllText($worldFile, [Text.Encoding]::UTF8) + if ([string]::IsNullOrWhiteSpace($text)) { return @() } + $items = $text | ConvertFrom-Json + if ($null -eq $items) { return @() } + return @($items | Where-Object { $null -ne $_ }) +} + +function Save-WorldItems($items) { + Write-JsonFile $worldFile @($items) +} + +function Handle-Character($context, [string]$route) { + $request = $context.Request + $uid = $request.QueryString['uid'] + if ([string]::IsNullOrWhiteSpace($uid)) { Send-Response $context 400 '{"error":"missing uid"}'; return } + + switch ($route) { + 'lud0' { + if ($request.HttpMethod -eq 'POST') { + $body = Get-RequestBody $request + $record = $body | ConvertFrom-Json + Write-PlayerRecord $uid $record + Send-Response $context 200 '{"ok":true}' + } else { + $saved = Read-PlayerRecord $uid + if ($null -eq $saved) { Send-Response $context 404 '{"error":"character not found"}'; return } + Send-Response $context 200 (ConvertTo-Json -InputObject $saved -Depth 100 -Compress) + } + } + 'lud0/save' { + $record = (Get-RequestBody $request) | ConvertFrom-Json + Write-PlayerRecord $uid $record + Send-Response $context 200 '{"ok":true}' + } + 'lud0/load' { + $saved = Read-PlayerRecord $uid + if ($null -eq $saved -or -not (Test-PlayerAlive $saved)) { Send-Response $context 404 '{"error":"living character not found"}'; return } + Send-Response $context 200 (ConvertTo-Json -InputObject $saved -Depth 100 -Compress) + } + 'lud0/create' { + $null = Read-PlayerRecord $uid + $alivePath = Get-PlayerPath $uid 'Alive' + if (-not (Test-Path -LiteralPath $alivePath)) { + $initial = [ordered]@{ alive = 1; queue = 0 } + Write-PlayerRecord $uid $initial + } + Send-Response $context 200 '{"ok":true}' + } + 'lud0/kill' { + $saved = Read-PlayerRecord $uid + if ($null -ne $saved) { + $saved | Add-Member -NotePropertyName alive -NotePropertyValue 0 -Force + Write-PlayerRecord $uid $saved + } + Send-Response $context 200 '{"ok":true}' + } + 'lud0/find' { + $saved = Read-PlayerRecord $uid + if ($null -eq $saved -or -not (Test-PlayerAlive $saved) -or -not $saved.model) { Send-Response $context 404 '{"error":"living character not found"}'; return } + if (-not $saved.pos) { $saved | Add-Member -NotePropertyName pos -NotePropertyValue @(7500,7500,0) -Force } + if (-not $saved.queue) { $saved | Add-Member -NotePropertyName queue -NotePropertyValue 0 -Force } + $found = [ordered]@{ model = $saved.model; pos = @($saved.pos); queue = [int]$saved.queue } + Send-Response $context 200 (ConvertTo-Json -InputObject $found -Depth 20 -Compress) + } + 'lud0/wint' { + $saved = Read-PlayerRecord $uid + if ($null -eq $saved) { $saved = [pscustomobject]@{ alive = 1; queue = 0; ints = [pscustomobject]@{} } } + $body = (Get-RequestBody $request) | ConvertFrom-Json + if (-not $saved.ints) { $saved | Add-Member -NotePropertyName ints -NotePropertyValue ([pscustomobject]@{}) -Force } + $saved.ints | Add-Member -NotePropertyName ([string]$body.col) -NotePropertyValue ([int]$body.val) -Force + Write-PlayerRecord $uid $saved + Send-Response $context 200 '{"ok":true}' + } + 'lud0/rint' { + $saved = Read-PlayerRecord $uid + $body = (Get-RequestBody $request) | ConvertFrom-Json + $value = 0 + if ($null -ne $saved -and $saved.ints -and $null -ne $saved.ints.([string]$body.col)) { $value = [int]$saved.ints.([string]$body.col) } + Send-Response $context 200 ('{"int":' + $value + '}') + } + 'lud0/queue' { + $saved = Read-PlayerRecord $uid + if ($null -eq $saved) { $saved = [pscustomobject]@{ alive = 1; queue = 0 } } + $body = (Get-RequestBody $request) | ConvertFrom-Json + $saved | Add-Member -NotePropertyName queue -NotePropertyValue ([int]$body.queue) -Force + Write-PlayerRecord $uid $saved + Send-Response $context 200 '{"ok":true}' + } + default { Send-Response $context 404 '{"error":"unknown character operation"}' } + } +} + +function Handle-World($context, [string]$route) { + $request = $context.Request + $items = @(Read-WorldItems) + switch ($route) { + { $_ -eq 'world' -or $_ -eq 'world/sys' } { + Send-Response $context 200 '{"scurr":200,"snext":400,"stime":0,"toffset":0,"tscale":0}' + } + 'world/add' { + $body = (Get-RequestBody $request) | ConvertFrom-Json + $next = 1 + if ($items.Count -gt 0) { $next = 1 + [int](($items | Measure-Object -Property id -Maximum).Maximum) } + $record = [pscustomobject]@{ id = $next; type = [string]$body.type; pos = @($body.mt); imp = [int]$body.imp } + if ($null -ne $body.PSObject.Properties['state']) { $record | Add-Member -NotePropertyName state -NotePropertyValue $body.state } + if ($null -ne $body.PSObject.Properties['fuel']) { $record | Add-Member -NotePropertyName fuel -NotePropertyValue ([double]$body.fuel) } + $items += $record + Save-WorldItems $items + Send-Response $context 200 ('{"id":' + $next + '}') + } + 'world/update' { + $body = (Get-RequestBody $request) | ConvertFrom-Json + $item = $items | Where-Object { [int]$_.id -eq [int]$body.item } | Select-Object -First 1 + if ($null -eq $item) { Send-Response $context 404 '{"error":"item not found"}'; return } + if ($null -ne $body.PSObject.Properties['mt']) { $item.pos = @($body.mt) } + if ($null -ne $body.PSObject.Properties['state']) { + if ($null -eq $item.PSObject.Properties['state']) { $item | Add-Member -NotePropertyName state -NotePropertyValue $body.state } + else { $item.state = $body.state } + } + if ($null -ne $body.PSObject.Properties['fuel']) { + if ($null -eq $item.PSObject.Properties['fuel']) { $item | Add-Member -NotePropertyName fuel -NotePropertyValue ([double]$body.fuel) } + else { $item.fuel = [double]$body.fuel } + } + Save-WorldItems $items + Send-Response $context 200 '{"ok":true}' + } + 'world/remove' { + $body = (Get-RequestBody $request) | ConvertFrom-Json + $items = @($items | Where-Object { [int]$_.id -ne [int]$body.item }) + Save-WorldItems $items + Send-Response $context 200 '{"ok":true}' + } + 'world/get' { + $body = (Get-RequestBody $request) | ConvertFrom-Json + $item = $items | Where-Object { [int]$_.id -eq [int]$body.item } | Select-Object -First 1 + if ($null -eq $item) { Send-Response $context 404 '{"error":"item not found"}'; return } + $result = [ordered]@{ type = $item.type; pos = @($item.pos) } + if ($null -ne $item.PSObject.Properties['state']) { $result['state'] = $item.state } + if ($null -ne $item.PSObject.Properties['fuel']) { $result['fuel'] = $item.fuel } + Send-Response $context 200 (ConvertTo-Json -InputObject $result -Depth 40 -Compress) + } + 'world/list' { + $ids = @($items | Sort-Object id | ForEach-Object { [int]$_.id }) + Send-Response $context 200 (ConvertTo-Json -InputObject ([ordered]@{ count = $ids.Count; ids = $ids }) -Depth 10 -Compress) + } + 'world/count' { + Send-Response $context 200 ('{"count":' + $items.Count + '}') + } + 'world/batch' { + $body = (Get-RequestBody $request) | ConvertFrom-Json + $beg = [int]$body.beg; $end = [int]$body.end + $found = @($items | Where-Object { [int]$_.id -ge $beg -and [int]$_.id -le $end } | Sort-Object id) + $result = [ordered]@{ count = $found.Count; beg = $beg; end = $end } + foreach ($item in $found) { $result[[string]$item.id] = @([string]$item.type) + @($item.pos) } + Send-Response $context 200 (ConvertTo-Json -InputObject $result -Depth 30 -Compress) + } + default { Send-Response $context 404 '{"error":"unknown world operation"}' } + } +} + +$listener = [Net.HttpListener]::new() +$listener.Prefixes.Add("http://127.0.0.1:$port/") +$listener.Start() +[IO.File]::WriteAllText($readyFile, [string]$PID, [Text.Encoding]::ASCII) +Write-StoreLog "Local DayZ persistence listening at 127.0.0.1:$port" + +try { + while ($listener.IsListening) { + $context = $listener.GetContext() + try { + $route = $context.Request.Url.AbsolutePath.Trim('/') + if ($route -eq 'health') { Send-Response $context 200 '{"status":"ready"}'; continue } + if ($route -eq 'lud0' -or $route.StartsWith('lud0/')) { Handle-Character $context $route; continue } + if ($route -eq 'world' -or $route.StartsWith('world/')) { Handle-World $context $route; continue } + Send-Response $context 404 '{"error":"not found"}' + } catch { + Write-StoreLog ("Request error: " + $_.Exception.Message) + try { Send-Response $context 500 '{"error":"local storage error"}' } catch { } + } + } +} finally { + $listener.Stop() + $listener.Close() + Remove-Item -LiteralPath $readyFile -Force -ErrorAction SilentlyContinue +} diff --git a/release-assets/server/MPMissions/dayz_Auto.ChernarusPlus/dz_worldPersist.sqf b/release-assets/server/MPMissions/dayz_Auto.ChernarusPlus/dz_worldPersist.sqf new file mode 100644 index 00000000..33662fcb --- /dev/null +++ b/release-assets/server/MPMissions/dayz_Auto.ChernarusPlus/dz_worldPersist.sqf @@ -0,0 +1,150 @@ +/* + dz_worldPersist.sqf + Persistencia de veiculos e tendas (somente servidor). + + Comandos de engine: + dbWorldAdd -> id persistente (0 = falha) + dbWorldSave [id, objeto] -> bool + dbWorldRemove -> bool + dbWorldList -> array de ids + dbWorldSpawn -> objeto criado/restaurado +*/ + +if (!isServer) exitWith {}; + +DZ_WORLD_OBJECTS = []; +DZ_WORLD_SAVE_INTERVAL = 10; + +// Criados apenas quando o banco esta vazio (primeira execucao). +// [classe, posicao, direcao] +DZ_WORLD_INITIAL_VEHICLES = [ + ["Heli_Light01_H", [12020, 12700, 0], 0], + ["Heli_Medium01_H", [4850, 2450, 0], 90] +]; + +DZ_WORLD_INITIAL_TENTS = [ + ["Land_tent_east", [12080, 12640, 0], 45], + ["Land_tent_east", [4880, 2420, 0], 180] +]; + +dz_fnc_worldFind = { + private ["_obj", "_idx"]; + _obj = _this; + _idx = -1; + { + if ((_x select 0) == _obj) exitWith { _idx = _forEachIndex; }; + } forEach DZ_WORLD_OBJECTS; + _idx +}; + +dz_fnc_worldRegister = { + private ["_obj", "_id", "_idx"]; + _obj = _this; + if (isNull _obj) exitWith { 0 }; + _idx = _obj call dz_fnc_worldFind; + if (_idx >= 0) exitWith { (DZ_WORLD_OBJECTS select _idx) select 1 }; + _id = dbWorldAdd _obj; + if (_id > 0) then { + DZ_WORLD_OBJECTS set [count DZ_WORLD_OBJECTS, [_obj, _id]]; + diag_log format ["[persist] registrado %1 id %2", typeOf _obj, _id]; + } else { + diag_log format ["[persist] FALHA ao registrar %1", typeOf _obj]; + }; + _id +}; + +dz_fnc_worldUnregister = { + private ["_obj", "_idx", "_id", "_keep"]; + _obj = _this; + _idx = _obj call dz_fnc_worldFind; + if (_idx < 0) exitWith {}; + _id = (DZ_WORLD_OBJECTS select _idx) select 1; + _keep = []; + { + if ((_x select 0) != _obj) then { _keep set [count _keep, _x]; }; + } forEach DZ_WORLD_OBJECTS; + DZ_WORLD_OBJECTS = _keep; + dbWorldRemove _id; + diag_log format ["[persist] removido id %1", _id]; +}; + +dz_fnc_worldSaveAll = { + private ["_keep", "_obj", "_id"]; + _keep = []; + { + _obj = _x select 0; + _id = _x select 1; + if (isNull _obj) then { + dbWorldRemove _id; + } else { + if ((damage _obj) >= 0.95) then { + dbWorldRemove _id; + } else { + dbWorldSave [_id, _obj]; + _keep set [count _keep, _x]; + }; + }; + } forEach DZ_WORLD_OBJECTS; + DZ_WORLD_OBJECTS = _keep; +}; + +dz_fnc_worldRestore = { + private ["_ids", "_obj"]; + _ids = dbWorldList; + diag_log format ["[persist] restaurando %1 objeto(s)", count _ids]; + { + _obj = dbWorldSpawn _x; + if (!isNull _obj) then { + DZ_WORLD_OBJECTS set [count DZ_WORLD_OBJECTS, [_obj, _x]]; + diag_log format ["[persist] restaurado %1 id %2", typeOf _obj, _x]; + } else { + diag_log format ["[persist] FALHA ao restaurar id %1", _x]; + }; + } forEach _ids; +}; + +dz_fnc_worldSpawnInitial = { + private ["_def", "_veh"]; + { + _def = _x; + _veh = createVehicle [(_def select 0), (_def select 1), [], 0, "NONE"]; + if (!isNull _veh) then { + _veh setDir (_def select 2); + _veh setVariable ["allowHeliEngine", true]; + _veh setVariable ["allowAutoHower", true]; + _veh call dz_fnc_worldRegister; + } else { + diag_log format ["[persist] FALHA ao criar %1", _def select 0]; + }; + } forEach DZ_WORLD_INITIAL_VEHICLES; + + { + _def = _x; + _veh = createVehicle [(_def select 0), (_def select 1), [], 0, "NONE"]; + if (!isNull _veh) then { + _veh setDir (_def select 2); + _veh call dz_fnc_worldRegister; + } else { + diag_log format ["[persist] FALHA ao criar %1", _def select 0]; + }; + } forEach DZ_WORLD_INITIAL_TENTS; +}; + +// Autosave periodico (o servidor e morto com taskkill, entao salva seguido). +[] spawn { + while {true} do { + sleep DZ_WORLD_SAVE_INTERVAL; + call dz_fnc_worldSaveAll; + }; +}; + +// Restauracao no boot, depois do mundo/proxies carregados. +[] spawn { + sleep 5; + call dz_fnc_worldRestore; + if ((count DZ_WORLD_OBJECTS) == 0) then { + call dz_fnc_worldSpawnInitial; + }; +}; + +diag_log "[persist] dz_worldPersist inicializado"; diff --git a/release-assets/server/MPMissions/dayz_Auto.ChernarusPlus/init.sqf b/release-assets/server/MPMissions/dayz_Auto.ChernarusPlus/init.sqf index 337393d8..f0c194d4 100644 --- a/release-assets/server/MPMissions/dayz_Auto.ChernarusPlus/init.sqf +++ b/release-assets/server/MPMissions/dayz_Auto.ChernarusPlus/init.sqf @@ -22,4 +22,7 @@ spawnLoot [_position,30000,35000]; dbInitServer; +// Persistent world objects (vehicles / tents) +call compile preprocessFileLineNumbers "dz_worldPersist.sqf"; + setTimeForScripts 0.03;