• Advertisement
  • Popular Tags

  • Popular Now

  • Advertisement
  • Similar Content

    • By tj8146
      I am using immediate mode for OpenGL and I am creating a 2D top down car game. I am trying to configure my game loop in order to get my car-like physics working on a square shape. I have working code but it is not doing as I want it to. I am not sure as to whether it is my game loop that is incorrect or my code for the square is incorrect, or maybe both! Could someone help because I have been trying to work this out for over a day now
      I have attached my .cpp file if you wish to run it for yourself.. 
      WinMain code:
      /******************* WIN32 FUNCTIONS ***************************/ int WINAPI WinMain( HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State { MSG msg; // Windows Message Structure bool done=false; // Bool Variable To Exit Loop Car car; car.x = 220; car.y = 140; car.dx = 0; car.dy = 0; car.ang = 0; AllocConsole(); FILE *stream; freopen_s(&stream, "CONOUT$", "w", stdout); // Create Our OpenGL Window if (!CreateGLWindow("OpenGL Win32 Example",screenWidth,screenHeight)) { return 0; // Quit If Window Was Not Created } while(!done) // Loop That Runs While done=FALSE { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting? { if (msg.message==WM_QUIT) // Have We Received A Quit Message? { done=true; // If So done=TRUE break; } else // If Not, Deal With Window Messages { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else // If There Are No Messages { if(keys[VK_ESCAPE]) done = true; void processKeys(Car& car); //process keyboard while (game_is_running) { loops = 0; while (GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP) { update(car); // update variables next_game_tick += SKIP_TICKS; loops++; } display(car); // Draw The Scene SwapBuffers(hDC); // Swap Buffers (Double Buffering) } } } // Shutdown KillGLWindow(); // Kill The Window return (int)(msg.wParam); // Exit The Program } //WIN32 Processes function - useful for responding to user inputs or other events. LRESULT CALLBACK WndProc( HWND hWnd, // Handle For This Window UINT uMsg, // Message For This Window WPARAM wParam, // Additional Message Information LPARAM lParam) // Additional Message Information { switch (uMsg) // Check For Windows Messages { case WM_CLOSE: // Did We Receive A Close Message? { PostQuitMessage(0); // Send A Quit Message return 0; // Jump Back } break; case WM_SIZE: // Resize The OpenGL Window { reshape(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width, HiWord=Height return 0; // Jump Back } break; case WM_LBUTTONDOWN: { mouse_x = LOWORD(lParam); mouse_y = screenHeight - HIWORD(lParam); LeftPressed = true; } break; case WM_LBUTTONUP: { LeftPressed = false; } break; case WM_MOUSEMOVE: { mouse_x = LOWORD(lParam); mouse_y = screenHeight - HIWORD(lParam); } break; case WM_KEYDOWN: // Is A Key Being Held Down? { keys[wParam] = true; // If So, Mark It As TRUE return 0; // Jump Back } break; case WM_KEYUP: // Has A Key Been Released? { keys[wParam] = false; // If So, Mark It As FALSE return 0; // Jump Back } break; } // Pass All Unhandled Messages To DefWindowProc return DefWindowProc(hWnd,uMsg,wParam,lParam); }  
      C++ and OpenGL code:
      int mouse_x=0, mouse_y=0; bool LeftPressed = false; int screenWidth=1080, screenHeight=960; bool keys[256]; float radiansFromDegrees(float deg) { return deg * (M_PI / 180.0f); } float degreesFromRadians(float rad) { return rad / (M_PI / 180.0f); } bool game_is_running = true; const int TICKS_PER_SECOND = 50; const int SKIP_TICKS = 1000 / TICKS_PER_SECOND; const int MAX_FRAMESKIP = 10; DWORD next_game_tick = GetTickCount(); int loops; typedef struct { float x, y; float dx, dy; float ang; }Car; //OPENGL FUNCTION PROTOTYPES void display(const Car& car); //called in winmain to draw everything to the screen void reshape(int width, int height); //called when the window is resized void init(); //called in winmain when the program starts. void processKeys(Car& car); //called in winmain to process keyboard input void update(Car& car); //called in winmain to update variables /************* START OF OPENGL FUNCTIONS ****************/ void display(const Car& car) { const float w = 50.0f; const float h = 50.0f; glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); glTranslatef(100, 100, 0); glBegin(GL_POLYGON); glVertex2f(car.x, car.y); glVertex2f(car.x + w, car.y); glVertex2f(car.x + w, car.y + h); glVertex2f(car.x, car.y + h); glEnd(); glFlush(); } void reshape(int width, int height) // Resize the OpenGL window { screenWidth = width; screenHeight = height; // to ensure the mouse coordinates match // we will use these values to set the coordinate system glViewport(0, 0, width, height); // Reset the current viewport glMatrixMode(GL_PROJECTION); // select the projection matrix stack glLoadIdentity(); // reset the top of the projection matrix to an identity matrix gluOrtho2D(0, screenWidth, 0, screenHeight); // set the coordinate system for the window glMatrixMode(GL_MODELVIEW); // Select the modelview matrix stack glLoadIdentity(); // Reset the top of the modelview matrix to an identity matrix } void init() { glClearColor(1.0, 1.0, 0.0, 0.0); //sets the clear colour to yellow //glClear(GL_COLOR_BUFFER_BIT) in the display function //will clear the buffer to this colour. } void processKeys(Car& car) { if (keys[VK_UP]) { float cdx = sinf(radiansFromDegrees(car.ang)); float cdy = -cosf(radiansFromDegrees(car.ang)); car.dx += cdx; car.dy += cdy; } if (keys[VK_DOWN]) { float cdx = sinf(radiansFromDegrees(car.ang)); float cdy = -cosf(radiansFromDegrees(car.ang)); car.dx += -cdx; car.dy += -cdy; } if (keys[VK_LEFT]) { car.ang -= 2; } if (keys[VK_RIGHT]) { car.ang += 2; } } void update(Car& car) { car.x += car.dx*next_game_tick; }  
      game.cpp
    • By tj8146
      I am using immediate mode for OpenGL and I am creating a 2D top down car game. I am trying to configure my game loop in order to get my car-like physics working on a square shape. I have working code but it is not doing as I want it to. I am not sure as to whether it is my game loop that is incorrect or my code for the square is incorrect, or maybe both! Could someone help because I have been trying to work this out for over a day now
      I have attached my .cpp file if you wish to run it for yourself.. 
       
      This is my C++ and OpenGL code:
      int mouse_x=0, mouse_y=0; bool LeftPressed = false; int screenWidth=1080, screenHeight=960; bool keys[256]; float radiansFromDegrees(float deg) { return deg * (M_PI / 180.0f); } float degreesFromRadians(float rad) { return rad / (M_PI / 180.0f); } bool game_is_running = true; const int TICKS_PER_SECOND = 50; const int SKIP_TICKS = 1000 / TICKS_PER_SECOND; const int MAX_FRAMESKIP = 10; DWORD next_game_tick = GetTickCount(); int loops; typedef struct { float x, y; float dx, dy; float ang; }Car; //OPENGL FUNCTION PROTOTYPES void display(const Car& car); //called in winmain to draw everything to the screen void reshape(int width, int height); //called when the window is resized void init(); //called in winmain when the program starts. void processKeys(Car& car); //called in winmain to process keyboard input void update(Car& car); //called in winmain to update variables /************* START OF OPENGL FUNCTIONS ****************/ void display(const Car& car) { const float w = 50.0f; const float h = 50.0f; glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); glTranslatef(100, 100, 0); glBegin(GL_POLYGON); glVertex2f(car.x, car.y); glVertex2f(car.x + w, car.y); glVertex2f(car.x + w, car.y + h); glVertex2f(car.x, car.y + h); glEnd(); glFlush(); } void reshape(int width, int height) // Resize the OpenGL window { screenWidth = width; screenHeight = height; // to ensure the mouse coordinates match // we will use these values to set the coordinate system glViewport(0, 0, width, height); // Reset the current viewport glMatrixMode(GL_PROJECTION); // select the projection matrix stack glLoadIdentity(); // reset the top of the projection matrix to an identity matrix gluOrtho2D(0, screenWidth, 0, screenHeight); // set the coordinate system for the window glMatrixMode(GL_MODELVIEW); // Select the modelview matrix stack glLoadIdentity(); // Reset the top of the modelview matrix to an identity matrix } void init() { glClearColor(1.0, 1.0, 0.0, 0.0); //sets the clear colour to yellow //glClear(GL_COLOR_BUFFER_BIT) in the display function //will clear the buffer to this colour. } void processKeys(Car& car) { if (keys[VK_UP]) { float cdx = sinf(radiansFromDegrees(car.ang)); float cdy = -cosf(radiansFromDegrees(car.ang)); car.dx += cdx; car.dy += cdy; } if (keys[VK_DOWN]) { float cdx = sinf(radiansFromDegrees(car.ang)); float cdy = -cosf(radiansFromDegrees(car.ang)); car.dx += -cdx; car.dy += -cdy; } if (keys[VK_LEFT]) { car.ang -= 2; } if (keys[VK_RIGHT]) { car.ang += 2; } } void update(Car& car) { car.x += car.dx*next_game_tick; } My WinMain code:
      /******************* WIN32 FUNCTIONS ***************************/ int WINAPI WinMain( HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State { MSG msg; // Windows Message Structure bool done=false; // Bool Variable To Exit Loop Car car; car.x = 220; car.y = 140; car.dx = 0; car.dy = 0; car.ang = 0; AllocConsole(); FILE *stream; freopen_s(&stream, "CONOUT$", "w", stdout); // Create Our OpenGL Window if (!CreateGLWindow("OpenGL Win32 Example",screenWidth,screenHeight)) { return 0; // Quit If Window Was Not Created } while(!done) // Loop That Runs While done=FALSE { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting? { if (msg.message==WM_QUIT) // Have We Received A Quit Message? { done=true; // If So done=TRUE break; } else // If Not, Deal With Window Messages { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else // If There Are No Messages { if(keys[VK_ESCAPE]) done = true; void processKeys(Car& car); //process keyboard while (game_is_running) { loops = 0; while (GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP) { update(car); // update variables next_game_tick += SKIP_TICKS; loops++; } display(car); // Draw The Scene SwapBuffers(hDC); // Swap Buffers (Double Buffering) } } } // Shutdown KillGLWindow(); // Kill The Window return (int)(msg.wParam); // Exit The Program } //WIN32 Processes function - useful for responding to user inputs or other events. LRESULT CALLBACK WndProc( HWND hWnd, // Handle For This Window UINT uMsg, // Message For This Window WPARAM wParam, // Additional Message Information LPARAM lParam) // Additional Message Information { switch (uMsg) // Check For Windows Messages { case WM_CLOSE: // Did We Receive A Close Message? { PostQuitMessage(0); // Send A Quit Message return 0; // Jump Back } break; case WM_SIZE: // Resize The OpenGL Window { reshape(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width, HiWord=Height return 0; // Jump Back } break; case WM_LBUTTONDOWN: { mouse_x = LOWORD(lParam); mouse_y = screenHeight - HIWORD(lParam); LeftPressed = true; } break; case WM_LBUTTONUP: { LeftPressed = false; } break; case WM_MOUSEMOVE: { mouse_x = LOWORD(lParam); mouse_y = screenHeight - HIWORD(lParam); } break; case WM_KEYDOWN: // Is A Key Being Held Down? { keys[wParam] = true; // If So, Mark It As TRUE return 0; // Jump Back } break; case WM_KEYUP: // Has A Key Been Released? { keys[wParam] = false; // If So, Mark It As FALSE return 0; // Jump Back } break; } // Pass All Unhandled Messages To DefWindowProc return DefWindowProc(hWnd,uMsg,wParam,lParam); }  
      game.cpp
    • By lxjk
      Hi guys,
      There are many ways to do light culling in tile-based shading. I've been playing with this idea for a while, and just want to throw it out there.
      Because tile frustums are general small compared to light radius, I tried using cone test to reduce false positives introduced by commonly used sphere-frustum test.
      On top of that, I use distance to camera rather than depth for near/far test (aka. sliced by spheres).
      This method can be naturally extended to clustered light culling as well.
      The following image shows the general ideas

       
      Performance-wise I get around 15% improvement over sphere-frustum test. You can also see how a single light performs as the following: from left to right (1) standard rendering of a point light; then tiles passed the test of (2) sphere-frustum test; (3) cone test; (4) spherical-sliced cone test
       

       
      I put the details in my blog post (https://lxjk.github.io/2018/03/25/Improve-Tile-based-Light-Culling-with-Spherical-sliced-Cone.html), GLSL source code included!
       
      Eric
    • By Fadey Duh
      Good evening everyone!

      I was wondering if there is something equivalent of  GL_NV_blend_equation_advanced for AMD?
      Basically I'm trying to find more compatible version of it.

      Thank you!
    • By Jens Eckervogt
      Hello guys, 
       
      Please tell me! 
      How do I know? Why does wavefront not show for me?
      I already checked I have non errors yet.
      using OpenTK; using System.Collections.Generic; using System.IO; using System.Text; namespace Tutorial_08.net.sourceskyboxer { public class WaveFrontLoader { private static List<Vector3> inPositions; private static List<Vector2> inTexcoords; private static List<Vector3> inNormals; private static List<float> positions; private static List<float> texcoords; private static List<int> indices; public static RawModel LoadObjModel(string filename, Loader loader) { inPositions = new List<Vector3>(); inTexcoords = new List<Vector2>(); inNormals = new List<Vector3>(); positions = new List<float>(); texcoords = new List<float>(); indices = new List<int>(); int nextIdx = 0; using (var reader = new StreamReader(File.Open("Contents/" + filename + ".obj", FileMode.Open), Encoding.UTF8)) { string line = reader.ReadLine(); int i = reader.Read(); while (true) { string[] currentLine = line.Split(); if (currentLine[0] == "v") { Vector3 pos = new Vector3(float.Parse(currentLine[1]), float.Parse(currentLine[2]), float.Parse(currentLine[3])); inPositions.Add(pos); if (currentLine[1] == "t") { Vector2 tex = new Vector2(float.Parse(currentLine[1]), float.Parse(currentLine[2])); inTexcoords.Add(tex); } if (currentLine[1] == "n") { Vector3 nom = new Vector3(float.Parse(currentLine[1]), float.Parse(currentLine[2]), float.Parse(currentLine[3])); inNormals.Add(nom); } } if (currentLine[0] == "f") { Vector3 pos = inPositions[0]; positions.Add(pos.X); positions.Add(pos.Y); positions.Add(pos.Z); Vector2 tc = inTexcoords[0]; texcoords.Add(tc.X); texcoords.Add(tc.Y); indices.Add(nextIdx); ++nextIdx; } reader.Close(); return loader.loadToVAO(positions.ToArray(), texcoords.ToArray(), indices.ToArray()); } } } } } And It have tried other method but it can't show for me.  I am mad now. Because any OpenTK developers won't help me.
      Please help me how do I fix.

      And my download (mega.nz) should it is original but I tried no success...
      - Add blend source and png file here I have tried tried,.....  
       
      PS: Why is our community not active? I wait very longer. Stop to lie me!
      Thanks !
  • Advertisement
  • Advertisement
Sign in to follow this  

OpenGL Finding Ray/Triangle intersection points in GLSL

This topic is 677 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Greetings 
 
I am currently trying to figure out what would be the best/fastest method to get information 
from a triangle/ray intersection and hit point calculation done in GLSL.
 
I am currently rendering the Utah teapot (just under 10K triangles) with a simple OpenGL
shader program composed of a vertex shader, geometry shader (for a single pass wireframe)
and a fragment shader. 
 
The geometry shader could do the calculations of the ray/triangle to see if the invocation
(current triangle) is hit and the hit location. But how can I store this information so that the
application can retrieve the closest triangle hit and its hit location ?
I'd like to take advantage of the parallelism of the GPU to avoid iterating through all triangles
and testing them one by one (as on CPU) (in the event I am testing millions of triangles).
 
Oh, the only constraint, I have to avoid using the Compute Shader.
 
Thanks for any advice !
 
Daniel
 

Share this post


Link to post
Share on other sites
Advertisement

Hi, ultimately I would need to find the closest hit point from all triangles that were intersected, from a start point in world space.

The index of the triangle is not so important.

The issue I am running into is that there are no shared variables that I can use (like in the Compute shader), so I must be able to store the hit information somehow.  

Share this post


Link to post
Share on other sites

 

I am currently trying to figure out what would be the best/fastest method to get information 
from a triangle/ray intersection and hit point calculation done in GLSL.

 

To go back to this, there really is no fast way to do this. One way you could do this is to put a camera at the start point of the ray and then look down the ray. Then render the cube, glReadPixels(centerScreenPixel). Then you have the depth from where the center of the camera hit. You can use glUnproject() to get the actual position it hit.

 

That is of course terrible, I think all ways relative to a graphics card performing raycasting is bad. Compute Shaders would be the way to go for GPU. Otherwise just get download a physics engine or a raytracing engine like Intel Embree, and do a raycast on the CPU. All bullets in big game worlds are done on the CPU and they have many more than 10,000 triangles.

Share this post


Link to post
Share on other sites

Thanks for the advice dpa, an interesting concept, I am new to shading so any tips is helpful.  

 

I've tried using the Transform Feedback, creating a buffer to store if a hit is present and another to store a world space hit locations. 

It works great, but the glGetBufferSubData(), to get data back to the app,  is just so expensive, nearly 0.8ms just for that call, all other work is lighting fast. 

 

Right now I am looking to see if I can store the hit locations calculated in the Geometry shader ( the ray/triangle intersection algorithm is done there) into an image with the imageStore() and access it from the app per frame,  not sure if or how well this will work. I'll give an update on this,

 

Cheers

Share this post


Link to post
Share on other sites

I've tried using the Transform Feedback, creating a buffer to store if a hit is present and another to store a world space hit locations. 
It works great, but the glGetBufferSubData(), to get data back to the app,  is just so expensive, nearly 0.8ms just for that call, all other work is lighting fast. 

Not sure if you tried it, but keep in mind that TF (AKA stream out) can write a varying arount of data to a buffer. So your GS can either not output anything, or output hit depth and triangle index, which would greatly reduce the amount of data to be read back.

Depending on thr number of triangles in the mesh and the accuracy required, you could also use a second pass on the GPU to find the minimum-depth element in that TF buffer. Use a VS that outputs every TF-buffer entry at a hard-coded point location in the middle of a 1x1 pixel render target of 32bit unit format. Use a PS that outputs fixed point depth in the high bits and triangle ID in the low bits (e.g. 16&16). Set the blend mode to MIN (and pre-clear the texture to 0xFFFFFFFF) to get the smallest depth result, along with the corresponding triangle ID encoded in its low bits. Then there's only a single pixel texture to read back to the CPU.

Now though, read backs, no matter how small, are always stupidly expensive if done on the same frame as the commands that produced the data. To maintain high throughput, GPUs have very high command latency and very long pipelines. This latency is usually one to three frames, or in the dozens of milliseconds. Whenever you issue a GL command and immediately try to read back the results, you're asking the driver to flush this long pipeline and stall until it's empty. Not only will this take a dozen ms, but you're got a lovely pipeline bubble when you start using the GPU again afterwards.

To avoid this, you have to also pipeline your GPU queries, such as with double buffering. Ever frame you issue GL commands to generate a result into resource A, and then attempt to read back the results from last frame that are in resource B. Hopefully this avoids flushing the pipeline. To get more certainty, add more frames of buffering to make your pipeline longer...

I don't remember the GL details off the top of my head, but in D3D you can make DEFAULT resources that live on the GPU, and staging resources that live on the CPU. You would issue commands to generate data into GPU_A and commands to copy GPU_A into CPU_A. A frame later, you'd then map CPU_A to read your result.


As above though, why not just use a CPU raytrace? Instead of brute forcing the answer, you'd use a BVH/etc to quickly discard most triangles and then only check a handful.

Share this post


Link to post
Share on other sites

Those are great explanations Hodgman, i'll be looking into this.

 
My Utah teapot example is simply a mid-step investigation on how to get the closest ray/triangle intersection point.
I should have explained my whole objective earlier. 
 
My complete objective is somewhat more involved:
I am rendering a dynamic terrain using displacement mapping and viewpoint LOD on tessellation.
I have a Program that contains all shader stages, the Vert/tessC/tessE/Geom/Frag
 
Multiple co-planar quad patches representing tiles a fed to the pipeline, using a single glDrawArrays().
the Vertex Shader is a simple pass through,
the Tess. Control determins inner outter levels for each tile,
the Tess. Eval does displacement mapping from a 4096x4096 texture.
the Geom. Shader does some visual wireframe calculations (single pass).
the Frag. Shader does normal lighting.
 
Everything runs very nicely and under 2ms for nealy 200K shaded triangles, I can also do per frame updating of a sub-region of the displacement map (100x100pixels) for a very small cost in frame time (under 0.3ms).
 
Now I need to be able to ray trace from a single world space position and direction (app level) into the terrain and extract the exact position on the first triangle hit (ray/triangles intersection calculations done in the Geom shader stage seems a very suitable place). Viewpoint dependent tessellation is done in this gl program, the triangles are generated in the pipeline. In order to try to optimize the entire application, I though that calculating the closest hit point there would be best (using the single pass).
 
I've just tested out the GLSL imageStore/imageRead and the glGetTexImage()x2 (for my simpler teapot example) and again I am able to get the correct closest hit point result, but it's even slower then the TF.  I could try out an atomic operation on the image so I would only need a single pixel RGBA32F to contain my hit location (not entire buffer(s)), but I fear that, just like you mentioned, this will still be an expensive operation just to retrieve this single pixel. 
 
I am not too familiar with PBOs, perhaps this could something I look into?
 
Thanks again for any comments/feedback. 
Cheers,
 
DanielL

Share this post


Link to post
Share on other sites

 

I am rendering a dynamic terrain using displacement mapping and viewpoint LOD on tessellation.

 

Well you want to get away from using displacement that pushes vertices really high away from their triangle, this way you can just raycast against the triangle, then find what pixel maps to that location of the triangle and then offset it. To get the exact displacement depends on your setup. You can always raycast against the actual heightmap of the terrain (that is what I do). You always just raycast againt the heightmap, not the tessellation detail.  Again, physics engines usually have a raycast heightmap function which will do this for you. Tessellation is still based upon the height map.

 

Now if you were tessellation really strangely and the triangles were shifting so much that a hillside moves down drastically, when then yes, you could have something floating above that part of the hill, but your other option is that you have a ton of objects popping up and down all the time.

Share this post


Link to post
Share on other sites

I tested a different mechanism using the atomic operation on images, with interesting results :

 

Now I do not need 2 buffers of size 10K each (1 buffer for if triangle is hit or not, 1 buffer containing hitPoint locations) for the Transform Feedback OR the GLSL imageLoad()/ImageStore() functions.

 

I only need a buffer of 1 single unsigned int that will contain "t" the hit distance to a triangle (I use a glTexImage1D of size 1 for now).

The equation for the hit location is "Hit = Start + t*dir ", the "Start" point and "dir" direction are uniforms. Using the atomic operation, I can update the "t" using the imageAtomicMin(), so each geometry shader invocation will securely update this "t" if the result is smaller than the current one held in the image (the single uint).  

The application can then get this single "t" and calculate the hit point. 

 

Again, unfortunately the glGetTexImage() I use to retrieve this single uint (4 bytes) is "stupidly expensive" ;o) , costing around 1ms, but the complexity of the setup to find the hit point is drastically reduced. 

 

DanielL

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement