Possibility to retrieve objects by group. Reuse glowing point textures.
[sixth-3d.git] / src / main / java / eu / svjatoslav / sixth / e3d / renderer / raster / shapes / basic / GlowingPoint.java
1 /*
2  * Sixth 3D engine. Copyright ©2012-2016, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of version 3 of the GNU Lesser General Public License
6  * or later as published by the Free Software Foundation.
7  *
8  */
9
10 package eu.svjatoslav.sixth.e3d.renderer.raster.shapes.basic;
11
12 import eu.svjatoslav.sixth.e3d.geometry.Point3D;
13 import eu.svjatoslav.sixth.e3d.renderer.raster.Color;
14 import eu.svjatoslav.sixth.e3d.renderer.raster.texture.Texture;
15
16 import java.util.Collections;
17 import java.util.Set;
18 import java.util.WeakHashMap;
19
20 public class GlowingPoint extends ForwardOrientedTexture {
21
22     private static final int TEXTURE_SIZE = 50;
23     private final Color color;
24
25     private static final Set<GlowingPoint> glowingPoints = Collections.newSetFromMap(new WeakHashMap<GlowingPoint, Boolean>());
26
27     public GlowingPoint(final Point3D point, final double pointSize,
28                         final Color color) {
29         super(point, pointSize, getTexture(color));
30         this.color = color;
31     }
32
33     private static Texture getTexture(final Color color) {
34         // attempt to reuse texture from existing glowing point of the same color
35         for (GlowingPoint glowingPoint : glowingPoints)
36             if (color.equals(glowingPoint.color)) return glowingPoint.texture;
37
38         // existing texture not found, creating new one
39         return createTexture(color);
40     }
41
42     private static Texture createTexture(final Color color) {
43         final Texture texture = new Texture(TEXTURE_SIZE, TEXTURE_SIZE, 1);
44         for (int x = 0; x < TEXTURE_SIZE; x++)
45             for (int y = 0; y < TEXTURE_SIZE; y++) {
46                 int address = texture.primaryBitmap.getAddress(x, y);
47
48                 final int distance = (int) Math
49                         .sqrt((((TEXTURE_SIZE / 2) - x) * ((TEXTURE_SIZE / 2) - x))
50                                 + (((TEXTURE_SIZE / 2) - y) * ((TEXTURE_SIZE / 2) - y)));
51
52                 int alpha = 255 - ((270 * distance) / (TEXTURE_SIZE / 2));
53                 if (alpha < 0)
54                     alpha = 0;
55
56                 texture.primaryBitmap.bytes[address] = (byte) alpha;
57                 address++;
58                 texture.primaryBitmap.bytes[address] = (byte) color.b;
59                 address++;
60                 texture.primaryBitmap.bytes[address] = (byte) color.g;
61                 address++;
62                 texture.primaryBitmap.bytes[address] = (byte) color.r;
63             }
64
65         return texture;
66     }
67
68 }