Created
June 12, 2014 04:53
-
-
Save junkdog/28d45c17158e3ad3e12c to your computer and use it in GitHub Desktop.
BurntPizza's (http://www.java-gaming.org/index.php?action=profile;u=120868) worley impl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.Graphics; | |
import java.awt.Image; | |
import java.awt.image.BufferedImage; | |
import java.util.ArrayList; | |
import java.util.List; | |
import javax.swing.JFrame; | |
import javax.swing.JPanel; | |
public class Worley { | |
public static Image worley(int width, int height, List<Point> seeds) { | |
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); | |
float maxDist = -1; | |
for (int y = 0; y < height; y++) | |
for (int x = 0; x < width; x++) { | |
float dist = closest(seeds, x, y); | |
dist = Math.min(dist, 255); | |
if (maxDist < dist) { | |
maxDist = dist; | |
} | |
} | |
float scale = 255 / maxDist; | |
for (int y = 0; y < height; y++) | |
for (int x = 0; x < width; x++) { | |
float dist = closest(seeds, x, y); | |
dist = Math.min(dist * scale, 255); | |
//dist *= scale; | |
int color = (int) dist; | |
color = color << 16 | color << 8 | color; | |
img.setRGB(x, y, color); | |
} | |
return img; | |
} | |
private static float closest(List<Point> list, int x, int y) { | |
Point closest = list.get(0); | |
float closestDist = Float.MAX_VALUE; | |
for (Point p : list) { | |
float dx = p.x - x; | |
float dy = p.y - y; | |
dx *= dx; | |
dy *= dy; | |
float dist = dx + dy; | |
if (dist < closestDist) { | |
closestDist = dist; | |
closest = p; | |
} | |
} | |
return (float) Math.hypot(closest.x - x, closest.y - y); | |
} | |
@SuppressWarnings("serial") | |
public static void main(String[] a) { | |
int w = 400, h = 400; | |
List<Point> l = new ArrayList<Point>(); | |
for (int i = 0; i < 300; i++) { | |
l.add(new Point((float) Math.random() * w, (float) Math.random() * h)); | |
} | |
final Image i = worley(w, h, l); | |
JFrame j = new JFrame(); | |
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
j.setLocationRelativeTo(null); | |
j.add(new JPanel() { | |
{ | |
setSize(i.getWidth(null), i.getHeight(null)); | |
setPreferredSize(getSize()); | |
} | |
@Override | |
public void paint(Graphics g) { | |
g.drawImage(i, 0, 0, null); | |
} | |
}); | |
j.pack(); | |
j.setVisible(true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment