v1.3.13: 模块化注册架构 + PDS流程设计套件更名 + 依赖/圆周交互修复
- 模块化:EdcModule 契约 + registry + 模块独立目录;发布包增加 modules/registry.json - 更名:PDS流程设计套件 / ProcessDesignSuite;同步构建、发布脚本与文档 - 时序图:依赖偏移以时间显示/编辑;紧贴依赖隐藏箭头并在接缝显示标签;动作条磁吸 - 圆周:依赖标签沿圆弧方向、环间空隙;动作旋转磁吸增强;短弧标签优先动作名 - 清理:release 移至源码同级(本地不入库);tool 合并到 tools;发布说明迁移 docs/release-notes
This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
/// 架构图设计模块:手绘识别、系统架构图与参数化草图。
|
||||
///
|
||||
/// 模块入口:`lib/modules/architecture/`。新增模块请参考本文件与
|
||||
/// `lib/modules/README.md`,然后在 `lib/modules/registry.dart` 注册。
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'package:sequence_diagram/modules/architecture/domain/arch_models.dart';
|
||||
import 'package:sequence_diagram/modules/architecture/ui/architecture_ui.dart';
|
||||
import 'package:sequence_diagram/modules/module.dart';
|
||||
import 'package:sequence_diagram/state/app_controller.dart';
|
||||
|
||||
/// 架构图模块单例。
|
||||
const ArchitectureModule architectureModule = ArchitectureModule();
|
||||
|
||||
/// 架构图设计模块。
|
||||
class ArchitectureModule extends EdcModule {
|
||||
/// 构造模块。
|
||||
const ArchitectureModule();
|
||||
|
||||
/// 稳定 id。
|
||||
static const String moduleId = 'architecture';
|
||||
|
||||
@override
|
||||
String get id => moduleId;
|
||||
@override
|
||||
String get name => '架构图';
|
||||
@override
|
||||
String get shortName => '架构图';
|
||||
@override
|
||||
IconData get icon => Icons.account_tree_outlined;
|
||||
@override
|
||||
int get accent => 0xFF34D399;
|
||||
@override
|
||||
String get suffix => '.arch.json';
|
||||
@override
|
||||
bool get available => true;
|
||||
@override
|
||||
String get defaultName => '未命名-架构图';
|
||||
@override
|
||||
String get blurb => '手绘识别 · 图形库';
|
||||
|
||||
@override
|
||||
String get enterStatus => '架构图设计 · 手绘识别';
|
||||
|
||||
@override
|
||||
void newDocument(AppController controller) {
|
||||
controller.newArchProject();
|
||||
}
|
||||
|
||||
@override
|
||||
void loadDocument(AppController controller, String source, {String? path}) {
|
||||
controller.loadArchDoc(ArchDoc.decode(source), path: path);
|
||||
}
|
||||
|
||||
@override
|
||||
String encodeDocument(AppController controller) => controller.arch.encode();
|
||||
|
||||
@override
|
||||
String documentName(AppController controller) => controller.project.name;
|
||||
|
||||
@override
|
||||
String? filePath(AppController controller) => controller.archFilePath;
|
||||
|
||||
@override
|
||||
bool isDirty(AppController controller) => controller.dirty;
|
||||
|
||||
@override
|
||||
Future<void> saveTo(AppController controller, String path) =>
|
||||
controller.saveArchAs(path);
|
||||
|
||||
@override
|
||||
Future<void> markSaved(AppController controller, String displayPath) =>
|
||||
controller.markArchSaved(displayPath);
|
||||
|
||||
@override
|
||||
bool isReadOnly(AppController controller) => false;
|
||||
|
||||
@override
|
||||
Map<ShortcutActivator, VoidCallback> buildShortcuts(ModuleUiContext ui) {
|
||||
final AppController c = ui.controller;
|
||||
return <ShortcutActivator, VoidCallback>{
|
||||
const SingleActivator(LogicalKeyboardKey.keyA, control: true): () {
|
||||
if (c.sketchMode) {
|
||||
c.selectAllSketch();
|
||||
} else {
|
||||
c.selectAllArch();
|
||||
}
|
||||
},
|
||||
const SingleActivator(LogicalKeyboardKey.delete): () {
|
||||
if (c.sketchMode) {
|
||||
c.deleteSketchSelection();
|
||||
} else {
|
||||
c.removeArchSelection();
|
||||
}
|
||||
},
|
||||
const SingleActivator(LogicalKeyboardKey.escape): () {
|
||||
if (c.sketchMode &&
|
||||
(c.sketchPendingCons != null || c.sketchPendingDim != null)) {
|
||||
c.cancelSketchCommand();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
Widget buildWorkspace(ModuleUiContext ui) => ArchitectureUi(ui).buildWorkspace();
|
||||
|
||||
@override
|
||||
Widget? buildLeftPanel(ModuleUiContext ui, {bool floating = false}) =>
|
||||
ArchitectureUi(ui).buildLeftPanel(ui.tokens, floating: floating);
|
||||
|
||||
@override
|
||||
Widget? buildRightPanel(ModuleUiContext ui, {bool floating = false}) =>
|
||||
ArchitectureUi(ui).buildRightPanel(ui.tokens, floating: floating);
|
||||
|
||||
@override
|
||||
List<Widget> buildToolbarCenter(ModuleUiContext ui, {required bool compact}) =>
|
||||
ArchitectureUi(ui).buildToolbarCenter(ui.tokens, compact: compact);
|
||||
|
||||
@override
|
||||
List<Widget> buildToolbarRight(ModuleUiContext ui) =>
|
||||
ArchitectureUi(ui).buildToolbarRight(ui.tokens, compact: ui.compact);
|
||||
|
||||
@override
|
||||
Widget buildStatusBar(ModuleUiContext ui) =>
|
||||
ArchitectureUi(ui).buildStatusBar(ui.tokens);
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
/// 架构图 DXF 导出(AutoCAD R12 ASCII,AC1009):
|
||||
/// 可直接在 AutoCAD / DraftSight / ZWCAD 等 CAD 软件中打开继续编辑。
|
||||
///
|
||||
/// 约定:
|
||||
/// - 图形几何统一采样为 POLYLINE/VERTEX(圆用 CIRCLE、直线用 LINE);
|
||||
/// - 文字用 TEXT(多行拆多条),连线标签同;
|
||||
/// - 图层按架构图图层写入 TABLES→LAYER(颜色近似为 ACI 色号);
|
||||
/// - Y 轴取反(CAD 绿轴向上,画布向下)。
|
||||
library;
|
||||
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:sequence_diagram/modules/architecture/library/symbol_library.dart';
|
||||
import 'arch_models.dart';
|
||||
import 'arch_painter.dart';
|
||||
|
||||
/// 构造架构图 DXF 文本。
|
||||
String buildArchDxf({required ArchDoc doc}) {
|
||||
final StringBuffer sb = StringBuffer();
|
||||
sb.write('0\nSECTION\n2\nHEADER\n9\n\$ACADVER\n1\nAC1009\n0\nENDSEC\n');
|
||||
|
||||
// TABLES → LAYER
|
||||
sb.write('0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLAYER\n70\n'
|
||||
'${doc.layers.length}\n');
|
||||
for (final ArchLayer l in doc.layers) {
|
||||
sb.write('0\nLAYER\n2\n${_name(l.name)}\n70\n0\n62\n${_aci(l.color)}\n'
|
||||
'6\nCONTINUOUS\n');
|
||||
}
|
||||
sb.write('0\nENDTAB\n0\nENDSEC\n');
|
||||
|
||||
// ENTITIES
|
||||
sb.write('0\nSECTION\n2\nENTITIES\n');
|
||||
for (final ArchConnector c in doc.connectors) {
|
||||
if (!doc.isLayerVisible(c.layerId)) continue;
|
||||
_connector(sb, doc, c);
|
||||
}
|
||||
for (final ArchShape s in doc.shapes) {
|
||||
if (!doc.isLayerVisible(s.layerId)) continue;
|
||||
_shape(sb, doc, s);
|
||||
}
|
||||
for (final ArchStroke s in doc.strokes) {
|
||||
if (!doc.isLayerVisible(s.layerId)) continue;
|
||||
_polyline(sb, _layerName(doc, s.layerId), s.pts, false);
|
||||
}
|
||||
sb.write('0\nENDSEC\n0\nEOF\n');
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
// ===================== 图形 =====================
|
||||
|
||||
void _shape(StringBuffer sb, ArchDoc doc, ArchShape s) {
|
||||
final String layer = _layerName(doc, s.layerId);
|
||||
switch (s.type) {
|
||||
case ArchShapeType.line:
|
||||
final Offset a = s.a ?? s.rect.topLeft;
|
||||
final Offset b = s.b ?? s.rect.bottomRight;
|
||||
_line(sb, layer, a, b);
|
||||
if (s.arrow) _solidArrow(sb, layer, a, b);
|
||||
break;
|
||||
case ArchShapeType.circle:
|
||||
_circle(sb, layer, s.rect.center, s.rect.width / 2);
|
||||
break;
|
||||
case ArchShapeType.text:
|
||||
break;
|
||||
case ArchShapeType.rect:
|
||||
_polyline(
|
||||
sb,
|
||||
layer,
|
||||
<Offset>[
|
||||
s.rect.topLeft,
|
||||
s.rect.topRight,
|
||||
s.rect.bottomRight,
|
||||
s.rect.bottomLeft,
|
||||
],
|
||||
true,
|
||||
);
|
||||
break;
|
||||
case ArchShapeType.polyline:
|
||||
_polyline(sb, layer, s.pts, false);
|
||||
break;
|
||||
case ArchShapeType.curve:
|
||||
_samplePath(sb, layer, archSplinePath(s.pts), closed: false);
|
||||
break;
|
||||
case ArchShapeType.roundRect:
|
||||
case ArchShapeType.ellipse:
|
||||
case ArchShapeType.triangle:
|
||||
case ArchShapeType.diamond:
|
||||
case ArchShapeType.cylinder:
|
||||
case ArchShapeType.cloud:
|
||||
case ArchShapeType.hexagon:
|
||||
case ArchShapeType.server:
|
||||
case ArchShapeType.client:
|
||||
case ArchShapeType.mobile:
|
||||
case ArchShapeType.firewall:
|
||||
case ArchShapeType.netSwitch:
|
||||
case ArchShapeType.queue:
|
||||
_samplePath(sb, layer, archShapePath(s), closed: true);
|
||||
break;
|
||||
case ArchShapeType.symbol:
|
||||
final LibSymbol? sym = SymbolCache.byId(s.symbolId);
|
||||
final Path symPath = (sym == null || s.symbolId.isEmpty)
|
||||
? archShapePath(s)
|
||||
: buildSymbolPath(sym, s.rect);
|
||||
_samplePathEach(sb, layer, symPath);
|
||||
break;
|
||||
}
|
||||
if (s.text.isNotEmpty) {
|
||||
final double size = s.type == ArchShapeType.text
|
||||
? (s.rect.height * 0.72).clamp(10.0, 120.0).toDouble()
|
||||
: 12.5;
|
||||
Offset center = s.rect.center;
|
||||
if (s.type == ArchShapeType.cloud) {
|
||||
center = center.translate(0, s.rect.height * 0.12);
|
||||
}
|
||||
_text(sb, layer, s.text, center, size);
|
||||
}
|
||||
}
|
||||
|
||||
void _connector(StringBuffer sb, ArchDoc doc, ArchConnector c) {
|
||||
final String layer = _layerName(doc, c.layerId);
|
||||
final ArchConnGeometry g = archConnectorGeometry(doc, c);
|
||||
_polyline(sb, layer, g.pts, false);
|
||||
if (g.pts.length >= 2) {
|
||||
_solidArrow(sb, layer, g.pts[g.pts.length - 2], g.end);
|
||||
}
|
||||
if (c.label.isNotEmpty) {
|
||||
_text(sb, layer, c.label, g.label, 10.5);
|
||||
}
|
||||
}
|
||||
|
||||
// ===================== 实体 =====================
|
||||
|
||||
void _polyline(StringBuffer sb, String layer, List<Offset> pts, bool closed) {
|
||||
if (pts.length < 2) return;
|
||||
sb.write('0\nPOLYLINE\n8\n$layer\n66\n1\n70\n${closed ? 1 : 0}\n');
|
||||
for (final Offset p in pts) {
|
||||
sb.write('0\nVERTEX\n8\n$layer\n10\n${_n(p.dx)}\n20\n${_n(-p.dy)}\n'
|
||||
'30\n0\n');
|
||||
}
|
||||
sb.write('0\nSEQEND\n8\n$layer\n');
|
||||
}
|
||||
|
||||
void _circle(StringBuffer sb, String layer, Offset c, double r) {
|
||||
sb.write('0\nCIRCLE\n8\n$layer\n10\n${_n(c.dx)}\n20\n${_n(-c.dy)}\n30\n0\n'
|
||||
'40\n${_n(r)}\n');
|
||||
}
|
||||
|
||||
void _line(StringBuffer sb, String layer, Offset a, Offset b) {
|
||||
sb.write('0\nLINE\n8\n$layer\n10\n${_n(a.dx)}\n20\n${_n(-a.dy)}\n30\n0\n'
|
||||
'11\n${_n(b.dx)}\n21\n${_n(-b.dy)}\n31\n0\n');
|
||||
}
|
||||
|
||||
void _solidArrow(StringBuffer sb, String layer, Offset from, Offset to) {
|
||||
final Offset d = to - from;
|
||||
final double len = d.distance;
|
||||
if (len < 1) return;
|
||||
final Offset u = d / len;
|
||||
final Offset n = Offset(-u.dy, u.dx);
|
||||
const double hl = 11;
|
||||
const double hw = 5.5;
|
||||
final Offset p1 = to - u * hl + n * hw;
|
||||
final Offset p2 = to - u * hl - n * hw;
|
||||
sb.write('0\nSOLID\n8\n$layer\n'
|
||||
'10\n${_n(to.dx)}\n20\n${_n(-to.dy)}\n30\n0\n'
|
||||
'11\n${_n(p1.dx)}\n21\n${_n(-p1.dy)}\n31\n0\n'
|
||||
'12\n${_n(p2.dx)}\n22\n${_n(-p2.dy)}\n32\n0\n'
|
||||
'13\n${_n(p2.dx)}\n23\n${_n(-p2.dy)}\n33\n0\n');
|
||||
}
|
||||
|
||||
void _text(StringBuffer sb, String layer, String text, Offset center, double size) {
|
||||
final List<String> lines = text.split('\n');
|
||||
final double lh = size * 1.25;
|
||||
final double y0 = center.dy - (lines.length - 1) * lh / 2;
|
||||
for (int i = 0; i < lines.length; i++) {
|
||||
final double yy = y0 + i * lh;
|
||||
sb.write('0\nTEXT\n8\n$layer\n'
|
||||
'10\n${_n(center.dx)}\n20\n${_n(-yy)}\n30\n0\n'
|
||||
'40\n${_n(size)}\n1\n${_esc(lines[i])}\n'
|
||||
'72\n1\n73\n2\n'
|
||||
'11\n${_n(center.dx)}\n21\n${_n(-yy)}\n31\n0\n');
|
||||
}
|
||||
}
|
||||
|
||||
/// 沿路径按固定步长采样为折线(圆弧近似)。
|
||||
void _samplePath(StringBuffer sb, String layer, Path path,
|
||||
{required bool closed}) {
|
||||
final List<Offset> pts = <Offset>[];
|
||||
for (final PathMetric m in path.computeMetrics()) {
|
||||
final int count = math.max(4, (m.length / 6).ceil());
|
||||
for (int i = 0; i <= count; i++) {
|
||||
final Tangent? t = m.getTangentForOffset(m.length * i / count);
|
||||
if (t != null) pts.add(t.position);
|
||||
}
|
||||
}
|
||||
if (pts.length > 1 && (pts.first - pts.last).distance < 0.5) {
|
||||
pts.removeLast();
|
||||
}
|
||||
_polyline(sb, layer, pts, closed);
|
||||
}
|
||||
|
||||
/// 每条子路径各自输出一条折线(图元库符号:多段线互不相连,不能合并)。
|
||||
void _samplePathEach(StringBuffer sb, String layer, Path path) {
|
||||
for (final PathMetric m in path.computeMetrics()) {
|
||||
final int count = math.max(2, (m.length / 6).ceil());
|
||||
final List<Offset> pts = <Offset>[];
|
||||
for (int i = 0; i <= count; i++) {
|
||||
final Tangent? t = m.getTangentForOffset(m.length * i / count);
|
||||
if (t != null) pts.add(t.position);
|
||||
}
|
||||
if (pts.length > 1 && (pts.first - pts.last).distance < 0.5) {
|
||||
pts.removeLast();
|
||||
}
|
||||
_polyline(sb, layer, pts, m.isClosed);
|
||||
}
|
||||
}
|
||||
|
||||
// ===================== 工具 =====================
|
||||
|
||||
String _layerName(ArchDoc doc, String layerId) =>
|
||||
_name(doc.layerById(layerId).name);
|
||||
|
||||
/// 图层 / 实体名安全化(DXF 名称不允许空格等特殊字符)。
|
||||
String _name(String raw) {
|
||||
final String n = raw.replaceAll(RegExp(r'[^\w\u4e00-\u9fa5\-]'), '_');
|
||||
return n.isEmpty ? 'LAYER' : n;
|
||||
}
|
||||
|
||||
/// 颜色近似为 AutoCAD 颜色号(R12 兼容)。
|
||||
int _aci(int argb) {
|
||||
const List<(int, int)> table = <(int, int)>[
|
||||
(0xFF4CC9F0, 4),
|
||||
(0xFF34D399, 3),
|
||||
(0xFFFFD166, 2),
|
||||
(0xFFFF8A5C, 30),
|
||||
(0xFFF472B6, 6),
|
||||
(0xFFA78BFA, 200),
|
||||
(0xFF38BDF8, 5),
|
||||
(0xFF94A3B8, 8),
|
||||
(0xFF7C8DA6, 8),
|
||||
];
|
||||
final int r = (argb >> 16) & 0xFF;
|
||||
final int g = (argb >> 8) & 0xFF;
|
||||
final int b = argb & 0xFF;
|
||||
int best = 7;
|
||||
double bestD = double.infinity;
|
||||
for (final (int rgb, int aci) in table) {
|
||||
final int rr = (rgb >> 16) & 0xFF;
|
||||
final int gg = (rgb >> 8) & 0xFF;
|
||||
final int bb = rgb & 0xFF;
|
||||
final double d = ((r - rr) * (r - rr) +
|
||||
(g - gg) * (g - gg) +
|
||||
(b - bb) * (b - bb))
|
||||
.toDouble();
|
||||
if (d < bestD) {
|
||||
bestD = d;
|
||||
best = aci;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
String _n(double v) {
|
||||
if ((v - v.roundToDouble()).abs() < 0.005) return v.round().toString();
|
||||
return v.toStringAsFixed(2);
|
||||
}
|
||||
|
||||
String _esc(String s) => s.replaceAll('\n', ' ').replaceAll('\r', ' ');
|
||||
@@ -0,0 +1,607 @@
|
||||
/// 架构图导出:SVG(矢量,可直接进文档 / 二次编辑)与 PNG(3840×2160 位图)。
|
||||
///
|
||||
/// 与其他导出保持同一约定:
|
||||
/// - 导出始终使用**纯白背景**([exportTokens]),与屏幕主题无关;
|
||||
/// - PNG 画布固定 1920×1080 逻辑尺寸 × 2 倍像素;
|
||||
/// - 不导出网格点阵与选中框,只导出设计内容。
|
||||
library;
|
||||
|
||||
import 'dart:math' as math;
|
||||
import 'dart:typed_data';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:sequence_diagram/export/export_geometry.dart';
|
||||
import 'package:sequence_diagram/modules/architecture/library/symbol_library.dart';
|
||||
import 'package:sequence_diagram/theme/tokens.dart';
|
||||
import 'arch_models.dart';
|
||||
import 'arch_painter.dart';
|
||||
|
||||
// ===================== PNG =====================
|
||||
|
||||
/// 渲染架构图 PNG(3840×2160 位图)并返回字节。
|
||||
Future<Uint8List> renderArchPng({
|
||||
required ArchDoc doc,
|
||||
required Tokens baseTokens,
|
||||
required String projectName,
|
||||
}) async {
|
||||
final Tokens et = exportTokens(baseTokens);
|
||||
final ui.PictureRecorder recorder = ui.PictureRecorder();
|
||||
final Canvas canvas = Canvas(recorder);
|
||||
const double w = 1920;
|
||||
const double h = 1080;
|
||||
canvas.scale(kExportPixelRatio);
|
||||
canvas.drawRect(
|
||||
const Rect.fromLTWH(0, 0, w, h),
|
||||
Paint()..color = Colors.white,
|
||||
);
|
||||
|
||||
// 标题与副标题(固定左上角)。
|
||||
_text(canvas, '架构图设计', const Offset(48, 36),
|
||||
color: et.text, size: 34, weight: FontWeight.w700);
|
||||
_text(canvas, 'PDS流程设计套件 · Process Design Suite · 手绘识别架构图', const Offset(48, 88),
|
||||
color: et.sub, size: 16, weight: FontWeight.w400);
|
||||
|
||||
// 内容适配(白底令牌 + 关闭网格点阵)。
|
||||
final Rect b = doc.contentBounds().inflate(40);
|
||||
final ExportFit fit = _contentFit(b, kExportContentArea);
|
||||
canvas.save();
|
||||
canvas.translate(fit.tx, fit.ty);
|
||||
ArchPainter(
|
||||
doc: doc.copyWith(zoom: fit.scale, panX: 0, panY: 0, gridSize: 0),
|
||||
t: et,
|
||||
).paint(canvas, const Size(w, h));
|
||||
canvas.restore();
|
||||
|
||||
_text(
|
||||
canvas,
|
||||
'PDS流程设计套件 · 架构图设计 · $projectName · 元件 ${doc.shapes.length} · 连线 '
|
||||
'${doc.connectors.length} · 墨迹 ${doc.strokes.length}',
|
||||
Offset(48, h - 38),
|
||||
color: et.sub,
|
||||
size: 15,
|
||||
weight: FontWeight.w400,
|
||||
);
|
||||
|
||||
final ui.Image image = await recorder.endRecording().toImage(
|
||||
(w * kExportPixelRatio).toInt(),
|
||||
(h * kExportPixelRatio).toInt(),
|
||||
);
|
||||
final ByteData? data = await image.toByteData(format: ui.ImageByteFormat.png);
|
||||
return data!.buffer.asUint8List();
|
||||
}
|
||||
|
||||
/// 内容适配:等比缩放并居中到 [area]。
|
||||
ExportFit _contentFit(Rect bounds, Rect area) {
|
||||
if (bounds.width <= 1 || bounds.height <= 1) {
|
||||
return const ExportFit(1, 0, 0);
|
||||
}
|
||||
final double s = math
|
||||
.min(area.width / bounds.width, area.height / bounds.height)
|
||||
.clamp(0.1, 1.6)
|
||||
.toDouble();
|
||||
final double tx =
|
||||
area.left + (area.width - bounds.width * s) / 2 - bounds.left * s;
|
||||
final double ty =
|
||||
area.top + (area.height - bounds.height * s) / 2 - bounds.top * s;
|
||||
return ExportFit(s, tx, ty);
|
||||
}
|
||||
|
||||
/// 用统一字体绘制单行文本。
|
||||
void _text(
|
||||
Canvas canvas,
|
||||
String s,
|
||||
Offset at, {
|
||||
required Color color,
|
||||
required double size,
|
||||
required FontWeight weight,
|
||||
}) {
|
||||
final TextPainter tp = TextPainter(
|
||||
text: TextSpan(
|
||||
text: s,
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
fontSize: size,
|
||||
fontWeight: weight,
|
||||
fontFamily: 'Microsoft YaHei UI',
|
||||
fontFamilyFallback: const <String>[
|
||||
'Microsoft YaHei',
|
||||
'Noto Sans SC',
|
||||
'sans-serif',
|
||||
],
|
||||
),
|
||||
),
|
||||
textDirection: TextDirection.ltr,
|
||||
)..layout();
|
||||
tp.paint(canvas, Offset(at.dx, at.dy - tp.height / 2));
|
||||
}
|
||||
|
||||
// ===================== SVG =====================
|
||||
|
||||
/// 构造架构图 SVG 文本(viewBox = 内容范围 + 留白;纯白背景)。
|
||||
String buildArchSvg({required ArchDoc doc, required Tokens baseTokens}) {
|
||||
final Tokens t = exportTokens(baseTokens);
|
||||
final Rect b = doc.contentBounds().inflate(40);
|
||||
final double w = math.max(b.width, 200);
|
||||
final double h = math.max(b.height, 160);
|
||||
final StringBuffer sb = StringBuffer();
|
||||
sb.writeln('<?xml version="1.0" encoding="UTF-8"?>');
|
||||
sb.writeln(
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" width="${w.round()}" height="${h.round()}" '
|
||||
'viewBox="${_n(b.left)} ${_n(b.top)} ${_n(w)} ${_n(h)}">');
|
||||
sb.writeln('<rect x="${_n(b.left)}" y="${_n(b.top)}" width="${_n(w)}" height="${_n(h)}" fill="#ffffff"/>');
|
||||
|
||||
// 连线(底层)。
|
||||
for (final ArchConnector c in doc.connectors) {
|
||||
if (!doc.isLayerVisible(c.layerId)) continue;
|
||||
_svgConnector(sb, doc, c);
|
||||
}
|
||||
// 图形。
|
||||
for (final ArchShape s in doc.shapes) {
|
||||
if (!doc.isLayerVisible(s.layerId)) continue;
|
||||
_svgShape(sb, s, t);
|
||||
}
|
||||
// 手绘墨迹。
|
||||
for (final ArchStroke s in doc.strokes) {
|
||||
if (!doc.isLayerVisible(s.layerId)) continue;
|
||||
sb.writeln(
|
||||
'<path d="${_smoothD(s.pts)}" fill="none" stroke="${_hex(s.color)}" stroke-width="${_n(s.w)}" '
|
||||
'stroke-linecap="round" stroke-linejoin="round"/>');
|
||||
}
|
||||
sb.writeln('</svg>');
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/// 连线(含正交折线、虚线、箭头与标签)。
|
||||
void _svgConnector(StringBuffer sb, ArchDoc doc, ArchConnector c) {
|
||||
final ArchConnGeometry g = archConnectorGeometry(doc, c);
|
||||
final String d = _polyD(g.pts);
|
||||
final String color = _hex(c.color);
|
||||
final String dash = c.dash ? ' stroke-dasharray="8 6"' : '';
|
||||
sb.writeln(
|
||||
'<path d="$d" fill="none" stroke="$color" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"$dash/>');
|
||||
// 箭头(终点方向)。
|
||||
if (g.pts.length >= 2) {
|
||||
final Offset a = g.pts[g.pts.length - 2];
|
||||
final Offset b2 = g.end;
|
||||
final Offset dv = b2 - a;
|
||||
final double len = dv.distance;
|
||||
if (len > 1) {
|
||||
final Offset u = dv / len;
|
||||
final Offset n = Offset(-u.dy, u.dx);
|
||||
const double hl = 11;
|
||||
const double hw = 5.5;
|
||||
final Offset p1 = b2 - u * hl + n * hw;
|
||||
final Offset p2 = b2 - u * hl - n * hw;
|
||||
sb.writeln(
|
||||
'<polygon points="${_n(b2.dx)},${_n(b2.dy)} ${_n(p1.dx)},${_n(p1.dy)} ${_n(p2.dx)},${_n(p2.dy)}" fill="$color"/>');
|
||||
}
|
||||
}
|
||||
// 标签(白底片 + 文本)。
|
||||
if (c.label.isNotEmpty) {
|
||||
final double lw = math.max(20, c.label.length * 10.5 + 10);
|
||||
final Rect bg = Rect.fromCenter(center: g.label, width: lw, height: 18);
|
||||
sb.writeln(
|
||||
'<rect x="${_n(bg.left)}" y="${_n(bg.top)}" width="${_n(bg.width)}" height="${_n(bg.height)}" rx="5" '
|
||||
'fill="#ffffff" stroke="#c9d6e5" stroke-width="1"/>');
|
||||
sb.writeln(
|
||||
'<text x="${_n(g.label.dx)}" y="${_n(g.label.dy)}" text-anchor="middle" dominant-baseline="central" '
|
||||
'font-family="Microsoft YaHei UI" font-size="10.5" fill="${_hex(0xFF334155)}">${_esc(c.label)}</text>');
|
||||
}
|
||||
}
|
||||
|
||||
/// 单个标准图形。
|
||||
void _svgShape(StringBuffer sb, ArchShape s, Tokens t) {
|
||||
final String fill = _hex(s.fill);
|
||||
final String fillOp = _op(s.fill);
|
||||
final String stroke = _hex(s.stroke);
|
||||
final String sw = _n(s.sw);
|
||||
final Rect r = s.rect;
|
||||
switch (s.type) {
|
||||
case ArchShapeType.rect:
|
||||
sb.writeln(
|
||||
'<rect x="${_n(r.left)}" y="${_n(r.top)}" width="${_n(r.width)}" height="${_n(r.height)}" '
|
||||
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
break;
|
||||
case ArchShapeType.roundRect:
|
||||
final double rad = math.min(s.radius, math.min(r.width, r.height) * 0.45);
|
||||
sb.writeln(
|
||||
'<rect x="${_n(r.left)}" y="${_n(r.top)}" width="${_n(r.width)}" height="${_n(r.height)}" rx="${_n(rad)}" '
|
||||
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
break;
|
||||
case ArchShapeType.ellipse:
|
||||
case ArchShapeType.circle:
|
||||
sb.writeln(
|
||||
'<ellipse cx="${_n(r.center.dx)}" cy="${_n(r.center.dy)}" rx="${_n(r.width / 2)}" ry="${_n(r.height / 2)}" '
|
||||
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
break;
|
||||
case ArchShapeType.triangle:
|
||||
sb.writeln(
|
||||
'<polygon points="${_points(archTrianglePoints(s))}" fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
break;
|
||||
case ArchShapeType.diamond:
|
||||
sb.writeln(
|
||||
'<polygon points="${_points(archDiamondPoints(r))}" fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
break;
|
||||
case ArchShapeType.hexagon:
|
||||
sb.writeln(
|
||||
'<polygon points="${_points(archHexagonPoints(r))}" fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
break;
|
||||
case ArchShapeType.cylinder:
|
||||
final double ry = math.min(r.height * 0.20, r.width * 0.32);
|
||||
final double l = r.left;
|
||||
final double rt = r.right;
|
||||
final double tp = r.top;
|
||||
final double bt = r.bottom;
|
||||
// 柱体(含底部弧)。
|
||||
sb.writeln(
|
||||
'<path d="M ${_n(l)} ${_n(tp + ry)} L ${_n(l)} ${_n(bt - ry)} '
|
||||
'A ${_n(r.width / 2)} ${_n(ry)} 0 0 0 ${_n(rt)} ${_n(bt - ry)} '
|
||||
'L ${_n(rt)} ${_n(tp + ry)} Z" '
|
||||
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
// 顶盖(稍亮)。
|
||||
final double lidOp =
|
||||
math.min(1.0, (_opValue(s.fill) + 0.10));
|
||||
sb.writeln(
|
||||
'<ellipse cx="${_n(r.center.dx)}" cy="${_n(tp + ry)}" rx="${_n(r.width / 2)}" ry="${_n(ry)}" '
|
||||
'fill="$fill" fill-opacity="${lidOp.toStringAsFixed(3)}" stroke="$stroke" stroke-width="$sw"/>');
|
||||
break;
|
||||
case ArchShapeType.cloud:
|
||||
// 双层绘制:第一层带描边,第二层纯填充覆盖内部接缝 → 外轮廓保持描边。
|
||||
final List<Offset> circles = <Offset>[
|
||||
Offset(r.left + r.width * 0.24, r.top + r.height * 0.62),
|
||||
Offset(r.left + r.width * 0.42, r.top + r.height * 0.40),
|
||||
Offset(r.left + r.width * 0.64, r.top + r.height * 0.34),
|
||||
Offset(r.left + r.width * 0.82, r.top + r.height * 0.58),
|
||||
];
|
||||
final List<double> radii = <double>[
|
||||
r.height * 0.26,
|
||||
r.height * 0.30,
|
||||
r.height * 0.28,
|
||||
r.height * 0.24,
|
||||
];
|
||||
final Rect base = Rect.fromLTRB(
|
||||
r.left + r.width * 0.06,
|
||||
r.top + r.height * 0.55,
|
||||
r.right - r.width * 0.06,
|
||||
r.top + r.height * 0.86,
|
||||
);
|
||||
for (int pass = 0; pass < 2; pass++) {
|
||||
final bool strokePass = pass == 0;
|
||||
for (int i = 0; i < circles.length; i++) {
|
||||
sb.writeln(
|
||||
'<circle cx="${_n(circles[i].dx)}" cy="${_n(circles[i].dy)}" r="${_n(radii[i])}" '
|
||||
'fill="$fill" fill-opacity="$fillOp"'
|
||||
'${strokePass ? ' stroke="$stroke" stroke-width="$sw"' : ''}/>');
|
||||
}
|
||||
sb.writeln(
|
||||
'<rect x="${_n(base.left)}" y="${_n(base.top)}" width="${_n(base.width)}" height="${_n(base.height)}" '
|
||||
'rx="${_n(r.height * 0.22)}" fill="$fill" fill-opacity="$fillOp"'
|
||||
'${strokePass ? ' stroke="$stroke" stroke-width="$sw"' : ''}/>');
|
||||
}
|
||||
break;
|
||||
case ArchShapeType.server:
|
||||
case ArchShapeType.client:
|
||||
case ArchShapeType.mobile:
|
||||
case ArchShapeType.firewall:
|
||||
case ArchShapeType.netSwitch:
|
||||
case ArchShapeType.queue:
|
||||
_svgItShape(sb, s, r, fill, fillOp, stroke, sw);
|
||||
break;
|
||||
case ArchShapeType.symbol:
|
||||
_svgSymbol(sb, s, r, fill, fillOp, stroke, sw);
|
||||
break;
|
||||
case ArchShapeType.text:
|
||||
break;
|
||||
case ArchShapeType.line:
|
||||
final Offset a = s.a ?? r.topLeft;
|
||||
final Offset b2 = s.b ?? r.bottomRight;
|
||||
sb.writeln(
|
||||
'<line x1="${_n(a.dx)}" y1="${_n(a.dy)}" x2="${_n(b2.dx)}" y2="${_n(b2.dy)}" '
|
||||
'stroke="$stroke" stroke-width="${_n(s.sw)}" stroke-linecap="round"/>');
|
||||
if (s.arrow) {
|
||||
_svgArrow(sb, a, b2, stroke);
|
||||
}
|
||||
break;
|
||||
case ArchShapeType.polyline:
|
||||
if (s.pts.length >= 2) {
|
||||
sb.writeln(
|
||||
'<polyline points="${_points(s.pts)}" fill="none" stroke="$stroke" stroke-width="${_n(s.sw)}" '
|
||||
'stroke-linecap="round" stroke-linejoin="round"/>');
|
||||
}
|
||||
break;
|
||||
case ArchShapeType.curve:
|
||||
if (s.pts.length >= 2) {
|
||||
sb.writeln(
|
||||
'<path d="${_splineD(s.pts)}" fill="none" stroke="$stroke" stroke-width="${_n(s.sw)}" '
|
||||
'stroke-linecap="round" stroke-linejoin="round"/>');
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// 图内文字。
|
||||
if (s.text.isNotEmpty) {
|
||||
final String tc = s.type == ArchShapeType.text
|
||||
? _hex(s.stroke)
|
||||
: _hex(0xFF1B2740);
|
||||
double size = 12.5;
|
||||
if (s.type == ArchShapeType.text) {
|
||||
size = (s.rect.height * 0.72).clamp(10.0, 120.0).toDouble();
|
||||
}
|
||||
Offset center = s.rect.center;
|
||||
if (s.type == ArchShapeType.cloud) {
|
||||
center = center.translate(0, s.rect.height * 0.12);
|
||||
} else if (s.type == ArchShapeType.cylinder) {
|
||||
center = center.translate(
|
||||
0,
|
||||
math.min(s.rect.height * 0.20, s.rect.width * 0.32) * 0.8);
|
||||
} else if (s.type == ArchShapeType.client) {
|
||||
center = Offset(s.rect.center.dx, s.rect.top + s.rect.height * 0.32);
|
||||
} else if (s.type == ArchShapeType.netSwitch) {
|
||||
center = Offset(s.rect.center.dx, s.rect.top + s.rect.height * 0.30);
|
||||
}
|
||||
_svgMultilineText(sb, s.text, center.dx, center.dy, tc, size);
|
||||
}
|
||||
}
|
||||
|
||||
/// IT 图形(服务器 / PC / 移动端 / 防火墙 / 交换机 / 队列)的 SVG 绘制。
|
||||
void _svgItShape(StringBuffer sb, ArchShape s, Rect r, String fill,
|
||||
String fillOp, String stroke, String sw) {
|
||||
final double rad = switch (s.type) {
|
||||
ArchShapeType.server => math.min(12.0, math.min(r.width, r.height) * 0.12),
|
||||
ArchShapeType.client => math.min(10.0, r.height * 0.08),
|
||||
ArchShapeType.mobile => math.min(16.0, r.width * 0.22),
|
||||
ArchShapeType.firewall => math.min(6.0, r.height * 0.10),
|
||||
ArchShapeType.netSwitch => math.min(10.0, r.height * 0.20),
|
||||
ArchShapeType.queue => r.height * 0.5,
|
||||
_ => 0.0,
|
||||
};
|
||||
sb.writeln(
|
||||
'<rect x="${_n(r.left)}" y="${_n(r.top)}" width="${_n(r.width)}" height="${_n(r.height)}" rx="${_n(rad)}" '
|
||||
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
final String inner =
|
||||
'stroke="$stroke" stroke-width="${_n(math.max(1, s.sw * 0.7))}" stroke-linecap="round"';
|
||||
void hline(double y, double x0, double x1) {
|
||||
sb.writeln('<line x1="${_n(x0)}" y1="${_n(y)}" x2="${_n(x1)}" y2="${_n(y)}" $inner/>');
|
||||
}
|
||||
|
||||
void dot(double x, double y, double radius) {
|
||||
sb.writeln(
|
||||
'<circle cx="${_n(x)}" cy="${_n(y)}" r="${_n(radius)}" fill="$stroke" fill-opacity="0.85"/>');
|
||||
}
|
||||
|
||||
switch (s.type) {
|
||||
case ArchShapeType.server:
|
||||
for (int i = 1; i <= 3; i++) {
|
||||
final double y = r.top + r.height * i / 4;
|
||||
hline(y, r.left + r.width * 0.10, r.right - r.width * 0.10);
|
||||
}
|
||||
for (int i = 0; i < 4; i++) {
|
||||
dot(r.left + r.width * 0.16, r.top + r.height * (i + 0.5) / 4,
|
||||
math.min(2.4, r.width * 0.035));
|
||||
}
|
||||
case ArchShapeType.client:
|
||||
final Rect screen =
|
||||
Rect.fromLTWH(r.left, r.top, r.width, r.height * 0.72);
|
||||
sb.writeln(
|
||||
'<rect x="${_n(screen.left)}" y="${_n(screen.top)}" width="${_n(screen.width)}" height="${_n(screen.height)}" rx="${_n(math.min(8, screen.height * 0.12))}" fill="none" stroke="$stroke" stroke-width="$sw"/>');
|
||||
sb.writeln(
|
||||
'<line x1="${_n(r.center.dx)}" y1="${_n(screen.bottom)}" x2="${_n(r.center.dx)}" y2="${_n(r.bottom - r.height * 0.10)}" $inner/>');
|
||||
hline(r.bottom - r.height * 0.08, r.center.dx - r.width * 0.18,
|
||||
r.center.dx + r.width * 0.18);
|
||||
case ArchShapeType.mobile:
|
||||
hline(r.top + r.height * 0.055, r.center.dx - r.width * 0.14,
|
||||
r.center.dx + r.width * 0.14);
|
||||
hline(r.bottom - r.height * 0.05, r.center.dx - r.width * 0.12,
|
||||
r.center.dx + r.width * 0.12);
|
||||
case ArchShapeType.firewall:
|
||||
for (int i = 1; i < 3; i++) {
|
||||
hline(r.top + r.height * i / 3, r.left, r.right);
|
||||
}
|
||||
for (int i = 0; i < 3; i++) {
|
||||
final double y0 = r.top + r.height * i / 3;
|
||||
final double y1 = r.top + r.height * (i + 1) / 3;
|
||||
final double offset = i.isEven ? 0.5 : 0.25;
|
||||
for (double fx = offset; fx < 0.95; fx += 0.5) {
|
||||
final double x = r.left + r.width * fx;
|
||||
sb.writeln(
|
||||
'<line x1="${_n(x)}" y1="${_n(y0)}" x2="${_n(x)}" y2="${_n(y1)}" $inner/>');
|
||||
}
|
||||
}
|
||||
case ArchShapeType.netSwitch:
|
||||
final double size = math.min(r.height * 0.20, 8.0);
|
||||
for (int i = 0; i < 6; i++) {
|
||||
final double x = r.left + r.width * (0.10 + i * 0.135);
|
||||
sb.writeln(
|
||||
'<rect x="${_n(x)}" y="${_n(r.bottom - r.height * 0.42)}" width="${_n(size * 1.4)}" height="${_n(size)}" rx="1.5" fill="$stroke" fill-opacity="0.85"/>');
|
||||
}
|
||||
case ArchShapeType.queue:
|
||||
final double h = r.height * 0.30;
|
||||
for (int i = 0; i < 3; i++) {
|
||||
final double x = r.left + r.width * (0.30 + i * 0.18);
|
||||
sb.writeln(
|
||||
'<path d="M ${_n(x - h * 0.35)} ${_n(r.center.dy - h * 0.5)} L ${_n(x + h * 0.35)} ${_n(r.center.dy)} L ${_n(x - h * 0.35)} ${_n(r.center.dy + h * 0.5)}" fill="none" $inner/>');
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// 图元库符号的 SVG 绘制(按 100×100 归一化基元映射到矩形)。
|
||||
void _svgSymbol(StringBuffer sb, ArchShape s, Rect r, String fill,
|
||||
String fillOp, String stroke, String sw) {
|
||||
final LibSymbol? sym = SymbolCache.byId(s.symbolId);
|
||||
if (sym == null || s.symbolId.isEmpty) {
|
||||
sb.writeln(
|
||||
'<rect x="${_n(r.left)}" y="${_n(r.top)}" width="${_n(r.width)}" height="${_n(r.height)}" rx="6" '
|
||||
'fill="none" stroke="$stroke" stroke-width="$sw" stroke-dasharray="4 3"/>');
|
||||
return;
|
||||
}
|
||||
Offset p2(double x, double y) => symPt(x, y, r);
|
||||
final double rad = (r.width + r.height) / 2 / 100;
|
||||
for (final SymPrim p in sym.prims) {
|
||||
switch (p.kind) {
|
||||
case SymPrimKind.text:
|
||||
if (p.pts.length < 2 || p.label.isEmpty) break;
|
||||
final Offset tl = p2(p.pts[0], p.pts[1]);
|
||||
final double size =
|
||||
(r.height * 0.14).clamp(7.0, 18.0).toDouble();
|
||||
sb.writeln(
|
||||
'<text x="${_n(tl.dx)}" y="${_n(tl.dy)}" font-family="Microsoft YaHei UI" font-size="${_n(size)}" '
|
||||
'font-weight="600" fill="$stroke">${_esc(p.label)}</text>');
|
||||
case SymPrimKind.line:
|
||||
if (p.pts.length < 4) break;
|
||||
final Offset a = p2(p.pts[0], p.pts[1]);
|
||||
final Offset b = p2(p.pts[2], p.pts[3]);
|
||||
sb.writeln(
|
||||
'<line x1="${_n(a.dx)}" y1="${_n(a.dy)}" x2="${_n(b.dx)}" y2="${_n(b.dy)}" '
|
||||
'stroke="$stroke" stroke-width="$sw" stroke-linecap="round"/>');
|
||||
case SymPrimKind.polyline:
|
||||
if (p.pts.length < 4) break;
|
||||
final List<Offset> pts = <Offset>[
|
||||
for (int i = 0; i + 1 < p.pts.length; i += 2) p2(p.pts[i], p.pts[i + 1]),
|
||||
];
|
||||
sb.writeln(
|
||||
'<polyline points="${_points(pts)}" fill="none" stroke="$stroke" stroke-width="$sw" '
|
||||
'stroke-linecap="round" stroke-linejoin="round"/>');
|
||||
case SymPrimKind.circle:
|
||||
if (p.pts.length < 2) break;
|
||||
final Offset c = p2(p.pts[0], p.pts[1]);
|
||||
final double rr = p.r * rad;
|
||||
sb.writeln(
|
||||
'<circle cx="${_n(c.dx)}" cy="${_n(c.dy)}" r="${_n(rr)}" '
|
||||
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
case SymPrimKind.rect:
|
||||
if (p.pts.length < 4) break;
|
||||
final Offset tl = p2(p.pts[0], p.pts[1]);
|
||||
sb.writeln(
|
||||
'<rect x="${_n(tl.dx)}" y="${_n(tl.dy)}" width="${_n(p.pts[2] / 100 * r.width)}" height="${_n(p.pts[3] / 100 * r.height)}" '
|
||||
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
|
||||
case SymPrimKind.arc:
|
||||
if (p.pts.length < 2) break;
|
||||
final Offset c = p2(p.pts[0], p.pts[1]);
|
||||
final double rr = p.r * rad;
|
||||
final double a0 = p.startDeg * math.pi / 180;
|
||||
final double a1 = (p.startDeg + p.sweepDeg) * math.pi / 180;
|
||||
final Offset s0 =
|
||||
c + Offset(math.cos(a0) * rr, math.sin(a0) * rr);
|
||||
final Offset s1 =
|
||||
c + Offset(math.cos(a1) * rr, math.sin(a1) * rr);
|
||||
final int large = p.sweepDeg.abs() > 180 ? 1 : 0;
|
||||
final int sweep = p.sweepDeg >= 0 ? 1 : 0;
|
||||
sb.writeln(
|
||||
'<path d="M ${_n(s0.dx)} ${_n(s0.dy)} A ${_n(rr)} ${_n(rr)} 0 $large $sweep ${_n(s1.dx)} ${_n(s1.dy)}" '
|
||||
'fill="none" stroke="$stroke" stroke-width="$sw" stroke-linecap="round"/>');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 箭头头部(line 图形用)。
|
||||
void _svgArrow(StringBuffer sb, Offset a, Offset b, String color) {
|
||||
final Offset dv = b - a;
|
||||
final double len = dv.distance;
|
||||
if (len < 1) return;
|
||||
final Offset u = dv / len;
|
||||
final Offset n = Offset(-u.dy, u.dx);
|
||||
const double hl = 11;
|
||||
const double hw = 5.5;
|
||||
final Offset p1 = b - u * hl + n * hw;
|
||||
final Offset p2 = b - u * hl - n * hw;
|
||||
sb.writeln(
|
||||
'<polygon points="${_n(b.dx)},${_n(b.dy)} ${_n(p1.dx)},${_n(p1.dy)} ${_n(p2.dx)},${_n(p2.dy)}" fill="$color"/>');
|
||||
}
|
||||
|
||||
/// 多行居中文本(每行一个 tspan)。
|
||||
void _svgMultilineText(
|
||||
StringBuffer sb, String text, double cx, double cy, String color, double size) {
|
||||
final List<String> lines = text.split('\n');
|
||||
final double lineH = size * 1.25;
|
||||
final double startY = cy - (lines.length - 1) * lineH / 2;
|
||||
sb.writeln(
|
||||
'<text text-anchor="middle" dominant-baseline="central" font-family="Microsoft YaHei UI" '
|
||||
'font-size="${_n(size)}" font-weight="600" fill="$color">');
|
||||
for (int i = 0; i < lines.length; i++) {
|
||||
sb.writeln(
|
||||
'<tspan x="${_n(cx)}" y="${_n(startY + i * lineH)}">${_esc(lines[i])}</tspan>');
|
||||
}
|
||||
sb.writeln('</text>');
|
||||
}
|
||||
|
||||
// ===================== 工具 =====================
|
||||
|
||||
/// 数字格式化(最多 2 位小数、去掉多余 0)。
|
||||
String _n(double v) {
|
||||
if ((v - v.roundToDouble()).abs() < 0.005) return v.round().toString();
|
||||
return v.toStringAsFixed(2);
|
||||
}
|
||||
|
||||
/// ARGB → `#rrggbb`。
|
||||
String _hex(int argb) {
|
||||
final int rgb = argb & 0xFFFFFF;
|
||||
return '#${rgb.toRadixString(16).padLeft(6, '0')}';
|
||||
}
|
||||
|
||||
/// ARGB → 不透明度字符串。
|
||||
String _op(int argb) => _opValue(argb).toStringAsFixed(3);
|
||||
|
||||
/// ARGB → 不透明度值(0..1)。
|
||||
double _opValue(int argb) => ((argb >> 24) & 0xFF) / 255;
|
||||
|
||||
/// 点列表 → polygon points。
|
||||
String _points(List<Offset> pts) =>
|
||||
pts.map((Offset p) => '${_n(p.dx)},${_n(p.dy)}').join(' ');
|
||||
|
||||
/// 折线 d。
|
||||
String _polyD(List<Offset> pts) {
|
||||
if (pts.isEmpty) return '';
|
||||
final StringBuffer sb = StringBuffer('M ${_n(pts.first.dx)} ${_n(pts.first.dy)}');
|
||||
for (int i = 1; i < pts.length; i++) {
|
||||
sb.write(' L ${_n(pts[i].dx)} ${_n(pts[i].dy)}');
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/// 样条 d(Catmull-Rom → 三次贝塞尔,与画布绘制一致)。
|
||||
String _splineD(List<Offset> pts) {
|
||||
if (pts.isEmpty) return '';
|
||||
final StringBuffer sb = StringBuffer('M ${_n(pts.first.dx)} ${_n(pts.first.dy)}');
|
||||
if (pts.length == 2) {
|
||||
sb.write(' L ${_n(pts[1].dx)} ${_n(pts[1].dy)}');
|
||||
return sb.toString();
|
||||
}
|
||||
for (int i = 0; i < pts.length - 1; i++) {
|
||||
final Offset p0 = i == 0 ? pts[i] : pts[i - 1];
|
||||
final Offset p1 = pts[i];
|
||||
final Offset p2 = pts[i + 1];
|
||||
final Offset p3 = i + 2 < pts.length ? pts[i + 2] : pts[i + 1];
|
||||
final Offset c1 = p1 + (p2 - p0) / 6;
|
||||
final Offset c2 = p2 - (p3 - p1) / 6;
|
||||
sb.write(
|
||||
' C ${_n(c1.dx)} ${_n(c1.dy)} ${_n(c2.dx)} ${_n(c2.dy)} ${_n(p2.dx)} ${_n(p2.dy)}');
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/// 平滑墨迹 d(与画布 `archSmoothPath` 一致的二次贝塞尔)。
|
||||
String _smoothD(List<Offset> pts) {
|
||||
if (pts.isEmpty) return '';
|
||||
final StringBuffer sb = StringBuffer('M ${_n(pts.first.dx)} ${_n(pts.first.dy)}');
|
||||
if (pts.length == 2) {
|
||||
sb.write(' L ${_n(pts[1].dx)} ${_n(pts[1].dy)}');
|
||||
return sb.toString();
|
||||
}
|
||||
for (int i = 1; i < pts.length - 1; i++) {
|
||||
final Offset mid = (pts[i] + pts[i + 1]) / 2;
|
||||
sb.write(' Q ${_n(pts[i].dx)} ${_n(pts[i].dy)} ${_n(mid.dx)} ${_n(mid.dy)}');
|
||||
}
|
||||
sb.write(' L ${_n(pts.last.dx)} ${_n(pts.last.dy)}');
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/// XML 文本转义。
|
||||
String _esc(String s) => s
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"');
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,971 @@
|
||||
/// 手绘识别:把一笔自由曲线识别成标准图形(直线 / 箭头 / 矩形 / 圆角矩形 /
|
||||
/// 圆 / 椭圆 / 三角形 / 菱形 / 六边形)。
|
||||
///
|
||||
/// 设计目标:像 iOS 手写便签那样——随手画个大概,松手后自动「扶正」成标准
|
||||
/// 图形;识别不了的笔迹保留为墨迹(不丢内容)。
|
||||
///
|
||||
/// 算法概览(纯几何、无依赖、可单测):
|
||||
/// 1. 清洗 & 重采样成均匀点列;
|
||||
/// 2. 首尾距离判定「闭合 / 开放」;
|
||||
/// 3. 开放笔迹:直线拟合(含水平 / 垂直吸附)→ 箭头(箭杆直线 + 尖端折返);
|
||||
/// 4. 闭合笔迹:径向椭圆残差 + Douglas-Peucker 顶点化简 + 折点合并,
|
||||
/// 按顶点数分流(3 三角 / 4 矩形或菱形 / 6 六边形 / ≥7 或残差小 → 椭圆)。
|
||||
library;
|
||||
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui' show Offset, Rect;
|
||||
|
||||
import 'arch_models.dart';
|
||||
|
||||
/// 识别结果:标准图形类型 + 规范化几何。
|
||||
class ArchRecognition {
|
||||
/// 构造识别结果。
|
||||
const ArchRecognition({
|
||||
required this.type,
|
||||
required this.rect,
|
||||
this.radius = 0,
|
||||
this.dir = 0,
|
||||
this.a,
|
||||
this.b,
|
||||
this.arrow = false,
|
||||
this.pts,
|
||||
});
|
||||
|
||||
/// 图形类型(含 [ArchShapeType.line] 直线 / 箭头)。
|
||||
final ArchShapeType type;
|
||||
|
||||
/// 规范化后的外接矩形。
|
||||
final Rect rect;
|
||||
|
||||
/// 圆角半径([ArchShapeType.roundRect])。
|
||||
final double radius;
|
||||
|
||||
/// 三角形朝向:0 上 / 1 右 / 2 下 / 3 左。
|
||||
final int dir;
|
||||
|
||||
/// 直线起点。
|
||||
final Offset? a;
|
||||
|
||||
/// 直线终点。
|
||||
final Offset? b;
|
||||
|
||||
/// 是否为箭头(仅 [ArchShapeType.line])。
|
||||
final bool arrow;
|
||||
|
||||
/// 折线 / 曲线的通过点([ArchShapeType.polyline] / [ArchShapeType.curve])。
|
||||
final List<Offset>? pts;
|
||||
}
|
||||
|
||||
/// 识别一笔手绘:成功返回标准图形,失败返回 null(调用方保留墨迹)。
|
||||
ArchRecognition? recognizeArchStroke(List<Offset> raw) {
|
||||
final List<Offset> pts = _clean(raw);
|
||||
if (pts.length < 5) return null;
|
||||
final double len = _polyLength(pts);
|
||||
if (len < 18) return null;
|
||||
final Rect bb = _bounds(pts);
|
||||
if (math.max(bb.width, bb.height) < 14) return null;
|
||||
final double diag = math.sqrt(bb.width * bb.width + bb.height * bb.height);
|
||||
|
||||
// 单笔「圆柱」:柱体 + 顶盖两圈轮廓,路径长度显著大于外接矩形周长。
|
||||
final double gap = (pts.last - pts.first).distance;
|
||||
final double hullPer = 2 * (bb.width + bb.height);
|
||||
if (hullPer > 40 && len > hullPer * 1.38) {
|
||||
final List<List<Offset>> parts = _splitOnJumps(pts, diag);
|
||||
if (parts.length == 2) {
|
||||
final ArchRecognition? cyl = _cylinderFromParts(parts[0], parts[1]) ??
|
||||
_cylinderFromParts(parts[1], parts[0]);
|
||||
if (cyl != null) return cyl;
|
||||
}
|
||||
// 无内部跳变(顶盖起点与柱体起点重合)时:接近闭合即视为圆柱。
|
||||
if (gap <= 0.45 * diag) {
|
||||
return ArchRecognition(type: ArchShapeType.cylinder, rect: bb);
|
||||
}
|
||||
}
|
||||
|
||||
final bool closed = gap <= math.max(16, 0.22 * diag);
|
||||
if (closed) {
|
||||
if (math.min(bb.width, bb.height) < 10) return null;
|
||||
return _classifyClosed(pts, bb, diag);
|
||||
}
|
||||
return _classifyOpen(pts, len);
|
||||
}
|
||||
|
||||
/// 多笔合并识别(如:两笔画出的矩形、先画柱体再画顶盖的圆柱)。
|
||||
///
|
||||
/// 按端点最近邻串接各笔后走单笔识别管线;接缝过大(两笔相距太远)时放弃。
|
||||
ArchRecognition? recognizeArchStrokes(List<List<Offset>> strokes) {
|
||||
final List<List<Offset>> parts = <List<Offset>>[
|
||||
for (final List<Offset> s in strokes)
|
||||
if (_clean(s).length >= 4) _clean(s),
|
||||
];
|
||||
if (parts.isEmpty) return null;
|
||||
if (parts.length == 1) return recognizeArchStroke(parts.first);
|
||||
if (parts.length > 2) return null;
|
||||
final List<Offset> a = parts[0];
|
||||
final List<Offset> b = parts[1];
|
||||
final double g1 = (a.last - b.first).distance;
|
||||
final double g2 = (a.last - b.last).distance;
|
||||
final double g3 = (a.first - b.first).distance;
|
||||
final double g4 = (a.first - b.last).distance;
|
||||
List<Offset> merged;
|
||||
double gap;
|
||||
if (g1 <= g2 && g1 <= g3 && g1 <= g4) {
|
||||
merged = <Offset>[...a, ...b];
|
||||
gap = g1;
|
||||
} else if (g2 <= g3 && g2 <= g4) {
|
||||
merged = <Offset>[...a, ...b.reversed];
|
||||
gap = g2;
|
||||
} else if (g3 <= g4) {
|
||||
merged = <Offset>[...a.reversed, ...b];
|
||||
gap = g3;
|
||||
} else {
|
||||
merged = <Offset>[...a.reversed, ...b.reversed];
|
||||
gap = g4;
|
||||
}
|
||||
final Rect bb = _bounds(merged);
|
||||
final double diag = math.sqrt(bb.width * bb.width + bb.height * bb.height);
|
||||
if (gap > math.max(26.0, 0.30 * diag)) return null;
|
||||
return recognizeArchStroke(merged);
|
||||
}
|
||||
|
||||
/// 两个「部件」识别结果组合成圆柱(顶盖椭圆 + 柱体矩形,形状层面快速判定)。
|
||||
ArchRecognition? archCylinderFromRecognitions(
|
||||
ArchRecognition body,
|
||||
ArchRecognition lid,
|
||||
) {
|
||||
final bool bodyIsRect =
|
||||
body.type == ArchShapeType.rect || body.type == ArchShapeType.roundRect;
|
||||
final bool lidIsEllipse =
|
||||
lid.type == ArchShapeType.ellipse || lid.type == ArchShapeType.circle;
|
||||
if (!bodyIsRect || !lidIsEllipse) return null;
|
||||
final Rect br = body.rect;
|
||||
final Rect lr = lid.rect;
|
||||
final bool geomOk =
|
||||
(lr.center.dx - br.center.dx).abs() <= math.max(14, br.width * 0.20) &&
|
||||
(lr.width - br.width).abs() <= math.max(18, br.width * 0.38) &&
|
||||
lr.center.dy <= br.top + lr.height * 0.9 &&
|
||||
lr.bottom >= br.top - lr.height * 0.6;
|
||||
if (!geomOk) return null;
|
||||
return ArchRecognition(
|
||||
type: ArchShapeType.cylinder,
|
||||
rect: Rect.fromLTRB(
|
||||
math.min(lr.left, br.left),
|
||||
math.min(lr.top, br.top),
|
||||
math.max(lr.right, br.right),
|
||||
math.max(lr.bottom, br.bottom),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 按跳变(相邻点距离过大)把一笔拆成多段(单笔圆柱的柱体 + 顶盖)。
|
||||
List<List<Offset>> _splitOnJumps(List<Offset> pts, double diag) {
|
||||
final double thr = math.max(14.0, 0.18 * diag);
|
||||
final List<List<Offset>> parts = <List<Offset>>[];
|
||||
List<Offset> cur = <Offset>[pts.first];
|
||||
for (int i = 1; i < pts.length; i++) {
|
||||
if ((pts[i] - pts[i - 1]).distance > thr) {
|
||||
if (cur.length >= 4) parts.add(cur);
|
||||
cur = <Offset>[pts[i]];
|
||||
} else {
|
||||
cur.add(pts[i]);
|
||||
}
|
||||
}
|
||||
if (cur.length >= 4) parts.add(cur);
|
||||
return parts;
|
||||
}
|
||||
|
||||
/// 圆柱顶盖(扁椭圆)识别:放宽椭圆残差阈值(扁椭圆曲率大、抖动残差偏高),
|
||||
/// 只要「近椭圆」即可作为顶盖。
|
||||
ArchRecognition? _recognizeLid(List<Offset> lidPts) {
|
||||
final Rect lb = _bounds(lidPts);
|
||||
if (math.min(lb.width, lb.height) < 10) return null;
|
||||
final List<Offset> pts = _resample(lidPts, 72);
|
||||
final double res90 = _percentile(_ellipseResiduals(pts, lb), 0.90);
|
||||
if (res90 <= 0.24) return _ellipseFrom(lb);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// 两段轮廓组合成圆柱:一段是柱体(矩形类),一段是顶盖(椭圆类)。
|
||||
ArchRecognition? _cylinderFromParts(List<Offset> bodyPts, List<Offset> lidPts) {
|
||||
final Rect bb = _bounds(bodyPts);
|
||||
final double bd = math.sqrt(bb.width * bb.width + bb.height * bb.height);
|
||||
final Rect lb = _bounds(lidPts);
|
||||
final double ld = math.sqrt(lb.width * lb.width + lb.height * lb.height);
|
||||
final double gapB = (bodyPts.last - bodyPts.first).distance;
|
||||
final double gapL = (lidPts.last - lidPts.first).distance;
|
||||
if (math.min(bb.width, bb.height) < 12 || math.min(lb.width, lb.height) < 10) {
|
||||
return null;
|
||||
}
|
||||
if (gapB > math.max(20, 0.35 * bd) || gapL > math.max(20, 0.35 * ld)) {
|
||||
return null;
|
||||
}
|
||||
final ArchRecognition? lid = _recognizeLid(lidPts);
|
||||
if (lid == null ||
|
||||
(lid.type != ArchShapeType.ellipse && lid.type != ArchShapeType.circle)) {
|
||||
return null;
|
||||
}
|
||||
final ArchRecognition? body = _classifyClosed(bodyPts, bb, bd);
|
||||
final bool bodyRect = body != null &&
|
||||
(body.type == ArchShapeType.rect ||
|
||||
body.type == ArchShapeType.roundRect);
|
||||
if (!bodyRect && !_hasTwoSideEdges(bodyPts, bb)) return null;
|
||||
final Rect lr = lid.rect;
|
||||
final bool geomOk =
|
||||
(lr.center.dx - bb.center.dx).abs() <= math.max(14, bb.width * 0.20) &&
|
||||
(lr.width - bb.width).abs() <= math.max(18, bb.width * 0.38) &&
|
||||
lr.center.dy <= bb.top + lr.height * 0.9 &&
|
||||
lr.bottom >= bb.top - lr.height * 0.6;
|
||||
if (!geomOk) return null;
|
||||
return ArchRecognition(
|
||||
type: ArchShapeType.cylinder,
|
||||
rect: Rect.fromLTRB(
|
||||
math.min(lr.left, bb.left),
|
||||
math.min(lr.top, bb.top),
|
||||
math.max(lr.right, bb.right),
|
||||
math.max(lr.bottom, bb.bottom),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 柱体结构判定:左右两侧各有一条较长的竖直侧边(圆柱轮廓的必要条件)。
|
||||
bool _hasTwoSideEdges(List<Offset> bodyPts, Rect bb) {
|
||||
final double eps = math.max(3.0, 0.04 * math.min(bb.width, bb.height));
|
||||
double lMin = double.infinity, lMax = -double.infinity;
|
||||
double rMin = double.infinity, rMax = -double.infinity;
|
||||
for (final Offset p in bodyPts) {
|
||||
if ((p.dx - bb.left).abs() <= eps) {
|
||||
if (p.dy < lMin) lMin = p.dy;
|
||||
if (p.dy > lMax) lMax = p.dy;
|
||||
}
|
||||
if ((p.dx - bb.right).abs() <= eps) {
|
||||
if (p.dy < rMin) rMin = p.dy;
|
||||
if (p.dy > rMax) rMax = p.dy;
|
||||
}
|
||||
}
|
||||
final double lSpan = lMax - lMin;
|
||||
final double rSpan = rMax - rMin;
|
||||
return lSpan >= bb.height * 0.4 && rSpan >= bb.height * 0.4;
|
||||
}
|
||||
|
||||
/// 把识别结果转成标准图形(画布提交 / 示例场景共用)。
|
||||
ArchShape archShapeFromRecognition(
|
||||
ArchRecognition r, {
|
||||
required String id,
|
||||
required int color,
|
||||
String text = '',
|
||||
}) {
|
||||
if (r.type == ArchShapeType.line) {
|
||||
final Offset a = r.a ?? Offset.zero;
|
||||
final Offset b = r.b ?? Offset.zero;
|
||||
return ArchShape(
|
||||
id: id,
|
||||
type: ArchShapeType.line,
|
||||
rect: Rect.fromPoints(a, b),
|
||||
a: a,
|
||||
b: b,
|
||||
arrow: r.arrow,
|
||||
fill: 0,
|
||||
stroke: color,
|
||||
sw: 2.4,
|
||||
text: text,
|
||||
);
|
||||
}
|
||||
if (r.type == ArchShapeType.polyline || r.type == ArchShapeType.curve) {
|
||||
final List<Offset> pts = r.pts ?? const <Offset>[];
|
||||
return ArchShape(
|
||||
id: id,
|
||||
type: r.type,
|
||||
rect: r.rect,
|
||||
fill: 0,
|
||||
stroke: color,
|
||||
sw: 2.4,
|
||||
text: text,
|
||||
pts: pts,
|
||||
);
|
||||
}
|
||||
return ArchShape(
|
||||
id: id,
|
||||
type: r.type,
|
||||
rect: r.rect,
|
||||
radius: r.radius,
|
||||
dir: r.dir,
|
||||
fill: archFillOf(color),
|
||||
stroke: color,
|
||||
sw: 1.8,
|
||||
text: text,
|
||||
);
|
||||
}
|
||||
|
||||
// ===================== 开放笔迹:直线 / 箭头 =====================
|
||||
|
||||
/// 开放笔迹分类:先试直线(含水平/垂直吸附),再试箭头。
|
||||
ArchRecognition? _classifyOpen(List<Offset> pts, double len) {
|
||||
final Offset a = pts.first;
|
||||
final Offset b = pts.last;
|
||||
final double chord = (b - a).distance;
|
||||
|
||||
// 1) 直线:路径基本沿首尾弦推进,且最大偏距很小。
|
||||
if (chord >= 0.72 * len) {
|
||||
final double dev = _maxDeviation(pts, a, b);
|
||||
if (dev <= math.max(4.0, 0.075 * chord)) {
|
||||
return _line(a, b, arrow: false);
|
||||
}
|
||||
}
|
||||
|
||||
// 2) 箭头:离起点最远的点为箭尖;箭杆近似直线;尖端之后有明显折返
|
||||
// (手绘箭头的头部是一笔折返的「>」)。
|
||||
int tip = 0;
|
||||
double best = -1;
|
||||
for (int i = 0; i < pts.length; i++) {
|
||||
final double d = (pts[i] - a).distance;
|
||||
if (d > best) {
|
||||
best = d;
|
||||
tip = i;
|
||||
}
|
||||
}
|
||||
if (tip >= 2 && pts.length - 1 - tip >= 2) {
|
||||
final Offset t = pts[tip];
|
||||
final double shaft = best;
|
||||
if (shaft >= 0.5 * len && shaft >= 14) {
|
||||
final double shaftDev = _maxDeviation(pts.sublist(0, tip + 1), a, t);
|
||||
if (shaftDev <= math.max(4.0, 0.065 * shaft)) {
|
||||
final double headLen = len - _polyLength(pts.sublist(0, tip + 1));
|
||||
if (headLen <= 0.45 * len && headLen >= math.max(5.0, 0.035 * len)) {
|
||||
final Offset u = (t - a) / shaft;
|
||||
double minProj = shaft;
|
||||
for (int i = tip + 1; i < pts.length; i++) {
|
||||
final double pr = _dot(pts[i] - a, u);
|
||||
if (pr < minProj) minProj = pr;
|
||||
}
|
||||
if (minProj <= shaft - math.max(5.0, 0.065 * len)) {
|
||||
return _line(a, t, arrow: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3) 折线 / 曲线:既不是直线也不是箭头。
|
||||
return _classifyPolyOrCurve(pts, len);
|
||||
}
|
||||
|
||||
/// 折线 / 曲线分流:
|
||||
/// - 有集中的尖折点(折点转角大)→ 折线(近轴段自动扶正);
|
||||
/// - 平缓弯曲 → 曲线(样条通过点)。
|
||||
ArchRecognition? _classifyPolyOrCurve(List<Offset> pts, double len) {
|
||||
final Rect bb = _bounds(pts);
|
||||
final double diag =
|
||||
math.max(1, math.sqrt(bb.width * bb.width + bb.height * bb.height));
|
||||
final List<int> idx =
|
||||
_rdpIndices(pts, math.max(3.0, 0.03 * diag));
|
||||
final List<int> merged = _mergeOpen(pts, idx, 24);
|
||||
final List<Offset> v = <Offset>[for (final int i in merged) pts[i]];
|
||||
if (v.length < 2) return null;
|
||||
final double chord = (v.last - v.first).distance;
|
||||
if (v.length == 2) {
|
||||
// 轻微弯曲的笔迹:保留弧度成为曲线(不弯曲的早走直线分支了)。
|
||||
if (len >= chord * 1.015 && len <= chord * 2.2) {
|
||||
return ArchRecognition(
|
||||
type: ArchShapeType.curve,
|
||||
rect: _bounds(v),
|
||||
pts: v,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
double maxTurn = 0;
|
||||
for (int i = 1; i < v.length - 1; i++) {
|
||||
maxTurn = math.max(maxTurn, _turnDeg(v[i - 1], v[i], v[i + 1]));
|
||||
}
|
||||
// 优先级:直线 > 曲线 > 折线。只有「折点犀利 + 每段足够直」才判为折线;
|
||||
// 否则一律归为曲线(曲线识别优先)。
|
||||
if (maxTurn >= 55 && v.length <= 9 && _segmentsStraight(pts, v)) {
|
||||
final List<Offset> snapped = _snapAxisSegments(v, 12);
|
||||
return ArchRecognition(
|
||||
type: ArchShapeType.polyline,
|
||||
rect: _bounds(snapped),
|
||||
pts: snapped,
|
||||
);
|
||||
}
|
||||
// 平缓弯曲 → 曲线:用更粗的简化取「通过点」,保留动势。
|
||||
final List<int> idx2 = _rdpIndices(pts, math.max(5.0, 0.07 * diag));
|
||||
final List<Offset> cv = <Offset>[for (final int i in idx2) pts[i]];
|
||||
if (cv.length < 3) return null;
|
||||
return ArchRecognition(
|
||||
type: ArchShapeType.curve,
|
||||
rect: _bounds(cv),
|
||||
pts: cv,
|
||||
);
|
||||
}
|
||||
|
||||
/// 判断折点之间的每一段是否足够「直」:
|
||||
/// 直线段 → 折线候选;带明显弧度的段 → 归为曲线(曲线优先)。
|
||||
bool _segmentsStraight(List<Offset> pts, List<Offset> v) {
|
||||
if (v.length < 2) return false;
|
||||
final List<int> idx = <int>[];
|
||||
for (final Offset t in v) {
|
||||
int bestI = 0;
|
||||
double bestD = double.infinity;
|
||||
for (int i = 0; i < pts.length; i++) {
|
||||
final double d = (pts[i] - t).distance;
|
||||
if (d < bestD) {
|
||||
bestD = d;
|
||||
bestI = i;
|
||||
}
|
||||
}
|
||||
idx.add(bestI);
|
||||
}
|
||||
for (int i = 1; i < idx.length; i++) {
|
||||
if (idx[i] <= idx[i - 1]) return false;
|
||||
}
|
||||
for (int s = 0; s < idx.length - 1; s++) {
|
||||
final Offset a = pts[idx[s]];
|
||||
final Offset b = pts[idx[s + 1]];
|
||||
final double segLen = (b - a).distance;
|
||||
if (segLen < 6) continue;
|
||||
double maxDev = 0;
|
||||
for (int i = idx[s] + 1; i < idx[s + 1]; i++) {
|
||||
final double d = archDistToSegment(pts[i], a, b);
|
||||
if (d > maxDev) maxDev = d;
|
||||
}
|
||||
if (maxDev > math.max(3.5, segLen * 0.055)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// 把一段手画轨迹简化为折线顶点(连线轨迹识别用):
|
||||
/// RDP 抽稀 + 共线合并 + 近轴段扶正(±12° 吸附为水平 / 垂直)。
|
||||
List<Offset> simplifyArchPolyline(List<Offset> pts) {
|
||||
final List<Offset> clean = _clean(pts);
|
||||
if (clean.length < 2) return clean;
|
||||
final Rect b = _bounds(clean);
|
||||
final double diag = math.sqrt(b.width * b.width + b.height * b.height);
|
||||
final List<int> idx = _rdpIndices(clean, math.max(4.0, 0.035 * diag));
|
||||
final List<int> merged = _mergeOpen(clean, idx, 24);
|
||||
final List<Offset> v = <Offset>[for (final int i in merged) clean[i]];
|
||||
if (v.length < 2) return <Offset>[clean.first, clean.last];
|
||||
return _snapAxisSegments(v, 12);
|
||||
}
|
||||
|
||||
/// 合并共线折点(开放折线:只处理内部顶点)。
|
||||
List<int> _mergeOpen(List<Offset> pts, List<int> idx, double tolDeg) {
|
||||
final List<int> cur = List<int>.of(idx);
|
||||
bool changed = true;
|
||||
while (changed && cur.length > 2) {
|
||||
changed = false;
|
||||
for (int i = 1; i < cur.length - 1; i++) {
|
||||
if (_turnDeg(pts[cur[i - 1]], pts[cur[i]], pts[cur[i + 1]]) < tolDeg) {
|
||||
cur.removeAt(i);
|
||||
changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
|
||||
/// 近水平 / 垂直的折线段扶正(±[tolDeg] 内吸附为水平 / 垂直)。
|
||||
List<Offset> _snapAxisSegments(List<Offset> v, double tolDeg) {
|
||||
final List<Offset> out = List<Offset>.of(v);
|
||||
for (int i = 0; i < out.length - 1; i++) {
|
||||
final Offset d = out[i + 1] - out[i];
|
||||
if (d.distance < 0.001) continue;
|
||||
final double ang = math.atan2(d.dy, d.dx) * 180 / math.pi;
|
||||
double m = ang % 180;
|
||||
if (m > 90) m -= 180;
|
||||
final double devH = m.abs();
|
||||
final double devV = 90 - m.abs();
|
||||
if (devH <= tolDeg) {
|
||||
final double y = (out[i].dy + out[i + 1].dy) / 2;
|
||||
out[i] = Offset(out[i].dx, y);
|
||||
out[i + 1] = Offset(out[i + 1].dx, y);
|
||||
} else if (devV <= tolDeg) {
|
||||
final double x = (out[i].dx + out[i + 1].dx) / 2;
|
||||
out[i] = Offset(x, out[i].dy);
|
||||
out[i + 1] = Offset(x, out[i + 1].dy);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// 云判定:统计闭合曲线上的「凹口」段数(鼓包相接处方向反转)。
|
||||
///
|
||||
/// 矩形 / 圆角矩形 / 椭圆边界全程同向(凸),凹口数为 0;
|
||||
/// 云由多个鼓包拼接而成,凹口 ≥ 3。
|
||||
int _concaveRunCount(List<Offset> pts) {
|
||||
final int total = pts.length;
|
||||
if (total < 24) return 0;
|
||||
final int k = math.max(2, total ~/ 20);
|
||||
final List<double> turns = <double>[];
|
||||
for (int i = 0; i < total; i++) {
|
||||
final Offset a = pts[(i + k) % total] - pts[i];
|
||||
final Offset b = pts[(i + 2 * k) % total] - pts[(i + k) % total];
|
||||
final double la = a.distance;
|
||||
final double lb = b.distance;
|
||||
if (la < 0.001 || lb < 0.001) {
|
||||
turns.add(0);
|
||||
continue;
|
||||
}
|
||||
double s = (a.dx * b.dy - a.dy * b.dx) / (la * lb);
|
||||
s = s.clamp(-1.0, 1.0);
|
||||
turns.add(math.asin(s) * 180 / math.pi);
|
||||
}
|
||||
double totalTurn = 0;
|
||||
for (final double v in turns) {
|
||||
totalTurn += v;
|
||||
}
|
||||
final double dir = totalTurn >= 0 ? 1 : -1;
|
||||
int runs = 0;
|
||||
bool inRun = false;
|
||||
for (int i = 0; i < total * 2; i++) {
|
||||
final bool concave = turns[i % total] * dir < -10.0;
|
||||
if (concave && !inRun) {
|
||||
runs++;
|
||||
inRun = true;
|
||||
} else if (!concave) {
|
||||
inRun = false;
|
||||
}
|
||||
}
|
||||
return (runs / 2).round();
|
||||
}
|
||||
|
||||
/// 构造直线识别结果;方向接近水平 / 垂直(±8°)时吸附到正轴。
|
||||
ArchRecognition _line(Offset a, Offset b, {required bool arrow}) {
|
||||
Offset aa = a;
|
||||
Offset bb = b;
|
||||
final Offset d = b - a;
|
||||
if (d.distance > 0.001) {
|
||||
final double ang = math.atan2(d.dy, d.dx) * 180 / math.pi;
|
||||
double m = ang % 180;
|
||||
if (m > 90) m -= 180; // 归一化到 (-90, 90]:0 = 水平,±90 = 垂直
|
||||
final double devH = m.abs();
|
||||
final double devV = 90 - m.abs();
|
||||
if (devH <= 8) {
|
||||
final double y = (a.dy + b.dy) / 2;
|
||||
aa = Offset(a.dx, y);
|
||||
bb = Offset(b.dx, y);
|
||||
} else if (devV <= 8) {
|
||||
final double x = (a.dx + b.dx) / 2;
|
||||
aa = Offset(x, a.dy);
|
||||
bb = Offset(x, b.dy);
|
||||
}
|
||||
}
|
||||
return ArchRecognition(
|
||||
type: ArchShapeType.line,
|
||||
rect: Rect.fromPoints(aa, bb),
|
||||
a: aa,
|
||||
b: bb,
|
||||
arrow: arrow,
|
||||
);
|
||||
}
|
||||
|
||||
// ===================== 闭合笔迹:多边形 / 椭圆 =====================
|
||||
|
||||
/// 闭合笔迹分类:顶点数 + 椭圆残差(分位)+ 贴边率。
|
||||
ArchRecognition? _classifyClosed(List<Offset> raw, Rect bb, double diag) {
|
||||
final List<Offset> pts = _resample(raw, 72);
|
||||
final double res90 = _percentile(_ellipseResiduals(pts, bb), 0.90);
|
||||
final List<int> poly =
|
||||
_rdpIndices(pts, math.max(2.2, 0.016 * diag), closed: true);
|
||||
final List<int> merged = _mergeCollinear(
|
||||
pts,
|
||||
poly,
|
||||
13,
|
||||
math.max(3.0, 0.075 * diag),
|
||||
);
|
||||
final int n = merged.length;
|
||||
|
||||
// 顶点很少(光滑闭合曲线)→ 椭圆残差小则是圆 / 椭圆。
|
||||
if (n <= 2) {
|
||||
return res90 <= 0.15 ? _ellipseFrom(bb) : null;
|
||||
}
|
||||
|
||||
if (n >= 7) {
|
||||
if (res90 <= 0.15) return _ellipseFrom(bb);
|
||||
// 云:边界上有多个「凹口」(鼓包相接处);矩形类边界全凸、椭圆已排除。
|
||||
if (_concaveRunCount(pts) >= 3) {
|
||||
return ArchRecognition(type: ArchShapeType.cloud, rect: bb);
|
||||
}
|
||||
// 大圆角矩形会被化简出很多顶点:贴边率高 → 按矩形(含圆角)处理。
|
||||
if (_sideFit(pts, bb) >= 0.5) return _quadFromRect(pts, bb);
|
||||
return null;
|
||||
}
|
||||
if (n == 6) {
|
||||
if (res90 <= 0.15) return _ellipseFrom(bb);
|
||||
// 起笔 / 收笔接缝可能带来 1–2 个多余顶点,先尝试合并回四边形。
|
||||
final List<int>? quad = _tryMergeToQuad(pts, merged, 13);
|
||||
if (quad != null && _sideFit(pts, bb) >= 0.45) {
|
||||
return _quad(pts, bb, quad);
|
||||
}
|
||||
return ArchRecognition(type: ArchShapeType.hexagon, rect: bb);
|
||||
}
|
||||
if (n == 5) {
|
||||
final List<int>? quad = _tryMergeToQuad(pts, merged, 13);
|
||||
if (quad != null && _sideFit(pts, bb) >= 0.45) {
|
||||
return _quad(pts, bb, quad);
|
||||
}
|
||||
// 五边形等暂无对应标准图形:保留墨迹。
|
||||
return null;
|
||||
}
|
||||
if (n == 3) return _triangle(pts, bb, merged);
|
||||
return _quad(pts, bb, merged);
|
||||
}
|
||||
|
||||
/// 由外接矩形构造椭圆 / 圆(长短边接近时归一为圆)。
|
||||
ArchRecognition _ellipseFrom(Rect bb) {
|
||||
final double w = bb.width;
|
||||
final double h = bb.height;
|
||||
if (w > 0 && h > 0 && (w - h).abs() <= 0.18 * math.max(w, h)) {
|
||||
final double d = (w + h) / 2;
|
||||
return ArchRecognition(
|
||||
type: ArchShapeType.circle,
|
||||
rect: Rect.fromCenter(center: bb.center, width: d, height: d),
|
||||
);
|
||||
}
|
||||
return ArchRecognition(type: ArchShapeType.ellipse, rect: bb);
|
||||
}
|
||||
|
||||
/// 四顶点:按边方向判别矩形(含圆角矩形)与菱形。
|
||||
ArchRecognition? _quad(List<Offset> pts, Rect bb, List<int> merged) {
|
||||
final List<Offset> v = <Offset>[for (final int i in merged) pts[i]];
|
||||
double axisScore = 0;
|
||||
double diagScore = 0;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
final Offset e = v[(i + 1) % 4] - v[i];
|
||||
if (e.distance < 0.5) return null;
|
||||
final double ang = math.atan2(e.dy, e.dx) * 180 / math.pi;
|
||||
double m = ang % 90;
|
||||
if (m < 0) m += 90;
|
||||
final double b = math.min(m, 90 - m); // 与最近坐标轴的夹角(0..45)
|
||||
axisScore += b;
|
||||
diagScore += 45 - b;
|
||||
}
|
||||
if (axisScore > diagScore) {
|
||||
return ArchRecognition(type: ArchShapeType.diamond, rect: bb);
|
||||
}
|
||||
return _quadFromRect(pts, bb);
|
||||
}
|
||||
|
||||
/// 矩形系列:估计圆角半径(外接矩形四角到笔迹的最小距离 / 0.414),
|
||||
/// 明显圆角 → 圆角矩形。
|
||||
ArchRecognition _quadFromRect(List<Offset> pts, Rect bb) {
|
||||
final double minSide = math.min(bb.width, bb.height);
|
||||
final double r = _cornerRadiusFromBbox(pts, bb);
|
||||
if (r > math.max(9, 0.075 * minSide)) {
|
||||
return ArchRecognition(
|
||||
type: ArchShapeType.roundRect,
|
||||
rect: bb,
|
||||
radius: math.min(r, 0.45 * minSide),
|
||||
);
|
||||
}
|
||||
return ArchRecognition(type: ArchShapeType.rect, rect: bb);
|
||||
}
|
||||
|
||||
/// 三角形:最长边为底,把顶点吸附到外接矩形的对应边上(正三角 / 直角靠边)。
|
||||
ArchRecognition? _triangle(List<Offset> pts, Rect bb, List<int> merged) {
|
||||
final List<Offset> v = <Offset>[for (final int i in merged) pts[i]];
|
||||
double bestLen = -1;
|
||||
int baseI = 0;
|
||||
for (int i = 0; i < 3; i++) {
|
||||
final double d = (v[(i + 1) % 3] - v[i]).distance;
|
||||
if (d > bestLen) {
|
||||
bestLen = d;
|
||||
baseI = i;
|
||||
}
|
||||
}
|
||||
final Offset b0 = v[baseI];
|
||||
final Offset b1 = v[(baseI + 1) % 3];
|
||||
final Offset apex = v[(baseI + 2) % 3];
|
||||
final Offset baseMid = (b0 + b1) / 2;
|
||||
final bool horiz = (b1.dx - b0.dx).abs() >= (b1.dy - b0.dy).abs();
|
||||
if (horiz) {
|
||||
final bool up = apex.dy < baseMid.dy;
|
||||
final double baseY = up ? bb.bottom : bb.top;
|
||||
final double apexY = up ? bb.top : bb.bottom;
|
||||
return ArchRecognition(
|
||||
type: ArchShapeType.triangle,
|
||||
rect: Rect.fromLTRB(
|
||||
bb.left,
|
||||
math.min(apexY, baseY),
|
||||
bb.right,
|
||||
math.max(apexY, baseY),
|
||||
),
|
||||
dir: up ? 0 : 2,
|
||||
);
|
||||
}
|
||||
final bool left = apex.dx < baseMid.dx;
|
||||
final double baseX = left ? bb.right : bb.left;
|
||||
final double apexX = left ? bb.left : bb.right;
|
||||
return ArchRecognition(
|
||||
type: ArchShapeType.triangle,
|
||||
rect: Rect.fromLTRB(
|
||||
math.min(apexX, baseX),
|
||||
bb.top,
|
||||
math.max(apexX, baseX),
|
||||
bb.bottom,
|
||||
),
|
||||
dir: left ? 3 : 1,
|
||||
);
|
||||
}
|
||||
|
||||
// ===================== 几何工具 =====================
|
||||
|
||||
/// 椭圆残差列表:以 [bb] 为「拟合椭圆」,逐点计算归一化偏差。
|
||||
List<double> _ellipseResiduals(List<Offset> pts, Rect bb) {
|
||||
final double rx = bb.width / 2;
|
||||
final double ry = bb.height / 2;
|
||||
if (rx < 1 || ry < 1 || pts.isEmpty) return <double>[1];
|
||||
final List<double> out = <double>[];
|
||||
for (final Offset p in pts) {
|
||||
final double nx = (p.dx - bb.center.dx) / rx;
|
||||
final double ny = (p.dy - bb.center.dy) / ry;
|
||||
out.add((math.sqrt(nx * nx + ny * ny) - 1).abs());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// 分位数([q] 0..1)。
|
||||
double _percentile(List<double> values, double q) {
|
||||
if (values.isEmpty) return 1;
|
||||
final List<double> s = List<double>.of(values)..sort();
|
||||
final int idx = ((s.length - 1) * q).round().clamp(0, s.length - 1);
|
||||
return s[idx];
|
||||
}
|
||||
|
||||
/// 贴边率:笔迹点贴近外接矩形四条边的比例
|
||||
/// (区分「有直边的矩形」与「全曲线的椭圆」)。
|
||||
double _sideFit(List<Offset> pts, Rect bb) {
|
||||
if (pts.isEmpty) return 0;
|
||||
final double eps = math.max(4.0, 0.05 * math.min(bb.width, bb.height));
|
||||
int hit = 0;
|
||||
for (final Offset p in pts) {
|
||||
final double d = math.min(
|
||||
math.min((p.dy - bb.top).abs(), (p.dy - bb.bottom).abs()),
|
||||
math.min((p.dx - bb.left).abs(), (p.dx - bb.right).abs()),
|
||||
);
|
||||
if (d <= eps) hit++;
|
||||
}
|
||||
return hit / pts.length;
|
||||
}
|
||||
|
||||
/// 估计圆角半径:外接矩形四个角到笔迹的最小距离 / (√2−1)
|
||||
/// (90° 圆角弧线到尖角的距离恰为 0.414r),再减去手抖带来的基础偏差。
|
||||
double _cornerRadiusFromBbox(List<Offset> pts, Rect bb) {
|
||||
final List<Offset> corners = <Offset>[
|
||||
bb.topLeft,
|
||||
bb.topRight,
|
||||
bb.bottomRight,
|
||||
bb.bottomLeft,
|
||||
];
|
||||
double sum = 0;
|
||||
for (final Offset c in corners) {
|
||||
double dmin = double.infinity;
|
||||
for (final Offset p in pts) {
|
||||
final double d = (p - c).distance;
|
||||
if (d < dmin) dmin = d;
|
||||
}
|
||||
sum += dmin;
|
||||
}
|
||||
return math.max(0, (sum / 4) / 0.4142 - 3.5);
|
||||
}
|
||||
|
||||
/// 四边形的「与坐标轴 / 对角线贴合度」:各边到最近轴(0° / 90°)或
|
||||
/// 对角线(45°)的平均偏差(度)。越小越像矩形 / 菱形。
|
||||
double _quadDeviation(List<Offset> pts, List<int> quad) {
|
||||
final List<Offset> v = <Offset>[for (final int i in quad) pts[i]];
|
||||
double axis = 0;
|
||||
double diag = 0;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
final Offset e = v[(i + 1) % 4] - v[i];
|
||||
if (e.distance < 0.5) return double.infinity;
|
||||
final double ang = math.atan2(e.dy, e.dx) * 180 / math.pi;
|
||||
double m = ang % 90;
|
||||
if (m < 0) m += 90;
|
||||
final double b = math.min(m, 90 - m);
|
||||
axis += b;
|
||||
diag += 45 - b;
|
||||
}
|
||||
return math.min(axis, diag) / 4;
|
||||
}
|
||||
|
||||
/// 尝试把 5 / 6 个顶点合并成四边形(起笔 / 收笔接缝可能多出顶点):
|
||||
/// 暴力尝试删除 1–2 个顶点,取「最像四边形」的组合;偏差超限返回 null。
|
||||
List<int>? _tryMergeToQuad(List<Offset> pts, List<int> merged, double maxDev) {
|
||||
final int n = merged.length;
|
||||
if (n == 4) return merged;
|
||||
if (n < 4 || n > 6) return null;
|
||||
double best = maxDev;
|
||||
List<int>? bestSet;
|
||||
if (n == 5) {
|
||||
for (int i = 0; i < 5; i++) {
|
||||
final List<int> r = List<int>.of(merged)..removeAt(i);
|
||||
final double d = _quadDeviation(pts, r);
|
||||
if (d < best) {
|
||||
best = d;
|
||||
bestSet = r;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (int i = 0; i < 6; i++) {
|
||||
for (int j = i + 1; j < 6; j++) {
|
||||
final List<int> r = List<int>.of(merged)
|
||||
..removeAt(j)
|
||||
..removeAt(i);
|
||||
final double d = _quadDeviation(pts, r);
|
||||
if (d < best) {
|
||||
best = d;
|
||||
bestSet = r;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return bestSet;
|
||||
}
|
||||
|
||||
/// 最大偏距:所有点到直线 a–b 的距离最大值。
|
||||
double _maxDeviation(List<Offset> pts, Offset a, Offset b) {
|
||||
double m = 0;
|
||||
for (final Offset p in pts) {
|
||||
final double d = archDistToSegment(p, a, b);
|
||||
if (d > m) m = d;
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
/// 去掉间距过近的重复点。
|
||||
List<Offset> _clean(List<Offset> raw) {
|
||||
final List<Offset> out = <Offset>[];
|
||||
for (final Offset p in raw) {
|
||||
if (out.isEmpty || (p - out.last).distance > 0.6) out.add(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// 折线总长。
|
||||
double _polyLength(List<Offset> pts) {
|
||||
double s = 0;
|
||||
for (int i = 1; i < pts.length; i++) {
|
||||
s += (pts[i] - pts[i - 1]).distance;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/// 外接矩形。
|
||||
Rect _bounds(List<Offset> pts) {
|
||||
double l = pts.first.dx, r = l, t = pts.first.dy, b = t;
|
||||
for (final Offset p in pts) {
|
||||
if (p.dx < l) l = p.dx;
|
||||
if (p.dx > r) r = p.dx;
|
||||
if (p.dy < t) t = p.dy;
|
||||
if (p.dy > b) b = p.dy;
|
||||
}
|
||||
return Rect.fromLTRB(l, t, r, b);
|
||||
}
|
||||
|
||||
/// 重采样成 [n] 个均匀点(按弧长)。
|
||||
List<Offset> _resample(List<Offset> pts, int n) {
|
||||
final double len = _polyLength(pts);
|
||||
if (len <= 0.0001 || pts.length < 2) return List<Offset>.of(pts);
|
||||
final double step = len / (n - 1);
|
||||
final List<Offset> out = <Offset>[pts.first];
|
||||
double need = step;
|
||||
Offset prev = pts.first;
|
||||
for (int i = 1; i < pts.length && out.length < n; i++) {
|
||||
Offset cur = pts[i];
|
||||
double segLen = (cur - prev).distance;
|
||||
while (segLen >= need && segLen > 0.0001 && out.length < n) {
|
||||
final Offset np = prev + (cur - prev) * (need / segLen);
|
||||
out.add(np);
|
||||
prev = np;
|
||||
segLen = (cur - prev).distance;
|
||||
need = step;
|
||||
}
|
||||
need -= segLen;
|
||||
prev = cur;
|
||||
}
|
||||
while (out.length < n) {
|
||||
out.add(pts.last);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Douglas-Peucker 顶点索引([closed] 时把首点视为终点,去掉重复)。
|
||||
List<int> _rdpIndices(List<Offset> pts, double eps, {bool closed = false}) {
|
||||
final List<Offset> work =
|
||||
closed ? <Offset>[...pts, pts.first] : pts;
|
||||
final List<bool> keep = List<bool>.filled(work.length, false);
|
||||
keep[0] = true;
|
||||
keep[work.length - 1] = true;
|
||||
final List<List<int>> stack = <List<int>>[
|
||||
<int>[0, work.length - 1],
|
||||
];
|
||||
while (stack.isNotEmpty) {
|
||||
final List<int> seg = stack.removeLast();
|
||||
final int s = seg[0];
|
||||
final int e = seg[1];
|
||||
double maxD = 0;
|
||||
int idx = -1;
|
||||
for (int i = s + 1; i < e; i++) {
|
||||
final double d = archDistToSegment(work[i], work[s], work[e]);
|
||||
if (d > maxD) {
|
||||
maxD = d;
|
||||
idx = i;
|
||||
}
|
||||
}
|
||||
if (idx >= 0 && maxD > eps) {
|
||||
keep[idx] = true;
|
||||
stack.add(<int>[s, idx]);
|
||||
stack.add(<int>[idx, e]);
|
||||
}
|
||||
}
|
||||
final List<int> out = <int>[];
|
||||
for (int i = 0; i < work.length; i++) {
|
||||
if (keep[i]) out.add(i);
|
||||
}
|
||||
if (closed && out.isNotEmpty && out.last == work.length - 1) {
|
||||
out.removeLast();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// 合并近似共线的折点(也合并过短的边),直到稳定;最少保留 3 个顶点。
|
||||
List<int> _mergeCollinear(
|
||||
List<Offset> pts,
|
||||
List<int> idx,
|
||||
double tolDeg,
|
||||
double minSeg,
|
||||
) {
|
||||
final List<int> cur = List<int>.of(idx);
|
||||
bool changed = true;
|
||||
while (changed && cur.length > 3) {
|
||||
changed = false;
|
||||
final int n = cur.length;
|
||||
for (int i = 0; i < n; i++) {
|
||||
final Offset p = pts[cur[(i - 1 + n) % n]];
|
||||
final Offset v = pts[cur[i]];
|
||||
final Offset q = pts[cur[(i + 1) % n]];
|
||||
final double turn = _turnDeg(p, v, q);
|
||||
final bool tiny = (v - p).distance < minSeg || (q - v).distance < minSeg;
|
||||
if (turn < tolDeg || tiny) {
|
||||
cur.removeAt(i);
|
||||
changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
|
||||
/// 折点转向角(度):0 = 直线方向,90 = 直角折点。
|
||||
double _turnDeg(Offset p, Offset v, Offset q) {
|
||||
final Offset a = v - p;
|
||||
final Offset b = q - v;
|
||||
final double la = a.distance;
|
||||
final double lb = b.distance;
|
||||
if (la < 0.001 || lb < 0.001) return 0;
|
||||
final double c = (_dot(a, b) / (la * lb)).clamp(-1.0, 1.0);
|
||||
return math.acos(c) * 180 / math.pi;
|
||||
}
|
||||
|
||||
/// 点积(dart:ui 的 Offset 无 dot,自带实现)。
|
||||
double _dot(Offset a, Offset b) => a.dx * b.dx + a.dy * b.dy;
|
||||
@@ -0,0 +1,361 @@
|
||||
/// 架构图示例场景:自动化产线系统架构(手绘稿 / 完成图两种状态),
|
||||
/// 以及「手绘识别对照表」的素材(用于演示与截图)。
|
||||
///
|
||||
/// 「手绘稿」= 把每个标准图形的轮廓采样成带抖动的单笔墨迹 + 箭头墨迹;
|
||||
/// 「完成图」= 识别后的标准图形 + 吸附连线 + 标签文字。
|
||||
/// 两个场景共用同一套几何,保证演示「画 → 识别 → 成图」的完整链路。
|
||||
library;
|
||||
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui';
|
||||
|
||||
import 'arch_models.dart';
|
||||
import 'arch_painter.dart';
|
||||
|
||||
/// 示例场景种类。
|
||||
enum ArchDemoKind {
|
||||
/// 手绘稿(全部为墨迹,等待识别)。
|
||||
ink,
|
||||
|
||||
/// 完成图(标准图形 + 连线 + 文字)。
|
||||
done,
|
||||
}
|
||||
|
||||
/// 示例场景中的一个图形定义。
|
||||
class ArchDemoEntry {
|
||||
/// 构造图形定义。
|
||||
const ArchDemoEntry(
|
||||
this.id,
|
||||
this.type,
|
||||
this.rect,
|
||||
this.color,
|
||||
this.text, {
|
||||
this.radius = 0,
|
||||
this.dir = 0,
|
||||
});
|
||||
|
||||
/// 图形 id。
|
||||
final String id;
|
||||
|
||||
/// 图形类型。
|
||||
final ArchShapeType type;
|
||||
|
||||
/// 外接矩形(世界坐标)。
|
||||
final Rect rect;
|
||||
|
||||
/// 主题色。
|
||||
final int color;
|
||||
|
||||
/// 图内文字。
|
||||
final String text;
|
||||
|
||||
/// 圆角半径(圆角矩形)。
|
||||
final double radius;
|
||||
|
||||
/// 朝向(三角形)。
|
||||
final int dir;
|
||||
}
|
||||
|
||||
/// 示例场景中的一条连线定义。
|
||||
class ArchDemoConn {
|
||||
/// 构造连线定义。
|
||||
const ArchDemoConn(
|
||||
this.from,
|
||||
this.to,
|
||||
this.label, {
|
||||
this.dash = false,
|
||||
this.route = ArchRoute.straight,
|
||||
});
|
||||
|
||||
/// 起点图形 id。
|
||||
final String from;
|
||||
|
||||
/// 终点图形 id。
|
||||
final String to;
|
||||
|
||||
/// 连线标签。
|
||||
final String label;
|
||||
|
||||
/// 是否虚线。
|
||||
final bool dash;
|
||||
|
||||
/// 走线方式(直线 / 正交折线)。
|
||||
final ArchRoute route;
|
||||
}
|
||||
|
||||
/// 示例图形清单(两个场景共用)。
|
||||
List<ArchDemoEntry> archDemoEntries() => <ArchDemoEntry>[
|
||||
const ArchDemoEntry('S1', ArchShapeType.cloud,
|
||||
Rect.fromLTWH(620, 20, 250, 120), 0xFF94A3B8, '云平台 · 远程运维'),
|
||||
const ArchDemoEntry('S2', ArchShapeType.rect,
|
||||
Rect.fromLTWH(600, 186, 290, 78), 0xFF38BDF8, '组态上位机 (Windows)'),
|
||||
const ArchDemoEntry('S3', ArchShapeType.roundRect,
|
||||
Rect.fromLTWH(628, 310, 234, 66), 0xFFA78BFA, '工业交换机',
|
||||
radius: 16),
|
||||
const ArchDemoEntry('S4', ArchShapeType.rect,
|
||||
Rect.fromLTWH(595, 424, 300, 84), 0xFF4CC9F0, 'PLC 主站\n(EtherCAT)'),
|
||||
const ArchDemoEntry('S5', ArchShapeType.rect,
|
||||
Rect.fromLTWH(120, 438, 190, 76), 0xFF34D399, '视觉相机\nGigE'),
|
||||
const ArchDemoEntry('S6', ArchShapeType.roundRect,
|
||||
Rect.fromLTWH(1030, 438, 190, 76), 0xFFF472B6, 'IO 模块',
|
||||
radius: 14),
|
||||
const ArchDemoEntry('S7', ArchShapeType.rect,
|
||||
Rect.fromLTWH(540, 560, 240, 76), 0xFFFFD166, '伺服驱动器'),
|
||||
const ArchDemoEntry('S8', ArchShapeType.ellipse,
|
||||
Rect.fromLTWH(505, 706, 150, 96), 0xFF38BDF8, '伺服电机'),
|
||||
const ArchDemoEntry('S9', ArchShapeType.ellipse,
|
||||
Rect.fromLTWH(820, 706, 180, 96), 0xFF34D399, '气缸 / 传感器'),
|
||||
const ArchDemoEntry('S10', ArchShapeType.cylinder,
|
||||
Rect.fromLTWH(140, 690, 150, 130), 0xFFFF8A5C, '历史数据库'),
|
||||
];
|
||||
|
||||
/// 示例连线清单。
|
||||
List<ArchDemoConn> archDemoConns() => <ArchDemoConn>[
|
||||
const ArchDemoConn('S1', 'S2', '光纤 / 5G', dash: true),
|
||||
const ArchDemoConn('S2', 'S3', 'Profinet'),
|
||||
const ArchDemoConn('S3', 'S4', 'Profinet'),
|
||||
const ArchDemoConn('S4', 'S5', 'GigE', route: ArchRoute.ortho),
|
||||
const ArchDemoConn('S4', 'S7', 'EtherCAT'),
|
||||
const ArchDemoConn('S4', 'S6', 'EtherCAT'),
|
||||
const ArchDemoConn('S7', 'S8', '动力线'),
|
||||
const ArchDemoConn('S6', 'S9', '24V IO / 气路'),
|
||||
const ArchDemoConn('S4', 'S10', 'OPC UA', route: ArchRoute.ortho),
|
||||
];
|
||||
|
||||
/// 由定义构造标准图形。
|
||||
ArchShape _shapeOf(ArchDemoEntry e) => ArchShape(
|
||||
id: e.id,
|
||||
type: e.type,
|
||||
rect: e.rect,
|
||||
radius: e.radius,
|
||||
dir: e.dir,
|
||||
fill: archFillOf(e.color),
|
||||
stroke: e.color,
|
||||
sw: 1.8,
|
||||
text: e.text,
|
||||
);
|
||||
|
||||
/// 手绘稿场景:所有图形与连线的「原始墨迹」。
|
||||
ArchDoc archDemoInkScene() {
|
||||
final List<ArchStroke> strokes = <ArchStroke>[];
|
||||
final Map<String, ArchShape> byId = <String, ArchShape>{};
|
||||
int seed = 7;
|
||||
const int inkColor = 0xFF64748B;
|
||||
for (final ArchDemoEntry e in archDemoEntries()) {
|
||||
byId[e.id] = _shapeOf(e);
|
||||
final Path path = archShapePath(byId[e.id]!);
|
||||
final List<Offset> pts =
|
||||
archInkOutline(path, seed: seed++, jitter: 1.7, gapFrac: 0.07);
|
||||
if (pts.length > 4) {
|
||||
strokes.add(ArchStroke(
|
||||
id: 'K${strokes.length + 1}',
|
||||
pts: pts,
|
||||
color: inkColor,
|
||||
));
|
||||
}
|
||||
}
|
||||
for (final ArchDemoConn c in archDemoConns()) {
|
||||
final ArchShape f = byId[c.from]!;
|
||||
final ArchShape t = byId[c.to]!;
|
||||
final Offset a = archBorderPoint(f, t.rect.center);
|
||||
final Offset b = archBorderPoint(t, f.rect.center);
|
||||
final List<Offset> pts = _inkArrow(a, b, seed: seed++);
|
||||
if (pts.length > 6) {
|
||||
strokes.add(ArchStroke(
|
||||
id: 'K${strokes.length + 1}',
|
||||
pts: pts,
|
||||
color: inkColor,
|
||||
));
|
||||
}
|
||||
}
|
||||
return ArchDoc(strokes: strokes);
|
||||
}
|
||||
|
||||
/// 完成图场景:标准图形 + 吸附连线 + 标题。
|
||||
ArchDoc archDemoDoneScene() {
|
||||
final List<ArchShape> shapes = <ArchShape>[
|
||||
const ArchShape(
|
||||
id: 'T0',
|
||||
type: ArchShapeType.text,
|
||||
rect: Rect.fromLTWH(120, 40, 430, 40),
|
||||
fill: 0,
|
||||
stroke: 0xFF64748B,
|
||||
sw: 0,
|
||||
text: '自动化产线 · 系统架构(示例)',
|
||||
),
|
||||
for (final ArchDemoEntry e in archDemoEntries()) _shapeOf(e),
|
||||
];
|
||||
final Map<String, ArchShape> byId = <String, ArchShape>{
|
||||
for (final ArchShape s in shapes) s.id: s,
|
||||
};
|
||||
final List<ArchConnector> conns = <ArchConnector>[];
|
||||
for (final ArchDemoConn c in archDemoConns()) {
|
||||
final ArchShape f = byId[c.from]!;
|
||||
final ArchShape t = byId[c.to]!;
|
||||
conns.add(ArchConnector(
|
||||
id: 'C${conns.length + 1}',
|
||||
fromId: c.from,
|
||||
from: f.rect.center,
|
||||
toId: c.to,
|
||||
to: t.rect.center,
|
||||
label: c.label,
|
||||
dash: c.dash,
|
||||
route: c.route,
|
||||
));
|
||||
}
|
||||
return ArchDoc(shapes: shapes, connectors: conns);
|
||||
}
|
||||
|
||||
/// 「手绘识别对照表」素材:一组(标签, 手绘墨迹),供演示 / 截图逐个识别。
|
||||
List<(String, List<Offset>)> archRecognitionSheet() {
|
||||
final List<(String, List<Offset>)> out = <(String, List<Offset>)>[];
|
||||
int seed = 101;
|
||||
void addStroke(String label, List<Offset> pts) {
|
||||
out.add((label, pts));
|
||||
}
|
||||
|
||||
void addOutline(String label, ArchShape proto) {
|
||||
addStroke(
|
||||
label,
|
||||
archInkOutline(archShapePath(proto), seed: seed++, jitter: 1.8, gapFrac: 0.07),
|
||||
);
|
||||
}
|
||||
|
||||
ArchShape proto(ArchShapeType type, Rect r, {double radius = 0}) => ArchShape(
|
||||
id: 'x',
|
||||
type: type,
|
||||
rect: r,
|
||||
radius: radius,
|
||||
fill: 0,
|
||||
stroke: 0xFF64748B,
|
||||
sw: 1.8,
|
||||
);
|
||||
|
||||
addStroke('直线', _inkLine(const Offset(24, 128), const Offset(196, 66), seed: seed++));
|
||||
addStroke('箭头', _inkArrow(const Offset(24, 132), const Offset(196, 60), seed: seed++));
|
||||
addOutline('矩形', proto(ArchShapeType.rect, const Rect.fromLTWH(34, 30, 152, 104)));
|
||||
addOutline('圆角矩形',
|
||||
proto(ArchShapeType.roundRect, const Rect.fromLTWH(34, 30, 152, 104), radius: 22));
|
||||
addOutline('圆形', proto(ArchShapeType.circle, const Rect.fromLTWH(46, 26, 128, 128)));
|
||||
addOutline('椭圆', proto(ArchShapeType.ellipse, const Rect.fromLTWH(30, 42, 160, 92)));
|
||||
addOutline('三角形', proto(ArchShapeType.triangle, const Rect.fromLTWH(44, 26, 140, 118)));
|
||||
addOutline('菱形', proto(ArchShapeType.diamond, const Rect.fromLTWH(30, 32, 160, 108)));
|
||||
addStroke(
|
||||
'折线',
|
||||
archInkOutline(
|
||||
Path()
|
||||
..moveTo(26, 30)
|
||||
..lineTo(26, 96)
|
||||
..lineTo(118, 96)
|
||||
..lineTo(118, 142)
|
||||
..lineTo(196, 142),
|
||||
seed: seed++,
|
||||
jitter: 1.5,
|
||||
gapFrac: 0,
|
||||
),
|
||||
);
|
||||
addStroke(
|
||||
'曲线',
|
||||
archInkOutline(
|
||||
Path()
|
||||
..moveTo(24, 122)
|
||||
..cubicTo(62, 36, 138, 150, 198, 62),
|
||||
seed: seed++,
|
||||
jitter: 1.7,
|
||||
gapFrac: 0,
|
||||
),
|
||||
);
|
||||
return out;
|
||||
}
|
||||
|
||||
// ===================== 墨迹采样 =====================
|
||||
|
||||
/// 沿路径采样成一段带抖动的「手绘墨迹」([gapFrac] 为收笔缺口占比)。
|
||||
List<Offset> archInkOutline(
|
||||
Path path, {
|
||||
required int seed,
|
||||
double jitter = 1.7,
|
||||
double gapFrac = 0.07,
|
||||
}) {
|
||||
final List<PathMetric> metrics = path.computeMetrics().toList();
|
||||
double total = 0;
|
||||
for (final PathMetric m in metrics) {
|
||||
total += m.length;
|
||||
}
|
||||
if (total < 10) return <Offset>[];
|
||||
final math.Random rnd = math.Random(seed);
|
||||
final List<Offset> out = <Offset>[];
|
||||
final double stop = total * (1 - gapFrac);
|
||||
final double step = math.max(3.0, total / 260);
|
||||
double walked = 0;
|
||||
for (final PathMetric m in metrics) {
|
||||
double d = 0;
|
||||
while (d < m.length && walked < stop) {
|
||||
final Tangent? tan = m.getTangentForOffset(d);
|
||||
if (tan != null) {
|
||||
final Offset dir = tan.vector;
|
||||
final Offset nrm = Offset(-dir.dy, dir.dx);
|
||||
final double j = (rnd.nextDouble() * 2 - 1) * jitter +
|
||||
math.sin(d * 0.045 + seed) * jitter * 0.6;
|
||||
out.add(tan.position + nrm * j);
|
||||
}
|
||||
d += step;
|
||||
walked += step;
|
||||
}
|
||||
if (walked >= stop) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// 采样一段直线墨迹。
|
||||
List<Offset> _inkLine(Offset a, Offset b, {int seed = 1, double jitter = 1.2}) {
|
||||
final math.Random rnd = math.Random(seed);
|
||||
final List<Offset> out = <Offset>[];
|
||||
final Offset d = b - a;
|
||||
final double len = d.distance;
|
||||
if (len < 4) return out;
|
||||
final Offset u = d / len;
|
||||
final Offset n = Offset(-u.dy, u.dx);
|
||||
for (double t = 0; t <= len - 3; t += 6) {
|
||||
out.add(a + u * t + n * ((rnd.nextDouble() * 2 - 1) * jitter));
|
||||
}
|
||||
out.add(b);
|
||||
return out;
|
||||
}
|
||||
|
||||
/// 采样一段单笔箭头墨迹:箭杆 + 尖端折返的「>」形头部。
|
||||
List<Offset> _inkArrow(Offset a, Offset b, {int seed = 1, double jitter = 1.2}) {
|
||||
final math.Random rnd = math.Random(seed);
|
||||
final List<Offset> out = <Offset>[];
|
||||
final Offset d = b - a;
|
||||
final double len = d.distance;
|
||||
if (len < 36) return out;
|
||||
final Offset u = d / len;
|
||||
final Offset n = Offset(-u.dy, u.dx);
|
||||
// 箭杆
|
||||
for (double t = 0; t <= len - 4; t += 7) {
|
||||
out.add(a + u * t + n * ((rnd.nextDouble() * 2 - 1) * jitter));
|
||||
}
|
||||
// 头部:尖端 → 左后 → 右后(同一笔完成)
|
||||
final double hs = math.min(40, len * 0.18);
|
||||
final Offset p1 = b + _rot(u, 155) * hs;
|
||||
final Offset p2 = b + _rot(u, -155) * hs;
|
||||
final Offset mid = (p1 + p2) / 2;
|
||||
const int seg = 4;
|
||||
for (int i = 1; i <= seg; i++) {
|
||||
out.add(Offset.lerp(b, p1, i / seg)! + n * ((rnd.nextDouble() * 2 - 1) * jitter * 0.5));
|
||||
}
|
||||
for (int i = 1; i <= seg; i++) {
|
||||
out.add(i <= 2
|
||||
? Offset.lerp(p1, mid, i / 2)!
|
||||
: Offset.lerp(mid, p2, (i - 2) / (seg - 2))!);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// 向量旋转(度)。
|
||||
Offset _rot(Offset v, double deg) {
|
||||
final double r = deg * math.pi / 180;
|
||||
return Offset(v.dx * math.cos(r) - v.dy * math.sin(r),
|
||||
v.dx * math.sin(r) + v.dy * math.cos(r));
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
/// 手绘识别 · 图元库匹配。
|
||||
///
|
||||
/// 把笔迹(可多笔,顺序无关)与图元库每个符号的轮廓做「归一化双向
|
||||
/// chamfer 距离」匹配,返回最相似的图元。
|
||||
///
|
||||
/// 与内置识别的关系:内置识别(矩形 / 圆 / 箭头 / 折线…)优先且保持不变;
|
||||
/// **内置识别不了的笔迹再走本匹配器**——因此「图元库可扩展」等价于
|
||||
/// 「能手绘识别的图形可扩展」:用户导入 / 自建的图元也能被画出来识别。
|
||||
library;
|
||||
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui' show Offset, Path, PathMetric, Rect, Tangent;
|
||||
|
||||
import 'package:sequence_diagram/modules/architecture/library/symbol_library.dart';
|
||||
|
||||
/// 图元匹配结果。
|
||||
class ArchSymbolMatch {
|
||||
/// 构造。
|
||||
const ArchSymbolMatch({required this.symbol, required this.score});
|
||||
|
||||
/// 命中的图元。
|
||||
final LibSymbol symbol;
|
||||
|
||||
/// 双向 chamfer 平均距离(归一化坐标 0..1,越小越像)。
|
||||
final double score;
|
||||
}
|
||||
|
||||
/// 识别阈值(归一化单位):匹配分数大于该值视为「都不像」。
|
||||
///
|
||||
/// 标定依据(合成笔迹回归):真命中 0.006–0.03(接地 0.006 / 灯 0.013 /
|
||||
/// 自定义图元≈0.01),乱涂 / 斜线等假命中 ≥0.07;取 0.06 保守稳妥。
|
||||
const double kArchSymbolMaxScore = 0.06;
|
||||
|
||||
/// 最佳与次佳的分数差下限:相差太小说明特征不明显,宁可不错认。
|
||||
/// (灯 vs 电机 这类相似图形差约 0.010;取 0.008 兼顾召回与精度。)
|
||||
const double kArchSymbolMargin = 0.008;
|
||||
|
||||
/// 识别笔迹(多笔按点集合并)。
|
||||
ArchSymbolMatch? recognizeArchSymbol(
|
||||
List<List<Offset>> strokes,
|
||||
List<LibSymbol> catalog, {
|
||||
double maxScore = kArchSymbolMaxScore,
|
||||
double margin = kArchSymbolMargin,
|
||||
int inputSamples = 96,
|
||||
int refSamples = 128,
|
||||
}) {
|
||||
// 每笔独立重采样(避免笔与笔之间产生"跳线"污染),按各笔长度分配采样数。
|
||||
final List<List<Offset>> parts = <List<Offset>>[];
|
||||
final List<double> lens = <double>[];
|
||||
double total = 0;
|
||||
for (final List<Offset> s in strokes) {
|
||||
if (s.length < 2) continue;
|
||||
double len = 0;
|
||||
for (int i = 1; i < s.length; i++) {
|
||||
len += (s[i] - s[i - 1]).distance;
|
||||
}
|
||||
if (len < 1e-6) continue;
|
||||
parts.add(s);
|
||||
lens.add(len);
|
||||
total += len;
|
||||
}
|
||||
if (parts.isEmpty || total < 1e-6 || catalog.isEmpty) return null;
|
||||
final List<Offset> pts = <Offset>[];
|
||||
for (int i = 0; i < parts.length; i++) {
|
||||
final int count = math.max(4, (inputSamples * lens[i] / total).round());
|
||||
pts.addAll(_resample(parts[i], count));
|
||||
}
|
||||
if (pts.length < 4) return null;
|
||||
final _Np input = _Np.of(pts);
|
||||
if (input.extent < 1e-6) return null;
|
||||
|
||||
// 多尺度:手绘大小 / 完整度与图元不完全一致(少画一笔、比例不同都要容忍),
|
||||
// 对输入做几档缩放,取最像的一档。
|
||||
const List<double> scales = <double>[0.7, 0.85, 1.0, 1.2, 1.45];
|
||||
final List<List<Offset>> scaled = <List<Offset>>[
|
||||
for (final double s in scales)
|
||||
<Offset>[for (final Offset p in input.pts) p * s],
|
||||
];
|
||||
|
||||
ArchSymbolMatch? best;
|
||||
double second = double.infinity;
|
||||
for (final LibSymbol sym in catalog) {
|
||||
final List<Offset> refPts = _sampleSymbol(sym, refSamples);
|
||||
if (refPts.length < 4) continue;
|
||||
final _Np ref = _Np.of(refPts);
|
||||
if (ref.extent < 1e-6) continue;
|
||||
double score = double.infinity;
|
||||
for (final List<Offset> sp in scaled) {
|
||||
final double sc = _chamfer(sp, ref.pts);
|
||||
if (sc < score) score = sc;
|
||||
}
|
||||
if (best == null || score < best.score) {
|
||||
second = best?.score ?? second;
|
||||
best = ArchSymbolMatch(symbol: sym, score: score);
|
||||
} else if (score < second) {
|
||||
second = score;
|
||||
}
|
||||
}
|
||||
if (best == null) return null;
|
||||
if (best.score > maxScore) return null;
|
||||
if (second.isFinite && second - best.score < margin) return null;
|
||||
return best;
|
||||
}
|
||||
|
||||
// ===================== 内部实现 =====================
|
||||
|
||||
/// 归一化点集:中心化 + 按最大边缩放(对平移 / 缩放不敏感)。
|
||||
class _Np {
|
||||
const _Np(this.pts, this.extent);
|
||||
|
||||
final List<Offset> pts;
|
||||
final double extent;
|
||||
|
||||
static _Np of(List<Offset> pts) {
|
||||
if (pts.isEmpty) return const _Np(<Offset>[], 0);
|
||||
double l = pts.first.dx, r = l, t = pts.first.dy, b = t;
|
||||
for (final Offset p in pts) {
|
||||
if (p.dx < l) l = p.dx;
|
||||
if (p.dx > r) r = p.dx;
|
||||
if (p.dy < t) t = p.dy;
|
||||
if (p.dy > b) b = p.dy;
|
||||
}
|
||||
final double ext = math.max(r - l, b - t);
|
||||
if (ext < 1e-6) return _Np(List<Offset>.filled(pts.length, Offset.zero), 0);
|
||||
final Offset c = Offset((l + r) / 2, (t + b) / 2);
|
||||
return _Np(<Offset>[
|
||||
for (final Offset p in pts)
|
||||
Offset((p.dx - c.dx) / ext, (p.dy - c.dy) / ext),
|
||||
], ext);
|
||||
}
|
||||
}
|
||||
|
||||
/// 按弧长均匀重采样折线到 [n] 个点。
|
||||
List<Offset> _resample(List<Offset> pts, int n) {
|
||||
if (pts.length <= 1) return List<Offset>.of(pts);
|
||||
double total = 0;
|
||||
for (int i = 1; i < pts.length; i++) {
|
||||
total += (pts[i] - pts[i - 1]).distance;
|
||||
}
|
||||
if (total < 1e-6) return <Offset>[pts.first];
|
||||
final List<Offset> out = <Offset>[pts.first];
|
||||
int seg = 0;
|
||||
double acc = 0;
|
||||
double segLen = (pts[1] - pts[0]).distance;
|
||||
for (int i = 1; i < n; i++) {
|
||||
final double target = total * i / (n - 1);
|
||||
while (acc + segLen < target && seg < pts.length - 2) {
|
||||
acc += segLen;
|
||||
seg++;
|
||||
segLen = (pts[seg + 1] - pts[seg]).distance;
|
||||
}
|
||||
final double rest = target - acc;
|
||||
final double t = segLen <= 1e-9 ? 0 : (rest / segLen).clamp(0.0, 1.0);
|
||||
out.add(Offset.lerp(pts[seg], pts[seg + 1], t)!);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// 采样图元轮廓(在 100×100 归一化盒内按各子路径长度分配采样点)。
|
||||
List<Offset> _sampleSymbol(LibSymbol sym, int n) {
|
||||
final Path path = buildSymbolPath(sym, const Rect.fromLTWH(0, 0, 100, 100));
|
||||
final List<PathMetric> metrics = path.computeMetrics().toList();
|
||||
double total = 0;
|
||||
for (final PathMetric m in metrics) {
|
||||
total += m.length;
|
||||
}
|
||||
if (total < 1e-6) return const <Offset>[];
|
||||
final List<Offset> out = <Offset>[];
|
||||
for (final PathMetric m in metrics) {
|
||||
final int count = math.max(2, (n * m.length / total).round());
|
||||
for (int i = 0; i <= count; i++) {
|
||||
final Tangent? t = m.getTangentForOffset(m.length * i / count);
|
||||
if (t != null) out.add(t.position);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// 双向 chamfer 平均距离。
|
||||
double _chamfer(List<Offset> a, List<Offset> b) {
|
||||
double d1 = 0;
|
||||
for (final Offset p in a) {
|
||||
d1 += _nearest(p, b);
|
||||
}
|
||||
d1 /= a.length;
|
||||
double d2 = 0;
|
||||
for (final Offset p in b) {
|
||||
d2 += _nearest(p, a);
|
||||
}
|
||||
d2 /= b.length;
|
||||
return (d1 + d2) / 2;
|
||||
}
|
||||
|
||||
double _nearest(Offset p, List<Offset> pts) {
|
||||
double best = double.infinity;
|
||||
for (final Offset q in pts) {
|
||||
final double d = (p - q).distanceSquared;
|
||||
if (d < best) best = d;
|
||||
}
|
||||
return math.sqrt(best);
|
||||
}
|
||||
@@ -0,0 +1,557 @@
|
||||
/// 图元库(内置图形图元)数据层。
|
||||
///
|
||||
/// - 内置符号:[SymbolLibrary.builtin],随安装包发布(只读,代码内定义);
|
||||
/// - 坐标约定:符号在 **100×100 归一化画布** 内绘制((0,0) 左上、(100,100)
|
||||
/// 右下),引脚 [SymPin] 位于边界附近;实际绘制时按目标矩形等比换算;
|
||||
/// - 单位:与画布一致(1 世界单位 = 1 mm)。
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui' show Offset, Path, Rect;
|
||||
|
||||
// ===================== 模型 =====================
|
||||
|
||||
/// 符号基元类型。
|
||||
enum SymPrimKind {
|
||||
/// 直线:pts = [x1, y1, x2, y2]。
|
||||
line,
|
||||
|
||||
/// 折线:pts = [x1, y1, x2, y2, …]。
|
||||
polyline,
|
||||
|
||||
/// 圆:pts = [cx, cy],[SymPrim.r] 为半径。
|
||||
circle,
|
||||
|
||||
/// 圆弧:pts = [cx, cy],[SymPrim.r]、[SymPrim.startDeg]、[SymPrim.sweepDeg]。
|
||||
arc,
|
||||
|
||||
/// 矩形:pts = [x, y, w, h]。
|
||||
rect,
|
||||
|
||||
/// 文本:pts = [x, y] 为左上角锚点,[SymPrim.label] 为文字。
|
||||
text,
|
||||
}
|
||||
|
||||
/// 基元 JSON 名称 ↔ 枚举。
|
||||
String symPrimKindName(SymPrimKind k) => switch (k) {
|
||||
SymPrimKind.line => 'line',
|
||||
SymPrimKind.polyline => 'polyline',
|
||||
SymPrimKind.circle => 'circle',
|
||||
SymPrimKind.arc => 'arc',
|
||||
SymPrimKind.rect => 'rect',
|
||||
SymPrimKind.text => 'text',
|
||||
};
|
||||
|
||||
SymPrimKind symPrimKindFrom(String s) => switch (s) {
|
||||
'polyline' => SymPrimKind.polyline,
|
||||
'circle' => SymPrimKind.circle,
|
||||
'arc' => SymPrimKind.arc,
|
||||
'rect' => SymPrimKind.rect,
|
||||
'text' => SymPrimKind.text,
|
||||
_ => SymPrimKind.line,
|
||||
};
|
||||
|
||||
/// 符号基元(几何 / 文本)。
|
||||
class SymPrim {
|
||||
/// 构造。
|
||||
const SymPrim({
|
||||
required this.kind,
|
||||
this.pts = const <double>[],
|
||||
this.r = 0,
|
||||
this.startDeg = 0,
|
||||
this.sweepDeg = 0,
|
||||
this.label = '',
|
||||
});
|
||||
|
||||
/// 类型。
|
||||
final SymPrimKind kind;
|
||||
|
||||
/// 归一化坐标(含义随类型)。
|
||||
final List<double> pts;
|
||||
|
||||
/// 半径(circle / arc)。
|
||||
final double r;
|
||||
|
||||
/// 起始角(度,arc)。
|
||||
final double startDeg;
|
||||
|
||||
/// 扫掠角(度,arc)。
|
||||
final double sweepDeg;
|
||||
|
||||
/// 文本内容(text)。
|
||||
final String label;
|
||||
|
||||
/// 序列化。
|
||||
Map<String, dynamic> toJson() => <String, dynamic>{
|
||||
'kind': symPrimKindName(kind),
|
||||
'pts': pts,
|
||||
if (r != 0) 'r': r,
|
||||
if (startDeg != 0) 'start': startDeg,
|
||||
if (sweepDeg != 0) 'sweep': sweepDeg,
|
||||
if (label.isNotEmpty) 'label': label,
|
||||
};
|
||||
|
||||
/// 反序列化。
|
||||
static SymPrim fromJson(Map<String, dynamic> j) => SymPrim(
|
||||
kind: symPrimKindFrom(j['kind'] as String? ?? 'line'),
|
||||
pts: ((j['pts'] as List<dynamic>?) ?? <dynamic>[])
|
||||
.map((dynamic e) => (e as num).toDouble())
|
||||
.toList(),
|
||||
r: (j['r'] as num?)?.toDouble() ?? 0,
|
||||
startDeg: (j['start'] as num?)?.toDouble() ?? 0,
|
||||
sweepDeg: (j['sweep'] as num?)?.toDouble() ?? 0,
|
||||
label: j['label'] as String? ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
/// 符号引脚(连接点;坐标同样为 100×100 归一化)。
|
||||
class SymPin {
|
||||
/// 构造。
|
||||
const SymPin({
|
||||
required this.id,
|
||||
this.name = '',
|
||||
required this.x,
|
||||
required this.y,
|
||||
this.dir = 'b',
|
||||
});
|
||||
|
||||
/// 引脚 id(如 `1` / `2` / `A1`)。
|
||||
final String id;
|
||||
|
||||
/// 展示名(缺省用 id)。
|
||||
final String name;
|
||||
|
||||
/// 归一化坐标 x。
|
||||
final double x;
|
||||
|
||||
/// 归一化坐标 y。
|
||||
final double y;
|
||||
|
||||
/// 出线方向(t 上 / b 下 / l 左 / r 右)。
|
||||
final String dir;
|
||||
|
||||
/// 序列化。
|
||||
Map<String, dynamic> toJson() => <String, dynamic>{
|
||||
'id': id,
|
||||
if (name.isNotEmpty) 'name': name,
|
||||
'x': x,
|
||||
'y': y,
|
||||
'dir': dir,
|
||||
};
|
||||
|
||||
/// 反序列化。
|
||||
static SymPin fromJson(Map<String, dynamic> j) => SymPin(
|
||||
id: j['id'] as String? ?? '',
|
||||
name: j['name'] as String? ?? '',
|
||||
x: (j['x'] as num?)?.toDouble() ?? 0,
|
||||
y: (j['y'] as num?)?.toDouble() ?? 0,
|
||||
dir: j['dir'] as String? ?? 'b',
|
||||
);
|
||||
}
|
||||
|
||||
/// 图元符号。
|
||||
class LibSymbol {
|
||||
/// 构造。
|
||||
const LibSymbol({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.category,
|
||||
required this.prims,
|
||||
required this.pins,
|
||||
this.tags = const <String>[],
|
||||
});
|
||||
|
||||
/// 符号 id(稳定标识;用户符号文件名由它生成)。
|
||||
final String id;
|
||||
|
||||
/// 名称(如「断路器」)。
|
||||
final String name;
|
||||
|
||||
/// 分类(如「开关电器」)。
|
||||
final String category;
|
||||
|
||||
/// 检索标签。
|
||||
final List<String> tags;
|
||||
|
||||
/// 基元列表。
|
||||
final List<SymPrim> prims;
|
||||
|
||||
/// 引脚列表。
|
||||
final List<SymPin> pins;
|
||||
|
||||
/// 序列化。
|
||||
Map<String, dynamic> toJson() => <String, dynamic>{
|
||||
'id': id,
|
||||
'name': name,
|
||||
'category': category,
|
||||
'tags': tags,
|
||||
'prims': <Map<String, dynamic>>[
|
||||
for (final SymPrim p in prims) p.toJson(),
|
||||
],
|
||||
'pins': <Map<String, dynamic>>[
|
||||
for (final SymPin p in pins) p.toJson(),
|
||||
],
|
||||
};
|
||||
|
||||
/// 反序列化。
|
||||
static LibSymbol fromJson(Map<String, dynamic> j) => LibSymbol(
|
||||
id: j['id'] as String? ?? '',
|
||||
name: j['name'] as String? ?? '未命名',
|
||||
category: j['category'] as String? ?? '未分类',
|
||||
tags: ((j['tags'] as List<dynamic>?) ?? <dynamic>[])
|
||||
.map((dynamic e) => e.toString())
|
||||
.toList(),
|
||||
prims: ((j['prims'] as List<dynamic>?) ?? <dynamic>[])
|
||||
.map((dynamic e) => SymPrim.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
pins: ((j['pins'] as List<dynamic>?) ?? <dynamic>[])
|
||||
.map((dynamic e) => SymPin.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
/// 序列化为带缩进的 JSON 文本。
|
||||
String encode() => const JsonEncoder.withIndent(' ').convert(toJson());
|
||||
}
|
||||
|
||||
// ===================== 归一化 → 画布几何 =====================
|
||||
|
||||
/// 归一化坐标(0..100)→ [box] 内的坐标。
|
||||
Offset symPt(double x, double y, Rect box) => Offset(
|
||||
box.left + x / 100 * box.width,
|
||||
box.top + y / 100 * box.height,
|
||||
);
|
||||
|
||||
/// 单个基元的路径(文本基元不产生路径,返回 null)。
|
||||
Path? symPrimPath(SymPrim p, Rect box) {
|
||||
switch (p.kind) {
|
||||
case SymPrimKind.line:
|
||||
case SymPrimKind.polyline:
|
||||
if (p.pts.length < 4) return null;
|
||||
final Path path = Path()
|
||||
..moveTo(symPt(p.pts[0], p.pts[1], box).dx,
|
||||
symPt(p.pts[0], p.pts[1], box).dy);
|
||||
for (int i = 2; i + 1 < p.pts.length; i += 2) {
|
||||
final Offset o = symPt(p.pts[i], p.pts[i + 1], box);
|
||||
path.lineTo(o.dx, o.dy);
|
||||
}
|
||||
return path;
|
||||
case SymPrimKind.circle:
|
||||
if (p.pts.length < 2) return null;
|
||||
final Offset c = symPt(p.pts[0], p.pts[1], box);
|
||||
final double r = p.r / 100 * ((box.width + box.height) / 2);
|
||||
return Path()..addOval(Rect.fromCircle(center: c, radius: r));
|
||||
case SymPrimKind.arc:
|
||||
if (p.pts.length < 2) return null;
|
||||
final Offset c = symPt(p.pts[0], p.pts[1], box);
|
||||
final double r = p.r / 100 * ((box.width + box.height) / 2);
|
||||
return Path()
|
||||
..addArc(
|
||||
Rect.fromCircle(center: c, radius: r),
|
||||
p.startDeg * math.pi / 180,
|
||||
p.sweepDeg * math.pi / 180,
|
||||
);
|
||||
case SymPrimKind.rect:
|
||||
if (p.pts.length < 4) return null;
|
||||
final Offset tl = symPt(p.pts[0], p.pts[1], box);
|
||||
final Rect r = Rect.fromLTWH(
|
||||
tl.dx,
|
||||
tl.dy,
|
||||
p.pts[2] / 100 * box.width,
|
||||
p.pts[3] / 100 * box.height,
|
||||
);
|
||||
return Path()..addRect(r);
|
||||
case SymPrimKind.text:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// 整个符号的几何路径(不含文本)。
|
||||
Path buildSymbolPath(LibSymbol s, Rect box) {
|
||||
final Path out = Path();
|
||||
for (final SymPrim p in s.prims) {
|
||||
final Path? sub = symPrimPath(p, box);
|
||||
if (sub != null) out.addPath(sub, Offset.zero);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// 图元自然边界(100×100 归一化空间内所有基元的外接矩形;最小 20×20)。
|
||||
Rect symbolNaturalBounds(LibSymbol s) {
|
||||
double? l, t, r, b;
|
||||
void inc(double x, double y) {
|
||||
l = (l == null || x < l!) ? x : l;
|
||||
t = (t == null || y < t!) ? y : t;
|
||||
r = (r == null || x > r!) ? x : r;
|
||||
b = (b == null || y > b!) ? y : b;
|
||||
}
|
||||
|
||||
for (final SymPrim p in s.prims) {
|
||||
switch (p.kind) {
|
||||
case SymPrimKind.line:
|
||||
case SymPrimKind.polyline:
|
||||
for (int i = 0; i + 1 < p.pts.length; i += 2) {
|
||||
inc(p.pts[i], p.pts[i + 1]);
|
||||
}
|
||||
case SymPrimKind.circle:
|
||||
case SymPrimKind.arc:
|
||||
if (p.pts.length >= 2) {
|
||||
inc(p.pts[0] - p.r, p.pts[1] - p.r);
|
||||
inc(p.pts[0] + p.r, p.pts[1] + p.r);
|
||||
}
|
||||
case SymPrimKind.rect:
|
||||
if (p.pts.length >= 4) {
|
||||
inc(p.pts[0], p.pts[1]);
|
||||
inc(p.pts[0] + p.pts[2], p.pts[1] + p.pts[3]);
|
||||
}
|
||||
case SymPrimKind.text:
|
||||
if (p.pts.length >= 2) inc(p.pts[0], p.pts[1]);
|
||||
}
|
||||
}
|
||||
if (l == null || t == null || r == null || b == null) {
|
||||
return const Rect.fromLTWH(0, 0, 100, 100);
|
||||
}
|
||||
// 最小尺寸保底(避免退化成线 / 点)。
|
||||
double w = r! - l!;
|
||||
double h = b! - t!;
|
||||
if (w < 20) {
|
||||
l = l! - (20 - w) / 2;
|
||||
w = 20;
|
||||
}
|
||||
if (h < 20) {
|
||||
t = t! - (20 - h) / 2;
|
||||
h = 20;
|
||||
}
|
||||
return Rect.fromLTWH(l!, t!, w, h).inflate(2);
|
||||
}
|
||||
|
||||
/// 图元库:内置符号(随安装包发布,只读)。
|
||||
class SymbolLibrary {
|
||||
SymbolLibrary._();
|
||||
|
||||
// 垂直元件的通用引脚(上 / 下)。
|
||||
static const List<SymPin> _vpins = <SymPin>[
|
||||
SymPin(id: '1', x: 50, y: 0, dir: 't'),
|
||||
SymPin(id: '2', x: 50, y: 100, dir: 'b'),
|
||||
];
|
||||
|
||||
/// 内置符号(电气常用图元;100×100 归一化)。
|
||||
static const List<LibSymbol> builtin = <LibSymbol>[
|
||||
LibSymbol(
|
||||
id: 'qf-brk',
|
||||
name: '断路器 QF',
|
||||
category: '开关电器',
|
||||
tags: <String>['断路器', '空开', 'QF', '开关'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 34]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 34, 66, 56]),
|
||||
SymPrim(kind: SymPrimKind.circle, pts: <double>[50, 66], r: 3.5),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 70, 50, 100]),
|
||||
SymPrim(kind: SymPrimKind.text, pts: <double>[72, 26], label: 'QF'),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'fu-fuse',
|
||||
name: '熔断器 FU',
|
||||
category: '保护电器',
|
||||
tags: <String>['熔断器', '保险', 'FU'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 32]),
|
||||
SymPrim(kind: SymPrimKind.rect, pts: <double>[38, 32, 24, 36]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 32, 50, 68]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 68, 50, 100]),
|
||||
SymPrim(kind: SymPrimKind.text, pts: <double>[68, 26], label: 'FU'),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'km-coil',
|
||||
name: '接触器线圈 KM',
|
||||
category: '开关电器',
|
||||
tags: <String>['接触器', '线圈', 'KM'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 30]),
|
||||
SymPrim(kind: SymPrimKind.rect, pts: <double>[32, 30, 36, 40]),
|
||||
SymPrim(kind: SymPrimKind.text, pts: <double>[40, 44], label: 'KM'),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 70, 50, 100]),
|
||||
],
|
||||
pins: <SymPin>[
|
||||
SymPin(id: 'A1', x: 50, y: 0, dir: 't'),
|
||||
SymPin(id: 'A2', x: 50, y: 100, dir: 'b'),
|
||||
],
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'no-contact',
|
||||
name: '常开触点',
|
||||
category: '开关电器',
|
||||
tags: <String>['常开', '动合', 'NO', '触点'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 40]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 40, 68, 60]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 60, 50, 100]),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'nc-contact',
|
||||
name: '常闭触点',
|
||||
category: '开关电器',
|
||||
tags: <String>['常闭', '动断', 'NC', '触点'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 40]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 40, 50, 60]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 60, 50, 100]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[40, 52, 60, 52]),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'sb-no',
|
||||
name: '按钮(常开)SB',
|
||||
category: '主令电器',
|
||||
tags: <String>['按钮', 'SB', '启动'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[40, 26, 60, 26]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 26, 50, 40]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 40, 66, 58]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 58, 50, 78]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 78, 50, 100]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 26]),
|
||||
SymPrim(kind: SymPrimKind.text, pts: <double>[68, 30], label: 'SB'),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'hl-lamp',
|
||||
name: '指示灯 HL',
|
||||
category: '指示器件',
|
||||
tags: <String>['指示灯', '信号灯', 'HL'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 28]),
|
||||
SymPrim(kind: SymPrimKind.circle, pts: <double>[50, 50], r: 22),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[36, 36, 64, 64]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[64, 36, 36, 64]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 72, 50, 100]),
|
||||
SymPrim(kind: SymPrimKind.text, pts: <double>[72, 34], label: 'HL'),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'motor-m',
|
||||
name: '电机 M',
|
||||
category: '负载',
|
||||
tags: <String>['电机', '马达', 'M'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 26]),
|
||||
SymPrim(kind: SymPrimKind.circle, pts: <double>[50, 50], r: 24),
|
||||
SymPrim(kind: SymPrimKind.text, pts: <double>[42, 42], label: 'M'),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 74, 50, 100]),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'fr-thermal',
|
||||
name: '热继电器 FR',
|
||||
category: '保护电器',
|
||||
tags: <String>['热继电器', '过载', 'FR'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 22]),
|
||||
SymPrim(kind: SymPrimKind.rect, pts: <double>[40, 22, 20, 20]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[40, 42, 60, 22]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 42, 50, 100]),
|
||||
SymPrim(kind: SymPrimKind.text, pts: <double>[68, 24], label: 'FR'),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'terminal',
|
||||
name: '端子 / 接线点',
|
||||
category: '连接器件',
|
||||
tags: <String>['端子', '接线', '连接点'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 38]),
|
||||
SymPrim(kind: SymPrimKind.rect, pts: <double>[40, 38, 20, 24]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 62, 50, 100]),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'pe-ground',
|
||||
name: '接地 PE',
|
||||
category: '连接器件',
|
||||
tags: <String>['接地', '地', 'PE'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 52]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[30, 52, 70, 52]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[38, 62, 62, 62]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[45, 72, 55, 72]),
|
||||
],
|
||||
pins: <SymPin>[SymPin(id: '1', x: 50, y: 0, dir: 't')],
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'resistor',
|
||||
name: '电阻 R',
|
||||
category: '无源元件',
|
||||
tags: <String>['电阻', 'R'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 34]),
|
||||
SymPrim(kind: SymPrimKind.rect, pts: <double>[38, 34, 24, 32]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 66, 50, 100]),
|
||||
SymPrim(kind: SymPrimKind.text, pts: <double>[70, 42], label: 'R'),
|
||||
],
|
||||
pins: _vpins,
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'coil-ka',
|
||||
name: '继电器线圈 KA',
|
||||
category: '开关电器',
|
||||
tags: <String>['继电器', '线圈', 'KA'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 30]),
|
||||
SymPrim(kind: SymPrimKind.rect, pts: <double>[32, 30, 36, 40]),
|
||||
SymPrim(kind: SymPrimKind.text, pts: <double>[40, 44], label: 'KA'),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 70, 50, 100]),
|
||||
],
|
||||
pins: <SymPin>[
|
||||
SymPin(id: 'A1', x: 50, y: 0, dir: 't'),
|
||||
SymPin(id: 'A2', x: 50, y: 100, dir: 'b'),
|
||||
],
|
||||
),
|
||||
LibSymbol(
|
||||
id: 'dc-supply',
|
||||
name: '直流电源 DC',
|
||||
category: '电源',
|
||||
tags: <String>['电源', '直流', 'DC', '电池'],
|
||||
prims: <SymPrim>[
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 0, 50, 40]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[32, 40, 68, 40]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[42, 50, 58, 50]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[32, 60, 68, 60]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[42, 70, 58, 70]),
|
||||
SymPrim(kind: SymPrimKind.line, pts: <double>[50, 70, 50, 100]),
|
||||
],
|
||||
pins: <SymPin>[
|
||||
SymPin(id: '+', x: 50, y: 0, dir: 't'),
|
||||
SymPin(id: '-', x: 50, y: 100, dir: 'b'),
|
||||
],
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/// 运行时图元缓存(内置;绘制与手写识别共用)。
|
||||
class SymbolCache {
|
||||
SymbolCache._();
|
||||
|
||||
static final List<LibSymbol> _all =
|
||||
List<LibSymbol>.unmodifiable(SymbolLibrary.builtin);
|
||||
static final Map<String, LibSymbol> _byId = <String, LibSymbol>{
|
||||
for (final LibSymbol s in SymbolLibrary.builtin) s.id: s,
|
||||
};
|
||||
|
||||
/// 全部图元(内置)。
|
||||
static List<LibSymbol> get all => _all;
|
||||
|
||||
/// 按 id 查找图元。
|
||||
static LibSymbol? byId(String id) => _byId[id];
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,362 @@
|
||||
/// 参数化草图绘制:几何(直线 / 圆 / 弧)、点(固定点高亮)、
|
||||
/// 约束图标(H / V / ∥ / ⊥ / = / ◎ / T)、驱动尺寸标注与预览。
|
||||
///
|
||||
/// 所有尺寸按 `1 / zoom` 逆缩放,保持屏幕像素恒定(CAD 观感)。
|
||||
library;
|
||||
|
||||
import 'dart:math' as math;
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:sequence_diagram/theme/tokens.dart';
|
||||
import 'sketch_models.dart';
|
||||
|
||||
/// 草图配色(浅 / 深色主题下都可读)。
|
||||
const int kSketchLineColor = 0xFF2F6FEB;
|
||||
const int kSketchPointColor = 0xFF64748B;
|
||||
const int kSketchFixedColor = 0xFFDC2626;
|
||||
const int kSketchDimColor = 0xFF0F766E;
|
||||
const int kSketchConsColor = 0xFF7C3AED;
|
||||
const int kSketchSelColor = 0xFFF97316;
|
||||
const int kSketchPreviewColor = 0xFF0EA5E9;
|
||||
|
||||
/// 草图预览信息(绘制中的橡皮筋)。
|
||||
class SketchPreview {
|
||||
/// 构造。
|
||||
const SketchPreview({required this.pts, this.kind = SketchKind.line, this.closed = false});
|
||||
|
||||
/// 预览点(世界坐标)。
|
||||
final List<Offset> pts;
|
||||
|
||||
/// 预览类型(line:折线描边;circle / arc 用第一点为圆心)。
|
||||
final SketchKind kind;
|
||||
|
||||
/// 是否闭合描边。
|
||||
final bool closed;
|
||||
}
|
||||
|
||||
/// 绘制草图内容(调用方已完成 translate + scale)。
|
||||
void paintSketch(
|
||||
Canvas canvas,
|
||||
SketchDoc doc,
|
||||
Tokens t, {
|
||||
Set<String> sel = const <String>{},
|
||||
Offset? hover,
|
||||
SketchPreview? preview,
|
||||
Offset? snapMark,
|
||||
}) {
|
||||
// 逆缩放因子:通过画布变换取得真实缩放,保证线宽 / 字号恒定。
|
||||
final double scale = _canvasScale(canvas);
|
||||
final double s = scale <= 0 ? 1 : 1 / scale;
|
||||
|
||||
// ---- 几何 ----
|
||||
for (final SketchEntity e in doc.entities) {
|
||||
final bool selected = sel.contains(e.id);
|
||||
final Paint paint = Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = (selected ? 2.4 : 1.6) * s
|
||||
..strokeCap = StrokeCap.round
|
||||
..strokeJoin = StrokeJoin.round
|
||||
..color = Color(selected ? kSketchSelColor : kSketchLineColor);
|
||||
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) break;
|
||||
canvas.drawLine(a, b, paint);
|
||||
case SketchKind.circle:
|
||||
final Offset? c = doc.pointById(e.p1)?.pos;
|
||||
if (c == null) break;
|
||||
canvas.drawCircle(c, e.r, paint);
|
||||
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) break;
|
||||
final (double a1, double sweep) =
|
||||
sketchArcAngles(c, ps, pe, e.ccw);
|
||||
final Path path = Path()
|
||||
..addArc(Rect.fromCircle(center: c, radius: e.r),
|
||||
e.ccw ? a1 : a1 - sweep, sweep);
|
||||
canvas.drawPath(path, paint);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 点 ----
|
||||
for (final SketchPoint p in doc.points) {
|
||||
final bool selected = sel.contains(p.id);
|
||||
final bool hovered = hover != null && (hover - p.pos).distance < 7 * s;
|
||||
final double r = (hovered ? 3.6 : 2.8) * s;
|
||||
canvas.drawRect(
|
||||
Rect.fromCenter(center: p.pos, width: r * 2, height: r * 2),
|
||||
Paint()
|
||||
..color = Color(selected
|
||||
? kSketchSelColor
|
||||
: (p.fixed ? kSketchFixedColor : kSketchPointColor)),
|
||||
);
|
||||
if (p.fixed) {
|
||||
// 固定点:外圈提示锚定。
|
||||
canvas.drawCircle(
|
||||
p.pos,
|
||||
r * 2.2,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.2 * s
|
||||
..color = Color(kSketchFixedColor),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 约束图标 ----
|
||||
for (final SketchConstraint k in doc.constraints) {
|
||||
if (k.internal) continue;
|
||||
final List<Offset> anchors = _consAnchors(doc, k);
|
||||
for (final Offset a in anchors) {
|
||||
_label(canvas, _consGlyph(k.type), a, s,
|
||||
color: Color(kSketchConsColor),
|
||||
bg: t.panel.withValues(alpha: 0.92));
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 驱动尺寸 ----
|
||||
for (final SketchDim d in doc.dims) {
|
||||
_dim(canvas, doc, d, t, s, sel.contains(d.id));
|
||||
}
|
||||
|
||||
// ---- 预览 ----
|
||||
final SketchPreview? pv = preview;
|
||||
if (pv != null && pv.pts.isNotEmpty) {
|
||||
final Paint pp = Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.8 * s
|
||||
..strokeCap = StrokeCap.round
|
||||
..color = Color(kSketchPreviewColor);
|
||||
switch (pv.kind) {
|
||||
case SketchKind.line:
|
||||
if (pv.pts.length >= 2) {
|
||||
final Path path = Path()..moveTo(pv.pts.first.dx, pv.pts.first.dy);
|
||||
for (int i = 1; i < pv.pts.length; i++) {
|
||||
path.lineTo(pv.pts[i].dx, pv.pts[i].dy);
|
||||
}
|
||||
if (pv.closed) path.close();
|
||||
canvas.drawPath(path, pp);
|
||||
}
|
||||
case SketchKind.circle:
|
||||
if (pv.pts.length >= 2) {
|
||||
canvas.drawCircle(pv.pts.first,
|
||||
(pv.pts.last - pv.pts.first).distance, pp);
|
||||
}
|
||||
case SketchKind.arc:
|
||||
if (pv.pts.length >= 3) {
|
||||
final Offset c = pv.pts.first;
|
||||
final Offset ps = pv.pts[1];
|
||||
final Offset pe = pv.pts.last;
|
||||
final double r = (ps - c).distance;
|
||||
final (double a1, double sweep) = sketchArcAngles(c, ps, pe, true);
|
||||
canvas.drawPath(
|
||||
Path()
|
||||
..addArc(
|
||||
Rect.fromCircle(center: c, radius: r), a1, sweep),
|
||||
pp,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 捕捉标记 ----
|
||||
final Offset? sm = snapMark;
|
||||
if (sm != null) {
|
||||
canvas.drawCircle(
|
||||
sm,
|
||||
4.5 * s,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.6 * s
|
||||
..color = Color(kSketchPreviewColor),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 取画布当前缩放的倒数(保持屏幕像素恒定的线宽 / 文字)。
|
||||
double _canvasScale(Canvas canvas) {
|
||||
final Float64List m = canvas.getTransform();
|
||||
final double sx = math.sqrt(m[0] * m[0] + m[1] * m[1]);
|
||||
final double sy = math.sqrt(m[4] * m[4] + m[5] * m[5]);
|
||||
final double s = (sx + sy) / 2;
|
||||
return s <= 0 ? 1 : s;
|
||||
}
|
||||
|
||||
/// 约束图标锚点(每个约束可画多处)。
|
||||
List<Offset> _consAnchors(SketchDoc doc, SketchConstraint k) {
|
||||
Offset? midEntity(String id) {
|
||||
final SketchEntity? e = doc.entityById(id);
|
||||
if (e == null) return null;
|
||||
if (e.kind == SketchKind.line) {
|
||||
final Offset? a = doc.pointById(e.p1)?.pos;
|
||||
final Offset? b = doc.pointById(e.p2)?.pos;
|
||||
if (a == null || b == null) return null;
|
||||
final Offset m = Offset.lerp(a, b, 0.5)!;
|
||||
final Offset d = b - a;
|
||||
final double len = d.distance;
|
||||
if (len < 1e-6) return m;
|
||||
return m + Offset(-d.dy / len, d.dx / len) * 12;
|
||||
}
|
||||
final Offset? c = doc.pointById(e.p1)?.pos;
|
||||
if (c == null) return null;
|
||||
return c + Offset(e.r * 0.35, -e.r * 0.35);
|
||||
}
|
||||
|
||||
switch (k.type) {
|
||||
case SketchConsType.horizontal:
|
||||
case SketchConsType.vertical:
|
||||
final Offset? m = midEntity(k.a);
|
||||
return m == null ? <Offset>[] : <Offset>[m];
|
||||
case SketchConsType.pointOnEntity:
|
||||
final Offset? p = doc.pointById(k.a)?.pos;
|
||||
return p == null ? <Offset>[] : <Offset>[p + const Offset(10, -10)];
|
||||
case SketchConsType.concentric:
|
||||
final Offset? c = doc.pointById(doc.entityById(k.a)?.p1)?.pos;
|
||||
return c == null ? <Offset>[] : <Offset>[c + const Offset(14, -14)];
|
||||
default:
|
||||
final List<Offset> out = <Offset>[];
|
||||
final Offset? m1 = midEntity(k.a);
|
||||
if (m1 != null) out.add(m1);
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
String _consGlyph(SketchConsType t2) => switch (t2) {
|
||||
SketchConsType.horizontal => 'H',
|
||||
SketchConsType.vertical => 'V',
|
||||
SketchConsType.parallel => '∥',
|
||||
SketchConsType.perpendicular => '⊥',
|
||||
SketchConsType.equal => '=',
|
||||
SketchConsType.concentric => '◎',
|
||||
SketchConsType.tangent => 'T',
|
||||
SketchConsType.pointOnEntity => '⌐',
|
||||
};
|
||||
|
||||
/// 画一条尺寸标注。
|
||||
void _dim(
|
||||
Canvas canvas,
|
||||
SketchDoc doc,
|
||||
SketchDim d,
|
||||
Tokens t,
|
||||
double s,
|
||||
bool selected,
|
||||
) {
|
||||
final Offset? anchor = sketchDimAnchor(doc, d);
|
||||
if (anchor == null) return;
|
||||
final Color color = Color(selected ? kSketchSelColor : kSketchDimColor);
|
||||
final Paint line = Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.2 * s
|
||||
..color = color;
|
||||
|
||||
switch (d.type) {
|
||||
case SketchDimType.length:
|
||||
case SketchDimType.distance:
|
||||
final (Offset p1, Offset p2) = d.type == SketchDimType.length
|
||||
? _entityEnds(doc, d.a)
|
||||
: (doc.pointById(d.a)?.pos ?? Offset.zero,
|
||||
doc.pointById(d.b)?.pos ?? Offset.zero);
|
||||
final Offset dir = p2 - p1;
|
||||
final double len = dir.distance;
|
||||
if (len < 1e-6) return;
|
||||
final Offset n = Offset(-dir.dy / len, dir.dx / len);
|
||||
final double off = d.type == SketchDimType.length ? 18 : -20;
|
||||
final Offset a2 = p1 + n * (off * s);
|
||||
final Offset b2 = p2 + n * (off * s);
|
||||
canvas.drawLine(a2, b2, line);
|
||||
canvas.drawLine(p1, a2 + n * 3 * s, line);
|
||||
canvas.drawLine(p2, b2 + n * 3 * s, line);
|
||||
_tick(canvas, a2, n, s, color);
|
||||
_tick(canvas, b2, n, s, color);
|
||||
case SketchDimType.radius:
|
||||
final SketchEntity? e = doc.entityById(d.a);
|
||||
final Offset? c = doc.pointById(e?.p1)?.pos;
|
||||
if (e == null || c == null) return;
|
||||
final Offset dir = const Offset(0.7071, -0.7071);
|
||||
final Offset end = c + dir * e.r;
|
||||
canvas.drawLine(c, end, line);
|
||||
canvas.drawLine(
|
||||
c,
|
||||
c + dir * (e.r * 0.45),
|
||||
Paint()
|
||||
..strokeWidth = 3.2 * s
|
||||
..color = color);
|
||||
case SketchDimType.angle:
|
||||
final Offset? a1 = doc.pointById(doc.entityById(d.a)?.p1)?.pos;
|
||||
final Offset? a2 = doc.pointById(doc.entityById(d.a)?.p2)?.pos;
|
||||
if (a1 == null || a2 == null) return;
|
||||
// 简化:在第一条线的中点画一个角度弧示意。
|
||||
final Offset m = Offset.lerp(a1, a2, 0.5)!;
|
||||
canvas.drawCircle(
|
||||
m,
|
||||
10 * s,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.2 * s
|
||||
..color = color,
|
||||
);
|
||||
}
|
||||
_label(canvas, sketchDimText(d), anchor, s,
|
||||
color: color, bg: t.panel.withValues(alpha: 0.94), border: color);
|
||||
}
|
||||
|
||||
(Offset, Offset) _entityEnds(SketchDoc doc, String id) {
|
||||
final SketchEntity? e = doc.entityById(id);
|
||||
if (e == null) return (Offset.zero, Offset.zero);
|
||||
return (doc.pointById(e.p1)?.pos ?? Offset.zero,
|
||||
doc.pointById(e.p2)?.pos ?? Offset.zero);
|
||||
}
|
||||
|
||||
/// 尺寸界线端点的小斜线(CAD 风格刻度)。
|
||||
void _tick(Canvas canvas, Offset p, Offset n, double s, Color color) {
|
||||
canvas.drawLine(
|
||||
p + Offset(-n.dy, n.dx) * 3.5 * s,
|
||||
p + Offset(n.dy, -n.dx) * 3.5 * s,
|
||||
Paint()
|
||||
..strokeWidth = 1.2 * s
|
||||
..color = color,
|
||||
);
|
||||
}
|
||||
|
||||
/// 小圆角标签(逆缩放保持屏幕字号恒定)。
|
||||
void _label(
|
||||
Canvas canvas,
|
||||
String text,
|
||||
Offset anchor,
|
||||
double s, {
|
||||
required Color color,
|
||||
required Color bg,
|
||||
Color? border,
|
||||
}) {
|
||||
final TextPainter tp = TextPainter(
|
||||
text: TextSpan(
|
||||
text: text,
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
fontSize: 10 * s,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
textDirection: TextDirection.ltr,
|
||||
)..layout();
|
||||
final Rect r = Rect.fromCenter(
|
||||
center: anchor,
|
||||
width: tp.width + 8 * s,
|
||||
height: tp.height + 3 * s,
|
||||
);
|
||||
final RRect rr = RRect.fromRectAndRadius(r, Radius.circular(4 * s));
|
||||
canvas.drawRRect(rr, Paint()..color = bg);
|
||||
canvas.drawRRect(
|
||||
rr,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1 * s
|
||||
..color = border ?? color.withValues(alpha: 0.45),
|
||||
);
|
||||
tp.paint(canvas, r.center - Offset(tp.width / 2, tp.height / 2));
|
||||
}
|
||||
@@ -0,0 +1,579 @@
|
||||
/// 参数化草图求解器:把「约束 + 驱动尺寸 + 拖拽目标」作为残差,
|
||||
/// 用 Levenberg–Marquardt(数值雅可比)最小二乘求解点坐标与半径。
|
||||
///
|
||||
/// 权重约定(越大越硬):
|
||||
/// - 几何约束 / 驱动尺寸:30(先满足);
|
||||
/// - 拖拽目标:6(尽量跟随鼠标,但不破坏约束);
|
||||
/// - 正则项:0.03(把无驱动变量轻微拉回原位,避免欠约束漂移)。
|
||||
library;
|
||||
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui' show Offset;
|
||||
|
||||
import 'sketch_models.dart';
|
||||
|
||||
/// 求解结果。
|
||||
class SketchSolveResult {
|
||||
/// 构造。
|
||||
const SketchSolveResult({
|
||||
required this.doc,
|
||||
required this.converged,
|
||||
required this.iterations,
|
||||
required this.residual,
|
||||
});
|
||||
|
||||
/// 求解后的文档。
|
||||
final SketchDoc doc;
|
||||
|
||||
/// 是否收敛(残差平方和 < 1e-8)。
|
||||
final bool converged;
|
||||
|
||||
/// 实际迭代次数。
|
||||
final int iterations;
|
||||
|
||||
/// 最终残差平方和。
|
||||
final double residual;
|
||||
}
|
||||
|
||||
/// 求解草图:返回满足(尽量)约束与尺寸的新文档。
|
||||
///
|
||||
/// [dragPoints]:拖拽目标(点 id → 世界坐标);[dragRadii]:拖拽半径(实体 id → 半径)。
|
||||
SketchSolveResult solveSketch(
|
||||
SketchDoc doc, {
|
||||
Map<String, Offset> dragPoints = const <String, Offset>{},
|
||||
Map<String, double> dragRadii = const <String, double>{},
|
||||
int maxIter = 30,
|
||||
}) {
|
||||
final _VarSet vs = _VarSet(doc);
|
||||
if (vs.n == 0) {
|
||||
return SketchSolveResult(
|
||||
doc: doc, converged: true, iterations: 0, residual: 0);
|
||||
}
|
||||
final _Access acc = _Access(doc, vs);
|
||||
final List<_Res> res = <_Res>[];
|
||||
|
||||
for (final SketchConstraint k in doc.constraints) {
|
||||
_addConstraint(doc, acc, k, res);
|
||||
}
|
||||
for (final SketchEntity e in doc.entities) {
|
||||
_addArcInternal(doc, acc, e, res);
|
||||
}
|
||||
for (final SketchDim d in doc.dims) {
|
||||
_addDim(doc, acc, d, res);
|
||||
}
|
||||
|
||||
// ---- 拖拽目标 ----
|
||||
dragPoints.forEach((String id, Offset t) {
|
||||
if (doc.pointById(id) == null) return;
|
||||
res.add(_Res(6, (List<double> x) {
|
||||
acc.x = x;
|
||||
return acc.p(id).dx - t.dx;
|
||||
}));
|
||||
res.add(_Res(6, (List<double> x) {
|
||||
acc.x = x;
|
||||
return acc.p(id).dy - t.dy;
|
||||
}));
|
||||
});
|
||||
dragRadii.forEach((String id, double r) {
|
||||
final SketchEntity? e = doc.entityById(id);
|
||||
if (e == null || e.kind == SketchKind.line) return;
|
||||
res.add(_Res(6, (List<double> x) {
|
||||
acc.x = x;
|
||||
return acc.r(id) - r;
|
||||
}));
|
||||
});
|
||||
|
||||
// ---- 正则项(soft stay) ----
|
||||
final List<double> x0 = vs.x0();
|
||||
for (int i = 0; i < vs.n; i++) {
|
||||
final int idx = i;
|
||||
res.add(_Res(0.03, (List<double> x) => x[idx] - x0[idx]));
|
||||
}
|
||||
|
||||
final (List<double> x, bool conv, int iters, double err) =
|
||||
_lm(res, x0, maxIter);
|
||||
return SketchSolveResult(
|
||||
doc: vs.apply(doc, x),
|
||||
converged: conv,
|
||||
iterations: iters,
|
||||
residual: err,
|
||||
);
|
||||
}
|
||||
|
||||
/// 估算剩余自由度(变量数 − 独立约束数,粗略:约束 / 尺寸各算 1,同心算 2)。
|
||||
int sketchDofCount(SketchDoc doc) {
|
||||
int vars = 0;
|
||||
for (final SketchPoint p in doc.points) {
|
||||
if (!p.fixed) vars += 2;
|
||||
}
|
||||
for (final SketchEntity e in doc.entities) {
|
||||
if (e.kind != SketchKind.line) vars += 1;
|
||||
}
|
||||
int cons = 0;
|
||||
for (final SketchConstraint k in doc.constraints) {
|
||||
cons += k.type == SketchConsType.concentric ? 2 : 1;
|
||||
}
|
||||
cons += doc.dims.length;
|
||||
for (final SketchEntity e in doc.entities) {
|
||||
if (e.kind == SketchKind.arc) cons += 2;
|
||||
}
|
||||
final int dof = vars - cons;
|
||||
return dof < 0 ? 0 : dof;
|
||||
}
|
||||
|
||||
// ===================== 残差构建 =====================
|
||||
|
||||
/// 几何约束残差。
|
||||
void _addConstraint(
|
||||
SketchDoc doc,
|
||||
_Access acc,
|
||||
SketchConstraint k,
|
||||
List<_Res> res,
|
||||
) {
|
||||
if (k.type == SketchConsType.horizontal ||
|
||||
k.type == SketchConsType.vertical) {
|
||||
final SketchEntity? e = doc.entityById(k.a);
|
||||
if (e == null || e.kind != SketchKind.line) return;
|
||||
if (doc.pointById(e.p1) == null || doc.pointById(e.p2) == null) return;
|
||||
final bool horiz = k.type == SketchConsType.horizontal;
|
||||
res.add(_Res(30, (List<double> x) {
|
||||
acc.x = x;
|
||||
return horiz
|
||||
? acc.p(e.p2).dy - acc.p(e.p1).dy
|
||||
: acc.p(e.p2).dx - acc.p(e.p1).dx;
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (k.type == SketchConsType.parallel ||
|
||||
k.type == SketchConsType.perpendicular) {
|
||||
final SketchEntity? e1 = doc.entityById(k.a);
|
||||
final SketchEntity? e2 = doc.entityById(k.b);
|
||||
if (e1 == null ||
|
||||
e2 == null ||
|
||||
e1.kind != SketchKind.line ||
|
||||
e2.kind != SketchKind.line) {
|
||||
return;
|
||||
}
|
||||
final bool par = k.type == SketchConsType.parallel;
|
||||
res.add(_Res(30, (List<double> x) {
|
||||
acc.x = x;
|
||||
final Offset d1 = acc.p(e1.p2) - acc.p(e1.p1);
|
||||
final Offset d2 = acc.p(e2.p2) - acc.p(e2.p1);
|
||||
final double l1 = d1.distance;
|
||||
final double l2 = d2.distance;
|
||||
if (l1 < 1e-9 || l2 < 1e-9) return 0;
|
||||
return par
|
||||
? (d1.dx * d2.dy - d1.dy * d2.dx) / (l1 * l2)
|
||||
: (d1.dx * d2.dx + d1.dy * d2.dy) / (l1 * l2);
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (k.type == SketchConsType.equal) {
|
||||
final SketchEntity? e1 = doc.entityById(k.a);
|
||||
final SketchEntity? e2 = doc.entityById(k.b);
|
||||
if (e1 == null || e2 == null) return;
|
||||
res.add(_Res(30, (List<double> x) {
|
||||
acc.x = x;
|
||||
if (e1.kind == SketchKind.line && e2.kind == SketchKind.line) {
|
||||
return (acc.p(e1.p2) - acc.p(e1.p1)).distance -
|
||||
(acc.p(e2.p2) - acc.p(e2.p1)).distance;
|
||||
}
|
||||
return acc.r(e1.id) - acc.r(e2.id);
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (k.type == SketchConsType.concentric) {
|
||||
final SketchEntity? e1 = doc.entityById(k.a);
|
||||
final SketchEntity? e2 = doc.entityById(k.b);
|
||||
if (e1 == null ||
|
||||
e2 == null ||
|
||||
e1.kind == SketchKind.line ||
|
||||
e2.kind == SketchKind.line) {
|
||||
return;
|
||||
}
|
||||
res.add(_Res(30, (List<double> x) {
|
||||
acc.x = x;
|
||||
return acc.p(e1.p1).dx - acc.p(e2.p1).dx;
|
||||
}));
|
||||
res.add(_Res(30, (List<double> x) {
|
||||
acc.x = x;
|
||||
return acc.p(e1.p1).dy - acc.p(e2.p1).dy;
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (k.type == SketchConsType.tangent) {
|
||||
final SketchEntity? e1 = doc.entityById(k.a);
|
||||
final SketchEntity? e2 = doc.entityById(k.b);
|
||||
if (e1 == null || e2 == null) return;
|
||||
final SketchEntity? line = e1.kind == SketchKind.line
|
||||
? e1
|
||||
: (e2.kind == SketchKind.line ? e2 : null);
|
||||
final SketchEntity? circle = e1.kind != SketchKind.line
|
||||
? e1
|
||||
: (e2.kind != SketchKind.line ? e2 : null);
|
||||
if (line != null && circle != null) {
|
||||
res.add(_Res(30, (List<double> x) {
|
||||
acc.x = x;
|
||||
final Offset a = acc.p(line.p1);
|
||||
final Offset d = acc.p(line.p2) - a;
|
||||
final double len = d.distance;
|
||||
if (len < 1e-9) return 0;
|
||||
final Offset c = acc.p(circle.p1);
|
||||
final double dist =
|
||||
((c - a).dx * d.dy - (c - a).dy * d.dx).abs() / len;
|
||||
return dist - acc.r(circle.id);
|
||||
}));
|
||||
} else if (e1.kind != SketchKind.line && e2.kind != SketchKind.line) {
|
||||
res.add(_Res(30, (List<double> x) {
|
||||
acc.x = x;
|
||||
return (acc.p(e1.p1) - acc.p(e2.p1)).distance -
|
||||
(acc.r(e1.id) + acc.r(e2.id));
|
||||
}));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (k.type == SketchConsType.pointOnEntity) {
|
||||
final SketchPoint? pt = doc.pointById(k.a);
|
||||
final SketchEntity? e = doc.entityById(k.b);
|
||||
if (pt == null || e == null) return;
|
||||
if (e.kind == SketchKind.line) {
|
||||
res.add(_Res(30, (List<double> x) {
|
||||
acc.x = x;
|
||||
final Offset a = acc.p(e.p1);
|
||||
final Offset d = acc.p(e.p2) - a;
|
||||
final double len = d.distance;
|
||||
if (len < 1e-9) return 0;
|
||||
final Offset pp = acc.p(pt.id);
|
||||
return ((pp - a).dx * d.dy - (pp - a).dy * d.dx) / len;
|
||||
}));
|
||||
} else {
|
||||
res.add(_Res(30, (List<double> x) {
|
||||
acc.x = x;
|
||||
return (acc.p(pt.id) - acc.p(e.p1)).distance - acc.r(e.id);
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 圆弧内部约束:端点落在圆上。
|
||||
void _addArcInternal(
|
||||
SketchDoc doc,
|
||||
_Access acc,
|
||||
SketchEntity e,
|
||||
List<_Res> res,
|
||||
) {
|
||||
if (e.kind != SketchKind.arc) return;
|
||||
if (doc.pointById(e.p1) == null ||
|
||||
doc.pointById(e.p2) == null ||
|
||||
doc.pointById(e.p3) == null) {
|
||||
return;
|
||||
}
|
||||
res.add(_Res(30, (List<double> x) {
|
||||
acc.x = x;
|
||||
return (acc.p(e.p2) - acc.p(e.p1)).distance - acc.r(e.id);
|
||||
}));
|
||||
res.add(_Res(30, (List<double> x) {
|
||||
acc.x = x;
|
||||
return (acc.p(e.p3) - acc.p(e.p1)).distance - acc.r(e.id);
|
||||
}));
|
||||
}
|
||||
|
||||
/// 驱动尺寸残差。
|
||||
void _addDim(SketchDoc doc, _Access acc, SketchDim d, List<_Res> res) {
|
||||
if (d.type == SketchDimType.length) {
|
||||
final SketchEntity? e = doc.entityById(d.a);
|
||||
if (e == null || e.kind != SketchKind.line) return;
|
||||
res.add(_Res(30, (List<double> x) {
|
||||
acc.x = x;
|
||||
return (acc.p(e.p2) - acc.p(e.p1)).distance - d.value;
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (d.type == SketchDimType.radius) {
|
||||
final SketchEntity? e = doc.entityById(d.a);
|
||||
if (e == null || e.kind == SketchKind.line) return;
|
||||
res.add(_Res(30, (List<double> x) {
|
||||
acc.x = x;
|
||||
return acc.r(e.id) - d.value;
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (d.type == SketchDimType.angle) {
|
||||
final SketchEntity? e1 = doc.entityById(d.a);
|
||||
final SketchEntity? e2 = doc.entityById(d.b);
|
||||
if (e1 == null ||
|
||||
e2 == null ||
|
||||
e1.kind != SketchKind.line ||
|
||||
e2.kind != SketchKind.line) {
|
||||
return;
|
||||
}
|
||||
final double cosTarget =
|
||||
math.cos(d.value.clamp(0.01, 179.99) * math.pi / 180);
|
||||
res.add(_Res(30, (List<double> x) {
|
||||
acc.x = x;
|
||||
final Offset d1 = acc.p(e1.p2) - acc.p(e1.p1);
|
||||
final Offset d2 = acc.p(e2.p2) - acc.p(e2.p1);
|
||||
final double l1 = d1.distance;
|
||||
final double l2 = d2.distance;
|
||||
if (l1 < 1e-9 || l2 < 1e-9) return 0;
|
||||
return (d1.dx * d2.dx + d1.dy * d2.dy) / (l1 * l2) - cosTarget;
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (d.type == SketchDimType.distance) {
|
||||
if (doc.pointById(d.a) == null || doc.pointById(d.b) == null) return;
|
||||
res.add(_Res(30, (List<double> x) {
|
||||
acc.x = x;
|
||||
return (acc.p(d.b) - acc.p(d.a)).distance - d.value;
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
// ===================== 求解内部实现 =====================
|
||||
|
||||
/// 残差项:函数 + 权重。
|
||||
class _Res {
|
||||
const _Res(this.weight, this.f);
|
||||
|
||||
/// 权重。
|
||||
final double weight;
|
||||
|
||||
/// 残差函数(输入变量向量)。
|
||||
final double Function(List<double> x) f;
|
||||
}
|
||||
|
||||
/// 变量集:点坐标(未固定的点)与半径(圆 / 弧)。
|
||||
class _VarSet {
|
||||
_VarSet(this.doc) {
|
||||
for (final SketchPoint p in doc.points) {
|
||||
if (p.fixed) continue;
|
||||
_pointIndex[p.id] = _n;
|
||||
_n += 2;
|
||||
}
|
||||
for (final SketchEntity e in doc.entities) {
|
||||
if (e.kind == SketchKind.line) continue;
|
||||
_radiusIndex[e.id] = _n;
|
||||
_n += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// 源文档。
|
||||
final SketchDoc doc;
|
||||
|
||||
/// 变量总数。
|
||||
int _n = 0;
|
||||
|
||||
/// 点 → 变量下标(x, y)。
|
||||
final Map<String, int> _pointIndex = <String, int>{};
|
||||
|
||||
/// 实体 → 半径变量下标。
|
||||
final Map<String, int> _radiusIndex = <String, int>{};
|
||||
|
||||
/// 变量总数。
|
||||
int get n => _n;
|
||||
|
||||
/// 初始变量向量。
|
||||
List<double> x0() {
|
||||
final List<double> x = List<double>.filled(_n, 0);
|
||||
for (final SketchPoint p in doc.points) {
|
||||
final int? i = _pointIndex[p.id];
|
||||
if (i == null) continue;
|
||||
x[i] = p.x;
|
||||
x[i + 1] = p.y;
|
||||
}
|
||||
for (final SketchEntity e in doc.entities) {
|
||||
final int? i = _radiusIndex[e.id];
|
||||
if (i == null) continue;
|
||||
x[i] = e.r;
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
/// 把变量向量写回文档。
|
||||
SketchDoc apply(SketchDoc source, List<double> x) {
|
||||
final List<SketchPoint> pts = <SketchPoint>[
|
||||
for (final SketchPoint p in source.points)
|
||||
_pointIndex.containsKey(p.id)
|
||||
? p.copyWith(
|
||||
x: x[_pointIndex[p.id]!],
|
||||
y: x[_pointIndex[p.id]! + 1],
|
||||
)
|
||||
: p,
|
||||
];
|
||||
final List<SketchEntity> ents = <SketchEntity>[
|
||||
for (final SketchEntity e in source.entities)
|
||||
_radiusIndex.containsKey(e.id)
|
||||
? e.copyWith(r: math.max(0.5, x[_radiusIndex[e.id]!]))
|
||||
: e,
|
||||
];
|
||||
return source.copyWith(points: pts, entities: ents);
|
||||
}
|
||||
}
|
||||
|
||||
/// 访问器:把变量向量映射为点坐标 / 半径(未参与求解的取文档原值)。
|
||||
class _Access {
|
||||
_Access(this.doc, this.vs);
|
||||
|
||||
final SketchDoc doc;
|
||||
final _VarSet vs;
|
||||
|
||||
/// 当前变量向量。
|
||||
late List<double> x;
|
||||
|
||||
/// 取点坐标。
|
||||
Offset p(String id) {
|
||||
final int? i = vs._pointIndex[id];
|
||||
if (i != null) return Offset(x[i], x[i + 1]);
|
||||
final SketchPoint? pt = doc.pointById(id);
|
||||
return pt == null ? Offset.zero : pt.pos;
|
||||
}
|
||||
|
||||
/// 取半径。
|
||||
double r(String id) {
|
||||
final int? i = vs._radiusIndex[id];
|
||||
if (i != null) return x[i];
|
||||
return doc.entityById(id)?.r ?? 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Levenberg–Marquardt:返回(解, 是否收敛, 迭代数, 残差平方和)。
|
||||
(List<double>, bool, int, double) _lm(
|
||||
List<_Res> res,
|
||||
List<double> x0,
|
||||
int maxIter,
|
||||
) {
|
||||
final int n = x0.length;
|
||||
final List<double> x = List<double>.of(x0);
|
||||
|
||||
double err(List<double> v) {
|
||||
double s = 0;
|
||||
for (final _Res r in res) {
|
||||
final double e = r.weight * r.f(v);
|
||||
s += e * e;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
double e0 = err(x);
|
||||
double lambda = 1e-4;
|
||||
int iters = 0;
|
||||
const double convTol = 1e-10;
|
||||
|
||||
for (int it = 0; it < maxIter; it++) {
|
||||
if (e0 < convTol) break;
|
||||
iters = it + 1;
|
||||
final List<double> rv = List<double>.generate(
|
||||
res.length, (int i) => res[i].weight * res[i].f(x));
|
||||
final List<List<double>> jac = List<List<double>>.generate(
|
||||
res.length,
|
||||
(int _) => List<double>.filled(n, 0),
|
||||
);
|
||||
for (int j = 0; j < n; j++) {
|
||||
final double h = 1e-5 * (1 + x[j].abs());
|
||||
final double old = x[j];
|
||||
x[j] = old + h;
|
||||
for (int i = 0; i < res.length; i++) {
|
||||
jac[i][j] = (res[i].weight * res[i].f(x) - rv[i]) / h;
|
||||
}
|
||||
x[j] = old;
|
||||
}
|
||||
final List<List<double>> a =
|
||||
List<List<double>>.generate(n, (int _) => List<double>.filled(n, 0));
|
||||
final List<double> g = List<double>.filled(n, 0);
|
||||
for (int i = 0; i < res.length; i++) {
|
||||
final List<double> ji = jac[i];
|
||||
final double ri = rv[i];
|
||||
for (int p = 0; p < n; p++) {
|
||||
final double vp = ji[p];
|
||||
if (vp == 0) continue;
|
||||
g[p] -= vp * ri;
|
||||
for (int q = p; q < n; q++) {
|
||||
a[p][q] += vp * ji[q];
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int p = 0; p < n; p++) {
|
||||
for (int q = 0; q < p; q++) {
|
||||
a[p][q] = a[q][p];
|
||||
}
|
||||
}
|
||||
bool accepted = false;
|
||||
for (int t = 0; t < 8; t++) {
|
||||
// 单位阵阻尼(标准 LM):秩缺陷方向的 diag(A) 元极小,
|
||||
// 若按 diag(A) 阻尼会产生病态大跳步,这里统一按标量阻尼。
|
||||
final List<List<double>> ad = List<List<double>>.generate(
|
||||
n,
|
||||
(int p) => List<double>.generate(
|
||||
n,
|
||||
(int q) => a[p][q] + (p == q ? lambda : 0.0),
|
||||
),
|
||||
);
|
||||
final List<double>? d = _solveLinear(ad, g);
|
||||
if (d == null) {
|
||||
lambda *= 8;
|
||||
if (lambda > 1e9) break;
|
||||
continue;
|
||||
}
|
||||
final List<double> x2 =
|
||||
List<double>.generate(n, (int p) => x[p] + d[p]);
|
||||
final double e2 = err(x2);
|
||||
if (e2 < e0) {
|
||||
for (int p = 0; p < n; p++) {
|
||||
x[p] = x2[p];
|
||||
}
|
||||
e0 = e2;
|
||||
lambda = math.max(lambda / 4, 1e-9);
|
||||
accepted = true;
|
||||
break;
|
||||
}
|
||||
lambda *= 6;
|
||||
if (lambda > 1e9) break;
|
||||
}
|
||||
if (!accepted) break;
|
||||
}
|
||||
return (x, e0 < 1e-8, iters, e0);
|
||||
}
|
||||
|
||||
/// 高斯消元(部分主元);奇异返回 null。
|
||||
List<double>? _solveLinear(List<List<double>> m, List<double> b) {
|
||||
final int n = b.length;
|
||||
final List<List<double>> a = <List<double>>[
|
||||
for (int i = 0; i < n; i++) <double>[...m[i], b[i]],
|
||||
];
|
||||
for (int col = 0; col < n; col++) {
|
||||
int piv = col;
|
||||
double best = a[col][col].abs();
|
||||
for (int r = col + 1; r < n; r++) {
|
||||
final double v = a[r][col].abs();
|
||||
if (v > best) {
|
||||
best = v;
|
||||
piv = r;
|
||||
}
|
||||
}
|
||||
if (best < 1e-12) return null;
|
||||
if (piv != col) {
|
||||
final List<double> tmp = a[piv];
|
||||
a[piv] = a[col];
|
||||
a[col] = tmp;
|
||||
}
|
||||
final double d = a[col][col];
|
||||
for (int r = col + 1; r < n; r++) {
|
||||
final double f = a[r][col] / d;
|
||||
if (f == 0) continue;
|
||||
for (int ccol = col; ccol <= n; ccol++) {
|
||||
a[r][ccol] -= f * a[col][ccol];
|
||||
}
|
||||
}
|
||||
}
|
||||
final List<double> x = List<double>.filled(n, 0);
|
||||
for (int i = n - 1; i >= 0; i--) {
|
||||
double s = a[i][n];
|
||||
for (int j = i + 1; j < n; j++) {
|
||||
s -= a[i][j] * x[j];
|
||||
}
|
||||
final double d = a[i][i];
|
||||
if (d.abs() < 1e-12) return null;
|
||||
x[i] = s / d;
|
||||
}
|
||||
return x;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,617 @@
|
||||
/// 架构图模块 UI:工具栏中段 / 右侧工具、左右侧栏、状态栏。
|
||||
///
|
||||
/// 由 `ArchitectureModule` 通过 `lib/modules/registry.dart` 注册后由外壳调用。
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter/material.dart' hide Action;
|
||||
|
||||
import 'package:sequence_diagram/modules/architecture/domain/arch_dxf.dart';
|
||||
import 'package:sequence_diagram/modules/architecture/domain/arch_export.dart';
|
||||
import 'package:sequence_diagram/modules/architecture/domain/arch_models.dart';
|
||||
import 'package:sequence_diagram/modules/architecture/sketch/sketch_models.dart';
|
||||
import 'package:sequence_diagram/modules/architecture/sketch/sketch_solver.dart';
|
||||
import 'package:sequence_diagram/modules/architecture/ui/arch_panel.dart';
|
||||
import 'package:sequence_diagram/modules/architecture/ui/arch_view.dart';
|
||||
import 'package:sequence_diagram/modules/module.dart';
|
||||
import 'package:sequence_diagram/persistence/android_docs.dart';
|
||||
import 'package:sequence_diagram/state/app_controller.dart';
|
||||
import 'package:sequence_diagram/theme/tokens.dart';
|
||||
import 'package:sequence_diagram/ui/dialogs.dart';
|
||||
|
||||
/// 架构图模块 UI 构建器。
|
||||
class ArchitectureUi {
|
||||
/// 构造 UI 构建器。
|
||||
const ArchitectureUi(this.ui);
|
||||
|
||||
/// 外壳上下文。
|
||||
final ModuleUiContext ui;
|
||||
|
||||
AppController get c => ui.controller;
|
||||
BuildContext get context => ui.context;
|
||||
Tokens get t => ui.tokens;
|
||||
double get _toolScale => ui.toolScale;
|
||||
double _toolFont(double size) => ui.toolFont(size);
|
||||
double get _leftPanelWidth => ui.leftPanelWidth;
|
||||
double get _rightPanelWidth => ui.rightPanelWidth;
|
||||
Widget _panelControls(Tokens t, bool left) => ui.panelControls(left);
|
||||
|
||||
/// 工具栏中段:选择 / 手绘 / 连线 / 橡皮 + 识别。
|
||||
List<Widget> buildToolbarCenter(Tokens t, {required bool compact}) =>
|
||||
<Widget>[_archTools(t, compact)];
|
||||
|
||||
/// 工具栏右侧:导出 / 缩放 / 适应视图。
|
||||
List<Widget> buildToolbarRight(Tokens t, {required bool compact}) => <Widget>[
|
||||
_exportMenu(t),
|
||||
SizedBox(width: (compact ? 4 : 6) * _toolScale),
|
||||
_zoomBox(t),
|
||||
SizedBox(width: (compact ? 4 : 6) * _toolScale),
|
||||
_iconBtn(t, Icons.crop_free, c.archFit, tooltip: '适应视图'),
|
||||
];
|
||||
|
||||
/// 左侧栏。
|
||||
Widget buildLeftPanel(Tokens t, {bool floating = false}) =>
|
||||
_archLeftPanel(t, floating: floating);
|
||||
|
||||
/// 右侧栏。
|
||||
Widget buildRightPanel(Tokens t, {bool floating = false}) =>
|
||||
_archRightPanel(t, floating: floating);
|
||||
|
||||
/// 底部状态栏。
|
||||
Widget buildStatusBar(Tokens t) => _archStatusBar(t);
|
||||
|
||||
/// 工作区:架构图画布。
|
||||
Widget buildWorkspace() => Container(
|
||||
color: t.canvas2,
|
||||
child: ArchView(controller: c),
|
||||
);
|
||||
|
||||
|
||||
/// 缩放控件:显示当前百分比并提供缩小 / 放大按钮。
|
||||
Widget _zoomBox(Tokens t) {
|
||||
final double s = _toolScale;
|
||||
final double zoom = c.arch.zoom;
|
||||
final String pct = '${(zoom * 100).round()}%';
|
||||
return Container(
|
||||
height: 34 * s,
|
||||
padding: EdgeInsets.symmetric(horizontal: 4 * s),
|
||||
decoration: BoxDecoration(
|
||||
color: t.panel,
|
||||
borderRadius: BorderRadius.circular(9),
|
||||
border: Border.all(color: t.line2),
|
||||
),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
_miniIcon(t, Icons.remove, () => c.archZoomBy(0.9)),
|
||||
SizedBox(
|
||||
width: 52 * s,
|
||||
child: Text(pct,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: t.text, fontSize: _toolFont(11))),
|
||||
),
|
||||
_miniIcon(t, Icons.add, () => c.archZoomBy(1.1)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 导出菜单:SVG / PNG / DXF。
|
||||
Widget _exportMenu(Tokens t) {
|
||||
final double s = _toolScale;
|
||||
final bool licensed = c.licensed;
|
||||
final Color fg = licensed ? Colors.white : t.dim;
|
||||
return Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 3 * s),
|
||||
child: PopupMenuButton<String>(
|
||||
tooltip: '导出(SVG / PNG / DXF)· 架构图',
|
||||
color: t.panel2,
|
||||
position: PopupMenuPosition.under,
|
||||
onSelected: (String v) {
|
||||
if (v == 'svg') _exportArchSvg();
|
||||
if (v == 'png') _exportArchPng();
|
||||
if (v == 'dxf') _exportArchDxf();
|
||||
},
|
||||
itemBuilder: (BuildContext ctx) => <PopupMenuEntry<String>>[
|
||||
_exportItem(t, 'svg', Icons.code, '导出 SVG',
|
||||
'矢量图:架构图无损缩放 / 二次编辑', licensed),
|
||||
_exportItem(t, 'png', Icons.image_outlined, '导出 PNG',
|
||||
'位图(3840×2160):分享 / 汇报', licensed),
|
||||
_exportItem(t, 'dxf', Icons.architecture, '导出 DXF',
|
||||
'AutoCAD / DraftSight 等可编辑的 CAD 图纸', licensed),
|
||||
],
|
||||
child: Container(
|
||||
height: 34 * s,
|
||||
padding: EdgeInsets.symmetric(horizontal: 12 * s),
|
||||
decoration: BoxDecoration(
|
||||
color: licensed ? t.accent2 : t.panel2,
|
||||
borderRadius: BorderRadius.circular(9),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
Icon(Icons.ios_share, size: 15 * s, color: fg),
|
||||
SizedBox(width: 6 * s),
|
||||
Text('导出',
|
||||
style: TextStyle(
|
||||
fontSize: _toolFont(11),
|
||||
fontWeight: FontWeight.w600,
|
||||
color: fg)),
|
||||
Icon(Icons.arrow_drop_down, size: 18 * s, color: fg),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _archTools(Tokens t, bool compact) {
|
||||
// 草图模式:工具在左侧栏,这里显示状态与快捷退出。
|
||||
if (c.sketchMode) {
|
||||
return Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: 12 * _toolScale),
|
||||
height: 34 * _toolScale,
|
||||
decoration: BoxDecoration(
|
||||
color: t.panel,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: t.accent),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
Icon(Icons.edit_note, size: 15 * _toolScale, color: t.accent),
|
||||
SizedBox(width: 6 * _toolScale),
|
||||
Text(
|
||||
'参数化草图 · ${sketchToolLabel(c.sketchTool)}',
|
||||
style: TextStyle(
|
||||
color: t.accent,
|
||||
fontSize: _toolFont(11),
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
SizedBox(width: 10 * _toolScale),
|
||||
InkWell(
|
||||
onTap: () => c.setSketchMode(false),
|
||||
borderRadius: BorderRadius.circular(7),
|
||||
child: Container(
|
||||
padding: EdgeInsets.symmetric(
|
||||
horizontal: 8 * _toolScale, vertical: 3 * _toolScale),
|
||||
decoration: BoxDecoration(
|
||||
color: t.panel2,
|
||||
borderRadius: BorderRadius.circular(7),
|
||||
border: Border.all(color: t.line),
|
||||
),
|
||||
child: Text('退出草图',
|
||||
style:
|
||||
TextStyle(color: t.sub, fontSize: _toolFont(10.5))),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
final ArchTool tool = c.archTool;
|
||||
Widget seg(String label, IconData icon, ArchTool value, String tip) {
|
||||
final bool active = tool == value;
|
||||
return Tooltip(
|
||||
message: tip,
|
||||
child: InkWell(
|
||||
onTap: () => c.setArchTool(value),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
child: Container(
|
||||
width: (compact ? 74 : 90) * _toolScale,
|
||||
height: 34 * _toolScale,
|
||||
alignment: Alignment.center,
|
||||
decoration: BoxDecoration(
|
||||
color: active ? t.accent.withValues(alpha: 0.16) : Colors.transparent,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: active ? Border.all(color: t.accent, width: 1.4) : null,
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
Icon(icon, size: 15 * _toolScale, color: active ? t.accent : t.sub),
|
||||
SizedBox(width: 4 * _toolScale),
|
||||
Text(label,
|
||||
style: TextStyle(
|
||||
color: active ? t.accent : t.sub,
|
||||
fontWeight: active ? FontWeight.w600 : FontWeight.normal,
|
||||
fontSize: _toolFont(12),
|
||||
)),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
Container(
|
||||
padding: EdgeInsets.all(3 * _toolScale),
|
||||
decoration: BoxDecoration(
|
||||
color: t.panel,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: t.line2),
|
||||
),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
seg('选择', Icons.near_me_outlined, ArchTool.select, '选择 / 移动 / 缩放'),
|
||||
seg('手绘', Icons.gesture, ArchTool.pen,
|
||||
c.archAutoRecognize ? '按住拖动绘制,松手自动识别' : '按住拖动绘制;画完点「识别」确认识别'),
|
||||
seg('连线', Icons.arrow_right_alt, ArchTool.connect,
|
||||
'从图形拖到另一个图形(横平竖直正交走线,角点可拖拽)'),
|
||||
seg('橡皮', Icons.cleaning_services_outlined, ArchTool.eraser,
|
||||
'擦除图形 / 墨迹 / 连线(拖动连擦,一次撤销可整体回退)'),
|
||||
],
|
||||
),
|
||||
),
|
||||
SizedBox(width: 6 * _toolScale),
|
||||
// 「识别」确认按钮:手动模式下把待识别墨迹统一识别(自动模式下也可用)。
|
||||
Container(
|
||||
padding: EdgeInsets.all(3 * _toolScale),
|
||||
decoration: BoxDecoration(
|
||||
color: t.panel,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: t.line2),
|
||||
),
|
||||
child: InkWell(
|
||||
onTap: c.arch.strokes.isEmpty ? null : c.archRecognizeInk,
|
||||
borderRadius: BorderRadius.circular(9),
|
||||
child: Container(
|
||||
height: 34 * _toolScale,
|
||||
padding: EdgeInsets.symmetric(horizontal: 12 * _toolScale),
|
||||
alignment: Alignment.center,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
Icon(Icons.auto_fix_high,
|
||||
size: 15 * _toolScale,
|
||||
color: c.arch.strokes.isEmpty ? t.dim : t.accent),
|
||||
SizedBox(width: 5 * _toolScale),
|
||||
Text(
|
||||
'识别(${c.arch.strokes.length})',
|
||||
style: TextStyle(
|
||||
color: c.arch.strokes.isEmpty ? t.dim : t.accent,
|
||||
fontSize: _toolFont(11),
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _miniIcon(Tokens t, IconData icon, VoidCallback onTap) {
|
||||
return InkWell(
|
||||
onTap: onTap,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(6 * _toolScale),
|
||||
child: Icon(icon, size: 15 * _toolScale, color: t.sub),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
PopupMenuItem<String> _exportItem(
|
||||
Tokens t, String value, IconData icon, String label, String hint, bool enabled) {
|
||||
final Color main = enabled ? t.text : t.dim;
|
||||
return PopupMenuItem<String>(
|
||||
value: value,
|
||||
enabled: enabled,
|
||||
height: 46,
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Icon(icon, size: 17, color: enabled ? t.accent : t.dim),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Text(label,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(color: main, fontSize: 12.5, fontWeight: FontWeight.w600)),
|
||||
Text(hint,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(color: enabled ? t.dim : t.dim.withValues(alpha: 0.6), fontSize: 10)),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _iconBtn(Tokens t, IconData icon, VoidCallback? onTap, {String? tooltip, Color? color}) {
|
||||
final double s = _toolScale;
|
||||
return IconButton(
|
||||
onPressed: onTap,
|
||||
icon: Icon(icon, size: 18 * s, color: onTap == null ? t.dim : (color ?? t.text)),
|
||||
tooltip: tooltip,
|
||||
splashRadius: 16 * s,
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: BoxConstraints(minWidth: 34 * s, minHeight: 34 * s),
|
||||
// 新版 Flutter 的 IconButton 已移除 tapTargetSize 形参,改由 style 提供。
|
||||
style: IconButton.styleFrom(tapTargetSize: s < 1 ? MaterialTapTargetSize.shrinkWrap : null),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _exportArchSvg() async {
|
||||
if (!c.licensed) {
|
||||
if (context.mounted) {
|
||||
await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 SVG。');
|
||||
}
|
||||
return;
|
||||
}
|
||||
final String svg = buildArchSvg(doc: c.arch, baseTokens: Tokens.of(c.brightness));
|
||||
if (AndroidDocs.isAvailable) {
|
||||
final String? name = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (_) => AndroidFileDialog(
|
||||
saveMode: true,
|
||||
defaultName: '${c.project.name}-架构图.svg',
|
||||
suffix: '.svg',
|
||||
),
|
||||
);
|
||||
if (name == null) return;
|
||||
try {
|
||||
await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(svg)),
|
||||
mime: 'image/svg+xml');
|
||||
if (context.mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name');
|
||||
} catch (e) {
|
||||
if (context.mounted) await showMessage(context, '导出失败', '$e');
|
||||
}
|
||||
return;
|
||||
}
|
||||
final String? path = await pickFile(
|
||||
context,
|
||||
save: true,
|
||||
defaultName: '${c.project.name}-架构图.svg',
|
||||
suffix: '.svg',
|
||||
);
|
||||
if (path == null) return;
|
||||
try {
|
||||
await File(path).writeAsString(svg, flush: true);
|
||||
if (context.mounted) c.setStatus('已导出 $path');
|
||||
} catch (e) {
|
||||
if (context.mounted) await showMessage(context, '导出失败', '$e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _exportArchPng() async {
|
||||
if (!c.licensed) {
|
||||
if (context.mounted) {
|
||||
await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 PNG。');
|
||||
}
|
||||
return;
|
||||
}
|
||||
final Uint8List bytes;
|
||||
try {
|
||||
bytes = await renderArchPng(
|
||||
doc: c.arch,
|
||||
baseTokens: Tokens.of(c.brightness),
|
||||
projectName: c.project.name,
|
||||
);
|
||||
} catch (e) {
|
||||
if (context.mounted) await showMessage(context, '导出失败', '$e');
|
||||
return;
|
||||
}
|
||||
if (!context.mounted) return;
|
||||
if (AndroidDocs.isAvailable) {
|
||||
final String? name = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (_) => AndroidFileDialog(
|
||||
saveMode: true,
|
||||
defaultName: '${c.project.name}-架构图.png',
|
||||
suffix: '.png',
|
||||
),
|
||||
);
|
||||
if (name == null) return;
|
||||
try {
|
||||
await AndroidDocs.saveFile(name, bytes, mime: 'image/png');
|
||||
if (context.mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name');
|
||||
} catch (e) {
|
||||
if (context.mounted) await showMessage(context, '导出失败', '$e');
|
||||
}
|
||||
return;
|
||||
}
|
||||
final String? path = await pickFile(
|
||||
context,
|
||||
save: true,
|
||||
defaultName: '${c.project.name}-架构图.png',
|
||||
suffix: '.png',
|
||||
);
|
||||
if (path == null) return;
|
||||
try {
|
||||
await File(path).writeAsBytes(bytes, flush: true);
|
||||
if (context.mounted) c.setStatus('已导出 $path');
|
||||
} catch (e) {
|
||||
if (context.mounted) await showMessage(context, '导出失败', '$e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _exportArchDxf() async {
|
||||
if (!c.licensed) {
|
||||
if (context.mounted) {
|
||||
await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 DXF。');
|
||||
}
|
||||
return;
|
||||
}
|
||||
final String dxf = buildArchDxf(doc: c.arch);
|
||||
if (AndroidDocs.isAvailable) {
|
||||
final String? name = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (_) => AndroidFileDialog(
|
||||
saveMode: true,
|
||||
defaultName: '${c.project.name}-架构图.dxf',
|
||||
suffix: '.dxf',
|
||||
),
|
||||
);
|
||||
if (name == null) return;
|
||||
try {
|
||||
await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(dxf)),
|
||||
mime: 'application/dxf');
|
||||
if (context.mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name');
|
||||
} catch (e) {
|
||||
if (context.mounted) await showMessage(context, '导出失败', '$e');
|
||||
}
|
||||
return;
|
||||
}
|
||||
final String? path = await pickFile(
|
||||
context,
|
||||
save: true,
|
||||
defaultName: '${c.project.name}-架构图.dxf',
|
||||
suffix: '.dxf',
|
||||
);
|
||||
if (path == null) return;
|
||||
try {
|
||||
await File(path).writeAsString(dxf, flush: true);
|
||||
if (context.mounted) c.setStatus('已导出 $path');
|
||||
} catch (e) {
|
||||
if (context.mounted) await showMessage(context, '导出失败', '$e');
|
||||
}
|
||||
}
|
||||
|
||||
Widget _archLeftPanel(Tokens t, {bool floating = false}) {
|
||||
return Container(
|
||||
width: _leftPanelWidth,
|
||||
decoration: BoxDecoration(
|
||||
color: t.panel,
|
||||
border: floating ? Border.all(color: t.line2) : Border(right: BorderSide(color: t.line)),
|
||||
boxShadow: floating
|
||||
? <BoxShadow>[BoxShadow(color: Colors.black.withValues(alpha: 0.4), blurRadius: 20, offset: const Offset(4, 0))]
|
||||
: null,
|
||||
),
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.fromLTRB(12, 10, 12, 12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Row(
|
||||
children: <Widget>[
|
||||
_sectionLabel(t, '架构图 · 设计工具'),
|
||||
const Spacer(),
|
||||
_panelControls(t, true),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
ArchLeftBody(controller: c),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _archRightPanel(Tokens t, {bool floating = false}) {
|
||||
return Container(
|
||||
width: _rightPanelWidth,
|
||||
decoration: BoxDecoration(
|
||||
color: t.panel,
|
||||
border: floating ? Border.all(color: t.line2) : Border(left: BorderSide(color: t.line)),
|
||||
boxShadow: floating
|
||||
? <BoxShadow>[BoxShadow(color: Colors.black.withValues(alpha: 0.4), blurRadius: 20, offset: const Offset(-4, 0))]
|
||||
: null,
|
||||
),
|
||||
child: Column(
|
||||
children: <Widget>[
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 10, 0),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
_sectionLabel(t, '属性 · 架构图'),
|
||||
const Spacer(),
|
||||
_panelControls(t, false),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.fromLTRB(14, 8, 14, 16),
|
||||
child: ArchRightBody(controller: c),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _sectionLabel(Tokens t, String s) => Text(
|
||||
s,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(color: t.text2, fontSize: 11.5, letterSpacing: 1.2, fontWeight: FontWeight.w600),
|
||||
);
|
||||
|
||||
Widget _archStatusBar(Tokens t) {
|
||||
final ArchDoc doc = c.arch;
|
||||
final String toolLabel = c.sketchMode
|
||||
? '草图·${sketchToolLabel(c.sketchTool)}'
|
||||
: switch (c.archTool) {
|
||||
ArchTool.select => '选择',
|
||||
ArchTool.pen => c.archAutoRecognize ? '手绘识别' : '手绘(待确认)',
|
||||
ArchTool.connect => '连线',
|
||||
ArchTool.eraser => '橡皮',
|
||||
};
|
||||
final List<String> items = <String>[
|
||||
c.sketchMode ? '参数化草图' : '架构图模式',
|
||||
if (c.sketchMode) ...<String>[
|
||||
'实体 ${doc.sketch.entities.length}',
|
||||
'约束 ${doc.sketch.constraints.where((SketchConstraint k) => !k.internal).length}',
|
||||
'尺寸 ${doc.sketch.dims.length}',
|
||||
'自由度 ${sketchDofCount(doc.sketch)}',
|
||||
] else ...<String>[
|
||||
'元件 ${doc.shapes.length}',
|
||||
'连线 ${doc.connectors.length}',
|
||||
'墨迹 ${doc.strokes.length}',
|
||||
'图层 ${doc.layerById(doc.activeLayer).name}',
|
||||
],
|
||||
'工具 $toolLabel',
|
||||
if (!c.sketchMode && c.archOrtho) '正交 开',
|
||||
if (!c.sketchMode && c.archPolar) '极轴 ${c.archPolarDeg.round()}°',
|
||||
'缩放 ${(doc.zoom * 100).round()}%',
|
||||
c.status,
|
||||
];
|
||||
return Container(
|
||||
height: 32,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
decoration: BoxDecoration(
|
||||
color: t.chrome,
|
||||
border: Border(top: BorderSide(color: t.line2)),
|
||||
),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
children: items.map((String s) {
|
||||
final bool last = s == items.last;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 22),
|
||||
child: Text(s, style: TextStyle(color: last ? t.ok : t.sub, fontSize: 11)),
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (c.dirty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 14),
|
||||
child: Text('● 未保存', style: TextStyle(color: t.warn, fontSize: 11)),
|
||||
),
|
||||
Text('F1 帮助 · Ctrl+Z 撤销 · Ctrl+S 保存', style: TextStyle(color: t.dim, fontSize: 10)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user