Files
auto-solution/auto-solution-rule/src/main/java/com/solution/rule/utils/FireRuleRedWeaponOutputFillHelper.java

1328 lines
52 KiB
Java
Raw Normal View History

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.FireRuleOutputVO;
import com.solution.rule.domain.ultimately.vo.FireRuleRouteTrackPointVO;
2026-04-11 13:46:02 +08:00
import com.solution.rule.domain.ultimately.vo.FireRuleSceneGroupNodeVO;
import com.solution.rule.domain.ultimately.vo.FireRuleSceneTaskNodeVO;
import com.solution.rule.domain.ultimately.vo.FireRuleSceneTaskPayloadVO;
import com.solution.rule.domain.ultimately.vo.FireRuleTrackParamVO;
import com.solution.rule.domain.ultimately.vo.FireRuleTrackRouteVO;
2026-04-11 13:46:02 +08:00
import com.solution.rule.domain.ultimately.vo.FireRuleWingmanDataVO;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
2026-04-11 13:46:02 +08:00
import java.util.HashSet;
import java.util.List;
2026-04-11 13:46:02 +08:00
import java.util.Locale;
import java.util.Map;
2026-04-11 13:46:02 +08:00
import java.util.Set;
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 节点(一个装备 -> 一个任务节点)。
*
* <p>字段映射约定:</p>
* <ul>
* <li>drawName = Name + \"打击任务\"</li>
* <li>side = OwnerForceSide(按你的要求直接复制)</li>
* <li>id 优先 EquipmentID,其次 PlatID,最后用 index 兜底</li>
* <li>task.payload.weaponId = EquipmentID</li>
* <li>task.payload.sideId = OwnerForceSide</li>
* <li>missionList:尽量从 SubComponents.weapon[*] 中提取 mountedWeapon/name/number/launcherType</li>
* </ul>
*/
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<FireRuleSceneTaskNodeVO> toTaskNodes(List<FireRuleRedWeaponEquipmentVO> redWeapons) {
if (redWeapons == null || redWeapons.isEmpty()) {
return Collections.emptyList();
}
List<FireRuleSceneTaskNodeVO> 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<FireRuleRedWeaponEquipmentVO> 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<Coord> warZone = toWarZonePolygon(blueTask.getWarZoneLocation());
Map<String, Double> 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<FireRuleRedPlatformSlotVO> 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));
}
}
}
/**
* 航迹规则:按蓝方 trackPoints 生成 {@link FireRuleTrackParamVO#routeMap} 条目(JSON 顶层 key=航迹 id),
* 并将同一 id 写入对应红方任务 {@code execute[0].targetList[*].moveRouteId}。多蓝方任务循环时 merge,不覆盖已有 id。
*/
@SuppressWarnings("rawtypes")
public static void fillTrackParamAndBindMoveRoute(FireRuleOutputVO out, FireRuleTaskInputDTO blueTask, Map params) {
if (out == null || blueTask == null || out.getTasks() == null || out.getTasks().isEmpty()) {
return;
}
ensureTrackParam(out);
List<FireRuleSceneTaskNodeVO> tasks = out.getTasks();
List<FireRuleRedWeaponEquipmentVO> reds = out.getRedWeapons();
if (reds == null) {
reds = Collections.emptyList();
}
List<Coord> warPoly = toWarZonePolygon(blueTask.getWarZoneLocation());
Coord blueAnchor = computeBlueAnchor(blueTask);
Coord clampAnchor = resolveClampAnchor(blueAnchor, warPoly);
boolean zoneClamp = Boolean.parseBoolean(String.valueOf(params.getOrDefault("enableTrackWarZoneClamp", true)));
String dirMode = str(params, "trackPointDirectionMode", "head2next");
double fallbackBrg = readDouble(params, "trackFallbackBearingDeg", readDouble(params, "fallbackBearingDeg", 0d));
double mainBearing = computeTrackBearingDeg(blueTask, dirMode, fallbackBrg);
String algo = str(params, "trackRouteAlgorithm", "followBlue");
String nameSuffix = str(params, "trackRouteNameSuffix", "航迹");
String groundType = str(params, "trackGroundTrackType", "routeLineGround");
String blueIdSeg = sanitizeRouteIdSegment(nz(blueTask.getId()));
for (int i = 0; i < tasks.size(); i++) {
FireRuleSceneTaskNodeVO node = tasks.get(i);
if (node == null) {
continue;
}
FireRuleRedWeaponEquipmentVO red = i < reds.size() ? reds.get(i) : null;
List<TrackNode> nodes = extractSortedBlueTrackNodes(blueTask);
if (nodes.isEmpty()) {
continue;
}
List<TrackNode> transformed = applyTrackRouteAlgorithm(nodes, algo, params, mainBearing, i);
int extraMax = readInt(params, "trackExtraNodesMax", 0);
if (extraMax > 0) {
transformed = injectExtraTrackNodes(transformed, extraMax);
}
if (zoneClamp && warPoly.size() >= 3) {
transformed = clampTrackNodesToWarZone(transformed, warPoly, clampAnchor);
}
boolean air = resolveAirTrack(blueTask, red, params);
String routeName = nz(node.getDrawName()) + nameSuffix;
String routeId = buildUniqueRouteId(out.getTrackParam().getRouteMap(), blueIdSeg, sanitizeRouteIdSegment(nz(node.getId())), i);
FireRuleTrackRouteVO route = buildTrackRouteVo(transformed, routeName, air, groundType);
out.getTrackParam().getRouteMap().put(routeId, route);
bindMoveRouteIdToFirstExecute(node, routeId);
}
}
2026-04-11 13:46:02 +08:00
/**
* 编组规则:按红方装备列表分组,写入 {@link FireRuleTrackParamVO#getGroups}(JSON 键 Groups),
* groupType=addGroup,drawName=领队装备名+后缀;僚机 wingmanData 中 name 为红方 equipmentId。
* 多蓝方任务循环时与航迹一致:在已有 Groups 上追加,且 group id 与已有项冲突时自动加后缀。
*/
@SuppressWarnings("rawtypes")
public static void fillTrackParamGroups(FireRuleOutputVO out, FireRuleTaskInputDTO blueTask, Map params) {
if (out == null || blueTask == null) {
return;
}
boolean enabled = Boolean.parseBoolean(String.valueOf(params.getOrDefault("groupRuleEnabled", true)));
if (!enabled) {
return;
}
List<FireRuleRedWeaponEquipmentVO> reds = out.getRedWeapons();
if (reds == null || reds.isEmpty()) {
return;
}
ensureTrackParam(out);
String dirMode = str(params, "trackPointDirectionMode", "head2next");
double fallbackBrg = readDouble(params, "trackFallbackBearingDeg", readDouble(params, "fallbackBearingDeg", 0d));
double mainBearing = computeTrackBearingDeg(blueTask, dirMode, fallbackBrg);
String mode = str(params, "groupFormationMode", "onePerRed");
int clusterSize = readInt(params, "groupClusterSize", 3);
if (clusterSize < 1) {
clusterSize = 1;
}
int minWing = readInt(params, "groupMinMembersForWingman", 2);
List<List<FireRuleRedWeaponEquipmentVO>> buckets = splitRedsIntoGroups(reds, mode, clusterSize);
List<FireRuleSceneGroupNodeVO> batch = new ArrayList<>();
String blueSeg = sanitizeRouteIdSegment(nz(blueTask.getId()));
int gidx = 0;
for (List<FireRuleRedWeaponEquipmentVO> bucket : buckets) {
if (bucket == null || bucket.isEmpty()) {
continue;
}
FireRuleRedWeaponEquipmentVO leader = pickGroupLeader(bucket, params);
if (leader == null) {
continue;
}
FireRuleSceneGroupNodeVO node = new FireRuleSceneGroupNodeVO();
String baseId = "group_" + blueSeg + "_" + gidx;
node.setId(ensureUniqueGroupId(out.getTrackParam(), baseId));
String suffix = str(params, "groupDrawNameSuffix", "编组");
boolean withIndex = Boolean.parseBoolean(String.valueOf(params.getOrDefault("groupDrawNameWithIndex", false)));
String drawName = nz(leader.getName()) + suffix;
if (withIndex) {
drawName += (gidx + 1);
}
node.setDrawName(drawName);
node.setGroupType("addGroup");
node.setName("addGroup");
node.setLeader(nz(leader.getEquipmentId()));
node.setSort(System.currentTimeMillis() + gidx);
node.setWingmanData(buildWingmanData(bucket, leader, mainBearing, params, minWing));
batch.add(node);
gidx++;
}
mergeGroupsIntoTrackParam(out.getTrackParam(), batch);
}
private static List<List<FireRuleRedWeaponEquipmentVO>> splitRedsIntoGroups(
List<FireRuleRedWeaponEquipmentVO> reds, String mode, int clusterSize) {
List<FireRuleRedWeaponEquipmentVO> clean = new ArrayList<>();
for (FireRuleRedWeaponEquipmentVO r : reds) {
if (r != null) {
clean.add(r);
}
}
List<List<FireRuleRedWeaponEquipmentVO>> out = new ArrayList<>();
if (clean.isEmpty()) {
return out;
}
if ("singleGroup".equalsIgnoreCase(mode)) {
out.add(clean);
return out;
}
if ("clusterByCount".equalsIgnoreCase(mode)) {
for (int i = 0; i < clean.size(); i += clusterSize) {
int end = Math.min(i + clusterSize, clean.size());
out.add(new ArrayList<>(clean.subList(i, end)));
}
return out;
}
for (FireRuleRedWeaponEquipmentVO r : clean) {
out.add(Collections.singletonList(r));
}
return out;
}
private static FireRuleRedWeaponEquipmentVO pickGroupLeader(List<FireRuleRedWeaponEquipmentVO> bucket, Map params) {
if (bucket == null || bucket.isEmpty()) {
return null;
}
String mode = str(params, "groupLeaderPickMode", "byHitRateThenId");
FireRuleRedWeaponEquipmentVO best = bucket.get(0);
for (int i = 1; i < bucket.size(); i++) {
FireRuleRedWeaponEquipmentVO cur = bucket.get(i);
if ("byId".equalsIgnoreCase(mode)) {
if (compareEquipmentId(cur, best) < 0) {
best = cur;
}
} else {
if (isBetterLeaderByHitRateThenId(cur, best)) {
best = cur;
}
}
}
return best;
}
private static boolean isBetterLeaderByHitRateThenId(FireRuleRedWeaponEquipmentVO cand, FireRuleRedWeaponEquipmentVO inc) {
double rc = leaderRad(cand);
double ri = leaderRad(inc);
int c = Double.compare(rc, ri);
if (c > 0) {
return true;
}
if (c < 0) {
return false;
}
return compareEquipmentId(cand, inc) < 0;
}
private static double leaderRad(FireRuleRedWeaponEquipmentVO w) {
if (w == null || w.getSuccessTargetRad() == null) {
return -1d;
}
return w.getSuccessTargetRad().doubleValue();
}
private static int compareEquipmentId(FireRuleRedWeaponEquipmentVO a, FireRuleRedWeaponEquipmentVO b) {
String sa = a != null ? nz(a.getEquipmentId()) : "";
String sb = b != null ? nz(b.getEquipmentId()) : "";
return sa.compareTo(sb);
}
private static List<FireRuleWingmanDataVO> buildWingmanData(
List<FireRuleRedWeaponEquipmentVO> bucket,
FireRuleRedWeaponEquipmentVO leader,
double mainBearing,
Map params,
int minMembersForWingman) {
if (bucket == null || leader == null || bucket.size() < minMembersForWingman) {
return Collections.emptyList();
}
double distBase = readDouble(params, "wingmanDistanceBaseMeters", 100);
double distStep = readDouble(params, "wingmanDistanceStepMeters", 50);
double angBase = readDouble(params, "wingmanAngleBaseDeg", 50);
double angStep = readDouble(params, "wingmanAngleStepDeg", 15);
double altBase = readDouble(params, "wingmanAltBaseMeters", 40);
double altScale = readDouble(params, "wingmanAltScale", 1.0);
List<FireRuleWingmanDataVO> list = new ArrayList<>();
int wmIdx = 0;
for (FireRuleRedWeaponEquipmentVO r : bucket) {
if (r == null || r == leader) {
continue;
}
FireRuleWingmanDataVO w = new FireRuleWingmanDataVO();
w.setKey(wmIdx);
w.setName(nz(r.getEquipmentId()));
w.setDistance((int) Math.round(distBase + wmIdx * distStep));
double deg = normDeg(mainBearing + angBase + wmIdx * angStep);
w.setAngle(String.format(Locale.US, "%.1f", deg));
Double lh = extractFirstPlatformHeight(leader);
Double wh = extractFirstPlatformHeight(r);
double delta = 0d;
if (lh != null && wh != null) {
delta = wh - lh;
}
w.setAlt((int) Math.round(altBase + altScale * delta));
list.add(w);
wmIdx++;
}
return list;
}
private static Double extractFirstPlatformHeight(FireRuleRedWeaponEquipmentVO red) {
if (red == null || red.getSubComponents() == null || red.getSubComponents().getPlatform() == null) {
return null;
}
for (FireRuleRedPlatformSlotVO pl : red.getSubComponents().getPlatform()) {
if (pl == null || pl.getPositions() == null || pl.getPositions().size() < 3) {
continue;
}
return pl.getPositions().get(2);
}
return null;
}
private static double normDeg(double deg) {
double a = deg % 360d;
if (a < 0) {
a += 360d;
}
return a;
}
private static String ensureUniqueGroupId(FireRuleTrackParamVO tp, String baseId) {
Set<String> seen = new HashSet<>();
if (tp.getGroups() != null) {
for (FireRuleSceneGroupNodeVO g : tp.getGroups()) {
if (g != null && !isBlank(g.getId())) {
seen.add(g.getId());
}
}
}
if (!seen.contains(baseId)) {
return baseId;
}
int k = 1;
while (seen.contains(baseId + "_" + k)) {
k++;
}
return baseId + "_" + k;
}
private static void mergeGroupsIntoTrackParam(FireRuleTrackParamVO tp, List<FireRuleSceneGroupNodeVO> batch) {
if (tp == null || batch == null || batch.isEmpty()) {
return;
}
List<FireRuleSceneGroupNodeVO> cur = tp.getGroups();
if (cur == null) {
cur = new ArrayList<>();
} else {
cur = new ArrayList<>(cur);
}
cur.addAll(batch);
tp.setGroups(cur);
}
private static void ensureTrackParam(FireRuleOutputVO out) {
if (out.getTrackParam() == null) {
out.setTrackParam(new FireRuleTrackParamVO());
}
}
private static String buildUniqueRouteId(Map<String, FireRuleTrackRouteVO> existing, String blueSeg, String nodeSeg, int index) {
String base = "route_" + blueSeg + "_" + nodeSeg + "_" + index;
if (existing == null || !existing.containsKey(base)) {
return base;
}
int k = 1;
while (existing.containsKey(base + "_" + k)) {
k++;
}
return base + "_" + k;
}
private static void bindMoveRouteIdToFirstExecute(FireRuleSceneTaskNodeVO node, String routeId) {
if (node == null || isBlank(routeId)) {
return;
}
FireRuleSceneTaskPayloadVO payload = node.getTask();
if (payload == null || payload.getExecute() == null || payload.getExecute().isEmpty()) {
return;
}
FireRuleExecuteBlockVO block = payload.getExecute().get(0);
if (block == null || block.getTargetList() == null) {
return;
}
for (FireRuleExecuteTargetItemVO item : block.getTargetList()) {
if (item != null) {
item.setMoveRouteId(routeId);
}
}
}
private static FireRuleTrackRouteVO buildTrackRouteVo(List<TrackNode> nodes, String name, boolean air, String groundType) {
FireRuleTrackRouteVO vo = new FireRuleTrackRouteVO();
vo.setName(name);
vo.setStartTime(null);
vo.setEndTime(null);
vo.setTrackType(air ? "routeLineAir" : groundType);
vo.setHeightType("msl");
vo.setSeaType("seaLevel");
List<FireRuleRouteTrackPointVO> pts = new ArrayList<>(nodes.size());
for (int j = 0; j < nodes.size(); j++) {
TrackNode tn = nodes.get(j);
FireRuleRouteTrackPointVO p = new FireRuleRouteTrackPointVO();
p.setIndex(String.valueOf(j + 1));
p.setLongitude(formatCoordNumber(tn.coord.lon));
p.setLatitude(formatCoordNumber(tn.coord.lat));
p.setHeight(tn.coord.height != null ? formatCoordNumber(tn.coord.height) : "0");
p.setSpeed(tn.speed != null ? formatCoordNumber(tn.speed) : null);
pts.add(p);
}
vo.setTrackPoints(pts);
vo.setPointCount(pts.size());
return vo;
}
private static String formatCoordNumber(double v) {
return String.valueOf(v);
}
private static boolean resolveAirTrack(FireRuleTaskInputDTO blue, FireRuleRedWeaponEquipmentVO red, Map params) {
String dt = blue != null ? nz(blue.getDataType()) : "";
if (csvContainsAny(str(params, "trackAirDataTypeCsv", ""), dt, false)) {
return true;
}
String blob = nz(blue != null ? blue.getDrawName() : "");
if (red != null) {
blob += " " + nz(red.getName()) + " " + nz(red.getPlatformType());
}
return csvContainsAny(str(params, "trackAirKeywordsCsv", ""), blob, false);
}
private static boolean csvContainsAny(String csv, String text, boolean tokenAsEquals) {
if (isBlank(csv) || text == null) {
return false;
}
String t = text.toLowerCase();
for (String part : csv.split(",")) {
String k = part.trim();
if (k.isEmpty()) {
continue;
}
if (tokenAsEquals) {
if (t.equalsIgnoreCase(k)) {
return true;
}
} else if (text.contains(k) || t.contains(k.toLowerCase())) {
return true;
}
}
return false;
}
private static String sanitizeRouteIdSegment(String raw) {
if (raw == null || raw.isEmpty()) {
return "x";
}
String s = raw.replaceAll("[^a-zA-Z0-9_-]", "_");
return s.isEmpty() ? "x" : s;
}
private static class TrackNode {
Coord coord;
Double speed;
TrackNode(Coord coord, Double speed) {
this.coord = coord;
this.speed = speed;
}
}
private static List<TrackNode> extractSortedBlueTrackNodes(FireRuleTaskInputDTO blueTask) {
List<TrackNode> list = new ArrayList<>();
if (blueTask == null || blueTask.getTrackPoints() == null) {
return list;
}
List<FireRuleTrackPointDTO> pts = new ArrayList<>(blueTask.getTrackPoints());
pts.sort((a, b) -> {
int ia = a != null && a.getIndex() != null ? a.getIndex() : 0;
int ib = b != null && b.getIndex() != null ? b.getIndex() : 0;
return Integer.compare(ia, ib);
});
for (FireRuleTrackPointDTO p : pts) {
if (p == null || p.getLongitude() == null || p.getLatitude() == null) {
continue;
}
list.add(new TrackNode(new Coord(p.getLongitude(), p.getLatitude(), p.getHeight()), p.getSpeed()));
}
return list;
}
private static List<TrackNode> applyTrackRouteAlgorithm(List<TrackNode> nodes, String algo, Map params, double mainBearing, int taskIndex) {
if (nodes == null || nodes.isEmpty()) {
return nodes;
}
String a = algo == null ? "followBlue" : algo.trim();
if ("shortestPath".equalsIgnoreCase(a)) {
return applyShortestPath(nodes, params);
}
if ("flank".equalsIgnoreCase(a)) {
return applyFlank(nodes, params, taskIndex);
}
if ("jam".equalsIgnoreCase(a)) {
return applyJam(nodes, params, mainBearing);
}
return copyTrackNodes(nodes);
}
private static List<TrackNode> copyTrackNodes(List<TrackNode> nodes) {
List<TrackNode> out = new ArrayList<>(nodes.size());
for (TrackNode n : nodes) {
out.add(new TrackNode(new Coord(n.coord.lon, n.coord.lat, n.coord.height), n.speed));
}
return out;
}
private static List<TrackNode> applyShortestPath(List<TrackNode> nodes, Map params) {
int segN = readInt(params, "trackShortPathSegments", 3);
if (segN < 1) {
segN = 1;
}
List<TrackNode> out = new ArrayList<>();
for (int i = 0; i < nodes.size(); i++) {
if (i == 0) {
out.add(copyNode(nodes.get(i)));
continue;
}
Coord a = nodes.get(i - 1).coord;
Coord b = nodes.get(i).coord;
Double spPrev = nodes.get(i - 1).speed;
Double spNext = nodes.get(i).speed;
for (int s = 1; s < segN; s++) {
double t = (double) s / (double) segN;
double lon = a.lon + (b.lon - a.lon) * t;
double lat = a.lat + (b.lat - a.lat) * t;
Double h = null;
if (a.height != null && b.height != null) {
h = a.height + (b.height - a.height) * t;
} else if (b.height != null) {
h = b.height;
} else {
h = a.height;
}
Double spd = null;
if (spPrev != null && spNext != null) {
spd = spPrev + (spNext - spPrev) * t;
} else if (spNext != null) {
spd = spNext;
} else {
spd = spPrev;
}
out.add(new TrackNode(new Coord(lon, lat, h), spd));
}
out.add(copyNode(nodes.get(i)));
}
return out;
}
private static TrackNode copyNode(TrackNode n) {
return new TrackNode(new Coord(n.coord.lon, n.coord.lat, n.coord.height), n.speed);
}
private static List<TrackNode> applyFlank(List<TrackNode> nodes, Map params, int taskIndex) {
double offsetM = readDouble(params, "trackFlankOffsetMeters", 800d);
String sideMode = str(params, "trackFlankSideMode", "alternate");
List<TrackNode> out = new ArrayList<>(nodes.size());
for (int i = 0; i < nodes.size(); i++) {
Coord c = nodes.get(i).coord;
double brg;
if (i < nodes.size() - 1) {
Coord nxt = nodes.get(i + 1).coord;
brg = bearingDeg(c.lon, c.lat, nxt.lon, nxt.lat);
} else if (i > 0) {
Coord prev = nodes.get(i - 1).coord;
brg = bearingDeg(prev.lon, prev.lat, c.lon, c.lat);
} else {
brg = 0d;
}
int sign = flankSign(sideMode, i, taskIndex);
Coord moved = moveByMeters(c, sign * offsetM, brg + 90d);
out.add(new TrackNode(moved, nodes.get(i).speed));
}
return out;
}
private static int flankSign(String mode, int pointIndex, int taskIndex) {
if ("left".equalsIgnoreCase(mode)) {
return 1;
}
if ("right".equalsIgnoreCase(mode)) {
return -1;
}
return (pointIndex + taskIndex) % 2 == 0 ? 1 : -1;
}
private static List<TrackNode> applyJam(List<TrackNode> nodes, Map params, double mainBearing) {
double wobble = readDouble(params, "trackJamWobbleMeters", 400d);
double periods = readDouble(params, "trackJamSegments", 4d);
if (periods < 0.5d) {
periods = 0.5d;
}
int n = nodes.size();
List<TrackNode> out = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
double frac = n <= 1 ? 0d : (double) i / (double) (n - 1);
double lateral = wobble * Math.sin(2d * Math.PI * periods * frac);
Coord c = moveByMeters(nodes.get(i).coord, lateral, mainBearing + 90d);
out.add(new TrackNode(c, nodes.get(i).speed));
}
return out;
}
private static List<TrackNode> injectExtraTrackNodes(List<TrackNode> nodes, int extraMax) {
if (nodes == null || nodes.size() < 2 || extraMax <= 0) {
return nodes;
}
int segs = nodes.size() - 1;
List<Integer> perSeg = new ArrayList<>(Collections.nCopies(segs, 0));
int base = extraMax / segs;
int rem = extraMax % segs;
for (int s = 0; s < segs; s++) {
perSeg.set(s, base + (s < rem ? 1 : 0));
}
List<TrackNode> out = new ArrayList<>();
for (int i = 0; i < nodes.size(); i++) {
out.add(copyNode(nodes.get(i)));
if (i >= nodes.size() - 1) {
break;
}
int ins = perSeg.get(i);
Coord a = nodes.get(i).coord;
Coord b = nodes.get(i + 1).coord;
Double sa = nodes.get(i).speed;
Double sb = nodes.get(i + 1).speed;
for (int k = 1; k <= ins; k++) {
double t = (double) k / (double) (ins + 1);
double lon = a.lon + (b.lon - a.lon) * t;
double lat = a.lat + (b.lat - a.lat) * t;
Double h = null;
if (a.height != null && b.height != null) {
h = a.height + (b.height - a.height) * t;
} else if (b.height != null) {
h = b.height;
} else {
h = a.height;
}
Double spd = null;
if (sa != null && sb != null) {
spd = sa + (sb - sa) * t;
} else if (sb != null) {
spd = sb;
} else {
spd = sa;
}
out.add(new TrackNode(new Coord(lon, lat, h), spd));
}
}
return out;
}
private static List<TrackNode> clampTrackNodesToWarZone(List<TrackNode> nodes, List<Coord> poly, Coord anchor) {
List<TrackNode> out = new ArrayList<>(nodes.size());
for (TrackNode n : nodes) {
Coord c = n.coord;
if (!isPointInPolygon(c, poly)) {
c = projectInsidePolygon(c, anchor, poly);
}
out.add(new TrackNode(c, n.speed));
}
return out;
}
private static Coord resolveClampAnchor(Coord blueAnchor, List<Coord> poly) {
if (poly.size() >= 3) {
if (blueAnchor != null && isPointInPolygon(blueAnchor, poly)) {
return blueAnchor;
}
return polygonCentroid(poly);
}
return blueAnchor != null ? blueAnchor : new Coord(0d, 0d, null);
}
private static Coord polygonCentroid(List<Coord> poly) {
double sx = 0, sy = 0;
for (Coord c : poly) {
sx += c.lon;
sy += c.lat;
}
int n = poly.size();
return new Coord(sx / n, sy / n, null);
}
/**
* 目标分配:为每个红方 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<FireRuleSceneTaskNodeVO> tasks,
List<FireRuleRedWeaponEquipmentVO> redWeapons,
FireRuleTaskInputDTO blueTask,
Map params) {
if (tasks == null || tasks.isEmpty() || blueTask == null) {
return;
}
List<String> 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<FireRuleExecuteTargetItemVO> 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<FireRuleExecuteBlockVO> execute = new ArrayList<>();
execute.add(block);
payload.setExecute(execute);
}
}
private static Double resolveRedWeaponHitRate(String weaponId, List<FireRuleRedWeaponEquipmentVO> 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<String> 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<String> extractBlueTargetEquipmentIds(FireRuleTaskInputDTO blueTask, Map params) {
List<String> 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<FireRuleMissionListItemVO> buildMissionList(FireRuleRedWeaponEquipmentVO redWeapon) {
if (redWeapon == null || redWeapon.getSubComponents() == null || redWeapon.getSubComponents().getWeapon() == null) {
return null;
}
List<FireRuleMissionListItemVO> 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<String, Object> 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<Coord> toWarZonePolygon(List<FireRuleCoordinateDTO> warZone) {
List<Coord> 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<String, Double> parseDistanceByPlatformCsv(String csv) {
Map<String, Double> 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<String, Double> byPlatform, double defKm) {
String name = red != null ? nz(red.getName()) : "";
String platform = red != null ? nz(red.getPlatformType()) : "";
for (Map.Entry<String, Double> 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<Coord> 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<Coord> 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<Double> asPosition(double lon, double lat, double height) {
List<Double> 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;
}
}