Skip to content

Mx2DNode Secondary Development API Reference (backend parametric drawing / data extraction) ​

Compiled from the project TypeScript source (src/mxcad/*.ts, src/sample/*.ts); all signatures and return values are subject to the source code.

I. Usage Pattern ​

Create a new .ts file under src/, import the modules, and use them:

ts
import { Mx2DDraw, MxBackstage, MxFun } from "../MxFun";
import { McDbDatabase } from "../mxcad/McDbDatabase";
import { McGePoint3d } from "../mxcad/McGePoint3d";
// ... import the remaining McDb* classes you need from ../mxcad/

Typical flow (see sample/ParamDraw.ts):

ts
// 1. Open the blank template (empty_template.dwg in the project directory)
if (!MxBackstage.openFile(Mx2DDraw.getEmptyTemplateDwgFilePath())) { /* failed */ }

// 2. Draw (see section 2)
Mx2DDraw.drawLine(new McGePoint3d([0,0,0]), new McGePoint3d([100,100,0]));

// 3. Save (DWG/DXF both fine; relative paths are relative to the project directory;
//    without a DWG license module it auto-converts via mxcadassembly)
if (!MxBackstage.writeFile("out/test.dwg")) { /* failed */ }

Mx2DDraw, MxBackstage, and MxFun are singletons (MxFun.init() is called by the mxapp.js entry point) — use them directly; do not new them.

II. Mx2DDraw — 2D Drawing Class ​

2.1 Pre-drawing Settings ​

MethodDescription
setColor(r, g, b)Set the current color (RGB 0-255)
setColorIndex(index)Set the AutoCAD color index
setLineWeight(lineWeight)Set line weight, takes a LineWeight enum (kLnWt025 = 0.25 mm, kLnWtByLayer = -1 follows the layer)
addLinetype(name, lineDefine) → linetype idAdd a linetype. lineDefine like "6,-10" (solid length, dash length…)
addLinetypeEx(name, lineDefine, textStyle) → linetype idLinetype with a text definition
setLinetype(name)Set the current linetype
setLineTypeScale(scale)Set the current linetype scale
addLayer(name) → layer idAdd a layer
setLayer(name) → boolSet the current layer
addTextStyle(name, shxFile, bigFontFile, xScale) → style idAdd an SHX text style
addTextStyle2(name, trueTypeFont, xScale) → style idAdd a TrueType text style (e.g. SimHei, SimSun)
setTextStyle(name) → boolSet the current text style
addDimStyle(name, doubleData, intData, stringData, idData) → style idAdd a dimension style (fails if a same-named style already exists)
addPatternDefinition(name, definition) → boolAdd a hatch pattern definition. definition format: "((angle, xOrigin, yOrigin, dx, dy, dash1, dash2, ...))", e.g. "((45, 0,0, 0,0.125))"

2.2 Basic Primitive Drawing (all return McDbObjectId) ​

MethodDescription
drawLine(pt1, pt2) / drawLine2(x1,y1,x2,y2)Line
drawPoint(x, y, z=0)Point
drawCircle(center, r) / drawCircle2(cx, cy, r)Circle
drawArc(center, radius, startAngle, endAngle)Arc
drawEllipse(center, majorAxisX, majorAxisY, radiusRatio) / drawEllipse2(cx,cy,cz, ...)Ellipse
drawText(position, text, height, rotation, hMode, vMode, widthFactor=1)Single-line text. hMode: 0 left / 1 center / 2 right; vMode: 1 bottom / 2 middle / 3 top; position may be an [x,y,z] array
drawMText(location, contents, height, width, rotation, attachment)MText. attachment 1–9 (nine-grid from top-left to bottom-right). Supports format codes, e.g. superscript 2: "\A2;Square method: m{\H0.3x;\S 2^;}"
drawImage(position, width, height, rotation, imageFilePath)Insert an image (JPG, etc.)
drawEntity(ent: McDbEntity)Draw a self-constructed entity object (e.g. build a McDbLine, set its properties, then submit)
erase(id) → boolDelete an object

2.3 Path → Primitive (the path API accumulates points first, then generates the entity) ​

ts
Mx2DDraw.pathMoveToEx(new McGePoint3d([600, 3300]), 0, 0, 0.3); // start point (incl. start/end widths, bulge)
Mx2DDraw.pathLineTo(700, 3300);                                  // subsequent points
Mx2DDraw.pathLineTo(700, 3400);
Mx2DDraw.pathLineTo(600, 3300);
Mx2DDraw.pathMakeClosed();          // optional: close
Mx2DDraw.pathMakeExclude(true);     // optional: mark as an excluded region (hole)

Generated results (all return an id):

  • drawPathToPolyline() → polyline
  • drawPathToSpline() → spline
  • drawPathToHatch(patternName = "", scale = 1) → hatch (the pattern name must be added via addPatternDefinition first; an empty string means solid fill)

2.4 Blocks ​

MethodDescription
InsertBlock(fileName, blockName) → block table record idImport a block definition from a DWG file (the block with the given name in the file); returns the new block record id. A relative fileName is based on the project directory
drawBlockReference(pos, blkName, scale, angleDeg) → block reference idInsert an existing block. angle unit: degrees

Title block (attribute) filling example — see drawTq in sample/ParamDraw.ts:

ts
let id = Mx2DDraw.drawBlockReference([100,100,0], "BT", 1.0, 0.0);
let blkRef = id.getEntity() as McDbBlockReference;
blkRef.createAttribute();
for (let i = 0; i < blkRef.attributeCount; i++) {
    let attrib = blkRef.attributeItem(i);
    attrib.textString = "John Doe";   // fill in by matching attrib.tag
}

2.5 Dimensions ​

MethodDescription
drawDimAligned(xLine1, xLine2, dimLinePoint)Aligned dimension
drawDimRotated(xLine1, xLine2, dimLinePoint, rotation)Rotated (linear) dimension
drawDimDiametric(chordPoint, farChordPoint, leaderLength)Diametric dimension
drawDimRadial(center, chordPoint, leaderLength)Radial dimension
drawDimAngular(arcPoint, xLine1, xLine2, sDimensionText)Angular dimension

Known source issue: drawEllipseArc and drawDimAngular internally call the wrong method (a typo); verify before use or switch to the low-level API.

2.6 Database and Objects ​

MethodDescription
currentDatabase() → McDbDatabaseThe current drawing database (drawing context)
backgroundDatabase() → McDbDatabaseThe database of the drawing opened in the background
objectIdToObject(id) → McDbObject|nullConvert an object id to an entity object (auto-mapped to the concrete type)
handleToObjectId(handle) / objectIdToHandle(id)Convert between handle and id
compareObject(id1, id2) → numberCompare whether two objects are the same (0 = same)
getEmptyTemplateDwgFilePath()Path of the blank template DWG (empty_template.dwg in the project directory)
getCurrentPath()Current program path (project dir/../../)

III. MxBackstage — Background File Handling ​

MethodDescription
openFile(fileName, iReadContent = 0) → boolOpen a drawing. iReadContent: 0 default; pass 67904 (kReadDefault|kReadxData) when extended data must be read
writeFile(fileName) → boolSave as DWG/DXF/mxweb (by extension). Without a DWG write module it auto-converts via mxcadassembly
writeWebGLFile(fileName) → boolOutput the frontend display file (mxweb)
getDatabase() → McDbDatabaseGet the current drawing database
initSet(iniJson) → boolInitialize conversion settings (JSON string; generally no need to call)

IV. McDbDatabase — Database Object ​

ts
let db: McDbDatabase = new McDbDatabase();   // standalone instance (for reading another file then merging)
db.readDwgFile("a.dwg");                     // relative paths are relative to the project directory; or get it from Mx2DDraw.currentDatabase()
Method/PropertyDescription
readDwgFile(fileName) → boolLoad a DWG standalone into this instance (call free() when done)
getBlockTable() / getLayerTable() / getDimStyleTable() / getLineTypeTable() / getTextStyleTable()Get each symbol table (a table object has getAll() returning an array of record ids)
currentSpace() / modelSpace() → McDbBlockTableRecordCurrent space / model space
currentSpace().getBoundingBox() → [minPt, maxPt]Bounding rectangle of the space
getUselessLayer() → id arrayUnused layers
marge(database, aryLayer?) → boolMerge another database into this one (optionally only the specified layer array)
insert(blkName, database) → boolInsert a block from another database
getSysVarString/setSysVarString(name, val)System variables (string)
getSysVarDouble/setSysVarDouble(name, val)System variables (double), e.g. LTSCALE global linetype scale
getSysVarLong/setSysVarLong, getSysVarPoint/setSysVarPointSystem variables (integer/point)
Properties: currentlyColorIndex, currentlyLayerName, currentlyLineTypeName, currentlyTextStyle, currentlyTrueColor, insbase, lineTypeScaleRead/write the current drawing state
free()Release (must be called for standalone readDwgFile instances)

LineWeight enum: kLnWt000~kLnWt211 (0/5/9/…/211), kLnWtByLayer=-1, kLnWtByBlock=-2, kLnWtByLwDefault=-3.

V. McDbEntity — Common Entity Parts ​

Properties and methods inherited by all concrete entities (Line/Circle/Polyline/Text/BlockReference/Dimension…):

Property/MethodDescription
layer / layerIdLayer name / layer id (read-write)
color / colorIndexColor (McCmColor) / color index (read-write)
linetype / linetypeId / linetypeScaleLinetype name / id / scale (read-write)
visibleWhether visible
textStyleIdText style id
getGeomExtents() → [minPt, maxPt]Geometric bounding rectangle
xdata(appName?) → MrxDbgRbListRead all extended data
setxDataString(appName, val, index=0) / getxDataString(appName, index=0)String extended data
setxDataDouble/ getxDataDouble, setxDataLong/getxDataLongDouble/integer extended data
explode() → id arrayExplode the entity (block references, polylines, etc.)
intersectWith(ent, mode=0) → point arrayIntersect with another entity

VI. Concrete Entity Classes (commonly used members) ​

The following members are taken from the source and sample usage; full definitions live in the corresponding src/mxcad/ files:

  • McDbLine: startPoint, endPoint (McGePoint3d, read-write; with new McDbLine() assign then Mx2DDraw.drawEntity(line))
  • McDbCircle: center, radius
  • McDbPolyline: numVerts vertex count, getPointAt(i), getBulgeAt(i)
  • McDbText: textString, position, alignmentPoint
  • McDbMText: contents, getAllText()
  • McDbBlockReference: position, blockName, blockTableRecordId, blockTransform, attributeCount, attributeItem(i) (returns McDbAttribute: tag, textString, position), createAttribute()
  • McDbDimension / McDbAlignedDimension / McDbRotatedDimension: xLine1Point, xLine2Point, getDimVarObjectId(342/343/344) (get the dimension block)
  • McDbBlockTableRecord (space/block definition): name, getAllEntity() → array of entity ids inside the block
  • McDbLayerTableRecord: name, colorIndex, color, off

VII. Selection Sets and Filtering ​

ts
import { MrxDbgSelSet } from "../mxcad/MrxDbgSelSet";
import { MrxDbgRbList } from "../mxcad/MrxDbgRbList";

let ss = new MrxDbgSelSet();
let filter = new MrxDbgRbList();
filter.addString("LWPOLYLINE", 5020);   // filter by type (5020 is the type code)
filter.addString("layer name", 8);        // filter by layer (8 is the layer code)
ss.allSelect(filter);                    // or selectAtPoint(pt, filter, tol)
                                          //    crossingSelect(pt1, pt2) / windowSelect(pt1, pt2)

for (let i = 0; i < ss.count; i++) {
    let ent = ss.item(i).getEntity();    // returns the concrete entity object
    if (ent instanceof McDbText) { /* ... */ }
}

MrxDbgRbList (resbuf list): count, atDouble/atLong/atString/atPoint(i), addDouble/addLong/addString/addPoint(v, dataType), itemDataType(i), removeAll().

VIII. Geometry Objects ​

  • McGePoint3d: x/y/z (read-write); construct with new McGePoint3d() or new McGePoint3d([x,y,z]); distanceTo(pt), add(pt), sum(pt), isEqualTo(pt), transformBy(mat)
  • McGeVector3d: vector
  • McGeMatrix3d: matrix transformation, preMultBy(mat) pre-multiply, etc.

IX. Secondary Development Guide ​

  1. New drawing feature: create a .ts under src/sample/, follow the TestDraw class structure of ParamDraw.ts (one primitive per draw method), register the command in MxCommand.ts

  2. Data extraction feature: see GetDwgData.ts (selection set + filter + instanceof dispatch + JSON output)

    ⚠️ No existing command covers geometry extraction: getcaddata extracts text and block attributes only — there is NO existing command for geometry entities such as lines/polylines/circles; secondary development is required. Minimal example (tested: extracts all lines to JSON; 105/105 lines matched exactly against the frontend mxcad export result):

    ts
    // src/sample/GetLines.ts
    import { Mx2DDraw, MxBackstage, MxFun } from "../MxFun";
    import { McDbLine } from "../mxcad/McDbLine";
    import { MrxDbgSelSet } from "../mxcad/MrxDbgSelSet";
    import { MrxDbgRbList } from "../mxcad/MrxDbgRbList";
    
    export function getlines(param: any) {
      if (!param.file) return { code: 3, message: "param.file error" };
      if (!param.outfile) return { code: 4, message: "param.outfile error" };
      let curPath = Mx2DDraw.getCurrentPath();
      if (!MxBackstage.openFile(curPath + param.file, 67904))
        return { code: 5, message: "openFile failed" };
      let db = MxBackstage.getDatabase();
      let ids = db.modelSpace().getAllEntity();   // all entity ids in model space
      let lines: any[] = [];
      for (let i = 0; i < ids.length; i++) {
        let ent = ids[i].getObject();            // id → concrete entity object
        if (!ent) continue;
        if (ent instanceof McDbLine) {
          let line: McDbLine = ent;
          lines.push({
            type: "LINE", layer: line.layer, linetype: line.linetype,
            handle: line.handle.imp,              // handle (string)
            startPoint: { x: line.startPoint.x, y: line.startPoint.y, z: line.startPoint.z },
            endPoint: { x: line.endPoint.x, y: line.endPoint.y, z: line.endPoint.z }
          });
        }
      }
      MxFun.writeFile(curPath + param.outfile, JSON.stringify({ count: lines.length, lines }, null, 1));
      return { ret: 0, resultfile: param.outfile };
    }

    Registration and invocation: add import { getlines } from "./sample/GetLines"; and MxProcessor.addCommand("getlines", getlines) in MxCommand.ts, then after npm run build run bin\node.exe mxapp.js getlines file=t1.dwg outfile=t1_lines.json. Other entity types (circle/polyline/dimension, etc.) follow the same pattern: swap the instanceof branch + corresponding members (see section 6).

  3. Cutting/export features: see CutDwg.ts (title block frame detection + sorting), ExportPdf.ts (whole-drawing PDF + title block frame localization)

  4. Compilation: npm run build (tsc); after any modification you MUST recompile (the runtime executes the .js)

  5. All sample code lives in the src/sample/ directory and can be copied and adapted directly