Search Results

Search found 234 results on 10 pages for 'glsl'.

Page 9/10 | < Previous Page | 5 6 7 8 9 10  | Next Page >

  • Using a texture as an integer array (OpenGL 3.3, shader version 3.3)

    - by Cubic
    I'm trying to have something like an integer array uniform for my fragment shader (I only need read access). Since it's a fairly large chunk of data (not so large that uploading it in every frame would be impossible, but enough to make me want to rather not do it). Essentially I want to just pass it a uniform telling the shader where this "array" is. I believe I can use a 1D texture for this, but I don't know how (actually, I don't know how to do many things because I just can't seem to find a reference for GLSL 3.3, I only ever find references for the C API). This sounds like a rather basic question and I'm sure it's been answered already somewhere, but I keep searching and can't quite find what I'm looking for.

    Read the article

  • Loaded OBJ Model Will Not Display in OpenGL / C++ Project

    - by Drake Summers
    I have been experimenting with new effects in game development. The programs I have written have been using generic shapes for the visuals. I wanted to test the effects on something a bit more complex, and wrote a resource loader for Wavefront OBJ files. I started with a simple cube in blender, exported it to an OBJ file with just vertices and triangulated faces, and used it to test the resource loader. I could not get the mesh to show up in my application. The loader never gave me any errors, so I wrote a snippet to loop through my vertex and index arrays that were returned from the loader. The data is exactly the way it is supposed to be. So I simplified the OBJ file by editing it directly to just show a front facing square. Still, nothing is displayed in the application. And don't worry, I did check to make sure that I decreased the value of each index by one while importing the OBJ. - BEGIN EDIT I also tested using glDrawArrays(GL_TRIANGLES, 0, 3 ); to draw the first triangle and it worked! So the issue could be in the binding of the VBO/IBO items. END EDIT - INDEX/VERTEX ARRAY OUTPUT: GLOBALS AND INITIALIZATION FUNCTION: GLuint program; GLint attrib_coord3d; std::vector<GLfloat> vertices; std::vector<GLushort> indices; GLuint vertexbuffer, indexbuffer; GLint uniform_mvp; int initialize() { if (loadModel("test.obj", vertices, indices)) { GLfloat myverts[vertices.size()]; copy(vertices.begin(), vertices.end(), myverts); GLushort myinds[indices.size()]; copy(indices.begin(), indices.end(), myinds); glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(myverts), myverts, GL_STATIC_DRAW); glGenBuffers(1, &indexbuffer); glBindBuffer(GL_ARRAY_BUFFER, indexbuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(myinds), myinds, GL_STATIC_DRAW); // OUTPUT DATA FROM NEW ARRAYS TO CONSOLE // ERROR HANDLING OMITTED FOR BREVITY } GLint link_result = GL_FALSE; GLuint vert_shader, frag_shader; if ((vert_shader = create_shader("tri.v.glsl", GL_VERTEX_SHADER)) == 0) return 0; if ((frag_shader = create_shader("tri.f.glsl", GL_FRAGMENT_SHADER)) == 0) return 0; program = glCreateProgram(); glAttachShader(program, vert_shader); glAttachShader(program, frag_shader); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &link_result); // ERROR HANDLING OMITTED FOR BREVITY const char* attrib_name; attrib_name = "coord3d"; attrib_coord3d = glGetAttribLocation(program, attrib_name); // ERROR HANDLING OMITTED FOR BREVITY const char* uniform_name; uniform_name = "mvp"; uniform_mvp = glGetUniformLocation(program, uniform_name); // ERROR HANDLING OMITTED FOR BREVITY return 1; } RENDERING FUNCTION: glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3(0.0, 0.0, -4.0)); glm::mat4 view = glm::lookAt(glm::vec3(0.0, 0.0, 4.0), glm::vec3(0.0, 0.0, 3.0), glm::vec3(0.0, 1.0, 0.0)); glm::mat4 projection = glm::perspective(45.0f, 1.0f*(screen_width/screen_height), 0.1f, 10.0f); glm::mat4 mvp = projection * view * model; int size; glUseProgram(program); glUniformMatrix4fv(uniform_mvp, 1, GL_FALSE, glm::value_ptr(mvp)); glClearColor(0.5, 0.5, 0.5, 1.0); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glEnableVertexAttribArray(attrib_coord3d); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer(attrib_coord3d, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexbuffer); glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &size); glDrawElements(GL_TRIANGLES, size/sizeof(GLushort), GL_UNSIGNED_SHORT, 0); glDisableVertexAttribArray(attrib_coord3d); VERTEX SHADER: attribute vec3 coord3d; uniform mat4 mvp; void main(void) { gl_Position = mvp * vec4(coord3d, 1.0); } FRAGMENT SHADER: void main(void) { gl_FragColor[0] = 0.0; gl_FragColor[1] = 0.0; gl_FragColor[2] = 1.0; gl_FragColor[3] = 1.0; } OBJ RESOURCE LOADER: bool loadModel(const char * path, std::vector<GLfloat> &out_vertices, std::vector<GLushort> &out_indices) { std::vector<GLfloat> temp_vertices; std::vector<GLushort> vertexIndices; FILE * file = fopen(path, "r"); // ERROR HANDLING OMITTED FOR BREVITY while(1) { char lineHeader[128]; int res = fscanf(file, "%s", lineHeader); if (res == EOF) { break; } if (strcmp(lineHeader, "v") == 0) { float _x, _y, _z; fscanf(file, "%f %f %f\n", &_x, &_y, &_z ); out_vertices.push_back(_x); out_vertices.push_back(_y); out_vertices.push_back(_z); } else if (strcmp(lineHeader, "f") == 0) { unsigned int vertexIndex[3]; int matches = fscanf(file, "%d %d %d\n", &vertexIndex[0], &vertexIndex[1], &vertexIndex[2]); out_indices.push_back(vertexIndex[0] - 1); out_indices.push_back(vertexIndex[1] - 1); out_indices.push_back(vertexIndex[2] - 1); } else { ... } } // ERROR HANDLING OMITTED FOR BREVITY return true; } I can edit the question to provide any further info you may need. I attempted to provide everything of relevance and omit what may have been unnecessary. I'm hoping this isn't some really poor mistake, because I have been at this for a few days now. If anyone has any suggestions or advice on the matter, I look forward to hearing it. As a final note: I added some arrays into the code with manually entered data, and was able to display meshes by using those arrays instead of the generated ones. I do not understand!

    Read the article

  • OpenGL ES Shader help (Blending)

    - by Chris
    Earlier I required assistance getting to grips with how to retain the alpha channel of a transparent texture in my colourised texture shader program. Whilst playing with that first version of my program (before obtaining the solution to my first requirement), I managed to enable transparency for the whole texture (effectively blending via GLSL), and I quite liked this, and I would now like to know if and how it is possible to retain this blending effect, on top of the existing output without affecting the original alpha channel - as I don't know how to input this transparency via the parameter that is already being provided with the textures alpha channel. A basic example of the blending program I am referring to (minus any other functionality) is as follows... varying vec2 texCoord; uniform sampler2D texSampler; void main() { gl_FragColor = vec4(texture2D(texSampler,texCoord).xyz,0.5); } Where 0.5 is the transparency (blending effect) of the whole texture. This is the current version of my program, which provides the ability to colour a texture according the colour parameter passed to the program, and retains the alpha channel of the original texture. varying vec2 texCoord; uniform sampler2D texSampler; uniform vec3 colour; void main() { gl_FragColor = vec4(colour,1) * vec4(texture2D(texSampler,texCoord).xyz,texture2D(texSampler,texCoord).w); } I need to know if it is possible to apply transparency on top this program, without affecting the original alpha channel which I have already preserved. I hope this makes enough sense, I am sure it is possible, and if so I should imagine it is rather simple, but this has me stumped. Any help much appreachiated. Cheers, Chris

    Read the article

  • Unity custom shaders and z-fighting

    - by Heisenbug
    I've just readed a chapter of Unity iOS Essential by Robert Wiebe. It shows a solution for handling z-figthing problem occuring while rendering a street on a plane with the same y offset. Basically it modified Normal-Diffuse shader provided by Unity, specifing the (texture?) offset in -1, -1. Here's basically what the shader looks like: Shader "Custom/ModifiedNormalDiffuse" { Properties { _Color ("Main Color", Color) = (1,1,1,1) _MainTex ("Base (RGB)", 2D) = "white" {} } SubShader { Offset -1,-1 //THIS IS THE ADDED LINE Tags { "RenderType"="Opaque" } LOD 200 CGPROGRAM #pragma surface surf Lambert sampler2D _MainTex; fixed4 _Color; struct Input { float2 uv_MainTex; }; void surf (Input IN, inout SurfaceOutput o) { half4 c = tex2D (_MainTex, IN.uv_MainTex) *_Color; o.Albedo = c.rgb; o.Alpha = c.a; } ENDCG } FallBack "Diffuse" } Ok. That's simple and it works. The author says about it: ...we could use a copy of the shader that draw the road at an Offset of -1, -1 so that whenever the two textures are drawn, the road is always drawn last. I don't know CG nor GLSL, but I've a little bit of experience with HLSL. Anyway I can't figure out what exactly is going on. Could anyone explain me what exactly Offset directly does, and how is solves z-fighting problems?

    Read the article

  • VBO and shaders confusion, what's their connection?

    - by Jeffrey
    Considering OpenGL 2.1 VBOs and 1.20 GLSL shaders: When creating an entity like "Zombie", is it good to initialize just the VBO buffer with the data once and do N glDrawArrays() calls per each N zombies? Is there a more efficient way? (With a single call we cannot pass different uniforms to the shader to calculate an offset, see point 3) When dealing with logical object (player, tree, cube etc), should I always use the same shader or should I customize (or be able to customize) the shaders per each object? Considering an entity class, should I create and define the shader at object initialization? When having a movable object such as a human, is there any more powerful way to deal with its coordinates than to initialize its VBO object at 0,0 and define an uniform offset to pass to the shader to calculate its real position? Could you make an example of the Data Oriented Design on creating a generic zombie class? Is the following good? Zombielist class: class ZombieList { GLuint vbo; // generic zombie vertex model std::vector<color>; // object default color std::vector<texture>; // objects textures std::vector<vector3D>; // objects positions public: unsigned int create(); // return object id void move(unsigned int objId, vector3D offset); void rotate(unsigned int objId, float angle); void setColor(unsigned int objId, color c); void setPosition(unsigned int objId, color c); void setTexture(unsigned int, unsigned int); ... void update(Player*); // move towards player, attack if near } Example: Player p; Zombielist zl; unsigned int first = zl.create(); zl.setPosition(first, vector3D(50, 50)); zl.setTexture(first, texture("zombie1.png")); ... while (running) { // main loop ... zl.update(&p); zl.draw(); // draw every zombie }

    Read the article

  • Render on other render targets starting from one already rendered on

    - by JTulip
    I have to perform a double pass convolution on a texture that is actually the color attachment of another render target, and store it in the color attachment of ANOTHER render target. This must be done multiple time, but using the same texture as starting point What I do now is (a bit abstracted, but what I have abstract is guaranteed to work singularly) renderOnRT(firstTarget); // This is working. for each other RT currRT{ glBindFramebuffer(GL_FRAMEBUFFER, currRT.frameBufferID); programX.use(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, firstTarget.colorAttachmentID); programX.setUniform1i("colourTexture",0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, firstTarget.depthAttachmentID); programX.setUniform1i("depthTexture",1); glBindBuffer(GL_ARRAY_BUFFER, quadBuffID); // quadBuffID is a VBO for a screen aligned quad. It is fine. programX.vertexAttribPointer(POSITION_ATTRIBUTE, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); glDrawArrays(GL_QUADS,0,4); programY.use(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, currRT.colorAttachmentID); // The second pass is done on the previous pass programY.setUniform1i("colourTexture",0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, currRT.depthAttachmentID); programY.setUniform1i("depthTexture",1); glBindBuffer(GL_ARRAY_BUFFER, quadBuffID); programY.vertexAttribPointer(POSITION_ATTRIBUTE, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); glDrawArrays(GL_QUADS, 0, 4); } The problem is that I end up with black textures and not the wanted result. The GLSL programs program(X,Y) works fine, already tested on single targets. Is there something stupid I am missing? Even an hint is much appreciated, thanks!

    Read the article

  • Creating a retro-style palette swapping effect in OpenGL

    - by Zack The Human
    I'm working on a Megaman-like game where I need to change the color of certain pixels at runtime. For reference: in Megaman when you change your selected weapon then main character's palette changes to reflect the selected weapon. Not all of the sprite's colors change, only certain ones do. This kind of effect was common and quite easy to do on the NES since the programmer had access to the palette and the logical mapping between pixels and palette indices. On modern hardware, though, this is a bit more challenging because the concept of palettes is not the same. All of my textures are 32-bit and do not use palettes. There are two ways I know of to achieve the effect I want, but I'm curious if there are better ways to achieve this effect easily. The two options I know of are: Use a shader and write some GLSL to perform the "palette swapping" behavior. If shaders are not available (say, because the graphics card doesn't support them) then it is possible to clone the "original" textures and generate different versions with the color changes pre-applied. Ideally I would like to use a shader since it seems straightforward and requires little additional work opposed to the duplicated-texture method. I worry that duplicating textures just to change a color in them is wasting VRAM -- should I not worry about that?

    Read the article

  • OpenGL, objects disappear at a certain z distance

    - by smoth190
    I'm writing a managed OpenGL library in C++, and I'm having a pretty annoying problem. Whenever I set an objects position to -2.0 or lower, the object disappears. And at distances 0 through -1.9, it doesn't appear to move away from them camera. I have a world matrix (which is multiplied by the objects position to move it), a view matrix (which is just the identity matrix currently) and a projection matrix, which is setup like this: FOV: 45.0f Aspect Ratio: 1 zNear: 0.1f zFar: 100.0f using GLMs glm::perspective method. The order the matrices are multiplied by in the shader is world, view, projection, then position. I can move the object along the X and Y axis perfectly fine. I have depth testing enabled, using GL_LEQUAL. I can change the actually vertices positions to anything I want, and they move away from the camera or towards it perfectly fine. It just seems to be the world matrix acting up. I'm using glm::mat4 for the world matrix, and glm::vec3 for positions. Whats going on here? I'm also using OpenGL 3.1, GLSL version 140 (1.4?).

    Read the article

  • Basic OpenGL ES2 (iPhone Simulator) question...

    - by David
    Hi! I'm trying to modify the fragment shader which is part of the standard iPhone/XCode OpenGL ES template. I want to make it so that every other row of pixels is transparent. I have this code so far: varying lowp vec4 colorVarying; void main() { gl_FragColor = vec4(colorVarying.x, colorVarying.y, colorVarying.z, floor(mod(gl_FragCoord.y, 2.0))); } But when I compile and run I still get the same square moving up and down with no other effects. What am I doing wrong here? I'm a complete n00b at Glsl - I'm trying to teach myself the very basics. (starting with this tutorial - http://www.mobileorchard.com/getting-started-with-opengl-es-20-on-the-iphone-3gs/) Please help! Thanks! David :)

    Read the article

  • Wine is no longer able to initialize OpenGL

    - by nebukadnezzar
    Since a while, wine is no longer able to initialize OpenGL on my 64bit Linux. This is by no means a unique problem to me- Lots of people with nvidia cards running 64bit linux seem to have this problem with wine on oneiric: http://forum.winehq.org/viewtopic.php?p=66856&sid=9d6e5ad628ee6fb6e5ef04577275daed http://forum.pinguyos.com/Thread-Wine-OpenGl-Problem https://bbs.archlinux.org/viewtopic.php?id=137696 And while some launchpad bug reports say one should use this workaround: LD_PRELOAD=/usr/lib32/nvidia-current/libGL.so.1 wine <app> It unfortunately does not solve the problem at all for me; That is, if i'd run CS:S, the game will run just fine for a while, but will abort after some time, including a range of GLSL-related errors. Here the startup errors from simply running steam: + wine steam.exe fixme:process:GetLogicalProcessorInformation ((nil),0x33e488): stub [.. snip ...] fixme:dwmapi:DwmSetWindowAttribute (0x1009a, 3, 0x33d384, 4) stub fixme:dwmapi:DwmSetWindowAttribute (0x1009a, 4, 0x33d374, 4) stub err:wgl:is_extension_supported No OpenGL extensions found, check if your OpenGL setup is correct! err:wgl:is_extension_supported No OpenGL extensions found, check if your OpenGL setup is correct! err:wgl:is_extension_supported No OpenGL extensions found, check if your OpenGL setup is correct! [... this error is being reported a few dozen times, so snip again ...] err:wgl:is_extension_supported No OpenGL extensions found, check if your OpenGL setup is correct! err:wgl:is_extension_supported No OpenGL extensions found, check if your OpenGL setup is correct! err:wgl:is_extension_supported No OpenGL extensions found, check if your OpenGL setup is correct! err:wgl:is_extension_supported No OpenGL extensions found, check if your OpenGL setup is correct! fixme:iphlpapi:NotifyAddrChange (Handle 0x47cdba8, overlapped 0x45dba80): stub fixme:winsock:WSALookupServiceBeginW (0x47cdbc8 0x00000ff0 0x47cdbc4) Stub! [... snip ...] Here are the errors reported while running, and after running (because the log is huge-ish, it's pasted elsewhere): http://paste.ubuntu.com/901925/ Now, 32bit OpenGL works just fine; The 32bit executables of Nexuiz, for example, work just fine. That being said, I'm suspecting that this is a problem of wine itself. I've already manually built the git version of wine, to no avail. So what's going on? Is something broken? How do I check (correctly) whether something is broken? How do I solve this?

    Read the article

  • How to send multiple MVP matrices to a vertex shader in OpenGL ES 2.0

    - by Carbon Crystal
    I'm working my way through optimizing the rendering of sprites in a 2D game using OpenGL ES and I've hit the limit of my knowledge when it comes to GLSL and vertex shaders. I have two large float buffers containing my vertex coordinates and texture coordinates (eventually this will be one buffer) for multiple sprites in order to perform a single glDrawArrays call. This works but I've hit a snag when it comes to passing the transformation matrix into the vertex shader. My shader code is: uniform mat4 u_MVPMatrix; attribute vec4 a_Position; attribute vec2 a_TexCoordinate; varying vec2 v_TexCoordinate; void main() { v_TexCoordinate = a_TexCoordinate; gl_Position = u_MVPMatrix * a_Position; } In Java (Android) I am using a FloatBuffer to store the vertex/texture data and this is provided to the shader like so: mGlEs20.glVertexAttribPointer(mVertexHandle, Globals.GL_POSITION_VERTEX_COUNT, GLES20.GL_FLOAT, false, 0, mVertexCoordinates); mGlEs20.glVertexAttribPointer(mTextureCoordinateHandle, Globals.GL_TEXTURE_VERTEX_COUNT, GLES20.GL_FLOAT, false, 0, mTextureCoordinates); (The Globals.GL_POSITION_VERTEX_COUNT etc are just integers with the value of 2 right now) And I'm passing the MVP (Model/View/Projection) matrix buffer like this: GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mModelCoordinates); (mModelCoordinates is a FloatBuffer containing 16-float sequences representing the MVP matrix for each sprite) This renders my scene but all the sprites share the same transformation, so it's obviously only picking the first 16 elements from the buffer which makes sense since I am passing in "1" as the second parameter. The documentation for this method says: "This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices." So I tried modifying the shader with a fixed size array large enough to accomodate most of my scenarios: uniform mat4 u_MVPMatrix[1000]; But this lead to an error in the shader: cannot convert from 'uniform array of 4X4 matrix of float' to 'Position 4-component vector of float' This just seems wrong anyway as it's not clear to me how the shader would know when to transition to the next matrix anyway. Anyone have an idea how I can get my shader to pick up a different MVP matrix (i.e. the NEXT 16 floats) from my MVP buffer for every 4 vertices it encounters? (I am using GL_TRIANGLE_STRIP so each sprite has 4 vertices). Thanks!

    Read the article

  • How to snap a 2D Quad to the mouse cursor using OpenGL 3.0/WIN32?

    - by NoobScratcher
    I've been having issues trying to snap a 2D Quad to the mouse cursor position I'm able : 1.) To get values into posX, posY, posZ 2.) Translate with the values from those 3 variables But the quad positioning I'm not able to do correctly in such a way that the 2D Quad is near the mouse cursor using those values from those 3 variables eg."posX, posY, posZ" I need the mouse cursor in the center of the 2D Quad. I'm hoping someone can help me achieve this. I've tried searching around with no avail. Heres the function that is ment to do the snapping but instead creates weird flicker or shows nothing at all only the 3d models show up : void display() { glClearColor(0.0,0.0,0.0,1.0); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); for(std::vector<GLuint>::iterator I = cube.begin(); I != cube.end(); ++I) { glCallList(*I); } if(DrawArea == true) { glReadPixels(winX, winY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ); cerr << winZ << endl; glGetDoublev(GL_MODELVIEW_MATRIX, modelview); glGetDoublev(GL_PROJECTION_MATRIX, projection); glGetIntegerv(GL_VIEWPORT, viewport); gluUnProject(winX, winY, winZ , modelview, projection, viewport, &posX, &posY, & posZ); glBindTexture(GL_TEXTURE_2D, DrawAreaTexture); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB, DrawAreaSurface->w, DrawAreaSurface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, DrawAreaSurface->pixels); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, DrawAreaTexture); glTranslatef(posX , posY, posZ); glBegin(GL_QUADS); glTexCoord2f (0.0, 0.0); glVertex3f(0.5, 0.5, 0); glTexCoord2f (1.0, 0.0); glVertex3f(0, 0.5, 0); glTexCoord2f (1.0, 1.0); glVertex3f(0, 0, 0); glTexCoord2f (0.0, 1.0); glVertex3f(0.5, 0, 0); glEnd(); } SwapBuffers(hDC); } I'm using : OpenGL 3.0 WIN32 API C++ GLSL if you really want the full source here it is - http://pastebin.com/1Ncm9HNf , Its pretty messy.

    Read the article

  • How to snap a 2D Quad to the mouse cursor using OpenGL 3.0?

    - by NoobScratcher
    I've been having issues trying to snap a 2D Quad to the mouse cursor position I'm able : 1.) To get values into posX, posY, posZ 2.) Translate with the values from those 3 variables But the quad positioning I'm not able to do correctly in such a way that the 2D Quad is near the mouse cursor using those values from those 3 variables eg."posX, posY, posZ" I need the mouse cursor in the center of the 2D Quad. I'm hoping someone can help me achieve this. I've tried searching around with no avail. Heres the function that is ment to do the snapping but instead creates weird flicker or shows nothing at all only the 3d models show up : void display() { glClearColor(0.0,0.0,0.0,1.0); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); for(std::vector<GLuint>::iterator I = cube.begin(); I != cube.end(); ++I) { glCallList(*I); } if(DrawArea == true) { glReadPixels(winX, winY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ); cerr << winZ << endl; glGetDoublev(GL_MODELVIEW_MATRIX, modelview); glGetDoublev(GL_PROJECTION_MATRIX, projection); glGetIntegerv(GL_VIEWPORT, viewport); gluUnProject(winX, winY, winZ , modelview, projection, viewport, &posX, &posY, & posZ); glBindTexture(GL_TEXTURE_2D, DrawAreaTexture); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB, DrawAreaSurface->w, DrawAreaSurface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, DrawAreaSurface->pixels); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, DrawAreaTexture); glTranslatef(posX , posY, posZ); glBegin(GL_QUADS); glTexCoord2f (0.0, 0.0); glVertex3f(0.5, 0.5, 0); glTexCoord2f (1.0, 0.0); glVertex3f(0, 0.5, 0); glTexCoord2f (1.0, 1.0); glVertex3f(0, 0, 0); glTexCoord2f (0.0, 1.0); glVertex3f(0.5, 0, 0); glEnd(); } SwapBuffers(hDC); } I'm using : OpenGL 3.0 WIN32 API C++ GLSL if you really want the full source here it is - http://pastebin.com/1Ncm9HNf , Its pretty messy.

    Read the article

  • Speeding up procedural texture generation

    - by FalconNL
    Recently I've begun working on a game that takes place in a procedurally generated solar system. After a bit of a learning curve (having neither worked with Scala, OpenGL 2 ES or Libgdx before), I have a basic tech demo going where you spin around a single procedurally textured planet: The problem I'm running into is the performance of the texture generation. A quick overview of what I'm doing: a planet is a cube that has been deformed to a sphere. To each side, a n x n (e.g. 256 x 256) texture is applied, which are bundled in one 8n x n texture that is sent to the fragment shader. The last two spaces are not used, they're only there to make sure the width is a power of 2. The texture is currently generated on the CPU, using the updated 2012 version of the simplex noise algorithm linked to in the paper 'Simplex noise demystified'. The scene I'm using to test the algorithm contains two spheres: the planet and the background. Both use a greyscale texture consisting of six octaves of 3D simplex noise, so for example if we choose 128x128 as the texture size there are 128 x 128 x 6 x 2 x 6 = about 1.2 million calls to the noise function. The closest you will get to the planet is about what's shown in the screenshot and since the game's target resolution is 1280x720 that means I'd prefer to use 512x512 textures. Combine that with the fact the actual textures will of course be more complicated than basic noise (There will be a day and night texture, blended in the fragment shader based on sunlight, and a specular mask. I need noise for continents, terrain color variation, clouds, city lights, etc.) and we're looking at something like 512 x 512 x 6 x 3 x 15 = 70 million noise calls for the planet alone. In the final game, there will be activities when traveling between planets, so a wait of 5 or 10 seconds, possibly 20, would be acceptable since I can calculate the texture in the background while traveling, though obviously the faster the better. Getting back to our test scene, performance on my PC isn't too terrible, though still too slow considering the final result is going to be about 60 times worse: 128x128 : 0.1s 256x256 : 0.4s 512x512 : 1.7s This is after I moved all performance-critical code to Java, since trying to do so in Scala was a lot worse. Running this on my phone (a Samsung Galaxy S3), however, produces a more problematic result: 128x128 : 2s 256x256 : 7s 512x512 : 29s Already far too long, and that's not even factoring in the fact that it'll be minutes instead of seconds in the final version. Clearly something needs to be done. Personally, I see a few potential avenues, though I'm not particularly keen on any of them yet: Don't precalculate the textures, but let the fragment shader calculate everything. Probably not feasible, because at one point I had the background as a fullscreen quad with a pixel shader and I got about 1 fps on my phone. Use the GPU to render the texture once, store it and use the stored texture from then on. Upside: might be faster than doing it on the CPU since the GPU is supposed to be faster at floating point calculations. Downside: effects that cannot (easily) be expressed as functions of simplex noise (e.g. gas planet vortices, moon craters, etc.) are a lot more difficult to code in GLSL than in Scala/Java. Calculate a large amount of noise textures and ship them with the application. I'd like to avoid this if at all possible. Lower the resolution. Buys me a 4x performance gain, which isn't really enough plus I lose a lot of quality. Find a faster noise algorithm. If anyone has one I'm all ears, but simplex is already supposed to be faster than perlin. Adopt a pixel art style, allowing for lower resolution textures and fewer noise octaves. While I originally envisioned the game in this style, I've come to prefer the realistic approach. I'm doing something wrong and the performance should already be one or two orders of magnitude better. If this is the case, please let me know. If anyone has any suggestions, tips, workarounds, or other comments regarding this problem I'd love to hear them.

    Read the article

  • Issues glVertexAttribPointer last 2 parameters?

    - by NoobScratcher
    Introduction Hello I will start out by explaining my setup, showing samples as I go along explaining the situation. I'm using these tools: OpenGL 3.3 GLSL 330 C++ Problem The problem is when I render the wavefront obj 3d model it gives a very weird visual glitch the model was supposed to be a square but instead its a triangluated mess with parts of the vertexes pointing in a stretched direction in massive amounts towards the bottom left side of the frustum.... Explanation: I'm using std::vectors to store my wavefront .obj model data using sscanf to get the floating point values into the structure members x,y,z and store them into the Points structure variable p; int index = IndexAssigner(1, 1); ifstream file (list[index].c_str() ); points.push_back(Point()); Point p; int face[4]; while (!file.eof() ) { char modelbuffer[10000]; file.getline(modelbuffer, 10000); switch(modelbuffer[0]) { case 'v' : sscanf(modelbuffer, "v %f %f %f", &p.x, &p.y, &p.z); points.push_back(p); break; case 'f': sscanf(modelbuffer, "f %d %d %d %d", face, face+1, face+2, face+3 ); faces.push_back(face[0]); faces.push_back(face[1]); faces.push_back(face[2]); faces.push_back(face[3]); } //Turn on FileReader aka "RENDER CODE" FileReader = true; } then I render the Points vector using the .data() member of std::vectors to the frustum. Other declarations: int numfloats = 4; float* point=reinterpret_cast<float*>(&points[0]); int num_bytes=numfloats*sizeof(float); Vector declarations: struct Point {float x, y , z; }; std::vector<int>faces; std::vector<Point>points; Render code: glGenBuffers(1, &vertexbuffer); glGenTextures(1, &ModelTexture); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBindTexture(GL_TEXTURE_3D, ModelTexture); glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA, ModelSurface->w, ModelSurface->h, 0, GL_BGR, GL_UNSIGNED_BYTE, ModelSurface->pixels); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glBufferData(GL_ARRAY_BUFFER, sizeof(points), points.data(), GL_STATIC_DRAW); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE,num_bytes ,points.data()); glEnableVertexAttribArray(3); //Translation Process GLfloat TranslationMatrix[] = { 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0 }; //Send Translation Matrix up to the vertex shader glUniformMatrix4fv(translation, 1, TRUE, TranslationMatrix); glDrawElements( GL_QUADS, faces.size(), GL_UNSIGNED_INT, faces.data()); I tried looking at what was causing this and went through every function every parameter ,etc looked at the man pages. Then found out that it could be my glVertexAttribPointer. Here are the man pages for glVertexAttribPointer http://www.opengl.org/sdk/docs/man/xhtml/glVertexAttribPointer.xml The last 2 parameters is my problem How do I write those 2 last parameters do I try putting the data from Points into it?. glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE,num_bytes ,points.data()); How does it work with vectors? Is it fast?* if you can not be bothered too look at the man pages here is the scripts coming from the man pages directly. Stride Specifies the byte offset between consecutive generic vertex attributes. If stride is 0, the generic vertex attributes are understood to be tightly packed in the array. The initial value is 0. Pointer Specifies a pointer to the first component of the first generic vertex attribute in the array. The initial value is 0. If you want my full source - http://ideone.com/fPfkg Thanks Again if you do read this.

    Read the article

  • std::vector::size with glDrawElements crashes?

    - by NoobScratcher
    ( win32 / OpenGL 3.3 / GLSL 330 ) I decided after a long time of trying to do a graphical user interface using just opengl graphics to go back to a gui toolkit and so in the process have had to port alot of my code to win32. But I have a problem with my glDrawElement function. my program compiles and runs fine until it gets to glDrawElements then crashes.. which is rather annoying right. so I was trying to figure out why and I found out its std::vector::size member not returning the correct amount of faces in the unsigned interger vector eg, "vector<unsigned int>faces; " so when I use cout << faces.size() << endl; I got 68 elements???? instead of 24 as you can see here in this .obj file: # Blender v2.61 (sub 0) OBJ File: '' # www.blender.org v 1.000000 -1.000000 -1.000000 v 1.000000 -1.000000 1.000000 v -1.000000 -1.000000 1.000000 v -1.000000 -1.000000 -1.000000 v 1.000000 1.000000 -0.999999 v 0.999999 1.000000 1.000001 v -1.000000 1.000000 1.000000 v -1.000000 1.000000 -1.000000 s off f 1 2 3 4 f 5 8 7 6 f 1 5 6 2 f 2 6 7 3 <--- 24 Faces not 68? f 3 7 8 4 f 5 1 4 8 I'm using a parser I created to get the faces/vertexes in my .obj file: char modelbuffer [20000]; int MAX_BUFF = 20000; unsigned int face[3]; FILE * pfile; pfile = fopen(szFileName, "rw"); while(fgets(modelbuffer, MAX_BUFF, pfile) != NULL) { if('v') { Point p; sscanf(modelbuffer, "v %f %f %f", &p.x, &p.y, &p.z); points.push_back(p); cout << " p.x = " << p.x << " p.y = " << p.y << " p.z = " << p.x << endl; } if('f') { sscanf(modelbuffer, "f %d %d %d %d", &face[0], &face[1], &face[2], &face[3]); cout << "face[0] = " << face[0] << " face[1] = " << face[1] << " face[2] = " << face[2] << " face[3] = " << face[3] << "\n"; faces.push_back(face[0] - 1); faces.push_back(face[1] - 1); faces.push_back(face[2] - 1); faces.push_back(face[3] - 1); cout << face[0] - 1 << face[1] - 1 << face[2] - 1 << face[3] - 1 << endl; } } using this struct to store the x,y,z positions also this vector was used with Point: vector<Point>points; struct Point { float x, y, z; }; If someone could tell me why its not working and how to fix it that would be awesome I also provide a pastebin to the full source code if you want a closer look. http://pastebin.com/gznYLVw7

    Read the article

  • Creating spotlight in OpenGL scene

    - by Victor Oliveira
    Im studying OpenGL and trying to create a spot light at my application. The code that Im using for my #vertex-shader is below: #:vertex-shader #{ #version 150 core in vec3 in_pos; in vec2 in_tc; out vec2 tc; glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 20.0f); GLfloat spot_direction[] = { -1.0, -1.0, 0.0 }; glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, spot_direction); glEnable(GL_LIGHT0); void main() { vec4 pos= vec4(vec3(1.0)*in_pos - vec3(1.0), 1.0); pos.z=0.0; gl_Position = pos; tc = in_tc; } } The thing is, everytime Im trying to run the code an Error that says: Type: other, Source: api, ID: 131169, Severity: low Message: Framebuffer detailed info: The driver allocated storage for renderbuffer 1. len = 157, written = 0 failed to compile vertex shader of deferred: directional info log for shader deferred: directional vertex info log for shader deferred: directional: ERROR: Unbound variable: when Specifications: Renderer: GeForce GTX 580/PCIe/SSE2 Version: 3.3.0 NVIDIA 319.17 GLSL: 3.30 NVIDIA via Cg compiler Status: Using GLEW 1.9.0 1024 x 768 OS: Linux debian I guess to create this spotlight is pretty much simple, but since Im really new to OpenGL I dont have a clue how to do it until now, even reading sources like: http://www.glprogramming.com/red/chapter05.html#name3 Read also in some place that light spots can get really hard to understand, but I cant avoid this step right now since Im following my lecture schedule. Could anybody help me?

    Read the article

  • What is different about C++ math.h abs() compared to my abs()

    - by moka
    I am currently writing some glsl like vector math classes in c++, and I just implemented an abs() function like this: template<class T> static inline T abs(T _a) { return _a < 0 ? -_a : _a; } I compared its speed to the default c++ abs from math.h like this: clock_t begin = clock(); for(int i=0; i<10000000; ++i) { float a = abs(-1.25); }; clock_t end = clock(); unsigned long time1 = (unsigned long)((float)(end-begin) / ((float)CLOCKS_PER_SEC/1000.0)); begin = clock(); for(int i=0; i<10000000; ++i) { float a = myMath::abs(-1.25); }; end = clock(); unsigned long time2 = (unsigned long)((float)(end-begin) / ((float)CLOCKS_PER_SEC/1000.0)); std::cout<<time1<<std::endl; std::cout<<time2<<std::endl; Now the default abs takes about 25ms while mine takes 60. I guess there is some low level optimisation going on. Does anybody know how math.h abs works internally? The performance difference is nothing dramatic, but I am just curious!

    Read the article

  • How to Implement Overlay blend method using opengles 1.1

    - by Cylon
    Blow is the algorithm of overlay. and i want using it on iphone, but iphone 3g only support opengles 1.1, can not using glsl. can i using blend function or texture combine to implement it. thank you /////////Reference from OpenGL Shading® Language Third Edition /////////// 19.6.12 Overlay OVERLAY first computes the luminance of the base value. If the luminance value is less than 0.5, the blend and base values are multiplied together. If the luminance value is greater than 0.5, a screen operation is performed. The effect is that the base value is mixed with the blend value, rather than being replaced. This allows patterns and colors to overlay the base image, but shadows and highlights in the base image are preserved. A discontinuity occurs where luminance = 0.5. To provide a smooth transition, we actually do a linear blend of the two equations for luminance in the range [0.45,0.55]. float luminance = dot(base, lumCoeff); if (luminance < 0.45) result = 2.0 * blend * base; else if (luminance 0.55) result = white - 2.0 * (white - blend) * (white - base); else { vec4 result1 = 2.0 * blend * base; vec4 result2 = white - 2.0 * (white - blend) * (white - base); result = mix(result1, result2, (luminance - 0.45) * 10.0); }

    Read the article

  • How to check for mip-map availability in OpenGL?

    - by Xavier Ho
    Recently I bumped into a problem where my OpenGL program would not render textures correctly on a 2-year-old Lenovo laptop with an nVidia Quadro 140 card. It runs OpenGL 2.1.2, and GLSL 1.20, but when I turned on mip-mapping, the whole screen is black, with no warnings or errors. This is my texture filter code: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); After 40 minutes of fiddling around, I found out mip-mapping was the problem. Turning it off fixed it: // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); I get a lot of aliasing, but at least the program is visible and runs fine. Finally, two questions: What's the best or standard way to check if mip-mapping is available on a machine, aside from checking OpenGL versions? If mip-mapping is not available, what's the best work-around to avoid aliasing?

    Read the article

  • Overlay an image over video using OpenGL ES shaders

    - by BlueVoodoo
    I am trying to understand the basic concepts of OpenGL. A week into it, I am still far from there. Once I am in glsl, I know what to do but I find getting there is the tricky bit. I am currently able to pass in video pixels which I manipulate and present. I have then been trying to add still image as an overlay. This is where I get lost. My end goal is to end up in the same fragment shader with pixel data from both my video and my still image. I imagine this means I need two textures and pass on two pixel buffers. I am currently passing the video pixels like this: glGenTextures(1, &textures[0]); //target, texture glBindTexture(GL_TEXTURE_2D, textures[0]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_BGRA, GL_UNSIGNED_BYTE, buffer); Would I then repeat this process on textures[1] with the second buffer from the image? If so, do I then bind both GL_TEXTURE0 and GL_TEXTURE1? ...and would my shader look something like this? uniform sampler2D videoData; uniform sampler2D imageData; once I am in the shader? It seems no matter what combination I try, image and video always ends up being just video data in both these. Sorry for the many questions merged in here, just want to clear my many assumptions and move on. To clarify the question a bit, what do I need to do to add pixels from a still image in the process described? ("easy to understand" sample code or any types of hints would be appreciated).

    Read the article

  • Manipulating gl_LightSource[gl_MaxLights]

    - by pion
    The The OpenGL ® Shading Language Spec version 1.20 http://www.opengl.org/registry/doc/GLSLangSpec.Full.1.20.8.pdf shows the following: struct gl_LightSourceParameters { vec4 ambient; // Acli vec4 diffuse; // Dcli vec4 specular; // Scli vec4 position; // Ppli vec4 halfVector; // Derived: Hi vec3 spotDirection; // Sdli float spotExponent; // Srli float spotCutoff; // Crli // (range: [0.0,90.0], 180.0) float spotCosCutoff; // Derived: cos(Crli) // (range: [1.0,0.0],-1.0) float constantAttenuation; // K0 float linearAttenuation; // K1 float quadraticAttenuation;// K2 }; uniform gl_LightSourceParameters gl_LightSource[gl_MaxLights]; Also, http://www.lighthouse3d.com/opengl/glsl/index.php?ogldir1 shows the following code snippets: lightDir = normalize(vec3(gl_LightSource[0].position)); https://cvs.khronos.org/svn/repos/registry/trunk/public/webgl/doc/spec/WebGL-spec.html#5.10 shows many uniform* functions but nothing seems to deal with an array of uniform variable like gl_LightSource[0]. How do we set the gl_LightSource[0] fields in WebGL using JavaScript? For example, gl_LightSource[0].position Thanks in advance for your help. Note: Cross post on http://www.khronos.org/message_boards/viewtopic.php?f=43&t=3373

    Read the article

  • How is the gimbal locked problem solved using accumulative matrix transformations

    - by Luke San Antonio
    I am reading the online "Learning Modern 3D Graphics Programming" book by Jason L. McKesson As of now, I am up to the gimbal lock problem and how to solve it using quaternions. However right here, at the Quaternions page. Part of the problem is that we are trying to store an orientation as a series of 3 accumulated axial rotations. Orientations are orientations, not rotations. And orientations are certainly not a series of rotations. So we need to treat the orientation of the ship as an orientation, as a specific quantity. I guess this is the first spot I start to get confused, the reason is because I don't see the dramatic difference between orientations and rotations. I also don't understand why an orientation cannot be represented by a series of rotations... Also: The first thought towards this end would be to keep the orientation as a matrix. When the time comes to modify the orientation, we simply apply a transformation to this matrix, storing the result as the new current orientation. This means that every yaw, pitch, and roll applied to the current orientation will be relative to that current orientation. Which is precisely what we need. If the user applies a positive yaw, you want that yaw to rotate them relative to where they are current pointing, not relative to some fixed coordinate system. The concept, I understand, however I don't understand how if accumulating matrix transformations is a solution to this problem, how the code given in the previous page isn't just that. Here's the code: void display() { glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glutil::MatrixStack currMatrix; currMatrix.Translate(glm::vec3(0.0f, 0.0f, -200.0f)); currMatrix.RotateX(g_angles.fAngleX); DrawGimbal(currMatrix, GIMBAL_X_AXIS, glm::vec4(0.4f, 0.4f, 1.0f, 1.0f)); currMatrix.RotateY(g_angles.fAngleY); DrawGimbal(currMatrix, GIMBAL_Y_AXIS, glm::vec4(0.0f, 1.0f, 0.0f, 1.0f)); currMatrix.RotateZ(g_angles.fAngleZ); DrawGimbal(currMatrix, GIMBAL_Z_AXIS, glm::vec4(1.0f, 0.3f, 0.3f, 1.0f)); glUseProgram(theProgram); currMatrix.Scale(3.0, 3.0, 3.0); currMatrix.RotateX(-90); //Set the base color for this object. glUniform4f(baseColorUnif, 1.0, 1.0, 1.0, 1.0); glUniformMatrix4fv(modelToCameraMatrixUnif, 1, GL_FALSE, glm::value_ptr(currMatrix.Top())); g_pObject->Render("tint"); glUseProgram(0); glutSwapBuffers(); } To my understanding, isn't what he is doing (modifying a matrix on a stack) considered accumulating matrices, since the author combined all the individual rotation transformations into one matrix which is being stored on the top of the stack. My understanding of a matrix is that they are used to take a point which is relative to an origin (let's say... the model), and make it relative to another origin (the camera). I'm pretty sure this is a safe definition, however I feel like there is something missing which is blocking me from understanding this gimbal lock problem. One thing that doesn't make sense to me is: If a matrix determines the difference relative between two "spaces," how come a rotation around the Y axis for, let's say, roll, doesn't put the point in "roll space" which can then be transformed once again in relation to this roll... In other words shouldn't any further transformations to this point be in relation to this new "roll space" and therefore not have the rotation be relative to the previous "model space" which is causing the gimbal lock. That's why gimbal lock occurs right? It's because we are rotating the object around set X, Y, and Z axes rather than rotating the object around it's own, relative axes. Or am I wrong? Since apparently this code I linked in isn't an accumulation of matrix transformations can you please give an example of a solution using this method. So in summary: What is the difference between a rotation and an orientation? Why is the code linked in not an example of accumulation of matrix transformations? What is the real, specific purpose of a matrix, if I had it wrong? How could a solution to the gimbal lock problem be implemented using accumulation of matrix transformations? Also, as a bonus: Why are the transformations after the rotation still relative to "model space?" Another bonus: Am I wrong in the assumption that after a transformation, further transformations will occur relative to the current? Also, if it wasn't implied, I am using OpenGL, GLSL, C++, and GLM, so examples and explanations in terms of these are greatly appreciated, if not necessary. The more the detail the better! Thanks in advance...

    Read the article

  • PyOpenGL - passing transformation matrix into shader

    - by M-V
    I am having trouble passing projection and modelview matrices into the GLSL shader from my PyOpenGL code. My understanding is that OpenGL matrices are column major, but when I pass in projection and modelview matrices as shown, I don't see anything. I tried the transpose of the matrices, and it worked for the modelview matrix, but the projection matrix doesn't work either way. Here is the code: import OpenGL from OpenGL.GL import * from OpenGL.GL.shaders import * from OpenGL.GLU import * from OpenGL.GLUT import * from OpenGL.GLUT.freeglut import * from OpenGL.arrays import vbo import numpy, math, sys strVS = """ attribute vec3 aVert; uniform mat4 uMVMatrix; uniform mat4 uPMatrix; uniform vec4 uColor; varying vec4 vCol; void main() { // option #1 - fails gl_Position = uPMatrix * uMVMatrix * vec4(aVert, 1.0); // option #2 - works gl_Position = vec4(aVert, 1.0); // set color vCol = vec4(uColor.rgb, 1.0); } """ strFS = """ varying vec4 vCol; void main() { // use vertex color gl_FragColor = vCol; } """ # particle system class class Scene: # initialization def __init__(self): # create shader self.program = compileProgram(compileShader(strVS, GL_VERTEX_SHADER), compileShader(strFS, GL_FRAGMENT_SHADER)) glUseProgram(self.program) self.pMatrixUniform = glGetUniformLocation(self.program, 'uPMatrix') self.mvMatrixUniform = glGetUniformLocation(self.program, "uMVMatrix") self.colorU = glGetUniformLocation(self.program, "uColor") # attributes self.vertIndex = glGetAttribLocation(self.program, "aVert") # color self.col0 = [1.0, 1.0, 0.0, 1.0] # define quad vertices s = 0.2 quadV = [ -s, s, 0.0, -s, -s, 0.0, s, s, 0.0, s, s, 0.0, -s, -s, 0.0, s, -s, 0.0 ] # vertices self.vertexBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer) vertexData = numpy.array(quadV, numpy.float32) glBufferData(GL_ARRAY_BUFFER, 4*len(vertexData), vertexData, GL_STATIC_DRAW) # render def render(self, pMatrix, mvMatrix): # use shader glUseProgram(self.program) # set proj matrix glUniformMatrix4fv(self.pMatrixUniform, 1, GL_FALSE, pMatrix) # set modelview matrix glUniformMatrix4fv(self.mvMatrixUniform, 1, GL_FALSE, mvMatrix) # set color glUniform4fv(self.colorU, 1, self.col0) #enable arrays glEnableVertexAttribArray(self.vertIndex) # set buffers glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer) glVertexAttribPointer(self.vertIndex, 3, GL_FLOAT, GL_FALSE, 0, None) # draw glDrawArrays(GL_TRIANGLES, 0, 6) # disable arrays glDisableVertexAttribArray(self.vertIndex) class Renderer: def __init__(self): pass def reshape(self, width, height): self.width = width self.height = height self.aspect = width/float(height) glViewport(0, 0, self.width, self.height) glEnable(GL_DEPTH_TEST) glDisable(GL_CULL_FACE) glClearColor(0.8, 0.8, 0.8,1.0) glutPostRedisplay() def keyPressed(self, *args): sys.exit() def draw(self): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # build projection matrix fov = math.radians(45.0) f = 1.0/math.tan(fov/2.0) zN, zF = (0.1, 100.0) a = self.aspect pMatrix = numpy.array([f/a, 0.0, 0.0, 0.0, 0.0, f, 0.0, 0.0, 0.0, 0.0, (zF+zN)/(zN-zF), -1.0, 0.0, 0.0, 2.0*zF*zN/(zN-zF), 0.0], numpy.float32) # modelview matrix mvMatrix = numpy.array([1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.5, 0.0, -5.0, 1.0], numpy.float32) # render self.scene.render(pMatrix, mvMatrix) # swap buffers glutSwapBuffers() def run(self): glutInitDisplayMode(GLUT_RGBA) glutInitWindowSize(400, 400) self.window = glutCreateWindow("Minimal") glutReshapeFunc(self.reshape) glutDisplayFunc(self.draw) glutKeyboardFunc(self.keyPressed) # Checks for key strokes self.scene = Scene() glutMainLoop() glutInit(sys.argv) prog = Renderer() prog.run() When I use option #2 in the shader without either matrix, I get the following output: What am I doing wrong?

    Read the article

  • Installing my sdist from PyPI puts the files in the wrong places

    - by Tartley
    Hey. My problem is that when I upload my Python package to PyPI, and then install it from there using pip, my app breaks because it installs my files into completely different locations than when I simply install the exact same package from a local sdist. Installing from the local sdist puts files on my system like this: /Python27/ Lib/ site-packages/ gloopy-0.1.alpha-py2.7.egg/ (egg and install info files) data/ (images and shader source) doc/ (html) examples/ (.py scripts that use the library) gloopy/ (source) This is much as I'd expect, and works fine (e.g. my source can find my data dir, because they lie next to each other, just like they do in development.) If I upload the same sdist to PyPI and then install it from there, using pip, then things look very different: /Python27/ data/ (images and shader source) doc/ (html) Lib/ site-packages/ gloopy-0.1.alpha-py2.7.egg/ (egg and install info files) gloopy/ (source files) examples/ (.py scripts that use the library) This doesn't work at all - my app can't find its data files, plus obviously it's a mess, polluting the top-level /python27 directory with all my junk. What am I doing wrong? How do I make the pip install behave like the local sdist install? Is that even what I should be trying to achieve? Details I have setuptools installed, and also distribute, and I'm calling distribute_setup.use_setuptools() WindowsXP, Python2.7. My development directory looks like this: /gloopy /data (image files and GLSL shader souce read at runtime) /doc (html files) /examples (some scripts to show off the library) /gloopy (the library itself) My MANIFEST.in mentions all the files I want to be included in the sdist, including everything in the data, examples and doc directories: recursive-include data *.* recursive-include examples *.py recursive-include doc/html *.html *.css *.js *.png include LICENSE.txt include TODO.txt My setup.py is quite verbose, but I guess the best thing is to include it here, right? I also includes duplicate references to the same data / doc / examples directories as are mentioned in the MANIFEST.in, because I understand this is required in order for these files to be copied from the sdist to the system during install. NAME = 'gloopy' VERSION= __import__(NAME).VERSION RELEASE = __import__(NAME).RELEASE SCRIPT = None CONSOLE = False def main(): import sys from pprint import pprint from setup_utils import distribute_setup from setup_utils.sdist_setup import get_sdist_config distribute_setup.use_setuptools() from setuptools import setup description, long_description = read_description() config = dict( name=name, version=version, description=description, long_description=long_description, keywords='', packages=find_packages(), data_files=[ ('examples', glob('examples/*.py')), ('data/shaders', glob('data/shaders/*.*')), ('doc', glob('doc/html/*.*')), ('doc/_images', glob('doc/html/_images/*.*')), ('doc/_modules', glob('doc/html/_modules/*.*')), ('doc/_modules/gloopy', glob('doc/html/_modules/gloopy/*.*')), ('doc/_modules/gloopy/geom', glob('doc/html/_modules/gloopy/geom/*.*')), ('doc/_modules/gloopy/move', glob('doc/html/_modules/gloopy/move/*.*')), ('doc/_modules/gloopy/shapes', glob('doc/html/_modules/gloopy/shapes/*.*')), ('doc/_modules/gloopy/util', glob('doc/html/_modules/gloopy/util/*.*')), ('doc/_modules/gloopy/view', glob('doc/html/_modules/gloopy/view/*.*')), ('doc/_static', glob('doc/html/_static/*.*')), ('doc/_api', glob('doc/html/_api/*.*')), ], classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: Microsoft :: Windows', 'Programming Language :: Python :: 2.7', ], # see classifiers http://pypi.python.org/pypi?:action=list_classifiers ) config.update(dict( author='Jonathan Hartley', author_email='[email protected]', url='http://bitbucket.org/tartley/gloopy', license='New BSD', ) ) if '--verbose' in sys.argv: pprint(config) setup(**config) if __name__ == '__main__': main()

    Read the article

< Previous Page | 5 6 7 8 9 10  | Next Page >