Formatting update
[sixth-3d.git] / src / main / java / eu / svjatoslav / sixth / e3d / renderer / raster / shapes / basic / GlowingPoint.java
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.basic;
6
7 import eu.svjatoslav.sixth.e3d.geometry.Point3D;
8 import eu.svjatoslav.sixth.e3d.renderer.raster.Color;
9 import eu.svjatoslav.sixth.e3d.renderer.raster.texture.Texture;
10
11 import java.util.Collections;
12 import java.util.Set;
13 import java.util.WeakHashMap;
14
15 public class GlowingPoint extends ForwardOrientedTexture {
16
17     private static final int TEXTURE_SIZE = 50;
18     private static final Set<GlowingPoint> glowingPoints = Collections.newSetFromMap(new WeakHashMap<>());
19     private final Color color;
20
21     public GlowingPoint(final Point3D point, final double pointSize,
22                         final Color color) {
23         super(point, pointSize, getTexture(color));
24         this.color = color;
25
26         synchronized (glowingPoints) {
27             glowingPoints.add(this);
28         }
29     }
30
31     private static Texture getTexture(final Color color) {
32         // attempt to reuse texture from existing glowing point of the same color
33         synchronized (glowingPoints) {
34             for (GlowingPoint glowingPoint : glowingPoints)
35                 if (color.equals(glowingPoint.color))
36                     return glowingPoint.texture;
37         }
38
39         // existing texture not found, creating new one
40         return createTexture(color);
41     }
42
43     private static Texture createTexture(final Color color) {
44         final Texture texture = new Texture(TEXTURE_SIZE, TEXTURE_SIZE, 1);
45         for (int x = 0; x < TEXTURE_SIZE; x++)
46             for (int y = 0; y < TEXTURE_SIZE; y++) {
47                 int address = texture.primaryBitmap.getAddress(x, y);
48
49                 final int distance = (int) Math
50                         .sqrt((((TEXTURE_SIZE / 2) - x) * ((TEXTURE_SIZE / 2) - x))
51                                 + (((TEXTURE_SIZE / 2) - y) * ((TEXTURE_SIZE / 2) - y)));
52
53                 int alpha = 255 - ((270 * distance) / (TEXTURE_SIZE / 2));
54                 if (alpha < 0)
55                     alpha = 0;
56
57                 texture.primaryBitmap.bytes[address] = (byte) alpha;
58                 address++;
59                 texture.primaryBitmap.bytes[address] = (byte) color.b;
60                 address++;
61                 texture.primaryBitmap.bytes[address] = (byte) color.g;
62                 address++;
63                 texture.primaryBitmap.bytes[address] = (byte) color.r;
64             }
65
66         return texture;
67     }
68
69 }