Jump to content

  • Log In with Google      Sign In   
  • Create Account


axel1994

Member Since 24 Jun 2013
Offline Last Active Yesterday, 02:41 PM
-----

Topics I've Started

Drawing texture problem

25 December 2013 - 03:01 PM

Hello,

 

I got a problem when I'm trying to draw a texture on a object (a rectangle in this case)

I don't think there is any problem in the shaders, but I'll give them either way.

Vertex shader:

#version 330

layout (location=0) in vec3 position;
layout (location=1) in vec2 uvcoor0;

out vec2 uvcoor;

void main() {
	gl_Position = vec4(position, 1.0);
	uvcoor = uvcoor0;
}

Fragment shader:

#version 330

uniform sampler2D tex;
in vec2 uvcoor;                                                                 
                                                                                   
void main() {                                                                                  
	gl_FragColor = texture2D(tex, uvcoor.st);                                                 
}

The code I'm using:

For the uv buffer

here I have an struct where I store the length and the actual uv coordinates

texturecoor.len = 4;
Vector2f vec;
texturecoor.texcor = new Vector2f[4];
vec.x = 1;
vec.y = 1;
texturecoor.texcor[0] = vec;
vec.x = 0;
vec.y = 1;
texturecoor.texcor[1] = vec;
vec.x = 1;
vec.y = 0;
texturecoor.texcor[3] = vec;
vec.x = 0;
vec.y = 0;
texturecoor.texcor[2] = vec;

The vertex and index coordinates are located in an .obj file that I load.

That works correctly (since I can draw the rect with a color instead of a texture.

Here is the obj file,

The index int are read in the exact same order.

Each vertex line is in xyz

# Blender v2.69 (sub 0) OBJ File: ''
# www.blender.org

o Plane
v 1.000000 1.000000 0.000000
v -1.000000 1.000000 0.000000
v 1.000000 -1.000000 0.000000
v -1.000000 -1.000000 0.000000

f 2 3 0
f 1 0 3

Loading the texture I use:

str is the relative path, load_image returns an image object that stores the width, height and data

GLuint texture;
image img = load_image(str);

glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);

glTexImage2D(GL_TEXTURE_2D,0, GL_RGB, img.width, img.height, 0, GL_BGRA, GL_UNSIGNED_BYTE, img.data);

destroyImg(img);

return texture;

loading everything into opengl I use the code:

(this is after I loaded all data in the buffers)

but for reference, here is my loading of my uvbuffer

(ttx is the data of the uv coordinates)

glGenBuffers(1, &uvbuffer);

glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
glBufferData(GL_ARRAY_BUFFER,sizeof(ttx), ttx, GL_DYNAMIC_DRAW);
glGenVertexArrays(1,&vao);
glBindVertexArray(vao);

glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

if (uv) {
	glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
	glEnableVertexAttribArray(1);
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);
}

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexbuffer);
glBindVertexArray(0);

When rendering I bind the texture, bind the vao and draw all triangles: (nbElem is the number of index elements)

glActiveTexture(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
//bind the vao (didnt copy that line of code)
glDrawElements(GL_TRIANGLES, nbElem, GL_UNSIGNED_INT, 0);

The included pictures are:

the image I load in

the image resulting on the screen

(I got the image from some examples pictures that came with the image loading lib I'm using)

 

It's not correct, but it also draws the image twice.

Once normally and once turned 90 degrees

 

what I've tried doing is, changing the texture coordinates order.

But the order I have now (0,1,3,2) gives the best result.

 

I also have a world matrix to represent a camera.
I multiple this camera with only the vertices (not with the uv coordinates)

 

Even without using the camera, I get exactly the same result.

Another issue, which I believe is part of this problem.

 

If I zoom out with my camera, the texture changes.

The more zoomed out, the more correct the image is displaying.

 

I did check the camera. But without a texture the camera works perfectly.

 

My apologies if I didn't include enough information.

 

Attached File  img_cheryl.jpg   41.92KB   2 downloads

Attached File  tex.png   310.03KB   1 downloads


Opengl Linux

16 November 2013 - 09:19 AM

So, this is a pretty dumb question.

 

But how do I get Opengl 3.3+ running on linux.

 

Atm glxinfo gives me the info: 3.0 Mesa 8.0.5

My graphics driver is Nvidia geforce GT 630M (2GB)

 

I've tried (and still am trying) to get Mesa 9.2.3 running.

I've got problems installing it.

 

I do know that Mesa 10 will be released quite soon, which supports 3.3.

But there have to be different options.

 

I also found the linux x64 (amd64/em64t) display driver on Nvidia website. But I don't know whether it supports opengl 3.3+

 

What I do know is that on my windows partition I got opengl 4.0 running.


Code review Pong - Java

24 June 2013 - 02:21 PM

So perhaps an introduction first.

I'm Axel, 19 years old. From Belgium, Europe.

 

This year I was studying for engineering.

But I found that I have an big interest in Programming and the theory behind it.

 

Like lots of "kids", I like games. And making games sounds interesting.

This is an interest I have always had.

 

But now I wanted to test that interest, to know I'm actually serious about it.

 

(But that isn't my only interest, I'm interested in Computer science in general)

 

I did a lot of research this past half year. And I like it, just the fact that lots of people say that there is a big chance that you need to work long hours scares me.

 

This September I'm starting in Computer science. The bachelor is a bit of everything and after that I can still chose what direction I want to take.

(In my university I can chose: multimedia (with focus on game programming, If i saw it correctly), Human-computer interaction (which I don't find that interesting)and Databases (with lots of networking, which looks interesting as well), they also have AI but thats only Master after Master.

Software engineering is included in all programs.

 

I learned python in the engineering courses. An learned Java on my own, I bought a couple books. Read them, made every exercise.

So I started making little programs. And now I made my first "moving" game. 

 

I made it first in Slick. But I wanted to know how to do it without slick.

So I made the following code.

 

I know the code probably sucks, yet I'm still kind of proud.

But you can always improve.

 

I got some other questions and insecurities. (mainly because this year in engineering went really bad for me in certain ways I definitely didn't expect) . But I'll post those in another thread.

 

One note with my code: the gameloop code isn't mine.

I looked on how looping works, tried lots of different methods.

Then I realized that working with something like I have now would be great.

But I didn't know how to begin writing the code. So I looked around, found a great tutorial thread which showed this code.

I do understand every line from it, but it's still copied.

So now (I'm going for another classic like tetris, space invaders or duck hunt) I'm going to write something myself.

Now I know what the theory behind the gameloop is.

 

Thank you for reading/commenting. :)

package Pong_Original_no_slick;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;


public class Mainframe implements MouseListener, KeyListener {

	JFrame window = new JFrame();
	Menu menuscreen = new Menu();
	Pauses pausescreen = new Pauses();
	JLabel text = new JLabel();
	
	private boolean running = true;
	private boolean paused = false;
	
	public static final String gamename = "Original Pong!";
	public static final int menu = 0;
	public static final int play = 1;
	public static final int pause = 2;
	private int menuselect=menu;
	
	private static final int screenwidth = 1000;
	private static final int screenheight = 600;
	
	private String mouse = "no input!";
	
	double x;
	double y;
	
	private static final int panellength = 130;
	private static final int panelwidth = 20;
	private static final int ballsize = 10;
	
	private static final int savetyborder = 20;
	
	private static final int playerx = 20; 
	double playery = 20.0;
	
	private static final int AIx = 960; 
	int AIy = 20;
	
	double ballx = 500.0;
	double bally = 300.0;
	double ballspeedx = -1;
	double ballspeedy = -1;
	
	int scoreplayer = 0;
	int scoreAI = 0;
	
	private static final int scorex = 470;
	private static final int scorey = 40;
	
	Pongscreen pong;
	int addscreen = 0;
	int counter=0;
	
	public static void main(String[] args) {
		new Mainframe();
	}
	
	public Mainframe(){
		window.setTitle(gamename);
		window.setSize(screenwidth+20, screenheight+40);
		
		window.add(menuscreen);
		
		window.setVisible(true);
		window.addMouseListener(this);
		window.addKeyListener(this);
		
		runGameLoop();
	}
	
	private void getcoordinates(){
		Point a = MouseInfo.getPointerInfo().getLocation();
		SwingUtilities.convertPointFromScreen(a, menuscreen);
		x = a.getX();
		y = a.getY();
		
		mouse = "Xpos: " +x+ "Ypos: "+y;
	}
	
	private void updateGame(){
		if (menuselect==menu){
			getcoordinates();
			text.setText(mouse);
			
			menuscreen.add(text);
			
			menuscreen.revalidate();
			window.revalidate();
			
			menuscreen.repaint();
			window.repaint();
		}
		if (menuselect==pause){
			menuscreen.setVisible(false);
			pong.setVisible(false);
			
			window.add(pausescreen);
			
			pausescreen.setVisible(true);
			window.revalidate();
			window.repaint();
		}
		if (menuselect==play){
			menuscreen.setVisible(false);
			pausescreen.setVisible(false);
			
	        moveplayer();
			moveAI();
			moveball();
			collisiondetection();
			
			
		}

	}
	private void drawGame(float interpolation){
	    //gamePanel.setInterpolation(interpolation);
		pong = new Pongscreen(){
            public void paintComponent (Graphics g){
        	    g.setColor(Color.GREEN);
        	    g.drawRect(20, 20, 1000-2*20, 600-2*20);
        	    
        	    String score="player:"+scoreplayer+"  AI:"+scoreAI;
    			g.drawString(score,scorex,scorey);
    		
    			g.fillRect(playerx, (int) playery, panelwidth, panellength); //player
    			g.fillRect(AIx, AIy, panelwidth, panellength); //AI
    		
    			g.fillOval((int) ballx,(int) bally, ballsize, ballsize); //the ball
             }
        };
        
        window.setBackground(Color.BLACK);
        
        if (addscreen==0){
        	window.add(pong);
        	addscreen++;
        }
        
	    pong.revalidate();
	    pong.repaint();
	    
	    window.revalidate();
		window.repaint();
	}
	
	public void runGameLoop(){
		Thread loop = new Thread(){
			public void run(){
				gameLoop();
			}
		};
		loop.start();
	}
	
	private void gameLoop(){
	    final double GAME_HERTZ = 100.0;
	      
	    //Calculate how many ns each frame should take for our target game hertz.
	    final double TIME_BETWEEN_UPDATES = 1000000000 / GAME_HERTZ;
	      
	    //At the very most we will update the game this many times before a new render.
	    //If you're worried about visual hitches more than perfect timing, set this to 1.
	    final int MAX_UPDATES_BEFORE_RENDER = 1;
	      
	    //We will need the last update time.
	    double lastUpdateTime = System.nanoTime();
	      
	    //Store the last time we rendered.
	    double lastRenderTime = System.nanoTime();
	      
	    //If we are able to get as high as this FPS, don't render again.
	    final double TARGET_FPS = 100;
	    final double TARGET_TIME_BETWEEN_RENDERS = 1000000000 / TARGET_FPS;  
	    
		while(running){
			
			double now = System.nanoTime();
	        int updateCount = 0;
	         
	        if (!paused){
	        	//Do as many game updates as we need to, potentially playing catchup.
	            while( now - lastUpdateTime > TIME_BETWEEN_UPDATES && updateCount < MAX_UPDATES_BEFORE_RENDER ){
	               updateGame();
	               lastUpdateTime += TIME_BETWEEN_UPDATES;
	               updateCount++;
	            }
	            //If for some reason an update takes forever, we don't want to do an insane number of catchups.
	            //If you were doing some sort of game that needed to keep EXACT time, you would get rid of this.
	            if ( now - lastUpdateTime > TIME_BETWEEN_UPDATES)
	            {
	               lastUpdateTime = now - TIME_BETWEEN_UPDATES;
	            }
	         
	            //Render. To do so, we need to calculate interpolation for a smooth render.
	            float interpolation = Math.min(1.0f, (float) ((now - lastUpdateTime) / TIME_BETWEEN_UPDATES) );
	            drawGame(interpolation);
	            //drawGame(interpolation);
	            lastRenderTime = now;
	         
	            //Yield until it has been at least the target time between renders. This saves the CPU from hogging.
	            while ( now - lastRenderTime < TARGET_TIME_BETWEEN_RENDERS && now - lastUpdateTime < TIME_BETWEEN_UPDATES)
	            {
	               Thread.yield();
	            
	               //This stops the app from consuming all your CPU. It makes this slightly less accurate, but is worth it.
	               //You can remove this line and it will still work (better), your CPU just climbs on certain OSes.
	               //FYI on some OS's this can cause pretty bad stuttering. Scroll down and have a look at different peoples' solutions to this.
	               try {Thread.sleep(1);} catch(Exception e) {} 
	            
	               now = System.nanoTime();
	            }
	         }
		}
	}
	
	private void moveplayer(){
		counter=0;
		window.addKeyListener(new KeyListener(){
			@Override
			public void keyPressed(KeyEvent e) {
				int source = e.getKeyCode();
				if (source==KeyEvent.VK_UP){
					if ((playery> savetyborder+2)&&(counter<10)){
						playery-=1.2;
						counter++;
					}
				}
				if (source==KeyEvent.VK_DOWN){
					if ((playery<screenheight-savetyborder-panellength)&&(counter<10)){
						playery+=1.2;
						counter++;
					}
				}
			}

			@Override
			public void keyReleased(KeyEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void keyTyped(KeyEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
	}
	private void moveAI(){
		if ((bally<(AIy+panellength/2))&&(AIy> savetyborder)){ //goes up
			AIy-=1;
		} 
		if ((bally>(AIy+panellength/2))&&(AIy< screenheight-savetyborder-panellength)){ //goes down
			AIy+=1;
		}	
	}
	private void moveball(){
		//give ball movement
		ballx+=ballspeedx;
		bally+=ballspeedy;
	}
	private void collisiondetection(){
		//AI scores
		if (ballx==savetyborder){ 
			ballx=500;
			bally=300;
			scoreAI+=1;
			playsound();
		}
		//player scores
		if (ballx==screenwidth-savetyborder-ballsize){
			ballx=500;
			bally=300;
			scoreplayer+=1;
			playsound();
		}
		//connect with leftpanel
		if ((ballx==savetyborder+panelwidth)&&(bally>playery)&&(bally<playery+panellength)){
			ballspeedx*=-1;
			playsound();
		}
		
		//connect with rightpanel
		if ((ballx==screenwidth-savetyborder-panelwidth-ballsize)&&(bally>AIy)&&(bally<AIy+panellength)){
			ballspeedx*=-1;
			playsound();
		}
		
		//connect with top screen
		if (bally==savetyborder){
			ballspeedy*=-1;
			playsound();
		}
		
		//connect with bottomscreen
		if (bally==screenheight-savetyborder-ballsize){ //player scores
			ballspeedy*=-1;
			playsound();
		}
	}
	private void playsound(){
		try {
	
	        URL url = this.getClass().getClassLoader().getResource("ponga.wav");
	        AudioInputStream song = AudioSystem.getAudioInputStream(url);
	        
	        Clip clip = AudioSystem.getClip();
	        
	        clip.open(song);
	        clip.start();
	     } 
catch (Exception e) {} 
	}

	@Override
	public void mouseClicked(MouseEvent arg0) {
		if (((330<x) && (x<680)) && ((y>300)&&(y<345))){
			menuselect=play;
		}
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyPressed(KeyEvent e) {
		int source = e.getKeyCode();
		if (source==KeyEvent.VK_SPACE){
			menuselect=pause;
		}
		if (source==KeyEvent.VK_ENTER){
			menuselect=play;
		}
		
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyTyped(KeyEvent e) {
		
	}
}


package Pong_Original_no_slick;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JPanel;

public class Menu extends JPanel{
	
	@Override
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		
		setBackground(Color.BLACK);
		
		g.setFont(new Font("default", Font.BOLD, 30));
	    g.setColor(Color.GREEN);
		g.drawString("Welcome to the original Pong game!",260 ,270);
		g.drawString("Press here to play!",375 ,330);
		g.drawRect(330, 300, 350, 45); 
	}
	
}


package Pong_Original_no_slick;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JPanel;

public class Pauses extends JPanel{

	@Override
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		
		setBackground(Color.BLACK);
		
		g.setFont(new Font("default", Font.BOLD, 30));
	    g.setColor(Color.GREEN);
		g.drawString("Welcome to the original Pong game!",260 ,270);
		g.drawString("Game is paused, press enter to unpause!",225 ,330);
	}
	
}



package Pong_Original_no_slick;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JPanel;

public class Pongscreen extends JPanel{
	
	@Override
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		
		setBackground(Color.BLACK);
	    g.setColor(Color.GREEN);
	    
	    //g.drawRect(savetyborder, savetyborder, screenwidth-2*savetyborder, screenheight-2*savetyborder);
	    g.drawRect(20, 20, 1000-2*20, 600-2*20);
	}

}



PARTNERS