docs: cad-mcp-aec.md 更新工具数(40 个都能加载) #115
No files matched your search
@@ -0,0 +1,229 @@
|
||||
#pragma once
|
||||
// ============================================================================
|
||||
// bvh.h
|
||||
// 2D AABB 层次包围盒 —— 干涉检查的**粗筛**层。
|
||||
//
|
||||
// 纯 C++(不依赖 ObjectARX),header-only,便于复用与推理。
|
||||
//
|
||||
// 相比「按质心中位分割」的朴素实现,这里的取舍:
|
||||
// - 按**质心中位数**沿**较长轴**二分 → 深度严格 O(log n),无退化分支;
|
||||
// - 内部节点记录**子树图元数**,交叉遍历时优先拆较大的一侧,减少无效下降;
|
||||
// - 自相交遍历**每对只报告一次**(叶内 i<j + 子树两两交叉),无重复无自比。
|
||||
//
|
||||
// 坐标约定:x 向右、y 向上;Box 为 (x1,y1)-(x2,y2)。
|
||||
// ============================================================================
|
||||
|
||||
#include <algorithm>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace dwg_bvh
|
||||
{
|
||||
|
||||
// 叶节点最多容纳的图元数:越小查询越快、建树越慢
|
||||
constexpr int kLeafSize = 4;
|
||||
|
||||
struct Box
|
||||
{
|
||||
double x1 = 0.0, y1 = 0.0, x2 = 0.0, y2 = 0.0;
|
||||
|
||||
double width() const { return x2 - x1; }
|
||||
double height() const { return y2 - y1; }
|
||||
double area() const { return width() * height(); }
|
||||
bool valid() const { return x2 >= x1 && y2 >= y1; }
|
||||
|
||||
// 反向极值盒:任何 grow 都能把它撑开(用于求并集)
|
||||
static Box empty()
|
||||
{
|
||||
Box b;
|
||||
b.x1 = b.y1 = 1e300;
|
||||
b.x2 = b.y2 = -1e300;
|
||||
return b;
|
||||
}
|
||||
|
||||
void grow(const Box& o)
|
||||
{
|
||||
if (o.x1 < x1) x1 = o.x1;
|
||||
if (o.y1 < y1) y1 = o.y1;
|
||||
if (o.x2 > x2) x2 = o.x2;
|
||||
if (o.y2 > y2) y2 = o.y2;
|
||||
}
|
||||
|
||||
// 接触即算相交
|
||||
bool intersects(const Box& o) const
|
||||
{
|
||||
return !(x2 < o.x1 || o.x2 < x1 || y2 < o.y1 || o.y2 < y1);
|
||||
}
|
||||
|
||||
// 交集盒(可能退化,调用方自行判断)
|
||||
Box overlap(const Box& o) const
|
||||
{
|
||||
Box r;
|
||||
r.x1 = (x1 > o.x1) ? x1 : o.x1;
|
||||
r.y1 = (y1 > o.y1) ? y1 : o.y1;
|
||||
r.x2 = (x2 < o.x2) ? x2 : o.x2;
|
||||
r.y2 = (y2 < o.y2) ? y2 : o.y2;
|
||||
return r;
|
||||
}
|
||||
};
|
||||
|
||||
struct Primitive
|
||||
{
|
||||
Box box;
|
||||
int payload = -1; // 调用方的索引(如实体在自身数组里的下标)
|
||||
};
|
||||
|
||||
struct Node
|
||||
{
|
||||
Box box;
|
||||
int first = 0; // 叶:图元区间起点;内部:左子节点下标
|
||||
int count = 0; // 叶:图元个数;内部:子树图元总数
|
||||
bool leaf = true;
|
||||
};
|
||||
|
||||
class Tree
|
||||
{
|
||||
public:
|
||||
// 建树(就地重排 prims;payload 随图元一起搬,调用方索引不受影响)
|
||||
void Build(std::vector<Primitive> prims)
|
||||
{
|
||||
m_prims.swap(prims);
|
||||
m_nodes.clear();
|
||||
if (m_prims.empty()) return;
|
||||
m_nodes.reserve(2 * m_prims.size());
|
||||
m_nodes.emplace_back();
|
||||
buildNode(0, 0, static_cast<int>(m_prims.size()));
|
||||
}
|
||||
|
||||
bool empty() const { return m_nodes.empty(); }
|
||||
int size() const { return static_cast<int>(m_prims.size()); }
|
||||
|
||||
// 两两自检:所有包围盒相交的 (payloadA, payloadB),每对仅一次
|
||||
void SelfPairs(std::vector<std::pair<int, int>>& out) const
|
||||
{
|
||||
if (!m_nodes.empty()) selfPairs(0, out);
|
||||
}
|
||||
|
||||
// 查询与 box 相交的 payload
|
||||
void Query(const Box& q, std::vector<int>& out) const
|
||||
{
|
||||
out.clear();
|
||||
if (m_nodes.empty()) return;
|
||||
std::vector<int> stack;
|
||||
stack.push_back(0);
|
||||
while (!stack.empty())
|
||||
{
|
||||
const int idx = stack.back();
|
||||
stack.pop_back();
|
||||
const Node& n = m_nodes[idx];
|
||||
if (!n.box.intersects(q)) continue;
|
||||
if (n.leaf)
|
||||
{
|
||||
const int end = n.first + n.count;
|
||||
for (int i = n.first; i < end; ++i)
|
||||
if (m_prims[i].box.intersects(q)) out.push_back(m_prims[i].payload);
|
||||
}
|
||||
else
|
||||
{
|
||||
stack.push_back(n.first);
|
||||
stack.push_back(n.first + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
void buildNode(int nodeIdx, int first, int count)
|
||||
{
|
||||
Box hull = Box::empty();
|
||||
Box cent = Box::empty();
|
||||
for (int i = first; i < first + count; ++i)
|
||||
{
|
||||
const Box& b = m_prims[i].box;
|
||||
hull.grow(b);
|
||||
Box c;
|
||||
c.x1 = c.x2 = (b.x1 + b.x2) * 0.5;
|
||||
c.y1 = c.y2 = (b.y1 + b.y2) * 0.5;
|
||||
cent.grow(c);
|
||||
}
|
||||
|
||||
m_nodes[nodeIdx].box = hull;
|
||||
m_nodes[nodeIdx].first = first;
|
||||
m_nodes[nodeIdx].count = count;
|
||||
m_nodes[nodeIdx].leaf = true;
|
||||
if (count <= kLeafSize) return;
|
||||
|
||||
const bool byX = cent.width() >= cent.height();
|
||||
const int mid = count / 2;
|
||||
auto begin = m_prims.begin() + first;
|
||||
std::nth_element(begin, begin + mid, begin + count,
|
||||
[byX](const Primitive& a, const Primitive& b)
|
||||
{
|
||||
const double ca = byX ? (a.box.x1 + a.box.x2) : (a.box.y1 + a.box.y2);
|
||||
const double cb = byX ? (b.box.x1 + b.box.x2) : (b.box.y1 + b.box.y2);
|
||||
return ca < cb;
|
||||
});
|
||||
|
||||
// 注意:emplace_back 可能重分配 m_nodes,故不持有 Node& 引用
|
||||
const int leftIdx = static_cast<int>(m_nodes.size());
|
||||
m_nodes.emplace_back();
|
||||
m_nodes.emplace_back();
|
||||
m_nodes[nodeIdx].first = leftIdx;
|
||||
m_nodes[nodeIdx].leaf = false;
|
||||
|
||||
buildNode(leftIdx, first, mid);
|
||||
buildNode(leftIdx + 1, first + mid, count - mid);
|
||||
}
|
||||
|
||||
void selfPairs(int idx, std::vector<std::pair<int, int>>& out) const
|
||||
{
|
||||
const Node& n = m_nodes[idx];
|
||||
if (n.leaf)
|
||||
{
|
||||
const int end = n.first + n.count;
|
||||
for (int i = n.first; i < end; ++i)
|
||||
for (int j = i + 1; j < end; ++j)
|
||||
if (m_prims[i].box.intersects(m_prims[j].box))
|
||||
out.emplace_back(m_prims[i].payload, m_prims[j].payload);
|
||||
return;
|
||||
}
|
||||
selfPairs(n.first, out);
|
||||
selfPairs(n.first + 1, out);
|
||||
crossPairs(n.first, n.first + 1, out);
|
||||
}
|
||||
|
||||
void crossPairs(int a, int b, std::vector<std::pair<int, int>>& out) const
|
||||
{
|
||||
const Node& na = m_nodes[a];
|
||||
const Node& nb = m_nodes[b];
|
||||
if (!na.box.intersects(nb.box)) return;
|
||||
|
||||
if (na.leaf && nb.leaf)
|
||||
{
|
||||
const int ea = na.first + na.count;
|
||||
const int eb = nb.first + nb.count;
|
||||
for (int i = na.first; i < ea; ++i)
|
||||
for (int j = nb.first; j < eb; ++j)
|
||||
if (m_prims[i].box.intersects(m_prims[j].box))
|
||||
out.emplace_back(m_prims[i].payload, m_prims[j].payload);
|
||||
return;
|
||||
}
|
||||
|
||||
// 优先拆「较大」的一侧,让递归更快收敛
|
||||
const bool splitA = nb.leaf || (!na.leaf && na.count >= nb.count);
|
||||
if (splitA)
|
||||
{
|
||||
crossPairs(na.first, b, out);
|
||||
crossPairs(na.first + 1, b, out);
|
||||
}
|
||||
else
|
||||
{
|
||||
crossPairs(a, nb.first, out);
|
||||
crossPairs(a, nb.first + 1, out);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<Primitive> m_prims;
|
||||
std::vector<Node> m_nodes;
|
||||
};
|
||||
|
||||
} // namespace dwg_bvh
|
||||
@@ -10,6 +10,11 @@ set(SOURCES
|
||||
"dwg_review_frame.cpp"
|
||||
"dwg_review_check.cpp"
|
||||
"dwg_review_view.cpp"
|
||||
"dwg_review_ui.cpp"
|
||||
"find_collisions.cpp"
|
||||
"dwg_annotate_common.cpp"
|
||||
"dwg_annotate_draw.cpp"
|
||||
"dwg_annotate_edit.cpp"
|
||||
"StdAfx.cpp"
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
#include "KTCad.h"
|
||||
#include "dwg_annotate_common.h"
|
||||
#include "dbcolor.h" // AcCmColor
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
// windows.h(经 afxwin.h)把 min/max 定义成宏,会顶掉下面的 std::min / std::max
|
||||
// (CadProject 那边的 cadsdk.h 里带了 NOMINMAX,本仓库的 KTCad.h 没有)。
|
||||
#undef min
|
||||
#undef max
|
||||
|
||||
|
||||
namespace dwg_annotate
|
||||
{
|
||||
|
||||
DocLock::DocLock()
|
||||
: m_bLocked(false), m_pDoc(NULL)
|
||||
{
|
||||
m_pDoc = acDocManager->curDocument();
|
||||
if (m_pDoc != NULL && acDocManager->lockDocument(m_pDoc) == Acad::eOk)
|
||||
m_bLocked = true;
|
||||
}
|
||||
|
||||
DocLock::~DocLock()
|
||||
{
|
||||
if (m_bLocked && m_pDoc != NULL)
|
||||
acDocManager->unlockDocument(m_pDoc);
|
||||
}
|
||||
|
||||
using namespace dwg_review;
|
||||
|
||||
const char* kDefaultAnnotLayer = "AI_REVIEW";
|
||||
|
||||
// ===========================================================================
|
||||
// 编码
|
||||
// ===========================================================================
|
||||
|
||||
std::wstring utf8ToWStr(const std::string& s)
|
||||
{
|
||||
if (s.empty()) return std::wstring();
|
||||
int len = ::MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), NULL, 0);
|
||||
if (len <= 0) return std::wstring();
|
||||
std::wstring out((size_t)len, L'\0');
|
||||
::MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), &out[0], len);
|
||||
return out;
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// 图层
|
||||
// ===========================================================================
|
||||
|
||||
bool ensureLayer(AcDbDatabase* pDb, const std::string& name, int aciColor)
|
||||
{
|
||||
if (!pDb || name.empty()) return false;
|
||||
const std::wstring wn = utf8ToWStr(name);
|
||||
|
||||
// 已存在则直接返回
|
||||
AcDbLayerTable* pLT = nullptr;
|
||||
if (pDb->getLayerTable(pLT, AcDb::kForRead) == Acad::eOk && pLT)
|
||||
{
|
||||
const bool exists = pLT->has(wn.c_str());
|
||||
pLT->close();
|
||||
if (exists) return true;
|
||||
}
|
||||
|
||||
// 创建新图层
|
||||
if (pDb->getLayerTable(pLT, AcDb::kForWrite) != Acad::eOk || !pLT) return false;
|
||||
|
||||
AcDbLayerTableRecord* pRec = new AcDbLayerTableRecord();
|
||||
pRec->setName(wn.c_str());
|
||||
AcCmColor color;
|
||||
color.setColorIndex((Adesk::UInt16)aciColor);
|
||||
pRec->setColor(color);
|
||||
|
||||
const Acad::ErrorStatus es = pLT->add(pRec);
|
||||
pRec->close();
|
||||
pLT->close();
|
||||
return es == Acad::eOk || es == Acad::eDuplicateRecordName;
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// 空间
|
||||
// ===========================================================================
|
||||
|
||||
AcDbBlockTableRecord* openWriteSpace(AcDbDatabase* pDb, const std::string& space)
|
||||
{
|
||||
if (!pDb) return nullptr;
|
||||
|
||||
AcDbBlockTable* pBT = nullptr;
|
||||
if (pDb->getBlockTable(pBT, AcDb::kForRead) != Acad::eOk || !pBT) return nullptr;
|
||||
|
||||
AcDbBlockTableRecord* pRec = nullptr;
|
||||
if (space.empty() || space == "Model" || space == "model")
|
||||
{
|
||||
pBT->getAt(ACDB_MODEL_SPACE, pRec, AcDb::kForWrite);
|
||||
}
|
||||
else
|
||||
{
|
||||
AcDbObjectId id;
|
||||
const std::wstring ws = utf8ToWStr(space);
|
||||
if (pBT->getAt(ws.c_str(), id) == Acad::eOk)
|
||||
acdbOpenObject(pRec, id, AcDb::kForWrite);
|
||||
}
|
||||
pBT->close();
|
||||
return pRec;
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// 参数解析
|
||||
// ===========================================================================
|
||||
|
||||
bool parsePoint(const nlohmann::json& j, AcGePoint3d& out)
|
||||
{
|
||||
if (j.is_array() && j.size() >= 2)
|
||||
{
|
||||
out.x = j[0].get<double>();
|
||||
out.y = j[1].get<double>();
|
||||
out.z = (j.size() >= 3) ? j[2].get<double>() : 0.0;
|
||||
return true;
|
||||
}
|
||||
if (j.is_object() && j.contains("x") && j.contains("y"))
|
||||
{
|
||||
out.x = j["x"].get<double>();
|
||||
out.y = j["y"].get<double>();
|
||||
out.z = j.contains("z") ? j["z"].get<double>() : 0.0;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool parsePoints(const nlohmann::json& arr, std::vector<AcGePoint3d>& out)
|
||||
{
|
||||
out.clear();
|
||||
if (!arr.is_array()) return false;
|
||||
for (size_t i = 0; i < arr.size(); ++i)
|
||||
{
|
||||
AcGePoint3d p;
|
||||
if (!parsePoint(arr[i], p)) { out.clear(); return false; }
|
||||
out.push_back(p);
|
||||
}
|
||||
return !out.empty();
|
||||
}
|
||||
|
||||
bool parseWindow(const nlohmann::json& args, double& x1, double& y1, double& x2, double& y2)
|
||||
{
|
||||
if (args.contains("window") && args["window"].is_object())
|
||||
{
|
||||
const nlohmann::json& w = args["window"];
|
||||
if (w.contains("min_x") && w.contains("min_y") && w.contains("max_x") && w.contains("max_y"))
|
||||
{
|
||||
x1 = w["min_x"].get<double>(); y1 = w["min_y"].get<double>();
|
||||
x2 = w["max_x"].get<double>(); y2 = w["max_y"].get<double>();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (args.contains("min_x") && args.contains("min_y") &&
|
||||
args.contains("max_x") && args.contains("max_y"))
|
||||
{
|
||||
x1 = args["min_x"].get<double>(); y1 = args["min_y"].get<double>();
|
||||
x2 = args["max_x"].get<double>(); y2 = args["max_y"].get<double>();
|
||||
return true;
|
||||
}
|
||||
if (args.contains("p1") && args.contains("p2"))
|
||||
{
|
||||
AcGePoint3d a, b;
|
||||
if (parsePoint(args["p1"], a) && parsePoint(args["p2"], b))
|
||||
{
|
||||
x1 = (std::min)(a.x, b.x); y1 = (std::min)(a.y, b.y);
|
||||
x2 = (std::max)(a.x, b.x); y2 = (std::max)(a.y, b.y);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<std::string> collectHandlesArg(const nlohmann::json& args)
|
||||
{
|
||||
std::vector<std::string> hs;
|
||||
if (args.contains("handle") && args["handle"].is_string())
|
||||
hs.push_back(args["handle"].get<std::string>());
|
||||
if (args.contains("handles") && args["handles"].is_array())
|
||||
{
|
||||
for (size_t i = 0; i < args["handles"].size(); ++i)
|
||||
if (args["handles"][i].is_string())
|
||||
hs.push_back(args["handles"][i].get<std::string>());
|
||||
}
|
||||
return hs;
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// 公共参数默认值
|
||||
// ===========================================================================
|
||||
|
||||
std::string getLayerArg(const nlohmann::json& args)
|
||||
{
|
||||
if (args.contains("layer") && args["layer"].is_string())
|
||||
return args["layer"].get<std::string>();
|
||||
return std::string(kDefaultAnnotLayer);
|
||||
}
|
||||
|
||||
int getColorArg(const nlohmann::json& args, int def)
|
||||
{
|
||||
if (args.contains("color") && args["color"].is_number_integer())
|
||||
return args["color"].get<int>();
|
||||
return def;
|
||||
}
|
||||
|
||||
std::string getSpaceArg(const nlohmann::json& args)
|
||||
{
|
||||
if (args.contains("space") && args["space"].is_string())
|
||||
return args["space"].get<std::string>();
|
||||
return std::string("Model");
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// 实体写入
|
||||
// ===========================================================================
|
||||
|
||||
void applyLayerColor(AcDbEntity* pEnt, const std::string& layer, int aciColor)
|
||||
{
|
||||
if (!pEnt) return;
|
||||
if (!layer.empty())
|
||||
{
|
||||
const std::wstring wl = utf8ToWStr(layer);
|
||||
pEnt->setLayer(wl.c_str());
|
||||
}
|
||||
pEnt->setColorIndex((Adesk::UInt16)aciColor);
|
||||
}
|
||||
|
||||
AcDbObjectId appendToSpace(AcDbBlockTableRecord* pSpace, AcDbEntity* pEnt)
|
||||
{
|
||||
AcDbObjectId id = AcDbObjectId::kNull;
|
||||
if (!pEnt) return id;
|
||||
if (!pSpace)
|
||||
{
|
||||
pEnt->close();
|
||||
return id;
|
||||
}
|
||||
if (pSpace->appendAcDbEntity(id, pEnt) != Acad::eOk)
|
||||
id = AcDbObjectId::kNull;
|
||||
pEnt->close();
|
||||
return id;
|
||||
}
|
||||
|
||||
std::string handleOfId(AcDbDatabase* pDb, const AcDbObjectId& id)
|
||||
{
|
||||
if (!pDb || id == AcDbObjectId::kNull) return std::string();
|
||||
AcDbEntity* pEnt = nullptr;
|
||||
if (acdbOpenObject(pEnt, id, AcDb::kForRead) != Acad::eOk || !pEnt) return std::string();
|
||||
const std::string h = handleOf(pEnt);
|
||||
pEnt->close();
|
||||
return h;
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// 结果构造
|
||||
// ===========================================================================
|
||||
|
||||
nlohmann::json makeCreatedItem(AcDbDatabase* pDb, const AcDbObjectId& id,
|
||||
const std::string& type, const std::string& layer)
|
||||
{
|
||||
nlohmann::json item;
|
||||
item["handle"] = handleOfId(pDb, id);
|
||||
item["type"] = type;
|
||||
item["layer"] = layer;
|
||||
return item;
|
||||
}
|
||||
|
||||
nlohmann::json createdResult(const std::vector<nlohmann::json>& created)
|
||||
{
|
||||
nlohmann::json r;
|
||||
r["ok"] = true;
|
||||
r["count"] = (int)created.size();
|
||||
r["created"] = created;
|
||||
return makeJsonResult(r);
|
||||
}
|
||||
|
||||
} // namespace dwg_annotate
|
||||
@@ -0,0 +1,83 @@
|
||||
#pragma once
|
||||
// ============================================================================
|
||||
// dwg_annotate_common.h
|
||||
// 图纸批注工具集 - 公共辅助层
|
||||
//
|
||||
// 供 dwg_annotate_draw / dwg_annotate_edit 共用,避免重复实现:
|
||||
// - 批注图层自动创建(默认 AI_REVIEW)
|
||||
// - 以 kForWrite 打开目标空间
|
||||
// - UTF-8 <-> 宽字符、点/窗口参数解析
|
||||
// - 图层/颜色设置、实体 append 与关闭
|
||||
// - 统一创建结果构造
|
||||
//
|
||||
// 依赖 dwg_review_common(复用其 handleOf / makeJsonResult / makeError /
|
||||
// objectIdFromHandle / kErr* 等)。
|
||||
// ============================================================================
|
||||
|
||||
#include "KTCad.h"
|
||||
#include "dwg_review_common.h"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
namespace dwg_annotate
|
||||
{
|
||||
|
||||
// 默认批注图层名
|
||||
extern const char* kDefaultAnnotLayer;
|
||||
|
||||
// 写数据库前必须拿文档锁:MCP 工具是在主线程的消息里跑的,**不在命令上下文**,
|
||||
// 不锁的话 kForWrite 打开块表记录 / appendAcDbEntity 会返回 Acad::eLockViolation(0x140),
|
||||
// 表现为 "cannot open target space for write"。
|
||||
// (与 cad_mcp_aec 的 DocLock 同一套办法;各 Execute 开头构造一个,析构自动解锁。)
|
||||
class DocLock
|
||||
{
|
||||
public:
|
||||
DocLock();
|
||||
~DocLock();
|
||||
bool ok() const { return m_bLocked; }
|
||||
|
||||
private:
|
||||
DocLock(const DocLock&);
|
||||
DocLock& operator=(const DocLock&);
|
||||
|
||||
bool m_bLocked;
|
||||
AcApDocument* m_pDoc;
|
||||
};
|
||||
|
||||
// 确保图层存在(不存在则以给定 ACI 颜色创建)
|
||||
bool ensureLayer(AcDbDatabase* pDb, const std::string& name, int aciColor);
|
||||
|
||||
// 以 kForWrite 打开指定空间的块表记录(成功返回的对象需调用者 close)
|
||||
AcDbBlockTableRecord* openWriteSpace(AcDbDatabase* pDb, const std::string& space);
|
||||
|
||||
// UTF-8 -> 宽字符
|
||||
std::wstring utf8ToWStr(const std::string& s);
|
||||
|
||||
// ---------- 参数解析 ----------
|
||||
// 点:[x,y] / [x,y,z] / {"x":..,"y":..,"z":..}
|
||||
bool parsePoint(const nlohmann::json& j, AcGePoint3d& out);
|
||||
bool parsePoints(const nlohmann::json& arr, std::vector<AcGePoint3d>& out);
|
||||
// 窗口:window 对象 或 min_x/min_y/max_x/max_y 或 p1/p2 两角点
|
||||
bool parseWindow(const nlohmann::json& args, double& x1, double& y1, double& x2, double& y2);
|
||||
// 句柄列表:handle / handles
|
||||
std::vector<std::string> collectHandlesArg(const nlohmann::json& args);
|
||||
|
||||
// ---------- 公共参数默认值 ----------
|
||||
std::string getLayerArg(const nlohmann::json& args); // 默认 AI_REVIEW
|
||||
int getColorArg(const nlohmann::json& args, int def = 256); // 默认 ByLayer
|
||||
std::string getSpaceArg(const nlohmann::json& args); // 默认 Model
|
||||
|
||||
// ---------- 实体写入 ----------
|
||||
void applyLayerColor(AcDbEntity* pEnt, const std::string& layer, int aciColor);
|
||||
// append 到空间并 close 实体,返回 ObjectId(kNull = 失败)
|
||||
AcDbObjectId appendToSpace(AcDbBlockTableRecord* pSpace, AcDbEntity* pEnt);
|
||||
std::string handleOfId(AcDbDatabase* pDb, const AcDbObjectId& id);
|
||||
|
||||
// ---------- 结果构造 ----------
|
||||
nlohmann::json makeCreatedItem(AcDbDatabase* pDb, const AcDbObjectId& id,
|
||||
const std::string& type, const std::string& layer);
|
||||
// 包装为 MCP 文本信封:{"ok":true,"count":N,"created":[...]}
|
||||
nlohmann::json createdResult(const std::vector<nlohmann::json>& created);
|
||||
|
||||
} // namespace dwg_annotate
|
||||
@@ -0,0 +1,502 @@
|
||||
// ============================================================================
|
||||
// dwg_annotate_draw.cpp
|
||||
// 图纸批注 - 绘制类工具(均为 c++_dll 后端)
|
||||
// draw_revision_cloud : 修订云线(rect / polygon / circle)
|
||||
// add_text : 单行文字 AcDbText
|
||||
// add_mtext : 多行文字 AcDbMText
|
||||
// add_polyline : 多段线 AcDbPolyline
|
||||
// add_line : 直线 AcDbLine
|
||||
// add_leader_annotation : 引线批注 AcDbLeader + AcDbMText
|
||||
//
|
||||
// 所有批注默认落在 AI_REVIEW 图层(不存在则自动创建),可在参数中覆盖。
|
||||
// ============================================================================
|
||||
|
||||
#include "KTCad.h"
|
||||
#include "dwg_annotate_common.h"
|
||||
#include "mcp_plugin_api.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// windows.h(经 afxwin.h)把 min/max 定义成宏,会顶掉下面的 std::min / std::max
|
||||
// (CadProject 那边的 cadsdk.h 里带了 NOMINMAX,本仓库的 KTCad.h 没有)。
|
||||
#undef min
|
||||
#undef max
|
||||
|
||||
|
||||
using namespace dwg_annotate;
|
||||
using namespace dwg_review;
|
||||
|
||||
namespace
|
||||
{
|
||||
const double kPi = 3.14159265358979323846;
|
||||
|
||||
// 圆采样为闭合多边形顶点
|
||||
void circleToPoints(double cx, double cy, double r, int n, std::vector<AcGePoint2d>& out)
|
||||
{
|
||||
out.clear();
|
||||
if (n < 3) n = 3;
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
const double a = 2.0 * kPi * i / n;
|
||||
out.push_back(AcGePoint2d(cx + r * std::cos(a), cy + r * std::sin(a)));
|
||||
}
|
||||
}
|
||||
|
||||
// 在闭合多边形基础上细分并逐顶点设凸度,得到云线
|
||||
void buildCloudPolyline(AcDbPolyline& pl, const std::vector<AcGePoint2d>& base,
|
||||
double bulge, double chord)
|
||||
{
|
||||
const size_t n = base.size();
|
||||
if (n < 3) return;
|
||||
|
||||
if (chord <= 1e-9)
|
||||
{
|
||||
double minx = base[0].x, maxx = base[0].x, miny = base[0].y, maxy = base[0].y;
|
||||
for (size_t i = 1; i < n; ++i)
|
||||
{
|
||||
minx = (std::min)(minx, base[i].x); maxx = (std::max)(maxx, base[i].x);
|
||||
miny = (std::min)(miny, base[i].y); maxy = (std::max)(maxy, base[i].y);
|
||||
}
|
||||
const double diag = std::sqrt((maxx - minx) * (maxx - minx) + (maxy - miny) * (maxy - miny));
|
||||
chord = diag / 16.0;
|
||||
if (chord < 1e-6) chord = 1.0;
|
||||
}
|
||||
|
||||
unsigned int idx = 0;
|
||||
for (size_t i = 0; i < n; ++i)
|
||||
{
|
||||
const AcGePoint2d& a = base[i];
|
||||
const AcGePoint2d& b = base[(i + 1) % n];
|
||||
const double len = a.distanceTo(b);
|
||||
int k = (int)std::floor(len / chord + 0.5);
|
||||
if (k < 1) k = 1;
|
||||
for (int s = 0; s < k; ++s)
|
||||
{
|
||||
const double t = (double)s / (double)k;
|
||||
pl.addVertexAt(idx++, AcGePoint2d(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t));
|
||||
}
|
||||
}
|
||||
pl.setClosed(Adesk::kTrue);
|
||||
|
||||
const unsigned int total = pl.numVerts();
|
||||
for (unsigned int i = 0; i < total; ++i)
|
||||
pl.setBulgeAt(i, bulge);
|
||||
}
|
||||
|
||||
// 字符串 -> MText 对齐点
|
||||
AcDbMText::AttachmentPoint attachmentFromString(const std::string& s,
|
||||
AcDbMText::AttachmentPoint def)
|
||||
{
|
||||
if (s == "top_left") return AcDbMText::kTopLeft;
|
||||
if (s == "top_center") return AcDbMText::kTopCenter;
|
||||
if (s == "top_right") return AcDbMText::kTopRight;
|
||||
if (s == "middle_left") return AcDbMText::kMiddleLeft;
|
||||
if (s == "middle_center" || s == "center") return AcDbMText::kMiddleCenter;
|
||||
if (s == "middle_right") return AcDbMText::kMiddleRight;
|
||||
if (s == "bottom_left") return AcDbMText::kBottomLeft;
|
||||
if (s == "bottom_center")return AcDbMText::kBottomCenter;
|
||||
if (s == "bottom_right") return AcDbMText::kBottomRight;
|
||||
return def;
|
||||
}
|
||||
|
||||
// 按名称解析文字样式 id(失败返回 kNull)
|
||||
AcDbObjectId resolveTextStyle(AcDbDatabase* pDb, const std::string& name)
|
||||
{
|
||||
AcDbObjectId id = AcDbObjectId::kNull;
|
||||
if (!pDb || name.empty()) return id;
|
||||
AcDbTextStyleTable* pTST = nullptr;
|
||||
if (pDb->getTextStyleTable(pTST, AcDb::kForRead) == Acad::eOk && pTST)
|
||||
{
|
||||
const std::wstring wn = utf8ToWStr(name);
|
||||
pTST->getAt(wn.c_str(), id);
|
||||
pTST->close();
|
||||
}
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// draw_revision_cloud
|
||||
// ===========================================================================
|
||||
class mcp_Tool_DrawRevisionCloud : public mcp_Tool
|
||||
{
|
||||
public:
|
||||
nlohmann::json Execute(const nlohmann::json& args) override
|
||||
{
|
||||
AcDbDatabase* pDb = acdbHostApplicationServices()->workingDatabase();
|
||||
if (!pDb) return makeError(kErrNoDocument, "no working database");
|
||||
|
||||
DocLock lock; // 写库前先锁文档,见 dwg_annotate_common.h
|
||||
if (!lock.ok()) return makeError(kErrInternal, "cannot lock drawing document");
|
||||
|
||||
const std::string shape = args.value("shape", std::string("rect"));
|
||||
const double bulge = args.value("bulge", 0.5);
|
||||
const double chord = args.value("chord", 0.0);
|
||||
|
||||
std::vector<AcGePoint2d> base;
|
||||
|
||||
if (shape == "rect")
|
||||
{
|
||||
double x1, y1, x2, y2;
|
||||
if (!parseWindow(args, x1, y1, x2, y2))
|
||||
return makeError(kErrBadParam,
|
||||
"rect cloud requires min_x/min_y/max_x/max_y or window or p1/p2");
|
||||
base.push_back(AcGePoint2d(x1, y1));
|
||||
base.push_back(AcGePoint2d(x2, y1));
|
||||
base.push_back(AcGePoint2d(x2, y2));
|
||||
base.push_back(AcGePoint2d(x1, y2));
|
||||
}
|
||||
else if (shape == "polygon")
|
||||
{
|
||||
std::vector<AcGePoint3d> pts;
|
||||
if (!args.contains("points") || !parsePoints(args["points"], pts) || pts.size() < 3)
|
||||
return makeError(kErrBadParam, "polygon cloud requires points (>=3)");
|
||||
for (size_t i = 0; i < pts.size(); ++i)
|
||||
base.push_back(AcGePoint2d(pts[i].x, pts[i].y));
|
||||
}
|
||||
else if (shape == "circle")
|
||||
{
|
||||
AcGePoint3d c;
|
||||
if (!args.contains("center") || !parsePoint(args["center"], c))
|
||||
return makeError(kErrBadParam, "circle cloud requires center [x,y]");
|
||||
const double r = args.value("radius", 0.0);
|
||||
if (r <= 1e-9) return makeError(kErrBadParam, "circle cloud requires positive radius");
|
||||
|
||||
double ch = chord;
|
||||
if (ch <= 1e-9) ch = 2.0 * kPi * r / 12.0;
|
||||
if (ch < 1e-6) ch = r / 3.0;
|
||||
int n = (int)std::floor(2.0 * kPi * r / ch + 0.5);
|
||||
if (n < 8) n = 8;
|
||||
circleToPoints(c.x, c.y, r, n, base);
|
||||
}
|
||||
else
|
||||
{
|
||||
return makeError(kErrBadParam, "shape must be rect|polygon|circle");
|
||||
}
|
||||
|
||||
AcDbBlockTableRecord* pSpace = openWriteSpace(pDb, getSpaceArg(args));
|
||||
if (!pSpace) return makeError(kErrNoDocument, "cannot open target space for write");
|
||||
|
||||
const std::string layer = getLayerArg(args);
|
||||
ensureLayer(pDb, layer, 1);
|
||||
|
||||
AcDbPolyline* pl = new AcDbPolyline();
|
||||
buildCloudPolyline(*pl, base, bulge, chord);
|
||||
applyLayerColor(pl, layer, getColorArg(args));
|
||||
|
||||
const AcDbObjectId id = appendToSpace(pSpace, pl);
|
||||
pSpace->close();
|
||||
if (id == AcDbObjectId::kNull) return makeError(kErrInternal, "append failed");
|
||||
|
||||
std::vector<nlohmann::json> created;
|
||||
created.push_back(makeCreatedItem(pDb, id, "LWPOLYLINE", layer));
|
||||
return createdResult(created);
|
||||
}
|
||||
};
|
||||
EXPORT_MCP_TOOL(mcp_Tool_DrawRevisionCloud, CreateDrawRevisionCloudTool)
|
||||
|
||||
// ===========================================================================
|
||||
// add_text(单行文字)
|
||||
// ===========================================================================
|
||||
class mcp_Tool_AddText : public mcp_Tool
|
||||
{
|
||||
public:
|
||||
nlohmann::json Execute(const nlohmann::json& args) override
|
||||
{
|
||||
AcDbDatabase* pDb = acdbHostApplicationServices()->workingDatabase();
|
||||
if (!pDb) return makeError(kErrNoDocument, "no working database");
|
||||
|
||||
DocLock lock; // 写库前先锁文档,见 dwg_annotate_common.h
|
||||
if (!lock.ok()) return makeError(kErrInternal, "cannot lock drawing document");
|
||||
|
||||
if (!args.contains("text") || !args["text"].is_string())
|
||||
return makeError(kErrBadParam, "text is required");
|
||||
const std::string text = args["text"].get<std::string>();
|
||||
|
||||
AcGePoint3d pos;
|
||||
if (args.contains("position"))
|
||||
{
|
||||
if (!parsePoint(args["position"], pos)) return makeError(kErrBadParam, "invalid position");
|
||||
}
|
||||
else if (args.contains("x") && args.contains("y"))
|
||||
{
|
||||
pos.x = args["x"].get<double>(); pos.y = args["y"].get<double>(); pos.z = 0.0;
|
||||
}
|
||||
else return makeError(kErrBadParam, "position [x,y] is required");
|
||||
|
||||
double height = args.value("height", 2.5);
|
||||
if (height <= 1e-9) height = 2.5;
|
||||
const double rot = args.value("rotation", 0.0) * kPi / 180.0;
|
||||
|
||||
AcDbBlockTableRecord* pSpace = openWriteSpace(pDb, getSpaceArg(args));
|
||||
if (!pSpace) return makeError(kErrNoDocument, "cannot open target space for write");
|
||||
|
||||
const std::string layer = getLayerArg(args);
|
||||
ensureLayer(pDb, layer, 1);
|
||||
|
||||
const std::wstring wtext = utf8ToWStr(text);
|
||||
AcDbText* pText = new AcDbText(pos, wtext.c_str(), AcDbObjectId::kNull, height, rot);
|
||||
applyLayerColor(pText, layer, getColorArg(args));
|
||||
|
||||
if (args.contains("text_style") && args["text_style"].is_string())
|
||||
{
|
||||
const AcDbObjectId sid = resolveTextStyle(pDb, args["text_style"].get<std::string>());
|
||||
if (sid != AcDbObjectId::kNull) pText->setTextStyle(sid);
|
||||
}
|
||||
|
||||
const AcDbObjectId id = appendToSpace(pSpace, pText);
|
||||
pSpace->close();
|
||||
if (id == AcDbObjectId::kNull) return makeError(kErrInternal, "append failed");
|
||||
|
||||
std::vector<nlohmann::json> created;
|
||||
created.push_back(makeCreatedItem(pDb, id, "TEXT", layer));
|
||||
return createdResult(created);
|
||||
}
|
||||
};
|
||||
EXPORT_MCP_TOOL(mcp_Tool_AddText, CreateAddTextTool)
|
||||
|
||||
// ===========================================================================
|
||||
// add_mtext(多行文字)
|
||||
// ===========================================================================
|
||||
class mcp_Tool_AddMText : public mcp_Tool
|
||||
{
|
||||
public:
|
||||
nlohmann::json Execute(const nlohmann::json& args) override
|
||||
{
|
||||
AcDbDatabase* pDb = acdbHostApplicationServices()->workingDatabase();
|
||||
if (!pDb) return makeError(kErrNoDocument, "no working database");
|
||||
|
||||
DocLock lock; // 写库前先锁文档,见 dwg_annotate_common.h
|
||||
if (!lock.ok()) return makeError(kErrInternal, "cannot lock drawing document");
|
||||
|
||||
if (!args.contains("text") || !args["text"].is_string())
|
||||
return makeError(kErrBadParam, "text is required");
|
||||
const std::string text = args["text"].get<std::string>();
|
||||
|
||||
AcGePoint3d pos;
|
||||
if (args.contains("position"))
|
||||
{
|
||||
if (!parsePoint(args["position"], pos)) return makeError(kErrBadParam, "invalid position");
|
||||
}
|
||||
else if (args.contains("x") && args.contains("y"))
|
||||
{
|
||||
pos.x = args["x"].get<double>(); pos.y = args["y"].get<double>(); pos.z = 0.0;
|
||||
}
|
||||
else return makeError(kErrBadParam, "position [x,y] is required");
|
||||
|
||||
double height = args.value("height", 2.5);
|
||||
if (height <= 1e-9) height = 2.5;
|
||||
const double width = args.value("width", 0.0);
|
||||
const double rot = args.value("rotation", 0.0) * kPi / 180.0;
|
||||
|
||||
AcDbMText::AttachmentPoint att = AcDbMText::kTopLeft;
|
||||
if (args.contains("attachment") && args["attachment"].is_string())
|
||||
att = attachmentFromString(args["attachment"].get<std::string>(), att);
|
||||
|
||||
AcDbBlockTableRecord* pSpace = openWriteSpace(pDb, getSpaceArg(args));
|
||||
if (!pSpace) return makeError(kErrNoDocument, "cannot open target space for write");
|
||||
|
||||
const std::string layer = getLayerArg(args);
|
||||
ensureLayer(pDb, layer, 1);
|
||||
|
||||
const std::wstring wtext = utf8ToWStr(text);
|
||||
AcDbMText* pM = new AcDbMText();
|
||||
pM->setContents(wtext.c_str());
|
||||
pM->setTextHeight(height);
|
||||
pM->setLocation(pos);
|
||||
if (width > 1e-9) pM->setWidth(width);
|
||||
pM->setRotation(rot);
|
||||
pM->setAttachment(att);
|
||||
applyLayerColor(pM, layer, getColorArg(args));
|
||||
|
||||
if (args.contains("text_style") && args["text_style"].is_string())
|
||||
{
|
||||
const AcDbObjectId sid = resolveTextStyle(pDb, args["text_style"].get<std::string>());
|
||||
if (sid != AcDbObjectId::kNull) pM->setTextStyle(sid);
|
||||
}
|
||||
|
||||
const AcDbObjectId id = appendToSpace(pSpace, pM);
|
||||
pSpace->close();
|
||||
if (id == AcDbObjectId::kNull) return makeError(kErrInternal, "append failed");
|
||||
|
||||
std::vector<nlohmann::json> created;
|
||||
created.push_back(makeCreatedItem(pDb, id, "MTEXT", layer));
|
||||
return createdResult(created);
|
||||
}
|
||||
};
|
||||
EXPORT_MCP_TOOL(mcp_Tool_AddMText, CreateAddMTextTool)
|
||||
|
||||
// ===========================================================================
|
||||
// add_polyline
|
||||
// ===========================================================================
|
||||
class mcp_Tool_AddPolyline : public mcp_Tool
|
||||
{
|
||||
public:
|
||||
nlohmann::json Execute(const nlohmann::json& args) override
|
||||
{
|
||||
AcDbDatabase* pDb = acdbHostApplicationServices()->workingDatabase();
|
||||
if (!pDb) return makeError(kErrNoDocument, "no working database");
|
||||
|
||||
DocLock lock; // 写库前先锁文档,见 dwg_annotate_common.h
|
||||
if (!lock.ok()) return makeError(kErrInternal, "cannot lock drawing document");
|
||||
|
||||
std::vector<AcGePoint3d> pts;
|
||||
if (!args.contains("points") || !parsePoints(args["points"], pts) || pts.size() < 2)
|
||||
return makeError(kErrBadParam, "points (>=2) is required");
|
||||
|
||||
const bool closed = args.value("closed", false);
|
||||
|
||||
AcDbBlockTableRecord* pSpace = openWriteSpace(pDb, getSpaceArg(args));
|
||||
if (!pSpace) return makeError(kErrNoDocument, "cannot open target space for write");
|
||||
|
||||
const std::string layer = getLayerArg(args);
|
||||
ensureLayer(pDb, layer, 1);
|
||||
|
||||
AcDbPolyline* pl = new AcDbPolyline();
|
||||
for (size_t i = 0; i < pts.size(); ++i)
|
||||
pl->addVertexAt((unsigned int)i, AcGePoint2d(pts[i].x, pts[i].y));
|
||||
pl->setClosed(closed ? Adesk::kTrue : Adesk::kFalse);
|
||||
applyLayerColor(pl, layer, getColorArg(args));
|
||||
|
||||
const AcDbObjectId id = appendToSpace(pSpace, pl);
|
||||
pSpace->close();
|
||||
if (id == AcDbObjectId::kNull) return makeError(kErrInternal, "append failed");
|
||||
|
||||
std::vector<nlohmann::json> created;
|
||||
created.push_back(makeCreatedItem(pDb, id, "LWPOLYLINE", layer));
|
||||
return createdResult(created);
|
||||
}
|
||||
};
|
||||
EXPORT_MCP_TOOL(mcp_Tool_AddPolyline, CreateAddPolylineTool)
|
||||
|
||||
// ===========================================================================
|
||||
// add_line
|
||||
// ===========================================================================
|
||||
class mcp_Tool_AddLine : public mcp_Tool
|
||||
{
|
||||
public:
|
||||
nlohmann::json Execute(const nlohmann::json& args) override
|
||||
{
|
||||
AcDbDatabase* pDb = acdbHostApplicationServices()->workingDatabase();
|
||||
if (!pDb) return makeError(kErrNoDocument, "no working database");
|
||||
|
||||
DocLock lock; // 写库前先锁文档,见 dwg_annotate_common.h
|
||||
if (!lock.ok()) return makeError(kErrInternal, "cannot lock drawing document");
|
||||
|
||||
AcGePoint3d a, b;
|
||||
if (args.contains("start") && args.contains("end"))
|
||||
{
|
||||
if (!parsePoint(args["start"], a) || !parsePoint(args["end"], b))
|
||||
return makeError(kErrBadParam, "invalid start/end");
|
||||
}
|
||||
else if (args.contains("x1") && args.contains("y1") &&
|
||||
args.contains("x2") && args.contains("y2"))
|
||||
{
|
||||
a = AcGePoint3d(args["x1"].get<double>(), args["y1"].get<double>(), 0.0);
|
||||
b = AcGePoint3d(args["x2"].get<double>(), args["y2"].get<double>(), 0.0);
|
||||
}
|
||||
else return makeError(kErrBadParam, "start/end [x,y] (or x1/y1/x2/y2) is required");
|
||||
|
||||
AcDbBlockTableRecord* pSpace = openWriteSpace(pDb, getSpaceArg(args));
|
||||
if (!pSpace) return makeError(kErrNoDocument, "cannot open target space for write");
|
||||
|
||||
const std::string layer = getLayerArg(args);
|
||||
ensureLayer(pDb, layer, 1);
|
||||
|
||||
AcDbLine* pLine = new AcDbLine(a, b);
|
||||
applyLayerColor(pLine, layer, getColorArg(args));
|
||||
|
||||
const AcDbObjectId id = appendToSpace(pSpace, pLine);
|
||||
pSpace->close();
|
||||
if (id == AcDbObjectId::kNull) return makeError(kErrInternal, "append failed");
|
||||
|
||||
std::vector<nlohmann::json> created;
|
||||
created.push_back(makeCreatedItem(pDb, id, "LINE", layer));
|
||||
return createdResult(created);
|
||||
}
|
||||
};
|
||||
EXPORT_MCP_TOOL(mcp_Tool_AddLine, CreateAddLineTool)
|
||||
|
||||
// ===========================================================================
|
||||
// add_leader_annotation(引线 + 多行文字)
|
||||
// ===========================================================================
|
||||
class mcp_Tool_AddLeaderAnnotation : public mcp_Tool
|
||||
{
|
||||
public:
|
||||
nlohmann::json Execute(const nlohmann::json& args) override
|
||||
{
|
||||
AcDbDatabase* pDb = acdbHostApplicationServices()->workingDatabase();
|
||||
if (!pDb) return makeError(kErrNoDocument, "no working database");
|
||||
|
||||
DocLock lock; // 写库前先锁文档,见 dwg_annotate_common.h
|
||||
if (!lock.ok()) return makeError(kErrInternal, "cannot lock drawing document");
|
||||
|
||||
if (!args.contains("text") || !args["text"].is_string())
|
||||
return makeError(kErrBadParam, "text is required");
|
||||
const std::string text = args["text"].get<std::string>();
|
||||
|
||||
std::vector<AcGePoint3d> pts;
|
||||
if (!args.contains("points") || !parsePoints(args["points"], pts) || pts.size() < 2)
|
||||
return makeError(kErrBadParam, "points (>=2, first = arrow tip) is required");
|
||||
|
||||
double height = args.value("height", 2.5);
|
||||
if (height <= 1e-9) height = 2.5;
|
||||
const bool arrow = args.value("arrow", true);
|
||||
|
||||
AcGePoint3d textPos = pts.back();
|
||||
if (args.contains("text_position")) parsePoint(args["text_position"], textPos);
|
||||
|
||||
AcDbBlockTableRecord* pSpace = openWriteSpace(pDb, getSpaceArg(args));
|
||||
if (!pSpace) return makeError(kErrNoDocument, "cannot open target space for write");
|
||||
|
||||
const std::string layer = getLayerArg(args);
|
||||
const int color = getColorArg(args);
|
||||
ensureLayer(pDb, layer, 1);
|
||||
|
||||
std::vector<nlohmann::json> created;
|
||||
|
||||
// 1) 文字批注(先入库,供引线关联)
|
||||
const std::wstring wtext = utf8ToWStr(text);
|
||||
AcDbMText* pM = new AcDbMText();
|
||||
pM->setContents(wtext.c_str());
|
||||
pM->setTextHeight(height);
|
||||
pM->setLocation(textPos);
|
||||
pM->setAttachment(AcDbMText::kMiddleLeft);
|
||||
applyLayerColor(pM, layer, color);
|
||||
const AcDbObjectId mId = appendToSpace(pSpace, pM);
|
||||
|
||||
// 2) 引线
|
||||
AcDbLeader* pL = new AcDbLeader();
|
||||
pL->setDimstyleData(pDb->dimstyle());
|
||||
for (size_t i = 0; i < pts.size(); ++i)
|
||||
pL->appendVertex(pts[i]);
|
||||
pL->setHasArrowHead(arrow ? Adesk::kTrue : Adesk::kFalse);
|
||||
applyLayerColor(pL, layer, color);
|
||||
const AcDbObjectId lId = appendToSpace(pSpace, pL);
|
||||
|
||||
pSpace->close();
|
||||
|
||||
if (mId == AcDbObjectId::kNull && lId == AcDbObjectId::kNull)
|
||||
return makeError(kErrInternal, "append failed");
|
||||
|
||||
// 3) 关联文字并重算引线(失败则退化为"引线 + 文字"分离放置,视觉仍正确)
|
||||
if (lId != AcDbObjectId::kNull && mId != AcDbObjectId::kNull)
|
||||
{
|
||||
AcDbLeader* pL2 = nullptr;
|
||||
if (acdbOpenObject(pL2, lId, AcDb::kForWrite) == Acad::eOk && pL2)
|
||||
{
|
||||
if (pL2->attachAnnotation(mId) == Acad::eOk)
|
||||
pL2->evaluateLeader();
|
||||
pL2->close();
|
||||
}
|
||||
}
|
||||
|
||||
if (mId != AcDbObjectId::kNull) created.push_back(makeCreatedItem(pDb, mId, "MTEXT", layer));
|
||||
if (lId != AcDbObjectId::kNull) created.push_back(makeCreatedItem(pDb, lId, "LEADER", layer));
|
||||
return createdResult(created);
|
||||
}
|
||||
};
|
||||
EXPORT_MCP_TOOL(mcp_Tool_AddLeaderAnnotation, CreateAddLeaderAnnotationTool)
|
||||
@@ -0,0 +1,128 @@
|
||||
// ============================================================================
|
||||
// dwg_annotate_edit.cpp
|
||||
// 图纸批注 - 编辑类工具(均为 c++_dll 后端)
|
||||
// delete_entities : 按 handle 列表删除实体
|
||||
// set_entity_properties : 修改已有实体的图层 / 颜色
|
||||
//
|
||||
// 用于审图后清理 AI 自己产生的批注、删除图纸废线,或把问题实体标红/归层。
|
||||
// ============================================================================
|
||||
|
||||
#include "KTCad.h"
|
||||
#include "dwg_annotate_common.h"
|
||||
#include "mcp_plugin_api.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace dwg_annotate;
|
||||
using namespace dwg_review;
|
||||
|
||||
namespace
|
||||
{
|
||||
// 打开指定句柄的实体(kForWrite);失败返回 false
|
||||
bool openForWrite(const std::string& hs, AcDbEntity*& out)
|
||||
{
|
||||
out = nullptr;
|
||||
AcDbObjectId id;
|
||||
if (!objectIdFromHandle(hs, id)) return false;
|
||||
if (acdbOpenObject(out, id, AcDb::kForWrite) != Acad::eOk) { out = nullptr; return false; }
|
||||
return out != nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// delete_entities
|
||||
// ===========================================================================
|
||||
class mcp_Tool_DeleteEntities : public mcp_Tool
|
||||
{
|
||||
public:
|
||||
nlohmann::json Execute(const nlohmann::json& args) override
|
||||
{
|
||||
AcDbDatabase* pDb = acdbHostApplicationServices()->workingDatabase();
|
||||
if (!pDb) return makeError(kErrNoDocument, "no working database");
|
||||
|
||||
DocLock lock; // 写库前先锁文档,见 dwg_annotate_common.h
|
||||
if (!lock.ok()) return makeError(kErrInternal, "cannot lock drawing document");
|
||||
|
||||
const std::vector<std::string> hs = collectHandlesArg(args);
|
||||
if (hs.empty()) return makeError(kErrBadParam, "handle or handles is required");
|
||||
|
||||
int count = 0;
|
||||
nlohmann::json failed = nlohmann::json::array();
|
||||
|
||||
for (size_t i = 0; i < hs.size(); ++i)
|
||||
{
|
||||
AcDbEntity* pEnt = nullptr;
|
||||
if (!openForWrite(hs[i], pEnt)) { failed.push_back(hs[i]); continue; }
|
||||
|
||||
const Acad::ErrorStatus es = pEnt->erase();
|
||||
pEnt->close();
|
||||
if (es == Acad::eOk) ++count;
|
||||
else failed.push_back(hs[i]);
|
||||
}
|
||||
|
||||
nlohmann::json r;
|
||||
r["ok"] = true;
|
||||
r["count"] = count;
|
||||
r["failed"] = failed;
|
||||
return makeJsonResult(r);
|
||||
}
|
||||
};
|
||||
EXPORT_MCP_TOOL(mcp_Tool_DeleteEntities, CreateDeleteEntitiesTool)
|
||||
|
||||
// ===========================================================================
|
||||
// set_entity_properties
|
||||
// ===========================================================================
|
||||
class mcp_Tool_SetEntityProperties : public mcp_Tool
|
||||
{
|
||||
public:
|
||||
nlohmann::json Execute(const nlohmann::json& args) override
|
||||
{
|
||||
AcDbDatabase* pDb = acdbHostApplicationServices()->workingDatabase();
|
||||
if (!pDb) return makeError(kErrNoDocument, "no working database");
|
||||
|
||||
DocLock lock; // 写库前先锁文档,见 dwg_annotate_common.h
|
||||
if (!lock.ok()) return makeError(kErrInternal, "cannot lock drawing document");
|
||||
|
||||
const std::vector<std::string> hs = collectHandlesArg(args);
|
||||
if (hs.empty()) return makeError(kErrBadParam, "handle or handles is required");
|
||||
|
||||
const bool hasLayer = args.contains("layer") && args["layer"].is_string();
|
||||
const bool hasColor = args.contains("color") && args["color"].is_number_integer();
|
||||
if (!hasLayer && !hasColor)
|
||||
return makeError(kErrBadParam, "at least one of layer / color is required");
|
||||
|
||||
const std::string layer = hasLayer ? args["layer"].get<std::string>() : std::string();
|
||||
const int color = hasColor ? args["color"].get<int>() : -1;
|
||||
|
||||
if (hasLayer) ensureLayer(pDb, layer, 1);
|
||||
|
||||
int count = 0;
|
||||
nlohmann::json failed = nlohmann::json::array();
|
||||
|
||||
for (size_t i = 0; i < hs.size(); ++i)
|
||||
{
|
||||
AcDbEntity* pEnt = nullptr;
|
||||
if (!openForWrite(hs[i], pEnt)) { failed.push_back(hs[i]); continue; }
|
||||
|
||||
if (hasLayer)
|
||||
{
|
||||
const std::wstring wl = utf8ToWStr(layer);
|
||||
pEnt->setLayer(wl.c_str());
|
||||
}
|
||||
if (hasColor)
|
||||
pEnt->setColorIndex((Adesk::UInt16)color);
|
||||
|
||||
pEnt->draw();
|
||||
pEnt->close();
|
||||
++count;
|
||||
}
|
||||
|
||||
nlohmann::json r;
|
||||
r["ok"] = true;
|
||||
r["count"] = count;
|
||||
r["failed"] = failed;
|
||||
return makeJsonResult(r);
|
||||
}
|
||||
};
|
||||
EXPORT_MCP_TOOL(mcp_Tool_SetEntityProperties, CreateSetEntityPropertiesTool)
|
||||
@@ -0,0 +1,192 @@
|
||||
// ============================================================================
|
||||
// dwg_review_ui.cpp
|
||||
// 图纸审查 - 绘图区界面控制工具(c++_dll 后端)
|
||||
// set_drawing_area : 最大化绘图区(最大化主窗口 + 进入「干净屏幕」)与还原
|
||||
//
|
||||
// 背景:截图质量与「绘图区像素」直接相关。实测 CAD 主窗口未最大化时,绘图区只有
|
||||
// 2110x462 —— 竖向被标题栏 / 功能区 / 命令行 / 状态栏吃掉约 500px。最大化窗口并进入
|
||||
// 干净屏幕(隐藏功能区 / 命令行 / 面板)后绘图区显著变大;同样按长边 1280 下采样时
|
||||
// 有效像素更多、视口宽高比更接近图纸,自适应瓦片张数更少。
|
||||
//
|
||||
// 实测(AutoCAD 2020,屏幕 3440x1440,测试图纸)绘图区像素:
|
||||
// 非最大化 / 无干净屏幕 : 2110 x 462
|
||||
// 最大化 + 干净屏幕 : 3310 x 1084 → 面积 3.68x
|
||||
//
|
||||
// 重要:本工具会**改动用户的 CAD 界面**(窗口位置 + 干净屏幕状态)。
|
||||
// 调用方必须在 finally 里以 mode="restore" 还原;还原信息在本进程内静态保存。
|
||||
// 注意 restore 的窗口几何是**延迟**压回的(CLEANSCREENOFF 异步,见 restore 分支),
|
||||
// 调用方在 restore 后应等待约 0.8s 再认为界面已还原。
|
||||
// ============================================================================
|
||||
|
||||
#include "KTCad.h"
|
||||
#include "dwg_review_common.h"
|
||||
#include "mcp_plugin_api.h"
|
||||
|
||||
#include <Windows.h>
|
||||
#include <string>
|
||||
|
||||
using namespace dwg_review;
|
||||
|
||||
namespace
|
||||
{
|
||||
// 进程内保存的还原信息(工具调用跨请求,故用静态变量)。
|
||||
struct SavedUiState
|
||||
{
|
||||
bool valid;
|
||||
bool cleanWasOn;
|
||||
WINDOWPLACEMENT place;
|
||||
|
||||
SavedUiState() : valid(false), cleanWasOn(false)
|
||||
{
|
||||
place.length = sizeof(WINDOWPLACEMENT);
|
||||
}
|
||||
};
|
||||
SavedUiState g_saved;
|
||||
|
||||
// 待延迟还原的窗口(见 restore 分支:CLEANSCREENOFF 是异步命令,
|
||||
// AutoCAD 处理它时会按「进入干净屏幕时的布局」重设窗口几何,
|
||||
// 覆盖掉我们同步执行的 SetWindowPlacement,故需延后一段时间再压回去)。
|
||||
HWND g_pendingRestore = NULL;
|
||||
|
||||
// 把保存的窗口布局压回去(幂等;无保存信息则空操作)。
|
||||
void applySavedPlacement()
|
||||
{
|
||||
if (g_pendingRestore && ::IsWindow(g_pendingRestore) && g_saved.valid)
|
||||
::SetWindowPlacement(g_pendingRestore, &g_saved.place);
|
||||
g_pendingRestore = NULL;
|
||||
g_saved.valid = false;
|
||||
}
|
||||
|
||||
void CALLBACK delayedRestoreProc(HWND, UINT, UINT_PTR idEvent, DWORD)
|
||||
{
|
||||
::KillTimer(NULL, idEvent);
|
||||
applySavedPlacement();
|
||||
}
|
||||
|
||||
// CAD 主框架窗口:优先 adsw_acadMainWnd(),退回绘图视图的根窗口。
|
||||
HWND mainFrame()
|
||||
{
|
||||
HWND h = adsw_acadMainWnd();
|
||||
if (h && ::IsWindow(h)) return h;
|
||||
CView *v = acedGetAcadDwgView();
|
||||
if (v && v->m_hWnd) return ::GetAncestor(v->m_hWnd, GA_ROOT);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// 绘图视图窗口(仅图形区,不含滚动条 / 状态栏)。
|
||||
HWND dwgView()
|
||||
{
|
||||
CView *v = acedGetAcadDwgView();
|
||||
if (v && v->m_hWnd) return v->m_hWnd;
|
||||
return adsw_acadDocWnd();
|
||||
}
|
||||
|
||||
// 发送命令(异步;调用方需等待渲染)。
|
||||
void sendCmd(const wchar_t *cmd)
|
||||
{
|
||||
if (acDocManager && acDocManager->curDocument())
|
||||
acDocManager->sendStringToExecute(acDocManager->curDocument(), cmd);
|
||||
}
|
||||
|
||||
// 读取整型系统变量;失败返回 fallback。
|
||||
int getIntVar(const ACHAR *name, int fallback)
|
||||
{
|
||||
struct resbuf rb;
|
||||
if (acedGetVar(name, &rb) == RTNORM && rb.restype == RTSHORT)
|
||||
return rb.resval.rint;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
nlohmann::json viewSize()
|
||||
{
|
||||
nlohmann::json a = nlohmann::json::array();
|
||||
HWND h = dwgView();
|
||||
RECT rc;
|
||||
if (!h || !::GetClientRect(h, &rc)) return a;
|
||||
a.push_back(rc.right - rc.left);
|
||||
a.push_back(rc.bottom - rc.top);
|
||||
return a;
|
||||
}
|
||||
|
||||
nlohmann::json mainRect()
|
||||
{
|
||||
nlohmann::json a = nlohmann::json::array();
|
||||
HWND h = mainFrame();
|
||||
RECT rc;
|
||||
if (!h || !::GetWindowRect(h, &rc)) return a;
|
||||
a.push_back(rc.left);
|
||||
a.push_back(rc.top);
|
||||
a.push_back(rc.right);
|
||||
a.push_back(rc.bottom);
|
||||
return a;
|
||||
}
|
||||
}
|
||||
|
||||
class mcp_Tool_SetDrawingArea : public mcp_Tool
|
||||
{
|
||||
public:
|
||||
virtual nlohmann::json Execute(const nlohmann::json &args) override
|
||||
{
|
||||
std::string mode = "max";
|
||||
if (args.contains("mode") && args["mode"].is_string())
|
||||
mode = args["mode"].get<std::string>();
|
||||
|
||||
HWND hMain = mainFrame();
|
||||
if (!hMain)
|
||||
return makeError(kErrBadParam, "cannot locate AutoCAD main window");
|
||||
|
||||
nlohmann::json r;
|
||||
|
||||
if (mode == "max")
|
||||
{
|
||||
// 只保存一次(重复 max 不会覆盖首次的原始状态)
|
||||
if (!g_saved.valid)
|
||||
{
|
||||
g_saved.place.length = sizeof(WINDOWPLACEMENT);
|
||||
::GetWindowPlacement(hMain, &g_saved.place);
|
||||
// CLEANSCREENSTATE 读不到时按「原本没开」处理
|
||||
g_saved.cleanWasOn = (getIntVar(L"CLEANSCREENSTATE", 0) != 0);
|
||||
g_saved.valid = true;
|
||||
}
|
||||
if (!::IsZoomed(hMain))
|
||||
::ShowWindow(hMain, SW_MAXIMIZE);
|
||||
if (!g_saved.cleanWasOn)
|
||||
sendCmd(L"_.CLEANSCREENON ");
|
||||
r["mode"] = "max";
|
||||
r["clean_before"] = g_saved.cleanWasOn;
|
||||
}
|
||||
else if (mode == "restore")
|
||||
{
|
||||
if (g_saved.valid)
|
||||
{
|
||||
if (!g_saved.cleanWasOn)
|
||||
{
|
||||
// 退出干净屏幕是**异步**命令:AutoCAD 随后会按「进入干净屏幕时的布局」
|
||||
// 重设窗口几何,把我们同步执行的 SetWindowPlacement 覆盖掉
|
||||
// (表现为窗口仍最大化)。故延后 700ms 再压回原始布局。
|
||||
sendCmd(L"_.CLEANSCREENOFF ");
|
||||
g_pendingRestore = hMain;
|
||||
::SetTimer(NULL, 0, 700, delayedRestoreProc);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 原本就在干净屏幕:无异步覆盖,直接同步还原。
|
||||
g_pendingRestore = hMain;
|
||||
applySavedPlacement();
|
||||
}
|
||||
}
|
||||
r["mode"] = "restore";
|
||||
}
|
||||
else
|
||||
{
|
||||
return makeError(kErrBadParam, "mode must be 'max' or 'restore'");
|
||||
}
|
||||
|
||||
r["ok"] = true;
|
||||
r["main_rect"] = mainRect();
|
||||
r["view_size"] = viewSize(); // 注意:CLEANSCREENON 异步,刚调用时可能还是旧值
|
||||
return makeJsonResult(r);
|
||||
}
|
||||
};
|
||||
|
||||
EXPORT_MCP_TOOL(mcp_Tool_SetDrawingArea, CreateSetDrawingAreaTool)
|
||||
@@ -0,0 +1,339 @@
|
||||
// ============================================================================
|
||||
// find_collisions.cpp
|
||||
// 图纸审查 - 干涉 / 碰撞**候选**检查
|
||||
//
|
||||
// find_collisions : 粗筛出「包围盒相交」的实体对,附重叠证据,供审查 agent 判断
|
||||
//
|
||||
// 设计要点:
|
||||
// - **粗筛**:BVH(bvh.h)两两自检,只对相交的包围盒做后续处理;
|
||||
// - **容器过滤**:图框块 / 分区边界会与「一切」相交,制造海量假候选。
|
||||
// 用重叠**度**(与多少其他实体相交)识别:`deg >= max(deg_min, frac * 其他实体数)`
|
||||
// → 判为容器,剔除其全部配对。**与图幅/缩放无关**,实测图框 deg=35/25/23,
|
||||
// 其余实体全部 deg<=3,分离极干净。(另保留基于面积的 `exclude_oversized` 作快速预筛。)
|
||||
// - **证据**:重叠盒 + 逐轴重叠比(`ratio`,见下)+ 类型 / 图层 / 是否同层同类型;
|
||||
// - **排序**:按 `ratio` 降序 + 分页 → 最可疑的排在最前;
|
||||
// - **只报候选、不下结论**:AABB 相交 ≠ 真干涉(L 形布局的两个实体包围盒会相交,
|
||||
// 相邻管段在接口处也会相接)。真伪由审查 agent 依据证据判断,必要时用
|
||||
// `inspect_region` 放大目视复核。
|
||||
//
|
||||
// `ratio` 定义:逐轴重叠比之积。
|
||||
// 某轴重叠比 = 该轴重叠长度 / 两实体该轴较短长度;**至少一方在该轴退化为 0**
|
||||
// (水平线的高、竖直线的宽)时该轴取 1.0(视为完全重叠)。
|
||||
// 于是:共线相接的两段 → 0;横管穿过阀门 → ≈1;斜管交叉 → 较大。
|
||||
//
|
||||
// 注:本工具按 **2D(x/y)** 判定,与插件其余工具一致;z 不参与。
|
||||
// ============================================================================
|
||||
|
||||
#include "KTCad.h"
|
||||
#include "dwg_review_common.h"
|
||||
#include "mcp_plugin_api.h"
|
||||
#include "bvh.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
// windows.h(经 afxwin.h)把 min/max 定义成宏,会顶掉下面的 std::min / std::max
|
||||
// (CadProject 那边的 cadsdk.h 里带了 NOMINMAX,本仓库的 KTCad.h 没有)。
|
||||
#undef min
|
||||
#undef max
|
||||
|
||||
|
||||
using namespace dwg_review;
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
struct EntInfo
|
||||
{
|
||||
AcDbObjectId id;
|
||||
std::string handle;
|
||||
std::string type;
|
||||
std::string layer;
|
||||
BBox box;
|
||||
};
|
||||
|
||||
struct Pair
|
||||
{
|
||||
int a = 0;
|
||||
int b = 0;
|
||||
double ratio = 0.0;
|
||||
BBox ov;
|
||||
double ow = 0.0;
|
||||
double oh = 0.0;
|
||||
bool exact = false;
|
||||
};
|
||||
|
||||
// ---------- 宽松参数解析(LLM 常把数字写成字符串、把 bool 写成 0/1) ----------
|
||||
double numArg(const nlohmann::json& args, const char* key, double dflt)
|
||||
{
|
||||
auto it = args.find(key);
|
||||
if (it == args.end() || it->is_null()) return dflt;
|
||||
if (it->is_number()) return it->get<double>();
|
||||
if (it->is_boolean()) return it->get<bool>() ? 1.0 : 0.0;
|
||||
if (it->is_string())
|
||||
{
|
||||
try { return std::stod(it->get<std::string>()); }
|
||||
catch (...) { return dflt; }
|
||||
}
|
||||
return dflt;
|
||||
}
|
||||
|
||||
bool boolArg(const nlohmann::json& args, const char* key, bool dflt)
|
||||
{
|
||||
auto it = args.find(key);
|
||||
if (it == args.end() || it->is_null()) return dflt;
|
||||
if (it->is_boolean()) return it->get<bool>();
|
||||
if (it->is_number()) return it->get<double>() != 0.0;
|
||||
return dflt;
|
||||
}
|
||||
|
||||
double clampd(double v, double lo, double hi)
|
||||
{
|
||||
return v < lo ? lo : (v > hi ? hi : v);
|
||||
}
|
||||
|
||||
dwg_bvh::Box toBvhBox(const BBox& b)
|
||||
{
|
||||
dwg_bvh::Box r;
|
||||
r.x1 = b.minX; r.y1 = b.minY; r.x2 = b.maxX; r.y2 = b.maxY;
|
||||
return r;
|
||||
}
|
||||
|
||||
// 单轴重叠比:至少一方在该轴退化为 0 → 视为完全重叠(1.0)
|
||||
double axisFrac(double a1, double a2, double b1, double b2, double o1, double o2)
|
||||
{
|
||||
const double shorter = std::min(a2 - a1, b2 - b1);
|
||||
if (shorter <= 0.0) return 1.0;
|
||||
return (o2 - o1) / shorter;
|
||||
}
|
||||
|
||||
// 可选细筛:几何是否真的相交。AEC 自定义实体未必实现 intersectWith,
|
||||
// 失败 / 未实现时返回 false(调用方据此把 exact 置 false,但仍保留候选)。
|
||||
bool geometryIntersects(const AcDbObjectId& idA, const AcDbObjectId& idB)
|
||||
{
|
||||
AcDbEntity* pa = nullptr;
|
||||
if (acdbOpenObject(pa, idA, AcDb::kForRead) != Acad::eOk || !pa) return false;
|
||||
|
||||
AcDbEntity* pb = nullptr;
|
||||
if (acdbOpenObject(pb, idB, AcDb::kForRead) != Acad::eOk || !pb)
|
||||
{
|
||||
pa->close();
|
||||
return false;
|
||||
}
|
||||
|
||||
bool hit = false;
|
||||
try
|
||||
{
|
||||
AcGePoint3dArray pts;
|
||||
hit = (pa->intersectWith(pb, AcDb::kOnBothOperands, pts) == Acad::eOk)
|
||||
&& pts.length() > 0;
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
hit = false;
|
||||
}
|
||||
pb->close();
|
||||
pa->close();
|
||||
return hit;
|
||||
}
|
||||
|
||||
nlohmann::json entJson(const EntInfo& e)
|
||||
{
|
||||
nlohmann::json j;
|
||||
j["handle"] = e.handle;
|
||||
j["type"] = e.type;
|
||||
j["layer"] = e.layer;
|
||||
j["bbox"] = bboxJson(e.box);
|
||||
return j;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
class mcp_Tool_FindCollisions : public mcp_Tool
|
||||
{
|
||||
public:
|
||||
nlohmann::json Execute(const nlohmann::json& args) override
|
||||
{
|
||||
CommonQuery q = parseCommonQuery(args);
|
||||
|
||||
const int limit = (q.limit > 0 && q.limit <= 1000) ? q.limit : 200;
|
||||
const double minOverlap = clampd(numArg(args, "min_overlap", 0.0), 0.0, 1.0);
|
||||
const bool sameLayer = boolArg(args, "include_same_layer", true);
|
||||
const double maxAreaFrac = clampd(numArg(args, "exclude_oversized", 0.5), 0.0, 1.0);
|
||||
const bool narrow = boolArg(args, "narrow", false);
|
||||
// 容器过滤(图框块 / 分区边界):重叠度阈值
|
||||
const int contDegMin = static_cast<int>(
|
||||
clampd(numArg(args, "exclude_container_deg", 8.0), 1.0, 100000.0));
|
||||
const double contDegFrac = clampd(numArg(args, "exclude_container_frac", 0.25), 0.0, 1.0);
|
||||
|
||||
// ---- 1) 收集实体(含包围盒) ----
|
||||
std::vector<EntInfo> ents;
|
||||
forEachEntity(q, [&](AcDbEntity* pEnt) -> bool
|
||||
{
|
||||
BBox b;
|
||||
if (!entityBBox(pEnt, b) || !b.valid) return true;
|
||||
|
||||
EntInfo info;
|
||||
info.id = pEnt->objectId();
|
||||
info.handle = handleOf(pEnt);
|
||||
info.type = entityTypeName(pEnt);
|
||||
info.layer = layerOf(pEnt);
|
||||
info.box = b;
|
||||
ents.push_back(std::move(info));
|
||||
return true;
|
||||
});
|
||||
|
||||
if (ents.size() < 2)
|
||||
{
|
||||
nlohmann::json r = pageResult(0, 0, 0, nlohmann::json::array());
|
||||
r["entity_count"] = static_cast<int>(ents.size());
|
||||
r["excluded_containers"] = nlohmann::json::array();
|
||||
return makeJsonResult(r);
|
||||
}
|
||||
|
||||
// 被剔除的「容器」(图框块 / 分区边界),供审查 agent 知情
|
||||
nlohmann::json containers = nlohmann::json::array();
|
||||
|
||||
// ---- 2) 面积预筛:剔除「过大」实体(图框块会与一切相交) ----
|
||||
// 参考面积:有 window 用 window,否则用全部实体的并集
|
||||
BBox ref = ents[0].box;
|
||||
for (const EntInfo& e : ents)
|
||||
{
|
||||
if (e.box.minX < ref.minX) ref.minX = e.box.minX;
|
||||
if (e.box.minY < ref.minY) ref.minY = e.box.minY;
|
||||
if (e.box.maxX > ref.maxX) ref.maxX = e.box.maxX;
|
||||
if (e.box.maxY > ref.maxY) ref.maxY = e.box.maxY;
|
||||
}
|
||||
const double refArea = (ref.maxX - ref.minX) * (ref.maxY - ref.minY);
|
||||
|
||||
std::vector<dwg_bvh::Primitive> prims;
|
||||
std::vector<EntInfo> kept;
|
||||
prims.reserve(ents.size());
|
||||
kept.reserve(ents.size());
|
||||
for (const EntInfo& e : ents)
|
||||
{
|
||||
if (refArea > 0.0)
|
||||
{
|
||||
const double a = (e.box.maxX - e.box.minX) * (e.box.maxY - e.box.minY);
|
||||
if (a > refArea * maxAreaFrac)
|
||||
{
|
||||
nlohmann::json c;
|
||||
c["handle"] = e.handle;
|
||||
c["type"] = e.type;
|
||||
c["layer"] = e.layer;
|
||||
c["reason"] = "oversized";
|
||||
containers.push_back(std::move(c));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
prims.push_back({ toBvhBox(e.box), static_cast<int>(kept.size()) });
|
||||
kept.push_back(e);
|
||||
}
|
||||
|
||||
// ---- 3) 粗筛 ----
|
||||
dwg_bvh::Tree tree;
|
||||
tree.Build(prims);
|
||||
std::vector<std::pair<int, int>> hits;
|
||||
tree.SelfPairs(hits);
|
||||
|
||||
// ---- 3.5) 容器过滤:重叠度过高的实体判为图框块 / 分区边界,剔除其全部配对 ----
|
||||
// 判据与图幅、缩放无关,只依赖「与多少其他实体相交」——实测分离极干净
|
||||
// (图框 deg=35/25/23,其余实体全部 deg<=3)。
|
||||
std::vector<int> deg(kept.size(), 0);
|
||||
for (const auto& h : hits)
|
||||
{
|
||||
++deg[h.first];
|
||||
++deg[h.second];
|
||||
}
|
||||
const int others = (kept.size() > 0) ? static_cast<int>(kept.size()) - 1 : 0;
|
||||
const int degLimit = std::max(
|
||||
contDegMin, static_cast<int>(std::ceil(contDegFrac * others)));
|
||||
|
||||
std::vector<char> isContainer(kept.size(), 0);
|
||||
for (std::size_t i = 0; i < kept.size(); ++i)
|
||||
{
|
||||
if (deg[i] < degLimit) continue;
|
||||
isContainer[i] = 1;
|
||||
nlohmann::json c;
|
||||
c["handle"] = kept[i].handle;
|
||||
c["type"] = kept[i].type;
|
||||
c["layer"] = kept[i].layer;
|
||||
c["degree"] = deg[i];
|
||||
c["reason"] = "container";
|
||||
containers.push_back(std::move(c));
|
||||
}
|
||||
|
||||
// ---- 4) 组装证据 / 过滤 / 排序 ----
|
||||
std::vector<Pair> pairs;
|
||||
pairs.reserve(hits.size());
|
||||
for (const auto& h : hits)
|
||||
{
|
||||
if (isContainer[h.first] || isContainer[h.second]) continue;
|
||||
const EntInfo& ea = kept[h.first];
|
||||
const EntInfo& eb = kept[h.second];
|
||||
if (!sameLayer && ea.layer == eb.layer) continue;
|
||||
|
||||
const BBox& A = ea.box;
|
||||
const BBox& B = eb.box;
|
||||
const double ox1 = std::max(A.minX, B.minX);
|
||||
const double oy1 = std::max(A.minY, B.minY);
|
||||
const double ox2 = std::min(A.maxX, B.maxX);
|
||||
const double oy2 = std::min(A.maxY, B.maxY);
|
||||
if (ox2 < ox1 || oy2 < oy1) continue;
|
||||
|
||||
Pair p;
|
||||
p.a = h.first;
|
||||
p.b = h.second;
|
||||
p.ov.minX = ox1; p.ov.minY = oy1; p.ov.maxX = ox2; p.ov.maxY = oy2;
|
||||
p.ov.valid = true;
|
||||
p.ow = ox2 - ox1;
|
||||
p.oh = oy2 - oy1;
|
||||
p.ratio = axisFrac(A.minX, A.maxX, B.minX, B.maxX, ox1, ox2)
|
||||
* axisFrac(A.minY, A.maxY, B.minY, B.maxY, oy1, oy2);
|
||||
if (p.ratio < minOverlap) continue;
|
||||
pairs.push_back(p);
|
||||
}
|
||||
|
||||
std::sort(pairs.begin(), pairs.end(),
|
||||
[](const Pair& x, const Pair& y) { return x.ratio > y.ratio; });
|
||||
|
||||
// ---- 5) 可选细筛(只对进入返回页的候选做,控制开销) ----
|
||||
const int total = static_cast<int>(pairs.size());
|
||||
const int from = (q.offset > 0) ? std::min(q.offset, total) : 0;
|
||||
const int to = std::min(total, from + limit);
|
||||
|
||||
nlohmann::json items = nlohmann::json::array();
|
||||
for (int i = from; i < to; ++i)
|
||||
{
|
||||
Pair& p = pairs[i];
|
||||
nlohmann::json it;
|
||||
it["a"] = entJson(kept[p.a]);
|
||||
it["b"] = entJson(kept[p.b]);
|
||||
it["overlap"] = {
|
||||
{ "bbox", bboxJson(p.ov) },
|
||||
{ "width", p.ow },
|
||||
{ "height", p.oh },
|
||||
{ "area", p.ow * p.oh },
|
||||
{ "ratio", p.ratio }
|
||||
};
|
||||
it["same_layer"] = (kept[p.a].layer == kept[p.b].layer);
|
||||
it["same_type"] = (kept[p.a].type == kept[p.b].type);
|
||||
if (narrow)
|
||||
{
|
||||
p.exact = geometryIntersects(kept[p.a].id, kept[p.b].id);
|
||||
it["exact"] = p.exact;
|
||||
}
|
||||
items.push_back(std::move(it));
|
||||
}
|
||||
|
||||
nlohmann::json r = pageResult(total, to - from, from, items);
|
||||
r["entity_count"] = static_cast<int>(kept.size());
|
||||
r["excluded_containers"] = std::move(containers);
|
||||
return makeJsonResult(r);
|
||||
}
|
||||
};
|
||||
|
||||
EXPORT_MCP_TOOL(mcp_Tool_FindCollisions, CreateFindCollisionsTool)
|
||||
+8
-9
@@ -159,12 +159,11 @@ MCP 工具是通过 `PostMessage` 在主线程的消息里跑的,**不在命
|
||||
- 新建实体后 `bbox` 会是 `±1e20`:自定义实体的几何要等一次 REGEN 才建出来,
|
||||
`getGeomExtents` 在未绘制时返回无效值。不是错误。
|
||||
- 没有事务/撤销包装:调用即改库。批量改图建议先 `query_aec_entities` 拿 handle,再逐条 `update`。
|
||||
- **`mcp_config.json` 里有 10 个工具在当前 `cad_mcp_plugins.dll` 里没有对应工厂函数**
|
||||
(`CreateSetDrawingAreaTool`、`CreateFindCollisionsTool`、`CreateDrawRevisionCloudTool`、
|
||||
`CreateAddTextTool`、`CreateAddMTextTool`、`CreateAddPolylineTool`、`CreateAddLineTool`、
|
||||
`CreateAddLeaderAnnotationTool`、`CreateDeleteEntitiesTool`、`CreateSetEntityPropertiesTool`)。
|
||||
这份配置来自更新一版的插件工程,而仓库里的 `cad_mcp_plugins` 只有 16 个工具,
|
||||
于是这 10 个在 `tools/list` 里会被静默丢掉(实测 `tools/list` = 30 = 18 + 12)。
|
||||
要补齐得先把那 10 个工具的实现补进 `cad_mcp_plugins`。
|
||||
- 插件侧 `private_description()` / `private_input_schema()` 与 `mcp_config.json` 保持同文案;
|
||||
**改描述时两边一起改**(配置里写了 `description` / `inputSchema` 时以配置为准)。
|
||||
- `mcp_config.json` 里的 40 个工具现在都能加载(`tools/list` = 40)。
|
||||
其中 26 个属于 `cad_mcp_plugins`(含从 CadProject 合并过来的批注/编辑类工具),
|
||||
12 个属于本插件,2 个是 lisp_inline。
|
||||
移植那批工具时踩到两个本仓库差异(已修,见那次提交):
|
||||
1. 上游 `dll` 的写库工具没有文档锁,在本仓库的运行方式下会返回
|
||||
`cannot open target space for write`(`eLockViolation`)—— 补了 `dwg_annotate::DocLock`;
|
||||
2. 上游 `cadsdk.h` 带 `NOMINMAX`,本仓库 `KTCad.h` 没有,
|
||||
`std::min/std::max` 被 windows 宏顶掉 —— 在用到它们的三个文件里 `#undef min/max`。
|
||||
Reference in new issue
Block a user