Debian Codegraph @

src/scene/castleinternalnormals.pas

raw
1 {
2 Copyright 2003-2023 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 { @abstract(Calculating normal vectors for various 3D objects,
17 with appropriate smoothing.)
18
19 This is developed for VRML/X3D geometric primitives,
20 although some parts are not coupled with VRML/X3D stuff.
21 So it can be used in other situations too. }
22 unit CastleInternalNormals;
23
24 {$I castleconf.inc}
25
26 interface
27
28 uses SysUtils, CastleUtils, CastleVectors, X3DNodes;
29
30 { Calculate normal vectors for indexed faces, smoothing them according
31 to CreaseAngleRad.
32
33 CoordIndex are indexes to Vertices. Indexes < 0 are used to separate
34 faces. So this works just like VRML/X3D IndexedFaceSet.coordIndex.
35
36 It's smart and ignores incorrect indexes (outside Vertices range),
37 and incorrect triangles in the face (see IndexedPolygonNormal).
38
39 Returns a list of normalized vectors. This has the same Count
40 as CoordIndex, and should be accessed in the same way.
41 This way you (may) have different normal vector values for each
42 vertex on each face, so it's most flexible.
43 (For negative indexes in CoordIndex, corresponding value in result
44 is undefined.)
45
46 Remember it's your responsibility to free result of this function
47 at some point.
48
49 @param(FromCcw Specifies whether we should generate normals
50 pointing from CCW (counter-clockwise) or CW.)
51
52 @param(CreaseAngleRad Specifies in radians what is the acceptable
53 angle for smoothing adjacent faces. More precisely, we calculate
54 for each vertex it's neighbor faces normals. Then we divide these
55 faces into groups, such that each group has faces that have normals
56 within CreaseAngleRad range, and this group results in one smoothed
57 normal. For example, it's possible for a vertex shared by 4 faces
58 to be smoothed on first two faces and last two faces separately.
59
60 Note that when creaseAngleRad >= Pi, you wil be better off
61 using CreateSmoothNormals. This will work faster, and return shorter
62 normals array (so it's also more memory-efficient).)
63
64 @param(Convex Set this to @true if you know the faces are convex.
65 This makes calculation faster (but may yield incorrect results
66 for concave polygons).) }
67 function CreateNormals(CoordIndex: TInt32List;
68 Vertices: TVector3List;
69 CreaseAngleRad: Single;
70 const FromCcw, Convex: boolean): TVector3List;
71
72 { Calculate flat per-face normals for indexed faces.
73
74 Note that the result is not a compatible replacement for CreateNormals,
75 as it's Count is the number of @italic(faces). For each face, a single
76 normal is stored, as this is most sensible compact representation.
77 Using something larger would be a waste of memory and time. }
78 function CreateFlatNormals(coordIndex: TInt32List;
79 vertices: TVector3List;
80 const FromCcw, Convex: boolean): TVector3List;
81
82 { Calculate always smooth normals per-vertex, for VRML/X3D coordinate-based
83 node. We use TAbstractGeometryNode.InternalCoordPolygons for this, so the node class
84 must implement it.
85
86 Note that the result is not a compatible replacement for CreateNormals,
87 as this generates Coordinates.Count normal vectors in result.
88 You should access these normal vectors just like Node.Coordinates,
89 i.e. they are indexed by Node.CoordIndex if Node.CoordIndex <> nil.
90
91 If Node.Coordinates is @nil (which means that node is coordinate-based,
92 but "coord" field is not present), we return @nil. }
93 function CreateSmoothNormalsCoordinateNode(
94 Node: TAbstractGeometryNode;
95 State: TX3DGraphTraverseState;
96 const FromCcw: boolean): TVector3List;
97
98 implementation
99
100 uses Generics.Collections,
101 X3DFields, CastleTriangulate;
102
103 type
104 TFace = record
105 StartIndex: Integer;
106 IndicesCount: Integer;
107 Normal: TVector3;
108 end;
109 PFace = ^TFace;
110
111 TFaceList = {$ifdef FPC}specialize{$endif} TStructList<TFace>;
112
113 function CreateNormals(CoordIndex: TInt32List;
114 Vertices: TVector3List;
115 CreaseAngleRad: Single;
116 const FromCcw, Convex: boolean): TVector3List;
117 var
118 Faces: TFaceList;
119 { For each vertex (this array Count is always Vertices.Count),
120 to which faces this vertex belongs? Contains indexes to Faces[] list.
121
122 Although vertex may be more than once on the same face (in case
123 of incorrect data, or some concave faces), a face is mentioned
124 at most once (for given vertex) in this structure. }
125 VerticesFaces: array of TIntegerList;
126 NormalsResult: TVector3List absolute Result;
127 CosCreaseAngle: Single;
128
129 procedure CalculateFacesAndVerticesFaces;
130 var
131 ThisFace: PFace;
132 I, ThisFaceNum: Integer;
133 begin
134 I := 0;
135 while I < CoordIndex.Count do
136 begin
137 ThisFaceNum := Faces.Count;
138 ThisFace := PFace(Faces.Add);
139
140 ThisFace^.StartIndex := I;
141 while (I < CoordIndex.Count) and (CoordIndex[I] >= 0) do
142 begin
143 { Check that CoordIndex[I] is valid (within Vertices.Count range).
144 Note that we cannot remove here wrong indexes from CoordIndex.
145 It's tempting, but:
146 - Removing them is not so easy. We would have to modify also other
147 xxxIndex fields e.g. IndexedFaceSet.texCoordIndex.
148 - Our engine generally preserves VRML/X3D data, never auto-correcting
149 it (it's a decision that makes various things safer). }
150 if (CoordIndex[I] < Vertices.Count) and
151 { Make sure to add only the 1st occurrence of a vertex on this face.
152 Valid concave faces may specify the same vertex multiple times. }
153 (VerticesFaces[CoordIndex[I]].IndexOf(ThisFaceNum) = -1) then
154 VerticesFaces[CoordIndex[I]].Add(ThisFaceNum);
155 Inc(I);
156 end;
157
158 { calculate ThisFace.IndicesCount.
159 We completed one face: indexes StartIndex .. i - 1 }
160 ThisFace^.IndicesCount := i-ThisFace^.StartIndex;
161
162 { calculate ThisFace.Normal }
163 ThisFace^.Normal := IndexedPolygonNormal(
164 PInt32Array(CoordIndex.Ptr(ThisFace^.StartIndex)), ThisFace^.IndicesCount,
165 PVector3Array(Vertices.L), Vertices.Count,
166 Vector3(0, 0, 1), Convex);
167
168 { move to next face (omits the negative index we're standing on) }
169 Inc(I);
170 end;
171 end;
172
173 { For given Face and VertexNum (index to Vertices array),
174 set the normal vector in NormalsResult array.
175 Vertex must be present at least once on a given face.
176 Works OK also in cases when vertex is duplicated (present more than once)
177 on a single face. }
178 procedure SetNormal(VertexNum: integer; const face: TFace; const Normal: TVector3);
179 var
180 I: Integer;
181 Found: boolean;
182 begin
183 Found := false;
184 for I := Face.StartIndex to Face.StartIndex + Face.IndicesCount - 1 do
185 if CoordIndex.L[I] = VertexNum then
186 begin
187 Found := true; { Found := true, but keep looking in case duplicated }
188 NormalsResult.L[I] := Normal;
189 end;
190 Assert(Found, 'CastleInternalNormals.SetNormal failed, vertex not on face');
191 end;
192
193 procedure CalculateVertexNormals(VertexNum: Integer);
194 var
195 { Initialized to VerticesFaces[VertexNum] }
196 ThisVertexFaces: TIntegerList;
197
198 { Can face FaceNum1 be smoothed together with face FaceNum2. }
199 function FaceCanBeSmoothedWith(const FaceNum1, FaceNum2: integer): boolean;
200 begin
201 Result :=
202 { I want to check that
203 AngleRadBetweenNormals(...) < CreaseAngleRad
204 so
205 ArcCos(CosAngleRadBetweenNormals(...)) < CreaseAngleRad
206 so
207 CosAngleBetweenNormals(...) > CosCreaseAngle }
208 CosAngleBetweenNormals(
209 Faces.L[ThisVertexFaces.L[FaceNum1]].Normal,
210 Faces.L[ThisVertexFaces.L[FaceNum2]].Normal) >
211 CosCreaseAngle;
212 end;
213
214 var
215 I, J: Integer;
216 Normal: TVector3;
217 begin
218 ThisVertexFaces := VerticesFaces[VertexNum];
219 for I := 0 to ThisVertexFaces.Count - 1 do
220 begin
221 Normal := Faces.L[ThisVertexFaces[I]].Normal;
222 for J := 0 to ThisVertexFaces.Count - 1 do
223 if (I <> J) and FaceCanBeSmoothedWith(I, J) then
224 Normal := Normal + Faces.L[ThisVertexFaces[J]].Normal;
225 Normal := Normal.Normalize;
226 SetNormal(VertexNum, Faces.L[ThisVertexFaces[I]], Normal);
227 end;
228 end;
229
230 var
231 I: Integer;
232 begin
233 CosCreaseAngle := Cos(CreaseAngleRad);
234
235 SetLength(VerticesFaces, vertices.Count);
236
237 Result := nil;
238 Faces := nil;
239
240 try
241 try
242 for I := 0 to vertices.Count - 1 do
243 VerticesFaces[I] := TIntegerList.Create;
244 Faces := TFaceList.Create;
245
246 { calculate Faces and VerticesFaces contents }
247 CalculateFacesAndVerticesFaces;
248
249 Result := TVector3List.Create;
250 Result.Count := CoordIndex.Count;
251
252 { for each vertex, calculate all his normals (on all his faces) }
253 for I := 0 to Vertices.Count - 1 do CalculateVertexNormals(I);
254
255 if not FromCcw then Result.Negate;
256 finally
257 for I := 0 to Vertices.Count - 1 do VerticesFaces[I].Free;
258 Faces.Free;
259 end;
260 except FreeAndNil(Result); raise end;
261 end;
262
263 function CreateFlatNormals(CoordIndex: TInt32List;
264 Vertices: TVector3List;
265 const FromCcw, Convex: boolean): TVector3List;
266 var
267 I, StartIndex: Integer;
268 FaceNumber: Integer;
269 begin
270 { CoordIndex.Count is just a maximum Count, we will shrink it later. }
271 Result := TVector3List.Create;
272 try
273 Result.Count := CoordIndex.Count;
274 FaceNumber := 0;
275
276 I := 0;
277 while I < CoordIndex.Count do
278 begin
279 StartIndex := I;
280 while (I < CoordIndex.Count) and (CoordIndex.L[I] >= 0) do Inc(I);
281 Result.L[FaceNumber] := IndexedPolygonNormal(
282 PInt32Array(CoordIndex.Ptr(StartIndex)), I - StartIndex,
283 PVector3Array(Vertices.L), Vertices.Count, Vector3(0, 0, 0), Convex);
284 Inc(FaceNumber);
285
286 Inc(I);
287 end;
288
289 Result.Count := FaceNumber;
290
291 if not FromCcw then Result.Negate;
292 except FreeAndNil(Result); raise end;
293 end;
294
295 { CreateSmoothNormalsCoordinateNode ------------------------------------------ }
296
297 type
298 TCoordinateNormalsCalculator = class
299 public
300 Normals: TVector3List;
301 CoordIndex: TInt32List;
302 Coord: TVector3List;
303 Convex: boolean;
304 procedure Polygon(const Indexes: array of Cardinal);
305 end;
306
307 procedure TCoordinateNormalsCalculator.Polygon(
308 const Indexes: array of Cardinal);
309 var
310 FaceNormal: TVector3;
311 { DirectIndexes is Int32, not Cardinal array, since we cannot
312 guarantee that CoordIndex items are >= 0. }
313 DirectIndexes: array of Int32;
314 I: Integer;
315 Index: Int32;
316 begin
317 SetLength(DirectIndexes, Length(Indexes));
318 if CoordIndex <> nil then
319 begin
320 for I := 0 to Length(Indexes) - 1 do
321 DirectIndexes[I] := CoordIndex.L[Indexes[I]];
322 end else
323 begin
324 for I := 0 to Length(Indexes) - 1 do
325 DirectIndexes[I] := Indexes[I];
326 end;
327
328 FaceNormal := IndexedPolygonNormal(
329 PInt32Array(DirectIndexes), Length(DirectIndexes),
330 PVector3Array(Coord.L), Coord.Count, Vector3(0, 0, 0), Convex);
331
332 for I := 0 to Length(Indexes) - 1 do
333 begin
334 Index := DirectIndexes[I];
335 { Normals count is equal to vertexes count.
336 So if Index is incorrect, then we have coordIndex pointing
337 to a non-existing vertex index. VRML/X3D code will warn about it
338 elsewhere, here just make sure we don't crash. }
339 if Index < Normals.Count then
340 Normals.L[Index] := Normals.L[Index] + FaceNormal;
341 end;
342 end;
343
344 function CreateSmoothNormalsCoordinateNode(
345 Node: TAbstractGeometryNode;
346 State: TX3DGraphTraverseState;
347 const FromCcw: boolean): TVector3List;
348 var
349 Calculator: TCoordinateNormalsCalculator;
350 C: TMFVec3f;
351 begin
352 C := Node.InternalCoordinates(State);
353
354 { Node coordinate-based, but specified with empty coord }
355 if C = nil then Exit(nil);
356
357 Result := TVector3List.Create;
358 try
359 Result.Count := C.Count; { TFPSList initialized everything to 0 }
360
361 Calculator := TCoordinateNormalsCalculator.Create;
362 try
363 Calculator.Convex := Node.Convex;
364 Calculator.Coord := C.Items;
365 if Node.CoordIndexField <> nil then
366 Calculator.CoordIndex := Node.CoordIndexField.Items else
367 Calculator.CoordIndex := nil;
368 Calculator.Normals := Result;
369 Node.InternalCoordPolygons(State,
370 {$ifdef FPC}@{$endif}Calculator.Polygon);
371 finally FreeAndNil(Calculator) end;
372
373 Result.Normalize;
374 if not FromCcw then Result.Negate;
375
376 except FreeAndNil(Result); raise end;
377 end;
378
379 end.