I make a minimap like this:
public void createMinimap() {
for (int i = 0; i < tilearray.size(); i++) {
float tileX = (200 * tilearray.get(i).getX()) / (getmWidth() * 64);
float tileY = (100 * tilearray.get(i).getY()) / (getmHeight() * 64);
final Rectangle tileRect = new Rectangle(tileX + 590, tileY + 380,
(64 * 200) / (getmWidth() * 64) + (float) 1, (64 * 100)
/ (getmHeight() * 64) + (float) 1, vbom);
tileRect.setColor(Color.WHITE);
tileRect.setAlpha(.7f);
gameHUD.attachChild(tileRect);
mapRectArray.add(tileRect);
}
}
And when I have lots of elements in tilearray, my game lags some. What is the reason for this?
As you are creating more number of tiles and Rectangle objects , it may effect loading.So, i can suggest you to load the resources before the game launches.Load these resources in back ground by placing loading screen.So, after loading all resources you can skip to Game
Related
This is for a visualization I am working on. I want to divide a rectangle in N equal parts. I want these parts to have a width of say (min. 1px, max 1.5px), depending on the width of the rectangle and I want this division to end with a remainder of 0 (so I don't have a larger than the rest part).
I have tried implementing Modulo: https://processing.org/reference/modulo.html but I am not sure this is the correct way. Any ideas?
//Generates coordinates within each line.
for (int j = 0; j < line_coordinates.length; j++) {
//Positions start of line draw on random X coordinate.
float xv = component_x1 + (j * (component_length / line_coordinates.length+1));
float yv = line_height;
//Defines available with for each item in a component.
float item_availablewidth = component_length / line_coordinates.length+1;
//Creates vector with X coordinate and Y noise affected coordinate.
line_coordinates[j] = new PVector(xv, y);
rectMode(CENTER);
noStroke();
fill(232, 45, 34);
rect(line_coordinates[j].x,
line_coordinates[j].y - (line_height / 2),
item_availablewidth * item_randomwidthcoefficient,
line_height);
println("line_coordinates[j].x1",
line_coordinates[j].x - ((item_availablewidth * item_randomwidthcoefficient) / 2)); //This is where X starts.
println("line_coordinates[j].x2",
line_coordinates[j].x + ((item_availablewidth * item_randomwidthcoefficient) / 2)); //This is where X is supposed to end.
//This is the first method I tried but I found out this separation needs to be dynamic.
float drawnline_separation = 2;
float drawnline_total = (item_availablewidth * item_randomwidthcoefficient) / drawnline_separation;
println("drawnline_total",
drawnline_total);
//For loop divides each item in vertical -axidrawable- lines separating them by a max
for (int l = 0; l <= drawnline_total; l++) {
float drawnline_x = lerp(line_coordinates[j].x - ((item_availablewidth * item_randomwidthcoefficient) / 2),
line_coordinates[j].x + ((item_availablewidth * item_randomwidthcoefficient) / 2),
l/drawnline_total);
println("drawnline_x", drawnline_x);
stroke(23);
noFill();
//Draws line.
line(drawnline_x,
line_coordinates[j].y,
drawnline_x,
line_coordinates[j].y + 25 );
}
}
//This is the print I am getting.
line_coordinates[j].x1 346.42535
line_coordinates[j].x2 353.44092
drawnline_total 3.5077777
drawnline_x 346.42535
drawnline_x 348.42535
drawnline_x 350.42535
drawnline_x 352.42535
I hope I am being clear! Please let me know if my explanation is very confusing.
I wrote a function that takes the subpixels of an image for the purpose of upscaling, and the subpixel is generated by bilinear interpolation, but I am having some weird artifacts.
Here is my code:
public static int getSubPixel(BufferedImage bi, double x, double y) {
float[] topleft = new Color(bi.getRGB((int) Math.floor(x), (int) Math.floor(y))).getColorComponents(null);
float[] topright = new Color(bi.getRGB(Math.min(bi.getWidth() - 1, (int) Math.ceil(x)), (int) Math.floor(y))).getColorComponents(null);
float[] bottomleft = new Color(bi.getRGB((int) Math.floor(x), Math.min(bi.getHeight() - 1, (int) Math.ceil(y)))).getColorComponents(null);
float[] bottomright = new Color(bi.getRGB(Math.min(bi.getWidth() - 1, (int) Math.ceil(x)), Math.min(bi.getHeight() - 1, (int) Math.ceil(y)))).getColorComponents(null);
for (int i = 0; i < 3; i++) {
topleft[i] *= topleft[i];
topright[i] *= topright[i];
bottomleft[i] *= bottomleft[i];
bottomright[i] *= bottomright[i];
}
double decX = x % 1;
double decY = y % 1;
double inv_DecX = 1 - decX;
double inv_DecY = 1 - decY;
float red = (float) Math.sqrt((topleft[0] * inv_DecX + topright[0] * decX) * inv_DecY + (bottomleft[0] * inv_DecX + bottomright[0] * decX) * decY);
float green = (float) Math.sqrt((topleft[1] * inv_DecX + topright[1] * decX) * inv_DecY + (bottomleft[1] * inv_DecX + bottomright[1] * decX) * decY);
float blue = (float) Math.sqrt((topleft[2] * inv_DecX + topright[2] * decX) * inv_DecY + (bottomleft[2] * inv_DecX + bottomright[2] * decX) * decY);
return new Color(red, green, blue).getRGB();
}
This is the result of scaling up a 16x16 image 20 times:
As you can see, there is weird streaking going on. I did go out of my way to square the colors before averaging, then taking the square root of the result, but something does not seem right here. Any insight?
PS: I understand functions already exist to do this. This is an educational exercise. I am trying to understand the process by doing it on my own.
The stripe artifacts that you are seeing are caused by the linear interpolation scheme. Your implementation is correct (except for the squaring, which is unnecessary and causes the stripes to be stronger in darker regions of the image). This is what I'm seeing with a correct linear interpolation (16x instead of 20x as in the OP, I goofed) but without squaring (note less stripes in the dark blue parts):
If you want to get rid of the stripes, use a better interpolation scheme, such as cubic spline interpolation:
import ddf.minim.*;
Minim minim;
AudioPlayer player;
PImage img;
void setup() {
size(728, 546);
minim = new Minim(this);
player = minim.loadFile("Bassnectar_-_Magical_World_feat.wav");
player.play();
img= loadImage("cat-in-shades-.jpg");
}
void draw() {
image(img, 0, 0);
tint(0, 100, 150);
stroke(255);
strokeWeight(4);
float a = 0;
float angle = (2*PI) / 200;
for(int i=0; i < player.bufferSize() - 1; i++) {
//player.mix.get(i) is a value between [-1,1]
float x = 250 + cos(a) * (20 * player.mix.get(i) + 100);
float x2 = 540 + cos(a) * (20 * player.mix.get(i) + 100);
float y = 230 + sin(a) * (20 * player.mix.get(i) + 100);
float y2 = 240 + sin(a) * (20 * player.mix.get(i) + 100);
float xFinal = 250 + cos(a+angle) * (20 * player.mix.get(i+1) + 100);
float x2Final = 540 + cos(a+angle) * (20 * player.mix.get(i+1) + 100);
float yFinal = 230 + sin(a+angle) * (20 * player.mix.get(i+1) + 100);
float y2Final = 240 + sin(a+angle) * (20 * player.mix.get(i+1) + 100);
line(x,y,xFinal,yFinal);
line(x2,y2,x2Final,y2Final);
a += angle;
}
}
void stop() {
player.close();
minim.stop();
super.stop();
}
The following code above is for creating an audio visualizer in Processing with the Minim library. For some reason I'm struggling to see how a circle is formed within the the code's for loop.
In general I'm also trying to break down the code and get a deeper understanding for what is going on. I am confused about the following:
'float x = 250 + cos(a) * (20 * player.mix.get(i) + 100);'
Is the 20 times and plus 100 used to scale up the sample? If so then why does the circle visualizer not display when I get rid of the 20 times and just have plus 20000? Is the 250 used for placement of the start point of the line on the x-axis within the background image?
Lastly, why is the variable 'angle' needed? When I take it out I notice the visualizer is not as smooth as there looks to be a division between the quadrants.
I have been playing around with this code, and can't find too many examples with detailed explanations so any help would be appreciated. Thank you.
The first thing you need to do is understand basic trigonometry better. There are a ton of resources out there: try googling "sin cos tutorial" or "sin and cos for game development" or "sohcahtoa" for a bunch of results.
But basically, if you have a start point, a rotation, and a distance, you can figure out where the end point is using sin and cos. The basic formula for calculating an end point is this:
endX = startX + cos(rotation)*distance;
endY = startY + sin(rotation)*distance;
Your code is using this formula to find points around a circle so that it can draw lines between them to draw the circle. Each line section of the circle is 2 of the end points.
The angle variable is used to specify how far apart those points are. The smaller you make it, the more "circle-y" it will look. The larger you make it, the more you'll be able to see the straight lines that make up the circle.
It might be easier to work with a simpler example:
void setup(){
size(500, 500);
}
void draw(){
background(0);
//draw white
stroke(255);
//the start point- try changing this to mouseX and mouseY
float centerX = width/2;
float centerY = height/2;
//the distance from the start point
float radius = 100;
//how far apart the points are
float angleIncrement = 30;
//loop to go around the circle. Try changing it to 180 to see what happens.
for(float angleInDegrees = 0; angleInDegrees <= 360; angleInDegrees+=angleIncrement){
//the first "end point" is the start point of the line
float startX = centerX + cos(radians(angleInDegrees))*radius;
float startY = centerY + sin(radians(angleInDegrees))*radius;
//the second "end point" is the end point of the line
//notice that we're adding the angleIncrement to the angle to get the next point
float endX = centerX + cos(radians(angleInDegrees+angleIncrement))*radius;
float endY = centerY + sin(radians(angleInDegrees+angleIncrement))*radius;
//draw the line
line(startX, startY, endX, endY);
}
}
I'm trying to implement Floyd Steinberg algorithm in Java, working with java.awt.image.BufferedImage.
I've used the algorithm described here
with a custom palette, and I was expecting to get more or less the same image as in the wikipedia example (or as generated by Gimp for example), but I get a very different version.
You can see what I get
I'm obviously missing something (output image has color which doesn't belong to my palette), but I can't figure out what.
What I'm doing wrong ?
Here's the code :
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.io.File;
import java.io.IOException;
public class FloydSteinbergTest {
private static final Color[] PALETTE = new Color[]{
new Color(221, 221, 221),
new Color(19, 125, 62),
new Color(179, 80, 188),
new Color(107, 138, 201),
new Color(177, 166, 39),
new Color(65, 174, 56),
new Color(208, 132, 153),
new Color(64, 64, 64),
new Color(154, 161, 161),
new Color(46, 110, 137),
new Color(126, 61, 181),
new Color(46, 56, 141),
new Color(79, 50, 31),
new Color(53, 70, 27),
new Color(150, 52, 48),
new Color(25, 22, 22)};
public static void main(String[] args) {
String lImgFile = "/tmp/test.jpg";
try {
// Load image
BufferedImage lImage = ImageIO.read(new File(lImgFile));
BufferedImage lOutImage = applyDitheredPalette(lImage, PALETTE);
ImageIO.write(lOutImage, "png", new File("/tmp/out.png"));
} catch (IOException lEx) {
System.out.println(lEx.getMessage());
}
}
/**
* #param pPalette Color palette to apply.
* #param pImage Image to apply palette on.
* #return {#link java.awt.image.BufferedImage} corresponding to pPalette applied on pImage using naive Floyd-Steinberg implementation
*/
public static BufferedImage applyDitheredPalette(BufferedImage pImage, Color[] pPalette) {
int lWidth = pImage.getWidth();
int lHeight = pImage.getHeight();
IndexColorModel lColorModel = paletteToColorModel(pPalette);
BufferedImage lImageOut = new BufferedImage(lWidth, lHeight, BufferedImage.TYPE_BYTE_INDEXED, lColorModel);
for (int y = (lHeight - 1); y >= 0; y--) {
for (int x = 0; x < lWidth; x++) {
// Get original pixel color channels
int lInitialPixelColor = pImage.getRGB(x, y);
// Finding nearest color in the palette
Color lNearestColor = getNearestColor(lInitialPixelColor, pPalette);
// Set quantized pixel
lImageOut.setRGB(x, y, lNearestColor.getRGB());
// Applying Floyd-Steinberg dithering
int quantizationError = lInitialPixelColor - lNearestColor.getRGB();
if ((x + 1) < lWidth) {
int lPixel = pImage.getRGB(x + 1, y);
lImageOut.setRGB(x + 1, y, lPixel + (quantizationError * (7 / 16)));
}
if ((x - 1) > 0 && (y + 1) < lHeight) {
int lPixel = pImage.getRGB(x - 1, y + 1);
lImageOut.setRGB(x - 1, y + 1, lPixel + (quantizationError * (3 / 16)));
}
if ((y + 1) < lHeight) {
int lPixel = pImage.getRGB(x, y + 1);
lImageOut.setRGB(x, y + 1, lPixel + (quantizationError * (5 / 16)));
}
if ((x + 1 < lWidth) && (y + 1 < lHeight)) {
int lPixel = pImage.getRGB(x + 1, y + 1);
lImageOut.setRGB(x + 1, y + 1, lPixel + (quantizationError * (1 / 16)));
}
// End of Floyd-Steinberg dithering
}
}
return lImageOut;
}
/**
* #param pPalette to load color model from
* #return {#link java.awt.image.IndexColorModel} Color model initialized using pPalette colors
*/
private static IndexColorModel paletteToColorModel(Color[] pPalette) {
int lSize = pPalette.length;
// Getting color component for each palette color
byte[] lReds = new byte[lSize];
byte[] lGreens = new byte[lSize];
byte[] lBlues = new byte[lSize];
for (int i = 0; i < lSize; i++) {
Color lColor = pPalette[i];
lReds[i] = (byte) lColor.getRed();
lGreens[i] = (byte) lColor.getGreen();
lBlues[i] = (byte) lColor.getBlue();
}
return new IndexColorModel(4, lSize, lReds, lGreens, lBlues);
}
/**
* #param pColor Color to approximate
* #param pPalette Color palette to use for quantization
* #return {#link java.awt.Color} nearest from pColor value took in pPalette
*/
private static Color getNearestColor(int pColor, Color[] pPalette) {
Color lNearestColor = null;
double lNearestDistance = Integer.MAX_VALUE;
double lTempDist;
for (Color lColor : pPalette) {
Color lRgb = new Color(pColor);
lTempDist = distance(lRgb.getRed(), lRgb.getGreen(), lRgb.getBlue(), lColor.getRed(), lColor.getGreen(), lColor.getBlue());
if (lTempDist < lNearestDistance) {
lNearestDistance = lTempDist;
lNearestColor = lColor;
}
}
return lNearestColor;
}
/**
* #return Distance between 2 pixels color channels.
*/
private static double distance(int pR1, int pG1, int pB1, int pR2, int pG2, int pB2) {
double lDist = Math.pow(pR1 - pR2, 2) + Math.pow(pG1 - pG2, 2) + Math.pow(pB1 - pB2, 2);
return Math.sqrt(lDist);
}}
This site is for questions, not for debugging. But as an attempt to at least answer the question "What I'm doing wrong?":
The term (7 / 16) will perform an integer division, and the result will be 0. Use (7.0 / 16.0) instead
You may not do arithmetic with RGB values! When you have an RGB value like 0x000000FF (blue) and you multiply it with 256, then the result will be 0x0000FF00 (green). The computations like lPixel + (quantizationError * (3.0 / 16.0) have to be done separately for the R, G and B channel
You're processing the image from the bottom to the top. Then distributing the error among the lower right pixels (as it is described on the wikipedia site) does not longer make sense. Change your loops from
for (int y = (lHeight - 1); y >= 0; y--)
to
for (int y = 0; y < lHeight; y++)
You can not store the quantization error directly in the pixels of BufferedImage, because the error may also be negative. The image can not handle this. (I also have doubts about your color model, but this is only a gut feeling)
The image that you described as the "expected result" contains colors that definitely are not contained in your palette.
Finally: Have a look at https://stackoverflow.com/a/5940260/3182664
I've been working recently on a fractal generator, and have been specifically working on the Mandelbrot set. Unfortunately, zooming and moving seems to be very inneficient and takes quite a while to refresh. I am generating it every time I zoom, and I know this is probably not the most efficient way of doing this, and I can't seem to find code that uses another method that I understand.
These are the following methods I use, the first being an intial generation, the second being a refresh method.
private void genMandelbrot(Dimension size) {
for(int x=0;x<size.width;x++) {
for(int y=0;y<size.height;y++) {
double moveX=globalx;
double moveY=globalx;
//zoom and x/y offset.
double real = 1.5 * (x - size.width / 2) / (0.5 * zoom * size.width) + moveX;
double imaginary=(y - size.height / 2) / (0.5 * zoom * size.height) + moveY;
double newRe=0,newIm=0,oldRe=0,oldIm=0;
int i;
for(i=0;i<8000;i++) {
oldRe = newRe;
oldIm = newIm;
newRe = oldRe * oldRe - oldIm * oldIm + real;
newIm = 2 * oldRe * oldIm + imaginary;
if((newRe * newRe + newIm * newIm) > 4) break;
}
Cell c = new Cell(Color.getHSBColor(i % 256, i % 255, 255 * ((i<20)? 1:0)), new Dimension(1,1), new Point(x,y));
cells.add(c);
}
}
}
public void refreshMandelbrot(Dimension size) {
for(Cell c : cells) {
double moveX=globalx;
double moveY=globalx;
int x=c.x;
int y=c.y;
//zoom and x/y offset.
double real = 1.5 * (x - size.width / 2) / (0.5 * zoom * size.width) + moveX;
double imaginary=(y - size.height / 2) / (0.5 * zoom * size.height) + moveY;
double newRe=0,newIm=0,oldRe=0,oldIm=0;
int i;
for(i=0;i<8000;i++) {
oldRe = newRe;
oldIm = newIm;
newRe = oldRe * oldRe - oldIm * oldIm + real;
newIm = 2 * oldRe * oldIm + imaginary;
if((newRe * newRe + newIm * newIm) > 4) break;
}
cells.set(cells.indexOf(c), new Cell(Color.getHSBColor(i % 256, i % 255, 255 * ((i<20)? 1:0)), new Dimension(1,1), new Point(x,y)));
}
System.out.println("Set refreshed.");
}
I suppose that cells is some kind of List implementation?
In that case, the most time of your refresh method is spent in this line:
cells.set(cells.indexOf(c), new Cell(Color.getHSBColor(i % 256, i % 255, 255 * ((i<20)? 1:0)), new Dimension(1,1), new Point(x,y)));
More precisely in cells.indexOf(c), where the entire list is iterated to find the correct index of c.
Since you are just changing the colour of each cell, the easiest fix is to change the colour of the cell you are currently working with. I don't know the actual implementation of your Cell class, but if it had a method setColor(...), you could replace the above line with
c.setColor(Color.getHSBColor(i % 256, i % 255, 255 * ((i<20)? 1:0)));
This reduces the runtime of the refreshMandelbrot method to the same as for the genMandelbrot method.
I don't know the purpose of the Cell class, but if you are only using it as a wrapper for a colour, you might gain some more performance if you store the computed colours for each pixel in a two-dimensional array or write directly to a Graphics or Raster object instead of handling a flat list of cell wrappers.
Most likely you need to subdivide the fractal and compute the less interesting tiles less intense. 8000 repetiton is a lot. You can also simplify the calculation a bit.