Version: v5.3.0
EWRS.lua is a DCS World Lua mission script that provides automated Early Warning Radar (EWR) picture reports and BRA (Bearing/Range/Altitude) callouts to players based on ground-based radar detection.
Designed for the 4YA Project Overlord WWII Normandy theatre, the script scans designated ground radar units, collects their detected targets, filters for airborne units, categorizes them into geographic zones, and periodically sends formatted reports to active players who have line-of-sight (LOS) to at least one friendly radar.
The system is designed to: - Distribute per-player BRA callouts (automated, via scheduled timers) - Provide a general "picture" overview of enemy concentrations per zone - Scale update rates dynamically based on server population - Only report targets visible above the radio/radar horizon (Earth curvature approximation)
-- All tunables live at the top of EWRS.lua
ewrs.messageUpdateInterval = 240 -- seconds between full message cycles
ewrs.messageDisplayTime = 20 -- seconds each message stays on screen
ewrs.enableRedTeam = true -- enable for Axis/Red
ewrs.enableBlueTeam = true -- enable for Allies/Blue
ewrs.useImprovedDetectionLogic = true -- suppress range for targets without distance lock
ewrs.maxThreatDisplay = 2 -- max threats in BRA table (0 = unlimited)
ewrs.PictureCallouts = true -- enable zone picture reports
ewrs.NoOfPictures = 2 -- how many zone summaries to show
ewrs.heartbeatEnabled = false -- periodic "script is still running" in-game message for debugging
ewrs.heartbeatInterval = 10 -- seconds between heartbeat messages
ewrs.minAltFriendlyContact = 75 -- AGL below which player gets "blind" warning
ewrs.minAltEnemyContact = 10 -- AGL below which enemy contacts are ignored
ewrs.redRadarsByName = {
"FREYA",
"Freya 1",
}
``
*initializeZones()` sets up the 23 named polygon zones covering the Normandy map and adjacent Channel areas.
buildActivePlayers() queries net.get_player_list() for all connected players, resolves slots to actual units, and populates activePlayers.
ewrs.radarNextPlayer), not a list index, so a player joining or leaving the server cannot make the cycle skip someone or waste a report slot.pictureUpdate() drives the detection pipeline:
findRadarUnits() scans all group names in blueRadarsByName and redRadarsByName, populating blueEwrUnits and redEwrUnits.findDetectedTargets(side) iterates each radar unit, pulls getDetectedTargets(RADAR), applies an Earth curvature / horizon filter, and returns a deduplicated list.
The geometric horizon is sqrt(2 * R * radar_height) + sqrt(2 * R * target_height), with R = 6,371,000 m. Heights are above sea level (clamped to zero), and range is horizontal. For example, a radar at 1,000 m and a target at 100 m have a combined horizon of approximately 148.6 km. DCS radar detection still determines terrain masking.filterUnits() performs O(N) hash-map deduplication and filters to air units only (Object.Category.UNIT, descriptor categories 0-1).getDetectedTargets(RADAR) before iterating to avoid pairs(nil) errors.currentlyDetectedRedUnits and currentlyDetectedBlueUnits. Both lists are always replaced, even when a side has no radar units, so a destroyed radar cannot leave stale contacts in the picture report.picture() runs when a report consumes the picture (see Lazy picture below):
findZone() to determine which zone it falls into.findZone() first rejects zones using a precomputed bounding box (ewrs.zoneBounds), then runs the full point-in-polygon test only on surviving candidates. The zone boxes are pairwise disjoint, so this eliminates the vast majority of polygon tests.pointInPolygon() is a local, allocation-free ray-casting test equivalent to mist.pointInPolygon for the {x=, z=} zone vertex format.sortPicture() copies zone data into redPicture / bluePicture and sorts by enemy contact count descending.The picture is lazy: findRadarUnits() sets ewrs.pictureDirty when detection data changes, and updatePicture() re-aggregates only when a report actually reads the picture. Previously the aggregation ran on a fixed 8-second timer whether or not a report was sent, which wasted most of the work at low player counts.
23 zones cover: LE HAVRE, ROUEN, BERNAY, EVREUX, LAIGLE, ARGENTAN, ESSAY, CABOURG, VILLERS_BOCAGE, BAYEUX, FLERS, ST.LO, AVRANCHES, CARENTAN, CHARTRES, PARIS, BEAUVAIS, CHANNEL WEST, CHANNEL CENTRAL, CHANNEL EAST, ISLE OF WIGHT, SELSEY, BEACHY_HEAD.
buildThreatTable(activePlayer):
useImprovedDetectionLogic is enabled and the target has no distance lock, Range is set to N/A.minAltEnemyContact (10m AGL) are filtered out.ipairs iteration) and returned.displayMessageToAll() runs every N seconds (default 240s, up to 360s at high player counts):
groupSettings, builds the threat table.outText() formats and sends the BRA report via trigger.action.outTextForGroup.minAltFriendlyContact (75m), appends "Kenway/Brutus is blind".PictureCallouts is enabled, appends the top zone summaries.adjustInterval() runs every 10 minutes:
| Player Count | Interval |
|---|---|
| >= 40 | 360s |
| >= 30 | 300s |
| < 30 | 240s |
This keeps total message volume bounded as server population grows.
All scheduled callbacks are registered through scheduleTracked(), which records the timer id in a per-instance registry (_G.EWRS_TIMER_IDS).
ewrs table on purpose: the documented recovery for a stuck script is to nil _G.ewrs and dofile() the file again. Because the registry survives that, the new instance cancels the previous instance's chains before arming its own — otherwise both copies would keep reporting.ewrs.shutdown() cancels every timer the instance scheduled and clears the loaded flag, so a later dofile() starts a clean instance.| Field | Purpose |
|---|---|
ewrs.blueEwrUnits / ewrs.redEwrUnits |
List of active radar unit names per side |
ewrs.currentlyDetectedRedUnits |
Detected targets visible to Blue radars |
ewrs.currentlyDetectedBlueUnits |
Detected targets visible to Red radars |
ewrs.activePlayers |
Table of connected players in valid slots |
ewrs.bluePicture / ewrs.redPicture |
Sorted zone summaries for picture reports |
ewrs.groupSettings |
Per-group message toggle state |
ewrs.zoneBounds |
Precomputed per-zone bounding boxes (picture prefilter) |
ewrs.pictureDirty |
Set when detection data changes; drives lazy re-aggregation |
ewrs.radarNextPlayer |
Name of the next player to be messaged (round-robin cursor) |
z corresponds to the mission editor y.ewrs.Zones are defined in the N1 Normandy coordinate space.Overall System Architecture
pictureUpdate Loop (15s cycle)
Radar Detection Pipeline
Threat Table Building (per player)
Message Display Pipeline (per player)
Zone Processing (Picture Report)
Player Management
Interval Adjustment Logic
| Function | Purpose |
|---|---|
ewrs.displayMessageToAll() |
Main loop. Picks one player per cycle, checks LOS, calls outText() or sends empty report. Schedules next run. |
ewrs.nextActivePlayer() |
Picks the next player for the round-robin report. Anchored to a player name so roster changes cannot skip a player or waste a cycle. |
ewrs.shutdown() |
Cancels every timer this instance scheduled and clears the loaded flag, so a later dofile() starts clean. |
ewrs.buildThreatTable(activePlayer) |
Returns a range-sorted table of {bearing, range, altitude, heading} for the player's nearest enemy contacts. |
ewrs.outText(activePlayer, threatTable, LOS) |
Formats and sends the BRA picture report (and optional zone summary) to the player's group via trigger.action.outTextForGroup. |
| Function | Purpose |
|---|---|
ewrs.getDetectedTargets() |
Wrapper that triggers detection for both sides. |
ewrs.findDetectedTargets(side) |
Iterates all radar units of side, pulls getDetectedTargets(RADAR), applies horizon/curvature filter, returns deduplicated list. |
ewrs.filterUnits(units) |
O(N) deduplication using a hash map. Also filters to Object.Category.UNIT and aircraft descriptor categories only (0-1). |
ewrs.findRadarUnits() |
Resolves radar group names into active unit lists (blueEwrUnits / redEwrUnits). |
| Function | Purpose |
|---|---|
ewrs.buildActivePlayers() |
Queries net API for all connected players, resolves slots to units, populates activePlayers. |
ewrs.addPlayer(playerName, groupID, unit) |
Adds one player record and bootstraps default groupSettings. |
ewrs.addGroupSettings(groupID) |
Initializes per-group settings (includes messages toggle). |
| Function | Purpose |
|---|---|
ewrs.picture() |
Resets zone counters, maps all detected targets into zones via findZone(), then calls sortPicture. |
ewrs.updatePicture() |
Re-aggregates the zone picture only when the detection data changed since the last aggregation (lazy picture). |
ewrs.findZone(x, z) |
Returns the index of the zone containing a point, using the bounding-box prefilter before the polygon test. |
ewrs.buildZoneBounds() |
Computes the bounding box of every zone once at startup. |
ewrs.sortPicture(zonesData) |
Copies zone data into redPicture / bluePicture and sorts each by enemy contact count descending. |
| Function | Purpose |
|---|---|
ewrs.adjustInterval() |
Dynamic throttling: increases messageUpdateInterval at 30+ and 40+ player thresholds. |
ewrs.pictureUpdate() |
Master scheduler: runs every 15s, chains buildActivePlayers -> findRadarUnits -> picture. |
| Function | Purpose |
|---|---|
getCardinalDirection(deg) |
Converts 0-360 heading to 8-point compass string (N, NE, E, SE, S, SW, W, NW). |
getRangeLabel(range) |
Buckets range into "MAX / LONG / MEDIUM / NEAR / MERGED". |
getAltLabel(alt) |
Buckets altitude into "V HIGH / HIGH / MED-HI / MED-LO / LOW / V LOW". |
getDistance3D(...) |
Euclidean 3D distance. |
getBearing(x1, z1, x2, z2) |
Bearing from (x1,z1) to (x2,z2) in degrees. |
getHeadingFromVec(vec) |
Computes heading from velocity vector. |
ewrs.pointInPolygon(px, pz, poly) |
Local, allocation-free ray-casting point-in-polygon test for the {x=, z=} zone vertex format. Equivalent to mist.pointInPolygon for this format. |
filterUnits uses a hash map instead of nested loops.table.insert, math.sqrt, trigger.action.outTextForGroup, etc.) are aliased to locals for faster lookup. Added mathCos localization for consistency.ewrs.pointInPolygon replaces mist.pointInPolygon, which deep-copies the polygon and allocates a Vec3 per vertex on every call. The local test allocates nothing.ewrs.zoneBounds lets findZone() reject a zone with four integer comparisons before running the polygon test. The 23 zone boxes are pairwise disjoint, so at most one zone survives the prefilter for any point.ewrs.pointInPolygon), so mist.lua no longer has to be loaded before this script.| File | Purpose |
|---|---|
EWRS.lua |
Cleaned production script (use this one) |
old/EWRS_old.lua |
Original script (kept for reference) |
.luacheckrc |
Luacheck configuration for DCS globals whitelist |
README.md |
This documentation |
README.html |
Rendered HTML with D2 diagrams |
../tests/ewrs_test.lua |
Mock-DCS test harness for EWRS.lua (cd tests && lua ewrs_test.lua) |
| Version | Date | Changes |
|---|---|---|
| v4.4 | Original | Base version by 4YA PO Modifications. Original zone-based picture reporting and BRA callout system. |
| v4.5 | -- | Replaced O(N^2) duplicate check in filterUnits with O(N) hash-map implementation. Replaced if/else heading logic with math-based lookup (getCardinalDirection). Inlined math functions (distance3D, bearing) in hot loops as local aliases. Localized global table lookups for performance. Cleaned up redundant code and comments. |
| v5.0 | -- | Dead code removal (unused constants, options, variables, mathAbs). Wired up PICTURE_DELAY and PICTURE_UPDATE_DELAY. Changed pairs to ipairs in buildThreatTable. Removed dead groupSettings fields (reference, measurements). Simplified greeting (removed dead "Reference: self" line). Added "No radar contacts found" message when LOS is false. Removed unused variables (side fetch in buildActivePlayers, contactType variable and unitType threat field). Spectator crash fix (slotID nil guard, unitName trimming, radarIndex reset). Nil guard for getDetectedTargets. Added mathCos localization. Added heartbeatEnabled / heartbeatInterval debug options. Added comprehensive README with D2 diagrams. |
| v5.1 | -- | Lua 5.1 compliance fix: removed all goto/::continue:: statements (Lua 5.2 feature incompatible with DCS). Replaced with inverted guard conditions in buildThreatTable, buildActivePlayers, and filterUnits. Heartbeat message now sent to all players in-game (was: log only). Added script-load message to players + log ("EWRS Running v5.1", 5s display). Updated AGENTS.md with Lua 5.1 constraint. |
| v5.2 | -- | Bug fix: Removed ewrs.radarIndex = 1 reset in buildActivePlayers() (line 609). This reset was clobbering the round-robin index every 15s, causing displayMessageToAll() to always message activePlayers[1] only. With this fix, the round-robin properly advances through all players in activePlayers. Bumped version string. |
| v5.2.1 | -- | Coalition messaging: Localized the "blind" altitude warning so Red players receive German ("Brutus hat keinen Sichtkontakt. Erhöhen Sie Ihre Höhe") and Blue players receive English ("Kenway is blind on you. Increase your altitude"). Fixed umlaut encoding (ö, ü, ä) in German strings. |
| v5.2.2 | -- | Reload safety: Added a reload guard (_G.ewrs = { loaded = true }) to prevent double-registration of event handlers and duplicate timers on hot-reload (dofile from the DCS console or mission editor). Also bumped the script-load message version string to v5.2.2. |
| v5.2.3 | -- | Bug fixes: (1) Fixed double-escaped \\n\\n in the German "blind" altitude warning. The Lua source had \\n\\n (4 source chars: backslash-backslash-n-backslash-backslash-n) which Lua parses to 2 literal backslash-n sequences in the message string. The English version was already correct (\n\n = 2 source chars = 2 newlines when parsed). Red players below 75m AGL were seeing a literal \n at the end of the warning instead of a newline. (2) Fixed inverted heartbeat gating: trigger.action.outText was being called unconditionally on every mission start (even with ewrs.heartbeatEnabled = false, the default), and only the reschedule was gated on the flag. Moved the outText call inside the if ewrs.heartbeatEnabled block. (3) Cleanup: 4 unused loop variable k → _ and 1 whitespace-only line. Bumped the script-load message version string to v5.2.3. |
| v5.2.4 | 2026-09-18 | Bug fixes: (1) Horizon filtering now uses the combined geometric horizon of radar and target elevations above sea level, compared with horizontal range, so elevated radars retain legitimate detections. (2) Player discovery skips missing names, slots, units, and groups, and isolates each player lookup so stale objects cannot interrupt discovery of other players. Updated detection and player-discovery documentation and diagrams. Script header, startup log, and in-game startup message now report v5.2.4. |
| v5.3.0 | 2026-10-22 | Bug fixes and performance: (1) Reload safety: all scheduled callbacks are registered through scheduleTracked() into a per-instance registry kept outside the ewrs table. The documented recovery (_G.ewrs = nil then dofile()) now cancels the previous instance's timer chains instead of leaving two copies of EWRS reporting side by side. Added ewrs.shutdown() to cancel every timer and clear the loaded flag. (2) Stale contacts: getDetectedTargets() now always replaces both detection lists, so a destroyed radar can no longer leave its last known contacts in the picture report forever. (3) Round-robin: the cursor is anchored to a player name (ewrs.radarNextPlayer) instead of a list index, so a player joining or leaving the server can no longer make the cycle skip someone or waste a report slot. (4) Performance: the zone point-in-polygon test is now a local, allocation-free ray caster (ewrs.pointInPolygon) instead of mist.pointInPolygon, and each zone carries a precomputed bounding box (ewrs.zoneBounds) used as a cheap prefilter, eliminating the vast majority of polygon tests. This removes the MIST load-order requirement. (5) Lazy picture: zone aggregation is no longer run on a fixed 8s timer; it is recomputed on demand when a report actually consumes it (ewrs.updatePicture()), and the now-unused PICTURE_DELAY constant was removed. Added a mock-DCS test harness (tests/ewrs_test.lua, 22 tests) covering detection, horizon filtering, threat tables, report formatting, reload safety, and the round-robin. Updated detection, zone, picture, message-display and player-management documentation and diagrams. Script header, startup log, and in-game startup message now report v5.3.0. |
EWRS.lua into your DCS mission's "Scripts" folder or "l10n/DEFAULT" folder.ewrs.blueRadarsByName and ewrs.redRadarsByName in the script to match your mission's radar group names.ewrs.Zones polygon coordinates.EWRS Running v5.3.0