- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathKochSnowflake.java
246 lines (215 loc) · 8.72 KB
/
KochSnowflake.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
packagecom.thealgorithms.others;
importjava.awt.BasicStroke;
importjava.awt.Color;
importjava.awt.Graphics2D;
importjava.awt.image.BufferedImage;
importjava.io.File;
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.List;
importjavax.imageio.ImageIO;
/**
* The Koch snowflake is a fractal curve and one of the earliest fractals to
* have been described. The Koch snowflake can be built up iteratively, in a
* sequence of stages. The first stage is an equilateral triangle, and each
* successive stage is formed by adding outward bends to each side of the
* previous stage, making smaller equilateral triangles. This can be achieved
* through the following steps for each line: 1. divide the line segment into
* three segments of equal length. 2. draw an equilateral triangle that has the
* middle segment from step 1 as its base and points outward. 3. remove the line
* segment that is the base of the triangle from step 2. (description adapted
* from https://en.wikipedia.org/wiki/Koch_snowflake ) (for a more detailed
* explanation and an implementation in the Processing language, see
* https://natureofcode.com/book/chapter-8-fractals/
* #84-the-koch-curve-and-the-arraylist-technique ).
*/
publicfinalclassKochSnowflake {
privateKochSnowflake() {
}
publicstaticvoidmain(String[] args) {
// Test Iterate-method
ArrayList<Vector2> vectors = newArrayList<Vector2>();
vectors.add(newVector2(0, 0));
vectors.add(newVector2(1, 0));
ArrayList<Vector2> result = iterate(vectors, 1);
assertresult.get(0).x == 0;
assertresult.get(0).y == 0;
assertresult.get(1).x == 1. / 3;
assertresult.get(1).y == 0;
assertresult.get(2).x == 1. / 2;
assertresult.get(2).y == Math.sin(Math.PI / 3) / 3;
assertresult.get(3).x == 2. / 3;
assertresult.get(3).y == 0;
assertresult.get(4).x == 1;
assertresult.get(4).y == 0;
// Test GetKochSnowflake-method
intimageWidth = 600;
doubleoffsetX = imageWidth / 10.;
doubleoffsetY = imageWidth / 3.7;
BufferedImageimage = getKochSnowflake(imageWidth, 5);
// The background should be white
assertimage.getRGB(0, 0) == newColor(255, 255, 255).getRGB();
// The snowflake is drawn in black and this is the position of the first vector
assertimage.getRGB((int) offsetX, (int) offsetY) == newColor(0, 0, 0).getRGB();
// Save image
try {
ImageIO.write(image, "png", newFile("KochSnowflake.png"));
} catch (IOExceptione) {
e.printStackTrace();
}
}
/**
* Go through the number of iterations determined by the argument "steps".
* Be careful with high values (above 5) since the time to calculate
* increases exponentially.
*
* @param initialVectors The vectors composing the shape to which the
* algorithm is applied.
* @param steps The number of iterations.
* @return The transformed vectors after the iteration-steps.
*/
publicstaticArrayList<Vector2> iterate(ArrayList<Vector2> initialVectors, intsteps) {
ArrayList<Vector2> vectors = initialVectors;
for (inti = 0; i < steps; i++) {
vectors = iterationStep(vectors);
}
returnvectors;
}
/**
* Method to render the Koch snowflake to a image.
*
* @param imageWidth The width of the rendered image.
* @param steps The number of iterations.
* @return The image of the rendered Koch snowflake.
*/
publicstaticBufferedImagegetKochSnowflake(intimageWidth, intsteps) {
if (imageWidth <= 0) {
thrownewIllegalArgumentException("imageWidth should be greater than zero");
}
doubleoffsetX = imageWidth / 10.;
doubleoffsetY = imageWidth / 3.7;
Vector2vector1 = newVector2(offsetX, offsetY);
Vector2vector2 = newVector2(imageWidth / 2.0, Math.sin(Math.PI / 3.0) * imageWidth * 0.8 + offsetY);
Vector2vector3 = newVector2(imageWidth - offsetX, offsetY);
ArrayList<Vector2> initialVectors = newArrayList<Vector2>();
initialVectors.add(vector1);
initialVectors.add(vector2);
initialVectors.add(vector3);
initialVectors.add(vector1);
ArrayList<Vector2> vectors = iterate(initialVectors, steps);
returngetImage(vectors, imageWidth, imageWidth);
}
/**
* Loops through each pair of adjacent vectors. Each line between two
* adjacent vectors is divided into 4 segments by adding 3 additional
* vectors in-between the original two vectors. The vector in the middle is
* constructed through a 60 degree rotation so it is bent outwards.
*
* @param vectors The vectors composing the shape to which the algorithm is
* applied.
* @return The transformed vectors after the iteration-step.
*/
privatestaticArrayList<Vector2> iterationStep(List<Vector2> vectors) {
ArrayList<Vector2> newVectors = newArrayList<Vector2>();
for (inti = 0; i < vectors.size() - 1; i++) {
Vector2startVector = vectors.get(i);
Vector2endVector = vectors.get(i + 1);
newVectors.add(startVector);
Vector2differenceVector = endVector.subtract(startVector).multiply(1. / 3);
newVectors.add(startVector.add(differenceVector));
newVectors.add(startVector.add(differenceVector).add(differenceVector.rotate(60)));
newVectors.add(startVector.add(differenceVector.multiply(2)));
}
newVectors.add(vectors.get(vectors.size() - 1));
returnnewVectors;
}
/**
* Utility-method to render the Koch snowflake to an image.
*
* @param vectors The vectors defining the edges to be rendered.
* @param imageWidth The width of the rendered image.
* @param imageHeight The height of the rendered image.
* @return The image of the rendered edges.
*/
privatestaticBufferedImagegetImage(ArrayList<Vector2> vectors, intimageWidth, intimageHeight) {
BufferedImageimage = newBufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
Graphics2Dg2d = image.createGraphics();
// Set the background white
g2d.setBackground(Color.WHITE);
g2d.fillRect(0, 0, imageWidth, imageHeight);
// Draw the edges
g2d.setColor(Color.BLACK);
BasicStrokebs = newBasicStroke(1);
g2d.setStroke(bs);
for (inti = 0; i < vectors.size() - 1; i++) {
intx1 = (int) vectors.get(i).x;
inty1 = (int) vectors.get(i).y;
intx2 = (int) vectors.get(i + 1).x;
inty2 = (int) vectors.get(i + 1).y;
g2d.drawLine(x1, y1, x2, y2);
}
returnimage;
}
/**
* Inner class to handle the vector calculations.
*/
privatestaticclassVector2 {
doublex;
doubley;
Vector2(doublex, doubley) {
this.x = x;
this.y = y;
}
@Override
publicStringtoString() {
returnString.format("[%f, %f]", this.x, this.y);
}
/**
* Vector addition
*
* @param vector The vector to be added.
* @return The sum-vector.
*/
publicVector2add(Vector2vector) {
doublex = this.x + vector.x;
doubley = this.y + vector.y;
returnnewVector2(x, y);
}
/**
* Vector subtraction
*
* @param vector The vector to be subtracted.
* @return The difference-vector.
*/
publicVector2subtract(Vector2vector) {
doublex = this.x - vector.x;
doubley = this.y - vector.y;
returnnewVector2(x, y);
}
/**
* Vector scalar multiplication
*
* @param scalar The factor by which to multiply the vector.
* @return The scaled vector.
*/
publicVector2multiply(doublescalar) {
doublex = this.x * scalar;
doubley = this.y * scalar;
returnnewVector2(x, y);
}
/**
* Vector rotation (see https://en.wikipedia.org/wiki/Rotation_matrix)
*
* @param angleInDegrees The angle by which to rotate the vector.
* @return The rotated vector.
*/
publicVector2rotate(doubleangleInDegrees) {
doubleradians = angleInDegrees * Math.PI / 180;
doubleca = Math.cos(radians);
doublesa = Math.sin(radians);
doublex = ca * this.x - sa * this.y;
doubley = sa * this.x + ca * this.y;
returnnewVector2(x, y);
}
}
}