e35c45107ac3fe31d29db75eff7308a03576477b
[sixth-3d.git] /
1 /*
2  * Sixth 3D engine. Author: Svjatoslav Agejenko.
3  * This project is released under Creative Commons Zero (CC0) license.
4  */
5 package eu.svjatoslav.sixth.e3d.renderer.raster.shapes.composite.base;
6
7 import eu.svjatoslav.sixth.e3d.geometry.Point3D;
8 import eu.svjatoslav.sixth.e3d.gui.RenderingContext;
9 import eu.svjatoslav.sixth.e3d.gui.ViewSpaceTracker;
10 import eu.svjatoslav.sixth.e3d.gui.humaninput.MouseInteractionController;
11 import eu.svjatoslav.sixth.e3d.math.Transform;
12 import eu.svjatoslav.sixth.e3d.math.TransformStack;
13 import eu.svjatoslav.sixth.e3d.renderer.raster.Color;
14 import eu.svjatoslav.sixth.e3d.renderer.raster.RenderAggregator;
15 import eu.svjatoslav.sixth.e3d.renderer.raster.lighting.LightingManager;
16 import eu.svjatoslav.sixth.e3d.renderer.raster.shapes.AbstractShape;
17 import eu.svjatoslav.sixth.e3d.renderer.raster.shapes.basic.line.Line;
18 import eu.svjatoslav.sixth.e3d.renderer.raster.shapes.basic.solidpolygon.SolidPolygon;
19 import eu.svjatoslav.sixth.e3d.renderer.raster.shapes.basic.texturedpolygon.TexturedPolygon;
20 import eu.svjatoslav.sixth.e3d.renderer.raster.slicer.Slicer;
21
22 import java.util.ArrayList;
23 import java.util.List;
24
25 /**
26  * A composite shape that groups multiple sub-shapes into a single logical unit.
27  *
28  * <p>Use {@code AbstractCompositeShape} to build complex 3D objects by combining
29  * primitive shapes (lines, polygons, textured polygons) into a group that can be
30  * positioned, rotated, and manipulated as one entity. Sub-shapes can be organized
31  * into named groups for selective visibility toggling.</p>
32  *
33  * <p><b>Usage example - creating a custom composite shape:</b></p>
34  * <pre>{@code
35  * // Create a composite shape at position (0, 0, 200)
36  * AbstractCompositeShape myObject = new AbstractCompositeShape(
37  *     new Point3D(0, 0, 200)
38  * );
39  *
40  * // Add sub-shapes
41  * myObject.addShape(new Line(
42  *     new Point3D(-50, 0, 0), new Point3D(50, 0, 0),
43  *     Color.RED, 2.0
44  * ));
45  *
46  * // Add shapes to a named group for toggling visibility
47  * myObject.addShape(labelShape, "labels");
48  * myObject.hideGroup("labels");  // hide all shapes in "labels" group
49  * myObject.showGroup("labels");  // show them again
50  *
51  * // Add to scene
52  * viewPanel.getRootShapeCollection().addShape(myObject);
53  * }</pre>
54  *
55  * <p><b>Level-of-detail slicing:</b></p>
56  * <p>Textured polygons within the composite shape are automatically sliced into smaller
57  * triangles based on distance from the viewer. This provides perspective-correct texture
58  * mapping without requiring hardware support. The slicing factor adapts dynamically.</p>
59  *
60  * <p><b>Extending this class:</b></p>
61  * <p>Override {@link #beforeTransformHook} to customize shape appearance or behavior
62  * on each frame (e.g., animations, dynamic geometry updates).</p>
63  *
64  * @see SubShape wrapper for individual sub-shapes with group and visibility support
65  * @see eu.svjatoslav.sixth.e3d.renderer.raster.shapes.AbstractShape the base shape class
66  * @see eu.svjatoslav.sixth.e3d.renderer.raster.slicer.Slicer the level-of-detail polygon slicer
67  */
68 public class AbstractCompositeShape extends AbstractShape {
69     private final List<SubShape> originalSubShapes = new ArrayList<>();
70     private final ViewSpaceTracker viewSpaceTracker;
71     double currentSliceFactor = 5;
72     private List<AbstractShape> renderedSubShapes = new ArrayList<>();
73     private boolean slicingOutdated = true;
74     private Transform transform;
75     private LightingManager lightingManager;
76
77     /**
78      * Creates a composite shape at the world origin with no rotation.
79      */
80     public AbstractCompositeShape() {
81         this(new Transform());
82     }
83
84     /**
85      * Creates a composite shape at the specified location with no rotation.
86      *
87      * @param location the position in world space
88      */
89     public AbstractCompositeShape(final Point3D location) {
90         this(new Transform(location));
91     }
92
93     /**
94      * Creates a composite shape with the specified transform (position and orientation).
95      *
96      * @param transform the initial transform defining position and rotation
97      */
98     public AbstractCompositeShape(final Transform transform) {
99         this.transform = transform;
100         viewSpaceTracker = new ViewSpaceTracker();
101     }
102
103     /**
104      * Adds a sub-shape to this composite shape without a group identifier.
105      *
106      * @param shape the shape to add
107      */
108     public void addShape(final AbstractShape shape) {
109         addShape(shape, null);
110     }
111
112     /**
113      * Adds a sub-shape to this composite shape with an optional group identifier.
114      *
115      * <p>Grouped shapes can be shown, hidden, or removed together using
116      * {@link #showGroup}, {@link #hideGroup}, and {@link #removeGroup}.</p>
117      *
118      * @param shape   the shape to add
119      * @param groupId the group identifier, or {@code null} for ungrouped shapes
120      */
121     public void addShape(final AbstractShape shape, final String groupId) {
122         final SubShape subShape = new SubShape(shape);
123         subShape.setGroup(groupId);
124         subShape.setVisible(true);
125         originalSubShapes.add(subShape);
126         slicingOutdated = true;
127     }
128
129     /**
130      * This method should be overridden by anyone wanting to customize shape
131      * before it is rendered.
132      */
133     public void beforeTransformHook(final TransformStack transformPipe,
134                                     final RenderingContext context) {
135     }
136
137     /**
138      * Returns the world-space position of this composite shape.
139      *
140      * @return the translation component of this shape's transform
141      */
142     public Point3D getLocation() {
143         return transform.getTranslation();
144     }
145
146     /**
147      * Returns the list of all sub-shapes (including hidden ones).
148      *
149      * @return the internal list of sub-shapes
150      */
151     public List<SubShape> getOriginalSubShapes() {
152         return originalSubShapes;
153     }
154
155     /**
156      * Returns the view-space tracker that monitors the distance
157      * and angle between the camera and this shape for level-of-detail adjustments.
158      *
159      * @return the view-space tracker for this shape
160      */
161     public ViewSpaceTracker getViewSpaceTracker() {
162         return viewSpaceTracker;
163     }
164
165     /**
166      * Hides all sub-shapes belonging to the specified group.
167      * Hidden shapes are not rendered but remain in the collection.
168      *
169      * @param groupIdentifier the group to hide
170      * @see #showGroup(String)
171      * @see #removeGroup(String)
172      */
173     public void hideGroup(final String groupIdentifier) {
174         for (int i = 0; i < originalSubShapes.size(); i++) {
175             final SubShape subShape = originalSubShapes.get(i);
176             if (subShape.matchesGroup(groupIdentifier)) {
177                 subShape.setVisible(false);
178                 slicingOutdated = true;
179             }
180         }
181     }
182
183     private boolean isReslicingNeeded(double proposedNewSliceFactor, double currentSliceFactor) {
184
185         if (slicingOutdated)
186             return true;
187
188         // reslice if there is significant difference between proposed and current slice factor
189         if (proposedNewSliceFactor > currentSliceFactor) {
190             final double tmp = proposedNewSliceFactor;
191             proposedNewSliceFactor = currentSliceFactor;
192             currentSliceFactor = tmp;
193         }
194
195         return (currentSliceFactor / proposedNewSliceFactor) > 1.5d;
196     }
197
198     /**
199      * Permanently removes all sub-shapes belonging to the specified group.
200      *
201      * @param groupIdentifier the group to remove
202      * @see #hideGroup(String)
203      */
204     public void removeGroup(final String groupIdentifier) {
205         final java.util.Iterator<SubShape> iterator = originalSubShapes
206                 .iterator();
207
208         while (iterator.hasNext()) {
209             final SubShape subShape = iterator.next();
210             if (subShape.matchesGroup(groupIdentifier)) {
211                 iterator.remove();
212                 slicingOutdated = true;
213             }
214         }
215     }
216
217     /**
218      * Returns all sub-shapes belonging to the specified group.
219      *
220      * @param groupIdentifier the group identifier to match
221      * @return list of matching sub-shapes
222      */
223     public List<SubShape> getGroup(final String groupIdentifier) {
224         final List<SubShape> result = new ArrayList<>();
225         for (int i = 0; i < originalSubShapes.size(); i++) {
226             final SubShape subShape = originalSubShapes.get(i);
227             if (subShape.matchesGroup(groupIdentifier))
228                 result.add(subShape);
229         }
230         return result;
231     }
232
233     private void resliceIfNeeded() {
234
235         final double proposedSliceFactor = viewSpaceTracker.proposeSliceFactor();
236
237         if (isReslicingNeeded(proposedSliceFactor, currentSliceFactor)) {
238             currentSliceFactor = proposedSliceFactor;
239             reslice();
240         }
241     }
242
243     /**
244      * Paint solid elements of this composite shape into given color.
245      */
246     public void setColor(final Color color) {
247         for (final SubShape subShape : getOriginalSubShapes()) {
248             final AbstractShape shape = subShape.getShape();
249
250             if (shape instanceof SolidPolygon)
251                 ((SolidPolygon) shape).setColor(color);
252
253             if (shape instanceof Line)
254                 ((Line) shape).color = color;
255         }
256     }
257
258     /**
259      * Assigns a group identifier to all sub-shapes that currently have no group.
260      *
261      * @param groupIdentifier the group to assign to ungrouped shapes
262      */
263     public void setGroupForUngrouped(final String groupIdentifier) {
264         for (int i = 0; i < originalSubShapes.size(); i++) {
265             final SubShape subShape = originalSubShapes.get(i);
266             if (subShape.isUngrouped())
267                 subShape.setGroup(groupIdentifier);
268         }
269     }
270
271     @Override
272     public void setMouseInteractionController(
273             final MouseInteractionController mouseInteractionController) {
274         super.setMouseInteractionController(mouseInteractionController);
275
276         for (final SubShape subShape : originalSubShapes)
277             subShape.getShape().setMouseInteractionController(
278                     mouseInteractionController);
279
280         slicingOutdated = true;
281
282     }
283
284     /**
285      * Replaces this shape's transform (position and orientation).
286      *
287      * @param transform the new transform to apply
288      */
289     public void setTransform(final Transform transform) {
290         this.transform = transform;
291     }
292
293     /**
294      * Sets the lighting manager for this composite shape and enables shading on all SolidPolygon sub-shapes.
295      *
296      * @param lightingManager the lighting manager to use for shading calculations
297      */
298     public void setLightingManager(final LightingManager lightingManager) {
299         this.lightingManager = lightingManager;
300         applyShadingToPolygons();
301     }
302
303     /**
304      * Enables or disables shading for all SolidPolygon sub-shapes.
305      *
306      * @param shadingEnabled true to enable shading, false to disable
307      */
308     public void setShadingEnabled(final boolean shadingEnabled) {
309         for (final SubShape subShape : getOriginalSubShapes()) {
310             final AbstractShape shape = subShape.getShape();
311             if (shape instanceof SolidPolygon) {
312                 ((SolidPolygon) shape).setShadingEnabled(shadingEnabled, lightingManager);
313             }
314         }
315     }
316
317     private void applyShadingToPolygons() {
318         if (lightingManager == null)
319             return;
320
321         for (final SubShape subShape : getOriginalSubShapes()) {
322             final AbstractShape shape = subShape.getShape();
323             if (shape instanceof SolidPolygon) {
324                 ((SolidPolygon) shape).setShadingEnabled(true, lightingManager);
325             }
326         }
327     }
328
329     public void setBackfaceCulling(final boolean backfaceCulling) {
330         for (final SubShape subShape : getOriginalSubShapes()) {
331             final AbstractShape shape = subShape.getShape();
332             if (shape instanceof SolidPolygon) {
333                 ((SolidPolygon) shape).setBackfaceCulling(backfaceCulling);
334             } else if (shape instanceof TexturedPolygon) {
335                 ((TexturedPolygon) shape).setBackfaceCulling(backfaceCulling);
336             }
337         }
338     }
339
340     /**
341      * Makes all sub-shapes belonging to the specified group visible.
342      *
343      * @param groupIdentifier the group to show
344      * @see #hideGroup(String)
345      */
346     public void showGroup(final String groupIdentifier) {
347         for (int i = 0; i < originalSubShapes.size(); i++) {
348             final SubShape subShape = originalSubShapes.get(i);
349             if (subShape.matchesGroup(groupIdentifier)) {
350                 subShape.setVisible(true);
351                 slicingOutdated = true;
352             }
353         }
354     }
355
356     private void reslice() {
357         slicingOutdated = false;
358
359         final List<AbstractShape> result = new ArrayList<>();
360
361         final Slicer slicer = new Slicer(currentSliceFactor);
362         for (int i = 0; i < originalSubShapes.size(); i++) {
363             final SubShape subShape = originalSubShapes.get(i);
364             if (subShape.isVisible()) {
365                 if (subShape.getShape() instanceof TexturedPolygon)
366                     slicer.slice((TexturedPolygon) subShape.getShape());
367                 else
368                     result.add(subShape.getShape());
369             }
370         }
371
372         result.addAll(slicer.getResult());
373
374         renderedSubShapes = result;
375     }
376
377     @Override
378     public void transform(final TransformStack transformPipe,
379                           final RenderAggregator aggregator, final RenderingContext context) {
380
381         // add current composite shape transform to the end of the transform
382         // pipeline
383         transformPipe.addTransform(transform);
384
385         viewSpaceTracker.analyze(transformPipe, context);
386
387         beforeTransformHook(transformPipe, context);
388
389         // hack, to get somewhat perspective correct textures
390         resliceIfNeeded();
391
392         // transform rendered subshapes
393         for (final AbstractShape shape : renderedSubShapes)
394             shape.transform(transformPipe, aggregator, context);
395
396         transformPipe.dropTransform();
397     }
398
399 }