RepliCAD

Форк
0
/
assemblyExporter.ts 
151 строка · 4.0 Кб
1
import type {
2
  Quantity_ColorRGBA,
3
  TCollection_ExtendedString,
4
  TDocStd_Document,
5
} from "replicad-opencascadejs";
6
import { uuidv } from "../utils/uuid";
7
import { getOC } from "../oclib";
8
import { AnyShape } from "../shapes";
9
import { GCWithScope, WrappingObj } from "../register";
10

11
const wrapString = (str: string): TCollection_ExtendedString => {
12
  const oc = getOC();
13
  return new oc.TCollection_ExtendedString_2(str, true);
14
};
15

16
function parseSlice(hex: string, index: number): number {
17
  return parseInt(hex.slice(index * 2, (index + 1) * 2), 16);
18
}
19
function colorFromHex(hex: string): [number, number, number] {
20
  let color = hex;
21
  if (color.indexOf("#") === 0) color = color.slice(1);
22

23
  if (color.length === 3) {
24
    color = color.replace(/([0-9a-f])/gi, "$1$1");
25
  }
26

27
  return [parseSlice(color, 0), parseSlice(color, 1), parseSlice(color, 2)];
28
}
29

30
const wrapColor = (hex: string, alpha = 1): Quantity_ColorRGBA => {
31
  const oc = getOC();
32
  const [r, g, b] = colorFromHex(hex);
33

34
  return new oc.Quantity_ColorRGBA_5(r / 255, g / 255, b / 255, alpha);
35
};
36

37
export class AssemblyExporter extends WrappingObj<TDocStd_Document> {}
38

39
type ShapeConfig = {
40
  shape: AnyShape;
41
  color?: string;
42
  alpha?: number;
43
  name?: string;
44
};
45

46
export function createAssembly(shapes: ShapeConfig[] = []): AssemblyExporter {
47
  const oc = getOC();
48

49
  const doc = new oc.TDocStd_Document(wrapString("XmlOcaf"));
50

51
  oc.XCAFDoc_ShapeTool.SetAutoNaming(false);
52

53
  const mainLabel = doc.Main();
54

55
  const tool = oc.XCAFDoc_DocumentTool.ShapeTool(mainLabel).get();
56
  const ctool = oc.XCAFDoc_DocumentTool.ColorTool(mainLabel).get();
57

58
  for (const { shape, name, color, alpha } of shapes) {
59
    const shapeNode = tool.NewShape();
60

61
    tool.SetShape(shapeNode, shape.wrapped);
62

63
    oc.TDataStd_Name.Set_1(shapeNode, wrapString(name || uuidv()));
64

65
    ctool.SetColor_3(
66
      shapeNode,
67
      wrapColor(color || "#f00", alpha ?? 1),
68
      // @ts-expect-error the type system does not work for these
69
      oc.XCAFDoc_ColorType.XCAFDoc_ColorSurf
70
    );
71
  }
72

73
  tool.UpdateAssemblies();
74

75
  return new AssemblyExporter(doc);
76
}
77

78
export type SupportedUnit =
79
  | "M"
80
  | "CM"
81
  | "MM"
82
  | "INCH"
83
  | "FT"
84
  | "m"
85
  | "mm"
86
  | "cm"
87
  | "inch"
88
  | "ft";
89

90
export function exportSTEP(
91
  shapes: ShapeConfig[] = [],
92
  { unit, modelUnit }: { unit?: SupportedUnit; modelUnit?: SupportedUnit } = {}
93
): Blob {
94
  const oc = getOC();
95
  const r = GCWithScope();
96

97
  const doc = createAssembly(shapes);
98

99
  if (unit || modelUnit) {
100
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
101
    const dummy = r(new oc.STEPCAFControl_Writer_1());
102

103
    oc.Interface_Static.SetCVal(
104
      "xstep.cascade.unit",
105
      (modelUnit || unit || "MM").toUpperCase()
106
    );
107
    oc.Interface_Static.SetCVal(
108
      "write.step.unit",
109
      (unit || modelUnit || "MM").toUpperCase()
110
    );
111
  }
112

113
  const session = r(new oc.XSControl_WorkSession());
114
  const writer = r(
115
    new oc.STEPCAFControl_Writer_2(
116
      r(new oc.Handle_XSControl_WorkSession_2(session)),
117
      false
118
    )
119
  );
120
  writer.SetColorMode(true);
121
  writer.SetLayerMode(true);
122
  writer.SetNameMode(true);
123
  oc.Interface_Static.SetIVal("write.surfacecurve.mode", true);
124
  oc.Interface_Static.SetIVal("write.precision.mode", 0);
125
  oc.Interface_Static.SetIVal("write.step.assembly", 2);
126
  oc.Interface_Static.SetIVal("write.step.schema", 5);
127

128
  const progress = r(new oc.Message_ProgressRange_1());
129
  writer.Transfer_1(
130
    new oc.Handle_TDocStd_Document_2(doc.wrapped),
131
    // @ts-expect-error the type system does not work for these
132
    oc.STEPControl_StepModelType.STEPControl_AsIs,
133
    null,
134
    progress
135
  );
136

137
  const filename = "export.step";
138
  const done = writer.Write(filename);
139

140
  if (done === oc.IFSelect_ReturnStatus.IFSelect_RetDone) {
141
    // Read the STEP File from the filesystem and clean up
142
    const file = oc.FS.readFile("/" + filename);
143
    oc.FS.unlink("/" + filename);
144

145
    // Return the contents of the STEP File
146
    const blob = new Blob([file], { type: "application/STEP" });
147
    return blob;
148
  } else {
149
    throw new Error("WRITE STEP FILE FAILED.");
150
  }
151
}
152

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.