Debian Codegraph @

src/scene/castleinternalbatchshapes.pas

raw
1 {
2 Copyright 2019-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 { Batch shapes (combine multiple shapes into one) (TBatchShapes). }
17 unit CastleInternalBatchShapes;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses CastleSceneInternalShape, CastleShapes, X3DNodes, X3DFields, X3DLoad;
24
25 type
26 TBatchShapes = class
27 strict private
28 const
29 { In each TMergePipeline we have a few slots,
30 to account for different values of things that must match for all
31 merged shapes. E.g. Material.EmissiveColor in slot 0 may be white,
32 in slot 1 Material.EmissiveColor may be blue.
33
34 We need more than 1 slot, otherwise dynamic batching could be easily
35 made worthless if one shape would be e.g. blue, and then 100 others would
36 be white.
37
38 But we also cannot have too many slots,
39 or the time spent in "finding the right slot to merge"
40 (FindMergeable in implementation, only for PreserveShapeOrder=false)
41 will grow. }
42 MergeSlots = 8;
43 type
44 { Shapes from different pipelines cannot be merged with each other,
45 and the pool shapes (in FPool) may be prepared differently for each
46 TMergePipeline. }
47 TMergePipeline = (
48 { TIndexedFaceSetNode with TexCoord=nil }
49 mpFacesNoTexCoord,
50 { TIndexedFaceSetNode with TexCoord<>nil }
51 mpFacesTexCoord,
52 { TIndexedTriangleSetNode with TexCoord=nil }
53 mpTrianglesNoTexCoord,
54 { TIndexedTriangleSetNode with TexCoord<>nil }
55 mpTrianglesTexCoord
56 );
57 TMergeSlot = 0 .. MergeSlots - 1;
58 TMergingShapes = array [TMergePipeline, TMergeSlot] of TCollectedShape;
59 const
60 MergePipelinesWithTexCoord = [mpFacesTexCoord, mpTrianglesTexCoord];
61 MergePipelinesWithFaces = [mpFacesNoTexCoord, mpFacesTexCoord];
62 var
63 FBatched: TCollectedShapeList;
64 FPool: TMergingShapes;
65 FPoolUsed: array [TMergePipeline] of Integer;
66
67 { FMergeTarget are copies of the respective shapes on FPool list,
68 when they first become used by Merge (not only allocated by AllocateSlot). }
69 FMergeTarget: TMergingShapes;
70
71 { When PreserveShapeOrder=false, we use this. }
72 FUnorderedPreviousShapes: TMergingShapes;
73
74 { When PreserveShapeOrder=true, we use this. }
75 FOrderPreviousShape: TCollectedShape;
76 FOrderPreviousShapeMerging: Boolean;
77 FOrderPreviousShapePipeline: TMergePipeline;
78
79 FPoolGeometries: TGroupNode;
80 LogIncreaseSlotsDone: Boolean;
81
82 { Add CollectedSource into CollectedTarget.
83 You can assume that CollectedTarget is one of our pool shapes,
84 with initial state and geometry calculated by InitializePool. }
85 procedure Merge(const CollectedTarget, CollectedSource: TCollectedShape;
86 const P: TMergePipeline; const FirstMerge: Boolean);
87
88 { Clear any possible leftovers from Merge, where a given shape was Target. }
89 procedure ClearMerge(const CollectedTarget: TCollectedShape;
90 const P: TMergePipeline);
91
92 { Similar to TAbstractGeometryNode.InternalCoordinates, but for tex coords. }
93 class function TexCoordinates(
94 const Geometry: TAbstractGeometryNode;
95 const State: TX3DGraphTraverseState): TMFVec2f;
96
97 procedure DoLogIncreaseSlots;
98 function GetPoolShapes(const Index: Integer): TGLShape;
99 public
100 var
101 { Make sure that shapes on the @link(Batched) list have the same order
102 in which they have been passed to the @link(Batch) method.
103
104 This makes batching less aggressive (so less effective,
105 less chance of merging),
106 but it makes sure that rendering output will be the same,
107 if the order was important (e.g. you were rendering
108 without Z-buffer test).
109
110 This matters when using blending, in practice.
111 When blending, then TShapesRenderer sorts (using BlendingSort) shapes
112 (original, not batched, shapes) and then passes these shapes in correct
113 order to this class.
114 Batching cannot break this order (as it would make blending
115 incorrect).
116
117 Reset to @false in each @link(FreeBatched). }
118 PreserveShapeOrder: Boolean;
119
120 constructor Create;
121 destructor Destroy; override;
122
123 { Merge given shape into the @link(Batched) shapes.
124 During this, the shape may merge with another shape into a single, larger
125 shape. Returns @true if the shape was added to @link(Batched),
126 otherwise it was not, and should be rendered by the caller immediately
127 without the help of batching. }
128 function Batch(const CollectedShape: TCollectedShape): Boolean;
129
130 procedure Commit;
131
132 { Currently gathered shapes by @link(Batched).
133 Call @link(Commit) before reading this. }
134 property Batched: TCollectedShapeList read FBatched;
135
136 { Release all shapes and clear the @link(Collected) list. }
137 procedure FreeBatched;
138
139 procedure GLContextClose;
140
141 { Enumerate "pool" shapes.
142 This is useful to prepare them (e.g. in TCastleScene.PrepareResources),
143 to make sure further usage of them will be fast. }
144 property PoolShapes[const Index: Integer]: TGLShape read GetPoolShapes;
145 function PoolShapesCount: Integer;
146 end;
147
148 implementation
149
150 uses SysUtils,
151 CastleUtils, CastleLog, CastleVectors, CastleRenderOptions;
152
153 {.$define CASTLE_DEBUG_BATCHING}
154
155 constructor TBatchShapes.Create;
156
157 function MergePipelineToStr(const P: TBatchShapes.TMergePipeline): String;
158 const
159 Names: array [TBatchShapes.TMergePipeline] of String = (
160 'FacesNoTexCoord',
161 'FacesTexCoord',
162 'TrianglesNoTexCoord',
163 'TrianglesTexCoord'
164 );
165 begin
166 Result := Names[P];
167 end;
168
169 function CreateShape(const AGeometry: TAbstractGeometryNode;
170 const AState: TX3DGraphTraverseState; const ParentInfo: PTraversingInfo): TShape;
171 begin
172 Result := TGLShape.Create(nil, AGeometry, AState, ParentInfo);
173 end;
174
175 procedure InitializePool;
176 var
177 ShapeNode: TShapeNode;
178 Geometry: TAbstractComposedGeometryNode;
179 State: TX3DGraphTraverseState;
180 ParentInfo: TTraversingInfo;
181 Shape: TGLShape;
182 P: TMergePipeline;
183 Slot: TMergeSlot;
184 CollectedShape: TCollectedShape;
185 begin
186 for P := Low(TMergePipeline) to High(TMergePipeline) do
187 for Slot := Low(TMergeSlot) to High(TMergeSlot) do
188 begin
189 // initialize Geometry and ShapeNode
190 if P in MergePipelinesWithFaces then
191 Geometry := TIndexedFaceSetNode.CreateWithShape(ShapeNode)
192 else
193 Geometry := TIndexedTriangleSetNode.CreateWithShape(ShapeNode);
194 Geometry.Coord := TCoordinateNode.Create;
195 if P in MergePipelinesWithTexCoord then
196 Geometry.TexCoord := TTextureCoordinateNode.Create;
197 FPoolGeometries.AddChildren(ShapeNode);
198
199 // initialize State
200 State := TX3DGraphTraverseState.Create;
201 State.ShapeNode := ShapeNode;
202
203 // initialize ParentInfo
204 ParentInfo.Node := ShapeNode;
205 ParentInfo.ParentInfo := nil;
206
207 // initialize Shape, add it to FPool
208 Shape := CreateShape(Geometry, State, @ParentInfo) as TGLShape;
209 Shape.DisableSharedCache := true;
210
211 CollectedShape := TCollectedShape.Create;
212 CollectedShape.Shape := Shape;
213 // We will take RenderOptions from merged Shapes
214 CollectedShape.RenderOptions := nil;
215 CollectedShape.SceneTransform := TMatrix4.Identity;
216
217 FPool[P, Slot] := CollectedShape;
218
219 {$ifdef CASTLE_DEBUG_BATCHING}
220 Shape.Node.X3DName := 'Batched_' + MergePipelineToStr(P) + '_' + IntToStr(Slot);
221 {$endif}
222 end;
223 end;
224
225 begin
226 inherited Create;
227 FBatched := TCollectedShapeList.Create(false);
228 FPoolGeometries := TGroupNode.Create;
229 InitializePool;
230 end;
231
232 destructor TBatchShapes.Destroy;
233 var
234 P: TMergePipeline;
235 Slot: TMergeSlot;
236 begin
237 { In case our GLContextClose was not called yet, but we are destroyed,
238 make sure to remove our pool shapes from cache. }
239 GLContextClose;
240
241 FreeAndNil(FBatched);
242 for P := Low(TMergePipeline) to High(TMergePipeline) do
243 for Slot := Low(TMergeSlot) to High(TMergeSlot) do
244 begin
245 if FPool[P, Slot] <> nil then
246 begin
247 FreeAndNil(FPool[P, Slot].Shape);
248 FreeAndNil(FPool[P, Slot]);
249 end;
250 end;
251 FreeAndNil(FPoolGeometries);
252 inherited;
253 end;
254
255 procedure TBatchShapes.DoLogIncreaseSlots;
256 begin
257 if not LogIncreaseSlotsDone then
258 begin
259 LogIncreaseSlotsDone := true;
260 WritelnLog('Consider increasing MergeSlots, to allow more batching');
261 end;
262 end;
263
264 function TBatchShapes.Batch(const CollectedShape: TCollectedShape): Boolean;
265
266 { Is this Shape suitable to consider for merging with @italic(anything).
267 If yes, then we also determine the proper TMergePipeline. }
268 function MergeableWithAnything(const Shape: TGLShape;
269 out P: TMergePipeline): Boolean;
270 var
271 Geometry: TAbstractGeometryNode;
272 TexCoord: TAbstractTextureCoordinateNode;
273 GeometryComposed: TAbstractComposedGeometryNode;
274 Faces: TIndexedFaceSetNode;
275 // Triangles: TIndexedTriangleSetNode; // not needed for now
276 begin
277 Result := false;
278
279 // We can only Merge geometries from VRML 2 / X3D (with TShapeNode set)
280 if Shape.Node = nil then
281 Exit;
282
283 // We can only merge TAbstractComposedGeometryNode for now
284 Geometry := Shape.Geometry;
285 if not (Geometry is TAbstractComposedGeometryNode) then
286 Exit;
287 GeometryComposed := TAbstractComposedGeometryNode(Geometry);
288
289 if {$ifndef CASTLE_SLIM_NODES}
290 (GeometryComposed.FdAttrib.Count <> 0) or
291 (GeometryComposed.FdFogCoord.Value <> nil) or
292 {$endif}
293 (GeometryComposed.FdColor.Value <> nil) or
294 (GeometryComposed.FdNormal.Value <> nil) or
295 ( { If the shape needs automatic texture coordinate generation,
296 batching is not possible, as the tex coordinate generation looks at shape's bounding box.
297 See https://github.com/castle-engine/castle-engine/issues/179 . }
298 (GeometryComposed.FdTexCoord.Value = nil) and
299 (Shape.Node <> nil) and
300 (Shape.Node.Appearance <> nil) and
301 (Shape.Node.Appearance.Texture <> nil) ) then
302 Exit;
303
304 TexCoord := GeometryComposed.TexCoord;
305
306 if GeometryComposed is TIndexedFaceSetNode then
307 begin
308 // conditions specific to TIndexedFaceSetNode
309 Faces := TIndexedFaceSetNode(GeometryComposed);
310 if (Faces.FdTexCoordIndex.Count <> 0) or // for now we don't handle texCoordIndex
311 (Faces.FdColorIndex.Count <> 0) or
312 (Faces.FdNormalIndex.Count <> 0) then
313 Exit;
314
315 if TexCoord = nil then
316 begin
317 P := mpFacesNoTexCoord;
318 Result := true;
319 end else
320 if TexCoord is TTextureCoordinateNode then
321 begin
322 Result := true;
323 P := mpFacesTexCoord;
324 end;
325 end else
326 if GeometryComposed is TIndexedTriangleSetNode then
327 begin
328 // conditions specific to TIndexedTriangleSetNode
329
330 if TexCoord = nil then
331 begin
332 P := mpTrianglesNoTexCoord;
333 Result := true;
334 end else
335 if TexCoord is TTextureCoordinateNode then
336 begin
337 Result := true;
338 P := mpTrianglesTexCoord;
339 end;
340 end;
341 end;
342
343 { Can two given shapes be merged.
344 Assumes that both shapes already passed MergeableWithAnything test,
345 and have the same TMergePipeline. }
346 function Mergeable(const CollectedShape1, CollectedShape2: TCollectedShape;
347 const P: TMergePipeline): Boolean;
348
349 function IndexedFaceSetContentsMatch(const I1, I2: TIndexedFaceSetNode): Boolean;
350 begin
351 Result :=
352 (
353 (I1.FdNormalPerVertex.Value = I2.FdNormalPerVertex.Value) and
354 (I1.FdSolid .Value = I2.FdSolid .Value) and
355 (I1.FdConvex .Value = I2.FdConvex .Value) and
356 (I1.FdCcw .Value = I2.FdCcw .Value) and
357 (I1.FdCreaseAngle .Value = I2.FdCreaseAngle .Value)
358 );
359 end;
360
361 function IndexedTriangleSetContentsMatch(const I1, I2: TIndexedTriangleSetNode): Boolean;
362 begin
363 Result :=
364 (
365 (I1.FdNormalPerVertex.Value = I2.FdNormalPerVertex.Value) and
366 (I1.FdSolid .Value = I2.FdSolid .Value) and
367 (I1.FdCcw .Value = I2.FdCcw .Value)
368 );
369 end;
370
371 function AbstractGeometriesMatch(const G1, G2: TAbstractGeometryNode): Boolean;
372 begin
373 Result :=
374 (G1 = G2) or
375 (
376 (G1 is TIndexedFaceSetNode) and
377 (G2 is TIndexedFaceSetNode) and
378 IndexedFaceSetContentsMatch(TIndexedFaceSetNode(G1), TIndexedFaceSetNode(G2))
379 ) or
380 (
381 (G1 is TIndexedTriangleSetNode) and
382 (G2 is TIndexedTriangleSetNode) and
383 IndexedTriangleSetContentsMatch(TIndexedTriangleSetNode(G1), TIndexedTriangleSetNode(G2))
384 );
385 end;
386
387 function TexturePropertiesContentsMatch(const P1, P2: TTexturePropertiesNode): Boolean;
388 begin
389 Result :=
390 (P1.AnisotropicDegree = P2.AnisotropicDegree) and
391 (P1.BoundaryModeR = P2.BoundaryModeR) and
392 (P1.BoundaryModeS = P2.BoundaryModeS) and
393 (P1.BoundaryModeT = P2.BoundaryModeT) and
394 (P1.MagnificationFilter = P2.MagnificationFilter) and
395 (P1.MinificationFilter = P2.MinificationFilter) and
396 (P1.GenerateMipMaps = P2.GenerateMipMaps) and // unhandled, but soon may be handled
397 (P1.GuiTexture = P2.GuiTexture);
398 end;
399
400 function TexturePropertiesEqual(const P1, P2: TX3DNode): Boolean;
401 begin
402 Result :=
403 (P1 = P2) or
404 (
405 (P1 is TTexturePropertiesNode) and
406 (P2 is TTexturePropertiesNode) and
407 TexturePropertiesContentsMatch(TTexturePropertiesNode(P1), TTexturePropertiesNode(P2))
408 );
409 end;
410
411 function ImageTextureContentsMatch(const Texture1, Texture2: TImageTextureNode): Boolean;
412 begin
413 Result :=
414 Texture1.FdUrl.Equals(Texture2.FdUrl) and
415 (Texture1.FlipVertically = Texture2.FlipVertically) and
416 (Texture1.AlphaChannel = Texture2.AlphaChannel) and
417 (Texture1.RepeatS = Texture2.RepeatS) and
418 (Texture1.RepeatT = Texture2.RepeatT) and
419 Texture1.FdEffects.Equals(Texture2.FdEffects) and
420 TexturePropertiesEqual(Texture1.FdTextureProperties.Value, Texture2.FdTextureProperties.Value);
421 end;
422
423 function TexturesEqual(const Texture1, Texture2: TX3DNode): Boolean;
424 begin
425 Result :=
426 (Texture1 = Texture2) or
427 (
428 (Texture1 is TImageTextureNode) and
429 (Texture2 is TImageTextureNode) and
430 ImageTextureContentsMatch(TImageTextureNode(Texture1), TImageTextureNode(Texture2))
431 );
432 end;
433
434 function MaterialTexturesEqual(const Texture1, Texture2: TX3DNode;
435 const Texture1Mapping, Texture2Mapping: String): Boolean;
436 begin
437 Result :=
438 TexturesEqual(Texture1, Texture2) and
439 (Texture1Mapping = Texture2Mapping);
440 end;
441
442 { Checks contents of M1 and M2,
443 assuming that they are both <> nil and different references
444 (so there's no point in checking their references). }
445 function PhongMaterialsContentsMatch(const M1, M2: TMaterialNode): Boolean;
446 begin
447 Result :=
448 (
449 TVector3.PerfectlyEquals(M1.FdDiffuseColor .Value, M2.FdDiffuseColor .Value) and
450 TVector3.PerfectlyEquals(M1.FdSpecularColor .Value, M2.FdSpecularColor .Value) and
451 TVector3.PerfectlyEquals(M1.FdEmissiveColor .Value, M2.FdEmissiveColor .Value) and
452 (M1.FdAmbientIntensity.Value = M2.FdAmbientIntensity.Value) and
453 (M1.FdTransparency .Value = M2.FdTransparency .Value) and
454
455 MaterialTexturesEqual(M1.FdNormalTexture .Value, M2.FdNormalTexture .Value, M1.FdNormalTextureMapping .Value, M2.FdNormalTextureMapping .Value) and
456 MaterialTexturesEqual(M1.FdDiffuseTexture .Value, M2.FdDiffuseTexture .Value, M1.FdDiffuseTextureMapping .Value, M2.FdDiffuseTextureMapping .Value) and
457 MaterialTexturesEqual(M1.FdSpecularTexture .Value, M2.FdSpecularTexture .Value, M1.FdSpecularTextureMapping .Value, M2.FdSpecularTextureMapping .Value) and
458 MaterialTexturesEqual(M1.FdEmissiveTexture .Value, M2.FdEmissiveTexture .Value, M1.FdEmissiveTextureMapping .Value, M2.FdEmissiveTextureMapping .Value) and
459 MaterialTexturesEqual(M1.FdAmbientTexture .Value, M2.FdAmbientTexture .Value, M1.FdAmbientTextureMapping .Value, M2.FdAmbientTextureMapping .Value) and
460 MaterialTexturesEqual(M1.FdOcclusionTexture.Value, M2.FdOcclusionTexture.Value, M1.FdOcclusionTextureMapping.Value, M2.FdOcclusionTextureMapping.Value)
461 );
462 end;
463
464 function UnlitMaterialsContentsMatch(const M1, M2: TUnlitMaterialNode): Boolean;
465 begin
466 Result :=
467 (
468 TVector3.PerfectlyEquals(M1.FdEmissiveColor .Value, M2.FdEmissiveColor .Value) and
469 (M1.FdTransparency .Value = M2.FdTransparency .Value) and
470
471 // ignored: MaterialTexturesEqual(M1.FdNormalTexture .Value, M2.FdNormalTexture .Value, M1.FdNormalTextureMapping .Value, M2.FdNormalTextureMapping .Value) and
472 MaterialTexturesEqual(M1.FdEmissiveTexture.Value, M2.FdEmissiveTexture.Value, M1.FdEmissiveTextureMapping.Value, M2.FdEmissiveTextureMapping.Value)
473 );
474 end;
475
476 function PhysicalMaterialsContentsMatch(const M1, M2: TPhysicalMaterialNode): Boolean;
477 begin
478 Result :=
479 (
480 TVector3.PerfectlyEquals(M1.FdEmissiveColor .Value, M2.FdEmissiveColor .Value) and
481 TVector3.PerfectlyEquals(M1.FdBaseColor .Value, M2.FdBaseColor .Value) and
482 (M1.FdMetallic .Value = M2.FdMetallic .Value) and
483 (M1.FdRoughness .Value = M2.FdRoughness .Value) and
484 (M1.FdTransparency.Value = M2.FdTransparency.Value) and
485
486 MaterialTexturesEqual(M1.FdNormalTexture .Value, M2.FdNormalTexture .Value, M1.FdNormalTextureMapping .Value, M2.FdNormalTextureMapping .Value) and
487 MaterialTexturesEqual(M1.FdEmissiveTexture .Value, M2.FdEmissiveTexture .Value, M1.FdEmissiveTextureMapping .Value, M2.FdEmissiveTextureMapping .Value) and
488 MaterialTexturesEqual(M1.FdBaseTexture .Value, M2.FdBaseTexture .Value, M1.FdBaseTextureMapping .Value, M2.FdBaseTextureMapping .Value) and
489 MaterialTexturesEqual(M1.FdMetallicRoughnessTexture.Value, M2.FdMetallicRoughnessTexture.Value, M1.FdMetallicRoughnessTextureMapping.Value, M2.FdMetallicRoughnessTextureMapping.Value) and
490 MaterialTexturesEqual(M1.FdOcclusionTexture .Value, M2.FdOcclusionTexture .Value, M1.FdOcclusionTextureMapping .Value, M2.FdOcclusionTextureMapping .Value)
491 );
492 end;
493
494 function AbstractMaterialsMatch(const M1, M2: TAbstractMaterialNode): Boolean;
495 begin
496 Result :=
497 (M1 = M2) or
498 (
499 (M1 is TMaterialNode) and
500 (M2 is TMaterialNode) and
501 PhongMaterialsContentsMatch(TMaterialNode(M1), TMaterialNode(M2))
502 ) or
503 (
504 (M1 is TUnlitMaterialNode) and
505 (M2 is TUnlitMaterialNode) and
506 UnlitMaterialsContentsMatch(TUnlitMaterialNode(M1), TUnlitMaterialNode(M2))
507 ) or
508 (
509 (M1 is TPhysicalMaterialNode) and
510 (M2 is TPhysicalMaterialNode) and
511 PhysicalMaterialsContentsMatch(TPhysicalMaterialNode(M1), TPhysicalMaterialNode(M2))
512 );
513 end;
514
515 function AppearancesMatch(const A1, A2: TAppearanceNode): Boolean;
516 begin
517 Result :=
518 (A1 = A2) or
519 (
520 (A1 <> nil) and
521 (A2 <> nil) and
522 TexturesEqual(A1.FdTexture.Value, A2.FdTexture.Value) and
523 (A1.FdTextureTransform.Value = A2.FdTextureTransform.Value) and
524 AbstractMaterialsMatch(A1.Material, A2.Material)
525 );
526 end;
527
528 function LightsMatch(const Lights1, Lights2: TLightInstancesList): Boolean;
529 begin
530 Result :=
531 (Lights1 = Lights2) or
532 (
533 (Lights1 <> nil) and
534 (Lights2 <> nil) and
535 Lights1.Equals(Lights2)
536 );
537 end;
538
539 var
540 Shape1, Shape2: TGLShape;
541 Geometry1, Geometry2: TAbstractGeometryNode;
542 State1, State2: TX3DGraphTraverseState;
543 begin
544 Shape1 := CollectedShape1.Shape;
545 Shape2 := CollectedShape2.Shape;
546 Geometry1 := Shape1.Geometry;
547 Geometry2 := Shape2.Geometry;
548 State1 := Shape1.State;
549 State2 := Shape2.State;
550 Result :=
551 { Checks begin from the ones most likely to be different (exit early).
552 Note that everything compared here must be also assigned in Merge
553 (when FirstMerge), to make sure all merged instances keep the same values
554 for this stuff. }
555 AppearancesMatch(Shape1.Node.Appearance, Shape2.Node.Appearance) and
556 AbstractGeometriesMatch(Geometry1, Geometry2) and
557 (State1.LocalFog = State2.LocalFog) and
558 (Shape1.Node.Shading = Shape2.Node.Shading) and
559 LightsMatch(State1.Lights, State2.Lights) and
560 (State1.ClipPlanes = State2.ClipPlanes) and
561 (State1.Effects = State2.Effects) and
562 (CollectedShape1.RenderOptions.Equals(CollectedShape2.RenderOptions)) and
563 (CollectedShape1.DepthRange = CollectedShape2.DepthRange);
564 end;
565
566 { Find a slot in Shapes[P] which is non-nil and can be merged with Shape.
567 Assumes that for Shape, we already determined given TMergePipeline. }
568 function FindMergeable(const Shapes: TMergingShapes;
569 const P: TMergePipeline; const CollectedShape: TCollectedShape;
570 out MergeSlot: TMergeSlot): Boolean;
571 var
572 MS: TMergeSlot;
573 begin
574 for MS := Low(TMergeSlot) to High(TMergeSlot) do
575 begin
576 if Shapes[P, MS] <> nil then
577 if Mergeable(CollectedShape, Shapes[P, MS], P) then
578 begin
579 MergeSlot := MS;
580 Exit(true);
581 end;
582 end;
583 Result := false;
584 end;
585
586 { First merge of two shapes.
587 Sets FMergeTarget[P, Slot] (using FPool[P, Slot]),
588 adds it to FBatched,
589 places there merge of Shape1 and Shape2.
590
591 Called must first check that FPool[P, Slot] was not used for anything
592 (e.g. by checking that FMergeTarget[P, Slot] is nil). }
593 procedure InitialMerge(
594 const CollectedShape1, CollectedShape2: TCollectedShape;
595 const P: TMergePipeline; const Slot: TMergeSlot);
596 begin
597 {$ifdef CASTLE_DEBUG_BATCHING}
598 if FMergeTarget[P, Slot] <> nil then
599 WritelnWarning('Batching: merging to already used slot');
600 {$endif}
601 FMergeTarget[P, Slot] := FPool[P, Slot];
602 FBatched.Add(FMergeTarget[P, Slot]);
603 ClearMerge(FMergeTarget[P, Slot], P);
604 Merge(FMergeTarget[P, Slot], CollectedShape1, P, true);
605 Merge(FMergeTarget[P, Slot], CollectedShape2, P, false);
606 end;
607
608 function AllocateSlot(const P: TMergePipeline; out Slot: TMergeSlot): Boolean;
609 begin
610 Result := FPoolUsed[P] < MergeSlots;
611 if Result then
612 begin
613 Slot := FPoolUsed[P];
614 Inc(FPoolUsed[P]);
615 end;
616 end;
617
618 var
619 Shape: TGLShape; //< Shortcut for CollectedShape.Shape
620
621 { Algorithm specific for PreserveShapeOrder=true case. }
622 procedure DoPreserveShapeOrder;
623 var
624 P: TMergePipeline;
625 Handled: Boolean;
626 Slot: TMergeSlot;
627 begin
628 Handled := false;
629
630 { When PreserveShapeOrder, the algorithm is simpler:
631 We try to merge an incoming shape with the previous shape
632 (taking into account that a previous shape may be already a result
633 of merging, depending on FOrderPreviousShapeMerging).
634 If this is not possible, we just push previous shape to FBatched. }
635
636 { In case of DoPreserveShapeOrder, Batch must *always* return true,
637 even for non-mergeable shapes. }
638 Result := true;
639
640 if not MergeableWithAnything(Shape, P) then
641 begin
642 { The non-mergeable shapes have to be added
643 to FBatched, to make sure they are in correct order between mergeable.
644 Testcase: merging scene with indicator (IndexedFaceSet, Text and Rectangle2D) in Unholy. }
645 // finish merging previous shape
646 if (FOrderPreviousShape <> nil) and
647 (not FOrderPreviousShapeMerging) then
648 FBatched.Add(FOrderPreviousShape);
649 FBatched.Add(CollectedShape);
650 FOrderPreviousShape := nil;
651 FOrderPreviousShapeMerging := false;
652 Handled := true;
653 end else
654 if (FOrderPreviousShape <> nil) and
655 (FOrderPreviousShapePipeline = P) and
656 Mergeable(FOrderPreviousShape, CollectedShape, P) then
657 begin
658 if FOrderPreviousShapeMerging then
659 begin
660 Merge(FOrderPreviousShape, CollectedShape, P, false);
661 Handled := true;
662 end else
663 if AllocateSlot(P, Slot) then
664 begin
665 InitialMerge(FOrderPreviousShape, CollectedShape, P, Slot);
666 FOrderPreviousShape := FMergeTarget[P, Slot];
667 FOrderPreviousShapeMerging := true;
668 Handled := true;
669 end else
670 DoLogIncreaseSlots;
671 end;
672
673 if not Handled then
674 begin
675 // finish merging previous shape, and add new shape as FOrderPreviousShape
676 if (FOrderPreviousShape <> nil) and
677 (not FOrderPreviousShapeMerging) then
678 FBatched.Add(FOrderPreviousShape);
679 FOrderPreviousShape := CollectedShape;
680 FOrderPreviousShapePipeline := P;
681 FOrderPreviousShapeMerging := false;
682 end;
683 end;
684
685 { Algorithm specific for PreserveShapeOrder=false case. }
686 procedure DoIgnoreShapeOrder;
687 var
688 P: TMergePipeline;
689 Slot: TMergeSlot;
690 begin
691 Result := MergeableWithAnything(Shape, P);
692 if not Result then
693 Exit;
694
695 { When not PreserveShapeOrder, we try to merge an incoming shape with
696 - one of the merges "in progress" (on FUnorderedPreviousShapes and FMergeTarget)
697 - or one of the previous shapes, not yet during merging (only on FUnorderedPreviousShapes)
698 - or we place it in a new slot, waiting for possible merge in the future. }
699
700 if FindMergeable(FUnorderedPreviousShapes, P, CollectedShape, Slot) then
701 begin
702 if FMergeTarget[P, Slot] <> nil then
703 begin
704 { Slot in the middle of merging, so merge more. }
705 Merge(FMergeTarget[P, Slot], CollectedShape, P, false);
706 end else
707 begin
708 { Slot not yet merging, so start merging.
709 This will set FMergeTarget[P, Slot], so next shapes will know we are in the middle
710 of merging. }
711 InitialMerge(FUnorderedPreviousShapes[P, Slot], CollectedShape, P, Slot);
712 Assert(FMergeTarget[P, Slot] <> nil);
713 FUnorderedPreviousShapes[P, Slot] := FMergeTarget[P, Slot];
714 end;
715 end else
716 if AllocateSlot(P, Slot) then
717 begin
718 { Add shape to FUnorderedPreviousShapes.
719 The corresponding FMergeTarget remains nil, so we know it is not yet in the middle of merging.
720
721 Note that this reserves a slot, IOW we treat FPool[P, Slot] as already used.
722 It may be wasteful (as we didn't start merging yet, we are not yet sure
723 whether FPool[P, Slot] will be needed) but we need to reserve this pool for possible
724 merging opportunity.
725
726 TODO: Maybe the logic could be improved, to not reserve pool yet?
727 Then our queue "waiting to be possibly merged" would not assign slots
728 (corresponding to FPool and FMergeTarget slots).
729 The advantage would be that we don't need so many MergeSlots
730 in case of PreserveShapeOrder=false to be efficient, in some cases.
731 }
732 FUnorderedPreviousShapes[P, Slot] := CollectedShape;
733 end else
734 begin
735 DoLogIncreaseSlots;
736 Result := false; // we would like to batch it, but MergeSlots is not enough
737 end;
738 end;
739
740 begin
741 Shape := CollectedShape.Shape;
742 if PreserveShapeOrder then
743 DoPreserveShapeOrder
744 else
745 DoIgnoreShapeOrder;
746 end;
747
748 procedure TBatchShapes.FreeBatched;
749 var
750 P: TMergePipeline;
751 Slot: TMergeSlot;
752 begin
753 FBatched.Clear;
754 for P := Low(TMergePipeline) to High(TMergePipeline) do
755 begin
756 for Slot := Low(TMergeSlot) to High(TMergeSlot) do
757 if FMergeTarget[P, Slot] <> nil then
758 begin
759 // all shapes from batching pool should have Shape assigned
760 Assert(FMergeTarget[P, Slot].Shape <> nil);
761
762 // don't wait for ClearMerge for this, do this earlier to release reference count
763 FMergeTarget[P, Slot].Shape.Node.FdAppearance.Value := nil;
764 // make sure this is unassigned, otherwise TX3DGraphTraverseState.Destroy would free it
765 FMergeTarget[P, Slot].Shape.State.Lights := nil;
766 FMergeTarget[P, Slot] := nil;
767 end;
768 FPoolUsed[P] := 0;
769 end;
770 PreserveShapeOrder := false;
771 end;
772
773 procedure TBatchShapes.Commit;
774
775 procedure DebugOutput;
776 var
777 CollectedShape: TCollectedShape;
778 Shape: TGLShape;
779 RootNode: TX3DRootNode;
780 Geometry: TAbstractGeometryNode;
781 begin
782 RootNode := TX3DRootNode.Create;
783 for CollectedShape in FBatched do
784 begin
785 Shape := CollectedShape.Shape;
786 Geometry := Shape.OriginalGeometry;
787 WritelnLog('Collected shape: %s, geometry: %s, bbox: %s', [
788 Shape.Node.X3DName,
789 Geometry.NiceName,
790 Shape.BoundingBox.ToString
791 ]);
792 Shape.Node.KeepExistingBegin;
793 RootNode.AddChildren(Shape.Node);
794 end;
795
796 if RootNode.FdChildren.Count <> 0 then
797 SaveNode(RootNode, 'cge_batching_output.x3d', ApplicationName);
798
799 for CollectedShape in FBatched do
800 begin
801 Shape := CollectedShape.Shape;
802 Shape.Node.KeepExistingEnd;
803 end;
804
805 FreeAndNil(RootNode);
806 end;
807
808 var
809 P: TMergePipeline;
810 Slot: TMergeSlot;
811 begin
812 for P := Low(TMergePipeline) to High(TMergePipeline) do
813 for Slot := Low(TMergeSlot) to High(TMergeSlot) do
814 begin
815 if FUnorderedPreviousShapes[P, Slot] <> nil then
816 begin
817 if FMergeTarget[P, Slot] = nil then
818 FBatched.Add(FUnorderedPreviousShapes[P, Slot]);
819 FUnorderedPreviousShapes[P, Slot] := nil;
820 end;
821 if FMergeTarget[P, Slot] <> nil then
822 begin
823 // all shapes from batching pool should have Shape assigned
824 Assert(FMergeTarget[P, Slot].Shape <> nil);
825
826 FMergeTarget[P, Slot].Shape.Changed(false, [
827 { Mark changes from
828 - TIndexedFaceSetNode.FdCoordIndex, TIndexedTriangleSetNode.FdIndex
829 - TCoordinateNode.FdPoint
830 - TTextureCoordinateNode.FdPoint
831 }
832 chCoordinate, chTextureCoordinate, chGeometry
833 ]);
834 end;
835 end;
836
837 if FOrderPreviousShape <> nil then
838 begin
839 if not FOrderPreviousShapeMerging then
840 FBatched.Add(FOrderPreviousShape);
841 FOrderPreviousShape := nil;
842 end;
843
844 {$ifdef CASTLE_DEBUG_BATCHING}
845 DebugOutput;
846 {$endif}
847 end;
848
849 procedure TBatchShapes.GLContextClose;
850 var
851 P: TMergePipeline;
852 Slot: TMergeSlot;
853 begin
854 for P := Low(TMergePipeline) to High(TMergePipeline) do
855 for Slot := Low(TMergeSlot) to High(TMergeSlot) do
856 FPool[P, Slot].Shape.GLContextClose;
857 end;
858
859 procedure TBatchShapes.Merge(
860 const CollectedTarget, CollectedSource: TCollectedShape;
861 const P: TMergePipeline; const FirstMerge: Boolean);
862 var
863 Target, Source: TGLShape;
864 StateTarget, StateSource: TX3DGraphTraverseState;
865 MeshTarget, MeshSource: TAbstractComposedGeometryNode;
866 CoordTarget, CoordSource: TMFVec3f;
867 TexCoordTarget, TexCoordSource: TMFVec2f;
868 IndexTarget, IndexSource: TInt32List;
869 OldCoordCount, I: Integer;
870 begin
871 Target := CollectedTarget.Shape;
872 Source := CollectedSource.Shape;
873 StateTarget := Target.State;
874 StateSource := Source.State;
875 MeshTarget := Target.Geometry as TAbstractComposedGeometryNode;
876 MeshSource := Source.Geometry as TAbstractComposedGeometryNode;
877
878 // no vertexes in source mesh, ignore it
879 if MeshSource.Coord = nil then
880 Exit;
881
882 if FirstMerge then
883 begin
884 // assign things that should be equal when merging
885 Assert(Source.Node <> nil); // only such source nodes are passed to Merge
886 Target.Node.FdShading.Value := Source.Node.FdShading.Value;
887 StateTarget.Lights := StateSource.Lights;
888 StateTarget.LocalFog := StateSource.LocalFog;
889 // using here FdAppearance.Value is marginally faster than Appearance, it matters a bit
890 Target.Node.FdAppearance.Value := Source.Node.Appearance;
891 MeshTarget.FdNormalPerVertex.Value := MeshSource.FdNormalPerVertex.Value;
892 MeshTarget.FdSolid .Value := MeshSource.FdSolid .Value;
893 if MeshTarget is TIndexedFaceSetNode then
894 begin
895 TIndexedFaceSetNode(MeshTarget).FdConvex .Value := TIndexedFaceSetNode(MeshSource).FdConvex .Value;
896 TIndexedFaceSetNode(MeshTarget).FdCreaseAngle .Value := TIndexedFaceSetNode(MeshSource).FdCreaseAngle .Value;
897 end;
898
899 CollectedTarget.DepthRange := CollectedSource.DepthRange;
900
901 { Assign RenderOptions. }
902 CollectedTarget.RenderOptions := CollectedSource.RenderOptions;
903 Target.OverrideRenderOptions := CollectedSource.RenderOptions;
904 end;
905
906 { Shapes to which we merge should have SceneTransform = identity always. }
907 Assert(TMatrix4.PerfectlyEquals(CollectedTarget.SceneTransform, TMatrix4.Identity));
908
909 CoordTarget := MeshTarget.InternalCoordinates(StateTarget);
910 CoordSource := MeshSource.InternalCoordinates(StateSource);
911 OldCoordCount := CoordTarget.Count;
912 CoordTarget.Items.AddRangeTransformed(CoordSource.Items,
913 CollectedSource.SceneTransform *
914 StateSource.Transformation.Transform);
915
916 if P in MergePipelinesWithTexCoord then
917 begin
918 TexCoordTarget := TexCoordinates(MeshTarget, StateTarget);
919 TexCoordSource := TexCoordinates(MeshSource, StateSource);
920 TexCoordTarget.Items.AddRange(TexCoordSource.Items);
921 Check(CoordTarget.Count = TexCoordTarget.Count); // TODO: secure from it
922 end;
923
924 IndexTarget := MeshTarget.CoordIndexField.Items;
925 IndexSource := MeshSource.CoordIndexField.Items;
926 if (P in MergePipelinesWithFaces) and
927 (IndexTarget.Count <> 0) and
928 (IndexTarget.Last >= 0) then
929 IndexTarget.Add(-1); // separate from next polygons
930 for I := 0 to IndexSource.Count - 1 do
931 begin
932 if IndexSource[I] >= 0 then
933 IndexTarget.Add(IndexSource[I] + OldCoordCount)
934 else
935 IndexTarget.Add(IndexSource[I]); // don't modify source negative indexes
936 end;
937 end;
938
939 procedure TBatchShapes.ClearMerge(const CollectedTarget: TCollectedShape;
940 const P: TMergePipeline);
941 var
942 Target: TGLShape;
943 StateTarget: TX3DGraphTraverseState;
944 MeshTarget: TAbstractComposedGeometryNode;
945 CoordTarget: TMFVec3f;
946 TexCoordTarget: TMFVec2f;
947 IndexTarget: TInt32List;
948 begin
949 { Shapes to which we merge should have SceneTransform = identity always. }
950 Assert(TMatrix4.PerfectlyEquals(CollectedTarget.SceneTransform, TMatrix4.Identity));
951
952 Target := CollectedTarget.Shape;
953
954 { Clearing this is not really needed now, Merge always overrides it.
955 But better clear it to be safe, instead of having potentially dangling pointer. }
956 Target.OverrideRenderOptions := nil;
957 CollectedTarget.RenderOptions := nil;
958
959 StateTarget := Target.State;
960 MeshTarget := Target.Geometry as TAbstractComposedGeometryNode;
961 CoordTarget := MeshTarget.InternalCoordinates(StateTarget);
962 CoordTarget.Items.Clear;
963 IndexTarget := MeshTarget.CoordIndexField.Items;
964 IndexTarget.Clear;
965 if P in MergePipelinesWithTexCoord then
966 begin
967 TexCoordTarget := TexCoordinates(MeshTarget, StateTarget);
968 TexCoordTarget.Items.Clear;
969 end;
970 end;
971
972 class function TBatchShapes.TexCoordinates(
973 const Geometry: TAbstractGeometryNode;
974 const State: TX3DGraphTraverseState): TMFVec2f;
975 var
976 TexCoordNode: TX3DNode;
977 begin
978 if Geometry.InternalTexCoord(State, TexCoordNode) and
979 (TexCoordNode is TTextureCoordinateNode) then
980 begin
981 Result := TTextureCoordinateNode(TexCoordNode).FdPoint;
982 end else
983 raise Exception.CreateFmt('Node %s does not have texture coordinates',
984 [Geometry.NiceName]);
985 end;
986
987 function TBatchShapes.GetPoolShapes(const Index: Integer): TGLShape;
988 var
989 PipelinesCount: Integer;
990 begin
991 PipelinesCount := Ord(High(TMergePipeline)) + 1;
992 Assert(Index div MergeSlots < PipelinesCount);
993 Result := FPool[TMergePipeline(Index div MergeSlots), Index mod MergeSlots].Shape;
994 end;
995
996 function TBatchShapes.PoolShapesCount: Integer;
997 var
998 PipelinesCount: Integer;
999 begin
1000 PipelinesCount := Ord(High(TMergePipeline)) + 1;
1001 Result := MergeSlots * PipelinesCount;
1002 end;
1003
1004 end.