Command API Reference
Command API Reference
This chapter provides a summary of commonly used APIs in command development as a quick reference manual.
Engine Core Object
Engine is the core singleton object of WebCAD, providing access to various subsystems.
Common Properties
import { Engine } from 'vjcad';
// Canvas control
Engine.pcanvas
// Current document
Engine.currentDoc
// Undo manager
Engine.undoManager
// Coordinate transformation
Engine.trans
// Current space (model space or paper space)
Engine.currentSpace
// Active document
Engine.activeDocument
// System variables
Engine.CECOLOR // Current color
Engine.OFFSETDIST // Offset distancepcanvas Methods
// Add entity
Engine.pcanvas.addEntity(entity: EntityBase): EntityBase
// Graphics regeneration
Engine.pcanvas.regen(): void // Partial update, only redraws modified entities
Engine.pcanvas.regen(true): void // Full redraw, clears and redraws all graphics
Engine.pcanvas.redraw(): void // Renders after updating view transform (pan/zoom/rotate)
Engine.pcanvas.render(): void // Lowest-level render, only performs GPU drawing
// Highlighting
Engine.pcanvas.highLightEntities(entities: EntityBase[]): void
Engine.pcanvas.clearHighLight(): void
Engine.pcanvas.clearGrip(): void
// Zoom
Engine.pcanvas.zoomExtents(): void
// Draw control
Engine.pcanvas.drawControl.drawPreviewEntity(entity: EntityBase): void
Engine.pcanvas.drawControl.drawPreviewEntities(entities: EntityBase[]): void
Engine.pcanvas.drawControl.drawHighLightEntity(entity: EntityBase): void
Engine.pcanvas.drawControl.previewGraphics.clear(): void
Engine.pcanvas.drawControl.setPreviewPosition(point: Point2D): void
Engine.pcanvas.drawControl.setPreviewRotation(angle: number): void
Engine.pcanvas.drawControl.setPreviewScale(sx: number, sy: number): void
Engine.pcanvas.drawControl.resetPreview(): voidundoManager Methods
// Undo marks (description is an optional operation label shown in UI and command line)
Engine.undoManager.start_undoMark(description?: string | UndoDescriptor): void
Engine.undoManager.end_undoMark(): void
// Undo/redo wrapper (supports nesting, recommended in commands)
Engine.startUndoRecord(description?: string | UndoDescriptor): void
Engine.endUndoRecord(): void
// Record operations
Engine.undoManager.added_undoMark(entities: EntityBase[]): void
Engine.undoManager.erased_undoMark(entities: EntityBase[]): void
Engine.undoManager.moved_undoMark(entities: EntityBase[], from: Point2D, to: Point2D): void
Engine.undoManager.rotate_undoMark(entities: EntityBase[], center: Point2D, angle: number): void
Engine.undoManager.mirrored_undoMark(entities: EntityBase[], pt1: Point2D, pt2: Point2D): void
Engine.undoManager.modEntity_undoMark(entity: EntityBase): void
Engine.undoManager.modLine_undoMark(line: LineEnt): void
Engine.undoManager.modArc_undoMark(arc: ArcEnt): void
Engine.undoManager.modRay_undoMark(ray: RayEnt): void
// Query history and batch operations
Engine.undoManager.getUndoHistory(): UndoHistoryItem[]
Engine.undoManager.getRedoHistory(): UndoHistoryItem[]
Engine.undoManager.getUndoCount(): number
Engine.undoManager.getRedoCount(): number
Engine.undoManager.undoSteps(countOrName: number | string, options?: { silent?: boolean }): number
Engine.undoManager.redoSteps(countOrName: number | string, options?: { silent?: boolean }): numbertrans Coordinate Transformation
// Canvas coordinates to world coordinates
Engine.trans.CanvasToWcs(canvasPoint: Point2D): Point2D
// World coordinates to canvas coordinates
Engine.trans.WcsToCanvas(worldPoint: Point2D): Point2DcurrentDoc / currentSpace
// Current document
Engine.currentDoc.currentSpace // Current space
Engine.currentDoc.CLAYER // Current layer
// Current space operations
Engine.currentDoc.currentSpace.items // All entities
Engine.currentDoc.currentSpace.erase(entities: EntityBase[]): void
Engine.currentDoc.currentSpace.addEntities(entities: EntityBase[]): voidInput Functions
getPoint
Get point coordinate input.
import { getPoint, PointInputOptions, InputStatusEnum } from 'vjcad';
const options = new PointInputOptions("Specify point:");
const result = await getPoint(options);
if (result.status === InputStatusEnum.OK) {
const point: Point2D = result.value;
}PointInputOptions Properties:
| Property | Type | Description |
|---|---|---|
message | string | Prompt message |
keywords | string[] | Keyword list |
useBasePoint | boolean | Whether to use base point (rubber band line) |
basePoint | Point2D | Base point coordinates |
useOsnap | boolean | Whether to enable object snap |
callback | function | Mouse move callback |
allowNumberResult | boolean | Whether to allow numeric input |
useOrthoMode | boolean | Whether to use ortho mode |
forceOrthomode | boolean | Whether to force ortho |
hideRubberBand | boolean | Whether to hide rubber band line |
Return Value PointInputResult:
| Property | Type | Description |
|---|---|---|
status | number | Input status |
value | Point2D | Point coordinates |
stringResult | string | Keyword result |
numberValue | number | Numeric result (requires allowNumberResult) |
getSelections
Get multiple entity selection.
import { getSelections, SelectionInputOptions, InputStatusEnum } from 'vjcad';
const options = new SelectionInputOptions();
const result = await getSelections(options);
if (result.status === InputStatusEnum.OK) {
const entities: EntityBase[] = result.value;
}SelectionInputOptions Properties:
| Property | Type | Description |
|---|---|---|
useOsnap | boolean | Whether to enable object snap |
Return Value SelectionSetInputResult:
| Property | Type | Description |
|---|---|---|
status | number | Input status |
value | EntityBase[] | Array of selected entities |
stringResult | string | Keyword result |
getEntity
Get single entity selection.
import { getEntity, SelectionSetInputOptions, InputStatusEnum } from 'vjcad';
const options = new SelectionSetInputOptions("Select an object:");
const result = await getEntity(options);
if (result.status === InputStatusEnum.OK) {
const entity = result.pickedEntity;
const pickPoint = result.pickedPoint;
}SelectionSetInputOptions Properties:
| Property | Type | Description |
|---|---|---|
message | string | Prompt message |
keywords | string[] | Keyword list |
useNestedPick | boolean | Whether to allow nested selection |
Return Value EntityPickResult:
| Property | Type | Description |
|---|---|---|
status | number | Input status |
pickedEntity | EntityBase | Picked entity |
pickedPoint | Point2D | Pick point coordinates |
stringResult | string | Keyword result |
getString
Get string input.
import { Engine, StringInputOptions, InputStatusEnum } from 'vjcad';
const options = new StringInputOptions("Enter text:");
const result = await Engine.getString(options);
if (result.status === InputStatusEnum.OK) {
const text: string = result.value;
}getInteger
Get integer input.
import { Engine, IntegerInputOptions, InputStatusEnum } from 'vjcad';
const options = new IntegerInputOptions("Enter quantity:");
options.defaultValue = 10;
options.lowerLimit = 1;
options.upperLimit = 100;
const result = await Engine.getInteger(options);
if (result.status === InputStatusEnum.OK) {
const count: number = result.value;
}getReal
Get real number input.
import { Engine, RealInputOptions, InputStatusEnum } from 'vjcad';
const options = new RealInputOptions("Enter scale:");
options.defaultValue = 1.0;
const result = await Engine.getReal(options);
if (result.status === InputStatusEnum.OK) {
const scale: number = result.value;
}getKeyword
Get keyword selection.
import { Engine, KeywordInputOptions, InputStatusEnum } from 'vjcad';
const options = new KeywordInputOptions("Select mode [Window(W)/Crossing(C)]:");
options.keywords = ["W", "C"];
options.defaultKeyword = "W";
const result = await Engine.getKeyword(options);
if (result.status === InputStatusEnum.OK) {
const keyword: string = result.value;
}InputStatusEnum
Input status enumeration values.
| Value | Name | Description |
|---|---|---|
| 5100 | OK | Successfully obtained input |
| -5002 | Cancel | User cancelled |
| -5005 | Keyword | User entered a keyword |
| 3 | EnterOrSpace | User pressed Enter or Space |
| 4 | IsNumber | User entered a number |
| 5000 | None | No input |
| -5001 | Error | An error occurred |
Output Functions
writeMessage
Output message to the command line.
import { writeMessage } from 'vjcad';
writeMessage("<br/>Operation completed.");
writeMessage(`<br/>${count} entities selected.`);ssSetFirst
Clear selection set.
import { ssSetFirst } from 'vjcad';
ssSetFirst([]); // Clear current selectionEntity Operations
Entity Base Class Methods
All entities inherit from EntityBase and have the following common methods:
// Set default properties (layer, color, etc.)
entity.setDefaults(): void
// Clone entity
entity.clone(): EntityBase
// Geometric transformations
entity.move(from: Point2D, to: Point2D): void
entity.rotate(center: Point2D, angle: number): void
entity.mirror(pt1: Point2D, pt2: Point2D): void
entity.scale(center: Point2D, factor: number): void
// Copy default properties from another entity
entity.fromDefaultProps(source: EntityBase): voidEntity Properties
// Common properties
entity.id: number // Entity ID
entity.type: string // Entity type
entity.color: number // Color
entity.layer: string // Layer name
entity.layerId: number // Layer IDCommon Entity Types
| Type | Class Name | type Value |
|---|---|---|
| Line | LineEnt | "LINE" |
| Circle | CircleEnt | "CIRCLE" |
| Arc | ArcEnt | "ARC" |
| Polyline | PolylineEnt | "PLINE" |
| Single-line Text | TextEnt | "TEXT" |
| Multi-line Text | MTextEnt | "MTEXT" |
| Block Reference | InsertEnt | "INSERT" |
| Ellipse | EllipseEnt | "ELLIPSE" |
| Spline | SplineEnt | "SPLINE" |
| Hatch | HatchEnt | "HATCH" |
| Image | ImageEnt | "IMAGE" |
| Point | DotEnt | "DOT" |
| Ray | RayEnt | "RAY" |
| Construction Line | XLineEnt | "XLINE" |
| Solid Fill | SolidEnt | "SOLID" |
Entity Creation Examples
import {
LineEnt,
CircleEnt,
ArcEnt,
PolylineEnt,
BulgePoint,
Point2D
} from 'vjcad';
// Create a line
const line = new LineEnt(
new Point2D(0, 0),
new Point2D(100, 100)
);
line.setDefaults();
// Create a circle
const circle = new CircleEnt(
new Point2D(50, 50), // Center
25 // Radius
);
circle.setDefaults();
// Create an arc
const arc = new ArcEnt(
new Point2D(50, 50), // Center
25, // Radius
0, // Start angle (radians)
Math.PI // End angle (radians)
);
arc.setDefaults();
// Create a polyline
const pline = new PolylineEnt();
pline.bulgePoints.add(new BulgePoint(new Point2D(0, 0), 0));
pline.bulgePoints.add(new BulgePoint(new Point2D(100, 0), 0));
pline.bulgePoints.add(new BulgePoint(new Point2D(100, 100), 0));
pline.isClosed = true;
pline.setDefaults();Command Registration
CommandDefinition
import { CommandDefinition, CommandOptions } from 'vjcad';
const options = new CommandOptions();
options.useAutoComplete = true;
const definition = new CommandDefinition(
'MYCMD', // Command name
'Command description', // Description
MyCommand, // Command class
options // Options
);CommandRegistry
import { CommandRegistry } from 'vjcad';
// Register command
CommandRegistry.regist(definition);
// Query command
const cmd = CommandRegistry.item('MYCMD');
// All commands
const allCommands = CommandRegistry.items;Register Commands in Plugins
// In onActivate
context.registerCommand('MYCMD', 'Command description', MyCommand);
// In onDeactivate
context.unregisterCommand('MYCMD');Utility Functions
startUndoMark / endUndoMark
Convenient undo mark functions:
import { startUndoMark, endUndoMark } from 'vjcad';
startUndoMark();
try {
// Operations...
} finally {
endUndoMark();
}regen
Regenerate graphics (partial update of modified entities):
import { regen } from 'vjcad';
// Partial update: only redraws entities marked with setModified()
regen(); // Equivalent to Engine.regen()
// Full redraw: clears and redraws all graphics
Engine.regen(true);Method Differences
render(): Lowest level, only calls GPU to render the current frameredraw(): Updates view transform (position/zoom/rotation), then calls renderregen(): Partial update, only re-renders entities marked with setModifiedregen(true): Full redraw, clears and redraws all graphics
Geometry Calculations
Point2D
import { Point2D } from 'vjcad';
const p1 = new Point2D(0, 0);
const p2 = new Point2D(100, 100);
// Properties
p1.x
p1.y
// Methods
p1.clone(): Point2D
p1.distanceTo(p2): number
p1.move(from: Point2D, to: Point2D): void
p1.rotate(angle: number, center?: Point2D): void
p1.offset(delta: Point2D): voidGeometryCalculator
Geometry calculation utility class:
import { GeometryCalculator } from 'vjcad';
// Line-to-line intersection
GeometryCalculator.LineToLine(line1, line2): Point2D[]
// Line-to-circle intersection
GeometryCalculator.LineToCircle(line, circle): Point2D[]
// Line-to-arc intersection
GeometryCalculator.LineToArc(line, arc): Point2D[]
// Line-to-polyline intersection
GeometryCalculator.LineToPline(line, pline): Point2D[]
// Circle-to-circle intersection
GeometryCalculator.CircleToCircle(circle1, circle2): Point2D[]
// Determine which side a point is on relative to a line
GeometryCalculator.witchSidePointToLine(lineStart, lineEnd, point): numberAngle Constants
import { ANGLE_90, ANGLE_180, ANGLE_270 } from 'vjcad';
// 90 degrees (radians)
ANGLE_90 // Math.PI / 2
// 180 degrees (radians)
ANGLE_180 // Math.PI
// 270 degrees (radians)
ANGLE_270 // Math.PI * 3 / 2Angle Utilities
import { normalizeAngleAlt, polarToCartesian } from 'vjcad';
// Normalize angle to [-PI, PI]
normalizeAngleAlt(angle: number): number
// Polar coordinates to Cartesian coordinates
polarToCartesian(center: Point2D, angle: number, distance: number): Point2DCoordinate Utilities
import {
getAngleBetweenPoints,
rotatePointAroundCenter
} from 'vjcad';
// Calculate angle between two points
getAngleBetweenPoints(p1: Point2D, p2: Point2D): number
// Rotate around a center point
rotatePointAroundCenter(center: Point2D, point: Point2D, angle: number): Point2DGeneral Utilities
import { distance, formatNumberEx } from 'vjcad';
// Calculate distance between two points
distance(p1: Point2D, p2: Point2D): number
// Format number
formatNumberEx(value: number, decimals: number): string