Skip to content

Fill ​

Solid fill ​

We can draw solid fill graphics directly through the drawPathToHatch() method provided by the mxcad instance object.

Click drawPathToHatch() to check the properties and methods in detail.

ts
import { MxCpp, McCmColor} from "mxcad"

const mxcad = MxCpp.getCurrentMxCAD()
// Draw a solid triangle to fill.
// Define the start point of a path
mxcad.pathMoveTo(150, 3300);
// The next point on the path
mxcad.pathLineTo(250, 3300);
// The next point on the path
mxcad.pathLineTo(250, 3400);
// The next point on the path
mxcad.pathLineTo(150, 3300);
// Fit the path into a transect
mxcad.drawColor = new McCmColor(255, 0, 0);
mxcad.drawPathToHatch(1);

We can also draw a solid fill graph by creating a McDbHatch object and setting the relevant fill properties.

Click on the McDbHatch to view detailed property and method descriptions.

ts
import { MxCpp, McDbHatch, McGePoint3dArray } from "mxcad"

const mxcad = MxCpp.getCurrentMxCAD();
// Draw rectangle fill
const solidReact = new McDbHatch();
const pointArr = new McGePoint3dArray();
pointArr.append(new McGePoint3d(250, 3400, 0));
pointArr.append(new McGePoint3d(250, 3300, 0));
pointArr.append(new McGePoint3d(350, 3300, 0));
pointArr.append(new McGePoint3d(350, 3400, 0));
solidReact.appendLoop(pointArr);
mxcad.drawEntity(solidReact);
// Draw circle fill
const solidCircle = new McDbHatch();
const center = new McGePoint3d(500, 3350, 0);
solidCircle.appendCircleLoop(center.x, center.y, 10);
mxcad.drawEntity(solidCircle);

Pattern fill ​

We can draw the patternfill pattern by adding a pattern definition using the addPatternDefinition() method provided by the mxcad instance object and setting the newly defined pattern to the value of the line attribute currently drawn by the drawPatternDefinition.

Click on the [addPatternDefinition ()] (../../api/classes/2d.McObject.md#addpatterndefinition) View detailed property and method descriptions.

ts
import { MxCpp, McCmColor} from "mxcad"
//angle, x-origin,y-origin, delta-x,delta-y,dash-1,dash-2, …
// "MyHatchPattern1" = Name of the pattern
//45 = angle Indicates the pattern line Angle.
//0 = x-origin is the x-coordinate of the point through which the first fill line passes
//0 = y-origin is the y coordinate of the point through which the first fill line passes
//0 = delta-x is the x-direction offset of the next fill line from the previous one
//0.125 = delta-y is the Y shift of the next fill line from the previous one
const mxcad = MxCpp.getCurrentMxCAD()
mxcad.addPatternDefinition("MyHatchPattern1", "((45, 0,0, 0,0.125))");
mxcad.drawPatternDefinition = "MyHatchPattern1";
// Define the start point of a path
mxcad.pathMoveToEx(600, 3300, 0, 0, 0.3);
// The next point on the path
mxcad.pathLineTo(700, 3300);
// The next point on the path
mxcad.pathLineTo(700, 3400);
// The next point on the path
mxcad.pathLineTo(600, 3300);
// Turn the path into a fill,80, is the scale of the fill pattern.
mxcad.drawPathToHatch(100);

We can also set the fill pattern for the fill entity by creating a McDbHatch object and providing the addPatternDefinition() method via the fill class to add a pattern definition.

Click on the McDbHatch.addPatternDefinition() to view detailed property and method descriptions.

ts
import { MxCpp, McDbHatch } from "mxcad"

// Draws a circle fill with pattern definition
const mxcad = MxCpp.getCurrentMxCAD();
mxcad.newFile();
// Draws a circle fill with pattern definition
const solidCircle = new McDbHatch();
const center = new McGePoint3d(500, 3350, 0);
solidCircle.appendCircleLoop(center.x, center.y, 30);
solidCircle.clearPatternDefinition();
/**
 * 45 = angle It's the pattern line Angle.
 * 0 = x-origin It's the base X coordinate
 * 0 = y-origin It's the base Y coordinate
 * 0 = delta-x   It's offset in the X direction
 * 0.25 = delta-y   It's a shift in the Y direction
 * [45, 0.17677695, 0, 0, 0.25, 0.125, -0.0625] It's dash data
 */
solidCircle.addPatternDefinition(45, 1, 1, 1, 0.25, [45, 0.17677695, 0, 0, 0.25, 0.125, -0.0625])
solidCircle.setPattern(McDb.HatchPatternType.kCustomDefined, 'test')
solidCircle.trueColor = new McCmColor(0, 133, 122);
mxcad.drawEntity(solidCircle);
mxcad.zoomAll();

Parsing hatch pattern files (.pat) ​

AutoCAD hatch pattern files (such as acad.pat) describe pattern definitions in plain text. We can read the content of a .pat file, parse it, and restore it as a fill pattern in MxCAD through the mxcad pattern definition API.

The format rules of a .pat file are as follows:

  • Lines starting with ;; are comments; blank lines are ignored;
  • A line starting with * is the pattern name line, in the format *pattern-name, description;
  • Each line after the pattern name line defines one group of pattern lines for the pattern, in the format angle, x-origin, y-origin, delta-x, delta-y, dash-1, dash-2, ...:
    • angle is the angle of the pattern line (in degrees);
    • x-origin, y-origin are the base point coordinates of the pattern line;
    • delta-x, delta-y are the X/Y offsets between two adjacent groups of fill lines;
    • dash-1, dash-2, ... is optional dash data: positive values draw a segment, negative values leave a gap, used to draw dashed-segment patterns;
  • Values that start with a decimal point (such as .125) are equivalent to 0.125.

The following is a snippet of a .pat file:

*ANSI31, ANSI Iron, Brick, Stone masonry
45, 0,0, 0,.125
*ANSI37, ANSI Lead, Zinc, Magnesium, Sound/Heat/Elec Insulation
45, 0,0, 0,.125
135, 0,0, 0,.125

The parsing function below converts the read .pat file content into a list of patterns. The value of each pattern is assembled into the definition string format required by addPatternDefinition(), such as "((45, 0,0, 0,0.125)(135, 0,0, 0,0.125))":

ts
const str = "..." // the content of the read .pat file
type PatInfo = { value: string; id: string; name: string; imgPath: string };

function useConvertPatFile(content: string) {
  const patterns: PatInfo[] = [];
  let currentPattern: PatInfo | null = null;

  // Split the file content into lines
  const lines = content.split('\n');

  // Iterate over each line
  lines.forEach(line => {
    // Ignore blank lines
    if (line.trim() === '') {
      return;
    }

    // Skip comment lines
    if (line.startsWith(';;')) {
      return;
    }

    // Check whether this is the start of a pattern
    if (line.startsWith('*')) {
      // If there is already a current pattern, push it to the array
      if (currentPattern) {
        currentPattern.value += ")"
        patterns.push(currentPattern);
      }

      // Create a new pattern
      const patternInfo = line.substring(1).split(',').map(info => info.trim());
      currentPattern = {
        id: patternInfo[0],
        name: patternInfo[1],
        value: "(",
        imgPath: ''
      };
    } else {
      // If there is no current pattern, a pattern definition line appeared before any pattern name line
      if (!currentPattern) {
        console.error("Invalid pattern file format. Missing pattern start marker (*)");
        return;
      }
      // Complete values starting with a decimal point into the 0.x form
      const lineString = line.trim().split(",").map((v) => {
        if (v.startsWith(".")) {
          return "0" + v
        }
        return v
      }).join()
      // Append the line content to the value of the current pattern
      const value = (currentPattern.value === "(" ? "(" : " (") + lineString + ")";
      currentPattern.value += value
    }
  });

  // Push the last pattern to the array
  if (currentPattern) {
    currentPattern.value += ")"
    patterns.push(currentPattern);
  }

  return patterns;
}

const patternDataList = useConvertPatFile(str);

Once the pattern list is parsed, we can register the pattern definition with the addPatternDefinition() method of the mxcad instance object, then set the current drawing pattern to draw the pattern fill:

ts
import { MxCpp } from "mxcad"

const mxcad = MxCpp.getCurrentMxCAD();
const item = patternDataList[10]; // load the corresponding pattern, 10: the tenth pattern
mxcad.addPatternDefinition(item.id, item.value);
mxcad.drawPatternDefinition = item.id;
// Define the start point of a path
mxcad.pathMoveTo(600, 3300);
// The next point on the path
mxcad.pathLineTo(700, 3300);
// The next point on the path
mxcad.pathLineTo(700, 3400);
// The next point on the path
mxcad.pathLineTo(600, 3300);
// Turn the path into a fill, 100 is the scale of the fill pattern
mxcad.drawPathToHatch(100);

We can also parse the pattern definition string group by group into parameters, and call the addPatternDefinition() method of the McDbHatch object to add pattern definitions to the fill entity:

ts
import { MxCpp, McDb, McDbHatch } from "mxcad"

/**
 * Parse the pattern definition string and call hatch's addPatternDefinition group by group
 * @param str the pattern definition string, for example: "((0, 0,0, 0,0.275, .2,-.075)(90, 0,0, 0,0.275, .2,-.075))"
 */
const parseAndAddPattern = (str: string, hatch: McDbHatch) => {
  // 1. Use a regular expression to extract all number groups inside parentheses
  const groups = str.match(/\(([^)]+)\)/g);
  if (!groups || groups.length === 0) return;
  groups.forEach(group => {
    // Extract all numbers inside this group (compatible with signs, decimal points and scientific notation)
    const nums = group.match(/-?[\d.eE+-]+/g)?.map(Number) || [];
    // 2. Map the parameters, missing values default to 0
    const angle = nums[0] ?? 0;
    const baseX = nums[1] ?? 0;
    const baseY = nums[2] ?? 0;
    const offsetX = nums[3] ?? 0;
    const offsetY = nums[4] ?? 0;
    // 3. Assemble the 6th and later parameters into the dashes array
    const dashes = nums.length > 5 ? nums.slice(5) : [];
    // 4. Add one group of pattern line definitions to the fill entity
    hatch.addPatternDefinition(angle, baseX, baseY, offsetX, offsetY, dashes);
  });
};

const hatchObj = new McDbHatch();
parseAndAddPattern(item.value, hatchObj);
hatchObj.setPattern(McDb.HatchPatternType.kCustomDefined, item.id);
hatchObj.appendCircleLoop(0, 0, 200);
hatchObj.scalePattern(5);
MxCpp.getCurrentMxCAD().drawEntity(hatchObj);

Hollow fill ​

The boundary of the fill entity McDbHatch can consist of multiple loops: the outer loop is the fill area, and other loops added inside it become holes, creating a hollow fill effect.

There are two ways to add an inner loop boundary:

  • Call appendCircleLoop() directly to add a circular inner loop boundary;
  • Call getSamplePoints() on any curve object to discretely sample it into a point array, then add it as an inner loop boundary through appendLoop().

Click McDbHatch.appendLoop(), McDbHatch.appendCircleLoop(), McDbCurve.getSamplePoints() to check the properties and methods in detail.

ts
import { MxCpp, McDbHatch, McGePoint3dArray, McGePoint3d, McDbCircle } from "mxcad"

const mxcad = MxCpp.getCurrentMxCAD();
mxcad.newFile();
// Draw rectangle fill
const solidReact = new McDbHatch();
const pointArr = new McGePoint3dArray();
pointArr.append(new McGePoint3d(250, 3400, 0));
pointArr.append(new McGePoint3d(250, 3300, 0));
pointArr.append(new McGePoint3d(350, 3300, 0));
pointArr.append(new McGePoint3d(350, 3400, 0));
// The outer loop boundary
solidReact.appendLoop(pointArr);

// Method 1: add a circular inner loop boundary, hollowing out a circular hole in the fill
solidReact.appendCircleLoop(265, 3385, 10);

// Method 2: discretely sample a circle curve into a point array, then add the inner loop boundary with appendLoop
const circle = new McDbCircle(310, 3345, 0, 20);
const samplePoints = circle.getSamplePoints(0.000001);
let aryPoint = new McGePoint3dArray();
samplePoints.forEach((val, _type, dxf) => {
  if (dxf === 1010) {
    const point = new McGePoint3d(val.x, val.y, val.z)
    aryPoint.append(point);
  }
});
solidReact.appendLoop(aryPoint);

mxcad.drawEntity(solidReact);
mxcad.zoomAll();

Select point fill ​

We can use the MxCADUtilityClass class to realize the point-filling function combined with interactive drawing, which provides a series of graph-related tool methods. The builderHatchFromPoint() method provides a point coordinate to fill the corresponding position entity's fill object McDbHatch, if the fill object is successfully drawn, return the fill object, if it is not successfully drawn, return null.

In addition, mxcad provides a series of methods and properties to set the fill object McDbHatch, you can customize the fill graph style according to your needs.

tap MxCADUtilityClass(), McDbHatch() view detailed properties and methods.

ts
import { McGePoint3d, MxCADUiPrPoint, MxCADUtility, MxCpp } from "mxcad";

const getPoint = new MxCADUiPrPoint();
console.log("\n specifies a point inside the fill area :");
getPoint.disableAllTrace(true);
getPoint.setDisableOsnap(true);
let pt = (await getPoint.go()) as McGePoint3d;
if (! pt) return;

let hatch = MxCADUtility.builderHatchFromPoint(pt);
if (! hatch) {
console.log(" Closed region \n not found ")
return;
}
hatch.clearPatternDefinition();
hatch.addPatternDefinition(45, 1, 1, 1, 0.25, [45, 0.17677695, 0, 0, 0.25, 0.125, -0.0625])
hatch.setPattern(McDb.HatchPatternType.kCustomDefined, 'test')
hatch.trueColor = new McCmColor(0, 133, 122)
let mxcad = MxCpp.getCurrentMxCAD();
mxcad.drawEntity(hatch);