/// 参数化草图数据模型:点(自由度载体)、几何(直线 / 圆 / 弧)、 /// 几何约束与驱动尺寸;配合 `sketch_solver.dart` 的求解器实现参数化。 /// /// 设计要点: /// - 点是共享的:端点重合通过「引用同一个点」表达(天然重合,无需约束); /// - 尺寸是驱动量(driving dimension):改数值即驱动几何重新求解; /// - 全部可 JSON 往返,随架构图文档(`*.arch.json`)保存; /// - 命名沿用 CAD 习惯:P 点 / E 实体 / K 约束 / D 尺寸。 library; import 'dart:convert'; import 'dart:math' as math; import 'dart:ui' show Offset, Rect; // ===================== 基础模型 ===================== /// 草图点(求解变量 x / y;[fixed] 的点是锚点,不参与求解)。 class SketchPoint { /// 构造点。 const SketchPoint({ required this.id, required this.x, required this.y, this.fixed = false, }); /// 点 id(P 开头)。 final String id; /// 世界坐标 x。 final double x; /// 世界坐标 y。 final double y; /// 是否固定(锚点)。 final bool fixed; /// 位置。 Offset get pos => Offset(x, y); /// 复制并覆盖字段。 SketchPoint copyWith({double? x, double? y, bool? fixed}) => SketchPoint( id: id, x: x ?? this.x, y: y ?? this.y, fixed: fixed ?? this.fixed, ); /// 序列化。 Map toJson() => {'id': id, 'x': x, 'y': y, 'fixed': fixed}; /// 反序列化。 static SketchPoint fromJson(Map j) => SketchPoint( id: j['id'] as String? ?? '', x: (j['x'] as num?)?.toDouble() ?? 0, y: (j['y'] as num?)?.toDouble() ?? 0, fixed: j['fixed'] as bool? ?? false, ); } /// 草图几何类型。 enum SketchKind { /// 直线(p1 → p2)。 line, /// 圆(圆心 p1、半径 r)。 circle, /// 圆弧(圆心 p1、起点 p2、终点 p3、半径 r、[SketchEntity.ccw] 逆时针)。 arc, } /// 几何类型 ↔ JSON 字符串。 String sketchKindName(SketchKind k) => switch (k) { SketchKind.line => 'line', SketchKind.circle => 'circle', SketchKind.arc => 'arc', }; /// JSON 字符串 → 几何类型。 SketchKind sketchKindFrom(String s) => switch (s) { 'circle' => SketchKind.circle, 'arc' => SketchKind.arc, _ => SketchKind.line, }; /// 草图几何实体(全部坐标通过点 id 引用,共享点即共享位置)。 class SketchEntity { /// 构造实体。 const SketchEntity({ required this.id, required this.kind, this.p1 = '', this.p2 = '', this.p3 = '', this.r = 0, this.ccw = true, }); /// 实体 id(E 开头)。 final String id; /// 类型。 final SketchKind kind; /// 直线起点 / 圆心 / 圆弧圆心。 final String p1; /// 直线终点 / 圆弧起点。 final String p2; /// 圆弧终点。 final String p3; /// 半径(circle / arc)。 final double r; /// 圆弧方向:true 逆时针。 final bool ccw; /// 复制并覆盖字段。 SketchEntity copyWith({ String? p1, String? p2, String? p3, double? r, bool? ccw, }) => SketchEntity( id: id, kind: kind, p1: p1 ?? this.p1, p2: p2 ?? this.p2, p3: p3 ?? this.p3, r: r ?? this.r, ccw: ccw ?? this.ccw, ); /// 序列化。 Map toJson() => { 'id': id, 'kind': sketchKindName(kind), 'p1': p1, 'p2': p2, 'p3': p3, 'r': r, 'ccw': ccw, }; /// 反序列化。 static SketchEntity fromJson(Map j) => SketchEntity( id: j['id'] as String? ?? '', kind: sketchKindFrom(j['kind'] as String? ?? 'line'), p1: j['p1'] as String? ?? '', p2: j['p2'] as String? ?? '', p3: j['p3'] as String? ?? '', r: (j['r'] as num?)?.toDouble() ?? 0, ccw: j['ccw'] as bool? ?? true, ); } /// 几何约束类型。 enum SketchConsType { /// 水平(一条直线)。 horizontal, /// 竖直(一条直线)。 vertical, /// 平行(两条直线)。 parallel, /// 垂直(两条直线)。 perpendicular, /// 相等(两条线等长 / 两个圆等半径)。 equal, /// 同心(两个圆 / 弧)。 concentric, /// 相切(线与圆,或两个圆)。 tangent, /// 点在实体上(一个点 + 一条线 / 圆 / 弧)。 pointOnEntity, } /// 约束中文名(界面展示)。 String sketchConsLabel(SketchConsType t) => switch (t) { SketchConsType.horizontal => '水平', SketchConsType.vertical => '竖直', SketchConsType.parallel => '平行', SketchConsType.perpendicular => '垂直', SketchConsType.equal => '相等', SketchConsType.concentric => '同心', SketchConsType.tangent => '相切', SketchConsType.pointOnEntity => '点在线上', }; /// 约束 JSON 名称。 String sketchConsName(SketchConsType t) => switch (t) { SketchConsType.horizontal => 'horizontal', SketchConsType.vertical => 'vertical', SketchConsType.parallel => 'parallel', SketchConsType.perpendicular => 'perpendicular', SketchConsType.equal => 'equal', SketchConsType.concentric => 'concentric', SketchConsType.tangent => 'tangent', SketchConsType.pointOnEntity => 'pointOnEntity', }; /// 约束 JSON 名称 → 类型。 SketchConsType sketchConsFrom(String s) => switch (s) { 'horizontal' => SketchConsType.horizontal, 'vertical' => SketchConsType.vertical, 'parallel' => SketchConsType.parallel, 'perpendicular' => SketchConsType.perpendicular, 'equal' => SketchConsType.equal, 'concentric' => SketchConsType.concentric, 'tangent' => SketchConsType.tangent, _ => SketchConsType.pointOnEntity, }; /// 几何约束。 /// /// [a] / [b] 的含义随类型变化: /// - horizontal / vertical:a = 直线; /// - parallel / perpendicular / equal / concentric / tangent:a、b = 两实体; /// - pointOnEntity:a = 点 id,b = 实体 id。 class SketchConstraint { /// 构造约束。 const SketchConstraint({ required this.id, required this.type, this.a = '', this.b = '', this.internal = false, }); /// 约束 id(K 开头)。 final String id; /// 类型。 final SketchConsType type; /// 主引用。 final String a; /// 次引用。 final String b; /// 内部约束(如圆弧端点约束):不显示图标、用户不可删除。 final bool internal; /// 序列化。 Map toJson() => { 'id': id, 'type': sketchConsName(type), 'a': a, 'b': b, 'internal': internal, }; /// 反序列化。 static SketchConstraint fromJson(Map j) => SketchConstraint( id: j['id'] as String? ?? '', type: sketchConsFrom(j['type'] as String? ?? 'pointOnEntity'), a: j['a'] as String? ?? '', b: j['b'] as String? ?? '', internal: j['internal'] as bool? ?? false, ); } /// 驱动尺寸类型。 enum SketchDimType { /// 长度(一条直线)。 length, /// 半径(圆 / 弧)。 radius, /// 角度(两条直线,单位度)。 angle, /// 距离(两个点)。 distance, } /// 尺寸中文名。 String sketchDimLabel(SketchDimType t) => switch (t) { SketchDimType.length => '长度', SketchDimType.radius => '半径', SketchDimType.angle => '角度', SketchDimType.distance => '距离', }; /// 尺寸 JSON 名称。 String sketchDimName(SketchDimType t) => switch (t) { SketchDimType.length => 'length', SketchDimType.radius => 'radius', SketchDimType.angle => 'angle', SketchDimType.distance => 'distance', }; /// 尺寸 JSON 名称 → 类型。 SketchDimType sketchDimFrom(String s) => switch (s) { 'radius' => SketchDimType.radius, 'angle' => SketchDimType.angle, 'distance' => SketchDimType.distance, _ => SketchDimType.length, }; /// 驱动尺寸(a / b 为引用的实体或点 id)。 class SketchDim { /// 构造尺寸。 const SketchDim({ required this.id, required this.type, required this.value, this.a = '', this.b = '', }); /// 尺寸 id(D 开头)。 final String id; /// 类型。 final SketchDimType type; /// 驱动值(长度 / 半径为世界像素;角度为度)。 final double value; /// 主引用(长度 = 直线 id;半径 = 圆 / 弧 id;角度 = 两条线;距离 = 两个点)。 final String a; /// 次引用。 final String b; /// 复制并覆盖字段。 SketchDim copyWith({double? value, String? a, String? b}) => SketchDim( id: id, type: type, value: value ?? this.value, a: a ?? this.a, b: b ?? this.b, ); /// 序列化。 Map toJson() => { 'id': id, 'type': sketchDimName(type), 'value': value, 'a': a, 'b': b, }; /// 反序列化。 static SketchDim fromJson(Map j) => SketchDim( id: j['id'] as String? ?? '', type: sketchDimFrom(j['type'] as String? ?? 'length'), value: (j['value'] as num?)?.toDouble() ?? 0, a: j['a'] as String? ?? '', b: j['b'] as String? ?? '', ); } /// 草图工具。 enum SketchTool { /// 选择 / 拖动(拖动触发约束求解)。 select, /// 直线(点两下落线;近轴自动水平 / 竖直)。 line, /// 圆(圆心 + 半径点)。 circle, /// 圆弧(圆心 → 起点 → 终点)。 arc, /// 矩形(对角两点;自动水平 / 竖直 + 共享角点)。 rect, /// 修剪(点击线段删除该段)。 trim, } /// 工具中文名(状态栏用)。 String sketchToolLabel(SketchTool t) => switch (t) { SketchTool.select => '选择', SketchTool.line => '直线', SketchTool.circle => '圆', SketchTool.arc => '圆弧', SketchTool.rect => '矩形', SketchTool.trim => '修剪', }; // ===================== 文档 ===================== /// 参数化草图文档。 class SketchDoc { /// 构造文档。 const SketchDoc({ this.points = const [], this.entities = const [], this.constraints = const [], this.dims = const [], }); /// 空草图。 static const SketchDoc empty = SketchDoc(); /// 点列表(自由度载体)。 final List points; /// 几何实体列表。 final List entities; /// 约束列表。 final List constraints; /// 驱动尺寸列表。 final List dims; /// 是否为空。 bool get isEmpty => points.isEmpty && entities.isEmpty && constraints.isEmpty && dims.isEmpty; /// 按 id 查找点。 SketchPoint? pointById(String? id) { if (id == null) return null; for (final SketchPoint p in points) { if (p.id == id) return p; } return null; } /// 按 id 查找实体。 SketchEntity? entityById(String? id) { if (id == null) return null; for (final SketchEntity e in entities) { if (e.id == id) return e; } return null; } /// 按 id 查找尺寸。 SketchDim? dimById(String? id) { if (id == null) return null; for (final SketchDim d in dims) { if (d.id == id) return d; } return null; } /// 实体引用的点 id 列表。 List entityPointIds(SketchEntity e) => switch (e.kind) { SketchKind.line => [e.p1, e.p2], SketchKind.circle => [e.p1], SketchKind.arc => [e.p1, e.p2, e.p3], }.where((String s) => s.isNotEmpty).toList(); /// 全部已用 id。 Iterable get allIds => [ for (final SketchPoint p in points) p.id, for (final SketchEntity e in entities) e.id, for (final SketchConstraint k in constraints) k.id, for (final SketchDim d in dims) d.id, ]; /// 复制并覆盖字段。 SketchDoc copyWith({ List? points, List? entities, List? constraints, List? dims, }) => SketchDoc( points: points ?? this.points, entities: entities ?? this.entities, constraints: constraints ?? this.constraints, dims: dims ?? this.dims, ); /// 替换 / 追加点。 SketchDoc upsertPoint(SketchPoint p) { bool found = false; final List next = [ for (final SketchPoint x in points) if (x.id == p.id) (found = true) ? p : x else x, ]; if (!found) next.add(p); return copyWith(points: next); } /// 替换 / 追加实体。 SketchDoc upsertEntity(SketchEntity e) { bool found = false; final List next = [ for (final SketchEntity x in entities) if (x.id == e.id) (found = true) ? e : x else x, ]; if (!found) next.add(e); return copyWith(entities: next); } /// 删除实体:连带清理仅被它引用的点、引用它的约束与尺寸。 SketchDoc removeEntities(Set ids) { final List next = entities.where((SketchEntity e) => !ids.contains(e.id)).toList(); final Set used = { for (final SketchEntity e in next) ...entityPointIds(e), }; final List nextCons = constraints .where((SketchConstraint k) => !(ids.contains(k.a) || ids.contains(k.b))) .toList(); final List nextDims = dims .where((SketchDim d) => !(ids.contains(d.a) || ids.contains(d.b))) .toList(); return copyWith( entities: next, constraints: nextCons, dims: nextDims, points: points .where((SketchPoint p) => used.contains(p.id) || !_pointOnlyUsedBy(p.id, ids)) .toList(), ); } /// 某个点是否只被 [gone] 中的实体引用。 bool _pointOnlyUsedBy(String pointId, Set gone) { for (final SketchEntity e in entities) { if (gone.contains(e.id)) continue; if (entityPointIds(e).contains(pointId)) return false; } return true; } /// 删除指定对象(点 / 实体 / 约束 / 尺寸 id 混选)。 SketchDoc removeAny(Set ids) { final Set entIds = { for (final SketchEntity e in entities) if (ids.contains(e.id)) e.id, }; Set pointIds = { for (final SketchPoint p in points) if (ids.contains(p.id)) p.id, }; // 删除点 → 连带删除引用它的实体。 for (final SketchEntity e in entities) { if (entityPointIds(e).any(pointIds.contains)) entIds.add(e.id); } SketchDoc next = entIds.isEmpty ? this : removeEntities(entIds); pointIds = pointIds .where((String id) => next.pointById(id) != null) .toSet(); return next.copyWith( points: next.points .where((SketchPoint p) => !pointIds.contains(p.id)) .toList(), constraints: next.constraints .where((SketchConstraint k) => !ids.contains(k.id)) .toList(), dims: next.dims.where((SketchDim d) => !ids.contains(d.id)).toList(), ); } /// 内容外接矩形(适配视图用;空草图返回 null)。 Rect? contentBounds() { double? l, t, r, b; void inc(Offset p) { l = (l == null || p.dx < l!) ? p.dx : l; t = (t == null || p.dy < t!) ? p.dy : t; r = (r == null || p.dx > r!) ? p.dx : r; b = (b == null || p.dy > b!) ? p.dy : b; } for (final SketchPoint p in points) { inc(p.pos); } if (l == null || t == null || r == null || b == null) return null; for (final SketchEntity e in entities) { if (e.kind == SketchKind.circle || e.kind == SketchKind.arc) { final SketchPoint? c = pointById(e.p1); if (c != null) { inc(c.pos + Offset(-e.r, -e.r)); inc(c.pos + Offset(e.r, e.r)); } } } return Rect.fromLTRB(l!, t!, r!, b!); } /// 序列化。 Map toJson() => { 'points': >[ for (final SketchPoint p in points) p.toJson(), ], 'entities': >[ for (final SketchEntity e in entities) e.toJson(), ], 'constraints': >[ for (final SketchConstraint k in constraints) k.toJson(), ], 'dims': >[ for (final SketchDim d in dims) d.toJson(), ], }; /// 序列化为带缩进的 JSON 文本。 String encode() => const JsonEncoder.withIndent(' ').convert(toJson()); /// 从文本解码。 static SketchDoc decode(String source) => SketchDoc.fromJson(jsonDecode(source) as Map); /// 反序列化(缺失字段安全默认)。 static SketchDoc fromJson(Map j) => SketchDoc( points: ((j['points'] as List?) ?? []) .map((dynamic e) => SketchPoint.fromJson(e as Map)) .toList(), entities: ((j['entities'] as List?) ?? []) .map((dynamic e) => SketchEntity.fromJson(e as Map)) .toList(), constraints: ((j['constraints'] as List?) ?? []) .map((dynamic e) => SketchConstraint.fromJson(e as Map)) .toList(), dims: ((j['dims'] as List?) ?? []) .map((dynamic e) => SketchDim.fromJson(e as Map)) .toList(), ); } /// 生成不冲突的新 id(P / E / K / D 前缀 + 数字,从 1 递增)。 String sketchNewId(String prefix, Iterable existing) { final Set used = existing.toSet(); int n = 1; while (used.contains('$prefix$n')) { n++; } return '$prefix$n'; } // ===================== 几何工具 ===================== /// 点到线段距离。 double sketchDistToSegment(Offset p, Offset a, Offset b) { final Offset ab = b - a; final double len2 = ab.dx * ab.dx + ab.dy * ab.dy; if (len2 < 1e-9) return (p - a).distance; double t = ((p - a).dx * ab.dx + (p - a).dy * ab.dy) / len2; t = t.clamp(0.0, 1.0); return (p - (a + ab * t)).distance; } /// 圆弧起止角(弧度;ccw 决定方向)。 (double start, double sweep) sketchArcAngles( Offset c, Offset ps, Offset pe, bool ccw, ) { final double a1 = math.atan2(ps.dy - c.dy, ps.dx - c.dx); final double a2 = math.atan2(pe.dy - c.dy, pe.dx - c.dx); double sweep = ccw ? (a2 - a1) : (a1 - a2); while (sweep <= 0) { sweep += math.pi * 2; } if (sweep > math.pi * 2) sweep = math.pi * 2; return (a1, sweep); } /// 角度是否落在圆弧范围内。 bool sketchAngleInArc(Offset c, Offset p, Offset ps, Offset pe, bool ccw) { final (double a1, double sweep) = sketchArcAngles(c, ps, pe, ccw); double a = math.atan2(p.dy - c.dy, p.dx - c.dx); double d = ccw ? (a - a1) : (a1 - a); while (d < 0) { d += math.pi * 2; } return d <= sweep + 1e-9; } /// 实体到点的命中距离(轮廓)。 double sketchEntityDistance(SketchDoc doc, SketchEntity e, Offset p) { switch (e.kind) { case SketchKind.line: final Offset? a = doc.pointById(e.p1)?.pos; final Offset? b = doc.pointById(e.p2)?.pos; if (a == null || b == null) return double.infinity; return sketchDistToSegment(p, a, b); case SketchKind.circle: final Offset? c = doc.pointById(e.p1)?.pos; if (c == null) return double.infinity; return ((p - c).distance - e.r).abs(); case SketchKind.arc: final Offset? c = doc.pointById(e.p1)?.pos; final Offset? ps = doc.pointById(e.p2)?.pos; final Offset? pe = doc.pointById(e.p3)?.pos; if (c == null || ps == null || pe == null) return double.infinity; if (!sketchAngleInArc(c, p, ps, pe, e.ccw)) { // 不在弧范围内:按到两端点的最近距离算。 return math.min((p - ps).distance, (p - pe).distance); } return ((p - c).distance - e.r).abs(); } } /// 命中测试结果。 class SketchHit { /// 构造。 const SketchHit({this.pointId, this.entityId, this.dimId}); /// 命中的点 id。 final String? pointId; /// 命中的实体 id。 final String? entityId; /// 命中的尺寸 id。 final String? dimId; } /// 命中测试:点优先,其次尺寸标签附近,最后实体轮廓。 SketchHit sketchHitTest( SketchDoc doc, Offset p, { double pointTol = 8, double entityTol = 6, double dimTol = 12, }) { // 1) 点。 String? bestPoint; double bestD = pointTol; for (final SketchPoint pt in doc.points) { final double d = (pt.pos - p).distance; if (d <= bestD) { bestD = d; bestPoint = pt.id; } } if (bestPoint != null) return SketchHit(pointId: bestPoint); // 2) 尺寸(标签锚点附近)。 for (final SketchDim d in doc.dims) { final Rect? r = sketchDimBounds(doc, d); if (r != null && r.inflate(4).contains(p)) { return SketchHit(dimId: d.id); } } // 3) 实体。 String? bestEntity; double bestE = entityTol; for (final SketchEntity e in doc.entities) { final double d = sketchEntityDistance(doc, e, p); if (d <= bestE) { bestE = d; bestEntity = e.id; } } return SketchHit(entityId: bestEntity); } // ===================== 尺寸测量与布局 ===================== /// 测量尺寸当前值(界面预填充与约束可用性判断用);无法测量返回 null。 double? sketchMeasure(SketchDoc doc, SketchDimType type, String a, String b) { switch (type) { case SketchDimType.length: final SketchEntity? e = doc.entityById(a); if (e == null || e.kind != SketchKind.line) return null; final Offset? p1 = doc.pointById(e.p1)?.pos; final Offset? p2 = doc.pointById(e.p2)?.pos; if (p1 == null || p2 == null) return null; return (p2 - p1).distance; case SketchDimType.radius: final SketchEntity? e = doc.entityById(a); if (e == null || e.kind == SketchKind.line) return null; return e.r; case SketchDimType.angle: final SketchEntity? e1 = doc.entityById(a); final SketchEntity? e2 = doc.entityById(b); if (e1 == null || e2 == null || e1.kind != SketchKind.line || e2.kind != SketchKind.line) { return null; } final Offset? a1 = doc.pointById(e1.p1)?.pos; final Offset? a2 = doc.pointById(e1.p2)?.pos; final Offset? b1 = doc.pointById(e2.p1)?.pos; final Offset? b2 = doc.pointById(e2.p2)?.pos; if (a1 == null || a2 == null || b1 == null || b2 == null) return null; final Offset d1 = a2 - a1; final Offset d2 = b2 - b1; final double dot = d1.dx * d2.dx + d1.dy * d2.dy; final double cross = d1.dx * d2.dy - d1.dy * d2.dx; double ang = math.atan2(cross.abs(), dot) * 180 / math.pi; if (ang > 90) ang = 180 - ang; // 取锐角,与 CAD 习惯一致 return ang; case SketchDimType.distance: final Offset? p1 = doc.pointById(a)?.pos; final Offset? p2 = doc.pointById(b)?.pos; if (p1 == null || p2 == null) return null; return (p2 - p1).distance; } } /// 尺寸标签锚点(绘制 / 命中用)。 Offset? sketchDimAnchor(SketchDoc doc, SketchDim d) { switch (d.type) { case SketchDimType.length: final SketchEntity? e = doc.entityById(d.a); if (e == null) return null; final Offset? p1 = doc.pointById(e.p1)?.pos; final Offset? p2 = doc.pointById(e.p2)?.pos; if (p1 == null || p2 == null) return null; final Offset mid = Offset.lerp(p1, p2, 0.5)!; final Offset dir = p2 - p1; final double len = dir.distance; if (len < 1e-6) return mid; final Offset n = Offset(-dir.dy / len, dir.dx / len); return mid + n * 22; case SketchDimType.radius: final SketchEntity? e = doc.entityById(d.a); final Offset? c = doc.pointById(e?.p1)?.pos; if (e == null || c == null) return null; return c + Offset(e.r * 0.6, -e.r * 0.6); case SketchDimType.angle: final SketchEntity? e1 = doc.entityById(d.a); final SketchEntity? e2 = doc.entityById(d.b); if (e1 == null || e2 == null) return null; final Offset? m1a = doc.pointById(e1.p1)?.pos; final Offset? m1b = doc.pointById(e1.p2)?.pos; final Offset? m2a = doc.pointById(e2.p1)?.pos; final Offset? m2b = doc.pointById(e2.p2)?.pos; if (m1a == null || m1b == null || m2a == null || m2b == null) { return null; } return Offset.lerp(Offset.lerp(m1a, m1b, 0.5)!, Offset.lerp(m2a, m2b, 0.5)!, 0.5); case SketchDimType.distance: final Offset? p1 = doc.pointById(d.a)?.pos; final Offset? p2 = doc.pointById(d.b)?.pos; if (p1 == null || p2 == null) return null; return Offset.lerp(p1, p2, 0.5)! + const Offset(0, -16); } } /// 尺寸标签外接矩形(命中 / 布局用)。 Rect? sketchDimBounds(SketchDoc doc, SketchDim d) { final Offset? a = sketchDimAnchor(doc, d); if (a == null) return null; final String text = sketchDimText(d); final double w = text.length * 7.0 + 12; return Rect.fromCenter(center: a, width: w, height: 18); } /// 尺寸显示文本(如 `L120.0` / `R25.0` / `∠45.0°` / `⌀…`)。 String sketchDimText(SketchDim d) => switch (d.type) { SketchDimType.length => 'L${_fmt(d.value)}', SketchDimType.radius => 'R${_fmt(d.value)}', SketchDimType.angle => '∠${_fmt(d.value)}°', SketchDimType.distance => 'D${_fmt(d.value)}', }; String _fmt(double v) => (v - v.roundToDouble()).abs() < 0.05 ? v.round().toString() : v.toStringAsFixed(1); // ===================== 捕捉与自动约束 ===================== /// 捕捉结果:位置 + 可选的吸附目标(点 → 重合;实体 → 点在实体上)。 class SketchSnap { /// 构造。 const SketchSnap({required this.pos, this.pointId, this.entityId}); /// 吸附后的位置。 final Offset pos; /// 命中的已有点(复用该点 = 天然重合)。 final String? pointId; /// 命中的实体(生成 pointOnEntity 约束)。 final String? entityId; } /// 绘制捕捉:已有点 > 实体轮廓 > 网格。 SketchSnap sketchSnap( SketchDoc doc, Offset pos, { required bool gridSnap, required double grid, String? ignorePointId, double pointTol = 10, double entityTol = 8, }) { String? bestPoint; double bestD = pointTol; for (final SketchPoint p in doc.points) { if (p.id == ignorePointId) continue; final double d = (p.pos - pos).distance; if (d <= bestD) { bestD = d; bestPoint = p.id; } } if (bestPoint != null) { return SketchSnap(pos: doc.pointById(bestPoint)!.pos, pointId: bestPoint); } String? bestEntity; double bestE = entityTol; for (final SketchEntity e in doc.entities) { final double d = sketchEntityDistance(doc, e, pos); if (d <= bestE) { bestE = d; bestEntity = e.id; } } if (bestEntity != null) { return SketchSnap(pos: pos, entityId: bestEntity); } if (gridSnap && grid > 0) { return SketchSnap( pos: Offset( (pos.dx / grid).roundToDouble() * grid, (pos.dy / grid).roundToDouble() * grid, ), ); } return SketchSnap(pos: pos); } /// 新直线是否近轴(自动补水平 / 竖直约束);返回 null 表示无需约束。 SketchConsType? sketchAutoAxis(Offset a, Offset b, {double tolDeg = 2.5}) { final Offset d = b - a; if (d.distance < 1e-6) return null; final double ang = math.atan2(d.dy.abs(), d.dx.abs()) * 180 / math.pi; // 0..90° if (ang <= tolDeg) return SketchConsType.horizontal; if (ang >= 90 - tolDeg) return SketchConsType.vertical; return null; } /// 选择是否可添加某类约束(面板按钮启用 / 提示用)。 bool sketchCanConstrain( SketchDoc doc, SketchConsType type, List selIds, ) { final List es = [ for (final String id in selIds) if (doc.entityById(id) != null) doc.entityById(id)!, ]; final List ps = [ for (final String id in selIds) if (doc.pointById(id) != null) doc.pointById(id)!, ]; switch (type) { case SketchConsType.horizontal: case SketchConsType.vertical: return es.length == 1 && es.first.kind == SketchKind.line; case SketchConsType.parallel: case SketchConsType.perpendicular: return es.length == 2 && es.every((SketchEntity e) => e.kind == SketchKind.line); case SketchConsType.equal: if (es.length != 2) return false; final bool lines = es.every((SketchEntity e) => e.kind == SketchKind.line); final bool circles = es.every((SketchEntity e) => e.kind != SketchKind.line); return lines || circles; case SketchConsType.concentric: return es.length == 2 && es.every((SketchEntity e) => e.kind != SketchKind.line); case SketchConsType.tangent: if (es.length != 2) return false; final int nLines = es.where((SketchEntity e) => e.kind == SketchKind.line).length; return nLines <= 1; case SketchConsType.pointOnEntity: return ps.length == 1 && es.length == 1; } } /// 选择是否可添加某类尺寸。 bool sketchCanDim(SketchDoc doc, SketchDimType type, List selIds) { final List es = [ for (final String id in selIds) if (doc.entityById(id) != null) doc.entityById(id)!, ]; final List ps = [ for (final String id in selIds) if (doc.pointById(id) != null) doc.pointById(id)!, ]; switch (type) { case SketchDimType.length: return es.length == 1 && es.first.kind == SketchKind.line; case SketchDimType.radius: return es.length == 1 && es.first.kind != SketchKind.line; case SketchDimType.angle: return es.length == 2 && es.every((SketchEntity e) => e.kind == SketchKind.line); case SketchDimType.distance: return ps.length == 2; } } /// 从选择解析尺寸引用(与 [sketchCanDim] 配合);无法解析返回 null。 (String, String)? sketchDimRefs( SketchDoc doc, SketchDimType type, List selIds, ) { final List es = [ for (final String id in selIds) if (doc.entityById(id) != null) doc.entityById(id)!, ]; final List ps = [ for (final String id in selIds) if (doc.pointById(id) != null) doc.pointById(id)!, ]; switch (type) { case SketchDimType.length: case SketchDimType.radius: if (es.length != 1) return null; return (es.first.id, ''); case SketchDimType.angle: if (es.length != 2) return null; return (es[0].id, es[1].id); case SketchDimType.distance: if (ps.length != 2) return null; return (ps[0].id, ps[1].id); } } /// 从选择解析约束引用(与 [sketchCanConstrain] 配合);无法解析返回 null。 (String, String)? sketchConsRefs( SketchDoc doc, SketchConsType type, List selIds, ) { final List es = [ for (final String id in selIds) if (doc.entityById(id) != null) doc.entityById(id)!, ]; final List ps = [ for (final String id in selIds) if (doc.pointById(id) != null) doc.pointById(id)!, ]; switch (type) { case SketchConsType.horizontal: case SketchConsType.vertical: if (es.length != 1) return null; return (es.first.id, ''); case SketchConsType.parallel: case SketchConsType.perpendicular: case SketchConsType.equal: case SketchConsType.concentric: case SketchConsType.tangent: if (es.length != 2) return null; return (es[0].id, es[1].id); case SketchConsType.pointOnEntity: if (ps.length != 1 || es.length != 1) return null; return (ps.first.id, es.first.id); } } // ===================== 修剪 ===================== /// 直线与其它实体的交点参数(0..1,沿 p1 → p2)。 List sketchLineCuts( SketchDoc doc, SketchEntity line, { double eps = 1e-4, }) { final SketchPoint? pa = doc.pointById(line.p1); final SketchPoint? pb = doc.pointById(line.p2); if (pa == null || pb == null) return []; final Offset a = pa.pos; final Offset b = pb.pos; final Offset d = b - a; final double len2 = d.dx * d.dx + d.dy * d.dy; if (len2 < 1e-9) return []; final List out = []; for (final SketchEntity e in doc.entities) { if (e.id == line.id) continue; switch (e.kind) { case SketchKind.line: final Offset? qa = doc.pointById(e.p1)?.pos; final Offset? qb = doc.pointById(e.p2)?.pos; if (qa == null || qb == null) continue; final Offset qd = qb - qa; final double den = d.dx * qd.dy - d.dy * qd.dx; if (den.abs() < 1e-9) continue; final Offset w = qa - a; final double t = (w.dx * qd.dy - w.dy * qd.dx) / den; final double s = (w.dx * d.dy - w.dy * d.dx) / den; if (t > eps && t < 1 - eps && s > -eps && s < 1 + eps) out.add(t); case SketchKind.circle: case SketchKind.arc: final Offset? c = doc.pointById(e.p1)?.pos; if (c == null) continue; final double r = e.r; final Offset f = a - c; final double A = d.dx * d.dx + d.dy * d.dy; final double B = 2 * (f.dx * d.dx + f.dy * d.dy); final double C = f.dx * f.dx + f.dy * f.dy - r * r; final double disc = B * B - 4 * A * C; if (disc < 0) continue; final double sq = math.sqrt(disc); for (final double t in [(-B - sq) / (2 * A), (-B + sq) / (2 * A)]) { if (t <= eps || t >= 1 - eps) continue; if (e.kind == SketchKind.arc) { final Offset pt = a + d * t; final Offset? ps = doc.pointById(e.p2)?.pos; final Offset? pe = doc.pointById(e.p3)?.pos; if (ps == null || pe == null) continue; if (!sketchAngleInArc(c, pt, ps, pe, e.ccw)) continue; } out.add(t); } } } out.sort(); // 去重(容差 1e-4)。 final List uniq = []; for (final double t in out) { if (uniq.isEmpty || t - uniq.last > 1e-4) uniq.add(t); } return uniq; } /// 修剪一条直线:删除 [click] 所在的段(两交点之间 / 端点与交点之间)。 /// /// 返回修剪后的文档;直线完全被切除时返回删除后的文档; /// 无法修剪(无交点或在交点外)返回 null。 SketchDoc? sketchTrimLine(SketchDoc doc, String lineId, Offset click) { final SketchEntity? line = doc.entityById(lineId); if (line == null || line.kind != SketchKind.line) return null; final SketchPoint? pa = doc.pointById(line.p1); final SketchPoint? pb = doc.pointById(line.p2); if (pa == null || pb == null) return null; final Offset a = pa.pos; final Offset b = pb.pos; final Offset d = b - a; final double len2 = d.dx * d.dx + d.dy * d.dy; if (len2 < 1e-9) return null; final double tc = (((click - a).dx * d.dx + (click - a).dy * d.dy) / len2).clamp(0.0, 1.0); final List cuts = sketchLineCuts(doc, line); if (cuts.isEmpty) { // 没有交点:整条删除。 return doc.removeEntities({line.id}); } double left = 0; double right = 1; for (final double t in cuts) { if (t <= tc) left = math.max(left, t); if (t >= tc) right = math.min(right, t); } final bool keepLeft = left > 1e-3; final bool keepRight = right < 1 - 1e-3; SketchDoc next = doc; // 中间段始终切除;线段可能在两端保留残余。 final List pieces = []; final List newPoints = []; // 统一的新建 id 累加器,避免两段残余取到相同 id。 final List freshIds = []; String nextId(String prefix) { final String id = sketchNewId(prefix, [...doc.allIds, ...freshIds]); freshIds.add(id); return id; } if (keepLeft) { final String nid = nextId('P'); final SketchPoint pt = SketchPoint( id: nid, x: a.dx + d.dx * left, y: a.dy + d.dy * left, ); newPoints.add(pt); pieces.add(SketchEntity( id: nextId('E'), kind: SketchKind.line, p1: line.p1, p2: nid, )); } if (keepRight) { final String nid = nextId('P'); final SketchPoint pt = SketchPoint( id: nid, x: a.dx + d.dx * right, y: a.dy + d.dy * right, ); newPoints.add(pt); pieces.add(SketchEntity( id: nextId('E'), kind: SketchKind.line, p1: nid, p2: line.p2, )); } next = next.removeEntities({line.id}); if (!keepLeft && !keepRight) return next; // 修剪的残余段可能引用原端点(其点已被连带清理时需补回)。 for (final SketchEntity e in pieces) { for (final String pid in [e.p1, e.p2]) { if (pid.isEmpty || next.pointById(pid) != null) continue; if (pid == line.p1) next = next.upsertPoint(pa); if (pid == line.p2) next = next.upsertPoint(pb); } } for (final SketchPoint pt in newPoints) { next = next.upsertPoint(pt); } for (final SketchEntity e in pieces) { next = next.upsertEntity(e); } // 被修剪掉的中间段上原本挂接的点(无实体引用且非两端点)清理。 final Set used = { for (final SketchEntity e in next.entities) ...next.entityPointIds(e), }; return next.copyWith( points: next.points .where((SketchPoint p) => used.contains(p.id) || p.id == line.p1 || p.id == line.p2) .toList(), ); }