Merge pull request #572 from Pax1601/540-grouped-units-cant-be-selected

Grouped units can be deleted now
This commit is contained in:
Pax1601 2023-11-22 15:13:02 +01:00 committed by GitHub
commit 0ba05d5795
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 281 additions and 258 deletions

View File

@ -25,8 +25,6 @@ class DemoDataGenerator {
app.get('/demo/commands', (req, res) => this.command(req, res));
app.put('/demo', (req, res) => this.put(req, res));
console.log(config["authentication"]["gameMasterPassword"])
app.use('/demo', basicAuth({
users: {
'admin': config["authentication"]["gameMasterPassword"],
@ -54,9 +52,9 @@ class DemoDataGenerator {
isLeader: true
}
/*
***************** UNCOMMENT TO TEST ALL UNITS ****************
// UNCOMMENT TO TEST ALL UNITS ****************
var databases = Object.assign({}, aircraftDatabase, helicopterDatabase, groundUnitDatabase, navyUnitDatabase);
var t = Object.keys(databases).length;
@ -93,6 +91,7 @@ class DemoDataGenerator {
}
*/
let idx = 1;
DEMO_UNIT_DATA[idx] = JSON.parse(JSON.stringify(baseData));
DEMO_UNIT_DATA[idx].name = "S_75M_Volhov";
@ -116,6 +115,7 @@ class DemoDataGenerator {
DEMO_UNIT_DATA[idx].position.lat += idx / 100;
DEMO_UNIT_DATA[idx].category = "GroundUnit";
DEMO_UNIT_DATA[idx].isLeader = false;
idx += 1;
DEMO_UNIT_DATA[idx] = JSON.parse(JSON.stringify(baseData));

View File

@ -64,7 +64,7 @@ export class ControlTipsPlugin implements OlympusPlugin {
this.#updateTips();
});
document.addEventListener("mapVisibilityOptionsChanged", () => {
document.addEventListener("mapOptionsChanged", () => {
this.toggle( !this.#app.getMap().getVisibilityOptions()[SHOW_CONTROL_TIPS] );
});

View File

@ -23,7 +23,7 @@ body {
}
.hidden-cursor {
cursor: none !important;
/*cursor: none !important;*/
}
.hidden-cursor * {

View File

@ -1,5 +1,5 @@
import { LatLng, LatLngBounds } from "leaflet";
import { MapMarkerControl } from "../map/map";
import { MapMarkerVisibilityControl } from "../map/map";
export const UNITS_URI = "units";
export const WEAPONS_URI = "weapons";
@ -157,10 +157,10 @@ export const mapLayers = {
export const IDLE = "Idle";
export const MOVE_UNIT = "Move unit";
export const COALITIONAREA_DRAW_POLYGON = "Draw Coalition Area";
export const visibilityControls: string[] = ["human", "dcs", "aircraft", "helicopter", "groundunit-sam", "groundunit-other", "navyunit", "airbase"];
export const visibilityControlsTypes: string[][] = [["human"], ["dcs"], ["aircraft"], ["helicopter"], ["groundunit-sam", "groundunit-sam-radar", "groundunit-sam-launcher"], ["groundunit-other", "groundunit-ewr"], ["navyunit"], ["airbase"]];
export const visibilityControls: string[] = ["human", "dcs", "aircraft", "helicopter", "groundunit-sam", "groundunit", "navyunit", "airbase"];
export const visibilityControlsTypes: string[][] = [["human"], ["dcs"], ["aircraft"], ["helicopter"], ["groundunit-sam"], ["groundunit"], ["navyunit"], ["airbase"]];
export const visibilityControlsTooltips: string[] = ["Toggle human players visibility", "Toggle DCS controlled units visibility", "Toggle aircrafts visibility", "Toggle helicopter visibility", "Toggle SAM units visibility", "Toggle ground units (not SAM) visibility", "Toggle navy units visibility", "Toggle airbases visibility"];
export const MAP_MARKER_CONTROLS: MapMarkerControl[] = [{
export const MAP_MARKER_CONTROLS: MapMarkerVisibilityControl[] = [{
"name": "Human",
"image": "visibility/human.svg",
"toggles": ["human"],
@ -188,9 +188,9 @@ export const MAP_MARKER_CONTROLS: MapMarkerControl[] = [{
"toggles": ["groundunit-sam"],
"tooltip": "Toggle air defence units' visibility"
}, {
"image": "visibility/groundunit-other.svg",
"image": "visibility/groundunit.svg",
"name": "Ground units",
"toggles": ["groundunit-other"],
"toggles": ["groundunit"],
"tooltip": "Toggle ground units' visibility"
}, {
"image": "visibility/navyunit.svg",

2
client/src/dom.d.ts vendored
View File

@ -18,7 +18,7 @@ interface CustomEventMap {
"groupDeletion": CustomEvent<Unit[]>,
"mapStateChanged": CustomEvent<string>,
"mapContextMenu": CustomEvent<>,
"mapVisibilityOptionsChanged": CustomEvent<>,
"mapOptionsChanged": CustomEvent<>,
"commandModeOptionsChanged": CustomEvent<>,
"contactsUpdated": CustomEvent<Unit>,
"activeCoalitionChanged": CustomEvent<>

View File

@ -13,7 +13,6 @@ import { TemporaryUnitMarker } from "./markers/temporaryunitmarker";
import { ClickableMiniMap } from "./clickableminimap";
import { SVGInjector } from '@tanem/svg-injector'
import { mapLayers, mapBounds, minimapBoundaries, IDLE, COALITIONAREA_DRAW_POLYGON, MOVE_UNIT, SHOW_UNIT_CONTACTS, HIDE_GROUP_MEMBERS, SHOW_UNIT_PATHS, SHOW_UNIT_TARGETS, SHOW_UNIT_LABELS, SHOW_UNITS_ENGAGEMENT_RINGS, SHOW_UNITS_ACQUISITION_RINGS, HIDE_UNITS_SHORT_RANGE_RINGS, FILL_SELECTED_RING, MAP_MARKER_CONTROLS } from "../constants/constants";
import { TargetMarker } from "./markers/targetmarker";
import { CoalitionArea } from "./coalitionarea/coalitionarea";
import { CoalitionAreaContextMenu } from "../contextmenus/coalitionareacontextmenu";
import { DrawingCursor } from "./coalitionarea/drawingcursor";
@ -27,9 +26,9 @@ var hasTouchScreen = false;
//if ("maxTouchPoints" in navigator)
// hasTouchScreen = navigator.maxTouchPoints > 0;
if (hasTouchScreen)
if (hasTouchScreen)
L.Map.addInitHook('addHandler', 'boxSelect', TouchBoxSelect);
else
else
L.Map.addInitHook('addHandler', 'boxSelect', BoxSelect);
L.Map.addInitHook("addHandler", "gestureHandling", GestureHandling);
@ -38,10 +37,10 @@ L.Map.addInitHook("addHandler", "gestureHandling", GestureHandling);
require("../../public/javascripts/leaflet.nauticscale.js")
require("../../public/javascripts/L.Path.Drag.js")
export type MapMarkerControl = {
export type MapMarkerVisibilityControl = {
"image": string;
"isProtected"?: boolean,
"name":string,
"name": string,
"protectable"?: boolean,
"toggles": string[],
"tooltip": string
@ -75,7 +74,6 @@ export class Map extends L.Map {
#destinationRotationCenter: L.LatLng | null = null;
#coalitionAreas: CoalitionArea[] = [];
#targetCursor: TargetMarker = new TargetMarker(new L.LatLng(0, 0), { interactive: false });
#destinationPreviewCursors: DestinationPreviewMarker[] = [];
#drawingCursor: DrawingCursor = new DrawingCursor();
#destinationPreviewHandle: DestinationPreviewHandle = new DestinationPreviewHandle(new L.LatLng(0, 0));
@ -90,7 +88,7 @@ export class Map extends L.Map {
#coalitionAreaContextMenu: CoalitionAreaContextMenu = new CoalitionAreaContextMenu("coalition-area-contextmenu");
#mapSourceDropdown: Dropdown;
#mapMarkerControls:MapMarkerControl[] = MAP_MARKER_CONTROLS;
#mapMarkerVisibilityControls: MapMarkerVisibilityControl[] = MAP_MARKER_CONTROLS;
#mapVisibilityOptionsDropdown: Dropdown;
#optionButtons: { [key: string]: HTMLButtonElement[] } = {}
#visibilityOptions: { [key: string]: boolean } = {}
@ -100,21 +98,21 @@ export class Map extends L.Map {
*
* @param ID - the ID of the HTML element which will contain the context menu
*/
constructor(ID: string){
constructor(ID: string) {
/* Init the leaflet map */
super(ID, {
preferCanvas: true,
doubleClickZoom: false,
zoomControl: false,
boxZoom: false,
super(ID, {
preferCanvas: true,
doubleClickZoom: false,
zoomControl: false,
boxZoom: false,
//@ts-ignore Needed because the boxSelect option is non-standard
boxSelect: true,
zoomAnimation: true,
boxSelect: true,
zoomAnimation: true,
maxBoundsViscosity: 1.0,
minZoom: 7,
minZoom: 7,
keyboard: true,
keyboardPanDelta: 0,
gestureHandling: hasTouchScreen
gestureHandling: hasTouchScreen
});
this.setView([37.23, -115.8], 10);
@ -198,15 +196,15 @@ export class Map extends L.Map {
this.#panToUnit(this.#centerUnit);
});
document.addEventListener("mapVisibilityOptionsChanged", () => {
document.addEventListener("mapOptionsChanged", () => {
this.getContainer().toggleAttribute("data-hide-labels", !this.getVisibilityOptions()[SHOW_UNIT_LABELS]);
});
/* Pan interval */
this.#panInterval = window.setInterval(() => {
if (this.#panUp || this.#panDown || this.#panRight || this.#panLeft)
this.panBy(new L.Point(((this.#panLeft ? -1 : 0) + (this.#panRight ? 1 : 0)) * this.#deafultPanDelta,
((this.#panUp ? -1 : 0) + (this.#panDown ? 1 : 0)) * this.#deafultPanDelta));
this.panBy(new L.Point(((this.#panLeft ? -1 : 0) + (this.#panRight ? 1 : 0)) * this.#deafultPanDelta * (this.#shiftKey ? 3 : 1),
((this.#panUp ? -1 : 0) + (this.#panDown ? 1 : 0)) * this.#deafultPanDelta * (this.#shiftKey ? 3 : 1)));
}, 20);
/* Option buttons */
@ -257,7 +255,7 @@ export class Map extends L.Map {
/* Operations to perform if you are NOT in a state */
if (this.#state !== COALITIONAREA_DRAW_POLYGON) {
this.#deselectCoalitionAreas();
this.#deselectSelectedCoalitionArea();
}
/* Operations to perform if you ARE in a state */
@ -291,7 +289,6 @@ export class Map extends L.Map {
else {
this.#hiddenTypes.push(key);
}
Object.values(getApp().getUnitsManager().getUnits()).forEach((unit: Unit) => unit.updateVisibility());
}
getHiddenTypes() {
@ -377,11 +374,6 @@ export class Map extends L.Map {
this.#coalitionAreaContextMenu.hide();
}
isZooming() {
return this.#isZooming;
}
/* Mouse coordinates */
getMousePosition() {
return this.#lastMousePosition;
}
@ -390,11 +382,6 @@ export class Map extends L.Map {
return this.containerPointToLatLng(this.#lastMousePosition);
}
/* Spawn from air base */
spawnFromAirbase(e: any) {
//this.#aircraftSpawnMenu(e);
}
centerOnUnit(ID: number | null) {
if (ID != null) {
this.options.scrollWheelZoom = 'center';
@ -407,7 +394,7 @@ export class Map extends L.Map {
this.#updateCursor();
}
getCenterUnit() {
getCenteredOnUnit() {
return this.#centerUnit;
}
@ -420,7 +407,6 @@ export class Map extends L.Map {
}
this.setView(bounds.getCenter(), 8);
//this.setMaxBounds(bounds);
if (this.#miniMap)
this.#miniMap.remove();
@ -502,10 +488,35 @@ export class Map extends L.Map {
return this.#visibilityOptions;
}
isZooming() {
return this.#isZooming;
}
getPreviousZoom() {
return this.#previousZoom;
}
getIsUnitProtected(unit: Unit) {
const toggles = this.#mapMarkerVisibilityControls.reduce((list, control: MapMarkerVisibilityControl) => {
if (control.isProtected) {
list = list.concat(control.toggles);
}
return list;
}, [] as string[]);
if (toggles.length === 0)
return false;
return toggles.some((toggle: string) => {
// Specific coding for robots - extend later if needed
return (toggle === "dcs" && !unit.getControlled() && !unit.getHuman());
});
}
getMapMarkerVisibilityControls() {
return this.#mapMarkerVisibilityControls;
}
/* Event handlers */
#onClick(e: any) {
if (!this.#preventLeftClick) {
@ -560,19 +571,20 @@ export class Map extends L.Map {
}
}
else if (this.#state === MOVE_UNIT) {
if (!e.originalEvent.ctrlKey) {
getApp().getUnitsManager().clearDestinations();
if (!e.originalEvent.shiftKey) {
if (!e.originalEvent.ctrlKey) {
getApp().getUnitsManager().clearDestinations();
}
getApp().getUnitsManager().addDestination(this.#computeDestinationRotation && this.#destinationRotationCenter != null ? this.#destinationRotationCenter : e.latlng, this.#shiftKey, this.#destinationGroupRotation)
this.#destinationGroupRotation = 0;
this.#destinationRotationCenter = null;
this.#computeDestinationRotation = false;
}
getApp().getUnitsManager().addDestination(this.#computeDestinationRotation && this.#destinationRotationCenter != null ? this.#destinationRotationCenter : e.latlng, this.#shiftKey, this.#destinationGroupRotation)
this.#destinationGroupRotation = 0;
this.#destinationRotationCenter = null;
this.#computeDestinationRotation = false;
}
else {
this.setState(IDLE);
}
}
#onSelectionStart(e: any) {
@ -616,7 +628,7 @@ export class Map extends L.Map {
units.forEach((unit: Unit) => {
unit.appendContextActions(contextActionSet, null, e.latlng);
})
if (Object.keys(contextActionSet.getContextActions()).length > 0) {
getApp().getMap().showUnitContextMenu(e.originalEvent.x, e.originalEvent.y, e.latlng);
getApp().getMap().getUnitContextMenu().setContextActions(contextActionSet);
@ -626,6 +638,16 @@ export class Map extends L.Map {
}
#onMouseUp(e: any) {
if (this.#state === MOVE_UNIT && e.originalEvent.button == 2 && e.originalEvent.shiftKey) {
if (!e.originalEvent.ctrlKey) {
getApp().getUnitsManager().clearDestinations();
}
getApp().getUnitsManager().addDestination(this.#computeDestinationRotation && this.#destinationRotationCenter != null ? this.#destinationRotationCenter : e.latlng, this.#shiftKey, this.#destinationGroupRotation)
this.#destinationGroupRotation = 0;
this.#destinationRotationCenter = null;
this.#computeDestinationRotation = false;
}
}
#onMouseMove(e: any) {
@ -677,6 +699,7 @@ export class Map extends L.Map {
this.#isZooming = false;
}
/* */
#panToUnit(unit: Unit) {
var unitPosition = new L.LatLng(unit.getPosition().lat, unit.getPosition().lng);
this.setView(unitPosition, this.getZoom(), { animate: false });
@ -691,10 +714,10 @@ export class Map extends L.Map {
#createUnitMarkerControlButtons() {
const unitVisibilityControls = <HTMLElement>document.getElementById("unit-visibility-control");
const makeTitle = (isProtected:boolean) => {
return ( isProtected ) ? "Unit type is protected and will ignore orders" : "Unit is NOT protected and will respond to orders";
const makeTitle = (isProtected: boolean) => {
return (isProtected) ? "Unit type is protected and will ignore orders" : "Unit is NOT protected and will respond to orders";
}
this.getMapMarkerControls().forEach( (control:MapMarkerControl) => {
this.getMapMarkerVisibilityControls().forEach((control: MapMarkerVisibilityControl) => {
const toggles = `["${control.toggles.join('","')}"]`;
const div = document.createElement("div");
div.className = control.protectable === true ? "protectable" : "";
@ -707,7 +730,7 @@ export class Map extends L.Map {
`;
unitVisibilityControls.appendChild(div);
if ( control.protectable ) {
if (control.protectable) {
div.innerHTML += `
<button class="lock" ${control.isProtected ? "data-protected" : ""} title="${makeTitle(control.isProtected || false)}">
<img src="/resources/theme/images/buttons/other/lock-solid.svg" class="locked" />
@ -715,10 +738,10 @@ export class Map extends L.Map {
</button>`;
const btn = <HTMLButtonElement>div.querySelector("button.lock");
btn.addEventListener("click", (ev:MouseEventInit) => {
btn.addEventListener("click", (ev: MouseEventInit) => {
control.isProtected = !control.isProtected;
btn.toggleAttribute("data-protected", control.isProtected);
btn.title = makeTitle( control.isProtected );
btn.title = makeTitle(control.isProtected);
document.dispatchEvent(new CustomEvent("toggleMarkerProtection", {
detail: {
"_element": btn,
@ -732,28 +755,32 @@ export class Map extends L.Map {
unitVisibilityControls.querySelectorAll(`img[src$=".svg"]`).forEach(img => SVGInjector(img));
}
unitIsProtected(unit:Unit) {
const toggles = this.#mapMarkerControls.reduce((list, control:MapMarkerControl) => {
if (control.isProtected) {
list = list.concat(control.toggles);
}
return list;
}, [] as string[]);
if (toggles.length === 0)
return false;
return toggles.some((toggle:string) => {
// Specific coding for robots - extend later if needed
return (toggle === "dcs" && !unit.getControlled() && !unit.getHuman());
});
}
#deselectCoalitionAreas() {
#deselectSelectedCoalitionArea() {
this.getSelectedCoalitionArea()?.setSelected(false);
}
/* Cursors */
#updateCursor() {
/* If the ctrl key is being pressed or we are performing an area selection, show the default cursor */
if (this.#ctrlKey || this.#selecting) {
/* Hide all non default cursors */
this.#hideDestinationCursors();
this.#hideDrawingCursor();
this.#showDefaultCursor();
} else {
/* Hide all the unnecessary cursors depending on the active state */
if (this.#state !== IDLE) this.#hideDefaultCursor();
if (this.#state !== MOVE_UNIT) this.#hideDestinationCursors();
if (this.#state !== COALITIONAREA_DRAW_POLYGON) this.#hideDrawingCursor();
/* Show the active cursor depending on the active state */
if (this.#state === IDLE) this.#showDefaultCursor();
else if (this.#state === MOVE_UNIT) this.#showDestinationCursors();
else if (this.#state === COALITIONAREA_DRAW_POLYGON) this.#showDrawingCursor();
}
}
#showDefaultCursor() {
document.getElementById(this.#ID)?.classList.remove("hidden-cursor");
}
@ -766,48 +793,47 @@ export class Map extends L.Map {
const singleCursor = !this.#shiftKey;
const selectedUnitsCount = getApp().getUnitsManager().getSelectedUnits({ excludeHumans: true, onlyOnePerGroup: true }).length;
if (singleCursor) {
if ( this.#destinationPreviewCursors.length != 1) {
this.#hideDestinationCursors();
var marker = new DestinationPreviewMarker(this.getMouseCoordinates(), { interactive: false });
marker.addTo(this);
this.#destinationPreviewCursors = [marker];
}
this.#destinationPreviewHandleLine.removeFrom(this);
this.#destinationPreviewHandle.removeFrom(this);
this.#hideDestinationCursors();
}
else if (!singleCursor) {
while (this.#destinationPreviewCursors.length > selectedUnitsCount) {
this.removeLayer(this.#destinationPreviewCursors[0]);
this.#destinationPreviewCursors.splice(0, 1);
if (selectedUnitsCount > 1) {
while (this.#destinationPreviewCursors.length > selectedUnitsCount) {
this.removeLayer(this.#destinationPreviewCursors[0]);
this.#destinationPreviewCursors.splice(0, 1);
}
this.#destinationPreviewHandleLine.addTo(this);
this.#destinationPreviewHandle.addTo(this);
while (this.#destinationPreviewCursors.length < selectedUnitsCount) {
var cursor = new DestinationPreviewMarker(this.getMouseCoordinates(), { interactive: false });
cursor.addTo(this);
this.#destinationPreviewCursors.push(cursor);
}
this.#updateDestinationCursors();
}
this.#destinationPreviewHandleLine.addTo(this);
this.#destinationPreviewHandle.addTo(this);
while (this.#destinationPreviewCursors.length < selectedUnitsCount) {
var cursor = new DestinationPreviewMarker(this.getMouseCoordinates(), { interactive: false });
cursor.addTo(this);
this.#destinationPreviewCursors.push(cursor);
}
this.#updateDestinationCursors();
}
}
}
#updateDestinationCursors() {
const groupLatLng = this.#computeDestinationRotation && this.#destinationRotationCenter != null ? this.#destinationRotationCenter : this.getMouseCoordinates();
if (this.#destinationPreviewCursors.length == 1)
this.#destinationPreviewCursors[0].setLatLng(this.getMouseCoordinates());
else {
Object.values(getApp().getUnitsManager().computeGroupDestination(groupLatLng, this.#destinationGroupRotation)).forEach((latlng: L.LatLng, idx: number) => {
if (idx < this.#destinationPreviewCursors.length)
this.#destinationPreviewCursors[idx].setLatLng(this.#shiftKey ? latlng : this.getMouseCoordinates());
})
};
const selectedUnitsCount = getApp().getUnitsManager().getSelectedUnits({ excludeHumans: true, onlyOnePerGroup: true }).length;
if (selectedUnitsCount > 1) {
const groupLatLng = this.#computeDestinationRotation && this.#destinationRotationCenter != null ? this.#destinationRotationCenter : this.getMouseCoordinates();
if (this.#destinationPreviewCursors.length == 1)
this.#destinationPreviewCursors[0].setLatLng(this.getMouseCoordinates());
else {
Object.values(getApp().getUnitsManager().computeGroupDestination(groupLatLng, this.#destinationGroupRotation)).forEach((latlng: L.LatLng, idx: number) => {
if (idx < this.#destinationPreviewCursors.length)
this.#destinationPreviewCursors[idx].setLatLng(this.#shiftKey ? latlng : this.getMouseCoordinates());
})
};
this.#destinationPreviewHandleLine.setLatLngs([groupLatLng, this.getMouseCoordinates()]);
this.#destinationPreviewHandle.setLatLng(this.getMouseCoordinates());
this.#destinationPreviewHandleLine.setLatLngs([groupLatLng, this.getMouseCoordinates()]);
this.#destinationPreviewHandle.setLatLng(this.getMouseCoordinates());
} else {
this.#hideDestinationCursors();
}
}
#hideDestinationCursors() {
@ -838,34 +864,9 @@ export class Map extends L.Map {
this.#drawingCursor.removeFrom(this);
}
#updateCursor() {
/* If the ctrl key is being pressed or we are performing an area selection, show the default cursor */
if (this.#ctrlKey || this.#selecting) {
/* Hide all non default cursors */
this.#hideDestinationCursors();
this.#hideDrawingCursor();
this.#showDefaultCursor();
} else {
/* Hide all the unnecessary cursors depending on the active state */
if (this.#state !== IDLE) this.#hideDefaultCursor();
if (this.#state !== MOVE_UNIT) this.#hideDestinationCursors();
if (this.#state !== COALITIONAREA_DRAW_POLYGON) this.#hideDrawingCursor();
/* Show the active cursor depending on the active state */
if (this.#state === IDLE) this.#showDefaultCursor();
else if (this.#state === MOVE_UNIT) this.#showDestinationCursors();
else if (this.#state === COALITIONAREA_DRAW_POLYGON) this.#showDrawingCursor();
}
}
#setVisibilityOption(option: string, ev: any) {
this.#visibilityOptions[option] = ev.currentTarget.checked;
document.dispatchEvent(new CustomEvent("mapVisibilityOptionsChanged"));
}
getMapMarkerControls() {
return this.#mapMarkerControls;
document.dispatchEvent(new CustomEvent("mapOptionsChanged"));
}
}

View File

@ -2,16 +2,13 @@ import { SVGInjector } from "@tanem/svg-injector";
import { getApp } from "..";
import { Dropdown } from "../controls/dropdown";
import { Slider } from "../controls/slider";
import { aircraftDatabase } from "../unit/databases/aircraftdatabase";
import { Unit } from "../unit/unit";
import { Panel } from "./panel";
import { Switch } from "../controls/switch";
import { ROEDescriptions, ROEs, altitudeIncrements, emissionsCountermeasures, emissionsCountermeasuresDescriptions, maxAltitudeValues, maxSpeedValues, minAltitudeValues, minSpeedValues, reactionsToThreat, reactionsToThreatDescriptions, shotsIntensityDescriptions, shotsScatterDescriptions, speedIncrements } from "../constants/constants";
import { ftToM, knotsToMs, mToFt, msToKnots } from "../other/utils";
import { GeneralSettings, Radio, TACAN } from "../interfaces";
import { PrimaryToolbar } from "../toolbars/primarytoolbar";
import { ContextActionSet } from "../unit/contextactionset";
import { ContextAction } from "../unit/contextaction";
export class UnitControlPanel extends Panel {
#altitudeSlider: Slider;
@ -36,36 +33,36 @@ export class UnitControlPanel extends Panel {
*
* @param ID - the ID of the HTML element which will contain the context menu
*/
constructor(ID: string){
constructor(ID: string) {
super(ID);
/* Unit control sliders */
this.#altitudeSlider = new Slider("altitude-slider", 0, 100, "ft", (value: number) => { getApp().getUnitsManager().setAltitude(ftToM(value)); });
this.#altitudeTypeSwitch = new Switch("altitude-type-switch", (value: boolean) => { getApp().getUnitsManager().setAltitudeType(value? "ASL": "AGL"); });
this.#altitudeTypeSwitch = new Switch("altitude-type-switch", (value: boolean) => { getApp().getUnitsManager().setAltitudeType(value ? "ASL" : "AGL"); });
this.#speedSlider = new Slider("speed-slider", 0, 100, "kts", (value: number) => { getApp().getUnitsManager().setSpeed(knotsToMs(value)); });
this.#speedTypeSwitch = new Switch("speed-type-switch", (value: boolean) => { getApp().getUnitsManager().setSpeedType(value? "CAS": "GS"); });
this.#speedTypeSwitch = new Switch("speed-type-switch", (value: boolean) => { getApp().getUnitsManager().setSpeedType(value ? "CAS" : "GS"); });
/* Option buttons */
// Reversing the ROEs so that the least "aggressive" option is always on the left
this.#optionButtons["ROE"] = ROEs.slice(0).reverse().map((option: string, index: number) => {
return this.#createOptionButton(option, `roe/${option.toLowerCase()}.svg`, ROEDescriptions.slice(0).reverse()[index], () => { getApp().getUnitsManager().setROE(option); });
}).filter((button: HTMLButtonElement, index: number) => {return ROEs[index] !== "";});
}).filter((button: HTMLButtonElement, index: number) => { return ROEs[index] !== ""; });
this.#optionButtons["reactionToThreat"] = reactionsToThreat.map((option: string, index: number) => {
return this.#createOptionButton(option, `threat/${option.toLowerCase()}.svg`, reactionsToThreatDescriptions[index],() => { getApp().getUnitsManager().setReactionToThreat(option); });
return this.#createOptionButton(option, `threat/${option.toLowerCase()}.svg`, reactionsToThreatDescriptions[index], () => { getApp().getUnitsManager().setReactionToThreat(option); });
});
this.#optionButtons["emissionsCountermeasures"] = emissionsCountermeasures.map((option: string, index: number) => {
return this.#createOptionButton(option, `emissions/${option.toLowerCase()}.svg`, emissionsCountermeasuresDescriptions[index],() => { getApp().getUnitsManager().setEmissionsCountermeasures(option); });
return this.#createOptionButton(option, `emissions/${option.toLowerCase()}.svg`, emissionsCountermeasuresDescriptions[index], () => { getApp().getUnitsManager().setEmissionsCountermeasures(option); });
});
this.#optionButtons["shotsScatter"] = [1, 2, 3].map((option: number, index: number) => {
return this.#createOptionButton(option.toString(), `scatter/${option.toString().toLowerCase()}.svg`, shotsScatterDescriptions[index],() => { getApp().getUnitsManager().setShotsScatter(option); });
return this.#createOptionButton(option.toString(), `scatter/${option.toString().toLowerCase()}.svg`, shotsScatterDescriptions[index], () => { getApp().getUnitsManager().setShotsScatter(option); });
});
this.#optionButtons["shotsIntensity"] = [1, 2, 3].map((option: number, index: number) => {
return this.#createOptionButton(option.toString(), `intensity/${option.toString().toLowerCase()}.svg`, shotsIntensityDescriptions[index],() => { getApp().getUnitsManager().setShotsIntensity(option); });
return this.#createOptionButton(option.toString(), `intensity/${option.toString().toLowerCase()}.svg`, shotsIntensityDescriptions[index], () => { getApp().getUnitsManager().setShotsIntensity(option); });
});
this.getElement().querySelector("#roe-buttons-container")?.append(...this.#optionButtons["ROE"]);
@ -110,48 +107,50 @@ export class UnitControlPanel extends Panel {
/* Mouseover of (?) highlights activation buttons */
const operateAsQuestionMark = <HTMLElement>this.getElement().querySelector("#operate-as h4 img");
operateAsQuestionMark.addEventListener("mouseover", () => {
document.querySelectorAll(`#rapid-controls button.scenic-action`).forEach((btn:Element) => {
document.querySelectorAll(`#rapid-controls button.scenic-action`).forEach((btn: Element) => {
btn.classList.add(`pulse`);
});
});
operateAsQuestionMark.addEventListener("mouseout", () => {
document.querySelectorAll(`#rapid-controls button.scenic-action.pulse`).forEach((btn:Element) => {
document.querySelectorAll(`#rapid-controls button.scenic-action.pulse`).forEach((btn: Element) => {
btn.classList.remove(`pulse`);
});
});
/* Advanced settings dialog */
this.#advancedSettingsDialog = <HTMLElement> document.querySelector("#advanced-settings-dialog");
this.#advancedSettingsDialog = <HTMLElement>document.querySelector("#advanced-settings-dialog");
/* Advanced settings dropdowns */
this.#TACANXYDropdown = new Dropdown("TACAN-XY", () => {});
this.#TACANXYDropdown = new Dropdown("TACAN-XY", () => { });
this.#TACANXYDropdown.setOptions(["X", "Y"]);
this.#radioDecimalsDropdown = new Dropdown("radio-decimals", () => {});
this.#radioDecimalsDropdown = new Dropdown("radio-decimals", () => { });
this.#radioDecimalsDropdown.setOptions([".000", ".250", ".500", ".750"]);
this.#radioCallsignDropdown = new Dropdown("radio-callsign", () => {});
this.#radioCallsignDropdown = new Dropdown("radio-callsign", () => { });
this.#deleteDropdown = new Dropdown("delete-options", () => { });
/* Events and timer */
window.setInterval(() => {this.update();}, 25);
window.setInterval(() => { this.update(); }, 25);
document.addEventListener("unitsSelection", (e: CustomEvent<Unit[]>) => {
this.show();
document.addEventListener("unitsSelection", (e: CustomEvent<Unit[]>) => {
this.show();
this.addButtons();
this.#updateRapidControls();
this.#updateRapidControls();
});
document.addEventListener("clearSelection", () => {
document.addEventListener("clearSelection", () => {
this.hide();
this.#updateRapidControls();
this.#updateRapidControls();
});
document.addEventListener("applyAdvancedSettings", () => {this.#applyAdvancedSettings();})
document.addEventListener("applyAdvancedSettings", () => { this.#applyAdvancedSettings(); })
document.addEventListener("showAdvancedSettings", () => {
this.#updateAdvancedSettingsDialog(getApp().getUnitsManager().getSelectedUnits());
this.#advancedSettingsDialog.classList.remove("hide");
});
/* This is for when a ctrl-click happens on the map for deselection and we need to remove the selected unit from the panel */
document.addEventListener( "unitsDeselection", ( ev:CustomEventInit ) => {
this.getElement().querySelector( `button[data-unit-id="${ev.detail.ID}"]` )?.remove();
this.#updateRapidControls();
document.addEventListener("unitsDeselection", (ev: CustomEventInit) => {
this.show();
this.addButtons();
this.#updateRapidControls();
});
window.addEventListener("resize", (e: any) => this.#calculateMaxHeight());
@ -159,16 +158,16 @@ export class UnitControlPanel extends Panel {
const element = document.getElementById("toolbar-container");
if (element)
new ResizeObserver(() => this.#calculateTop()).observe(element);
this.#calculateMaxHeight()
this.hide();
}
show() {
const context = getApp().getCurrentContext();
if ( !context.getUseUnitControlPanel() )
if (!context.getUseUnitControlPanel())
return;
super.show();
this.#speedTypeSwitch.resetExpectedValue();
this.#altitudeTypeSwitch.resetExpectedValue();
@ -184,26 +183,26 @@ export class UnitControlPanel extends Panel {
addButtons() {
this.#units = getApp().getUnitsManager().getSelectedUnits();
this.#selectedUnitsTypes = getApp().getUnitsManager().getSelectedUnitsCategories();
if (this.#units.length < 20) {
this.getElement().querySelector("#selected-units-container")?.replaceChildren(...this.#units.map((unit: Unit, index: number) => {
var button = document.createElement("button");
var callsign = unit.getUnitName() || "";
var label = unit.getDatabase()?.getByName(unit.getName())?.label || unit.getName();
button.setAttribute("data-unit-id", "" + unit.ID );
button.setAttribute("data-unit-id", "" + unit.ID);
button.setAttribute("data-label", label);
button.setAttribute("data-callsign", callsign);
button.setAttribute("data-coalition", unit.getCoalition());
button.classList.add("pill", "highlight-coalition")
button.addEventListener("click", ( ev:MouseEventInit ) => {
button.addEventListener("click", (ev: MouseEventInit) => {
// Ctrl-click deselection
if ( ev.ctrlKey === true && ev.shiftKey === false && ev.altKey === false ) {
getApp().getUnitsManager().deselectUnit( unit.ID );
if (ev.ctrlKey === true && ev.shiftKey === false && ev.altKey === false) {
getApp().getUnitsManager().deselectUnit(unit.ID);
button.remove();
// Deselect all
// Deselect all
} else {
getApp().getUnitsManager().deselectAllUnits();
getApp().getUnitsManager().selectUnit(unit.ID, true);
@ -219,14 +218,14 @@ export class UnitControlPanel extends Panel {
}
update() {
if (this.getVisible()){
if (this.getVisible()) {
const element = this.getElement();
if (element != null && this.#units.length > 0) {
/* Toggle visibility of control elements */
var isTanker = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => {return unit.isTanker();});
var isAWACS = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => {return unit.isAWACS();});
var isActiveTanker = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => {return unit.getIsActiveTanker()});
var isActiveAWACAS = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => {return unit.getIsActiveAWACS()});
var isTanker = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => { return unit.isTanker(); });
var isAWACS = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => { return unit.isAWACS(); });
var isActiveTanker = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => { return unit.getIsActiveTanker() });
var isActiveAWACAS = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => { return unit.getIsActiveAWACS() });
element.toggleAttribute("data-show-categories-tooltip", this.#selectedUnitsTypes.length > 1);
element.toggleAttribute("data-show-speed-slider", this.#selectedUnitsTypes.length == 1);
@ -236,35 +235,35 @@ export class UnitControlPanel extends Panel {
element.toggleAttribute("data-show-emissions-countermeasures", (this.#selectedUnitsTypes.includes("Aircraft") || this.#selectedUnitsTypes.includes("Helicopter")) && !(this.#selectedUnitsTypes.includes("GroundUnit") || this.#selectedUnitsTypes.includes("NavyUnit")));
element.toggleAttribute("data-show-shots-scatter", this.#selectedUnitsTypes.includes("GroundUnit")); //TODO: more refined
element.toggleAttribute("data-show-shots-intensity", this.#selectedUnitsTypes.includes("GroundUnit")); //TODO: more refined
element.toggleAttribute("data-show-tanker-button", getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => {return unit.isTanker();}) === true);
element.toggleAttribute("data-show-AWACS-button", getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => {return unit.isAWACS();}) === true);
element.toggleAttribute("data-show-tanker-button", getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => { return unit.isTanker(); }) === true);
element.toggleAttribute("data-show-AWACS-button", getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => { return unit.isAWACS(); }) === true);
element.toggleAttribute("data-show-on-off", (this.#selectedUnitsTypes.includes("GroundUnit") || this.#selectedUnitsTypes.includes("NavyUnit")) && !(this.#selectedUnitsTypes.includes("Aircraft") || this.#selectedUnitsTypes.includes("Helicopter")));
element.toggleAttribute("data-show-follow-roads", (this.#selectedUnitsTypes.length == 1 && this.#selectedUnitsTypes.includes("GroundUnit")));
element.toggleAttribute("data-show-operate-as", getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => {return unit.getCoalition()}) === "neutral");
element.toggleAttribute("data-show-operate-as", getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => { return unit.getCoalition() }) === "neutral");
if (this.#units.length == 1) {
if (isAWACS)
if (isAWACS)
element.toggleAttribute("data-show-advanced-settings-button", isActiveAWACAS);
else if (isTanker)
else if (isTanker)
element.toggleAttribute("data-show-advanced-settings-button", isActiveTanker);
else
else
element.toggleAttribute("data-show-advanced-settings-button", true);
}
if (this.#selectedUnitsTypes.length == 1) {
/* Flight controls */
var desiredAltitude = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => {return unit.getDesiredAltitude()});
var desiredAltitudeType = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => {return unit.getDesiredAltitudeType()});
var desiredSpeed = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => {return unit.getDesiredSpeed()});
var desiredSpeedType = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => {return unit.getDesiredSpeedType()});
var isActiveTanker = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => {return unit.getIsActiveTanker()});
var isActiveAWACAS = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => {return unit.getIsActiveAWACS()});
var onOff = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => {return unit.getOnOff()});
var followRoads = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => {return unit.getFollowRoads()});
var operateAs = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => {return unit.getOperateAs()});
this.#altitudeTypeSwitch.setValue(desiredAltitudeType != undefined? desiredAltitudeType == "ASL": undefined, false);
this.#speedTypeSwitch.setValue(desiredSpeedType != undefined? desiredSpeedType == "CAS": undefined, false);
var desiredAltitude = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => { return unit.getDesiredAltitude() });
var desiredAltitudeType = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => { return unit.getDesiredAltitudeType() });
var desiredSpeed = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => { return unit.getDesiredSpeed() });
var desiredSpeedType = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => { return unit.getDesiredSpeedType() });
var isActiveTanker = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => { return unit.getIsActiveTanker() });
var isActiveAWACAS = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => { return unit.getIsActiveAWACS() });
var onOff = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => { return unit.getOnOff() });
var followRoads = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => { return unit.getFollowRoads() });
var operateAs = getApp().getUnitsManager().getSelectedUnitsVariable((unit: Unit) => { return unit.getOperateAs() });
this.#altitudeTypeSwitch.setValue(desiredAltitudeType != undefined ? desiredAltitudeType == "ASL" : undefined, false);
this.#speedTypeSwitch.setValue(desiredSpeedType != undefined ? desiredSpeedType == "CAS" : undefined, false);
this.#speedSlider.setMinMax(minSpeedValues[this.#selectedUnitsTypes[0]], maxSpeedValues[this.#selectedUnitsTypes[0]]);
this.#altitudeSlider.setMinMax(minAltitudeValues[this.#selectedUnitsTypes[0]], maxAltitudeValues[this.#selectedUnitsTypes[0]]);
@ -309,7 +308,7 @@ export class UnitControlPanel extends Panel {
this.#AWACSSwitch.setValue(isActiveAWACAS, false);
this.#onOffSwitch.setValue(onOff, false);
this.#followRoadsSwitch.setValue(followRoads, false);
this.#operateAsSwitch.setValue(operateAs? operateAs === "blue": undefined, false);
this.#operateAsSwitch.setValue(operateAs ? operateAs === "blue" : undefined, false);
}
}
}
@ -318,8 +317,8 @@ export class UnitControlPanel extends Panel {
var contextActionSet = new ContextActionSet();
var units = getApp().getUnitsManager().getSelectedUnits();
var showAltitudeChange = units.some((unit: Unit) => {return ["Aircraft", "Helicopter"].includes(unit.getCategory());});
this.getElement().querySelector("#climb")?.classList.toggle("hide", !showAltitudeChange);
var showAltitudeChange = units.some((unit: Unit) => { return ["Aircraft", "Helicopter"].includes(unit.getCategory()); });
this.getElement().querySelector("#climb")?.classList.toggle("hide", !showAltitudeChange);
this.getElement().querySelector("#descend")?.classList.toggle("hide", !showAltitudeChange);
units.forEach((unit: Unit) => {
@ -347,10 +346,8 @@ export class UnitControlPanel extends Panel {
}
}
#updateAdvancedSettingsDialog(units: Unit[])
{
if (units.length == 1)
{
#updateAdvancedSettingsDialog(units: Unit[]) {
if (units.length == 1) {
/* HTML Elements */
const unitNameEl = this.#advancedSettingsDialog.querySelector("#unit-name") as HTMLElement;
const prohibitJettisonCheckbox = this.#advancedSettingsDialog.querySelector("#prohibit-jettison-checkbox")?.querySelector("input") as HTMLInputElement;
@ -363,7 +360,7 @@ export class UnitControlPanel extends Panel {
const TACANCallsignInput = this.#advancedSettingsDialog.querySelector("#tacan-callsign")?.querySelector("input") as HTMLInputElement;
const radioMhzInput = this.#advancedSettingsDialog.querySelector("#radio-mhz")?.querySelector("input") as HTMLInputElement;
const radioCallsignNumberInput = this.#advancedSettingsDialog.querySelector("#radio-callsign-number")?.querySelector("input") as HTMLInputElement;
const unit = units[0];
const isTanker = unit.isTanker();
const isAWACS = unit.isAWACS();
@ -400,7 +397,7 @@ export class UnitControlPanel extends Panel {
radioMhzInput.value = String(radioMHz);
radioCallsignNumberInput.value = String(unit.getRadio().callsignNumber);
this.#radioDecimalsDropdown.setValue("." + radioDecimals);
if (isTanker) /* Set tanker specific options */
this.#radioCallsignDropdown.setOptions(["Texaco", "Arco", "Shell"]);
else if (isAWACS) /* Set AWACS specific options */
@ -414,8 +411,7 @@ export class UnitControlPanel extends Panel {
}
}
#applyAdvancedSettings()
{
#applyAdvancedSettings() {
/* HTML Elements */
const prohibitJettisonCheckbox = this.#advancedSettingsDialog.querySelector("#prohibit-jettison-checkbox")?.querySelector("input") as HTMLInputElement;
const prohibitAfterburnerCheckbox = this.#advancedSettingsDialog.querySelector("#prohibit-afterburner-checkbox")?.querySelector("input") as HTMLInputElement;
@ -431,7 +427,7 @@ export class UnitControlPanel extends Panel {
/* TACAN */
const TACAN: TACAN = {
isOn: TACANCheckbox.checked? true: false,
isOn: TACANCheckbox.checked ? true : false,
channel: Number(TACANChannelInput.value),
XY: this.#TACANXYDropdown.getValue(),
callsign: TACANCallsignInput.value as string
@ -443,18 +439,18 @@ export class UnitControlPanel extends Panel {
const radio: Radio = {
frequency: (radioMHz * 1000 + Number(radioDecimals.substring(1))) * 1000,
callsign: this.#radioCallsignDropdown.getIndex() + 1,
callsignNumber: Number(radioCallsignNumberInput.value)
callsignNumber: Number(radioCallsignNumberInput.value)
}
/* General settings */
const generalSettings: GeneralSettings = {
prohibitJettison: prohibitJettisonCheckbox.checked? true: false,
prohibitAfterburner: prohibitAfterburnerCheckbox.checked? true: false,
prohibitAA: prohibitAACheckbox.checked? true: false,
prohibitAG: prohibitAGCheckbox.checked? true: false,
prohibitAirWpn: prohibitAirWpnCheckbox.checked? true: false
prohibitJettison: prohibitJettisonCheckbox.checked ? true : false,
prohibitAfterburner: prohibitAfterburnerCheckbox.checked ? true : false,
prohibitAA: prohibitAACheckbox.checked ? true : false,
prohibitAG: prohibitAGCheckbox.checked ? true : false,
prohibitAirWpn: prohibitAirWpnCheckbox.checked ? true : false
}
/* Send command and close */
var units = getApp().getUnitsManager().getSelectedUnits();
// TODO: split setAdvancedOptions into setIsTanker, setIsAWACS, setAdvancedOptions

View File

@ -339,12 +339,14 @@ export class ServerManager {
this.PUT(data, callback);
}
// TODO: Remove coalition
scenicAAA(ID: number, coalition: string, callback: CallableFunction = () => {}) {
var command = { "ID": ID, "coalition": coalition }
var data = { "scenicAAA": command }
this.PUT(data, callback);
}
// TODO: Remove coalition
missOnPurpose(ID: number, coalition: string, callback: CallableFunction = () => {}) {
var command = { "ID": ID, "coalition": coalition }
var data = { "missOnPurpose": command }

View File

@ -190,15 +190,17 @@ export abstract class Unit extends CustomMarker {
/* Deselect units if they are hidden */
document.addEventListener("toggleCoalitionVisibility", (ev: CustomEventInit) => {
window.setTimeout(() => { this.setSelected(this.getSelected() && !this.getHidden()) }, 300);
this.#updateMarker();
this.setSelected(this.getSelected() && !this.getHidden());
});
document.addEventListener("toggleUnitVisibility", (ev: CustomEventInit) => {
window.setTimeout(() => { this.setSelected(this.getSelected() && !this.getHidden()) }, 300);
document.addEventListener("toggleMarkerVisibility", (ev: CustomEventInit) => {
this.#updateMarker();
this.setSelected(this.getSelected() && !this.getHidden());
});
/* Update the marker when the visibility options change */
document.addEventListener("mapVisibilityOptionsChanged", (ev: CustomEventInit) => {
/* Update the marker when the options change */
document.addEventListener("mapOptionsChanged", (ev: CustomEventInit) => {
this.#updateMarker();
/* Circles don't like to be updated when the map is zooming */
@ -323,7 +325,7 @@ export abstract class Unit extends CustomMarker {
}
/* If the unit is selected or if the view is centered on this unit, sent the update signal so that other elements like the UnitControlPanel can be updated. */
if (this.getSelected() || getApp().getMap().getCenterUnit() === this)
if (this.getSelected() || getApp().getMap().getCenteredOnUnit() === this)
document.dispatchEvent(new CustomEvent("unitUpdated", { detail: this }));
}
@ -415,7 +417,7 @@ export abstract class Unit extends CustomMarker {
else {
this.#clearContacts();
this.#clearPath();
this.#clearTarget();
this.#clearTargetPosition();
}
/* When the group leader is selected, if grouping is active, all the other group members are also selected */
@ -684,14 +686,11 @@ export abstract class Unit extends CustomMarker {
/* Hide the unit if it does not belong to the commanded coalition and it is not detected by a method that can pinpoint its location (RWR does not count) */
(!this.belongsToCommandedCoalition() && (this.#detectionMethods.length == 0 || (this.#detectionMethods.length == 1 && this.#detectionMethods[0] === RWR))) ||
/* Hide the unit if grouping is activated, the unit is not the group leader, it is not selected, and the zoom is higher than the grouping threshold */
(getApp().getMap().getVisibilityOptions()[HIDE_GROUP_MEMBERS] && !this.#isLeader && this.getCategory() == "GroundUnit" && getApp().getMap().getZoom() < GROUPING_ZOOM_TRANSITION &&
(getApp().getMap().getVisibilityOptions()[HIDE_GROUP_MEMBERS] && !this.#isLeader && !this.getSelected() && this.getCategory() == "GroundUnit" && getApp().getMap().getZoom() < GROUPING_ZOOM_TRANSITION &&
(this.belongsToCommandedCoalition() || (!this.belongsToCommandedCoalition() && this.#detectionMethods.length == 0))));
/* Force dead units to be hidden */
this.setHidden(hidden || !this.getAlive());
/* Force hidden units to be unselected */
this.setSelected(this.getSelected() && !this.getHidden());
}
setHidden(hidden: boolean) {
@ -775,7 +774,7 @@ export abstract class Unit extends CustomMarker {
return this.getDatabaseEntry()?.canAAA === true;
}
indirectFire() {
isIndirectFire() {
return this.getDatabaseEntry()?.indirectFire === true;
}
@ -932,6 +931,7 @@ export abstract class Unit extends CustomMarker {
});
}
// TODO: Remove coalition
scenicAAA() {
var coalition = "neutral";
if (this.getCoalition() === "red")
@ -941,6 +941,7 @@ export abstract class Unit extends CustomMarker {
getApp().getServerManager().scenicAAA(this.ID, coalition);
}
// TODO: Remove coalition
missOnPurpose() {
var coalition = "neutral";
if (this.getCoalition() === "red")
@ -1254,11 +1255,13 @@ export abstract class Unit extends CustomMarker {
}
#clearPath() {
for (let WP in this.#pathMarkers) {
getApp().getMap().removeLayer(this.#pathMarkers[WP]);
if (this.#pathPolyline.getLatLngs().length != 0) {
for (let WP in this.#pathMarkers) {
getApp().getMap().removeLayer(this.#pathMarkers[WP]);
}
this.#pathMarkers = [];
this.#pathPolyline.setLatLngs([]);
}
this.#pathMarkers = [];
this.#pathPolyline.setLatLngs([]);
}
#drawContacts() {
@ -1412,7 +1415,7 @@ export abstract class Unit extends CustomMarker {
}
}
else
this.#clearTarget();
this.#clearTargetPosition();
}
#drawTargetPosition(targetPosition: LatLng) {
@ -1424,7 +1427,7 @@ export abstract class Unit extends CustomMarker {
this.#targetPositionPolyline.setLatLngs([new LatLng(this.#position.lat, this.#position.lng), new LatLng(targetPosition.lat, targetPosition.lng)])
}
#clearTarget() {
#clearTargetPosition() {
if (getApp().getMap().hasLayer(this.#targetPositionMarker))
this.#targetPositionMarker.removeFrom(getApp().getMap());

View File

@ -6,7 +6,7 @@ import { CoalitionArea } from "../map/coalitionarea/coalitionarea";
import { groundUnitDatabase } from "./databases/groundunitdatabase";
import { DELETE_CYCLE_TIME, DELETE_SLOW_THRESHOLD, DataIndexes, GAME_MASTER, IADSDensities, IDLE, MOVE_UNIT } from "../constants/constants";
import { DataExtractor } from "../server/dataextractor";
import { citiesDatabase } from "./citiesDatabase";
import { citiesDatabase } from "./databases/citiesdatabase";
import { aircraftDatabase } from "./databases/aircraftdatabase";
import { helicopterDatabase } from "./databases/helicopterdatabase";
import { navyUnitDatabase } from "./databases/navyunitdatabase";
@ -321,11 +321,13 @@ export class UnitsManager {
getUnitsVariable(variableGetter: CallableFunction, units: Unit[]) {
if (units.length == 0)
return undefined;
return units.map((unit: Unit) => {
return variableGetter(unit);
})?.reduce((a: any, b: any) => {
return a === b ? a : undefined
var value: any = variableGetter(units[0]);
units.forEach((unit: Unit) => {
if (variableGetter(unit) !== value)
return undefined;
});
return value;
};
/** For a given unit, it returns if and how it is being detected by other units. NOTE: this function will return how a unit is being detected, i.e. how other units are detecting it. It will not return
@ -353,6 +355,7 @@ export class UnitsManager {
* @param latlng Position of the new destination
* @param mantainRelativePosition If true, the selected units will mantain their relative positions when reaching the target. This is useful to maintain a formation for groun/navy units
* @param rotation Rotation in radians by which the formation will be rigidly rotated. E.g. a ( V ) formation will look like this ( < ) if rotated pi/4 radians (90 degrees)
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
addDestination(latlng: L.LatLng, mantainRelativePosition: boolean, rotation: number, units: Unit[] | null = null) {
if (units === null)
@ -412,6 +415,7 @@ export class UnitsManager {
/** Instruct all the selected units to land at a specific location
*
* @param latlng Location where to land at
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
landAt(latlng: LatLng, units: Unit[] | null = null) {
if (units === null)
@ -428,6 +432,7 @@ export class UnitsManager {
/** Instruct all the selected units to change their speed
*
* @param speedChange Speed change, either "stop", "slow", or "fast". The specific value depends on the unit category
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
changeSpeed(speedChange: string, units: Unit[] | null = null) {
if (units === null)
@ -442,6 +447,7 @@ export class UnitsManager {
/** Instruct all the selected units to change their altitude
*
* @param altitudeChange Altitude change, either "climb" or "descend". The specific value depends on the unit category
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
changeAltitude(altitudeChange: string, units: Unit[] | null = null) {
if (units === null)
@ -456,6 +462,7 @@ export class UnitsManager {
/** Set a specific speed to all the selected units
*
* @param speed Value to set, in m/s
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
setSpeed(speed: number, units: Unit[] | null = null) {
if (units === null)
@ -471,6 +478,7 @@ export class UnitsManager {
/** Set a specific speed type to all the selected units
*
* @param speedType Value to set, either "CAS" or "GS". If "CAS" is selected, the unit will try to maintain the selected Calibrated Air Speed, but DCS will still only maintain a Ground Speed value so errors may arise depending on wind.
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
setSpeedType(speedType: string, units: Unit[] | null = null) {
if (units === null)
@ -486,6 +494,7 @@ export class UnitsManager {
/** Set a specific altitude to all the selected units
*
* @param altitude Value to set, in m
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
setAltitude(altitude: number, units: Unit[] | null = null) {
if (units === null)
@ -501,6 +510,7 @@ export class UnitsManager {
/** Set a specific altitude type to all the selected units
*
* @param altitudeType Value to set, either "ASL" or "AGL". If "AGL" is selected, the unit will try to maintain the selected Above Ground Level altitude. Due to a DCS bug, this will only be true at the final position.
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
setAltitudeType(altitudeType: string, units: Unit[] | null = null) {
if (units === null)
@ -516,6 +526,7 @@ export class UnitsManager {
/** Set a specific ROE to all the selected units
*
* @param ROE Value to set, see constants for acceptable values
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
setROE(ROE: string, units: Unit[] | null = null) {
if (units === null)
@ -531,6 +542,7 @@ export class UnitsManager {
/** Set a specific reaction to threat to all the selected units
*
* @param reactionToThreat Value to set, see constants for acceptable values
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
setReactionToThreat(reactionToThreat: string, units: Unit[] | null = null) {
if (units === null)
@ -546,6 +558,7 @@ export class UnitsManager {
/** Set a specific emissions & countermeasures to all the selected units
*
* @param emissionCountermeasure Value to set, see constants for acceptable values
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
setEmissionsCountermeasures(emissionCountermeasure: string, units: Unit[] | null = null) {
if (units === null)
@ -561,6 +574,7 @@ export class UnitsManager {
/** Turn selected units on or off, only works on ground and navy units
*
* @param onOff If true, the unit will be turned on
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
setOnOff(onOff: boolean, units: Unit[] | null = null) {
if (units === null)
@ -576,6 +590,7 @@ export class UnitsManager {
/** Instruct the selected units to follow roads, only works on ground units
*
* @param followRoads If true, units will follow roads
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
setFollowRoads(followRoads: boolean, units: Unit[] | null = null) {
if (units === null)
@ -591,6 +606,7 @@ export class UnitsManager {
/** Instruct selected units to operate as a certain coalition
*
* @param operateAsBool If true, units will operate as blue
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
setOperateAs(operateAsBool: boolean, units: Unit[] | null = null) {
var operateAs = operateAsBool ? "blue" : "red";
@ -607,6 +623,7 @@ export class UnitsManager {
/** Instruct units to attack a specific unit
*
* @param ID ID of the unit to attack
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
attackUnit(ID: number, units: Unit[] | null = null) {
if (units === null)
@ -620,7 +637,7 @@ export class UnitsManager {
}
/** Instruct units to refuel at the nearest tanker, if possible. Else units will RTB
*
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
refuel(units: Unit[] | null = null) {
if (units === null)
@ -638,6 +655,7 @@ export class UnitsManager {
* @param ID ID of the unit to follow
* @param offset Optional parameter, defines a static offset. X: front-rear, positive front, Y: top-bottom, positive top, Z: left-right, positive right
* @param formation Optional parameter, defines a predefined formation type. Values are: "trail", "echelon-lh", "echelon-rh", "line-abreast-lh", "line-abreast-rh", "front", "diamond"
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
followUnit(ID: number, offset?: { "x": number, "y": number, "z": number }, formation?: string, units: Unit[] | null = null) {
if (units === null)
@ -690,6 +708,7 @@ export class UnitsManager {
/** Instruct the selected units to perform precision bombing of specific coordinates
*
* @param latlng Location to bomb
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
bombPoint(latlng: LatLng, units: Unit[] | null = null) {
if (units === null)
@ -705,6 +724,7 @@ export class UnitsManager {
/** Instruct the selected units to perform carpet bombing of specific coordinates
*
* @param latlng Location to bomb
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
carpetBomb(latlng: LatLng, units: Unit[] | null = null) {
if (units === null)
@ -720,6 +740,7 @@ export class UnitsManager {
/** Instruct the selected units to fire at specific coordinates
*
* @param latlng Location to fire at
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
fireAtArea(latlng: LatLng, units: Unit[] | null = null) {
if (units === null)
@ -735,6 +756,7 @@ export class UnitsManager {
/** Instruct the selected units to simulate a fire fight at specific coordinates
*
* @param latlng Location to fire at
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
simulateFireFight(latlng: LatLng, units: Unit[] | null = null) {
if (units === null)
@ -756,7 +778,7 @@ export class UnitsManager {
}
/** Instruct units to enter into scenic AAA mode. Units will shoot in the air without aiming
*
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
scenicAAA(units: Unit[] | null = null) {
if (units === null)
@ -770,7 +792,7 @@ export class UnitsManager {
}
/** Instruct units to enter into miss on purpose mode. Units will aim to the nearest enemy unit but not precisely.
*
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
missOnPurpose(units: Unit[] | null = null) {
if (units === null)
@ -786,6 +808,7 @@ export class UnitsManager {
/** Instruct units to land at specific point
*
* @param latlng Point where to land
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
landAtPoint(latlng: LatLng, units: Unit[] | null = null) {
if (units === null)
@ -802,6 +825,7 @@ export class UnitsManager {
/** Set a specific shots scatter to all the selected units
*
* @param shotsScatter Value to set
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
setShotsScatter(shotsScatter: number, units: Unit[] | null = null) {
if (units === null)
@ -817,6 +841,7 @@ export class UnitsManager {
/** Set a specific shots intensity to all the selected units
*
* @param shotsScatter Value to set
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
setShotsIntensity(shotsIntensity: number, units: Unit[] | null = null) {
if (units === null)
@ -870,6 +895,7 @@ export class UnitsManager {
/** Set the hotgroup for the selected units. It will be the only hotgroup of the unit
*
* @param hotgroup Hotgroup number
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
setHotgroup(hotgroup: number, units: Unit[] | null = null) {
this.getUnitsByHotgroup(hotgroup).forEach((unit: Unit) => unit.setHotgroup(null));
@ -879,6 +905,7 @@ export class UnitsManager {
/** Add the selected units to a hotgroup. Units can be in multiple hotgroups at the same type
*
* @param hotgroup Hotgroup number
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
*/
addToHotgroup(hotgroup: number, units: Unit[] | null = null) {
if (units === null)
@ -891,6 +918,7 @@ export class UnitsManager {
/** Delete the selected units
*
* @param explosion If true, the unit will be deleted using an explosion
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
* @returns
*/
delete(explosion: boolean = false, explosionType: string = "", units: Unit[] | null = null) {
@ -929,6 +957,7 @@ export class UnitsManager {
*
* @param latlng Center of the group after the translation
* @param rotation Rotation of the group, in radians
* @param units (Optional) Array of units to apply the control to. If not provided, the operation will be completed on all selected units.
* @returns Array of positions for each unit, in order
*/
computeGroupDestination(latlng: LatLng, rotation: number, units: Unit[] | null = null) {
@ -1290,7 +1319,7 @@ export class UnitsManager {
const map = getApp().getMap();
const units = this.getSelectedUnits();
const numSelectedUnits = units.length;
const numProtectedUnits = units.filter((unit: Unit) => map.unitIsProtected(unit)).length;
const numProtectedUnits = units.filter((unit: Unit) => map.getIsUnitProtected(unit)).length;
if (numProtectedUnits === 1 && numSelectedUnits === numProtectedUnits)
(getApp().getPopupsManager().get("infoPopup") as Popup).setText(`Notice: unit is protected`);
@ -1300,6 +1329,6 @@ export class UnitsManager {
}
#unitIsProtected(unit: Unit) {
return getApp().getMap().unitIsProtected(unit)
return getApp().getMap().getIsUnitProtected(unit)
}
}

View File

@ -36,17 +36,9 @@ export class Weapon extends CustomMarker {
super(new LatLng(0, 0), { riseOnHover: true, keyboard: false });
this.ID = ID;
/* Deselect units if they are hidden */
document.addEventListener("toggleCoalitionVisibility", (ev: CustomEventInit) => {
window.setTimeout(() => { !this.getHidden() }, 300);
});
document.addEventListener("toggleUnitVisibility", (ev: CustomEventInit) => {
window.setTimeout(() => { !this.getHidden() }, 300);
});
document.addEventListener("mapVisibilityOptionsChanged", (ev: CustomEventInit) => {
/* Update the marker when the options change */
document.addEventListener("mapOptionsChanged", (ev: CustomEventInit) => {
this.#updateMarker();
});
}