• Advertisement

Search the Community

Showing results for tags 'OpenGL'.



More search options

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Categories

  • Audio
    • Music and Sound FX
  • Business
    • Business and Law
    • Career Development
    • Production and Management
  • Game Design
    • Game Design and Theory
    • Writing for Games
    • UX for Games
  • Industry
    • Interviews
    • Event Coverage
  • Programming
    • Artificial Intelligence
    • General and Gameplay Programming
    • Graphics and GPU Programming
    • Engines and Middleware
    • Math and Physics
    • Networking and Multiplayer
  • Visual Arts
  • Archive

Categories

  • News

Categories

  • Audio
  • Visual Arts
  • Programming
  • Writing

Categories

  • GameDev Unboxed

Categories

  • Game Dev Loadout

Categories

  • Game Developers Conference
    • GDC 2017
    • GDC 2018
  • Power-Up Digital Games Conference
    • PDGC I: Words of Wisdom
    • PDGC II: The Devs Strike Back
    • PDGC III: Syntax Error

Forums

  • Audio
    • Music and Sound FX
  • Business
    • Games Career Development
    • Production and Management
    • Games Business and Law
  • Game Design
    • Game Design and Theory
    • Writing for Games
  • Programming
    • Artificial Intelligence
    • Engines and Middleware
    • General and Gameplay Programming
    • Graphics and GPU Programming
    • Math and Physics
    • Networking and Multiplayer
  • Visual Arts
    • 2D and 3D Art
    • Critique and Feedback
  • Topical
    • Virtual and Augmented Reality
    • News
  • Community
    • For Beginners
    • GameDev Challenges
    • GDNet+ Member Forum
    • GDNet Lounge
    • GDNet Comments, Suggestions, and Ideas
    • Coding Horrors
    • Your Announcements
    • Hobby Project Classifieds
    • Indie Showcase
    • Article Writing
  • Affiliates
    • NeHe Productions
    • AngelCode
  • Workshops
    • C# Workshop
    • CPP Workshop
    • Freehand Drawing Workshop
    • Hands-On Interactive Game Development
    • SICP Workshop
    • XNA 4.0 Workshop
  • Archive
    • Topical
    • Affiliates
    • Contests
    • Technical
  • GameDev Challenges's Topics

Calendars

  • Community Calendar
  • Games Industry Events
  • Game Jams
  • GameDev Challenges's Schedule

Blogs

There are no results to display.

There are no results to display.

Developers

Developers


Group


About Me


Website


Industry Role


Twitter


Github


Twitch


Steam

Found 17494 results

  1. 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
  2. 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
  3. 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
  4. 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!
  5. 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 !
  6. I wasn't sure if this would be the right place for a topic like this so sorry if it isn't. I'm currently working on a project for Uni using FreeGLUT to make a simple solar system simulation. I've got to the point where I've implemented all the planets and have used a Scene Graph to link them all together. The issue I'm having with now though is basically the planets and moons orbit correctly at their own orbit speeds. I'm not really experienced with using matrices for stuff like this so It's likely why I can't figure out how exactly to get it working. This is where I'm applying the transformation matrices, as well as pushing and popping them. This is within the Render function that every planet including the sun and moons will have and run. if (tag != "Sun") { glRotatef(orbitAngle, orbitRotation.X, orbitRotation.Y, orbitRotation.Z); } glPushMatrix(); glTranslatef(position.X, position.Y, position.Z); glRotatef(rotationAngle, rotation.X, rotation.Y, rotation.Z); glScalef(scale.X, scale.Y, scale.Z); glDrawElements(GL_TRIANGLES, mesh->indiceCount, GL_UNSIGNED_SHORT, mesh->indices); if (tag != "Sun") { glPopMatrix(); } The "If(tag != "Sun")" parts are my attempts are getting the planets to orbit correctly though it likely isn't the way I'm meant to be doing it. So I was wondering if someone would be able to help me? As I really don't have an idea on what I would do to get it working. Using the if statement is truthfully the closest I've got to it working but there are still weird effects like the planets orbiting faster then they should depending on the number of planets actually be updated/rendered.
  7. Hello everyone, I have problem with texture using System; using OpenTK; using OpenTK.Input; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL4; using System.Drawing; using System.Reflection; namespace Tutorial_05 { class Game : GameWindow { private static int WIDTH = 1200; private static int HEIGHT = 720; private static KeyboardState keyState; private int vaoID; private int vboID; private int iboID; private Vector3[] vertices = { new Vector3(-0.5f, 0.5f, 0.0f), // V0 new Vector3(-0.5f, -0.5f, 0.0f), // V1 new Vector3(0.5f, -0.5f, 0.0f), // V2 new Vector3(0.5f, 0.5f, 0.0f) // V3 }; private Vector2[] texcoords = { new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0) }; private int[] indices = { 0, 1, 3, 3, 1, 2 }; private string vertsrc = @"#version 450 core in vec3 position; in vec2 textureCoords; out vec2 pass_textureCoords; void main(void) { gl_Position = vec4(position, 1.0); pass_textureCoords = textureCoords; }"; private string fragsrc = @"#version 450 core in vec2 pass_textureCoords; out vec4 out_color; uniform sampler2D textureSampler; void main(void) { out_color = texture(textureSampler, pass_textureCoords); }"; private int programID; private int vertexShaderID; private int fragmentShaderID; private int textureID; private Bitmap texsrc; public Game() : base(WIDTH, HEIGHT, GraphicsMode.Default, "Tutorial 05 - Texturing", GameWindowFlags.Default, DisplayDevice.Default, 4, 5, GraphicsContextFlags.Default) { } protected override void OnLoad(EventArgs e) { base.OnLoad(e); CursorVisible = true; GL.GenVertexArrays(1, out vaoID); GL.BindVertexArray(vaoID); GL.GenBuffers(1, out vboID); GL.BindBuffer(BufferTarget.ArrayBuffer, vboID); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vertices.Length * Vector3.SizeInBytes), vertices, BufferUsageHint.StaticDraw); GL.GenBuffers(1, out iboID); GL.BindBuffer(BufferTarget.ElementArrayBuffer, iboID); GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(indices.Length * sizeof(int)), indices, BufferUsageHint.StaticDraw); vertexShaderID = GL.CreateShader(ShaderType.VertexShader); GL.ShaderSource(vertexShaderID, vertsrc); GL.CompileShader(vertexShaderID); fragmentShaderID = GL.CreateShader(ShaderType.FragmentShader); GL.ShaderSource(fragmentShaderID, fragsrc); GL.CompileShader(fragmentShaderID); programID = GL.CreateProgram(); GL.AttachShader(programID, vertexShaderID); GL.AttachShader(programID, fragmentShaderID); GL.LinkProgram(programID); // Loading texture from embedded resource texsrc = new Bitmap(Assembly.GetEntryAssembly().GetManifestResourceStream("Tutorial_05.example.png")); textureID = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, textureID); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, texsrc.Width, texsrc.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero); System.Drawing.Imaging.BitmapData bitmap_data = texsrc.LockBits(new Rectangle(0, 0, texsrc.Width, texsrc.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, texsrc.Width, texsrc.Height, PixelFormat.Bgra, PixelType.UnsignedByte, bitmap_data.Scan0); texsrc.UnlockBits(bitmap_data); GL.Enable(EnableCap.Texture2D); GL.BufferData(BufferTarget.TextureBuffer, (IntPtr)(texcoords.Length * Vector2.SizeInBytes), texcoords, BufferUsageHint.StaticDraw); GL.BindAttribLocation(programID, 0, "position"); GL.BindAttribLocation(programID, 1, "textureCoords"); } protected override void OnResize(EventArgs e) { base.OnResize(e); GL.Viewport(0, 0, ClientRectangle.Width, ClientRectangle.Height); } protected override void OnUpdateFrame(FrameEventArgs e) { base.OnUpdateFrame(e); keyState = Keyboard.GetState(); if (keyState.IsKeyDown(Key.Escape)) { Exit(); } } protected override void OnRenderFrame(FrameEventArgs e) { base.OnRenderFrame(e); // Prepare for background GL.Clear(ClearBufferMask.ColorBufferBit); GL.ClearColor(Color4.Red); // Draw traingles GL.EnableVertexAttribArray(0); GL.EnableVertexAttribArray(1); GL.BindVertexArray(vaoID); GL.UseProgram(programID); GL.BindBuffer(BufferTarget.ArrayBuffer, vboID); GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 0, IntPtr.Zero); GL.ActiveTexture(TextureUnit.Texture0); GL.BindTexture(TextureTarget.Texture3D, textureID); GL.BindBuffer(BufferTarget.ElementArrayBuffer, iboID); GL.DrawElements(BeginMode.Triangles, indices.Length, DrawElementsType.UnsignedInt, 0); GL.DisableVertexAttribArray(0); GL.DisableVertexAttribArray(1); SwapBuffers(); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); GL.DeleteVertexArray(vaoID); GL.DeleteBuffer(vboID); } } } I can not remember where do I add GL.Uniform2();
  8. Hello everyone For @80bserver8 nice job - I have found Google search. How did you port from Javascript WebGL to C# OpenTK.? I have been searched Google but it shows f***ing Unity 3D. I really want know how do I understand I want start with OpenTK But I want know where is porting of Javascript and C#? Thanks!
  9. Hi I draw in a OpenGL framebuffer. All is fine but it eats FPS (frames per second), hence I wonder if I could execute the framebuffer drawing only every 5-10th loop or so? Many thanks
  10. hi all, how to implement this type of effect ? Also what is this effect called? this is considered volumetric lighting? what are the options of doing this? a. billboard? but i want this to have the 3D effect that when we rotate the camera we can still have that 3d feel. b. a transparent 3d mesh? and we can animate it as well? need your expert advise. additional: 2. how to implement things like fireball projectile (shot from a monster) (billboard texture or a 3d mesh)? Note: im using OpenGL ES 2.0 on mobile. thanks!
  11. Let me preface this by saying that I am not familiar with 3d modeling at all. In fact I know almost nothing about it. This is perhaps why I've decided to write my own 3D model format and my own 3D modeling software from scratch (I didn't want to deal with existing formats, which seemed quite complex for what I wanted to do) . Now my 3D modeling software is quite adequate for small things, but it's really slow to use and unfit for organic shapes. My 3D model format is very simple; -25,4.48,-25:251,252,250 -24,4.58,-25:250,253,250 -25,4.62,-24:250,252,251 -24,4.58,-25:250,253,250 -24,4.62,-24:250,253,251 -25,4.62,-24:250,252,251 -25,4.62,-24:250,252,251 -24,4.62,-24:250,253,251 ... It's broken in 2 part, the first 3 numbers (separated by ',') are floating point values representing the location of a vertex and the last 3 numbers represents the RGB value of the color of that vertex. Triangles are simply drawn by taking the first 3 vertex, then the next 3, etc till the whole list is drawn. Of course once loaded this data takes the form of a model class, which is a list of instances of a small vertex class. As you can imagine, this is probably the simplest way to store a model that contains "textures" (which I use loosely), but is good enough for my game. I've looked at several model format but mine seems quite unique at what it does. Is there anything like it out there? I would like to write a small converter to take models made with more competent 3D software and use them in my engine. Another option would be to write a plugin for an existing 3D modeling software, but I am unsure on how I would go about that since I have almost no experience with them. Could anyone point me in the right direction? At first it seemed like a reasonably simple thing to do but the more I investigate the question the more I think I'll just have to spend a few days fleshing out my own 3D modeling software.
  12. I'm having some problems trying to figure out why my application won't draw the triangle I'm telling it to draw on the screen. After every single gl call in my code I check if glGetError() isn't equal to GL_NO_ERRORS, however it always is so I don't have any errors or anything to use when debugging. I'm literally clueless as to why my application won't render the triangle. The only thing that the window displays is a grey background since I set the clear color to be grey. It would be nice to get some tips as to what to do when your OpenGL window isn't displaying anything and glGetError() returns nothing of use.
  13. I am trying to render a 3d model of a bmx bike. The problem is, when I use the lib3ds mesh matrices, the bike renders completely wrong with bike components drawing all over the place. It almost works when I don't use the mesh matrices from the lib3ds file, but some bike components are displayed incorrectly, so I probably need to use them. I have checked the values of the mesh matrices and they are not identity matrices. I use the following code to store the modified matrix for a mesh of the bike: float meshMat[4][4]; lib3ds_matrix_copy(meshMat, mesh->matrix); lib3ds_matrix_inv(meshMat); pMesh->m_matTransformationMatrix = glm::mat4( meshMat[0][0], meshMat[0][2], meshMat[0][1], meshMat[0][3], meshMat[1][0], meshMat[1][2], meshMat[1][1], meshMat[1][3], meshMat[2][0], meshMat[2][2], meshMat[2][1], meshMat[2][3], meshMat[3][0], meshMat[3][2], meshMat[3][1], meshMat[3][3] ); I use the following code when rendering a mesh of the bike: glUniformMatrix4fv(glGetUniformLocation(getGameEngine()->m_uiProgram1, "model"), 1, GL_FALSE, glm::value_ptr(pMesh->m_matTransformationMatrix)); I use this glsl code for my vertex shader: #version 330 in vec3 in_position; uniform mat4 camera; uniform mat4 model; void main(void) { gl_Position = camera * model * vec4(in_position,1); } I'm currently not using my matrix (pos, rot & scale) for the bike, to less complicate things, so I'm only using the matrix from lib3ds currently. I have switched y and z for all 4 vectors in the lib3ds matrix, because I have Y and Z switched in OpenGL. I see that many examples on the net use glMultMatrix but that is an outdated OpenGL function, I am using the model in the GPU shaders. Can anyone help? If you need to see more code, just ask and I'll provide it. Thanks, Mex
  14. Trying to get texture buffer objects working. I'm planning on updating a buffer every frame with instance matrices, for now I have stored a single color. I stripped my code to a simple example. Right now the color I am getting is black. I'm wondering if there is something dumb I need to know about TBO's. I have 0 glGetError() issues. The buffer should definitely contain data, so I wonder if there isn't something with binding the texture properly. ***I missed in my example, but I am calling glUniform1i("instanceMatrixBuffer", 11); To properly bind texture 11 to the sampler in the shader. glGenVertexArrays(1, &VAO_Handle); glBindVertexArray(VAO_Handle); glBindBuffer(GL_ARRAY_BUFFER, VBO_Handle); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)this->m_vboLayout.positionDataOffset); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, VBO_Index_Handle); glBindVertexArray(0); ...later glBindVertexArray(VAO_Handle); static bool doOnce = true; if(doOnce) { doOnce = false; glGenBuffers(1, &TBO_Buffer_Handle); glBindBuffer(GL_TEXTURE_BUFFER, VBO_Index); float data[4] = {1.0, 0.0, 1.0, 1.0}; glBufferData(GL_TEXTURE_BUFFER, sizeof(float)*4, data, GL_STATIC_DRAW); glGenTextures(1, &TBO_Texture_Handle); glBindTexture(GL_TEXTURE_BUFFER, Texture_Index ); glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, VBO_Index); } glActiveTexture(GL_TEXTURE11); glBindBuffer(GL_TEXTURE_BUFFER, VBO_Index); glBindTexture(GL_TEXTURE_BUFFER, Texture_Index); glDrawElementsInstanced(GL_TRIANGLES, meshToRender->num_faces*3, GL_UNSIGNED_INT, 0, instanceCount) GLSL vec4 Color = texelFetch(instanceMatrixBuffer, 0);
  15. Hey guys. For a long time I have been very interested in game dev and programming. I have surfed the internet for tutorials and example code for begginers on how to create a 3D game engine or how to make a game in a already made game engine. Unfortunately I can't find anything that can help me. All the game engine tutorials are about game Design which I am interested about but I want to make a 3d game first or the tutorials just end up chucking at me this complex paragraph of code that I have never seen before and no idea how it works. I'm hoping someone can help me here and point me in the right direction for game dev. I have been programming in Python for over a year which is my main language and I have already made some 2d games in there and recently I have started to learn Java and c# since i heard they were good for game dev and also the syntax between the 2 is unbelievablely similar. I have also heard that opengl is good for game dev but again I can't find any good tutorials on it I really want to learn all I can about game dev and become a indi game developer and make a low poly game because they look awesome. Hope someone can help
  16. Hi Guys, A quick question. I have a 3d grid sector made out of AABB boxes ( see picture below ). When I turn the light on, I get the light catching the extremities of the boxes creating ugly line artifacts. Just wondering if there's a way to solve this problem. Thanks again, Mike
  17. I spent the last few days implementing Deferred rendering and then Physically based Shading into my C++ engine to see if i'll be able to pull this off. My rendering setup is as follows: Position Buffer (RGB 16 bit float world space) Normal buffer (RGB 16 bit float world space) Albedo buffer (RGB 8 bit) Roughness/Metallness Buffer (one in the R component, one in the G component) It's not an efficient setup but i wanted to keep it simple and optimize it later after i get everything to work. Here is the shader which i'm using: #version 330 in vec2 vTexcoord; out vec4 outputF; uniform sampler2D gPosition; uniform sampler2D gNormal; uniform sampler2D gAlbedo; uniform sampler2D gMetallicRoughness; uniform vec2 uPixelSize; uniform float uRadius; uniform vec3 uColor; uniform vec3 uLightPos; uniform vec3 uCameraPosition; const float PI = 3.141592653589793; float BRDF_Lambert(float NdotL) { return NdotL; } float BRDF_D_GGX(float NdotH, float roughness) { float roughness2 = roughness * roughness; float NdotH2 = NdotH * NdotH; float r1 = (NdotH2 - 1.0) / (roughness2 * NdotH2); float r2 = 1.0 / (PI * (roughness2 * NdotH2) * roughness2); return exp(r1) * r2; } //NdotV seems to be correct (instead of HdotV) float BRDF_F_FresnelSchlick(float NdotV, float F0) { return (F0 + (1.0f - F0) * (pow(1.0f - max(NdotV,0.0f),5.0f)));; } float BRDF_G_SchlickGGX(float NdotV,float roughness){ float k = (roughness*roughness)/2.0f; //float k = roughness; return (NdotV)/(NdotV * (1.0f - k) + k); } //geometrix shadowing - cook-Torrance float BRDF_G_Smith(float NdotV,float NdotL, float roughness) { NdotV = max(NdotV,0.0f); NdotL = max(NdotL,0.0f); return BRDF_G_SchlickGGX(NdotV,roughness) * BRDF_G_SchlickGGX(NdotL,roughness); } float calcAttenuation(float distToFragment,float lightRadius){ float att = clamp(1.0 - distToFragment*distToFragment/(lightRadius*lightRadius), 0.0, 1.0); att *= att; return att; } void main() { vec2 texCoord = vec2(gl_FragCoord.x * uPixelSize.x,gl_FragCoord.y*uPixelSize.y); vec3 fragPos = texture2D(gPosition, texCoord).rgb; vec3 fragNormal = texture2D(gNormal, texCoord).rgb; vec3 fragAlbedo = texture2D(gAlbedo, texCoord).rgb; vec2 fragMetallicRoughness = texture2D(gMetallicRoughness, texCoord).rg; float fragMetallic = fragMetallicRoughness.r; float fragRoughness = fragMetallicRoughness.g; fragRoughness = max(fragRoughness,0.05f);//if value is 0 it doesnt reflect anything //-------------- vec3 fragToLightNormal = uLightPos-fragPos; vec3 N = normalize(fragNormal);//normal vector vec3 L = normalize(fragToLightNormal);//light vector vec3 V = normalize(uCameraPosition-fragPos.xyz); //eye vector vec3 H = normalize(L+V); //half vector float NdotH = max(dot(N,H),0.0f); float NdotV = max(dot(N,V),0.0f); float NdotL = max(dot(N,L),0.0f); float VdotH = max(dot(V,H),0.0f); //------------------ float F0 = 0.04f;//assumption float D = BRDF_D_GGX(NdotH, fragRoughness); //normal distribution float F = BRDF_F_FresnelSchlick(NdotV, F0); // Fresnel float G = BRDF_G_Smith(NdotV,NdotL,fragRoughness); //geometric shadowing vec3 specularColor = mix(vec3(F0,F0,F0), fragAlbedo, fragMetallic); float specularContribution = (D * F * G) / (4.0f * NdotL * NdotV); float lightNormalLength = length(fragToLightNormal); float attenuation = calcAttenuation(lightNormalLength, uRadius); vec3 radiance = attenuation * uColor; vec3 finalColor= (fragAlbedo*(1.0f - F) + specularContribution * specularColor ) * radiance * BRDF_Lambert(NdotL); outputF = vec4(finalColor,1.0f); } For a while i had trouble with this part, but it seems to work. (correct me if you find issues here) float D = BRDF_D_GGX(NdotH, fragRoughness); //normal distribution float F = BRDF_F_FresnelSchlick(NdotV, F0); // Fresnel float G = BRDF_G_Smith(NdotV,NdotL,fragRoughness); //geometric shadowing The issue i'm having is with the last bit: vec3 specularColor = mix(vec3(F0,F0,F0), fragAlbedo, fragMetallic); float specularContribution = (D * F * G) / (4.0f * NdotL * NdotV); float lightNormalLength = length(fragToLightNormal); float attenuation = calcAttenuation(lightNormalLength, uRadius); vec3 radiance = attenuation * uColor; vec3 finalColor= (fragAlbedo*(1.0f - F) + specularContribution * specularColor ) * radiance * BRDF_Lambert(NdotL); outputF = vec4(finalColor,1.0f); I'm not really sure that i'm doing it right. I've done a bit of research online (looking up tutorials, etc...) but it seems that everyone is doing PBR slightly differently. As an example, my materials have a roughness and metallic texture. Sometimes roughness was implemented while metallic values weren't. (The F0 value was used, although i don't know if it's the same thing.) Some times i read about energy consetvation which is implemented by multiplying the kD factor with 1.0f -metallnessvalue: float kD = 1.0f- kS; kD*= 1.0f - fragMetallic; //energy consetvation Which confuses me a bit because i'm already multiplying the value with 1.0f-F0. (and doing so in my code results in darker overall colors:) vec3 finalColor= (fragAlbedo*(1.0f - F) * (1.0-fragMetallic) + specularContribution * specularColor ) * radiance * BRDF_Lambert(NdotL); I think that i'm handling the roughness/metallic values incorrectly in this code. So my question is: How exactly do i have to combine the albedo, roughness, metallic, normal/lighting data in the last step to get the correct results? Can someone glance over this code and point out what could be at fault? (Specifically in this code bit: ) vec3 specularColor = mix(vec3(F0,F0,F0), fragAlbedo, fragMetallic); float specularContribution = (D * F * G) / (4.0f * NdotL * NdotV); float lightNormalLength = length(fragToLightNormal); float attenuation = calcAttenuation(lightNormalLength, uRadius); vec3 radiance = attenuation * uColor; vec3 finalColor= (fragAlbedo*(1.0f - F) + specularContribution * specularColor ) * radiance * BRDF_Lambert(NdotL); outputF = vec4(finalColor,1.0f);
  18. So I've started in learning OpenGL , then I found the NeHe website and its Legacy Tutorials (here is the link http://nehe.gamedev.net/tutorial/lessons_01__05/22004/ ).But the problem is that I can't download any examples of code ( neither C code examples nor any other language ) .As you see it is impossible to download http://nehe.gamedev5.net/data/lessons/pelles_c/lesson01.zip . Does anyone has expamles of C code of this lessons ? And the second question. If I prefer coding on C , should I choose GLUT but not an OpenGL ?
  19. Hi, ok, so, we are having problems with our current mirror reflection implementation. At the moment we are doing it very simple, so for the i-th frame, we calculate the reflection vectors given the viewPoint and some predefined points on the mirror surface (position and normal). Then, using the least squared algorithm, we find the point that has the minimum distance from all these reflections vectors. This is going to be our virtual viewPoint (with the right orientation). After that, we render offscreen to a texture by setting the OpenGL camera on the virtual viewPoint. And finally we use the rendered texture on the mirror surface. So far this has always been fine, but now we are having some more strong constraints on accuracy. What are our best options given that: - we have a dynamic scene, the mirror and parts of the scene can change continuously from frame to frame - we have about 3k points (with normals) per mirror, calculated offline using some cad program (such as Catia) - all the mirror are always perfectly spherical (with different radius vertically and horizontally) and they are always convex - a scene can have up to 10 mirror - it should be fast enough also for vr (Htc Vive) on fastest gpus (only desktops) Looking around, some papers talk about calculating some caustic surface derivation offline, but I don't know if this suits my case Also, another paper, used some acceleration structures to detect the intersection between the reflection vectors and the scene, and then adjust the corresponding texture coordinate. This looks the most accurate but also very heavy from a computational point of view. Other than that, I couldn't find anything updated/exhaustive around, can you help me? Thanks in advance
  20. Hello all, I am currently working on a game engine for use with my game development that I would like to be as flexible as possible. As such the exact requirements for how things should work can't be nailed down to a specific implementation and I am looking for, at least now, a default good average case scenario design. Here is what I have implemented: Deferred rendering using OpenGL Arbitrary number of lights and shadow mapping Each rendered object, as defined by a set of geometry, textures, animation data, and a model matrix is rendered with its own draw call Skeletal animations implemented on the GPU. Model matrix transformation implemented on the GPU Frustum and octree culling for optimization Here are my questions and concerns: Doing the skeletal animation on the GPU, currently, requires doing the skinning for each object multiple times per frame: once for the initial geometry rendering and once for the shadow map rendering for each light for which it is not culled. This seems very inefficient. Is there a way to do skeletal animation on the GPU only once across these render calls? Without doing the model matrix transformation on the CPU, I fail to see how I can easily batch objects with the same textures and shaders in a single draw call without passing a ton of matrix data to the GPU (an array of model matrices then an index for each vertex into that array for transformation purposes?) If I do the matrix transformations on the CPU, It seems I can't really do the skinning on the GPU as the pre-transformed vertexes will wreck havoc with the calculations, so this seems not viable unless I am missing something Overall it seems like simplest solution is to just do all of the vertex manipulation on the CPU and pass the pre-transformed data to the GPU, using vertex shaders that do basically nothing. This doesn't seem the most efficient use of the graphics hardware, but could potentially reduce the number of draw calls needed. Really, I am looking for some advice on how to proceed with this, how something like this is typically handled. Are the multiple draw calls and skinning calculations not a huge deal? I would LIKE to save as much of the CPU's time per frame so it can be tasked with other things, as to keep CPU resources open to the implementation of the engine. However, that becomes a moot point if the GPU becomes a bottleneck.
  21. I'm trying to load data from a .gltf file into a struct to use to load a .bin file. I don't think there is a problem with how the vertex positions are loaded, but with the indices. This is what I get when drawing with glDrawArrays(GL_LINES, ...): Also, using glDrawElements gives a similar result. Since it looks like its drawing triangles using the wrong vertices for each face, I'm assuming it needs an index buffer/element buffer. (I'm not sure why there is a line going through part of it, it doesn't look like it belongs to a side, re-exported it without texture coordinates checked, and its not there) I'm using jsoncpp to load the GLTF file, its format is based on JSON. Here is the gltf struct I'm using, and how I parse the file: #define GLTF_TARGET_ARRAY_BUFFER (34962) #define GLTF_TARGET_ELEMENT_ARRAY_BUFFER (34963) #define GLTF_COMPONENT_TYPE_BYTE (5120) #define GLTF_COMPONENT_TYPE_UNSIGNED_BYTE (5121) #define GLTF_COMPONENT_TYPE_SHORT (5122) #define GLTF_COMPONENT_TYPE_UNSIGNED_SHORT (5123) #define GLTF_COMPONENT_TYPE_INT (5124) #define GLTF_COMPONENT_TYPE_UNSIGNED_INT (5125) #define GLTF_COMPONENT_TYPE_FLOAT (5126) #define GLTF_COMPONENT_TYPE_DOUBLE (5127) #define GLTF_PARAMETER_TYPE_BYTE (5120) #define GLTF_PARAMETER_TYPE_UNSIGNED_BYTE (5121) #define GLTF_PARAMETER_TYPE_SHORT (5122) #define GLTF_PARAMETER_TYPE_UNSIGNED_SHORT (5123) #define GLTF_PARAMETER_TYPE_INT (5124) #define GLTF_PARAMETER_TYPE_UNSIGNED_INT (5125) #define GLTF_PARAMETER_TYPE_FLOAT (5126) #define GLTF_PARAMETER_TYPE_FLOAT_VEC2 (35664) #define GLTF_PARAMETER_TYPE_FLOAT_VEC3 (35665) #define GLTF_PARAMETER_TYPE_FLOAT_VEC4 (35666) struct GLTF { struct Accessor { USHORT bufferView; USHORT componentType; UINT count; vector<INT> max; vector<INT> min; string type; }; vector<Accessor> m_accessors; struct Asset { string copyright; string generator; string version; }m_asset; struct BufferView { UINT buffer; UINT byteLength; UINT byteOffset; UINT target; }; vector<BufferView> m_bufferViews; struct Buffer { UINT byteLength; string uri; }; vector<Buffer> m_buffers; vector<string> m_Images; struct Material { string name; string alphaMode; Vec4 baseColorFactor; UINT baseColorTexture; UINT normalTexture; float metallicFactor; }; vector<Material> m_materials; struct Meshes { string name; struct Primitive { vector<UINT> attributes_indices; UINT indices; UINT material; }; vector<Primitive> primitives; }; vector<Meshes> m_meshes; struct Nodes { int mesh; string name; Vec3 translation; }; vector<Nodes> m_nodes; struct Scenes { UINT index; string name; vector<UINT> nodes; }; vector<Scenes> m_scenes; vector<UINT> samplers; struct Textures { UINT sampler; UINT source; }; vector<Textures> m_textures; map<UINT, string> attributes_map; map<UINT, string> textures_map; }; GLTF m_gltf; // This is actually in the Mesh class bool Mesh::Load(string sFilename) { string sFileAsString; stringstream sStream; ifstream fin(sFilename); sStream << fin.rdbuf(); fin.close(); sFileAsString = sStream.str(); Json::Reader r; Json::Value root; if (!r.parse(sFileAsString, root)) { string errors = r.getFormatedErrorMessages(); if (errors != "") { // TODO: Log errors return false; } } if (root.isNull()) return false; Json::Value object; Json::Value value; // Load Accessors array, these are referenced by attributes with their index value object = root.get("accessors", Json::Value()); // store object with key "accessors", if not found it will default to Json::Value() if (!object.isNull()) { for (Json::ValueIterator it = object.begin(); it != object.end(); it++) { GLTF::Accessor accessor; value = (*it).get("bufferView", Json::Value()); if (!value.isNull()) accessor.bufferView = value.asUINT(); else return false; value = (*it).get("componentType", Json::Value()); if (!value.isNull()) accessor.componentType = value.asUINT(); else return false; value = (*it).get("count", Json::Value()); if (!value.isNull()) accessor.count = value.asUINT(); else return false; value = (*it).get("type", Json::Value()); if (!value.isNull()) accessor.type = value.asString(); else return false; m_gltf.accessors.push_back(accessor); } } else return false; object = root.get("bufferViews", Json::Value()); if(!object.isNull()) { for (Json::ValueIterator it = object.begin(); it != object.end(); it++) { GLTF::BufferView bufferView; value = (*it).get("buffer", Json::Value()); if(!value.isNull()) bufferView.buffer = value.asUInt(); else return false; value = (*it).get("byteLength", Json::Value()); if(!value.isNull()) bufferView.byteLength = value.asUInt(); else return false; value = (*it).get("byteOffset", Json::Value()); if(!value.isNull()) bufferView.byteOffset = value.asUInt(); else return false; value = (*it).get("target", Json::Value()); if(!value.isNull()) bufferView.target = value.asUInt(); else return false; m_gltf.m_bufferViews.push_back(bufferView); } } else return false; object = root.get("buffers", Json::Value()); if(!object.isNull()) { for (Json::ValueIterator it = object.begin(); it != object.end(); it++) { GLTF::Buffer buffer; value = (*it).get("byteLength", Json::Value()); if(!value.isNull()) buffer.byteLength = value.asUInt(); else return false; // Store the filename of the .bin file value = (*it).get("uri", Json::Value()); if(!value.isNull()) buffer.uri = value.asString(); else return false; } } else return false; object = root.get("meshes", Json::Value()); if(!object.isNull()) { for(Json::ValueIterator it = object.begin(); it != object.end(); it++) { GLTF::Meshes mesh; value = (*it).get("primitives", Json::Value()); for(Json::ValueIterator value_it = value.begin(); value_it != value.end(); value_it++) { GLTF::Meshes::Primitive primitive; Json::Value attributes; attributes = (*value_it).get("attributes", Json::Value()); vector<string> memberNames = attributes.getMemberNames(); for(size_t i = 0; i < memberNames.size(); i++) { Json::Value member; member = attributes.get(memeberNames[i], Json::Value()); if(!member.isNull()) { primitive.attributes_indices.push_back(member.asUInt()); m_gltf.attributes_map[member.asUInt()] = memberNames[i]; // Each of these referes to an accessor by indice, so each indice should be unique, and they are when loading a cube } else return false; } // Indice of the accessor used for indices Json::Value indices; indices = (*value_it).get("indices", Json::Value()); primitive.indices = indices.asUInt(); mesh.primitives.push_back(primitive); } m_gltf.m_meshes.push_back(mesh); } } vector<float> vertexData; vector<USHORT> indiceData; int vertexBufferSizeTotal = 0; int elementBufferSizeTotal = 0; GLTF::Meshes mesh = m_gltf.m_meshes[0]; vector<GLTF::Meshes::Primitive> primitives = mesh.primitives; // trying to make the code easier to read for (size_t p = 0; p < primitive.size(); p++) { vector<UINT> attributes = primitives[p].attributes_indices; for(size_t a = 0; a < attributes.size(); a++) { GLTF::Accessor accessor = m_gltf.m_accessors[attributes[a]]; GLTF::BufferView bufferView = m_gltf.m_bufferViews[accessor.bufferView]; UINT target = bufferView.target; if(target == GLTF_TARGET_ARRAY_BUFFER) vertexBufferSizeTotal += bufferView.byteLength; } UINT indice = primitives[p].indices; GLTF::BufferView bufferView = m_gltf.m_bufferViews[indice]; UINT target = bufferView.target; if(target == GLTF_TARGET_ELEMENT_ARRAY_BUFFER) elementBufferSizeTotal += bufferView.byteLength; } // These have already been generated glBindVertexArray(g_pGame->m_VAO); glBindBuffer(GL_ARRAY_BUFFER, g_pGame->m_VBO); glBufferData(GL_ARRAY_BUFFER, vertexBufferSizeTotal, nullptr, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_pGame->m_EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementBufferSizeTotal, nullptr, GL_STATIC_DRAW); int offset = 0; int offset_indice = 0; for (size_t p = 0; p < primitive.size(); p++) { vector<UINT> attributes = primitives[p].attributes_indices; int pos = sFilename.find_last_of('\\') + 1; string sFolder = sFilename.substr(0, pos); for (size_t a = 0; a < attributes.size(); a++) { LoadBufferView(sFolder, attributes[a], data, offset); } UINT indice = primitives[p].indices; GLTF::BufferView bufferView_indice = m_gltf.m_bufferViews[indice]; UINT target_indice = bufferView_indice.target; bool result = LoadBufferView(sFolder, indice, data, offset_indice); if(!result) return false; } return true; } bool Mesh::LoadBufferView(string sFolder, UINT a, vector<float> &vertexData, vector<float> &indiceData, int &offset_indice) { ifstream fin; GLTF::Accessor accessor = m_gltf.m_accessors[a]; GLTF::BufferView bufferView = m_gltf.m_bufferViews[accessor.bufferView]; GLTF::Buffer buffer = m_gltf.m_buffers[bufferView.buffer]; const size_t count = accessor.count; UINT target = bufferView.target; int elementSize; int componentSize; int numComponents; string sFilename_bin = sFolder + buffer.uri; fin.open(sFilename_bin, ios::binary); if (fin.fail()) { return false; } fin.seekg(bufferView.byteOffset, ios::beg); switch (accessor.componentType) { case GLTF_COMPONENT_TYPE_BYTE: componentSize = sizeof(GLbyte); break; case GLTF_COMPONENT_TYPE_UNSIGNED_BYTE: componentSize = sizeof(GLubyte); break; case GLTF_COMPONENT_TYPE_SHORT: componentSize = sizeof(GLshort); break; case GLTF_COMPONENT_TYPE_UNSIGNED_SHORT: componentSize = sizeof(GLushort); break; case GLTF_COMPONENT_TYPE_INT: componentSize = sizeof(GLint); break; case GLTF_COMPONENT_TYPE_UNSIGNED_INT: componentSize = sizeof(GLuint); break; case GLTF_COMPONENT_TYPE_FLOAT: componentSize = sizeof(GLfloat); break; case GLTF_COMPONENT_TYPE_DOUBLE: componentSize = sizeof(GLfloat); break; default: componentSize = 0; break; } if (accessor.type == "SCALAR") numComponents = 1; else if (accessor.type == "VEC2") numComponents = 2; else if (accessor.type == "VEC3") numComponents = 3; else if (accessor.type == "VEC4") numComponents = 4; else if (accessor.type == "MAT2") numComponents = 4; else if (accessor.type == "MAT3") numComponents = 9; else if (accessor.type == "MAT4") numComponents = 16; else return false; vector<float> fSubdata; // I'm pretty sure this is one of the problems, or related to it. If I use vector<USHORT> only half of the vector if filled, if I use GLubyte, the entire vector is filled, but the data might not be right vector<GLubyte> nSubdata; elementSize = (componentSize) * (numComponents); // Only fill the vector I'm using if (accessor.type == "SCALAR") { nSubdata.resize(count * numComponents); fin.read(reinterpret_cast<char*>(&nSubdata[0]), count/* * elementSize*/); // I commented this out since I'm not sure which size the .bin is storing the indice values, and I kept getting runtime errors, no matter what type I used for nSubdata } else { fSubdata.resize(count * numComponents); fin.read(reinterpret_cast<char*>(&fSubdata[0]), count * elementSize); } switch (target) { case GLTF_TARGET_ARRAY_BUFFER: { vertexData.insert(vertexData.end(), fSubdata.begin(), fSubdata.end()); glBindBuffer(GL_ARRAY_BUFFER, g_pGame->m_VBO); glBufferSubData(GL_ARRAY_BUFFER, offset, fSubdata.size() * componentSize, &fSubdata[0]); int attribute_index = 0; // I'm only loading vertex positions, the only attribute stored in the files for now glEnableVertexAttribArray(attribute_index); glVertexAttribPointer(0, numComponents, GL_FLOAT, GL_FALSE, componentSize * numComponents, (void*)(offset)); }break; case GLTF_TARGET_ELEMENT_ARRAY_BUFFER: { indiceData.insert(indiceData.end(), nSubdata.begin(), nSubdata.end()); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_pGame->m_EBO); // This is another area where I'm not sure of the correct values, but if componentSize is the correct size for the type being used it should be correct glBufferSubData is expecting the size in bytes, right? glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, offset, nSubdata.size() * componentSize, &nSubdata[0]); }break; default: return false; } if (accessor.type == "SCALAR") offset += nSubdata.size() * componentSize; else offset += fSubdata.size() * componentSize; fin.close(); return true; } these are the draw calls, I only use one at a time, but neither is currently display properly, g_pGame->m_indices is the same as indiceData vector, and vertexCount contains the correct vertex count, but I forgot to copy the lines of code containing where I set them, which is at the end of Mesh::Load(), I double checked the values to make sure. glBindVertexArray(g_pGame->m_VAO); glDrawElements(GL_LINES, g_pGame->m_indices.size(), GL_UNSIGNED_BYTE, (void*)0); // Only shows with GL_UNSIGNED_BYTE glDrawArrays(GL_LINES, 0, g_pGame->m_vertexCount); So, I'm asking what type should I use for the indices? it doesn't seem to be unsigned short, which is what I selected with the Khronos Group Exporter for blender. Also, am I reading part or all of the .bin file wrong? Test.gltf Test.bin
  22. That means how do I use base DirectX or OpenGL api's to make a physics based destruction simulation? Will it be just smart rendering or something else is required?
  23. Let's start

    Hi everybody, After my first game and story, it is time to start the new one with more experience this time. The primary goal is to avoid the same mistakes, so I will start to talk about it now. It is not the very beginning as I already have 11000 lines of codes. From Soul of Mask experiences, I learn that I should talk about my game as soon as possible. So I will introduce the new game to my two favourite forums GDN and another one in French: Game name: Not sure about it yet and it is not so important now. Game genre: Platform, Adventure. (kind of limbo and Ninja Gaiden mixt) Programming: C core engine, C or C++ game (not decided yet) Graphics: 2D/3D. Graphics lib: OpenGL > 3.5 Audio: Not sure yet (probably OpenAl) Platforms: for the moment Windows 10 and Linux (other may come later or not) Relative to the game ( story, artwork, ....): As I said it didn't start already, but story big picture is finished. So what am I doing now? I am finishing the first part that will make me decide if I continue the project or not. It is essentially technical like object collision, sprite animation, learning more about platform game technic... What did I do? Well, I decided to not use SDL2 as I want to port my game in some platform that does not support SDL. So I choose OpenGL. Plus I plan to use some 3D features in the game. So I mocked SDL2 behaviour and write it very specifically for my game. Here is a screenshot that shows objects rotating. I used a sprite sheet from Soul of Mask, we can also see a red box and a rectangle coming from a function call drawRectangle (more details soon) here we can see the code I will need to write for an animation: bkp_graphics_2dReady(BKP_TRUE); BKP_Rec dest,src; BKP_Rotate r; src.w = 64; src.h = 64; src.x = 2; src.y = 2; dest.w = 92; dest.h = 92; dest.x = 500; dest.y = 200; static float iii = 0; static double tm = 0; static double ta = 0; static int alpha = 255 ; static int dal = 2; tm = glfwGetTime(); //animation timers if(tm - ta > 64.0f / 1000.0f) { ta = tm; iii += .125; if(alpha <=0 || alpha >=255) dal = -dal; alpha += dal; } r.center.z = 0; r.angle = -iii; r.center.x = dest.x + dest.w / 2; r.center.y = dest.y + dest.h / 2; bkp_graphics_drawSurface(G[0] ,&dest,&src,&r,BKP_GRAPHICS_FLIPNONE, &alpha); dest.w = 368; dest.h = 138; dest.x -= 35; dest.y -= 20; bkp_graphics_2dsetColori(255,255,255,255); bkp_graphics_drawRectangle(&dest, BKP_FALSE); dest.w = 168; dest.x = 250; r.angle = iii; bkp_graphics_drawSurface(G[2] ,&dest,&src,&r,BKP_GRAPHICS_FLIPH, NULL); r.angle = -iii /4; bkp_graphics_drawSurface(G[0] ,&dest,&src,&r,BKP_GRAPHICS_FLIPV, NULL); dest.x = 620; bkp_graphics_2dsetColori(255,0,0,255 / 2); bkp_graphics_drawRectangle(&dest, BKP_TRUE); bkp_graphics_2dFlush(); Looks a little bit like SDL. In this example we can see all the job done so far, Scaling, Positioning, FLIP (vertical, horizontal), Rotate around a point and transparency. Those are all I used with SDL2 so far for Soul of Mask. The first objective is checked. Here is a video that illustrates it: bkp-2018-03-01_15.32.12 I don't go into the deep details about how I did things, but if people request it in the comments I will, I mean I would like to share it as I think some people who use OpenGL better than I do may give me some precious pieces of advice and improve the way I did it, in the meantime more beginner than I am will have a hint to start. Time for a little of performance: The graphics engine is able to draw on those 3 differents devices (here GPU integrated in CPU) - draw a frame in 0.016 ms for 1700 animated sprites on a Intel(R) Core(TM) i5-4210U CPU 1366x768 - draw a frame in 0.016 ms for 1000 animated sprites on a Broadwell Intel Core M-5Y70 HD 4k - draw a frame in 0.016 ms for 7000 animated sprites on a Intel(R) Core(TM) i7-7700 CPU 1920x1080 I didn't test it with a Nvidia or Radeon graphics card yet, for the moment it is irrelevant but it will come later. Conclusion on using custom vs SDL2 pro: Faster. I know everything behind it. con: Fewer features, less flexible, unoptimized and probably full of bugs I didn't notice yet. I also added a log system I didn't have it for my previous game so at any crash I add to try to reproduce it very hard now it is better just have to read log file on crashes. here is the output of this video: DEBUG set Moving to directory `../` [ INFO ][ 2018-03-01 15:27:06] -> Starting Graphics Engine ... [ INFO ][ 2018-03-01 15:27:06] -> Starting GLFW 3.2.1 X11 GLX EGL clock_gettime /dev/js Xf86vm shared [ INFO ][ 2018-03-01 15:27:06] -> Monitor info: [ INFO ][ 2018-03-01 15:27:06] -> #1 1920x1080 [ INFO ][ 2018-03-01 15:27:06] -> #0 1366x768 [ INFO ][ 2018-03-01 15:27:06] -> -------------------------- [ INFO ][ 2018-03-01 15:27:06] -> GL Context Params : [ INFO ][ 2018-03-01 15:27:06] -> GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS : 192 [ INFO ][ 2018-03-01 15:27:06] -> GL_MAX_CUBE_MAP_TEXTURE_SIZE : 16384 [ INFO ][ 2018-03-01 15:27:06] -> GL_MAX_DRAW_BUFFERS : 8 [ INFO ][ 2018-03-01 15:27:06] -> GL_MAX_FRAGMENT_UNIFORM_COMPONENTS : 16384 [ INFO ][ 2018-03-01 15:27:06] -> GL_MAX_TEXTURE_IMAGE_UNITS : 32 [ INFO ][ 2018-03-01 15:27:06] -> GL_MAX_TEXTURE_SIZE : 16384 [ INFO ][ 2018-03-01 15:27:06] -> GL_MAX_VARYING_FLOATS : 128 [ INFO ][ 2018-03-01 15:27:06] -> GL_MAX_VERTEX_ATTRIBS : 16 [ INFO ][ 2018-03-01 15:27:06] -> GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS : 32 [ INFO ][ 2018-03-01 15:27:06] -> GL_MAX_VERTEX_UNIFORM_COMPONENTS : 16384 [ INFO ][ 2018-03-01 15:27:06] -> GL_MAX_MULTISAMPLE_COVERAGE_MODES_NV : 0 [ INFO ][ 2018-03-01 15:27:06] -> GL_MAX_SAMPLES : 8 [ INFO ][ 2018-03-01 15:27:06] -> GL_MAX_MULTISAMPLE_COVERAGE_MODES_NV : 32768 : 32768 [ INFO ][ 2018-03-01 15:27:06] -> GL_MAX_SAMPLES : 0 [ INFO ][ 2018-03-01 15:27:06] -> -------------------------- [ INFO ][ 2018-03-01 15:27:06] -> Opening window with GLFW3 [OK] [ INFO ][ 2018-03-01 15:27:06] -> Renderer : Mesa DRI Intel(R) Haswell Mobile [ INFO ][ 2018-03-01 15:27:06] -> OpenGL version : 4.5 (Core Profile) Mesa 17.2.4 [ INFO ][ 2018-03-01 15:27:06] -> 4.5 [ INFO ][ 2018-03-01 15:27:06] -> program 3 GL_VALIDATE_STATUS = 1: [ INFO ][ 2018-03-01 15:27:06] -> ------------- shader programme 3 info --------------- [ INFO ][ 2018-03-01 15:27:06] -> GL_LINK_STATUS = 1: [ INFO ][ 2018-03-01 15:27:06] -> GL_ATTACHED_SHADERS = 2: [ INFO ][ 2018-03-01 15:27:06] -> GL_ACTIVE_ATTRIBUTES = 1: [ INFO ][ 2018-03-01 15:27:06] -> 0) type:vec3 name: vp location: 0 [ INFO ][ 2018-03-01 15:27:06] -> GL_ACTIVE_UNIFORMS = 2: [ INFO ][ 2018-03-01 15:27:06] -> 0) type:mat4 name: matrix location: 0 [ INFO ][ 2018-03-01 15:27:06] -> 1) type:vec4 name: color location: 1 [ INFO ][ 2018-03-01 15:27:06] -> ------------- end info --------------- [ INFO ][ 2018-03-01 15:27:06] -> program 6 GL_VALIDATE_STATUS = 1: [ INFO ][ 2018-03-01 15:27:06] -> ------------- shader programme 6 info --------------- [ INFO ][ 2018-03-01 15:27:06] -> GL_LINK_STATUS = 1: [ INFO ][ 2018-03-01 15:27:06] -> GL_ATTACHED_SHADERS = 2: [ INFO ][ 2018-03-01 15:27:06] -> GL_ACTIVE_ATTRIBUTES = 2: [ INFO ][ 2018-03-01 15:27:06] -> 0) type:vec3 name: vertex_position location: 0 [ INFO ][ 2018-03-01 15:27:06] -> 1) type:vec2 name: vt_loc location: 1 [ INFO ][ 2018-03-01 15:27:06] -> GL_ACTIVE_UNIFORMS = 3: [ INFO ][ 2018-03-01 15:27:06] -> 0) type:mat4 name: matrix location: 0 [ INFO ][ 2018-03-01 15:27:06] -> 1) type:vec4 name: vt_ location: 1 [ INFO ][ 2018-03-01 15:27:06] -> 2) type:sampler2D name: basic_texture location: 2 [ INFO ][ 2018-03-01 15:27:06] -> ------------- end info --------------- [ INFO ][ 2018-03-01 15:27:06] -> program 9 GL_VALIDATE_STATUS = 1: [ INFO ][ 2018-03-01 15:27:06] -> ------------- shader programme 9 info --------------- [ INFO ][ 2018-03-01 15:27:06] -> GL_LINK_STATUS = 1: [ INFO ][ 2018-03-01 15:27:06] -> GL_ATTACHED_SHADERS = 2: [ INFO ][ 2018-03-01 15:27:06] -> GL_ACTIVE_ATTRIBUTES = 2: [ INFO ][ 2018-03-01 15:27:06] -> 0) type:vec3 name: vertex_position location: 0 [ INFO ][ 2018-03-01 15:27:06] -> 1) type:vec2 name: vt_loc location: 1 [ INFO ][ 2018-03-01 15:27:06] -> GL_ACTIVE_UNIFORMS = 4: [ INFO ][ 2018-03-01 15:27:06] -> 0) type:mat4 name: matrix location: 0 [ INFO ][ 2018-03-01 15:27:06] -> 1) type:vec4 name: vt_ location: 1 [ INFO ][ 2018-03-01 15:27:06] -> 2) type:sampler2D name: basic_texture location: 2 [ INFO ][ 2018-03-01 15:27:06] -> 3) type:float name: alpha_factor location: 3 [ INFO ][ 2018-03-01 15:27:06] -> ------------- end info --------------- [ INFO ][ 2018-03-01 15:27:06] -> 2D Graphics Engine start [OK] [ INFO ][ 2018-03-01 15:27:06] -> Graphics Engine started [ INFO ][ 2018-03-01 15:27:17] -> [ INFO ][ 2018-03-01 15:27:17] -> deleting shader programe 3 [ INFO ][ 2018-03-01 15:27:17] -> deleting shader programe 6 [ INFO ][ 2018-03-01 15:27:17] -> deleting shader programe 9 [ INFO ][ 2018-03-01 15:27:17] -> 2D Graphics Engine closed [OK] [ INFO ][ 2018-03-01 15:27:17] -> Window closed [OK] [ INFO ][ 2018-03-01 15:27:17] -> Graphics Engine stopped [OK] [ INFO ][ 2018-03-01 15:27:17] -> Logger closed [OK] [ INFO ][ 2018-03-01 15:27:17] -> Game Engine stopped [OK] What's next? I am learning about the type of game I am doing, I should have some basic movement of main character and platform collisions soon. I promise myself I will not do everything alone again so this blog will be also used to seduce whoever want to jump into this adventure. But by experience I know I may finish alone again (who knows). Thanks for reading, I will post more as soon as I have something new to show. Have a nice day.
  24. I am somewhat new to game development and trying to create a basic 3d engine. I have managed to set up a first person camera and it seems to be working fine for the most part. While I am able to look up, down, left and right just fine the camera is constrained to the mouse movement in the window (i.e when the mouse reaches edges of the window it discontinues camera rotation and mouse is out of window bounds. I tried to use SDL_WarpMouseInWindow(window, center.x,center.y) but when I do this then it messes up the camera and the camera is stuck, even though there is some slight movement of the camera, it keeps going back to the center. void Camera::UpdateViewByMouse(SDL_Window &window, glm::vec2 mousePosition) { float xDistanceFromWindowCenter = mousePosition.x - ((float)1024 / 2) ; float yDistanceFromWindowCenter = ((float)720 / 2) - mousePosition.y; yaw = xDistanceFromWindowCenter * cameraRotationSpeed; pitch = yDistanceFromWindowCenter * cameraRotationSpeed; SDL_WarpMouseInWindow(&window, 1024 / 2, 768 / 2); } i’ve been stuck on this for far too long. any help would be much appreciated i have also tried relative mouse movement, and .xrel and .yrel to avail. polling mouse state with sdl_event. I do also know that SDL_WarpMouseInWindow makes change to event and have tried also ignore and reenabling to no avail
  25. Hi all this is my first post on this forum. First of all i want to say you that i've searched many posts on this forum about this specific argument, without success, so i write another one.... Im a beginner. I want use GPU geometry clipmaps algorithm to visualize virtual inifinte terrains. I already tried to use vertex texture fetch with a single sampler2D with success. Readed many papers about the argument and all speak about the fact that EVERY level of a geometry clipmap, has its own texture. What means this exactly? i have to upload on graphic card a sampler2DArray? With a single sampler2D is conceptually simple. Creating a vbo and ibo on cpu (the vbo contains only the positions on X-Z plane, not the heights) and upload on GPU the texture containing the elevations. In vertex shader i sample, for every vertex, the relative height to te uv coordinate. But i can't imagine how can i reproduce various 2d footprint for every level of the clipmap. The only way i can imagine is follow: Upload the finer texture on GPU (entire heightmap). Create on CPU, and for each level of clipmap, the 2D footprints of entire clipmap. So in CPU i create all clipmap levels in terms of X-Z plane. In vertex shader sampling these values is simple using vertex texture fetch. So, how can i to sample a sampler2DArray in vertex shader, instead of upload a sampler2D of entire clipmap? Sorry for my VERY bad english, i hope i have been clear.
  • Advertisement