Related
I have a little bit knowledge of android and OGLES2.0 but when i am drawing a picture it takes approximately 0.4ms. So I can draw only 40 pictures in 16ms in order to get 60fps for my game.
Here is my GLRenderer code:
The important parts are the Render-method and the Sprite Class.
public class GLRenderer implements Renderer {
// Our matrices
private final float[] mtrxProjection = new float[16];
private final float[] mtrxView = new float[16];
private final float[] mtrxProjectionAndView = new float[16];
// Geometric variables
public static int[] vertices;
public static short[] indices;
public static int[] uvs;
public IntBuffer vertexBuffer;
public ShortBuffer drawListBuffer;
public IntBuffer uvBuffer;
public List<Sprite> sprites;
public int[] texturenames;
public MainActivity mainActivity;
// Our screenresolution
float mScreenWidth = 1280;
float mScreenHeight = 720;
float ssu = 1.0f;
float ssx = 1.0f;
float ssy = 1.0f;
float swp = 1280.0f;
float shp = 720.0f;
Update update;
Images images;
// Misc
Context mContext;
long mLastTime;
int mProgram;
public GLRenderer (MainActivity mainActivity) {
this.mContext = mainActivity;
this.mainActivity = mainActivity;
this.mLastTime = System.currentTimeMillis() + 100;
this.sprites = new ArrayList<Sprite>();
}
public void onPause () {
/* Do stuff to pause the renderer */
}
public void onResume () {
/* Do stuff to resume the renderer */
this.mLastTime = System.currentTimeMillis();
}
#Override
public void onDrawFrame (GL10 unused) {
// Get the current time
long now = System.currentTimeMillis();
// We should make sure we are valid and sane
if (this.mLastTime > now) return;
// Get the amount of time the last frame took.
long elapsed = now - this.mLastTime;
System.out.println(elapsed);
// clear Screen and Depth Buffer, we have set the clear color as black.
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
// Drawing all static things like the background
drawStatics();
for (Opponent opponent: this.update.opponents) {
int position = this.sprites.indexOf(opponent.getSprite());
// Rotate the sprite
this.sprites.get(position).rotate((float) Math.toRadians(opponent.getAngle()));
// Create the image information
SetupImage(opponent.getPicture(), 0);
// Update our example
UpdateSprite(position);
// Render our example
Render(this.mtrxProjectionAndView, 0);
}
for (Tower tower: this.update.towers) {
long a = System.nanoTime();
int position = this.sprites.indexOf(tower.getSprite());
// Rotate the sprite
this.sprites.get(position).rotate((float) Math.toRadians(tower.getAngle()));
// Create the image information
SetupImage(tower.getPicture(), 0);
// Update our example
UpdateSprite(position);
// Render our example
Render(this.mtrxProjectionAndView, 0);
System.out.println("time: " + (System.nanoTime() - a));
}
for (Bullet bullet: this.update.bullets) {
int position = this.sprites.indexOf(bullet.getSprite());
// Rotate the sprite
this.sprites.get(position).rotate((float) Math.toRadians(bullet.getAngle()));
// Create the image information
SetupImage(bullet.getPicture(), 0);
// Update our example
UpdateSprite(position);
// Render our example
Render(this.mtrxProjectionAndView, 0);
}
for (SuperExplosion explosion: this.update.explosions) {
int position = this.sprites.indexOf(explosion.getSprite());
// Rotate the sprite
// sprites.get(position).rotate((float)Math.toRadians(explosion.getAngle()));
// Create the image information
SetupImage(explosion.getPicture(), 0);
// Update our example
UpdateSprite(position);
// Render our example
Render(this.mtrxProjectionAndView, 0);
}
drawStatics2();
// Save the current time to see how long it took :).
this.mLastTime = now;
// System.out.println("höhe "+mScreenHeight+" breite "+ mScreenWidth);
}
private void drawStatics () {
// Ground
// Update our example
long h = System.nanoTime();
UpdateSprite(0);
// for (int i = 0; i < vertices.length; i++) {
// System.out.println("vertices [" + i + "]: " + vertices[i]);
// }
// Render our example
Render(this.mtrxProjectionAndView, 1);
System.out.println("time: " + (System.nanoTime() - h));
// Bar
// Update our example
UpdateSprite(1);
// Render our example
Render(this.mtrxProjectionAndView, 2);
if (!this.update.upgrade) {
if (this.update.normalSpeed) {
// Update our example
UpdateSprite(2);
// Render our example
Render(this.mtrxProjectionAndView, 3);
} else {
// Update our example
UpdateSprite(3);
// Render our example
Render(this.mtrxProjectionAndView, 4);
}
if (!this.update.start) {
// Update our example
UpdateSprite(4);
// Render our example
Render(this.mtrxProjectionAndView, 5);
}
}
// UpgradeBar
if (this.update.upgrade) {
// Update our example
UpdateSprite(6);
// Render our example
Render(this.mtrxProjectionAndView, 7);
}
h = System.nanoTime();
// Bunny1
// Update our example
UpdateSprite(7);
// Render our example
Render(this.mtrxProjectionAndView, 8);
System.out.println("time bunny1 " + (System.nanoTime() - h));
// CarrotTower
// Update our example
UpdateSprite(8);
// Render our example
Render(this.mtrxProjectionAndView, 9);
// MineThrower
// Update our example
UpdateSprite(9);
// Render our example
Render(this.mtrxProjectionAndView, 10);
// BunnyKing
// Update our example
UpdateSprite(10);
// Render our example
Render(this.mtrxProjectionAndView, 11);
}
private void drawStatics2 () {
// Life
// Update our example
UpdateSprite(5);
// Render our example
Render(this.mtrxProjectionAndView, 6);
}
private void Render (float[] m, int index) {
// get handle to vertex shader's vPosition member
int mPositionHandle = GLES20.glGetAttribLocation(riGraphicTools.sp_Image, "vPosition");
// Enable generic vertex attribute array
GLES20.glEnableVertexAttribArray(mPositionHandle);
// Prepare the triangle coordinate data
GLES20.glVertexAttribPointer(mPositionHandle, 3, GLES20.GL_INT, false, 0, this.vertexBuffer);
// Get handle to texture coordinates location
int mTexCoordLoc = GLES20.glGetAttribLocation(riGraphicTools.sp_Image, "a_texCoord");
// Enable generic vertex attribute array
GLES20.glEnableVertexAttribArray(mTexCoordLoc);
// Prepare the texturecoordinates
GLES20.glVertexAttribPointer(mTexCoordLoc, 2, GLES20.GL_INT, false, 0, this.uvBuffer);
// Get handle to shape's transformation matrix
int mtrxhandle = GLES20.glGetUniformLocation(riGraphicTools.sp_Image, "uMVPMatrix");
// Apply the projection and view transformation
GLES20.glUniformMatrix4fv(mtrxhandle, 1, false, m, 0);
// Get handle to textures locations
int mSamplerLoc = GLES20.glGetUniformLocation(riGraphicTools.sp_Image, "s_texture");
// Set the sampler texture unit to 0, where we have saved the texture.
GLES20.glUniform1i(mSamplerLoc, index);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, this.texturenames[index]);
// Set filtering
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
// Draw the triangle
GLES20.glDrawElements(GLES20.GL_TRIANGLES, indices.length, GLES20.GL_UNSIGNED_SHORT, this.drawListBuffer);
// Disable vertex array
GLES20.glDisableVertexAttribArray(mPositionHandle);
GLES20.glDisableVertexAttribArray(mTexCoordLoc);
}
#Override
public void onSurfaceChanged (GL10 gl, int width, int height) {
// We need to know the current width and height.
this.mScreenWidth = width;
this.mScreenHeight = height;
// Redo the Viewport, making it fullscreen.
GLES20.glViewport(0, 0, (int) this.mScreenWidth, (int) this.mScreenHeight);
// Clear our matrices
for (int i = 0; i < 16; i++) {
this.mtrxProjection[i] = 0.0f;
this.mtrxView[i] = 0.0f;
this.mtrxProjectionAndView[i] = 0.0f;
}
// Setup our screen width and height for normal sprite translation.
Matrix.orthoM(this.mtrxProjection, 0, 0f, this.mScreenWidth, 0.0f, this.mScreenHeight, 0, 50);
// Set the camera position (View matrix)
Matrix.setLookAtM(this.mtrxView, 0, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
// Calculate the projection and view transformation
Matrix.multiplyMM(this.mtrxProjectionAndView, 0, this.mtrxProjection, 0, this.mtrxView, 0);
// Setup our scaling system
SetupScaling();
// Create the GroundSprite
SetupTriangle(this.images.ground_1.getWidth(), this.images.ground_1.getHeight(), 0, 0);
SetupTriangle(this.images.bar1.getWidth(), this.images.bar1.getHeight(), 0, 0);
SetupTriangle(this.images.speed1.getWidth(), this.images.speed1.getHeight(), 0, 0);
SetupTriangle(this.images.speed2.getWidth(), this.images.speed2.getHeight(), 0, 0);
SetupTriangle(this.images.start.getWidth(), this.images.start.getHeight(), 0, 0);
SetupTriangle(this.images.life.getWidth(), this.images.life.getHeight(), 0, 0);
SetupTriangle(this.images.upgradeBar.getWidth(), this.images.upgradeBar.getHeight(), 0, 0);
SetupTriangle(this.images.bunny1.getWidth(), this.images.bunny1.getHeight(), 0, 0);
SetupTriangle(this.images.carrotTower.getWidth(), this.images.carrotTower.getHeight(), 0, 0);
SetupTriangle(this.images.mineThrower.getWidth(), this.images.mineThrower.getHeight(), 0, 0);
SetupTriangle(this.images.bunnyKing1.getWidth(), this.images.bunnyKing1.getHeight(), 0, 0);
this.sprites.get(0).translate(this.ssx * this.images.ground_1.getWidth() / 2, this.ssy * this.images.ground_1.getHeight() / 2);
this.sprites.get(1).translate(this.ssx * (this.images.bar1.getWidth() / 2) + this.ssx * 1084.0f, this.ssy * this.images.bar1.getHeight() / 2.0f);
this.sprites.get(2).translate(this.ssx * this.images.speed1.getWidth() / 2 + this.ssx * 20, this.mScreenHeight - (this.ssy * this.images.speed1.getHeight() / 2) - this.ssy * 5);
this.sprites.get(3).translate(this.ssx * this.images.speed2.getWidth() / 2 + this.ssx * 20, this.mScreenHeight - (this.ssy * this.images.speed2.getHeight() / 2) - this.ssy * 5);
this.sprites.get(4).translate(this.ssx * this.images.start.getWidth() / 2 + this.ssx * 120, this.mScreenHeight - (this.ssy * this.images.start.getHeight() / 2) - this.ssy * 5);
this.sprites.get(5).translate(this.ssx * this.images.life.getWidth() / 2 + this.ssx * 5, this.ssy * this.images.life.getHeight() / 2 + this.ssy * (20));
this.sprites.get(6).translate(this.ssx * this.images.upgradeBar.getWidth() / 2, this.ssy * this.images.upgradeBar.getHeight() / 2);
this.sprites.get(7).translate(this.ssx * (this.images.bunny1.getWidth()) + this.ssx * (1280 - 143 - (this.images.bunny1.getWidth() / 2)), this.mScreenHeight - (this.ssy * this.images.bunny1.getHeight() / 2) - (this.ssy * (235 + (this.images.bunny1.getHeight() / 2))));
this.sprites.get(8).translate(this.ssx * (this.images.carrotTower.getWidth()) + this.ssx * (1280 - 53 - (this.images.carrotTower.getWidth() / 2)), this.mScreenHeight - (this.ssy * this.images.carrotTower.getHeight() / 2) - (this.ssy * (235 + (this.images.carrotTower.getHeight() / 2))));
this.sprites.get(9).translate(this.ssx * (this.images.mineThrower.getWidth()) + this.ssx * (1280 - 143 - (this.images.mineThrower.getWidth() / 2)), this.mScreenHeight - (this.ssy * this.images.mineThrower.getHeight() / 2) - (this.ssy * (325 + (this.images.mineThrower.getHeight() / 2))));
this.sprites.get(10).translate(this.ssx * (this.images.bunnyKing1.getWidth()) + this.ssx * (1280 - 53 - (this.images.bunnyKing1.getWidth() / 2)), this.mScreenHeight - (this.ssy * this.images.bunnyKing1.getHeight() / 2) - (this.ssy * (325 + (this.images.bunnyKing1.getHeight() / 2))));
}
#Override
public void onSurfaceCreated (GL10 gl, EGLConfig config) {
// Setup our scaling system
SetupScaling();
// Set the clear color to black
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1);
// Blending
GLES20.glEnable(GLES20.GL_BLEND);
// How should opengl blend it
GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA);
// Create the shaders, solid color
int vertexShader = riGraphicTools.loadShader(GLES20.GL_VERTEX_SHADER, riGraphicTools.vs_SolidColor);
int fragmentShader = riGraphicTools.loadShader(GLES20.GL_FRAGMENT_SHADER, riGraphicTools.fs_SolidColor);
riGraphicTools.sp_SolidColor = GLES20.glCreateProgram(); // create empty
// OpenGL ES
// Program
GLES20.glAttachShader(riGraphicTools.sp_SolidColor, vertexShader); // add
// the
// vertex
// shader
// to
// program
GLES20.glAttachShader(riGraphicTools.sp_SolidColor, fragmentShader); // add
// the
// fragment
// shader
// to
// program
GLES20.glLinkProgram(riGraphicTools.sp_SolidColor); // creates OpenGL ES
// program
// executables
// Create the shaders, images
vertexShader = riGraphicTools.loadShader(GLES20.GL_VERTEX_SHADER, riGraphicTools.vs_Image);
fragmentShader = riGraphicTools.loadShader(GLES20.GL_FRAGMENT_SHADER, riGraphicTools.fs_Image);
riGraphicTools.sp_Image = GLES20.glCreateProgram(); // create empty
// OpenGL ES Program
GLES20.glAttachShader(riGraphicTools.sp_Image, vertexShader); // add the
// vertex
// shader
// to
// program
GLES20.glAttachShader(riGraphicTools.sp_Image, fragmentShader); // add
// the
// fragment
// shader
// to
// program
GLES20.glLinkProgram(riGraphicTools.sp_Image); // creates OpenGL ES
// program executables
// Set our shader programm
GLES20.glUseProgram(riGraphicTools.sp_Image);
// Creating a Images Object
this.images = new Images(this.mainActivity.getResources());
// Loading the Bitmaps
this.images.load();
Timer t = new Timer();
t.schedule(this.update = new Update(this.mainActivity, this, this.images), 16);
// Generate Textures, if more needed, alter these numbers.
this.texturenames = new int[24];
GLES20.glGenTextures(24, this.texturenames, 0);
SetupImageStatics();
}
private void SetupImageStatics () {
SetupImage(this.images.ground_1, 1);
SetupImage(this.images.bar1, 2);
SetupImage(this.images.speed1, 3);
SetupImage(this.images.speed2, 4);
SetupImage(this.images.start, 5);
SetupImage(this.images.life, 6);
SetupImage(this.images.upgradeBar, 7);
SetupImage(this.images.bunny1, 8);
SetupImage(this.images.carrotTower, 9);
SetupImage(this.images.mineThrower, 10);
SetupImage(this.images.bunnyKing1, 11);
}
public void SetupScaling () {
// The screen resolutions
this.swp = (this.mContext.getResources().getDisplayMetrics().widthPixels);
this.shp = (this.mContext.getResources().getDisplayMetrics().heightPixels);
// Orientation is assumed portrait
this.ssx = this.swp / 1280.0f;
this.ssy = this.shp / 720.0f;
// Get our uniform scaler
if (this.ssx > this.ssy) this.ssu = this.ssy;
else this.ssu = this.ssx;
}
public void processTouchEvent (MotionEvent me) {
switch (me.getAction()) {
case MotionEvent.ACTION_DOWN:
this.update.x = (int) me.getX();
this.update.y = (int) me.getY();
this.update.getItemOrUpgrade(this.update.x, this.update.y);
this.update.fastForward(this.update.x, this.update.y);
this.update.start(this.update.x, this.update.y);
this.update.nextUpgrade(this.update.x, this.update.y);
break;
case MotionEvent.ACTION_MOVE:
if (this.update.tower != 0) {
this.update.x = (int) me.getX();
this.update.y = (int) me.getY();
this.update.pathPlace(this.update.x, this.update.y);
}
break;
case MotionEvent.ACTION_UP:
this.update.x = (int) me.getX();
this.update.y = (int) me.getY();
this.update.placeOrReleaseItem = true;
break;
}
}
public void UpdateSprite (int location) {
// Get new transformed vertices
vertices = this.sprites.get(location).getTransformedVertices();
// The vertex buffer.
ByteBuffer bb = ByteBuffer.allocateDirect(vertices.length * 4);
bb.order(ByteOrder.nativeOrder());
this.vertexBuffer = bb.asIntBuffer();
this.vertexBuffer.put(vertices);
this.vertexBuffer.position(0);
}
public void SetupImage (Bitmap bmp, int index) {
// Create our UV coordinates.
uvs = new int[] { 0, 0, 0, 1, 1, 1, 1, 0 };
// The texture buffer
ByteBuffer bb = ByteBuffer.allocateDirect(uvs.length * 4);
bb.order(ByteOrder.nativeOrder());
this.uvBuffer = bb.asIntBuffer();
this.uvBuffer.put(uvs);
this.uvBuffer.position(0);
// // Retrieve our image from resources.
// int id =
// mContext.getResources().getIdentifier("drawable/ic_launcher", null,
// mContext.getPackageName());
//
// // Temporary create a bitmap
// Bitmap bmp = BitmapFactory.decodeResource(mContext.getResources(),
// id);
// Bind texture to texturename
GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + index);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, this.texturenames[index]);
// Set filtering
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
// Load the bitmap into the bound texture.
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bmp, 0);
// // We are done using the bitmap so we should recycle it.
// bmp.recycle();
}
public void SetupTriangle (float width, float height, float x, float y) {
// Get information of sprite.
this.sprites.add(new Sprite(width, height, x, y));
vertices = this.sprites.get(this.sprites.size() - 1).getTransformedVertices();
// The order of vertexrendering for a quad
indices = new short[] { 0, 1, 2, 0, 2, 3 };
// The vertex buffer.
ByteBuffer bb = ByteBuffer.allocateDirect(vertices.length * 4);
bb.order(ByteOrder.nativeOrder());
this.vertexBuffer = bb.asIntBuffer();
this.vertexBuffer.put(vertices);
this.vertexBuffer.position(0);
// initialize byte buffer for the draw list
ByteBuffer dlb = ByteBuffer.allocateDirect(indices.length * 2);
dlb.order(ByteOrder.nativeOrder());
this.drawListBuffer = dlb.asShortBuffer();
this.drawListBuffer.put(indices);
this.drawListBuffer.position(0);
}
class Sprite {
float angle;
float scale;
RectF base;
Point translation;
public Sprite (float width, float height, float x, float y) {
// Initialise our intital size around the 0,0 point
this.base = new RectF(-(width / 2f) * GLRenderer.this.ssu, (height / 2f) * GLRenderer.this.ssu, (width / 2f) * GLRenderer.this.ssu, -(height / 2f) * GLRenderer.this.ssu);
// Initial translation
this.translation = new Point(Math.round(x * GLRenderer.this.ssu), Math.round(y * GLRenderer.this.ssu));
// We start with our inital size
this.scale = 1f;
// We start in our inital angle
this.angle = 0.0f;
}
public void translate (float deltax, float deltay) {
// Update our location.
this.translation.x += Math.round(deltax);
this.translation.y += Math.round(deltay);
}
public void scale (float deltas) {
this.scale += deltas;
}
public void rotate (float deltaa) {
this.angle += deltaa;
}
public int[] getTransformedVertices () {
// Start with scaling
int x1 = Math.round(this.base.left * this.scale);
int x2 = Math.round(this.base.right * this.scale);
int y1 = Math.round(this.base.bottom * this.scale);
int y2 = Math.round(this.base.top * this.scale);
// We now detach from our Rect because when rotating,
// we need the seperate points, so we do so in opengl order
Point one = new Point(x1, y2);
Point two = new Point(x1, y1);
Point three = new Point(x2, y1);
Point four = new Point(x2, y2);
// We create the sin and cos function once,
// so we do not have calculate them each time.
float s = (float) Math.sin(this.angle);
float c = (float) Math.cos(this.angle);
// Then we rotate each point
one.x = Math.round(x1 * c - y2 * s);
one.y = Math.round(x1 * s + y2 * c);
two.x = Math.round(x1 * c - y1 * s);
two.y = Math.round(x1 * s + y1 * c);
three.x = Math.round(x2 * c - y1 * s);
three.y = Math.round(x2 * s + y1 * c);
four.x = Math.round(x2 * c - y2 * s);
four.y = Math.round(x2 * s + y2 * c);
// Finally we translate the sprite to its correct position.
one.x += this.translation.x;
one.y += this.translation.y;
two.x += this.translation.x;
two.y += this.translation.y;
three.x += this.translation.x;
three.y += this.translation.y;
four.x += this.translation.x;
four.y += this.translation.y;
// We now return our float array of vertices.
return new int[] { Math.round(one.x), Math.round(one.y), 0, Math.round(two.x), Math.round(two.y), 0, Math.round(three.x), Math.round(three.y), 0, Math.round(four.x), Math.round(four.y), 0, };
}
}
public class Update extends TimerTask {
Bitmap ball;
int x, y;
int mapStage = StaticVariables.getMap();
int towerCost = 200;
boolean start = false;
int x2 = 0;
int y2 = 0;
public int points = 50000;
public boolean stageClear = false;
boolean everythingSpawned = false;
public int life = 200;
private int space = 40;
public boolean stageLose = false;
public boolean upgrade = false;
List<Opponent> opponents = new ArrayList<Opponent>();
List<Tower> towers = new ArrayList<Tower>();
List<Bullet> bullets = new ArrayList<Bullet>();
List<SuperExplosion> explosions = new ArrayList<SuperExplosion>();
List<Path> paths = new ArrayList<Path>();
List<int[]> stages = new ArrayList<int[]>();
private List<Integer> minesPassive = new ArrayList<Integer>();
private List<Integer> removeBulletsIndex = new ArrayList<Integer>();
List<Integer> removeMinesPassive = new ArrayList<Integer>();
public int time = 16;
public int speed = 1;
public int stageLevel = 1;
public boolean placePossible = true;
private int timeTimes = 0;
private int bubble = 0;
public boolean wait = false;
public int mapLength;
boolean change = false, change1 = false, change2 = false, change3 = false;
double maxX, maxY, minX, minY, abstandX2, abstandX, abstandY2, abstandY, shortestSpacing, shortest, angleMaxX, angleMaxY, angleMinX, angleMinY, angleAbstandX, angleAbstandY;
int shortestIndex, index, spawnCounter = 0;
private MediaPlayer bubblePopSound;
private int tower = 0;
int nextImage = 0;
private boolean normalSpeed = true;
float invisability = 1;
private int upgradeBarDiff = 0;
private boolean hideUpgradeBar = false;
public int iceBallRotation;
private int explosionTime;
private List<MinePlace> minesPlaced = new ArrayList<MinePlace>();
private int gameLocation = 0;
Localizer localizer;
int testCounter;
boolean load = true;
private boolean placeOrReleaseItem = false;
double viewWidth, viewHeight;
MergeSort mergeSort = new MergeSort();
GLRenderer glRenderer2;
public List<Integer> getMinesPassive () {
return this.minesPassive;
}
public void setMinesPassive (int index2, int minesPassive) {
this.minesPassive.set(index2, minesPassive);
}
public void addMinesPassive (int minesPassive) {
this.minesPassive.add(minesPassive);
}
public void addMinesPassive (int i, Integer minesPassive) {
this.minesPassive.add(i, minesPassive);
}
}
I hope you know a method to improve the drawing speed.
Thank you in advance!
It is a bit hard to say how to increase performance in your case. Too much noise in code from my perspective. But generally speaking there are some basic tips on how to increase performance during rendering:
- avoid unnecessary OpenGl state machine changes
- avoid unnecessary OpenGl state querying (e.g. GLES20.glGetAttribLocation())
- avoid memory allocations during rendering
- use simplest shaders possible
- use texture atlases to avoid necessary texture binds
- use VBOs whenever possible
For more information on subject try to read https://www.opengl.org/wiki/Performance. Or see this talk https://www.youtube.com/watch?v=YLVbLVtjDDw.
You may also consider using libGDX http://libgdx.badlogicgames.com/ it will handle drawing sprites efficient way for you.
I'm writing a Raytracer in Java, I've gotten to the point where I can create objects, rays, test for intersections and then colour pixels. I've also got some basic anti aliasing done. My problem is that if a create a sphere, which should be in the centre of the world (i.e 0.0, 0.0, 0.0) and then draw the image, I end up with a picture like this.
When the red circle should be in the middle of the image.
Main method
public static void main(String[] args) {
System.out.println("Rendering...");
long start = System.nanoTime();
// Setting up the size of the image to be rendered
world = new World(1920, 1080, 1.0);
image = new Image("image.png");
sampler = new SimpleSampler(4);
projector = new OrthographicProjector();
// Main loop of program, goes through each pixel in image and assigns a colour value
for (int y = 0; y < world.viewPlane.height; y++) {
for (int x = 0; x < world.viewPlane.width; x++) {
// Render pixel colour
trace(x, y);
}
}
image.saveImage("PNG");
long end = System.nanoTime();
System.out.print("Loop Time = " + ((end - start)/1000000000.0f));
}
Trace method
public static void trace(int x, int y) {
Colour colour = new Colour();
//int colour = RayTracer.world.backgroundColour.toInteger();
for (int col = 0; col < sampler.samples; col++) {
for (int row = 0; row < sampler.samples; row++) {
Point2D point = sampler.sample(row, col, x, y);
Ray ray = projector.createRay(point);
double min = Double.MAX_VALUE;
Colour tempColour = new Colour();
for (int i = 0; i < world.worldObjects.size(); i++) {
double temp = world.worldObjects.get(i).intersect(ray);
if (temp != 0 && temp < min) {
min = temp;
tempColour = world.worldObjects.get(i).colour;
}
}
colour.add(tempColour);
}
}
colour.divide(sampler.samples*sampler.samples);
image.buffer.setRGB(x, y, colour.toInteger());
}
World.java
public class World {
public ViewPlane viewPlane;
public ArrayList<Renderable> worldObjects;
public Colour backgroundColour;
public World(int width, int height, double size) {
viewPlane = new ViewPlane(width, height, size);
backgroundColour = new Colour(0.0f, 0.0f, 0.0f);
worldObjects = new ArrayList<Renderable>();
worldObjects.add(new Sphere(new Point3D(0.0, 0.0, 0.0), 50, new Colour(1.0f, 0.0f, 0.0f)));
//worldObjects.add(new Sphere(new Point3D(-150.0, 0.0, 0.0), 50, new Colour(1.0f, 0.0f, 0.0f)));
//worldObjects.add(new Sphere(new Point3D(0.0, -540.0, 0.0), 50, new Colour(0.0f, 1.0f, 0.0f)));
}
}
SimpleSampler.java
public class SimpleSampler extends Sampler {
public SimpleSampler(int samples) {
this.samples = samples;
}
public Point2D sample(int row, int col, int x, int y) {
Point2D point = new Point2D(
x - RayTracer.world.viewPlane.width / 2 + (col + 0.5) / samples,
y - RayTracer.world.viewPlane.width / 2 + (row + 0.5) / samples);
return point;
}
}
OrthographicProjector.java
public class OrthographicProjector extends Projector{
public Ray createRay(Point2D point) {
Ray ray = new Ray();
ray.origin = new Point3D(
RayTracer.world.viewPlane.size * point.x,
RayTracer.world.viewPlane.size * point.y,
100);
ray.direction = new Vector3D(0.0, 0.0, -1.0);
return ray;
}
}
I have a feeling that somewhere along the way I've mixed an x with a y and this has rotated the image, but I haven't been able to track down the problem. If you would like to see any more of my code I would be happy to show it.
In SimpleSampler.java:
Point2D point = new Point2D(
x - RayTracer.world.viewPlane.width / 2 + (col + 0.5) / samples,
y - RayTracer.world.viewPlane.width / 2 + (row + 0.5) / samples);
You use width for both coordinates. Maybe you should use width and height.
I'm trying to draw a circle in LWJGL, but when I draw I try to draw it, it makes a shape that's more like an oval rather than a circle. Also, when I change my circleVertexCount 350+, the shape like flips out. I'm really not sure how the code works that creates the vertices(I have taken Geometry and I know the basic trig ratios). I haven't really found that good of tutorials on creating circles. Here's my code:
public class Circles {
// Setup variables
private int WIDTH = 800;
private int HEIGHT = 600;
private String title = "Circle";
private float fXOffset;
private int vbo = 0;
private int vao = 0;
int circleVertexCount = 300;
float[] vertexData = new float[(circleVertexCount + 1) * 4];
public Circles() {
setupOpenGL();
setupQuad();
while (!Display.isCloseRequested()) {
loop();
adjustVertexData();
Display.update();
Display.sync(60);
}
Display.destroy();
}
public void setupOpenGL() {
try {
Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT));
Display.setTitle(title);
Display.create();
} catch (LWJGLException e) {
e.printStackTrace();
System.exit(-1);
}
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
}
public void setupQuad() {
float r = 0.1f;
float x;
float y;
float offSetX = 0f;
float offSetY = 0f;
double theta = 2.0 * Math.PI;
vertexData[0] = (float) Math.sin(theta / circleVertexCount) * r + offSetX;
vertexData[1] = (float) Math.cos(theta / circleVertexCount) * r + offSetY;
for (int i = 2; i < 400; i += 2) {
double angle = theta * i / circleVertexCount;
x = (float) Math.cos(angle) * r;
vertexData[i] = x + offSetX;
}
for (int i = 3; i < 404; i += 2) {
double angle = Math.PI * 2 * i / circleVertexCount;
y = (float) Math.sin(angle) * r;
vertexData[i] = y + offSetY;
}
FloatBuffer vertexBuffer = BufferUtils.createFloatBuffer(vertexData.length);
vertexBuffer.put(vertexData);
vertexBuffer.flip();
vao = glGenVertexArrays();
glBindVertexArray(vao);
vbo = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER,vertexBuffer, GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, false, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
public void loop() {
glClear(GL_COLOR_BUFFER_BIT);
glBindVertexArray(vao);
glEnableVertexAttribArray(0);
glDrawArrays(GL_TRIANGLE_FAN, 0, vertexData.length / 2);
glDisableVertexAttribArray(0);
glBindVertexArray(0);
}
public static void main(String[] args) {
new Circles();
}
private void adjustVertexData() {
float newData[] = new float[vertexData.length];
System.arraycopy(vertexData, 0, newData, 0, vertexData.length);
if(Keyboard.isKeyDown(Keyboard.KEY_W)) {
fXOffset += 0.05f;
} else if(Keyboard.isKeyDown(Keyboard.KEY_S)) {
fXOffset -= 0.05f;
}
for(int i = 0; i < vertexData.length; i += 2) {
newData[i] += fXOffset;
}
FloatBuffer newDataBuffer = BufferUtils.createFloatBuffer(newData.length);
newDataBuffer.put(newData);
newDataBuffer.flip();
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferSubData(GL_ARRAY_BUFFER, 0, newDataBuffer);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
}
300 Vertex Count(This is my main problem)
400 Vertex Count - I removed this image, it's bugged out, should be a tiny sliver cut out from the right, like a secant
500 Vertex Count
Each 100, it removes more and more of the circle, and so on.
One of your problems is this:
for (int i = 2; i < 400; i += 2) {
double angle = theta * i / circleVertexCount;
x = (float) Math.cos(angle) * r;
vertexData[i] = x + offSetX;
}
for (int i = 3; i < 404; i += 2) {
double angle = Math.PI * 2 * i / circleVertexCount;
y = (float) Math.sin(angle) * r;
vertexData[i] = y + offSetY;
}
You are using a different value for angle for the x and y position of each vertex.
You could try this instead:
for (int i = 0; i <= circleVertexCount; i++) {
double angle = i * theta / circleVertexCount;
x = (float) Math.cos(angle) * r;
y = (float) Math.sin(angle) * r;
vertexData[i * 2] = x + offSetX;
vertexData[i * 2 + 1] = y + offSetY;
}
The reason part of your circle was being cut out at higher vertex counts was the i < 400 in your for loops, so I have changed it to i <= circleVertexCount.
Another problem is that your window is not square, and you are not using a shader (or the deprecated built in matrices) to correct this. This means that one unit up looks a different length than one unit right, resulting in an oval instead of a circle. To fix this you could multiply your vertex x position by your display height divided by your display width, preferably in a shader.
I would like to know if its possible to draw a Arc on a graphics Panel using a gradient and how I would go about it.
My end goal would be to rotate the arc in a full circle so it would be similar to a rotating loading circle. However it is not a loading bar. It would be a background of a custom JButton.
Any suggestions to alternatives that would create a similar effect would be appreciated.
This is similar to what oi want to draw. Keep in mind that it will be "rotating"
public class TestArc {
public static void main(String[] args) {
new TestArc();
}
public TestArc() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int radius = Math.min(getWidth(), getHeight());
int x = (getWidth() - radius) / 2;
int y = (getHeight() - radius) / 2;
RadialGradientPaint rgp = new RadialGradientPaint(
new Point(getWidth() / 2, getHeight() / 2),
radius,
new float[]{0f, 1f},
new Color[]{Color.RED, Color.YELLOW}
);
g2d.setPaint(rgp);
g2d.fill(new Arc2D.Float(x, y, radius, radius, 0, 45, Arc2D.PIE));
g2d.dispose();
}
}
}
You might like to have a look at 2D Graphics for more info
Updated after additional input
So you want a conical fill effect then...
The implementation I have comes from Harmonic Code, but I can't find a direct reference to it (I think it's part of his (excellent) series), but you can see the source code here
Now. I had issues with the angles as it appears that 0 starts at the top point (not the left) and it doesn't like negative angles...you might have better luck, but what I did was create a basic buffer at a position I could easily get working and then rotate the graphics context using an AffineTransformation...
public class TestArc {
public static void main(String[] args) {
new TestArc();
}
public TestArc() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private float angle = 0;
private float extent = 270;
private BufferedImage buffer;
public TestPane() {
Timer timer = new Timer(125, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
angle -= 5;
if (angle > 360) {
angle = 0;
}
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(false);
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected BufferedImage getBuffer() {
if (buffer == null) {
int radius = Math.min(getWidth(), getHeight());
int x = (getWidth() - radius) / 2;
int y = (getHeight() - radius) / 2;
buffer = new BufferedImage(radius, radius, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = buffer.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
float startAngle = 0;
Color start = new Color(0, 128, 0, 128);
Color end = new Color(0, 128, 0, 0);
ConicalGradientPaint rgp = new ConicalGradientPaint(
true,
new Point(getWidth() / 2, getHeight() / 2),
0.5f,
new float[]{startAngle, extent},
new Color[]{start, end});
g2d.setPaint(rgp);
g2d.fill(new Arc2D.Float(x, y, radius, radius, startAngle + 90, -extent, Arc2D.PIE));
// g2d.fill(new Ellipse2D.Float(0, 0, radius, radius));
g2d.dispose();
g2d.dispose();
}
return buffer;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int radius = Math.min(getWidth(), getHeight());
int x = (getWidth()) / 2;
int y = (getHeight()) / 2;
BufferedImage buffer = getBuffer();
g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(angle), x, y));
x = (getWidth() - buffer.getWidth()) / 2;
y = (getHeight() - buffer.getHeight()) / 2;
g2d.drawImage(buffer, x, y, this);
g2d.dispose();
}
}
public final class ConicalGradientPaint implements java.awt.Paint {
private final java.awt.geom.Point2D CENTER;
private final double[] FRACTION_ANGLES;
private final double[] RED_STEP_LOOKUP;
private final double[] GREEN_STEP_LOOKUP;
private final double[] BLUE_STEP_LOOKUP;
private final double[] ALPHA_STEP_LOOKUP;
private final java.awt.Color[] COLORS;
private static final float INT_TO_FLOAT_CONST = 1f / 255f;
/**
* Standard constructor which takes the FRACTIONS in values from 0.0f to
* 1.0f
*
* #param CENTER
* #param GIVEN_FRACTIONS
* #param GIVEN_COLORS
* #throws IllegalArgumentException
*/
public ConicalGradientPaint(final java.awt.geom.Point2D CENTER, final float[] GIVEN_FRACTIONS, final java.awt.Color[] GIVEN_COLORS) throws IllegalArgumentException {
this(false, CENTER, 0.0f, GIVEN_FRACTIONS, GIVEN_COLORS);
}
/**
* Enhanced constructor which takes the FRACTIONS in degress from 0.0f to
* 360.0f and also an GIVEN_OFFSET in degrees around the rotation CENTER
*
* #param USE_DEGREES
* #param CENTER
* #param GIVEN_OFFSET
* #param GIVEN_FRACTIONS
* #param GIVEN_COLORS
* #throws IllegalArgumentException
*/
public ConicalGradientPaint(final boolean USE_DEGREES, final java.awt.geom.Point2D CENTER, final float GIVEN_OFFSET, final float[] GIVEN_FRACTIONS, final java.awt.Color[] GIVEN_COLORS) throws IllegalArgumentException {
// Check that fractions and colors are of the same size
if (GIVEN_FRACTIONS.length != GIVEN_COLORS.length) {
throw new IllegalArgumentException("Fractions and colors must be equal in size");
}
final java.util.ArrayList<Float> FRACTION_LIST = new java.util.ArrayList<Float>(GIVEN_FRACTIONS.length);
final float OFFSET;
if (USE_DEGREES) {
final double DEG_FRACTION = 1f / 360f;
if (Double.compare((GIVEN_OFFSET * DEG_FRACTION), -0.5) == 0) {
OFFSET = -0.5f;
} else if (Double.compare((GIVEN_OFFSET * DEG_FRACTION), 0.5) == 0) {
OFFSET = 0.5f;
} else {
OFFSET = (float) (GIVEN_OFFSET * DEG_FRACTION);
}
for (float fraction : GIVEN_FRACTIONS) {
FRACTION_LIST.add((float) (fraction * DEG_FRACTION));
}
} else {
// Now it seems to work with rotation of 0.5f, below is the old code to correct the problem
// if (GIVEN_OFFSET == -0.5)
// {
// // This is needed because of problems in the creation of the Raster
// // with a angle offset of exactly -0.5
// OFFSET = -0.49999f;
// }
// else if (GIVEN_OFFSET == 0.5)
// {
// // This is needed because of problems in the creation of the Raster
// // with a angle offset of exactly +0.5
// OFFSET = 0.499999f;
// }
// else
{
OFFSET = GIVEN_OFFSET;
}
for (float fraction : GIVEN_FRACTIONS) {
FRACTION_LIST.add(fraction);
}
}
// Check for valid offset
if (OFFSET > 0.5f || OFFSET < -0.5f) {
throw new IllegalArgumentException("Offset has to be in the range of -0.5 to 0.5");
}
// Adjust fractions and colors array in the case where startvalue != 0.0f and/or endvalue != 1.0f
final java.util.List<java.awt.Color> COLOR_LIST = new java.util.ArrayList<java.awt.Color>(GIVEN_COLORS.length);
COLOR_LIST.addAll(java.util.Arrays.asList(GIVEN_COLORS));
// Assure that fractions start with 0.0f
if (FRACTION_LIST.get(0) != 0.0f) {
FRACTION_LIST.add(0, 0.0f);
final java.awt.Color TMP_COLOR = COLOR_LIST.get(0);
COLOR_LIST.add(0, TMP_COLOR);
}
// Assure that fractions end with 1.0f
if (FRACTION_LIST.get(FRACTION_LIST.size() - 1) != 1.0f) {
FRACTION_LIST.add(1.0f);
COLOR_LIST.add(GIVEN_COLORS[0]);
}
// Recalculate the fractions and colors with the given offset
final java.util.Map<Float, java.awt.Color> FRACTION_COLORS = recalculate(FRACTION_LIST, COLOR_LIST, OFFSET);
// Clear the original FRACTION_LIST and COLOR_LIST
FRACTION_LIST.clear();
COLOR_LIST.clear();
// Sort the hashmap by fraction and add the values to the FRACION_LIST and COLOR_LIST
final java.util.SortedSet<Float> SORTED_FRACTIONS = new java.util.TreeSet<Float>(FRACTION_COLORS.keySet());
final java.util.Iterator<Float> ITERATOR = SORTED_FRACTIONS.iterator();
while (ITERATOR.hasNext()) {
final float CURRENT_FRACTION = ITERATOR.next();
FRACTION_LIST.add(CURRENT_FRACTION);
COLOR_LIST.add(FRACTION_COLORS.get(CURRENT_FRACTION));
}
// Set the values
this.CENTER = CENTER;
COLORS = COLOR_LIST.toArray(new java.awt.Color[]{});
// Prepare lookup table for the angles of each fraction
final int MAX_FRACTIONS = FRACTION_LIST.size();
this.FRACTION_ANGLES = new double[MAX_FRACTIONS];
for (int i = 0; i < MAX_FRACTIONS; i++) {
FRACTION_ANGLES[i] = FRACTION_LIST.get(i) * 360;
}
// Prepare lookup tables for the color stepsize of each color
RED_STEP_LOOKUP = new double[COLORS.length];
GREEN_STEP_LOOKUP = new double[COLORS.length];
BLUE_STEP_LOOKUP = new double[COLORS.length];
ALPHA_STEP_LOOKUP = new double[COLORS.length];
for (int i = 0; i < (COLORS.length - 1); i++) {
RED_STEP_LOOKUP[i] = ((COLORS[i + 1].getRed() - COLORS[i].getRed()) * INT_TO_FLOAT_CONST) / (FRACTION_ANGLES[i + 1] - FRACTION_ANGLES[i]);
GREEN_STEP_LOOKUP[i] = ((COLORS[i + 1].getGreen() - COLORS[i].getGreen()) * INT_TO_FLOAT_CONST) / (FRACTION_ANGLES[i + 1] - FRACTION_ANGLES[i]);
BLUE_STEP_LOOKUP[i] = ((COLORS[i + 1].getBlue() - COLORS[i].getBlue()) * INT_TO_FLOAT_CONST) / (FRACTION_ANGLES[i + 1] - FRACTION_ANGLES[i]);
ALPHA_STEP_LOOKUP[i] = ((COLORS[i + 1].getAlpha() - COLORS[i].getAlpha()) * INT_TO_FLOAT_CONST) / (FRACTION_ANGLES[i + 1] - FRACTION_ANGLES[i]);
}
}
/**
* Recalculates the fractions in the FRACTION_LIST and their associated
* colors in the COLOR_LIST with a given OFFSET. Because the conical
* gradients always starts with 0 at the top and clockwise direction you
* could rotate the defined conical gradient from -180 to 180 degrees which
* equals values from -0.5 to +0.5
*
* #param FRACTION_LIST
* #param COLOR_LIST
* #param OFFSET
* #return Hashmap that contains the recalculated fractions and colors after
* a given rotation
*/
private java.util.HashMap<Float, java.awt.Color> recalculate(final java.util.List<Float> FRACTION_LIST, final java.util.List<java.awt.Color> COLOR_LIST, final float OFFSET) {
// Recalculate the fractions and colors with the given offset
final int MAX_FRACTIONS = FRACTION_LIST.size();
final java.util.HashMap<Float, java.awt.Color> FRACTION_COLORS = new java.util.HashMap<Float, java.awt.Color>(MAX_FRACTIONS);
for (int i = 0; i < MAX_FRACTIONS; i++) {
// Add offset to fraction
final float TMP_FRACTION = FRACTION_LIST.get(i) + OFFSET;
// Color related to current fraction
final java.awt.Color TMP_COLOR = COLOR_LIST.get(i);
// Check each fraction for limits (0...1)
if (TMP_FRACTION <= 0) {
FRACTION_COLORS.put(1.0f + TMP_FRACTION + 0.0001f, TMP_COLOR);
final float NEXT_FRACTION;
final java.awt.Color NEXT_COLOR;
if (i < MAX_FRACTIONS - 1) {
NEXT_FRACTION = FRACTION_LIST.get(i + 1) + OFFSET;
NEXT_COLOR = COLOR_LIST.get(i + 1);
} else {
NEXT_FRACTION = 1 - FRACTION_LIST.get(0) + OFFSET;
NEXT_COLOR = COLOR_LIST.get(0);
}
if (NEXT_FRACTION > 0) {
final java.awt.Color NEW_FRACTION_COLOR = getColorFromFraction(TMP_COLOR, NEXT_COLOR, (int) ((NEXT_FRACTION - TMP_FRACTION) * 10000), (int) ((-TMP_FRACTION) * 10000));
FRACTION_COLORS.put(0.0f, NEW_FRACTION_COLOR);
FRACTION_COLORS.put(1.0f, NEW_FRACTION_COLOR);
}
} else if (TMP_FRACTION >= 1) {
FRACTION_COLORS.put(TMP_FRACTION - 1.0f - 0.0001f, TMP_COLOR);
final float PREVIOUS_FRACTION;
final java.awt.Color PREVIOUS_COLOR;
if (i > 0) {
PREVIOUS_FRACTION = FRACTION_LIST.get(i - 1) + OFFSET;
PREVIOUS_COLOR = COLOR_LIST.get(i - 1);
} else {
PREVIOUS_FRACTION = FRACTION_LIST.get(MAX_FRACTIONS - 1) + OFFSET;
PREVIOUS_COLOR = COLOR_LIST.get(MAX_FRACTIONS - 1);
}
if (PREVIOUS_FRACTION < 1) {
final java.awt.Color NEW_FRACTION_COLOR = getColorFromFraction(TMP_COLOR, PREVIOUS_COLOR, (int) ((TMP_FRACTION - PREVIOUS_FRACTION) * 10000), (int) (TMP_FRACTION - 1.0f) * 10000);
FRACTION_COLORS.put(1.0f, NEW_FRACTION_COLOR);
FRACTION_COLORS.put(0.0f, NEW_FRACTION_COLOR);
}
} else {
FRACTION_COLORS.put(TMP_FRACTION, TMP_COLOR);
}
}
// Clear the original FRACTION_LIST and COLOR_LIST
FRACTION_LIST.clear();
COLOR_LIST.clear();
return FRACTION_COLORS;
}
/**
* With the START_COLOR at the beginning and the DESTINATION_COLOR at the
* end of the given RANGE the method will calculate and return the color
* that equals the given VALUE. e.g. a START_COLOR of BLACK (R:0, G:0, B:0,
* A:255) and a DESTINATION_COLOR of WHITE(R:255, G:255, B:255, A:255) with
* a given RANGE of 100 and a given VALUE of 50 will return the color that
* is exactly in the middle of the gradient between black and white which is
* gray(R:128, G:128, B:128, A:255) So this method is really useful to
* calculate colors in gradients between two given colors.
*
* #param START_COLOR
* #param DESTINATION_COLOR
* #param RANGE
* #param VALUE
* #return Color calculated from a range of values by given value
*/
public java.awt.Color getColorFromFraction(final java.awt.Color START_COLOR, final java.awt.Color DESTINATION_COLOR, final int RANGE, final int VALUE) {
final float SOURCE_RED = START_COLOR.getRed() * INT_TO_FLOAT_CONST;
final float SOURCE_GREEN = START_COLOR.getGreen() * INT_TO_FLOAT_CONST;
final float SOURCE_BLUE = START_COLOR.getBlue() * INT_TO_FLOAT_CONST;
final float SOURCE_ALPHA = START_COLOR.getAlpha() * INT_TO_FLOAT_CONST;
final float DESTINATION_RED = DESTINATION_COLOR.getRed() * INT_TO_FLOAT_CONST;
final float DESTINATION_GREEN = DESTINATION_COLOR.getGreen() * INT_TO_FLOAT_CONST;
final float DESTINATION_BLUE = DESTINATION_COLOR.getBlue() * INT_TO_FLOAT_CONST;
final float DESTINATION_ALPHA = DESTINATION_COLOR.getAlpha() * INT_TO_FLOAT_CONST;
final float RED_DELTA = DESTINATION_RED - SOURCE_RED;
final float GREEN_DELTA = DESTINATION_GREEN - SOURCE_GREEN;
final float BLUE_DELTA = DESTINATION_BLUE - SOURCE_BLUE;
final float ALPHA_DELTA = DESTINATION_ALPHA - SOURCE_ALPHA;
final float RED_FRACTION = RED_DELTA / RANGE;
final float GREEN_FRACTION = GREEN_DELTA / RANGE;
final float BLUE_FRACTION = BLUE_DELTA / RANGE;
final float ALPHA_FRACTION = ALPHA_DELTA / RANGE;
//System.out.println(DISTANCE + " " + CURRENT_FRACTION);
return new java.awt.Color(SOURCE_RED + RED_FRACTION * VALUE, SOURCE_GREEN + GREEN_FRACTION * VALUE, SOURCE_BLUE + BLUE_FRACTION * VALUE, SOURCE_ALPHA + ALPHA_FRACTION * VALUE);
}
#Override
public java.awt.PaintContext createContext(final java.awt.image.ColorModel COLOR_MODEL, final java.awt.Rectangle DEVICE_BOUNDS, final java.awt.geom.Rectangle2D USER_BOUNDS, final java.awt.geom.AffineTransform TRANSFORM, final java.awt.RenderingHints HINTS) {
final java.awt.geom.Point2D TRANSFORMED_CENTER = TRANSFORM.transform(CENTER, null);
return new ConicalGradientPaintContext(TRANSFORMED_CENTER);
}
#Override
public int getTransparency() {
return java.awt.Transparency.TRANSLUCENT;
}
private final class ConicalGradientPaintContext implements java.awt.PaintContext {
final private java.awt.geom.Point2D CENTER;
public ConicalGradientPaintContext(final java.awt.geom.Point2D CENTER) {
this.CENTER = new java.awt.geom.Point2D.Double(CENTER.getX(), CENTER.getY());
}
#Override
public void dispose() {
}
#Override
public java.awt.image.ColorModel getColorModel() {
return java.awt.image.ColorModel.getRGBdefault();
}
#Override
public java.awt.image.Raster getRaster(final int X, final int Y, final int TILE_WIDTH, final int TILE_HEIGHT) {
final double ROTATION_CENTER_X = -X + CENTER.getX();
final double ROTATION_CENTER_Y = -Y + CENTER.getY();
final int MAX = FRACTION_ANGLES.length;
// Create raster for given colormodel
final java.awt.image.WritableRaster RASTER = getColorModel().createCompatibleWritableRaster(TILE_WIDTH, TILE_HEIGHT);
// Create data array with place for red, green, blue and alpha values
int[] data = new int[(TILE_WIDTH * TILE_HEIGHT * 4)];
double dx;
double dy;
double distance;
double angle;
double currentRed = 0;
double currentGreen = 0;
double currentBlue = 0;
double currentAlpha = 0;
for (int py = 0; py < TILE_HEIGHT; py++) {
for (int px = 0; px < TILE_WIDTH; px++) {
// Calculate the distance between the current position and the rotation angle
dx = px - ROTATION_CENTER_X;
dy = py - ROTATION_CENTER_Y;
distance = Math.sqrt(dx * dx + dy * dy);
// Avoid division by zero
if (distance == 0) {
distance = 1;
}
// 0 degree on top
angle = Math.abs(Math.toDegrees(Math.acos(dx / distance)));
if (dx >= 0 && dy <= 0) {
angle = 90.0 - angle;
} else if (dx >= 0 && dy >= 0) {
angle += 90.0;
} else if (dx <= 0 && dy >= 0) {
angle += 90.0;
} else if (dx <= 0 && dy <= 0) {
angle = 450.0 - angle;
}
// Check for each angle in fractionAngles array
for (int i = 0; i < (MAX - 1); i++) {
if ((angle >= FRACTION_ANGLES[i])) {
currentRed = COLORS[i].getRed() * INT_TO_FLOAT_CONST + (angle - FRACTION_ANGLES[i]) * RED_STEP_LOOKUP[i];
currentGreen = COLORS[i].getGreen() * INT_TO_FLOAT_CONST + (angle - FRACTION_ANGLES[i]) * GREEN_STEP_LOOKUP[i];
currentBlue = COLORS[i].getBlue() * INT_TO_FLOAT_CONST + (angle - FRACTION_ANGLES[i]) * BLUE_STEP_LOOKUP[i];
currentAlpha = COLORS[i].getAlpha() * INT_TO_FLOAT_CONST + (angle - FRACTION_ANGLES[i]) * ALPHA_STEP_LOOKUP[i];
continue;
}
}
// Fill data array with calculated color values
final int BASE = (py * TILE_WIDTH + px) * 4;
data[BASE + 0] = (int) (currentRed * 255);
data[BASE + 1] = (int) (currentGreen * 255);
data[BASE + 2] = (int) (currentBlue * 255);
data[BASE + 3] = (int) (currentAlpha * 255);
}
}
// Fill the raster with the data
RASTER.setPixels(0, 0, TILE_WIDTH, TILE_HEIGHT, data);
return RASTER;
}
}
}
}
I am trying to paint a cube on a JFrame.
Sounds simple, but lags a lot. The 7th and 8th lines usually flash pretty bad.
here is the code:
http://pastebin.com/ncDasST6
if someone can give me a hint or two on how to stop this lag from occurring, that would be great :D.
Originally was for Applet, but i wanted it to execute through a .jar file.
Also, any way to add an Applet to a JFrame?
I tried doing: add(new Rotational()); //name of JApplet it is based off of.
Thanks, Fire
Does this variant work to your expectation? There are a number of changes which I did not bother to document (as I was 'just playing' with the code). Do a diff. to reveal the extent and nature of the changes.
It shows no lag or rendering artifacts here at 700x700.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.border.EmptyBorder;
public class Square extends JPanel implements MouseListener,
MouseMotionListener {
private static final long serialVersionUID = 1L;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrame f = new JFrame("Cube Rotational");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Square square = new Square();
square.setBorder(new EmptyBorder(5,5,5,5));
f.setContentPane(square);
f.pack();
f.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Square() {
init();
setPreferredSize(new Dimension(700,700));
}
class Point3D {
public int x, y, z;
public Point3D(int X, int Y, int Z) {
x = X;
y = Y;
z = Z;
}
}
class Edge {
public int a, b;
public Edge(int A, int B) {
a = A;
b = B;
}
}
static int width, height;
static int mx, my;
static int azimuth = 45, elevation = 45;
static Point3D[] vertices;
static Edge[] edges;
public void init() {
width = 500;
height = 500;
vertices = new Point3D[8];
vertices[0] = new Point3D(-1, -1, -1);
vertices[1] = new Point3D(-1, -1, 1);
vertices[2] = new Point3D(-1, 1, -1);
vertices[3] = new Point3D(-1, 1, 1);
vertices[4] = new Point3D(1, 1, -1);
vertices[5] = new Point3D(1, 1, 1);
vertices[6] = new Point3D(1, -1, -1);
vertices[7] = new Point3D(1, -1, 1);
edges = new Edge[12];
edges[0] = new Edge(0, 1);
edges[1] = new Edge(0, 2);
edges[2] = new Edge(0, 6);
edges[3] = new Edge(1, 3);
edges[4] = new Edge(1, 7);
edges[5] = new Edge(2, 3);
edges[6] = new Edge(2, 4);
edges[7] = new Edge(3, 5);
edges[8] = new Edge(4, 5);
edges[9] = new Edge(4, 6);
edges[10] = new Edge(5, 7);
edges[11] = new Edge(6, 7);
setCursor(new Cursor(Cursor.HAND_CURSOR));
addMouseListener(this);
addMouseMotionListener(this);
setVisible(true);
}
void drawWireframe(Graphics g) {
double theta = Math.PI * azimuth / 180.0;
double phi = Math.PI * elevation / 180.0;
float cosT = (float) Math.cos(theta);
float sinT = (float) Math.sin(theta);
float cosP = (float) Math.cos(phi);
float sinP = (float) Math.sin(phi);
float cosTcosP = cosT * cosP;
float cosTsinP = cosT * sinP;
float sinTcosP = sinT * cosP;
float sinTsinP = sinT * sinP;
Point[] points;
points = new Point[vertices.length];
float scaleFactor = (getWidth() + getHeight()) / 8;
float near = (float) 6;
float nearToObj = 1.5f;
for (int j = 0; j < vertices.length; ++j) {
int x0 = vertices[j].x;
int y0 = vertices[j].y;
int z0 = vertices[j].z;
float x1 = cosT * x0 + sinT * z0;
float y1 = -sinTsinP * x0 + cosP * y0 + cosTsinP * z0;
float z1 = cosTcosP * z0 - sinTcosP * x0 - sinP * y0;
x1 = x1 * near / (z1 + near + nearToObj);
y1 = y1 * near / (z1 + near + nearToObj);
points[j] = new Point(
(int) (getWidth() / 2 + scaleFactor * x1 + 0.5),
(int) (getHeight() / 2 - scaleFactor * y1 + 0.5));
}
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.white);
for (int j = 0; j < edges.length; ++j) {
int x1 = points[edges[j].a].x;
int x2 = points[edges[j].b].x;
int y1 = points[edges[j].a].y;
int y2 = points[edges[j].b].y;
((Graphics2D) g).setStroke(new BasicStroke(5));
g.drawLine(x1, y1, x2, y2);
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
mx = e.getX();
my = e.getY();
e.consume();
}
public void mouseReleased(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
int new_mx = e.getX();
int new_my = e.getY();
azimuth -= new_mx - mx;
azimuth %= 360;
elevation += new_my - my;
elevation %= 360;
repaint();
mx = new_mx;
my = new_my;
repaint();
e.consume();
}
#Override
public void paintComponent(Graphics g) {
drawWireframe(g);
}
}
Originally was for Applet, but i wanted it to execute through a .jar file.
Good idea converting an applet to something more sensible, but note that an applet can (and usually should) be packed into a Jar.
Also, any way to add an Applet to a JFrame?
This is possible, relatively easy with this code (barring mixing Swing (JFrame) & AWT (Applet) components), but not the best way to go. It is better to create a hybrid like (for example) the subway applet/application.
By moving the custom rendering from the frame to a JPanel, the code has been partially transformed into a hybrid, since the panel can be added to a frame or applet (or window or dialog, or another panel or..).