newdark: cleaned up code, io.lua handles strictly IO, osm.lua handles replicating OSM code, schema_db.lua handles resolving schemas => filenames, lua hook calls returns their values (to-do, try and return any value, probably never happening)

This commit is contained in:
ecker 2026-07-20 16:35:56 -05:00
parent 988a61de7a
commit 4fba288af5
9 changed files with 399 additions and 411 deletions

View File

@ -5,50 +5,28 @@ local soundMeta = darkMeta["sound"] or {}
local schemaName = soundMeta["schema"] or ""
local flags = soundMeta["flags"] or 0
local baseVolume = tonumber(soundMeta["volume"]) or 1.0
local overrideVol = tonumber(soundMeta["volume"]) or 0
local radius = tonumber(soundMeta["radius"]) or 0.0
local environmental = (math.floor(flags / 1) % 2) ~= 0
local isTurnedOff = (math.floor(flags / 4) % 2) ~= 0
local isMusic = (math.floor(flags / 16) % 2) ~= 0
if isMusic then return end
if schemaName == "" then return end
if isMusic or schemaName == "" then return end
local isTurnedOff = (math.floor(flags / 4) % 2) ~= 0
local startOn = not isTurnedOff
local isPlaying = false
local function playSound()
if isPlaying or schemaName == "" then return end
local wavList = soundMeta["wavs"]
local url = ""
if isPlaying then return end
if wavList and #wavList > 0 then
local totalWeight = 0
for _, wavData in ipairs(wavList) do
totalWeight = totalWeight + (tonumber(wavData.weight) or 1)
end
local schemaData = hooks.call("dark:ResolveSchema", { schema = schemaName })
if not schemaData or not schemaData.wavs or #schemaData.wavs == 0 then return end
local roll = math.random() * totalWeight
local current = 0
for _, wavData in ipairs(wavList) do
current = current + (tonumber(wavData.weight) or 1)
if roll <= current then
url = wavData.uri
break
end
end
end
if url == "" then return end
isPlaying = true
local resolvedUrl = string.resolveURI(url, metadata["system"]["root"])
local schemaVol = tonumber(soundMeta["schema_volume"]) or 0
local overrideVol = tonumber(soundMeta["volume"]) or 0
local pick = schemaData.wavs[math.random(#schemaData.wavs)]
local resolvedUrl = string.resolveURI(pick, metadata["system"]["root"])
local schemaVol = tonumber(schemaData.schema_volume) or 0
local baseVolume = 0.2
if overrideVol ~= 0 then baseVolume = math.pow(10, overrideVol / 2000.0) end
local finalVolume = baseVolume * math.pow(10, schemaVol / 2000.0)
@ -56,10 +34,10 @@ local function playSound()
local payload = {
filename = resolvedUrl,
spatial = not environmental,
streamed = soundMeta["stream"] == true,
streamed = schemaData.stream == true,
volume = finalVolume,
unique = true,
loop = not (soundMeta["play_once"] == true)
loop = not (schemaData.play_once == true)
}
if radius > 0 and not environmental then
@ -68,20 +46,18 @@ local function playSound()
payload.rolloffFactor = 1.0
end
isPlaying = true
ent:callHook("sound:Emit.%UID%", payload)
end
local function stopSound()
if not isPlaying or schemaName == "" then return end
if not isPlaying then return end
isPlaying = false
ent:callHook("sound:Stop.%UID%", {
})
ent:callHook("sound:Stop.%UID%", {})
end
ent:addHook("link:Message.%UID%", function(payload)
local msg = payload.message
if msg == "TurnOn" then
playSound()
elseif msg == "TurnOff" then

View File

@ -6,7 +6,6 @@ local physicsBody = ent:getComponent("PhysicsBody")
local metadata = ent:getComponent("Metadata")
local darkMeta = metadata["dark"] or {}
local doorMeta = darkMeta["door"] or {}
local schemaDb = darkMeta["schema_db"] or {}
local classTags = doorMeta["class_tags"] or (darkMeta["class_tags"] or "")
local state = 0
@ -49,6 +48,9 @@ end
local polarity = (openPos > closedPos) and 1 or -1
local status = tonumber(doorMeta["status"]) or 0
local oldStateString = (status == 1) and "Open" or "Closed"
local function stopCurrentSound()
if currentWav ~= "" then
ent:callHook("sound:Stop.%UID%", { filename = currentWav })
@ -57,76 +59,37 @@ local function stopCurrentSound()
end
local function playEnvSchema(newState)
local bestMatch = nil
local bestScore = -1
local queryTags = classTags
if queryTags ~= "" then queryTags = queryTags .. ", " end
queryTags = queryTags .. "Event StateChange, OpenState " .. newState .. ", OldOpenState " .. oldStateString
local resolvedUrl, schemaName = _G.DarkUtils.playSound(ent, queryTags, nil, {
spatial = true,
volume = 1.0,
maxDistance = 15.0,
rolloffFactor = 1.0,
unique = true
})
local myDoorType = nil
if classTags and classTags ~= "" then
myDoorType = string.match(classTags, "DoorType%s+([^%s,]+)")
end
for _, schema in ipairs(schemaDb) do
local sTags = schema.tags or ""
local isStateChange = string.find(sTags, "Event StateChange")
local openStateVals = string.match(sTags, "OpenState%s+([^,]+)")
local matchesState = openStateVals and string.find(openStateVals, newState)
if isStateChange and matchesState then
local score = 0
if myDoorType then
if string.find(sTags, myDoorType) then
score = score + 10
elseif string.find(sTags, "DoorType") then
score = score - 10
end
else
if string.find(sTags, "DoorType") then
score = score - 5
end
end
if score > bestScore then
bestScore = score
bestMatch = schema
end
end
end
if bestMatch then
if (newState == "Open" or newState == "Closed") and bestMatch.name == currentSchemaName then
if resolvedUrl then
if (newState == "Open" or newState == "Closed") and schemaName == currentSchemaName then
return
end
currentSchemaName = bestMatch.name
if bestMatch.wavs and #bestMatch.wavs > 0 then
local pick = bestMatch.wavs[math.random(#bestMatch.wavs)]
local resolvedUrl = string.resolveURI(pick, metadata["system"]["root"])
stopCurrentSound()
currentWav = resolvedUrl
ent:callHook("sound:Emit.%UID%", {
filename = resolvedUrl,
spatial = true,
volume = 1.0,
maxDistance = 15.0,
rolloffFactor = 1.0,
unique = true
})
end
stopCurrentSound()
currentSchemaName = schemaName
currentWav = resolvedUrl
end
end
local function setDoorState(newState)
if newState == "Open" and (state == 0 or state == 3) then
oldStateString = (state == 0) and "Closed" or "Closing"
state = 1
playEnvSchema("Opening")
elseif newState == "Close" and (state == 2 or state == 1) then
oldStateString = (state == 2) and "Open" or "Opening"
state = 3
playEnvSchema("Closing")
end
@ -145,9 +108,8 @@ ent:bind("tick", function(self)
currentDistance = targetDistance
state = 2
-- Stop the "Opening" sound
ent:callHook("sound:Stop.%UID%", {})
-- Play the "Open" (Latch) sound!
oldStateString = "Opening"
playEnvSchema("Open")
end
@ -160,9 +122,8 @@ ent:bind("tick", function(self)
currentDistance = 0
state = 0
-- Stop the "Closing" sound
ent:callHook("sound:Stop.%UID%", {})
-- Play the "Closed" (Latch) sound!
oldStateString = "Closing"
playEnvSchema("Closed")
end
end

View File

@ -3,163 +3,70 @@ local scene = entities.currentScene()
local metadata = ent:getComponent("Metadata")
local darkMeta = metadata["dark"] or {}
local schemaDb = darkMeta["schema_db"] or {}
local classTags = darkMeta["class_tags"] or ""
local connections = darkMeta["connections"]
local eName = ent:name() or tostring(ent:uid())
local eID = darkMeta["id"] or "??"
_G.DarkTargets = _G.DarkTargets or {}
if darkMeta["id"] then
_G.DarkTargets[darkMeta["id"]] = ent:uid()
end
_G.DarkScripts = _G.DarkScripts or {}
_G.OSM = _G.OSM or {}
_G.DarkUtils = _G.DarkUtils or {}
_G.DarkScripts["RelayTrap"] = function(entity, payload, dMeta)
local msg = payload.message
local eName = entity or entity:uid()
--print(string.format("%s (RelayTrap) is forwarding %s down its links...", eName, msg))
_G.DarkUtils.playSound = function(entity, tags, explicitSchema, emitOptions)
local result = hooks.call("dark:ResolveSchema", { tags = tags, schema = explicitSchema })
entity:callHook("link:Broadcast.%UID%", {
message = msg,
flavors = { "ControlDevice", "SwitchLink" },
caller = entity:uid(),
callerDarkID = payload.callerDarkID
})
if result and result.wavs and #result.wavs > 0 then
local pick = result.wavs[math.random(#result.wavs)]
local meta = entity:getComponent("Metadata")
local resolvedUrl = string.resolveURI(pick, meta["system"]["root"])
local options = emitOptions or {}
options.filename = resolvedUrl
if options.spatial == nil then options.spatial = true end
if options.volume == nil then options.volume = 1.0 end
entity:callHook("sound:Emit.%UID%", options)
return resolvedUrl, result.name
end
return nil, nil
end
_G.DarkScripts["ElevatorButton"] = _G.DarkScripts["RelayTrap"]
_G.DarkScripts["RequireAllTrap"] = function(entity, payload, dMeta)
local msg = payload.message
local callerDarkID = payload.callerDarkID
_G.RAT_States = _G.RAT_States or {}
local uid = entity:uid()
_G.RAT_States[uid] = _G.RAT_States[uid] or { inputs = {}, wasOn = false }
local state = _G.RAT_States[uid]
if callerDarkID then
state.inputs[callerDarkID] = (msg == "TurnOn")
end
local allOn = true
local incoming = dMeta["incoming_connections"] or {}
for i = 1, #incoming do
local conn = incoming[i]
if conn.flavor == "ControlDevice" or conn.flavor == "SwitchLink" then
if not state.inputs[conn.source_id] then
allOn = false
break
end
end
end
if allOn and not state.wasOn then
state.wasOn = true
--print(entity .. " (RequireAllTrap) conditions met! Broadcasting TurnOn.")
entity:callHook("link:Broadcast.%UID%", { message = "TurnOn", flavors = { "ControlDevice", "SwitchLink" }, callerDarkID = dMeta["id"], caller = uid })
elseif not allOn and state.wasOn then
state.wasOn = false
--print(entity .. " (RequireAllTrap) condition lost! Broadcasting TurnOff.")
entity:callHook("link:Broadcast.%UID%", { message = "TurnOff", flavors = { "ControlDevice", "SwitchLink" }, callerDarkID = dMeta["id"], caller = uid })
end
end
--[[
_G.DarkScripts["BaseElevator"] = function(entity, payload, dMeta)
local msg = payload.message
local eName = entity or entity:uid()
print(string.format("%s (Elevator) received command: %s", eName, msg))
if msg == "TurnOn" or msg == "TurnOff" then
print(string.format("--> Commanding Lift '%s' to move!", eName))
end
end
_G.DarkScripts["Elevator"] = _G.DarkScripts["BaseElevator"]
]]
ent:addHook("link:Message.%UID%", function(payload)
local msg = payload.message
local caller = payload.caller
local eName = ent:name() or ent:uid()
local callerID = payload.callerDarkID or "??"
--print(string.format("Entity %s (Dark ID: %s) received message: %s from UID: %s", eName, darkMeta["id"] or "Unknown", msg, tostring(caller)))
--print(string.format("[I/O] %s (%s) RECEIVED '%s' from (%s)", eName, eID, msg, callerID))
local scripts = darkMeta["scripts"] or {}
local scriptHandled = false
for _, script in ipairs(scripts) do
if _G.DarkScripts[script] then
_G.DarkScripts[script](ent, payload, darkMeta)
scriptHandled = true
end
end
if not scriptHandled then
if eName:lower():match("filter") or eName:lower():match("trigger") then
_G.DarkScripts["RelayTrap"](ent, payload, darkMeta)
local scriptDef = _G.OSM[script]
if scriptDef then
--print(string.format(" -> Handling via script: %s", script))
if type(scriptDef) == "table" and scriptDef.onMessage then
scriptDef.onMessage(ent, payload, darkMeta)
elseif type(scriptDef) == "function" then
scriptDef(ent, payload, darkMeta)
end
end
end
end)
local function playButtonSound()
if not classTags or classTags == "" then return end
local myDeviceType = string.match(classTags, "DeviceType%s+([^%s,]+)")
local bestMatch = nil
local bestScore = -1
for _, schema in ipairs(schemaDb) do
local sTags = schema.tags or ""
local score = 0
if myDeviceType then
local paddedTags = sTags .. ","
if string.find(paddedTags, "DeviceType%s+" .. myDeviceType .. "[,%s]") then
score = score + 10
elseif string.find(paddedTags, "DeviceType%s+Gen[,%s]") then
score = score + 5
elseif string.find(sTags, "DeviceType") then
score = score - 10
end
if score > 0 then
if string.find(sTags, "Reject") then
score = score + 5
elseif string.find(sTags, "StateChange") or string.find(sTags, "Activate") then
score = score + 5
end
end
end
if score > bestScore then
bestScore = score
bestMatch = schema
end
end
print("Button sound resolution:", ent, classTags, myDeviceType, bestMatch and bestMatch.name or "None", bestScore)
if bestMatch and bestScore > 0 and bestMatch.wavs and #bestMatch.wavs > 0 then
local pick = bestMatch.wavs[math.random(#bestMatch.wavs)]
local resolvedUrl = string.resolveURI(pick, metadata["system"]["root"])
ent:callHook("sound:Emit.%UID%", {
filename = resolvedUrl, spatial = true, volume = 1.0, maxDistance = 15.0, rolloffFactor = 1.0, unique = true
})
end
end
local connections = darkMeta["connections"]
ent:addHook("link:Broadcast.%UID%", function(payload)
local msg = payload.message
local validFlavors = payload.flavors or { "ControlDevice", "SwitchLink" }
if not connections then
--print(string.format("[I/O] %s (%s) tried to broadcast '%s', but has no connections.", eName, eID, msg))
return
end
--print(string.format("[I/O] %s (%s) BROADCASTING '%s'", eName, eID, msg))
for i = 1, #connections do
local conn = connections[i]
local isValid = false
@ -169,9 +76,8 @@ ent:addHook("link:Broadcast.%UID%", function(payload)
if isValid then
local targetUID = _G.DarkTargets[conn.target_id]
--print(string.format("Broadcasting %s to Dark ID %s (UID: %s) via %s", msg, conn.target_id, tostring(targetUID), conn.flavor))
if targetUID then
--print(string.format(" -> Sent to target ID %s via %s", conn.target_id, conn.flavor))
local targetEnt = entities.get(targetUID)
if targetEnt and targetEnt:uid() then
targetEnt:callHook("link:Message." .. targetUID, {
@ -180,34 +86,57 @@ ent:addHook("link:Broadcast.%UID%", function(payload)
callerDarkID = darkMeta["id"] or payload.callerDarkID
})
end
else
--print(string.format(" -> Target ID %s not found in DarkTargets! (Flavor: %s)", conn.target_id, conn.flavor))
end
end
end
end)
-- frobbage
if darkMeta["frob"] ~= nil then
ent:addHook("entity:Use.%UID%", function(payload)
local frobWorld = darkMeta["frob"]["world"] or 0
local kFrobMove = 1
local kFrobScript = 2
local kFrobMove = 1 -- 1 << 0
local kFrobScript = 2 -- 1 << 1
--print(string.format("[I/O] %s (%s) FROBBED by user.", eName, eID))
if bit.band(frobWorld, kFrobScript) ~= 0 then
print(ent, json.encode( darkMeta ))
playButtonSound()
local scripts = darkMeta["scripts"] or {}
local handledByScript = false
ent:callHook("link:Broadcast.%UID%", {
message = "TurnOn",
flavors = { "ControlDevice", "SwitchLink" },
caller = payload.user,
callerDarkID = darkMeta["id"]
})
for _, script in ipairs(scripts) do
if _G.OSM[script] and type(_G.OSM[script]) == "table" and _G.OSM[script].onFrob then
--print(string.format(" -> Frob handled by script: %s", script))
_G.OSM[script].onFrob(ent, payload, darkMeta)
handledByScript = true
end
end
if not handledByScript then
--print(" -> Frob falling back to default TurnOn broadcast.")
local played, schema = _G.DarkUtils.playSound(ent, classTags .. ", Event StateChange", nil, { spatial = true, maxDistance = 15.0 })
if not played then played, schema = _G.DarkUtils.playSound(ent, classTags .. ", Event Activate", nil, { spatial = true, maxDistance = 15.0 }) end
if not played then played, schema = _G.DarkUtils.playSound(ent, classTags, nil, { spatial = true, maxDistance = 15.0 }) end
if played then
--print(string.format(" -> Played fallback sound schema: %s", schema))
end
ent:callHook("link:Broadcast.%UID%", {
message = "TurnOn",
flavors = { "ControlDevice", "SwitchLink" },
caller = payload.user,
callerDarkID = darkMeta["id"]
})
end
end
if bit.band(frobWorld, kFrobMove) ~= 0 then
print("Item picked up!")
-- ent:callHook("inventory:Pickup.%UID%", { user = payload.user })
--print(string.format("[I/O] %s (%s) Picked up!", eName, eID))
end
end)
end
@ -216,8 +145,4 @@ ent:addHook("entity:Destroy.%UID%", function()
if darkMeta["id"] and _G.DarkTargets[darkMeta["id"]] == ent:uid() then
_G.DarkTargets[darkMeta["id"]] = nil
end
if _G.RAT_States and _G.RAT_States[ent:uid()] then
_G.RAT_States[ent:uid()] = nil
end
end)

View File

@ -0,0 +1,89 @@
_G.OSM = _G.OSM or {}
_G.OSM["TweqLockedButton"] = {
onMessage = function(entity, payload, dMeta) end,
onFrob = function(entity, payload, dMeta)
local eName = entity:name() or entity:uid()
-- todo: deduce lock state
local isLocked = true
print(entity, "is locked?", isLocked)
if isLocked then
-- print(string.format("%s is locked! Emitting 'cardfail'.", eName))
_G.DarkUtils.playSound(entity, "", "cardfail", { spatial = true, maxDistance = 15.0 })
-- entity:callHook("ui:FlashMessage", { text = "Access Required: {}" })
else
-- unlock logic
local cTags = (dMeta["class_tags"] or "") .. ", Event StateChange"
_G.DarkUtils.playSound(entity, cTags, "", { spatial = true, maxDistance = 15.0 })
entity:callHook("link:Broadcast.%UID%", {
message = "TurnOn", flavors = { "ControlDevice" }, caller = payload.user, callerDarkID = dMeta["id"]
})
end
end
}
_G.OSM["RelayTrap"] = function(entity, payload, dMeta)
local msg = payload.message
entity:callHook("link:Broadcast.%UID%", {
message = msg,
flavors = { "ControlDevice", "SwitchLink" },
caller = entity:uid(),
callerDarkID = payload.callerDarkID
})
end
_G.OSM["TrapQBFilter"] = _G.OSM["RelayTrap"]
_G.OSM["TrapQBNegFilter"] = _G.OSM["RelayTrap"]
_G.OSM["ElevatorButton"] = _G.OSM["RelayTrap"]
_G.OSM["RequireAllTrap"] = function(entity, payload, dMeta)
local msg = payload.message
local callerDarkID = payload.callerDarkID
_G.RAT_States = _G.RAT_States or {}
local uid = entity:uid()
_G.RAT_States[uid] = _G.RAT_States[uid] or { inputs = {}, wasOn = false }
local state = _G.RAT_States[uid]
if callerDarkID then
state.inputs[callerDarkID] = (msg == "TurnOn")
end
local allOn = true
local incoming = dMeta["incoming_connections"] or {}
for i = 1, #incoming do
local conn = incoming[i]
if conn.flavor == "ControlDevice" or conn.flavor == "SwitchLink" then
if not state.inputs[conn.source_id] then
allOn = false
break
end
end
end
if allOn and not state.wasOn then
state.wasOn = true
entity:callHook("link:Broadcast.%UID%", { message = "TurnOn", flavors = { "ControlDevice", "SwitchLink" }, callerDarkID = dMeta["id"], caller = uid })
elseif not allOn and state.wasOn then
state.wasOn = false
entity:callHook("link:Broadcast.%UID%", { message = "TurnOff", flavors = { "ControlDevice", "SwitchLink" }, callerDarkID = dMeta["id"], caller = uid })
end
end
_G.OSM["BaseElevator"] = function(entity, payload, dMeta)
local msg = payload.message
local eName = entity:name() or entity:uid()
-- print(string.format("%s (Elevator) received command: %s", eName, msg))
if msg == "TurnOn" or msg == "TurnOff" then
-- print(string.format("--> Commanding Lift '%s' to move!", eName))
end
end
_G.OSM["Elevator"] = _G.OSM["BaseElevator"]

View File

@ -0,0 +1,91 @@
local ent = ent
local metadata = ent:getComponent("Metadata")
local db = metadata["dark"]["schema_db"] or {}
local function parseTags(tagString)
local result = {}
if not tagString or tagString == "" then return result end
for pair in string.gmatch(tagString, "([^,]+)") do
pair = string.match(pair, "^%s*(.-)%s*$")
local key, val = string.match(pair, "^(%S+)%s+(.+)$")
if key and val then
result[key] = val
else
result[pair] = true
end
end
return result
end
local function matchValue(sVal, qVal)
if sVal == qVal then return true end
if type(sVal) == "string" and type(qVal) == "string" then
for piece in string.gmatch(sVal, "([^|]+)") do
if piece == qVal then return true end
end
end
if sVal == true and qVal ~= nil then return true end
return false
end
hooks.add("dark:ResolveSchema", function(payload)
local explicitSchema = payload.schema or ""
if explicitSchema ~= "" then
for _, schema in ipairs(db) do
if schema.name:lower() == explicitSchema:lower() then
return schema
end
end
end
local queryTags = parseTags(payload.tags)
local bestMatch = nil
local bestScore = -1
for _, schema in ipairs(db) do
local sTags = parseTags(schema.tags)
local score = 0
local isValid = true
if queryTags["Event"] and not sTags["Event"] then
isValid = false
end
if isValid then
for sKey, sVal in pairs(sTags) do
local qVal = queryTags[sKey]
if qVal == nil then
isValid = false
break
elseif matchValue(sVal, qVal) then
score = score + 10
elseif matchValue(sVal, "Gen") or matchValue(sVal, "Generic") then
score = score + 5
else
isValid = false
break
end
end
end
if isValid and score > bestScore then
if next(sTags) ~= nil then
bestScore = score
bestMatch = schema
end
end
end
if bestMatch then
bestMatch.score = bestScore
return bestMatch
end
return nil
end)

View File

@ -1,52 +1,34 @@
local ent = ent
local scene = entities.currentScene()
local metadata = ent:getComponent("Metadata")
local darkMeta = metadata["dark"] or {}
local soundMeta = darkMeta["sound"] or {}
local schemaDb = darkMeta["schema_db"] or {}
local connections = darkMeta["connections"] or {}
local isPlaying = false
local nativeSchema = soundMeta["schema"] or ""
ent:addHook("link:Message.%UID%", function(payload)
local msg = payload.message
if msg == "TurnOn" and not isPlaying then
local urlToPlay = ""
local explicitSchema = ""
for _, conn in ipairs(connections) do
if conn.flavor == "SoundDescription" and conn.wavs and #conn.wavs > 0 then
urlToPlay = conn.wavs[math.random(#conn.wavs)]
if conn.flavor == "SoundDescription" and conn.target_node and conn.target_node ~= "UnknownSchema" then
explicitSchema = conn.target_node
break
end
end
if urlToPlay == "" and nativeSchema ~= "" then
for _, entry in ipairs(schemaDb) do
if entry.name:lower() == nativeSchema:lower() then
if entry.wavs and #entry.wavs > 0 then
urlToPlay = entry.wavs[math.random(#entry.wavs)]
end
break
end
end
if explicitSchema == "" and nativeSchema ~= "" then
explicitSchema = nativeSchema
end
if urlToPlay ~= "" then
local resolvedUrl = string.resolveURI(urlToPlay, metadata["system"]["root"])
isPlaying = true
ent:callHook("sound:Emit.%UID%", {
filename = resolvedUrl,
spatial = false,
streamed = true,
volume = 1.0,
unique = true,
loop = false
if explicitSchema ~= "" then
local resolvedUrl = _G.DarkUtils.playSound(ent, "", explicitSchema, {
spatial = false, streamed = true, volume = 1.0, unique = true, loop = false
})
if resolvedUrl then isPlaying = true end
end
elseif msg == "TurnOff" and isPlaying then

View File

@ -1438,7 +1438,7 @@ void uf::graph::process( pod::Graph& graph, int32_t index, uf::Object& parent )
auto& metadataDark = node.metadata["dark"];
if ( ext::json::isObject( metadataDark ) ) {
bool emitsAudio = false;
// bind elevator
bool isElevator = false;
if ( ext::json::isArray( metadataDark["scripts"] ) ) {
@ -1454,10 +1454,17 @@ void uf::graph::process( pod::Graph& graph, int32_t index, uf::Object& parent )
emitsAudio = true;
}
// bind schema DB
if ( ext::json::isArray( metadataDark["schema_db"] ) ) {
UF_MSG_DEBUG("Binding schema DB: {}", node.name);
loadJson["assets"].emplace_back("ent://scripts/dark/schema_db.lua");
}
// bind io connectivity
if ( ext::json::isArray( metadataDark["connections"] ) || metadataDark["id"].is<int>() ) {
node.metadata["connections"] = metadataDark["connections"];
loadJson["assets"].emplace_back("ent://scripts/dark/io.lua");
loadJson["assets"].emplace_back("ent://scripts/dark/osm.lua");
}
// bind door
@ -1493,53 +1500,6 @@ void uf::graph::process( pod::Graph& graph, int32_t index, uf::Object& parent )
loadJson["assets"].emplace_back("ent://scripts/dark/trigger.lua");
}
// bind schema based on what we need
uf::stl::string classTags = metadataDark["class_tags"].as<uf::stl::string>("");
uf::stl::string explicitSchema = "";
if ( metadataDark["sound"].isObject() ) {
explicitSchema = metadataDark["sound"]["schema"].as<uf::stl::string>("");
}
if ( !classTags.empty() || !explicitSchema.empty() ) {
auto& localDb = node.metadata["dark"]["schema_db"];
uf::stl::vector<uf::stl::string> searchTerms;
auto extractTerm = [&](const uf::stl::string& prefix) {
size_t p = classTags.find(prefix);
if ( p != uf::stl::string::npos ) {
p += prefix.length();
size_t end = classTags.find_first_of(" ,", p);
if ( end == uf::stl::string::npos ) end = classTags.length();
uf::stl::string term = classTags.substr(p, end - p);
if ( !term.empty() ) searchTerms.push_back(term);
}
};
extractTerm("DeviceType ");
extractTerm("DoorType ");
ext::json::forEach( graph.metadata["dark"]["schema_db"], [&]( ext::json::Value& sch ){
uf::stl::string sName = sch["name"].as<uf::stl::string>("");
uf::stl::string sTags = sch["tags"].as<uf::stl::string>("");
bool keep = false;
if ( !explicitSchema.empty() && sName == explicitSchema ) {
keep = true;
} else {
for ( const auto& term : searchTerms ) {
if ( sTags.find(term) != uf::stl::string::npos ) {
keep = true;
break;
}
}
}
if ( keep ) {
localDb.emplace_back(sch);
}
});
}
if ( emitsAudio ) loadJson["behaviors"].emplace_back("AudioEmitterBehavior");
}

View File

@ -159,24 +159,58 @@ void ext::lua::onInitialization( const std::function<void()>& function ) {
namespace binds {
namespace hook {
void add( const uf::stl::string& name, LUA_FUN function ) {
uf::hooks.addHook( name, [function](ext::json::Value& json){
sol::table table = ext::lua::decode(json).value_or(ext::lua::state.create_table());
auto result = function( table );
// ???
#if UF_LUA_PCALLS
if ( !result.valid() ) {
sol::error err = result;
UF_MSG_ERROR("{}", err.what())
void add( const uf::stl::string& name, sol::protected_function function ) {
uf::hooks.addHook( name, [function]( const pod::Hook::userdata_t& payload ) -> pod::Hook::userdata_t {
ext::json::Value jsonPayload;
if ( payload.is<ext::json::Value>() ) {
jsonPayload = payload.get<ext::json::Value>();
}
sol::table table = ext::lua::decode(jsonPayload).value_or(ext::lua::state.create_table());
auto result = function( table );
#if UF_LUA_PCALLS
if ( !result.valid() ) {
sol::error err = result;
UF_MSG_ERROR("{}", err.what());
return pod::Hook::userdata_t();
}
#endif
sol::object retObj = result;
if ( retObj.get_type() != sol::type::lua_nil && retObj.is<sol::table>() ) {
auto encodedOpt = ext::lua::encode(retObj.as<sol::table>());
if (encodedOpt.has_value()) {
pod::Hook::userdata_t ret;
ret.create<ext::json::Value>(encodedOpt.value());
return ret;
}
#endif
});
};
void call( const uf::stl::string& name, sol::table table = ext::lua::createTable() ) {
ext::json::Value payload = uf::Serializer(table);
uf::hooks.call( name, payload );
return;
};
}
return pod::Hook::userdata_t();
}, pod::Hook::Type{UF_USERDATA_CTTI(ext::json::Value), sizeof(ext::json::Value)});
};
sol::object call( const uf::stl::string& name, sol::table table = ext::lua::createTable() ) {
auto encodedOpt = ext::lua::encode(table);
ext::json::Value payload = encodedOpt.has_value() ? encodedOpt.value() : ext::json::Value();
pod::Hook::userdata_t ud;
ud.create<ext::json::Value>(payload);
auto results = uf::hooks.call( name, ud );
if ( results.empty() ) return sol::lua_nil;
for ( auto& res : results ) {
if ( !res.is<ext::json::Value>() ) continue;
auto decodedOpt = ext::lua::decode( res.get<ext::json::Value>() );
if ( decodedOpt.has_value() ) {
return decodedOpt.value();
}
}
return sol::lua_nil;
};
}
namespace entities {
uf::Object& get(const uint& uid) {

View File

@ -1158,7 +1158,6 @@ namespace impl {
// fill indices
cell.polyIndices.resize( cell.header.numPolygons );
for ( uint8_t i = 0; i < cell.header.numPolygons; ++i ) {
// The reader can populate the vector directly!
reader.read( cell.polys[i].count, cell.polyIndices[i] );
}
@ -1418,12 +1417,12 @@ namespace impl {
uf::stl::string archetype = "Unknown";
ctx.findInheritedProperty(objectID, ctx.archetypes, archetype);
if ( ctx.customNames.count(objectID) ) {
node.name = uf::stl::string(ctx.customNames.at(objectID).c_str());
} else {
if ( archetype != "Unknown" ) node.name = uf::stl::string(archetype.c_str());
if ( node.name.empty()) node.name = ::fmt::format("object #{}", objectID);
}
if ( ctx.customNames.count(objectID) ) {
node.name = uf::stl::string(ctx.customNames.at(objectID).c_str());
} else {
if ( archetype != "Unknown" ) node.name = uf::stl::string(archetype.c_str());
if ( node.name.empty()) node.name = ::fmt::format("object #{}", objectID);
}
// bind position
PropertyPosition position = ctx.properties.position.at(objectID); {
@ -1518,38 +1517,6 @@ namespace impl {
metadata["sound"]["volume"] = ambient.override_volume;
metadata["sound"]["radius"] = ambient.radius * impl::darkToMeters;
metadata["sound"]["flags"] = ambient.flags;
uf::stl::string targetSchema = schemaName;
std::transform(targetSchema.begin(), targetSchema.end(), targetSchema.begin(), ::tolower);
int32_t schemaObjId = -1;
for ( const auto& [id, resolved] : ctx.schemas ) {
if ( resolved.name == targetSchema ) {
schemaObjId = id;
break;
}
}
if ( schemaObjId != -1 ) {
const auto& resolved = ctx.schemas.at(schemaObjId);
for ( const auto& wav : resolved.wavs ) {
auto& metadataWav = metadata["sound"]["wavs"].emplace_back();
metadataWav["uri"] = wav.name;
metadataWav["weight"] = wav.weight;
}
if ( resolved.hasPlayParams ) {
metadata["sound"]["schema_volume"] = resolved.playParams.volume;
metadata["sound"]["play_once"] = (resolved.playParams.flags & PropertySchPlayParams::SCH_PLAY_ONCE) != 0;
metadata["sound"]["stream"] = (resolved.playParams.flags & PropertySchPlayParams::SCH_STREAM) != 0;
}
if ( resolved.hasLoopParams ) {
metadata["sound"]["interval_min"] = resolved.loopParams.intervalMin;
metadata["sound"]["interval_max"] = resolved.loopParams.intervalMax;
}
}
}
// bind script
@ -1588,7 +1555,7 @@ namespace impl {
PropertyPhysAttr physAttr;
if ( ctx.findInheritedProperty( objectID, ctx.properties.physAttr, physAttr ) ) {
physMeta["mass"] = (physType.type == impl::PropertyPhysType::OBB || physAttr.edge_trigger != 0) ? 0.0f : physAttr.mass;
physMeta["mass"] = 0.0f; // (physType.type == impl::PropertyPhysType::OBB || physAttr.edge_trigger != 0) ? 0.0f : physAttr.mass;
physMeta["friction"] = physAttr.base_friction;
physMeta["restitution"] = physAttr.elasticity;
physMeta["gravity"] = uf::vector::encode( pod::Vector3f{0.0f, -0.0981f * physAttr.gravity, 0.0f} );
@ -1678,23 +1645,6 @@ namespace impl {
size_t sourceIdx = objectToNode[link.sourceId];
auto& srcNode = graph.nodes[sourceIdx];
if ( flavor == "SoundDescription" ) {
auto& connection = srcNode.metadata["dark"]["connections"].emplace_back();
connection["flavor"] = flavor;
connection["target_id"] = link.destId;
if ( ctx.schemas.count(link.destId) ) {
const auto& schema = ctx.schemas.at(link.destId);
connection["target_node"] = schema.name;
for (const auto& wav : schema.wavs) {
connection["wavs"].emplace_back(wav.name);
}
} else {
connection["target_node"] = "UnknownSchema";
}
continue;
}
if ( !objectToNode.count(link.destId) ) continue;
size_t destIdx = objectToNode[link.destId];
@ -1801,6 +1751,41 @@ namespace impl {
}
}
}
void processSchema( pod::Graph& graph, impl::DarkContext& ctx ) {
auto nodeID = graph.nodes.size();
auto& node = graph.nodes.emplace_back();
graph.root.children.emplace_back( nodeID );
node.name = "Schema DB";
auto& schemaDbMeta = node.metadata["dark"]["schema_db"];
for ( const auto& [id, schema] : ctx.schemas ) {
if ( schema.wavs.empty() ) continue;
auto& entry = schemaDbMeta.emplace_back();
entry["name"] = schema.name;
entry["tags"] = schema.classTag;
entry["msg"] = schema.msg;
entry["action"] = schema.action;
for (const auto& wav : schema.wavs) {
entry["wavs"].emplace_back(wav.name);
}
if ( schema.hasPlayParams ) {
entry["schema_volume"] = schema.playParams.volume;
entry["play_once"] = (schema.playParams.flags & impl::PropertySchPlayParams::SCH_PLAY_ONCE) != 0;
entry["stream"] = (schema.playParams.flags & impl::PropertySchPlayParams::SCH_STREAM) != 0;
}
if ( schema.hasLoopParams ) {
entry["interval_min"] = schema.loopParams.intervalMin;
entry["interval_max"] = schema.loopParams.intervalMax;
}
}
UF_MSG_DEBUG("Processed schema: {}", schemaDbMeta.size());
}
uf::stl::unordered_map<int32_t, uf::stl::string> parseNameMap( uf::stl::reader& reader ) {
uf::stl::unordered_map<int32_t, uf::stl::string> map;
@ -2060,22 +2045,7 @@ void ext::ttlg::loadMis( pod::Graph& graph, const uf::stl::string& filename, con
}
impl::processLinks( graph, ctx );
impl::processSongs( graph, ctx );
// needs a home
auto& schemaDbMeta = graph.metadata["dark"]["schema_db"];
for ( const auto& [id, schema] : ctx.schemas ) {
if ( schema.wavs.empty() ) continue;
auto& entry = schemaDbMeta.emplace_back();
entry["name"] = schema.name;
entry["tags"] = schema.classTag;
entry["msg"] = schema.msg;
entry["action"] = schema.action;
for (const auto& wav : schema.wavs) {
entry["wavs"].emplace_back(wav.name);
}
}
impl::processSchema( graph, ctx );
// disable postprocessing flags
if ( filename.starts_with("game://") ) graph.metadata["exporter"]["enabled"] = false; // disable exporting if loaded from a VPK