package com.solution.rule.utils; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.solution.rule.domain.ultimately.dto.FireRuleInputRedSubComponentsDTO; import com.solution.rule.domain.ultimately.dto.FireRuleCoordinateDTO; import com.solution.rule.domain.ultimately.dto.FireRuleTrackPointDTO; import com.solution.rule.domain.ultimately.dto.FireRuleTaskInputDTO; import com.solution.rule.domain.ultimately.dto.FireRuleTaskWeaponDTO; import com.solution.rule.domain.ultimately.dto.FireRuleWeaponComponentDTO; import com.solution.rule.domain.ultimately.dto.FireRuleComponentParamDTO; import com.solution.rule.domain.ultimately.vo.FireRuleLauncherConfigurationVO; import com.solution.rule.domain.ultimately.vo.FireRuleExecuteBlockVO; import com.solution.rule.domain.ultimately.vo.FireRuleExecuteTargetItemVO; import com.solution.rule.domain.ultimately.vo.FireRuleMissionListItemVO; import com.solution.rule.domain.ultimately.vo.FireRuleMountedWeaponRefVO; import com.solution.rule.domain.ultimately.vo.FireRuleRedSubComponentsVO; import com.solution.rule.domain.ultimately.vo.FireRuleRedWeaponEquipmentVO; import com.solution.rule.domain.ultimately.vo.FireRuleRedPlatformSlotVO; import com.solution.rule.domain.ultimately.vo.FireRuleRedWeaponSlotVO; import com.solution.rule.domain.ultimately.vo.FireRuleSceneTaskNodeVO; import com.solution.rule.domain.ultimately.vo.FireRuleSceneTaskPayloadVO; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 将入参中的红方装备 {@code SubComponents}(DTO)转为输出 VO,保持与原始 JSON 结构一致。 */ public final class FireRuleRedWeaponOutputFillHelper { private static final ObjectMapper MAPPER = new ObjectMapper() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); private FireRuleRedWeaponOutputFillHelper() { } /** * DTO 与 VO 字段/JsonProperty 对齐,通过 Jackson 树转换实现原样输出。 */ public static FireRuleRedSubComponentsVO toOutputSubComponents(FireRuleInputRedSubComponentsDTO src) { if (src == null) { return null; } return MAPPER.convertValue(src, FireRuleRedSubComponentsVO.class); } /** * 将输出 redWeapons 单项映射为 Tasks 节点(一个装备 -> 一个任务节点)。 * *

字段映射约定:

* */ public static FireRuleSceneTaskNodeVO toTaskNode(FireRuleRedWeaponEquipmentVO redWeapon, int index) { FireRuleSceneTaskNodeVO node = new FireRuleSceneTaskNodeVO(); if (redWeapon == null) { node.setId("redWeaponTask_" + index); node.setDrawName("打击任务"); return node; } String name = nz(redWeapon.getName()); node.setName(name); node.setDrawName(name + "打击任务"); node.setId(buildNodeId(redWeapon, index)); node.setSide(redWeapon.getOwnerForceSide()); // 按你的要求写死 Tasks 节点的展示字段 node.setColor("rgb(220, 39, 39)"); node.setDataType("taskPlane"); node.setGroupType("tasks"); node.setShow(true); node.setIsSelected(false); node.setSort((long) index); FireRuleSceneTaskPayloadVO payload = new FireRuleSceneTaskPayloadVO(); payload.setName(name); payload.setWeaponId(redWeapon.getEquipmentId()); payload.setSideId(redWeapon.getOwnerForceSide()); payload.setMissionList(buildMissionList(redWeapon)); node.setTask(payload); return node; } /** * 批量转换:redWeapons 有几个就生成几个 Tasks。 */ public static List toTaskNodes(List redWeapons) { if (redWeapons == null || redWeapons.isEmpty()) { return Collections.emptyList(); } List list = new ArrayList<>(redWeapons.size()); for (int i = 0; i < redWeapons.size(); i++) { list.add(toTaskNode(redWeapons.get(i), i)); } return list; } /** * 阵位填充:写入每个 redWeapon 的 SubComponents.platform[].positions = [lon,lat,height]。 * 混合模式:蓝方武器坐标中心为锚点 + 航迹方位偏移 + 编队偏移 + 作战区约束。 */ @SuppressWarnings("rawtypes") public static void fillPlatformPositions(List redWeapons, FireRuleTaskInputDTO blueTask, Map params) { if (redWeapons == null || redWeapons.isEmpty() || blueTask == null) { return; } Coord anchor = computeBlueAnchor(blueTask); if (anchor == null) { return; } double bearingDeg = computeTrackBearingDeg(blueTask, str(params, "trackPointDirectionMode", "head2next"), readDouble(params, "fallbackBearingDeg", 0d)); double minKm = readDouble(params, "deployDistanceKmMin", 8d); double maxKm = readDouble(params, "deployDistanceKmMax", 30d); double defKm = readDouble(params, "deployDistanceKmDefault", 15d); String formation = str(params, "formationType", "line"); double spacingM = readDouble(params, "formationSpacingMeters", 300d); double headingOffset = readDouble(params, "formationHeadingOffsetDeg", 15d); double minInterM = readDouble(params, "minInterPlatformDistanceMeters", 80d); if (spacingM < minInterM) { spacingM = minInterM; } double defaultHeight = readDouble(params, "defaultDeployHeight", 30d); double followRatio = readDouble(params, "heightFollowBlueRatio", 0d); boolean clamp = Boolean.parseBoolean(String.valueOf(params.getOrDefault("enableWarZoneClamp", true))); List warZone = toWarZonePolygon(blueTask.getWarZoneLocation()); Map distanceByPlatform = parseDistanceByPlatformCsv(str(params, "distanceByPlatformCsv", "")); for (FireRuleRedWeaponEquipmentVO red : redWeapons) { if (red == null || red.getSubComponents() == null || red.getSubComponents().getPlatform() == null) { continue; } double distKm = resolveDeployDistanceKm(red, distanceByPlatform, defKm); distKm = clampDouble(distKm, minKm, maxKm); List platforms = red.getSubComponents().getPlatform(); for (int i = 0; i < platforms.size(); i++) { FireRuleRedPlatformSlotVO slot = platforms.get(i); if (slot == null) { continue; } double extraBearing = formationBearingOffsetDeg(formation, i, headingOffset); double extraMeters = formationOffsetMeters(formation, i, spacingM); Coord c = moveByMeters(anchor, distKm * 1000d + extraMeters, bearingDeg + extraBearing); if (clamp && warZone.size() >= 3 && !isPointInPolygon(c, warZone)) { c = projectInsidePolygon(c, anchor, warZone); } double h = defaultHeight; if (anchor.height != null) { h = defaultHeight + anchor.height * followRatio; } slot.setPositions(asPosition(c.lon, c.lat, h)); } } } /** * 目标分配:为每个红方 Tasks 节点写入 task.execute[0].targetList[*].targetId。\n * targetId 来源:当前蓝方任务 {@link FireRuleTaskInputDTO#getTaskWeapons()} 下每条武器的 equipmentId。\n * 允许多个红方装备指向同一个蓝方目标(不做去重占用)。\n * 参数来自 rule.drl buildParam:\n * - executeTypeDefault\n * - targetPickMode: roundRobin/random\n * - minTargetsPerRed / maxTargetsPerRedCap\n * - radToTargetsCsv\n * - rangeParseRegex / rangeUnit / minRangeToAllowAssignKm\n */ @SuppressWarnings({"rawtypes", "unchecked"}) public static void assignTargetsToTasks(List tasks, List redWeapons, FireRuleTaskInputDTO blueTask, Map params) { if (tasks == null || tasks.isEmpty() || blueTask == null) { return; } List candidates = extractBlueTargetEquipmentIds(blueTask, params); if (candidates.isEmpty()) { return; } String executeType = str(params, "executeTypeDefault", "assault"); String pickMode = str(params, "targetPickMode", "roundRobin"); for (int i = 0; i < tasks.size(); i++) { FireRuleSceneTaskNodeVO node = tasks.get(i); if (node == null) { continue; } if (node.getTask() == null) { node.setTask(new FireRuleSceneTaskPayloadVO()); } FireRuleSceneTaskPayloadVO payload = node.getTask(); Double redHitRate = resolveRedWeaponHitRate(payload.getWeaponId(), redWeapons); int targetsPerRed = resolveTargetsPerRed(redHitRate, params); FireRuleExecuteBlockVO block = new FireRuleExecuteBlockVO(); block.setType(executeType); List targetList = new ArrayList<>(); for (int k = 0; k < targetsPerRed; k++) { String blueEquipmentId = pickBlueTargetId(candidates, pickMode, i, k, node, blueTask); if (isBlank(blueEquipmentId)) { continue; } FireRuleExecuteTargetItemVO item = new FireRuleExecuteTargetItemVO(); item.setId(UUID.randomUUID().toString()); item.setTargetId(blueEquipmentId); // weaponId:可填红方装备的 equipmentId(若无则留空) item.setWeaponId(payload.getWeaponId()); targetList.add(item); } block.setTargetList(targetList.isEmpty() ? null : targetList); List execute = new ArrayList<>(); execute.add(block); payload.setExecute(execute); } } private static Double resolveRedWeaponHitRate(String weaponId, List redWeapons) { if (isBlank(weaponId) || redWeapons == null || redWeapons.isEmpty()) { return null; } for (FireRuleRedWeaponEquipmentVO w : redWeapons) { if (w != null && weaponId.equals(w.getEquipmentId())) { return w.getSuccessTargetRad(); } } return null; } private static String pickBlueTargetId(List candidates, String pickMode, int taskIndex, int innerIndex, FireRuleSceneTaskNodeVO node, FireRuleTaskInputDTO blueTask) { if (candidates == null || candidates.isEmpty()) { return null; } if ("random".equalsIgnoreCase(pickMode)) { // 伪随机但稳定:基于 redTask.id + blueTask.id + innerIndex 做 hash String seed = nz(node != null ? node.getId() : "") + "|" + nz(blueTask.getId()) + "|" + innerIndex; int h = Math.abs(seed.hashCode()); return candidates.get(h % candidates.size()); } // 默认 roundRobin:按 Tasks 序号与目标序号轮询 int idx = Math.abs(taskIndex + innerIndex) % candidates.size(); return candidates.get(idx); } private static int resolveTargetsPerRed(Double successTargetRad, Map params) { int min = readInt(params, "minTargetsPerRed", 1); int max = readInt(params, "maxTargetsPerRedCap", 3); if (max <= 0) { max = 1; } if (min < 0) { min = 0; } if (min > max) { min = max; } int byRad = parseRadToTargets(successTargetRad, str(params, "radToTargetsCsv", "")); int v = byRad > 0 ? byRad : min; if (v < min) { v = min; } if (v > max) { v = max; } return v; } private static int parseRadToTargets(Double rad, String csv) { if (rad == null || csv == null || csv.trim().isEmpty()) { return 0; } double r = rad.doubleValue(); // 允许无序输入:找所有 threshold<=r 的最大 threshold 对应的 targets double bestTh = -1; int bestTargets = 0; for (String part : csv.split(",")) { String p = part.trim(); if (p.isEmpty() || !p.contains(":")) { continue; } String[] kv = p.split(":"); if (kv.length != 2) { continue; } try { double th = Double.parseDouble(kv[0].trim()); int t = Integer.parseInt(kv[1].trim()); if (r >= th && th > bestTh) { bestTh = th; bestTargets = t; } } catch (Exception ignore) { } } return bestTargets; } private static List extractBlueTargetEquipmentIds(FireRuleTaskInputDTO blueTask, Map params) { List all = new ArrayList<>(); if (blueTask == null || blueTask.getTaskWeapons() == null) { return all; } // 射程过滤参数 String regex = str(params, "rangeParseRegex", "(\\d+(?:\\.\\d+)?)"); String unit = str(params, "rangeUnit", "km"); double minKm = readDouble(params, "minRangeToAllowAssignKm", 0d); Pattern pattern = safePattern(regex); for (FireRuleTaskWeaponDTO w : blueTask.getTaskWeapons()) { if (w == null || isBlank(w.getEquipmentId())) { continue; } Double km = tryParseRangeKm(w, pattern, unit); if (km != null && km.doubleValue() < minKm) { continue; } all.add(w.getEquipmentId()); } return all; } private static Double tryParseRangeKm(FireRuleTaskWeaponDTO w, Pattern pattern, String unit) { if (w == null || w.getComponents() == null || w.getComponents().isEmpty() || pattern == null) { return null; } for (FireRuleWeaponComponentDTO c : w.getComponents()) { if (c == null || c.getComponentParams() == null) { continue; } for (FireRuleComponentParamDTO p : c.getComponentParams()) { if (p == null) { continue; } Double km = parseNumberToKm(p.getAttDefaultValue(), pattern, unit); if (km != null) { return km; } km = parseNumberToKm(p.getAttExplain(), pattern, unit); if (km != null) { return km; } } } return null; } private static Double parseNumberToKm(String text, Pattern pattern, String unit) { if (text == null || text.trim().isEmpty() || pattern == null) { return null; } Matcher m = pattern.matcher(text); if (!m.find()) { return null; } try { double v = Double.parseDouble(m.group(1)); if ("m".equalsIgnoreCase(unit)) { return v / 1000.0d; } return v; } catch (Exception e) { return null; } } private static Pattern safePattern(String regex) { try { return Pattern.compile(regex); } catch (Exception e) { return null; } } private static double readDouble(Map params, String key, double def) { Object v = params != null ? params.get(key) : null; if (v == null) { return def; } if (v instanceof Number) { return ((Number) v).doubleValue(); } try { return Double.parseDouble(String.valueOf(v).trim()); } catch (Exception e) { return def; } } private static int readInt(Map params, String key, int def) { Object v = params != null ? params.get(key) : null; if (v == null) { return def; } if (v instanceof Number) { return ((Number) v).intValue(); } try { return Integer.parseInt(String.valueOf(v).trim()); } catch (Exception e) { return def; } } private static String str(Map params, String key, String def) { Object v = params != null ? params.get(key) : null; return v == null ? def : String.valueOf(v); } private static List buildMissionList(FireRuleRedWeaponEquipmentVO redWeapon) { if (redWeapon == null || redWeapon.getSubComponents() == null || redWeapon.getSubComponents().getWeapon() == null) { return null; } List result = new ArrayList<>(); for (FireRuleRedWeaponSlotVO slot : redWeapon.getSubComponents().getWeapon()) { if (slot == null) { continue; } FireRuleLauncherConfigurationVO cfg = slot.getConfiguration(); FireRuleMountedWeaponRefVO mounted = cfg != null ? cfg.getMountedWeapon() : null; FireRuleMissionListItemVO item = new FireRuleMissionListItemVO(); // label:优先挂载武器名,其次 deviceName String label = mounted != null ? mounted.getName() : null; if (isBlank(label)) { label = slot.getDeviceName(); } item.setLabel(label); item.setNumber(cfg != null ? cfg.getNumber() : null); item.setValue(mounted != null ? mounted.getName() : null); item.setLauncherType(extractLauncherType(slot.getTwiceModified())); result.add(item); } return result.isEmpty() ? null : result; } private static String extractLauncherType(Map twiceModified) { if (twiceModified == null || twiceModified.isEmpty()) { return null; } Object v = twiceModified.get("launcherType"); return v == null ? null : String.valueOf(v); } private static String buildNodeId(FireRuleRedWeaponEquipmentVO redWeapon, int index) { String id = nz(redWeapon.getEquipmentId()); if (!id.isEmpty()) { return id; } id = nz(redWeapon.getPlatId()); if (!id.isEmpty()) { return id; } return "redWeaponTask_" + index; } private static String nz(String s) { return s == null ? "" : s; } private static boolean isBlank(String s) { return s == null || s.trim().isEmpty(); } // ------------------ 阵位几何辅助 ------------------ private static class Coord { final double lon; final double lat; final Double height; Coord(double lon, double lat, Double height) { this.lon = lon; this.lat = lat; this.height = height; } } private static Coord computeBlueAnchor(FireRuleTaskInputDTO blueTask) { if (blueTask == null || blueTask.getTaskWeapons() == null || blueTask.getTaskWeapons().isEmpty()) { return null; } double sumLon = 0d, sumLat = 0d, sumH = 0d; int count = 0, hc = 0; for (FireRuleTaskWeaponDTO w : blueTask.getTaskWeapons()) { if (w == null || w.getCoordinate() == null || w.getCoordinate().getLongitude() == null || w.getCoordinate().getLatitude() == null) { continue; } sumLon += w.getCoordinate().getLongitude(); sumLat += w.getCoordinate().getLatitude(); count++; if (w.getCoordinate().getHeight() != null) { sumH += w.getCoordinate().getHeight(); hc++; } } if (count == 0) { return null; } return new Coord(sumLon / count, sumLat / count, hc > 0 ? sumH / hc : null); } private static double computeTrackBearingDeg(FireRuleTaskInputDTO blueTask, String mode, double fallbackDeg) { if (blueTask == null || blueTask.getTrackPoints() == null || blueTask.getTrackPoints().size() < 2) { return fallbackDeg; } FireRuleTrackPointDTO a; FireRuleTrackPointDTO b; if ("tail2prev".equalsIgnoreCase(mode)) { int n = blueTask.getTrackPoints().size(); a = blueTask.getTrackPoints().get(n - 2); b = blueTask.getTrackPoints().get(n - 1); } else { a = blueTask.getTrackPoints().get(0); b = blueTask.getTrackPoints().get(1); } if (a == null || b == null || a.getLongitude() == null || a.getLatitude() == null || b.getLongitude() == null || b.getLatitude() == null) { return fallbackDeg; } return bearingDeg(a.getLongitude(), a.getLatitude(), b.getLongitude(), b.getLatitude()); } private static List toWarZonePolygon(List warZone) { List list = new ArrayList<>(); if (warZone == null) { return list; } for (FireRuleCoordinateDTO c : warZone) { if (c != null && c.getLongitude() != null && c.getLatitude() != null) { list.add(new Coord(c.getLongitude(), c.getLatitude(), c.getHeight())); } } return list; } private static Map parseDistanceByPlatformCsv(String csv) { Map map = new HashMap<>(); if (isBlank(csv)) { return map; } for (String part : csv.split(",")) { String p = part.trim(); if (!p.contains(":")) { continue; } String[] kv = p.split(":"); if (kv.length != 2) { continue; } try { map.put(kv[0].trim(), Double.parseDouble(kv[1].trim())); } catch (Exception ignore) { } } return map; } private static double resolveDeployDistanceKm(FireRuleRedWeaponEquipmentVO red, Map byPlatform, double defKm) { String name = red != null ? nz(red.getName()) : ""; String platform = red != null ? nz(red.getPlatformType()) : ""; for (Map.Entry e : byPlatform.entrySet()) { String k = e.getKey(); if (!isBlank(k) && (name.contains(k) || platform.contains(k))) { return e.getValue(); } } return defKm; } private static double formationBearingOffsetDeg(String formation, int index, double headingOffset) { if ("line".equalsIgnoreCase(formation)) { return 90d; } if ("wedge".equalsIgnoreCase(formation)) { return (index % 2 == 0 ? 1 : -1) * headingOffset; } if ("circle".equalsIgnoreCase(formation)) { return index * 45d; } return 0d; } private static double formationOffsetMeters(String formation, int index, double spacingM) { if ("line".equalsIgnoreCase(formation)) { return (index - 0.5d) * spacingM; } if ("wedge".equalsIgnoreCase(formation)) { return (index + 1) * spacingM * 0.5d; } if ("circle".equalsIgnoreCase(formation)) { return spacingM; } return index * spacingM; } private static Coord moveByMeters(Coord anchor, double meters, double bearingDeg) { double R = 6378137.0d; double brng = Math.toRadians(bearingDeg); double lat1 = Math.toRadians(anchor.lat); double lon1 = Math.toRadians(anchor.lon); double dR = meters / R; double lat2 = Math.asin(Math.sin(lat1) * Math.cos(dR) + Math.cos(lat1) * Math.sin(dR) * Math.cos(brng)); double lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(dR) * Math.cos(lat1), Math.cos(dR) - Math.sin(lat1) * Math.sin(lat2)); return new Coord(Math.toDegrees(lon2), Math.toDegrees(lat2), anchor.height); } private static double bearingDeg(double lon1, double lat1, double lon2, double lat2) { double phi1 = Math.toRadians(lat1); double phi2 = Math.toRadians(lat2); double dLon = Math.toRadians(lon2 - lon1); double y = Math.sin(dLon) * Math.cos(phi2); double x = Math.cos(phi1) * Math.sin(phi2) - Math.sin(phi1) * Math.cos(phi2) * Math.cos(dLon); double brng = Math.toDegrees(Math.atan2(y, x)); return (brng + 360d) % 360d; } private static boolean isPointInPolygon(Coord p, List poly) { boolean inside = false; for (int i = 0, j = poly.size() - 1; i < poly.size(); j = i++) { double xi = poly.get(i).lon, yi = poly.get(i).lat; double xj = poly.get(j).lon, yj = poly.get(j).lat; boolean intersect = ((yi > p.lat) != (yj > p.lat)) && (p.lon < (xj - xi) * (p.lat - yi) / (yj - yi + 1e-12) + xi); if (intersect) { inside = !inside; } } return inside; } private static Coord projectInsidePolygon(Coord out, Coord anchor, List poly) { if (isPointInPolygon(out, poly)) { return out; } // 二分逼近:沿 anchor -> out 连线回退到多边形内部 Coord in = anchor; if (!isPointInPolygon(in, poly)) { // anchor 不在区内时,退化为原点不处理 return out; } Coord lo = in; Coord hi = out; for (int i = 0; i < 24; i++) { Coord mid = new Coord((lo.lon + hi.lon) / 2d, (lo.lat + hi.lat) / 2d, out.height); if (isPointInPolygon(mid, poly)) { lo = mid; } else { hi = mid; } } return lo; } private static List asPosition(double lon, double lat, double height) { List p = new ArrayList<>(3); p.add(lon); p.add(lat); p.add(height); return p; } private static double clampDouble(double v, double min, double max) { if (v < min) { return min; } if (v > max) { return max; } return v; } }