Debian Codegraph @

src/scene/load/x3dloadinternalstl.pas

raw
1 {
2 Copyright 2017-2024 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Load and save models in the STL format.
17 See https://en.wikipedia.org/wiki/STL_%28file_format%29 for
18 more information about STL. }
19 unit X3DLoadInternalSTL;
20
21 {$I castleconf.inc}
22
23 interface
24
25 implementation
26
27 uses SysUtils, Classes,
28 X3DNodes, X3DLoad, CastleClassUtils, CastleVectors, CastleUtils, CastleDownload,
29 CastleTriangles, CastleLog, CastleStreamUtils,
30 CastleShapes, CastleSceneCore;
31
32 { Load STL text (ASCII) variation. }
33 procedure LoadSTLText(const Stream: TStream;
34 const Coordinate, Normal: TVector3List);
35
36 procedure AddTriangle(const Coordinate, Normal: TVector3List;
37 NormalVector: TVector3; const Triangle: TTriangle3);
38 begin
39 { if the STL file specifies zero vector, calculate it }
40 if NormalVector.IsPerfectlyZero then
41 NormalVector := Triangle.Normal;
42
43 { add 3 times the same NormalVector.
44 See TODO about TriangleSet.NormalPerVertex lower in this file. }
45 Normal.Add(NormalVector);
46 Normal.Add(NormalVector);
47 Normal.Add(NormalVector);
48
49 Coordinate.Add(Triangle.Data[0]);
50 Coordinate.Add(Triangle.Data[1]);
51 Coordinate.Add(Triangle.Data[2]);
52 end;
53
54 var
55 TextReader: TTextReader;
56
57 { Read a word expecting the ExpectedValue. Returns @true if found expected,
58 otherwise returns @false (and the warning is already emitted). }
59 function ReadExpect(const ExpectedValue: String): boolean;
60 var
61 S: String;
62 begin
63 S := TextReader.Read;
64 Result := S = ExpectedValue;
65 if not Result then
66 begin
67 if S = '' then
68 WritelnWarning('STL', 'Unexpected end of the file, expected "' + ExpectedValue + '"')
69 else
70 WritelnWarning('STL', 'Unexpected word "' + S + '" in file, expected "' + ExpectedValue + '"');
71 end;
72 end;
73
74 var
75 S: String;
76 NormalVector: TVector3;
77 Triangle: TTriangle3;
78 I: Integer;
79 begin
80 TextReader := TTextReader.Create(Stream, false);
81 try
82 TextReader.Readln; // read header line
83
84 repeat
85 { read triangle }
86 S := TextReader.Read;
87 if S = 'facet' then
88 begin
89 { S = facet -> new triangle }
90 if not ReadExpect('normal') then Exit;
91 NormalVector := TextReader.ReadVector3;
92 if not ReadExpect('outer') then Exit;
93 if not ReadExpect('loop') then Exit;
94 for I := 0 to 2 do
95 begin
96 if not ReadExpect('vertex') then Exit;
97 Triangle.Data[I] := TextReader.ReadVector3;
98 end;
99 AddTriangle(Coordinate, Normal, NormalVector, Triangle);
100 if not ReadExpect('endloop') then Exit;
101 if not ReadExpect('endfacet') then Exit;
102 end else
103 begin
104 { S = anything else -> end of reading }
105 if S <> 'endsolid' then
106 WritelnWarning('STL', 'Unexpected word "' + S + '" in file, expected "facet" or "endsolid"');
107 Exit;
108 end;
109 until false;
110
111 finally FreeAndNil(TextReader) end;
112 end;
113
114 const
115 BinaryHeader = 80;
116
117 procedure LittleEndianToNative(var V: TVector3);
118 begin
119 {$ifdef ENDIAN_BIG}
120 SwapEndian(V.X);
121 SwapEndian(V.Y);
122 SwapEndian(V.Z);
123 {$endif ENDIAN_BIG}
124 end;
125
126 procedure NativeToLittleEndian(var V: TVector3);
127 begin
128 {$ifdef ENDIAN_BIG}
129 SwapEndian(V.X);
130 SwapEndian(V.Y);
131 SwapEndian(V.Z);
132 {$endif ENDIAN_BIG}
133 end;
134
135 { Load STL binary variation. }
136 procedure LoadSTLBinary(const Stream: TStream;
137 const Coordinate, Normal: TVector3List);
138 var
139 TriangleCount: UInt32;
140 NormalVector: TVector3;
141 Triangle: TTriangle3;
142 I: Integer;
143 TriangleAttribute: Word;
144 begin
145 Stream.Position := BinaryHeader;
146 Stream.ReadLE(TriangleCount);
147
148 Coordinate.Count := TriangleCount * 3;
149 Normal.Count := TriangleCount * 3;
150
151 for I := 0 to TriangleCount - 1 do
152 begin
153 Stream.ReadBuffer(NormalVector, SizeOf(NormalVector));
154 LittleEndianToNative(NormalVector);
155
156 Stream.ReadBuffer(Triangle, SizeOf(Triangle));
157 LittleEndianToNative(Triangle.Data[0]);
158 LittleEndianToNative(Triangle.Data[1]);
159 LittleEndianToNative(Triangle.Data[2]);
160
161 { we read and ignore for now the TriangleAttribute,
162 see https://en.wikipedia.org/wiki/STL_%28file_format%29 for it's meaning }
163 Stream.ReadLE(TriangleAttribute);
164
165 { Add the triangle to Coordinate and Normal arrays now.
166 We could use the same AddTriangle procedure as the LoadSTLText,
167 but it would be less efficient -- it causes a resize when adding each triangle.
168 Here, we know the triangle count beforehand. }
169
170 { if the STL file specifies zero vector, calculate it }
171 if NormalVector.IsPerfectlyZero then
172 NormalVector := Triangle.Normal;
173
174 Coordinate[I * 3 ] := Triangle.Data[0];
175 Coordinate[I * 3 + 1] := Triangle.Data[1];
176 Coordinate[I * 3 + 2] := Triangle.Data[2];
177
178 Normal[I * 3 ] := NormalVector;
179 Normal[I * 3 + 1] := NormalVector;
180 Normal[I * 3 + 2] := NormalVector;
181 end;
182 end;
183
184 { Is STL a text file.
185
186 We used to detect it by looking if it starts with "solid", like:
187
188 Stream.ReadBuffer(Header, 5);
189 if Header = 'solid' then...
190
191 But this fails for some STL files, see
192 https://github.com/castle-engine/castle-engine/issues/433 .
193 We now know follow Blender's approach,
194 https://github.com/blender/blender-addons/blob/main/io_mesh_stl/stl_utils.py#L60 .
195
196 This resets Stream.Position to 0 after read. }
197 function DetectSTLText(const Stream: TStream): Boolean;
198 const
199 { Matches triangle read by LoadSTLBinary. }
200 StlTriangleSize = SizeOf(TVector3) + SizeOf(TTriangle3) + SizeOf(Word);
201 var
202 TriangleCount: UInt32;
203 begin
204 if Stream.Size < BinaryHeader + SizeOf(TriangleCount) then
205 Exit(true);
206
207 Stream.Position := BinaryHeader;
208 Stream.ReadLE(TriangleCount);
209
210 Result := not (
211 Stream.Size = BinaryHeader + SizeOf(TriangleCount) + TriangleCount * StlTriangleSize
212 );
213
214 Stream.Position := 0;
215 end;
216
217 { Load model in the STL format, converting it to an X3D nodes graph.
218 This is used by @link(LoadNode) when the file format is STL. }
219 function LoadSTL(const Stream: TStream; const BaseUrl: String): TX3DRootNode;
220 var
221 Material: TMaterialNode;
222 Appearance: TAppearanceNode;
223 Shape: TShapeNode;
224 TriangleSet: TTriangleSetNode;
225 Coordinate: TCoordinateNode;
226 Normal: TNormalNode;
227 begin
228 Result := TX3DRootNode.Create;
229 try
230 { setup common X3D nodes }
231 Coordinate := TCoordinateNode.Create;
232
233 Normal := TNormalNode.Create;
234
235 { The TriangleSet is perfect for STL geometry, see
236 http://www.web3d.org/documents/specifications/19775-1/V3.3/Part01/components/rendering.html#TriangleSet
237 Just a list of vertexes, each 3 vertexes make a triangle. }
238 TriangleSet := TTriangleSetNode.Create;
239 TriangleSet.Coord := Coordinate;
240 { TODO: NormalPerVertex := true on TriangleSet not supported (would allow
241 to be more compact) }
242 TriangleSet.NormalPerVertex := false;
243 TriangleSet.Normal := Normal;
244
245 { create some Material only to make it lit }
246 Material := TMaterialNode.Create;
247
248 Appearance := TAppearanceNode.Create;
249 Appearance.Material := Material;
250
251 Shape := TShapeNode.Create;
252 Shape.Appearance := Appearance;
253 Shape.Geometry := TriangleSet;
254 Result.AddChildren(Shape);
255
256 { actually read the file, filling Coordinate and Normal nodes }
257 if DetectSTLText(Stream) then
258 LoadSTLText(Stream, Coordinate.FdPoint.Items, Normal.FdVector.Items)
259 else
260 LoadSTLBinary(Stream, Coordinate.FdPoint.Items, Normal.FdVector.Items);
261
262 except FreeAndNil(Result); raise end;
263 end;
264
265 type
266 { Helper class to save STL.
267 Enumerates all triangle and saves them to Stream. }
268 TSaveStlHelper = class
269 Stream: TStream;
270 TriangleCount: UInt32;
271 procedure ProcessTriangle(Shape: TObject;
272 const Triangle: TTriangle3;
273 const Normal: TTriangle3; const TexCoord: TTriangle4;
274 const Face: TFaceIndex);
275 end;
276
277 procedure TSaveStlHelper.ProcessTriangle(Shape: TObject;
278 const Triangle: TTriangle3;
279 const Normal: TTriangle3; const TexCoord: TTriangle4;
280 const Face: TFaceIndex);
281 var
282 N: TVector3;
283 T: TTriangle3;
284 begin
285 Inc(TriangleCount);
286
287 N := Triangle.Normal;
288 NativeToLittleEndian(N);
289 Stream.WriteBuffer(N, SizeOf(N));
290
291 T := Triangle;
292 NativeToLittleEndian(T.Data[0]);
293 NativeToLittleEndian(T.Data[1]);
294 NativeToLittleEndian(T.Data[2]);
295 Stream.WriteBuffer(T, SizeOf(T));
296
297 { According to Wikipedia:
298 https://en.wikipedia.org/wiki/STL_%28file_format%29
299 """
300 2-byte ("short") unsigned integer that is the "attribute byte count" –
301 in the standard format, this should be zero because most software
302 does not understand anything else.
303 """ }
304 Stream.WriteLE(0);
305 end;
306
307 { Save model to STL format.
308 This is used by @link(SaveNode) when the file format is STL. }
309 procedure SaveSTL(const Node: TX3DRootNode; const Stream: TStream;
310 const Generator: String; const Source: String);
311 var
312 HeaderStr: AnsiString;
313 TriangleCount: UInt32;
314 Helper: TSaveStlHelper;
315 Scene: TCastleSceneCore;
316 Shape: TShape;
317 begin
318 HeaderStr := 'Binary STL generated by ' + Generator;
319 // limit to BinaryHeader chars
320 HeaderStr := Copy(HeaderStr, 1, BinaryHeader);
321 // expand to BinaryHeader chars
322 HeaderStr := HeaderStr + StringOfChar(' ', BinaryHeader - Length(HeaderStr));
323 Assert(Length(HeaderStr) = BinaryHeader);
324
325 Stream.WriteBuffer(HeaderStr[1], Length(HeaderStr));
326
327 TriangleCount := 0;
328 Stream.WriteLE(TriangleCount); // we will write this correctly later
329
330 Scene := TCastleSceneCore.Create(nil);
331 try
332 if Node.Scene <> nil then
333 begin
334 { Do DeepCopy, to not change nodes (Scene, associated nodes in shapes...).
335
336 Testcase: in castle-model-viewer,
337 - open water_final_using_noise_from_shaders.x3dv
338 - note that water animates (time sensor is associated with Scene),
339 - save to STL,
340 - should be no crash, and water should animate.
341
342 If we would not do DeepCopy, then above would crash, as FreeAndNil(Scene)
343 would clear time sensor scene. }
344 Scene.Load(Node.DeepCopy as TX3DRootNode, true);
345 end else
346 begin
347 // more efficient: use Node directly, we will unassociate from it later
348 Scene.Load(Node, false);
349 end;
350
351 Helper := TSaveStlHelper.Create;
352 try
353 Helper.Stream := Stream;
354 for Shape in Scene.Shapes.TraverseList(true) do
355 Shape.Triangulate({$ifdef FPC}@{$endif} Helper.ProcessTriangle);
356 TriangleCount := Helper.TriangleCount;
357 finally FreeAndNil(Helper) end;
358 finally FreeAndNil(Scene) end;
359
360 Stream.Position := BinaryHeader;
361 Stream.WriteLE(TriangleCount); // write TriangleCount correctly now
362 end;
363
364 var
365 ModelFormat: TModelFormat;
366 initialization
367 ModelFormat := TModelFormat.Create;
368 ModelFormat.OnLoad := {$ifdef FPC}@{$endif} LoadSTL;
369 ModelFormat.OnLoadForceMemoryStream := true;
370 ModelFormat.OnSave := {$ifdef FPC}@{$endif} SaveSTL;
371 ModelFormat.MimeTypes.Add('application/x-stl');
372 // other STL mime types
373 ModelFormat.MimeTypes.Add('application/wavefront-stl');
374 ModelFormat.MimeTypes.Add('application/vnd.ms-pki.stl');
375 ModelFormat.MimeTypes.Add('application/x-navistyle');
376 ModelFormat.FileFilterName := 'STereo Lithography (*.stl)';
377 ModelFormat.Extensions.Add('.stl');
378 RegisterModelFormat(ModelFormat);
379 end.