Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions resources/config/defaults.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ contact_label_padding = 5 # Additional padding for track labels in pixels
center_point_size = 3.0 # Size of the center point quad in pixels
bullseye_num_rings = 6 # Number of concentric rings in the bullseye display
bullseye_ring_distance = 20 # Distance between bullseye rings in nautical miles
bullseye_text_color = [ 220, 200, 40 ] # [r, g, b] Bullseye cursor text color
braa_text_color = [ 30, 150, 235 ] # [r, g, b] BRAA text and line color

[display]
icon_set = "classic" # Icon set to use for displaying objects (NTDS, classic)
Expand Down
54 changes: 44 additions & 10 deletions src/draw/imgui_radar_labels_renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@

from imgui_bundle import imgui
from draw.scene import Scene
from draw.shapes import Shapes
from game_object import GameObject
from game_object_types import get_layer_key
from game_object_types import GameObjectType, get_layer_key
from game_state import GameState
from sensor_tracks import Track
from util.track_labels import (TrackLabelLocation, TrackLabels, get_labels_for_class_type, evaluate_input_format)
Expand All @@ -28,12 +29,14 @@
# dx = offset_x_sign * offset + text_width_coef * text_width
# dy = offset_y_sign * offset + text_height_coef * text_height
_LABEL_OFFSET_COEFFICIENTS: Dict[TrackLabelLocation, Tuple[float, float, float, float]] = {
TrackLabelLocation.TOP_LEFT: (-1.0, -1.0, -1.0, -1.0),
TrackLabelLocation.TOP_CENTER: (0.0, -0.5, -1.0, -1.0),
TrackLabelLocation.TOP_RIGHT: (1.0, 0.0, -1.0, -1.0),
TrackLabelLocation.LEFT: (-1.0, -1.0, 0.0, -0.5),
TrackLabelLocation.CENTER: (0.0, -0.5, 0.0, -0.5),
TrackLabelLocation.RIGHT: (1.0, 0.0, 0.0, -0.5),
# Keep horizontal/text-width coefficients, but set text_height_coef to 0.0
# so vertical placement does not multiply by text height (avoids implicit gaps).
TrackLabelLocation.TOP_LEFT: (-1.0, -1.0, -1.0, 0.0),
TrackLabelLocation.TOP_CENTER: (0.0, -0.5, -1.0, 0.0),
TrackLabelLocation.TOP_RIGHT: (1.0, 0.0, -1.0, 0.0),
TrackLabelLocation.LEFT: (-1.0, -1.0, 0.0, 0.0),
TrackLabelLocation.CENTER: (0.0, -0.5, 0.0, 0.0),
TrackLabelLocation.RIGHT: (1.0, 0.0, 0.0, 0.0),
TrackLabelLocation.BOTTOM_LEFT: (-1.0, -1.0, 1.0, 0.0),
TrackLabelLocation.BOTTOM_CENTER: (0.0, -0.5, 1.0, 0.0),
TrackLabelLocation.BOTTOM_RIGHT: (1.0, 0.0, 1.0, 0.0),
Expand Down Expand Up @@ -265,7 +268,19 @@ def draw_all_ac_labels(self, gamestate: GameState):
if labels is None or not labels.labels:
continue

objs = list(objects_by_id.values())
if object_type == GameObjectType.FIXEDWING:
ordered_ids = gamestate.render_arrays.get_icon_order_for_shape(Shapes.SQUARE)
objs = [objects_by_id[oid] for oid in ordered_ids if oid in objects_by_id]
if not objs:
objs = list(objects_by_id.values())
elif object_type == GameObjectType.ROTARYWING:
ordered_ids = gamestate.render_arrays.get_icon_order_for_shape(Shapes.TOP_BOX)
objs = [objects_by_id[oid] for oid in ordered_ids if oid in objects_by_id]
if not objs:
objs = list(objects_by_id.values())
else:
objs = list(objects_by_id.values())

world_positions = np.array([(obj.U, obj.V) for obj in objs], dtype=np.float64)
screen_positions = self.scene.world_to_screen_batch(world_positions).tolist()

Expand Down Expand Up @@ -346,14 +361,33 @@ def render(self):
if imgui.begin("RadarLabelsOverlay", None, self._overlay_flags):
draw_list = imgui.get_window_draw_list()

# Render each cached label
# Render each cached label with a zero-padded background rectangle
for cached_label in self._text_cache.values():
# Calculate text size
text_size = imgui.calc_text_size(cached_label.text)

# Background color (semi-transparent dark) and zero padding
bg_col = imgui.get_color_u32(imgui.ImVec4(0.0, 0.0, 0.0, 0.7))

# Rectangle coordinates: no padding (zero padding)
rect_min = imgui.ImVec2(cached_label.x_screen, cached_label.y_screen)
rect_max = imgui.ImVec2(cached_label.x_screen + text_size.x, cached_label.y_screen + text_size.y)

# if rect_min rect_max overlaps with a rect_min and rect_max already in the draw_list, then skip drawing this label to avoid overlap
# for rects in draw_list:
# if (rect_min.x < rects.x and rect_max.x > rects.x and
# rect_min.y < rects.y and rect_max.y > rects.y):
# # Overlap detected, skip drawing this label
# continue

# Draw background rectangle then text
draw_list.add_rect_filled(rect_min, rect_max, bg_col)

# Get text color (white by default)
text_color = imgui.get_color_u32(
imgui.ImVec4(cached_label.color[0], cached_label.color[1], cached_label.color[2],
cached_label.color[3]))

# Add text to the draw list at the specified position
draw_list.add_text(imgui.ImVec2(cached_label.x_screen, cached_label.y_screen), text_color,
cached_label.text)

Expand Down
22 changes: 19 additions & 3 deletions src/draw/radar_labels_renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from typing import Dict, Optional

from draw.scene import Scene
from draw.shapes import Shapes
from draw.text import TextRendererMsdf, make_text_renderer
from game_object import GameObject
from game_object_types import GameObjectType
Expand Down Expand Up @@ -64,9 +65,21 @@ def set_hovered_obj(self, obj: GameObject | None):
"""
self._hovered_object = obj

def draw_all_ac_labels(self, gamestate: GameState):
def _get_ordered_objects_by_icon(self, gamestate: GameState, object_type: GameObjectType, shapes: list[Shapes]) -> list[GameObject]:
"""Return objects in the order they appear in the icon render buffers for given shapes."""
ordered_ids: list[str] = []
for shape in shapes:
ordered_ids.extend(gamestate.render_arrays.get_icon_order_for_shape(shape))

ordered_objects: list[GameObject] = []
type_objects = gamestate.objects.get(object_type, {})
for object_id in ordered_ids:
if object_id in type_objects:
ordered_objects.append(type_objects[object_id])

fixed_wing_objs = gamestate.objects[GameObjectType.FIXEDWING]
return ordered_objects

def draw_all_ac_labels(self, gamestate: GameState):

# Get the label configuration for this track type
labels = get_labels_for_class_type(GameObjectType.FIXEDWING)
Expand All @@ -76,7 +89,10 @@ def draw_all_ac_labels(self, gamestate: GameState):
font_scale = config.app_config.get_int("radar", "contact_font_scale")

if labels is not None:
for obj in fixed_wing_objs.values():
fixed_wing_objs = self._get_ordered_objects_by_icon(gamestate, GameObjectType.FIXEDWING, [Shapes.SQUARE])
if not fixed_wing_objs:
fixed_wing_objs = list(gamestate.objects[GameObjectType.FIXEDWING].values())
for obj in fixed_wing_objs:
self.draw_track_labels(obj, labels, offset, font_scale)

#draw hovered labels
Expand Down
92 changes: 89 additions & 3 deletions src/render_data_arrays.py
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,9 @@ def __init__(self, initial_capacity: int = 1024 * 8):
self.velocity_vectors = VelocityVectorRenderData(initial_capacity // 2)
self.lock_lines = LockLineRenderData(initial_capacity // 2)

# Store callsign metadata for objects currently in icon arrays.
self._callsign_by_object_id: dict[str, str] = {}

def _should_render_object_type(self, obj_type) -> bool:
"""Check if an object type should be rendered based on layer configuration."""
# Bullseye has a layer key, but its visibility is handled separately in
Expand All @@ -574,6 +577,77 @@ def _should_render_object_type(self, obj_type) -> bool:

return True # Default to showing unknown types

# Draw order by last callsign digit (flight position); later entries are drawn on top.
# Callsigns not ending in 1-4 are drawn first (bottom).
CALLSIGN_DRAW_PRIORITY = {"4": 1, "2": 2, "3": 3, "1": 4}
SORTED_SHAPES = (Shapes.SQUARE, Shapes.TOP_BOX)

def _callsign_priority(self, element_id: str) -> int:
callsign = self._callsign_by_object_id.get(element_id, "")
return self.CALLSIGN_DRAW_PRIORITY.get(callsign[-1:], 0)

def resort_by_callsign(self, objects: dict | None = None):
"""Refresh cached callsigns (if objects supplied) and re-sort all sorted icon arrays."""
if objects is not None:
for obj in objects.values():
if obj.object_id in self._callsign_by_object_id:
self._callsign_by_object_id[obj.object_id] = getattr(obj, 'CallSign', '') or ''
self.sort_elements_by_callsign()

def sort_elements_by_callsign(self, game_obj: GameObject | None = None):
"""Reorder aircraft icon arrays by flight position: #4, #2, #3, #1 (so #1 draws on top)."""
shapes_to_sort = list(self.SORTED_SHAPES)
if game_obj is not None:
shape = Shapes.from_idx(game_obj.icon) if game_obj.icon is not None else None
if shape in self.SORTED_SHAPES:
shapes_to_sort = [shape]

for shape in shapes_to_sort:
icon_data = self.icon_data.get(shape)
if icon_data is None or icon_data.count == 0:
continue

current_order = [icon_data.index_to_id[index] for index in range(icon_data.count)]
# Stable sort keeps existing relative order within each priority group.
new_order = sorted(current_order, key=self._callsign_priority)
if new_order != current_order:
self._reorder_icon_data(icon_data, new_order)

# Print the current ordered callsigns for debug/verification
#print("---")
#for index in range(icon_data.count):
# element_id = icon_data.index_to_id[index]
# callsign = self._callsign_by_object_id.get(element_id, "")
# print(callsign)

def _reorder_icon_data(self, icon_data: IconRenderData, new_order: list[str]):
"""Reorder an icon array to match the supplied list of element IDs."""
if icon_data.data is None or icon_data.count == 0:
return

active_data = icon_data.get_active_data()
if active_data is None:
return

reordered_data = np.zeros_like(active_data)
for new_index, element_id in enumerate(new_order):
old_index = icon_data.id_to_index[element_id]
reordered_data[new_index] = active_data[old_index]

icon_data.data[:icon_data.count] = reordered_data
for new_index, element_id in enumerate(new_order):
icon_data.index_to_id[new_index] = element_id
icon_data.id_to_index[element_id] = new_index
# Reordering icon instances only affects icon draw order.
# Label renderers should use the same ordered object list for consistent rendering.

def get_icon_order_for_shape(self, shape: Shapes) -> list[str]:
"""Return the object IDs in the current icon buffer order for a shape."""
icon_data = self.icon_data.get(shape)
if icon_data is None or icon_data.count == 0:
return []
return [icon_data.index_to_id[i] for i in range(icon_data.count)]

def add_object(self, game_obj: GameObject):
"""Add a game object to all relevant render arrays."""

Expand All @@ -586,6 +660,9 @@ def add_object(self, game_obj: GameObject):
shape = Shapes.from_idx(shape_id) if shape_id is not None else None
if shape is not None:
self.icon_data[shape].add_object(game_obj)
self._callsign_by_object_id[game_obj.object_id] = getattr(game_obj, 'CallSign', '') or ''
if shape in self.SORTED_SHAPES:
self.sort_elements_by_callsign(game_obj)

# Add velocity vector if it's an aircraft
if game_obj.is_air_unit() and game_obj.CAS > 0:
Expand All @@ -604,8 +681,14 @@ def remove_object(self, game_obj: GameObject):
shape_id = game_obj.icon

shape = Shapes.from_idx(shape_id) if shape_id is not None else None
if shape is not None:
removed = False
if shape is not None and object_id in self.icon_data[shape].id_to_index:
self.icon_data[shape].remove_object(object_id)
removed = True
self._callsign_by_object_id.pop(object_id, None)
# Removal swaps the last element into the gap, so restore callsign order.
if removed and shape in self.SORTED_SHAPES:
self.sort_elements_by_callsign(game_obj)

self.velocity_vectors.remove_object(object_id)
self.lock_lines.remove_object_locks(object_id)
Expand All @@ -627,9 +710,13 @@ def update_object(self, game_obj: GameObject):
if game_obj.object_id in self.icon_data[shape].id_to_index:
# Object exists, update it
self.icon_data[shape].update_object(game_obj)
self._callsign_by_object_id[game_obj.object_id] = getattr(game_obj, 'CallSign', '') or ''
else:
# Object doesn't exist, add it
self.icon_data[shape].add_object(game_obj)
self._callsign_by_object_id[game_obj.object_id] = getattr(game_obj, 'CallSign', '') or ''
if shape in self.SORTED_SHAPES:
self.sort_elements_by_callsign(game_obj)

# Update or add/remove velocity vector based on movement
if game_obj.is_air_unit() and game_obj.CAS > 0:
Expand Down Expand Up @@ -679,8 +766,7 @@ def rebuild_from_objects(self, objects: dict):
"""Rebuild all render arrays from a dictionary of game objects."""
self.clear_all()
for obj in objects.values():
self.add_object(obj)

self.add_object(obj)

class PolygonRenderData(GenericStructuredArray):
"""
Expand Down
61 changes: 61 additions & 0 deletions src/tests/test_render_data_arrays_fixed.py
Original file line number Diff line number Diff line change
Expand Up @@ -919,6 +919,67 @@ def test_add_object_with_locks(self):
assert "source" in render_arrays.lock_lines.id_to_locks
assert "target" in render_arrays.lock_lines.id_to_locks["source"]

def test_sort_square_callsigns_by_flight_position(self):
"""Square icons are ordered #4, #2, #3, #1 so #1 is drawn last (on top)."""
render_arrays = TrackRenderDataArrays(100)

callsigns = {"obj1": "Falcon11", "obj2": "Avenger23", "obj3": "Eagle22",
"obj4": "Viper14", "obj5": "Tanker", "obj6": "Hawk12"}
objs = {}
for obj_id, callsign in callsigns.items():
obj = self.create_mock_game_object(obj_id, icon=2)
obj.CallSign = callsign
objs[obj_id] = obj
render_arrays.add_object(obj)

ordered_ids = render_arrays.get_icon_order_for_shape(Shapes.SQUARE)
assert ordered_ids == ["obj5", "obj4", "obj3", "obj6", "obj2", "obj1"]

# Removing #1 leaves #3 on top, then #2, then #4
render_arrays.remove_object(objs["obj1"])
ordered_ids = render_arrays.get_icon_order_for_shape(Shapes.SQUARE)
assert ordered_ids == ["obj5", "obj4", "obj3", "obj6", "obj2"]

square = render_arrays.icon_data[Shapes.SQUARE]
for i, obj_id in enumerate(ordered_ids):
assert square.id_to_index[obj_id] == i

def test_resort_by_callsign_uses_updated_callsigns(self):
"""Manual re-sort picks up callsign changes from the supplied objects."""
render_arrays = TrackRenderDataArrays(100)

first = self.create_mock_game_object("obj1", icon=2)
first.CallSign = "Falcon11"
second = self.create_mock_game_object("obj2", icon=2)
second.CallSign = "Avenger24"
render_arrays.add_object(first)
render_arrays.add_object(second)
assert render_arrays.get_icon_order_for_shape(Shapes.SQUARE) == ["obj2", "obj1"]

first.CallSign = "Falcon14"
second.CallSign = "Avenger21"
render_arrays.resort_by_callsign({"obj1": first, "obj2": second})
assert render_arrays.get_icon_order_for_shape(Shapes.SQUARE) == ["obj1", "obj2"]

def test_get_icon_order_for_shape_returns_current_buffer_order(self):
"""Test that icon order can be retrieved from the current render array."""
render_arrays = TrackRenderDataArrays(100)

first = self.create_mock_game_object("obj1", icon=2)
first.CallSign = "Falcon11"
second = self.create_mock_game_object("obj2", icon=2)
second.CallSign = "Avenger21"
third = self.create_mock_game_object("obj3", icon=2)
third.CallSign = "Eagle22"

render_arrays.add_object(first)
render_arrays.add_object(second)
render_arrays.add_object(third)
render_arrays.sort_elements_by_callsign(first)

ordered_ids = render_arrays.get_icon_order_for_shape(Shapes.SQUARE)
assert ordered_ids == ["obj3", "obj1", "obj2"]

def test_remove_object(self):
"""Test removing an object from all arrays."""
render_arrays = TrackRenderDataArrays(100)
Expand Down
Loading