S1005403_RisCC/target_simulator/gui/ppi_display.py

159 lines
5.7 KiB
Python

# target_simulator/gui/ppi_display.py
"""
A Tkinter widget that displays a Plan Position Indicator (PPI) using Matplotlib.
"""
import tkinter as tk
from tkinter import ttk
import math
import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.transforms as transforms
import matplotlib.markers as markers
from core.models import Target
from typing import List
class PPIDisplay(ttk.Frame):
"""A custom widget for the PPI radar display."""
def __init__(self, master, max_range_nm: int = 100, scan_limit_deg: int = 60):
super().__init__(master)
self.max_range = max_range_nm
self.scan_limit_deg = scan_limit_deg
self.target_artists = []
self._create_controls()
self._create_plot()
def _create_controls(self):
"""Creates the control widgets for the PPI display."""
controls_frame = ttk.Frame(self)
controls_frame.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
ttk.Label(controls_frame, text="Range (NM):").pack(side=tk.LEFT)
# Generate range steps
steps = list(range(self.max_range, 19, -20))
if 10 not in steps:
steps.append(10)
self.range_var = tk.IntVar(value=self.max_range)
self.range_selector = ttk.Combobox(
controls_frame,
textvariable=self.range_var,
values=steps,
state="readonly",
width=5
)
self.range_selector.pack(side=tk.LEFT)
self.range_selector.bind("<<ComboboxSelected>>", self._on_range_selected)
def _create_plot(self):
"""Initializes the Matplotlib polar plot."""
# Dark theme for the plot
fig = Figure(figsize=(5, 5), dpi=100, facecolor='#3E3E3E')
fig.subplots_adjust(left=0.05, right=0.95, top=0.85, bottom=0.05)
self.ax = fig.add_subplot(111, projection='polar', facecolor='#2E2E2E')
# Configure polar axes
self.ax.set_theta_zero_location('N') # 0 degrees at the top
self.ax.set_theta_direction(-1) # Clockwise rotation
self.ax.set_rlabel_position(90)
self.ax.set_ylim(0, self.max_range)
# Set custom theta labels for sector scan view
angles = np.arange(0, 360, 30)
labels = []
for angle in angles:
if angle == 0:
labels.append("")
elif angle < 180:
labels.append(f"+{angle}°")
elif angle == 180:
labels.append("±180°")
else: # angle > 180
labels.append(f"-{360 - angle}°")
self.ax.set_thetagrids(angles, labels)
# Style the plot
self.ax.tick_params(axis='x', colors='white')
self.ax.tick_params(axis='y', colors='white')
self.ax.grid(color='white', linestyle='--', linewidth=0.5, alpha=0.5)
self.ax.spines['polar'].set_color('white')
self.ax.set_title("PPI Display", color='white', y=1.08)
# Draw scan sector limits
limit_rad = np.deg2rad(self.scan_limit_deg)
self.ax.plot([limit_rad, limit_rad], [0, self.max_range], color='yellow', linestyle='--', linewidth=1)
self.ax.plot([-limit_rad, -limit_rad], [0, self.max_range], color='yellow', linestyle='--', linewidth=1)
# Embed the plot in a Tkinter canvas
self.canvas = FigureCanvasTkAgg(fig, master=self)
self.canvas.draw()
self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
def _on_range_selected(self, event):
"""Handles the selection of a new range from the combobox."""
new_range = self.range_var.get()
self.ax.set_ylim(0, new_range)
# Update heading vector lengths on zoom
self.update_targets([]) # Pass empty list to redraw existing ones with new scale
self.canvas.draw()
def update_targets(self, targets: List[Target]):
"""
Updates the positions of targets on the PPI display.
Args:
targets: A list of Target objects to display.
"""
# If an empty list is passed, it means we just want to redraw existing targets
# (e.g., after a zoom change), not clear them.
if targets:
self.active_targets = [t for t in targets if t.active]
# Clear previously drawn targets
for artist in self.target_artists:
artist.remove()
self.target_artists.clear()
vector_len = self.range_var.get() / 25 # Length of heading vector relative to current view
for target in getattr(self, 'active_targets', []):
# Target position in polar
r1 = target.range_nm
th1 = np.deg2rad(target.azimuth_deg)
# Plot the target's center dot
dot, = self.ax.plot(th1, r1, 'o', markersize=5, color='red')
self.target_artists.append(dot)
# --- Calculate and plot heading vector ---
# Convert target polar to cartesian
x1 = r1 * np.sin(th1)
y1 = r1 * np.cos(th1)
# Calculate heading vector components
h_rad = np.deg2rad(target.heading_deg)
dx = vector_len * np.sin(h_rad)
dy = vector_len * np.cos(h_rad)
# Calculate end point of the vector in cartesian
x2, y2 = x1 + dx, y1 + dy
# Convert end point back to polar
r2 = np.sqrt(x2**2 + y2**2)
th2 = np.arctan2(x2, y2)
# Plot the heading line
line, = self.ax.plot([th1, th2], [r1, r2], color='red', linewidth=1.2)
self.target_artists.append(line)
# Redraw the canvas to show the changes
self.canvas.draw()