Search Results

Search found 1379 results on 56 pages for 'fragment shader'.

Page 23/56 | < Previous Page | 19 20 21 22 23 24 25 26 27 28 29 30  | Next Page >

  • Simplest way to render image over top of another with another image used as mask in OpenGL?

    - by Adam Naylor
    The effect I'm looking for is to have a single large background image that is always visible (at full alpha) and then show a second image (what I call a light map or specular map) that is partially shown over the top based on a third image (which is effectively a mask). The effect is similar to this effect except instead of simply darkening or lightening the background image using the third image it needs to mask the second without effecting the first at all. The third image is the only one that moves therefore hard baking the third images alpha into the second image isn't an option. If my explanation isn't clear I'll provide visual examples when I have more time. I'd prefer not to go down a shader route as I haven't taught myself this area yet so unless I have too I'd rather try to achieve this with simple alpha blending. Happy to use a shader approach. Cheers. Additional These third images are obviously light sources being cast onto the first image showing the specular information from the second image to simulate the light 'shining' off the objects in the first image. The solution I implement will need to allow two light sources to potentially overlap so my current thoughts are that the alpha values of the two images will need to be combined (Added?) to produce a final image which masks the second image? Don't worry about things like coloured lights. For this technique the lights are all considered white.

    Read the article

  • Learning OpenGL GLSL - VAO buffer problems?

    - by Bleary
    I've just started digging through OpenGL and GLSL, and now stumbled on something I can't get my head around this one!? I've stepped back to loading a simple cube and using a simple shader on it, but the result is triangles drawn incorrectly and/or missing. The code I had working perfectly on meshes, but was attempting to move to using VAOs so none of the code for storing the vertices and indices has changed. http://i.stack.imgur.com/RxxZ5.jpg http://i.stack.imgur.com/zSU50.jpg What I have for creating the VAO and buffers is this //Create the Vertex array object glGenVertexArrays(1, &vaoID); // Finally create our vertex buffer objects glGenBuffers(VBO_COUNT, mVBONames); glBindVertexArray(vaoID); // Save vertex attributes into GPU glBindBuffer(GL_ARRAY_BUFFER, mVBONames[VERTEX_VBO]); // Copy data into the buffer object glBufferData(GL_ARRAY_BUFFER, lPolygonVertexCount*VERTEX_STRIDE*sizeof(GLfloat), lVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(pos); glVertexAttribPointer(pos, 3, GL_FLOAT, GL_FALSE, VERTEX_STRIDE*sizeof(GLfloat),0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mVBONames[INDEX_VBO]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, lPolygonCount*sizeof(unsigned int), lIndices, GL_STATIC_DRAW); glBindVertexArray(0); And the code for drawing the mesh. glBindVertexArray(vaoID); glUseProgram(shader->programID); GLsizei lOffset = mSubMeshes[pMaterialIndex]->IndexOffset*sizeof(unsigned int); const GLsizei lElementCount = mSubMeshes[pMaterialIndex]->TriangleCount*TRIAGNLE_VERTEX_COUNT; glDrawElements(GL_TRIANGLES, lElementCount, GL_UNSIGNED_SHORT, reinterpret_cast<const GLvoid*>(lOffset)); // All the points are indeed in the correct place!? //glPointSize(10.0f); //glDrawElements(GL_POINTS, lElementCount, GL_UNSIGNED_SHORT, 0); glUseProgram(0); glBindVertexArray(0); Eyes have become bleary looking at this today so any thoughts or a fresh set of eyes would be greatly appreciated.

    Read the article

  • GLSL Normals not transforming propertly

    - by instancedName
    I've been stuck on this problem for two days. I've read many articles about transforming normals, but I'm just totaly stuck. I understand choping off W component for "turning off" translation, and doing inverse/traspose transformation for non-uniform scaling problem, but my bug seems to be from a different source. So, I've imported a simple ball into OpenGL. Only transformation that I'm applying is rotation over time. But when my ball rotates, the illuminated part of the ball moves around just as it would if direction light direction was changing. I just can't figure out what is the problem. Can anyone help me with this? Here's the GLSL code: Vertex Shader: #version 440 core uniform mat4 World, View, Projection; layout(location = 0) in vec3 VertexPosition; layout(location = 1) in vec3 VertexColor; layout(location = 2) in vec3 VertexNormal; out vec4 Color; out vec3 Normal; void main() { Color = vec4(VertexColor, 1.0); vec4 n = World * vec4(VertexNormal, 0.0f); Normal = n.xyz; gl_Position = Projection * View * World * vec4(VertexPosition, 1.0); } Fragment Shader: #version 440 core uniform vec3 LightDirection = vec3(0.0, 0.0, -1.0); uniform vec3 LightColor = vec3(1f); in vec4 Color; in vec3 Normal; out vec4 FragColor; void main() { diffuse = max(0.0, dot(normalize(-LightDirection), normalize(Normal))); vec4 scatteredLight = vec4(LightColor * diffuse, 1.0f); FragColor = min(Color * scatteredLight, vec4(1.0)); }

    Read the article

  • Having the same texture data in different ID3D11Texture2D

    - by bdmnd
    Sorry if this has been answered elsewhere - I'm rather new to DX. My question concerns conservation of resources - specifically textures in VRAM. I assume that upon returning from a call to CreateTexture2D, a copy of any textures data supplied has been copied elsewhere, likely VRAM. Does DX11 have any facility for having multiple ID3D11Texture2D objects which point to the same data? This might at first seem silly, but imagine a ID3D11Texture2D which is an array of textures. In one material, an artist has chosen to blend three identically sized maps, saved on disk as A.dds, B.dds, and C.dds. Then imagine they have another material which also uses three maps, but this time A.dds, B.dds, and D.dds. The shader code knows the diffuse texture is a texture array, and also has the number of layers baked (three in each case). I would essentially like to set up just two ID3D11Texture2D objects, one for each material, but I don't want to waste VRAM for two identical copies of A.dds and B.dds. I could use explicit texture arrays, of course, but this reduces the number of resources available to the shader and can complicate code somewhat more than would otherwise be needed.

    Read the article

  • Android 2D terrain scrolling

    - by Nikola Ninkovic
    I want to make infinite 2D terrain based on my algorithm.Then I want to move it along Y axis (to the left) This is how I did it : public class Terrain { Queue<Integer> _bottom; Paint _paint; Bitmap _texture; Point _screen; int _numberOfColumns = 100; int _columnWidth = 20; public Terrain(int screenWidth, int screenHeight, Bitmap texture) { _bottom = new LinkedList<Integer>(); _screen = new Point(screenWidth, screenHeight); _numberOfColumns = screenWidth / 6; _columnWidth = screenWidth / _numberOfColumns; for(int i=0;i<=_numberOfColumns;i++) { // Generate terrain point and put it into _bottom queue } _paint = new Paint(); _paint.setStyle(Paint.Style.FILL); _paint.setShader(new BitmapShader(texture, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT)); } public void update() { _bottom.remove(); // Algorithm calculates next point _bottom.add(nextPoint); } public void draw(Canvas canvas) { Iterator<Integer> i = _bottom.iterator(); int counter = 0; Path path = new Path(); path.moveTo(0, _screen.y); while (i.hasNext()) { path.lineTo(counter, _screen.y-i.next()); counter += _columnWidth; } path.lineTo(_screen.x, _screen.y); path.lineTo(0, _screen.y); canvas.drawPath(path2, _paint); } } The problem is that the game is too 'fast', so I tried with pausing thread with Thread.sleep(50); in run() method of my game thread but then it looks too torn. Well, is there any way to slow down drawing of my terrain ?

    Read the article

  • Complex shading using one single (small) texture

    - by teodron
    Recently I stumbled upon a demo reel in UDK about how one can attain beautiful results using just one (rather tiny) texture that's being sent to the shader pipeline. The famous link is this one. Basically, the author states that they've used just one texture and give a snapshot of the technique here. I see that every RGBA channel contains different grayscale information.. and that info could be used to inside a shader to obtain a colour blended output. The problem is that the reel displays a fairly complex scene. To top that, the author even makes use of a normal map. How did they manage to fit a normal map in an already cluttered texture? It makes sense to have a half-space normal map by using only RG from an RGB texture, but what about the rest of the information? Since it was proven to be possible, could someone please explain how it was done (the big picture, not the dirty details!)!? Here's the texture being used. Click to see in full size.

    Read the article

  • ERROR #342: DEVICE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND

    - by Telanor
    I've stared at this for at least half an hour now and I cannot figure out what directx is complaining about. I know this error normally means you put float3 instead of a float4 or something like that, but I've checked over and over and as far as I can tell, everything matches. This is the full error message: D3D11: ERROR: ID3D11DeviceContext::DrawIndexed: Input Assembler - Vertex Shader linkage error: Signatures between stages are incompatible. The input stage requires Semantic/Index (COLOR,0) as input, but it is not provided by the output stage. [ EXECUTION ERROR #342: DEVICE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND ] This is the vertex shader's input signature as seen in PIX: // Input signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------ ------ // POSITION 0 xyz 0 NONE float xyz // NORMAL 0 xyz 1 NONE float // COLOR 0 xyzw 2 NONE float The HLSL structure looks like this: struct VertexShaderInput { float3 Position : POSITION0; float3 Normal : NORMAL0; float4 Color: COLOR0; }; The input layout, from PIX, is: The C# structure holding the data looks like this: [StructLayout(LayoutKind.Sequential)] public struct PositionColored { public static int SizeInBytes = Marshal.SizeOf(typeof(PositionColored)); public static InputElement[] InputElements = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 0) }; Vector3 position; Vector3 normal; Vector4 color; #region Properties ... #endregion public PositionColored(Vector3 position, Vector3 normal, Vector4 color) { this.position = position; this.normal = normal; this.color = color; } public override string ToString() { StringBuilder sb = new StringBuilder(base.ToString()); sb.Append(" Position="); sb.Append(position); sb.Append(" Color="); sb.Append(Color); return sb.ToString(); } } SizeInBytes comes out to 40, which is correct (4*3 + 4*3 + 4*4 = 40). Can anyone find where the mistake is?

    Read the article

  • How to setup my texture cordinates correctly in GLSL 150 and OpenGL 3.3?

    - by RubyKing
    I'm trying to do texture mapping in GLSL 150 and OpenGL 3.3 Here are my shaders I've tried my best to get this correct as possible hopefully this is :) I'm guessing you want to know what the problem is well my texture shows but not in its fullest form just one section of it not the full texture on the quad. All I can think of is its the texture cordinates in the main.cpp which is at the bottom of this post. FRAGMENT SHADER #version 150 in vec2 Texcoord_VSPS; out vec4 color; // Values that stay constant for the whole mesh. uniform sampler2D myTextureSampler; //Main Entry Point void main() { // Output color = color of the texture at the specified UV color = texture2D( myTextureSampler, Texcoord_VSPS ); } VERTEX SHADER #version 150 //Position Container in vec3 position; //Container for TexCoords attribute vec2 Texcoord0; out vec2 Texcoord_VSPS; //out vec2 ex_texcoord; //TO USE A DIFFERENT COORDINATE SYSTEM JUST MULTIPLY THE MATRIX YOU WANT //Main Entry Point void main() { //Translations and w Cordinates stuff gl_Position = vec4(position.xyz, 1.0); Texcoord_VSPS = Texcoord0; } LINK TO MAIN.CPP http://pastebin.com/t7Vg9L0k

    Read the article

  • Multiple passes in direct3d10

    - by innochenti
    I begin to learning direct3d10 and stuck with multiple passes. As input I have a triangle(that stored in vb/ib) and effect file: //some vertex shader and globals goes there. skip them to preserve simplicity float4 ColorPixelShader(PixelInputType input) : SV_Target { return float4(1,0,0,0); } float4 ColorPixelShader1(PixelInputType input) : SV_Target { return float4(0,1,0,0); } technique10 ColorTechnique { pass pass0 { SetVertexShader(CompileShader(vs_4_0, ColorVertexShader())); SetPixelShader(CompileShader(ps_4_0, ColorPixelShader())); SetGeometryShader(NULL); } pass pass1 { SetVertexShader(CompileShader(vs_4_0, ColorVertexShader())); SetPixelShader(CompileShader(ps_4_0, ColorPixelShader1())); SetGeometryShader(NULL); } } And some render code: pass1->Apply(0); device->DrawIndexed(indexCount, 0, 0); pass2->Apply(0); device->DrawIndexed(indexCount, 0, 0); What I'd expect to see is the green triangle, but it always shows me red triangle. What am I doing wrong? Also, I've got another question - should I set vertex shader in every pass? I've added ColorVertexShader1 that translates vertex position by some delta, and 've got following picture: http://imgur.com/Oe7Qj

    Read the article

  • Atmospheric scattering OpenGL 3.3

    - by user1419305
    Im currently trying to convert a shader by Sean O'Neil to version 330 so i can try it out in a application im writing. Im having some issues with deprecated functions, so i replaced them, but im almost completely new to glsl, so i probably did a mistake somewhere. Original shaders can be found here: http://www.gamedev.net/topic/592043-solved-trying-to-use-atmospheric-scattering-oneill-2004-but-get-black-sphere/ My horrible attempt at converting them: Vertex Shader: #version 330 core layout(location = 0) in vec3 vertexPosition_modelspace; //layout(location = 1) in vec2 vertexUV; layout(location = 2) in vec3 vertexNormal_modelspace; uniform vec3 v3CameraPos; uniform vec3 v3LightPos; uniform vec3 v3InvWavelength; uniform float fCameraHeight; uniform float fCameraHeight2; uniform float fOuterRadius; uniform float fOuterRadius2; uniform float fInnerRadius; uniform float fInnerRadius2; uniform float fKrESun; uniform float fKmESun; uniform float fKr4PI; uniform float fKm4PI; uniform float fScale; uniform float fScaleDepth; uniform float fScaleOverScaleDepth; // passing in matrixes for transformations uniform mat4 MVP; uniform mat4 V; uniform mat4 M; const int nSamples = 4; const float fSamples = 4.0; out vec3 v3Direction; out vec4 gg_FrontColor; out vec4 gg_FrontSecondaryColor; float scale(float fCos) { float x = 1.0 - fCos; return fScaleDepth * exp(-0.00287 + x*(0.459 + x*(3.83 + x*(-6.80 + x*5.25)))); } void main(void) { vec3 v3Pos = vertexPosition_modelspace; vec3 v3Ray = v3Pos - v3CameraPos; float fFar = length(v3Ray); v3Ray /= fFar; vec3 v3Start = v3CameraPos; float fHeight = length(v3Start); float fDepth = exp(fScaleOverScaleDepth * (fInnerRadius - fCameraHeight)); float fStartAngle = dot(v3Ray, v3Start) / fHeight; float fStartOffset = fDepth*scale(fStartAngle); float fSampleLength = fFar / fSamples; float fScaledLength = fSampleLength * fScale; vec3 v3SampleRay = v3Ray * fSampleLength; vec3 v3SamplePoint = v3Start + v3SampleRay * 0.5; vec3 v3FrontColor = vec3(0.0, 0.0, 0.0); for(int i=0; i<nSamples; i++) { float fHeight = length(v3SamplePoint); float fDepth = exp(fScaleOverScaleDepth * (fInnerRadius - fHeight)); float fLightAngle = dot(v3LightPos, v3SamplePoint) / fHeight; float fCameraAngle = dot(v3Ray, v3SamplePoint) / fHeight; float fScatter = (fStartOffset + fDepth*(scale(fLightAngle) - scale(fCameraAngle))); vec3 v3Attenuate = exp(-fScatter * (v3InvWavelength * fKr4PI + fKm4PI)); v3FrontColor += v3Attenuate * (fDepth * fScaledLength); v3SamplePoint += v3SampleRay; } gg_FrontSecondaryColor.rgb = v3FrontColor * fKmESun; gg_FrontColor.rgb = v3FrontColor * (v3InvWavelength * fKrESun); gl_Position = MVP * vec4(vertexPosition_modelspace,1); v3Direction = v3CameraPos - v3Pos; } Fragment Shader: #version 330 core uniform vec3 v3LightPos; uniform float g; uniform float g2; in vec3 v3Direction; out vec4 FragColor; in vec4 gg_FrontColor; in vec4 gg_FrontSecondaryColor; void main (void) { float fCos = dot(v3LightPos, v3Direction) / length(v3Direction); float fMiePhase = 1.5 * ((1.0 - g2) / (2.0 + g2)) * (1.0 + fCos*fCos) / pow(1.0 + g2 - 2.0*g*fCos, 1.5); FragColor = gg_FrontColor + fMiePhase * gg_FrontSecondaryColor; FragColor.a = FragColor.b; } I wrote a function to render a sphere, and im trying to render this shader onto a inverted version of it, the sphere works completely fine, with normals and all. My problem is that the sphere gets rendered all black, so the shader is not working. This is how i'm trying to render the atmosphere inside my main rendering loop. glUseProgram(programAtmosphere); glBindTexture(GL_TEXTURE_2D, 0); //###################### glUniform3f(v3CameraPos, getPlayerPos().x, getPlayerPos().y, getPlayerPos().z); glUniform3f(v3LightPos, lightPos.x / sqrt(lightPos.x * lightPos.x + lightPos.y * lightPos.y), lightPos.y / sqrt(lightPos.x * lightPos.x + lightPos.y * lightPos.y), 0); glUniform3f(v3InvWavelength, 1.0 / pow(0.650, 4.0), 1.0 / pow(0.570, 4.0), 1.0 / pow(0.475, 4.0)); glUniform1fARB(fCameraHeight, 1); glUniform1fARB(fCameraHeight2, 1); glUniform1fARB(fInnerRadius, 6350); glUniform1fARB(fInnerRadius2, 6350 * 6350); glUniform1fARB(fOuterRadius, 6450); glUniform1fARB(fOuterRadius2, 6450 * 6450); glUniform1fARB(fKrESun, 0.0025 * 20.0); glUniform1fARB(fKmESun, 0.0015 * 20.0); glUniform1fARB(fKr4PI, 0.0025 * 4.0 * 3.141592653); glUniform1fARB(fKm4PI, 0.0015 * 4.0 * 3.141592653); glUniform1fARB(fScale, 1.0 / (6450 - 6350)); glUniform1fARB(fScaleDepth, 0.25); glUniform1fARB(fScaleOverScaleDepth, 4.0 / (6450 - 6350)); glUniform1fARB(g, -0.85); glUniform1f(g2, -0.85 * -0.85); // vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer[1]); glVertexAttribPointer( 0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // normals glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer[1]); glVertexAttribPointer( 2, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer[1]); glUniformMatrix4fv(ModelMatrixAT, 1, GL_FALSE, &ModelMatrix[0][0]); glUniformMatrix4fv(ViewMatrixAT, 1, GL_FALSE, &ViewMatrix[0][0]); glUniformMatrix4fv(ModelViewPAT, 1, GL_FALSE, &MVP[0][0]); // Draw the triangles glDrawElements( GL_TRIANGLES, // mode cubeIndices[1], // count GL_UNSIGNED_SHORT, // type (void*)0 // element array buffer offset ); Any ideas?

    Read the article

  • Issues with HLSL and lighting

    - by numerical25
    I am trying figure out whats going on with my HLSL code but I have no way of debugging it cause C++ gives off no errors. The application just closes when I run it. I am trying to add lighting to a 3d plane I made. below is my HLSL. The problem consist when my Pixel shader method returns the struct "outColor" . If I change the return value back to the struct "psInput" , everything goes back to working again. My light vectors and colors are at the top of the fx file // PS_INPUT - input variables to the pixel shader // This struct is created and fill in by the // vertex shader cbuffer Variables { matrix Projection; matrix World; float TimeStep; }; struct PS_INPUT { float4 Pos : SV_POSITION; float4 Color : COLOR0; float3 Normal : TEXCOORD0; float3 ViewVector : TEXCOORD1; }; float specpower = 80.0f; float3 camPos = float3(0.0f, 9.0, -256.0f); float3 DirectLightColor = float3(1.0f, 1.0f, 1.0f); float3 DirectLightVector = float3(0.0f, 0.602f, 0.70f); float3 AmbientLightColor = float3(1.0f, 1.0f, 1.0f); /*************************************** * Lighting functions ***************************************/ /********************************* * CalculateAmbient - * inputs - * vKa material's reflective color * lightColor - the ambient color of the lightsource * output - ambient color *********************************/ float3 CalculateAmbient(float3 vKa, float3 lightColor) { float3 vAmbient = vKa * lightColor; return vAmbient; } /********************************* * CalculateDiffuse - * inputs - * material color * The color of the direct light * the local normal * the vector of the direct light * output - difuse color *********************************/ float3 CalculateDiffuse(float3 baseColor, float3 lightColor, float3 normal, float3 lightVector) { float3 vDiffuse = baseColor * lightColor * saturate(dot(normal, lightVector)); return vDiffuse; } /********************************* * CalculateSpecular - * inputs - * viewVector * the direct light vector * the normal * output - specular highlight *********************************/ float CalculateSpecular(float3 viewVector, float3 lightVector, float3 normal) { float3 vReflect = reflect(lightVector, normal); float fSpecular = saturate(dot(vReflect, viewVector)); fSpecular = pow(fSpecular, specpower); return fSpecular; } /********************************* * LightingCombine - * inputs - * ambient component * diffuse component * specualr component * output - phong color color *********************************/ float3 LightingCombine(float3 vAmbient, float3 vDiffuse, float fSpecular) { float3 vCombined = vAmbient + vDiffuse + fSpecular.xxx; return vCombined; } //////////////////////////////////////////////// // Vertex Shader - Main Function /////////////////////////////////////////////// PS_INPUT VS(float4 Pos : POSITION, float4 Color : COLOR, float3 Normal : NORMAL) { PS_INPUT psInput; float4 newPosition; newPosition = Pos; newPosition.y = sin((newPosition.x * TimeStep) + (newPosition.z / 3.0f)) * 5.0f; // Pass through both the position and the color psInput.Pos = mul(newPosition , Projection ); psInput.Color = Color; psInput.ViewVector = normalize(camPos - psInput.Pos); return psInput; } /////////////////////////////////////////////// // Pixel Shader /////////////////////////////////////////////// //Anthony!!!!!!!!!!! Find out how color works when multiplying them float4 PS(PS_INPUT psInput) : SV_Target { float3 normal = -normalize(psInput.Normal); float3 vAmbient = CalculateAmbient(psInput.Color, AmbientLightColor); float3 vDiffuse = CalculateDiffuse(psInput.Color, DirectLightColor, normal, DirectLightVector); float fSpecular = CalculateSpecular(psInput.ViewVector, DirectLightVector, normal); float4 outColor; outColor.rgb = LightingCombine(vAmbient, vDiffuse, fSpecular); outColor.a = 1.0f; //Below is where the error begins return outColor; } // Define the technique technique10 Render { pass P0 { SetVertexShader( CompileShader( vs_4_0, VS() ) ); SetGeometryShader( NULL ); SetPixelShader( CompileShader( ps_4_0, PS() ) ); } } Below is some of my c++ code. Reason I am showing this is because it is pretty much what creates the surface normals for my shaders to evaluate. for the lighting for(int z=0; z < NUM_ROWS; ++z) { for(int x = 0; x < NUM_COLS; ++x) { int curVertex = x + (z * NUM_VERTSX); indices[curIndex] = curVertex; indices[curIndex + 1] = curVertex + NUM_VERTSX; indices[curIndex + 2] = curVertex + 1; D3DXVECTOR3 v0 = vertices[indices[curIndex]].pos; D3DXVECTOR3 v1 = vertices[indices[curIndex + 1]].pos; D3DXVECTOR3 v2 = vertices[indices[curIndex + 2]].pos; D3DXVECTOR3 normal; D3DXVECTOR3 cross; D3DXVec3Cross(&cross, &D3DXVECTOR3(v2 - v0),&D3DXVECTOR3(v1 - v0)); D3DXVec3Normalize(&normal, &cross); vertices[indices[curIndex]].normal = normal; vertices[indices[curIndex + 1]].normal = normal; vertices[indices[curIndex + 2]].normal = normal; indices[curIndex + 3] = curVertex + 1; indices[curIndex + 4] = curVertex + NUM_VERTSX; indices[curIndex + 5] = curVertex + NUM_VERTSX + 1; v0 = vertices[indices[curIndex + 3]].pos; v1 = vertices[indices[curIndex + 4]].pos; v2 = vertices[indices[curIndex + 5]].pos; D3DXVec3Cross(&cross, &D3DXVECTOR3(v2 - v0),&D3DXVECTOR3(v1 - v0)); D3DXVec3Normalize(&normal, &cross); vertices[indices[curIndex + 3]].normal = normal; vertices[indices[curIndex + 4]].normal = normal; vertices[indices[curIndex + 5]].normal = normal; curIndex += 6; } } and below is my c++ code, in it's entirety. showing the drawing and also calling on the passes #include "MyGame.h" //#include "CubeVector.h" /* This code sets a projection and shows a turning cube. What has been added is the project, rotation and a rasterizer to change the rasterization of the cube. The issue that was going on was something with the effect file which was causing the vertices not to be rendered correctly.*/ typedef struct { ID3D10Effect* pEffect; ID3D10EffectTechnique* pTechnique; //vertex information ID3D10Buffer* pVertexBuffer; ID3D10Buffer* pIndicesBuffer; ID3D10InputLayout* pVertexLayout; UINT numVertices; UINT numIndices; }ModelObject; ModelObject modelObject; // World Matrix D3DXMATRIX WorldMatrix; // View Matrix D3DXMATRIX ViewMatrix; // Projection Matrix D3DXMATRIX ProjectionMatrix; ID3D10EffectMatrixVariable* pProjectionMatrixVariable = NULL; //grid information #define NUM_COLS 16 #define NUM_ROWS 16 #define CELL_WIDTH 32 #define CELL_HEIGHT 32 #define NUM_VERTSX (NUM_COLS + 1) #define NUM_VERTSY (NUM_ROWS + 1) // timer variables LARGE_INTEGER timeStart; LARGE_INTEGER timeEnd; LARGE_INTEGER timerFreq; double currentTime; float anim_rate; // Variable to hold how long since last frame change float lastElaspedFrame = 0; // How long should the frames last float frameDuration = 0.5; bool MyGame::InitDirect3D() { if(!DX3dApp::InitDirect3D()) { return false; } // Get the timer frequency QueryPerformanceFrequency(&timerFreq); float freqSeconds = 1.0f / timerFreq.QuadPart; lastElaspedFrame = 0; D3D10_RASTERIZER_DESC rastDesc; rastDesc.FillMode = D3D10_FILL_WIREFRAME; rastDesc.CullMode = D3D10_CULL_FRONT; rastDesc.FrontCounterClockwise = true; rastDesc.DepthBias = false; rastDesc.DepthBiasClamp = 0; rastDesc.SlopeScaledDepthBias = 0; rastDesc.DepthClipEnable = false; rastDesc.ScissorEnable = false; rastDesc.MultisampleEnable = false; rastDesc.AntialiasedLineEnable = false; ID3D10RasterizerState *g_pRasterizerState; mpD3DDevice->CreateRasterizerState(&rastDesc, &g_pRasterizerState); mpD3DDevice->RSSetState(g_pRasterizerState); // Set up the World Matrix D3DXMatrixIdentity(&WorldMatrix); D3DXMatrixLookAtLH(&ViewMatrix, new D3DXVECTOR3(200.0f, 60.0f, -20.0f), new D3DXVECTOR3(200.0f, 50.0f, 0.0f), new D3DXVECTOR3(0.0f, 1.0f, 0.0f)); // Set up the projection matrix D3DXMatrixPerspectiveFovLH(&ProjectionMatrix, (float)D3DX_PI * 0.5f, (float)mWidth/(float)mHeight, 0.1f, 100.0f); pTimeVariable = NULL; if(!CreateObject()) { return false; } return true; } //These are actions that take place after the clearing of the buffer and before the present void MyGame::GameDraw() { static float rotationAngle = 0.0f; // create the rotation matrix using the rotation angle D3DXMatrixRotationY(&WorldMatrix, rotationAngle); rotationAngle += (float)D3DX_PI * 0.0f; // Set the input layout mpD3DDevice->IASetInputLayout(modelObject.pVertexLayout); // Set vertex buffer UINT stride = sizeof(VertexPos); UINT offset = 0; mpD3DDevice->IASetVertexBuffers(0, 1, &modelObject.pVertexBuffer, &stride, &offset); mpD3DDevice->IASetIndexBuffer(modelObject.pIndicesBuffer, DXGI_FORMAT_R32_UINT, 0); pTimeVariable->SetFloat((float)currentTime); // Set primitive topology mpD3DDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // Combine and send the final matrix to the shader D3DXMATRIX finalMatrix = (WorldMatrix * ViewMatrix * ProjectionMatrix); pProjectionMatrixVariable->SetMatrix((float*)&finalMatrix); // make sure modelObject is valid // Render a model object D3D10_TECHNIQUE_DESC techniqueDescription; modelObject.pTechnique->GetDesc(&techniqueDescription); // Loop through the technique passes for(UINT p=0; p < techniqueDescription.Passes; ++p) { modelObject.pTechnique->GetPassByIndex(p)->Apply(0); // draw the cube using all 36 vertices and 12 triangles mpD3DDevice->DrawIndexed(modelObject.numIndices,0,0); } } //Render actually incapsulates Gamedraw, so you can call data before you actually clear the buffer or after you //present data void MyGame::Render() { // Get the start timer count QueryPerformanceCounter(&timeStart); currentTime += anim_rate; DX3dApp::Render(); QueryPerformanceCounter(&timeEnd); anim_rate = ( (float)timeEnd.QuadPart - (float)timeStart.QuadPart ) / timerFreq.QuadPart; } bool MyGame::CreateObject() { VertexPos vertices[NUM_VERTSX * NUM_VERTSY]; for(int z=0; z < NUM_VERTSY; ++z) { for(int x = 0; x < NUM_VERTSX; ++x) { vertices[x + z * NUM_VERTSX].pos.x = (float)x * CELL_WIDTH; vertices[x + z * NUM_VERTSX].pos.z = (float)z * CELL_HEIGHT; vertices[x + z * NUM_VERTSX].pos.y = (float)(rand() % CELL_HEIGHT); vertices[x + z * NUM_VERTSX].color = D3DXVECTOR4(1.0, 0.0f, 0.0f, 0.0f); } } DWORD indices[NUM_VERTSX * NUM_VERTSY * 6]; int curIndex = 0; for(int z=0; z < NUM_ROWS; ++z) { for(int x = 0; x < NUM_COLS; ++x) { int curVertex = x + (z * NUM_VERTSX); indices[curIndex] = curVertex; indices[curIndex + 1] = curVertex + NUM_VERTSX; indices[curIndex + 2] = curVertex + 1; D3DXVECTOR3 v0 = vertices[indices[curIndex]].pos; D3DXVECTOR3 v1 = vertices[indices[curIndex + 1]].pos; D3DXVECTOR3 v2 = vertices[indices[curIndex + 2]].pos; D3DXVECTOR3 normal; D3DXVECTOR3 cross; D3DXVec3Cross(&cross, &D3DXVECTOR3(v2 - v0),&D3DXVECTOR3(v1 - v0)); D3DXVec3Normalize(&normal, &cross); vertices[indices[curIndex]].normal = normal; vertices[indices[curIndex + 1]].normal = normal; vertices[indices[curIndex + 2]].normal = normal; indices[curIndex + 3] = curVertex + 1; indices[curIndex + 4] = curVertex + NUM_VERTSX; indices[curIndex + 5] = curVertex + NUM_VERTSX + 1; v0 = vertices[indices[curIndex + 3]].pos; v1 = vertices[indices[curIndex + 4]].pos; v2 = vertices[indices[curIndex + 5]].pos; D3DXVec3Cross(&cross, &D3DXVECTOR3(v2 - v0),&D3DXVECTOR3(v1 - v0)); D3DXVec3Normalize(&normal, &cross); vertices[indices[curIndex + 3]].normal = normal; vertices[indices[curIndex + 4]].normal = normal; vertices[indices[curIndex + 5]].normal = normal; curIndex += 6; } } //Create Layout D3D10_INPUT_ELEMENT_DESC layout[] = { {"POSITION",0,DXGI_FORMAT_R32G32B32_FLOAT, 0 , 0, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"COLOR",0,DXGI_FORMAT_R32G32B32A32_FLOAT, 0 , 12, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"NORMAL",0,DXGI_FORMAT_R32G32B32A32_FLOAT, 0 , 28, D3D10_INPUT_PER_VERTEX_DATA, 0} }; UINT numElements = (sizeof(layout)/sizeof(layout[0])); modelObject.numVertices = sizeof(vertices)/sizeof(VertexPos); //Create buffer desc D3D10_BUFFER_DESC bufferDesc; bufferDesc.Usage = D3D10_USAGE_DEFAULT; bufferDesc.ByteWidth = sizeof(VertexPos) * modelObject.numVertices; bufferDesc.BindFlags = D3D10_BIND_VERTEX_BUFFER; bufferDesc.CPUAccessFlags = 0; bufferDesc.MiscFlags = 0; D3D10_SUBRESOURCE_DATA initData; initData.pSysMem = vertices; //Create the buffer HRESULT hr = mpD3DDevice->CreateBuffer(&bufferDesc, &initData, &modelObject.pVertexBuffer); if(FAILED(hr)) return false; modelObject.numIndices = sizeof(indices)/sizeof(DWORD); bufferDesc.ByteWidth = sizeof(DWORD) * modelObject.numIndices; bufferDesc.BindFlags = D3D10_BIND_INDEX_BUFFER; initData.pSysMem = indices; hr = mpD3DDevice->CreateBuffer(&bufferDesc, &initData, &modelObject.pIndicesBuffer); if(FAILED(hr)) return false; ///////////////////////////////////////////////////////////////////////////// //Set up fx files LPCWSTR effectFilename = L"effect.fx"; modelObject.pEffect = NULL; hr = D3DX10CreateEffectFromFile(effectFilename, NULL, NULL, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, mpD3DDevice, NULL, NULL, &modelObject.pEffect, NULL, NULL); if(FAILED(hr)) return false; pProjectionMatrixVariable = modelObject.pEffect->GetVariableByName("Projection")->AsMatrix(); pTimeVariable = modelObject.pEffect->GetVariableByName("TimeStep")->AsScalar(); //Dont sweat the technique. Get it! LPCSTR effectTechniqueName = "Render"; modelObject.pTechnique = modelObject.pEffect->GetTechniqueByName(effectTechniqueName); if(modelObject.pTechnique == NULL) return false; //Create Vertex layout D3D10_PASS_DESC passDesc; modelObject.pTechnique->GetPassByIndex(0)->GetDesc(&passDesc); hr = mpD3DDevice->CreateInputLayout(layout, numElements, passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &modelObject.pVertexLayout); if(FAILED(hr)) return false; return true; }

    Read the article

  • An issue with tessellation a model with DirectX11

    - by Paul Ske
    I took the hardware tessellation tutorial from Rastertek and implemended texturing instead of color. This is great, so I wanted to implemended the same techique to a model inside my game editor and I noticed it doesn't draw anything. I compared the detailed tessellation from DirectX SDK sample. Inside the shader file - if I replace the HullInputType with PixelInputType it draws. So, I think because when I compiled the shaders inside the program it compiles VertexShader, PixelShader, HullShader then DomainShader. Isn't it suppose to be VertexShader, HullSHader, DomainShader then PixelShader or does it really not matter? I am just curious why wouldn't the model even be drawn when HullInputType but renders fine with PixelInputType. Shader Code: [code] cbuffer ConstantBuffer { float4x4 WVP; float4x4 World; // the rotation matrix float3 lightvec; // the light's vector float4 lightcol; // the light's color float4 ambientcol; // the ambient light's color bool isSelected; } cbuffer cameraBuffer { float3 cameraDirection; float padding; } cbuffer TessellationBuffer { float tessellationAmount; float3 padding2; } struct ConstantOutputType { float edges[3] : SV_TessFactor; float inside : SV_InsideTessFactor; }; Texture2D Texture; Texture2D NormalTexture; SamplerState ss { MinLOD = 5.0f; MipLODBias = 0.0f; }; struct HullOutputType { float3 position : POSITION; float2 texcoord : TEXCOORD0; float3 normal : NORMAL; float3 tangent : TANGENT; }; struct HullInputType { float4 position : POSITION; float2 texcoord : TEXCOORD0; float3 normal : NORMAL; float3 tangent : TANGENT; }; struct VertexInputType { float4 position : POSITION; float2 texcoord : TEXCOORD; float3 normal : NORMAL; float3 tangent : TANGENT; uint uVertexID : SV_VERTEXID; }; struct PixelInputType { float4 position : SV_POSITION; float2 texcoord : TEXCOORD0; // texture coordinates float3 normal : NORMAL; float3 tangent : TANGENT; float4 color : COLOR; float3 viewDirection : TEXCOORD1; float4 depthBuffer : TEXTURE0; }; HullInputType VShader(VertexInputType input) { HullInputType output; output.position.w = 1.0f; output.position = mul(input.position,WVP); output.texcoord = input.texcoord; output.normal = input.normal; output.tangent = input.tangent; //output.normal = mul(normal,World); //output.tangent = mul(tangent,World); //output.color = output.color; //output.texcoord = texcoord; // set the texture coordinates, unmodified return output; } ConstantOutputType TexturePatchConstantFunction(InputPatch inputPatch,uint patchID : SV_PrimitiveID) { ConstantOutputType output; output.edges[0] = tessellationAmount; output.edges[1] = tessellationAmount; output.edges[2] = tessellationAmount; output.inside = tessellationAmount; return output; } [domain("tri")] [partitioning("integer")] [outputtopology("triangle_cw")] [outputcontrolpoints(3)] [patchconstantfunc("TexturePatchConstantFunction")] HullOutputType HShader(InputPatch patch, uint pointId : SV_OutputControlPointID, uint patchId : SV_PrimitiveID) { HullOutputType output; // Set the position for this control point as the output position. output.position = patch[pointId].position; // Set the input color as the output color. output.texcoord = patch[pointId].texcoord; output.normal = patch[pointId].normal; output.tangent = patch[pointId].tangent; return output; } [domain("tri")] PixelInputType DShader(ConstantOutputType input, float3 uvwCoord : SV_DomainLocation, const OutputPatch patch) { float3 vertexPosition; float2 uvPosition; float4 worldposition; PixelInputType output; // Interpolate world space position with barycentric coordinates float3 vWorldPos = uvwCoord.x * patch[0].position + uvwCoord.y * patch[1].position + uvwCoord.z * patch[2].position; // Determine the position of the new vertex. vertexPosition = vWorldPos; // Calculate the position of the new vertex against the world, view, and projection matrices. output.position = mul(float4(vertexPosition, 1.0f),WVP); // Send the input color into the pixel shader. output.texcoord = uvwCoord.x * patch[0].position + uvwCoord.y * patch[1].position + uvwCoord.z * patch[2].position; output.normal = uvwCoord.x * patch[0].position + uvwCoord.y * patch[1].position + uvwCoord.z * patch[2].position; output.tangent = uvwCoord.x * patch[0].position + uvwCoord.y * patch[1].position + uvwCoord.z * patch[2].position; //output.depthBuffer = output.position; //output.depthBuffer.w = 1.0f; //worldposition = mul(output.position,WVP); //output.viewDirection = cameraDirection.xyz - worldposition.xyz; //output.viewDirection = normalize(output.viewDirection); return output; } [/code] Somethings are commented out but will be in place when fixed. I'm probably not connecting something correctly.

    Read the article

  • How do I prevent TCP connection freezes over an OpenVPN network?

    - by Jason R
    New details added at the end of this question; it's possible that I'm zeroing in on the cause. I have a UDP OpenVPN-based VPN set up in tap mode (I need tap because I need the VPN to pass multicast packets, which doesn't seem to be possible with tun networks) with a handful of clients across the Internet. I've been experiencing frequent TCP connection freezes over the VPN. That is, I will establish a TCP connection (e.g. an SSH connection, but other protocols have similar issues), and at some point during the session, it seems that traffic will cease being transmitted over that TCP session. This seems to be related to points at which large data transfers occur, such as if I execute an ls command in an SSH session, or if I cat a long log file. Some Google searches turn up a number of answers like this previous one on Server Fault, indicating that the likely culprit is an MTU issue: that during periods of high traffic, the VPN is trying to send packets that get dropped somewhere in the pipes between the VPN endpoints. The above-linked answer suggests using the following OpenVPN configuration settings to mitigate the problem: fragment 1400 mssfix This should limit the MTU used on the VPN to 1400 bytes and fix the TCP maximum segment size to prevent the generation of any packets larger than that. This seems to mitigate the problem a bit, but I still frequently see the freezes. I've tried a number of sizes as arguments to the fragment directive: 1200, 1000, 576, all with similar results. I can't think of any strange network topology between the two ends that could trigger such a problem: the VPN server is running on a pfSense machine connected directly to the Internet, and my client is also connected directly to the Internet at another location. One other strange piece of the puzzle: if I run the tracepath utility, then that seems to band-aid the problem. A sample run looks like: [~]$ tracepath -n 192.168.100.91 1: 192.168.100.90 0.039ms pmtu 1500 1: 192.168.100.91 40.823ms reached 1: 192.168.100.91 19.846ms reached Resume: pmtu 1500 hops 1 back 64 The above run is between two clients on the VPN: I initiated the trace from 192.168.100.90 to the destination of 192.168.100.91. Both clients were configured with fragment 1200; mssfix; in an attempt to limit the MTU used on the link. The above results would seem to suggest that tracepath was able to detect a path MTU of 1500 bytes between the two clients. I would assume that it would be somewhat smaller due to the fragmentation settings specified in the OpenVPN configuration. I found that result somewhat strange. Even stranger, however: if I have a TCP connection in the stalled state (e.g. an SSH session with a directory listing that froze in the middle), then executing the tracepath command shown above causes the connection to start up again! I can't figure out any reasonable explanation for why this would be the case, but I feel like this might be pointing toward a solution to ultimately eradicate the problem. Does anyone have any recommendations for other things to try? Edit: I've come back and looked at this a bit further, and have found only more confounding information: I set the OpenVPN connection to fragment at 1400 bytes, as shown above. Then, I connected to the VPN from across the Internet and used Wireshark to look at the UDP packets that were sent to the VPN server while the stall occurred. None were greater than the specified 1400 byte count, so the fragmentation seems to be functioning properly. To verify that even a 1400-byte MTU would be sufficient, I pinged the VPN server using the following (Linux) command: ping <host> -s 1450 -M do This (I believe) sends a 1450-byte packet with fragmentation disabled (I at least verified that it didn't work if I set it to an obviously-too-large value like 1600 bytes). These seem to work just fine; I get replies back from the host with no issue. So, maybe this isn't an MTU issue at all. I'm just confused as to what else it might be! Edit 2: The rabbit hole just keeps getting deeper: I've now isolated the problem a bit more. It seems to be related to the exact OS that the VPN client uses. I have successfully duplicated the problem on at least three Ubuntu machines (versions 12.04 through 13.04). I can reliably duplicate an SSH connection freeze within a minute or so by just cat-ing a large log file. However, if I do the same test using a CentOS 6 machine as a client, then I don't see the problem! I've tested using the exact same OpenVPN client version as I was using on the Ubuntu machines. I can cat log files for hours without seeing the connection freeze. This seems to provide some insight as to the ultimate cause, but I'm just not sure what that insight is. I have examined the traffic over the VPN using Wireshark. I'm not a TCP expert, so I'm not sure what to make of the gory details, but the gist is that at some point, a UDP packet gets dropped due to the limited bandwidth of the Internet link, causing TCP retransmissions inside the VPN tunnel. On the CentOS client, these retransmissions occur properly and things move on happily. At some point with the Ubuntu clients, though, the remote end starts retransmitting the same TCP segment over and over (with the transmit delay increasing between each retransmission). The client sends what looks like a valid TCP ACK to each retransmission, but the remote end still continues to transmit the same TCP segment periodically. This extends ad infinitum and the connection stalls. My question here would be: Does anyone have any recommendations for how to troubleshoot and/or determine the root cause of the TCP issue? It's as if the remote end isn't accepting the ACK messages sent by the VPN client. One common difference between the CentOS node and the various Ubuntu releases is that Ubuntu has a much more recent Linux kernel version (from 3.2 in Ubuntu 12.04 to 3.8 in 13.04). A pointer to some new kernel bug maybe? I'm assuming that if that were so, then I wouldn't be the only one experiencing the problem; I don't think this seems like a particularly exotic setup.

    Read the article

  • OpenGL Colorspace Conversion

    - by Steven Behnke
    Does anyone know how to create a texture with a YUV colorspace so that we can get hardware based YUV to RGB colorspace conversion without having to use a fragment shader? I'm using an NVidia 9400 and I don't see an obvious GL extension that seems to do the trick. I've found examples how to use a fragment shader, but the project I'm working on currently only supports OpenGL 1.1 and I don't have time to convert it to 2.0 and perform all the regression testing necessary. This is also targeting Linux. On other platforms I've been using a MESA extension but it doesn't function on the Nvidia card.

    Read the article

  • Caching query results in django

    - by Marcio Cruz
    I'm trying to find a way to cache the results of a query that won't change with frequency. For example, categories of products from an e-commerce (cellphones, TV, etc). I'm thinking of using the template fragment caching, but in this fragment, I will iterate over a list of these categories. This list is avaliable in any part of the site, so it's in my base.html file. Do I have always to send the list of categories when rendering the templates? Or is there a more dynamic way to do this, making the list always available in the template?

    Read the article

  • Android app crashes when I change the default xml layout file to another

    - by mib1413456
    I am currently just starting to learn android development and have created a basic "Hello world" app that uses "activity_main.xml" for the default layout. I tried to create a new layout xml file called "new_layout.xml" with a text view, a text field and a button and did the following changes in the MainActivity.java file: setContentView(R.layout.new_layout); I did nothing else expect for adding a new_layout.xml in the res/layout folder, I have tried restarting and cleaning the project but nothing. Below is my activity_main.xml file, new_layout.xml file and MainActivity.java activity_main.xml: <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="org.example.androidsdk.demo.MainActivity" tools:ignore="MergeRootFrame" /> new_layout.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:ems="10" > <requestFocus /> </EditText> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> MainActivity.java file package org.example.androidsdk.demo; import android.app.Activity; import android.app.ActionBar; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.os.Build; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.new_layout); if (savedInstanceState == null) { getFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); return rootView; } } }

    Read the article

  • Projecting a targetting ring using direct3d

    - by JohnB
    I'm trying to draw a "targetting ring" on the ground below a "unit" in a hobby 3d game I'm working on. Basically I want to project a bright red patterned ring onto the ground terrain below the unit. The only approach I can think of is this - Draw the world once as normal Draw the world a second time but in my vertex shader I have the world x,y,z coordinates of the vertex and I can pass in the coordinates of the highlighted unit - so I can calculate what the u,v coordinates in my project texture should be at that point in the world for that vertex. I'd then use the pixel shader to pick pixels from the target ring texture and blend them into the previously drawn world. I believe that should be easy, and should work but it involves me drawing the whole visible world twice as it's hard to determine exactly which polygons the targetting ring might fall onto. It seems a big overhead to draw the whole world twice, once for the normal lit textured ground, and then again just to draw the targetting ring. Is there a better approach that I'm missing?

    Read the article

  • agent-based simulation: performance issue: Python vs NetLogo & Repast

    - by max
    I'm replicating a small piece of Sugarscape agent simulation model in Python 3. I found the performance of my code is ~3 times slower than that of NetLogo. Is it likely the problem with my code, or can it be the inherent limitation of Python? Obviously, this is just a fragment of the code, but that's where Python spends two-thirds of the run-time. I hope if I wrote something really inefficient it might show up in this fragment: UP = (0, -1) RIGHT = (1, 0) DOWN = (0, 1) LEFT = (-1, 0) all_directions = [UP, DOWN, RIGHT, LEFT] # point is just a tuple (x, y) def look_around(self): max_sugar_point = self.point max_sugar = self.world.sugar_map[self.point].level min_range = 0 random.shuffle(self.all_directions) for r in range(1, self.vision+1): for d in self.all_directions: p = ((self.point[0] + r * d[0]) % self.world.surface.length, (self.point[1] + r * d[1]) % self.world.surface.height) if self.world.occupied(p): # checks if p is in a lookup table (dict) continue if self.world.sugar_map[p].level > max_sugar: max_sugar = self.world.sugar_map[p].level max_sugar_point = p if max_sugar_point is not self.point: self.move(max_sugar_point) Roughly equivalent code in NetLogo (this fragment does a bit more than the Python function above): ; -- The SugarScape growth and motion procedures. -- to M ; Motion rule (page 25) locals [ps p v d] set ps (patches at-points neighborhood) with [count turtles-here = 0] if (count ps > 0) [ set v psugar-of max-one-of ps [psugar] ; v is max sugar w/in vision set ps ps with [psugar = v] ; ps is legal sites w/ v sugar set d distance min-one-of ps [distance myself] ; d is min dist from me to ps agents set p random-one-of ps with [distance myself = d] ; p is one of the min dist patches if (psugar >= v and includeMyPatch?) [set p patch-here] setxy pxcor-of p pycor-of p ; jump to p set sugar sugar + psugar-of p ; consume its sugar ask p [setpsugar 0] ; .. setting its sugar to 0 ] set sugar sugar - metabolism ; eat sugar (metabolism) set age age + 1 end On my computer, the Python code takes 15.5 sec to run 1000 steps; on the same laptop, the NetLogo simulation running in Java inside the browser finishes 1000 steps in less than 6 sec. EDIT: Just checked Repast, using Java implementation. And it's also about the same as NetLogo at 5.4 sec. Recent comparisons between Java and Python suggest no advantage to Java, so I guess it's just my code that's to blame? EDIT: I understand MASON is supposed to be even faster than Repast, and yet it still runs Java in the end.

    Read the article

  • HLSL: Enforce Constant Register Limit at Compile Time

    - by Andrew Russell
    In HLSL, is there any way to limit the number of constant registers that the compiler uses? Specifically, if I have something like: float4 foobar[300]; In a vs_2_0 vertex shader, the compiler will merrily generate the effect with more than 256 constant registers. But a 2.0 vertex shader is only guaranteed to have access to 256 constant registers, so when I try to use the effect, it fails in an obscure and GPU-dependent way at runtime. I would much rather have it fail at compile time. This problem is especially annoying as the compiler itself allocates constant registers behind the scenes, on top of the ones I am asking for. I have to check the assembly to see if I'm over the limit. Ideally I'd like to do this in HLSL (I'm using the XNA content pipeline), but if there's a flag that can be passed to the compiler that would also be interesting.

    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

  • How to get the request url from HttpServletRequest

    - by Gagan
    Say i make a get request like this: GET http://cotnet.diggstatic.com:6000/js/loader/443/JS_Libraries,jquery|Class|analytics|lightbox|label|jquery-dom|jquery-cookie?q=hello#frag HTTP/1.0 Host: cotnet.diggstatic.com:6000 My servlet takes request like this: HttpServletRequest req; When i debug my server and execute, i get the following: req.getRequestURL().toString() = "http://cotnet.diggstatic.com:6000/js/loader/443/JS_Libraries,jquery%7cClass%7canalytics%7clightbox%7clabel%7cjquery-dom%7cjquery-cookie" req.getRequestURI() = "/js/loader/443/JS_Libraries,jquery%7cClass%7canalytics%7clightbox%7clabel%7cjquery-dom%7cjquery-cookie" req.getQueryString() = "q=hello" How does one get the fragment information ? Also, when i debug the request, i see a uri_ field of type java.net.URI which has the fragment information. This is exactly what i want. How can i get that ?

    Read the article

  • DocumentFragment not appending in IE

    - by bmwbzz
    I have a select list which, when changed, pulls data via ajax and dynamically creates select lists. Then based on the data used to create the select lists (a type), I pull more data via ajax if i don't have it already and create the options for the select list and store them in a fragment. Then I append that fragment to the select list. This is zippy in FF3 and Chrome but either doesn't append the options at all or takes a long time (minutes) to append the options in IE7. Note: I am also using jQuery. code from the success callback which creates the select lists: blockDiv.empty(); var contentItemTypes = new Array(); selectLists = new Array(); for (var post in msg) { if (post != undefined) { var div = fragment.cloneNode(true); //deep copy var nameDiv = $(div.firstChild); nameDiv.text(msg[post].Name); blockDiv[0].appendChild(div); var allSelectLists = blockDiv.find('.editor-field select'); var selectList = $(allSelectLists[allSelectLists.length - 1]); var blockId = msg[post].ID; var elId = 'PageContentItem.' + blockId; selectList.attr('id', elId); selectList.attr('name', elId); var contentItemTypeId = msg[post].ContentItemTypeId; selectList.attr('cit', contentItemTypeId); if (contentItems[contentItemTypeId] != null || contentItems[contentItemTypeId] != undefined) { contentItems[contentItemTypeId] = null; } selectLists[post] = selectList; } } var firstContentTypeId = selectLists[0].attr('cit'); getContentItems(firstContentTypeId, setContentItemsForList, 0); code to get the items for the options in the select lists. function getContentItems(contentTypeId, callback, callbackParam) { if (contentItems[contentTypeId] != null || contentItems[contentTypeId] != undefined) { callback(contentTypeId, callbackParam); return; } contentItems[contentTypeId] = document.createDocumentFragment(); Q.ajax({ type: "POST", url: "/CMS/ContentItem/ListByContentType/" + contentTypeId, data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", error: function(xhr, msg, e) { var err = eval("(" + xhr.responseText + ")"); alert(err.ExceptionType + " ***** " + err.Message + " ***** " + err.StackTrace); }, success: function(msg) { var li; for (var post in msg) { if (post != undefined) { li = $('<option value="' + msg[post].ID + '">' + msg[post].Description + '</option>'); contentItems[contentTypeId].appendChild(li[0]); } } callback(contentTypeId, callbackParam); } }); } function setContentItemsForList(contentTypeId, selectIndex) { if (selectIndex < selectLists.length) { var items = contentItems[contentTypeId].cloneNode(true); selectLists[selectIndex].append($(items.childNodes)); selectIndex++; if (selectIndex < selectLists.length) { var nextContentTypeId = selectLists[selectIndex].attr('cit'); getContentItems(nextContentTypeId, setContentItemsForList, selectIndex); } } }

    Read the article

  • OpenGL + cgFX Alpha Blending failure

    - by dopplex
    I have a shader that needs to additively blend to its output render target. While it had been fully implemented and working, I recently refactored and have done something that is causing the alpha blending to not work anymore. I'm pretty sure that the problem is somewhere in my calls to either OpenGL or cgfx - but I'm currently at a loss for where exactly the problem is, as everything looks like it is set up properly for alpha blending to occur. No OpenGL or cg framework errors are showing up, either. For some context, what I'm doing here is taking a buffer which contains screen position and luminance values for each pixel, copying it to a PBO, and using it as the vertex buffer for drawing GL_POINTS. Everything except for the alpha blending appears to be working as expected. I've confirmed both that the input vertex buffer has the correct values, and that my vertex and fragment shaders are outputting the points to the correct locations and with the correct luminance values. The way that I've arrived at the conclusion that the Alpha blending was broken is by making my vertex shader output every point to the same screen location and then setting the pixel shader to always output a value of float4(0.5) for that pixel. Invariably, the end color (dumped afterwards) ends up being float4(0.5). The confusing part is that as far as I can tell, everything is properly set for alpha blending to occur. The cgfx pass has the two following state assignments (among others - I'll put a full listing at the end): BlendEnable = true; BlendFunc = int2(One, One); This ought to be enough, since I am calling cgSetPassState() - and indeed, when I use glGets to check the values of GL_BLEND_SRC, GL_BLEND_DEST, GL_BLEND, and GL_BLEND_EQUATION they all look appropriate (GL_ONE, GL_ONE, GL_TRUE, and GL_FUNC_ADD). This check was done immediately after the draw call. I've been looking around to see if there's anything other than blending being enabled and the blending function being correctly set that would cause alpha blending not to occur, but without any luck. I considered that I could be doing something wrong with GL, but GL is telling me that blending is enabled. I doubt it's cgFX related (as otherwise the GL state wouldn't even be thinking it was enabled) but it still fails if I explicitly use GL calls to set the blend mode and enable it. Here's the trimmed down code for starting the cgfx pass and the draw call: CGtechnique renderTechnique = Filter->curTechnique; TEXUNITCHECK; CGpass pass = cgGetFirstPass(renderTechnique); TEXUNITCHECK; while (pass) { cgSetPassState(pass); cgUpdatePassParameters(pass); //drawFSPointQuadBuff((void*)PointQuad); drawFSPointQuadBuff((void*)LumPointBuffer); TEXUNITCHECK; cgResetPassState(pass); pass = cgGetNextPass(pass); }; and the function with the draw call: void drawFSPointQuadBuff(void* args) { PointBuffer* pointBuffer = (PointBuffer*)args; FBOERRCHECK; glClear(GL_COLOR_BUFFER_BIT); GLERRCHECK; glPointSize(1.0); GLERRCHECK; glEnableClientState(GL_VERTEX_ARRAY); GLERRCHECK; glEnable(GL_POINT_SMOOTH); if (pointBuffer-BufferObject) { glBindBufferARB(GL_ARRAY_BUFFER_ARB, (unsigned int)pointBuffer-BufData); glVertexPointer(pointBuffer-numComp, GL_FLOAT, 0, 0); } else { glVertexPointer(pointBuffer-numComp, GL_FLOAT, 0, pointBuffer-BufData); }; GLERRCHECK; glDrawArrays(GL_POINTS, 0, pointBuffer-numElem); GLboolean testBool; glGetBooleanv(GL_BLEND, &testBool); int iblendColor, iblendDest, iblendEquation, iblendSrc; glGetIntegerv(GL_BLEND_SRC, &iblendSrc); glGetIntegerv(GL_BLEND_DST, &iblendDest); glGetIntegerv(GL_BLEND_EQUATION, &iblendEquation); if (iblendEquation == GL_FUNC_ADD) { cerr << "Correct func" << endl; }; GLERRCHECK; if (pointBuffer-BufferObject) { glBindBufferARB(GL_ARRAY_BUFFER_ARB,0); } GLERRCHECK; glDisableClientState(GL_VERTEX_ARRAY); GLERRCHECK; }; Finally, here is the full state setting of the shader: AlphaTestEnable = false; DepthTestEnable = false; DepthMask = false; ColorMask = true; CullFaceEnable = false; BlendEnable = true; BlendFunc = int2(One, One); FragmentProgram = compile glslf std_PS(); VertexProgram = compile glslv bilatGridVS2();

    Read the article

  • rails expiring cache

    - by ash34
    Hi, I entered some products data into a table using a migration. I need to expire the page and fragment cache when I update, add, delete products from this table. I created a sweeper for this. class ProductSweeper < ActionController::Caching::Sweeper observe Product def after_create expire_cache end def after_save expire_cache end def after_update expire_cache end def after_destroy expire_cache end private def expire_cache expire_page(:controller => 'ProductsController', :action => 'index') expire_fragment 'listed_products' end end Then in script/console I update the product name and saved. When I reload my app in the browser it still gives me a cache hit. Cached fragment hit: views/listed_products (0.2ms) Can someone tell me how to expire this cache. I will not be adding, updating, deleting products through a controller action. thanks, ash

    Read the article

< Previous Page | 19 20 21 22 23 24 25 26 27 28 29 30  | Next Page >