Search Results

Search found 69 results on 3 pages for 'dyslexic tangent'.

Page 1/3 | 1 2 3  | Next Page >

  • Triangle Strips and Tangent Space Normal Mapping

    - by Koarl
    Short: Do triangle strips and Tangent Space Normal mapping go together? According to quite a lot of tutorials on bump mapping, it seems common practice to derive tangent space matrices in a vertex program and transform the light direction vector(s) to tangent space and then pass them on to a fragment program. However, if one was using triangle strips or index buffers, it is a given that the vertex buffer contains vertices that sit at border edges and would thus require more than one normal to derive tangent space matrices to interpolate between in fragment programs. Is there any reasonable way to not have duplicate vertices in your buffer and still use tangent space normal mapping? Which one do you think is better: Having normal and tangent encoded in the assets and just optimize the geometry handling to alleviate the cost of duplicate vertices or using triangle strips and computing normals/tangents completely at run time? Thinking about it, the more reasonable answer seems to be the first one, but why might my professor still be fussing about triangle strips when it seems so obvious?

    Read the article

  • Tangent basis calculation problem

    - by Kirill Daybov
    I have the problem with seams with calculating a tangent basis in my application. I'm using a seems to be right algorithm, but it gives wrong result on the seams. What am I doing wrong? Is there a problem with an algorithm, or with the model? The designer says that our models with our normal maps are rendered correctly in Xoliul Shader Plugin in 3Ds Max, so there should be a way to calculate correct tangent basis programmatically. Here's an example of the problem I'm talking about. Steps, I've already taken: - Tried different algorithm (from Gamasutra, I can't post the link because I don't have enough reputation yet). I got wrong, much worse, results; - Tried to average basis vectors for vertexes are used in multiple faces; - Tried to average basis vectors for vertexes that have same world coordinates (this would be obviously wrong solution, but I've tried it anyway).

    Read the article

  • For normal mapping, why can we not simply add the tangent normal to the surface normal?

    - by sebf
    I am looking at implementing bump mapping (which in all implementations I have seen is really normal mapping), and so far all I have read says that to do this, we create a matrix to convert from world-space to tangent-space, in order to transform the lights and eye direction vectors into tangent space, so that the vectors from the normal map may be used directly in place of those passed through from the vertex shader. What I do not understand though, is why we cannot just use the normalised sum of the sampled-normal vector, and the surface-normal? (assuming we already transform and pass through the surface normal for the existing lighting functions) Take the diagram below; the normal is simply the deviation from the 'reference normal' for any given coordinate system, correct? And transforming the surface normal of a mapped surface from world space to tangent space makes it equivalent to the tangent space 'reference normal', no? If so, why do we transform all lighting vectors into tangent space, instead of simply transforming the sampled tangent once in the pixel shader?

    Read the article

  • Why aren't tangent space normal maps completely blue?

    - by seahorse
    Why aren't normal maps just blue? I would think that normal maps should be predominantly blue in color because the Z component of the normal is represented by blue. Normals point out of the surface in the Z direction so we should see blue as the predominant colour since the Z component is dominant. By definition tangent space is perpendicular to the surface. At any point we should have the normal always pointing in the Z (blue direction) with no X (red direction) or Y (green direction). Thus the normal map (since it is a "normal map") should have the colour of the normals which is just blue (R = x = 0, G = y = 0, B = z = 1) with no shades in between. But normal maps are not so, and they have gradients of shades in them. Why is this so?

    Read the article

  • Quaddratic Bezier Curve: Calculate Tangent

    - by stefan.at.wpf
    Hello, I have have a quadratic bezier curve and I want to calculate the slope of the tangent in a given point. For example, let it be the middlepoint of the quadratic bezier curve, therefore t=0.5 (please see the link below for a picture of this). I've calculated the first derivation of the formula for the quadratic bezier curve, however I get 400 as value for the slope, though it should be 0. Maybe I'm using the first derivation in a wrong way? I know I could also calculate the tangents using trigonometric functions, however I'd like to do it using the first derivation, shouldn't this be possible? Thanks for any hint! For clarification / please note: I'm interested in a general way to get the slope in a arbitrary given point on a quadratic bezier curve, not only to get the tangent in the start- and end point. A picture of my problem including the text above: http://cid-0432ee4cfe9c26a0.skydrive.live.com/self.aspx/%c3%96ffentlich/Quadratic%20Bezier%20Curve.pdf Thank you very much for any hint!

    Read the article

  • Quadratic Bezier Curve: Calculate Tangent

    - by stefan.at.wpf
    I have a quadratic bezier curve and I want to calculate the slope of the tangent in a given point. For example, let it be the middlepoint of the quadratic bezier curve, therefore t=0.5 (please see the link below for a picture of this). I've calculated the first derivative of the formula for the quadratic bezier curve; however I get 400 as value for the slope, though it should be 0. Maybe I'm using the first derivative in a wrong way? I know I could also calculate the tangents using trigonometric functions; however I'd like to do it using the first derivative, shouldn't this be possible? Thanks for any hint! For clarification / please note: I'm interested in a general way to get the slope in a arbitrary given point on a quadratic bezier curve, not only to get the tangent in the start- and end point. A picture of my problem including the text above: http://cid-0432ee4cfe9c26a0.skydrive.live.com/self.aspx/%c3%96ffentlich/Quadratic%20Bezier%20Curve.pdf Thank you very much for any hint!

    Read the article

  • Get Angle to Tangent that Intersects Point

    - by Christian Stewart
    I have a circle around a given point, call this point (x1, y1). I know the radius of the circle around this point. I also have a second point (x2, y2), that is a distance away, outside the radius of the circle. I need a algebraic way through code to calculate the heading (angle from vertical) needed to intersect the circle at 90* to the center point (I.E. get the angle of the tangent intersecting line 2) around the point (x1, y1) from the second point (x2, y2) A bit of background: Essentially the two points are GPS coordinates on a 2D map, I need to know the target heading to intersect the circle in order to follow its path around the center point. Thanks! Christian

    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

  • tangent of two circles

    - by harryovers
    Hello, I am trying to write some code that that will draw the line which is a tangent between 2 circles. so far i have been able to draw multiple circles, and lines between the centers. i have a class which stores the values used in drawing the circles (radius, position). what i need is a method in this class to find all posible tangents between 2 circles. any help would be great. this is what i have so far (it could very well be a load of rubbish) public static Vector2[] Tangents(circle c1, circle c2) { if (c2.radius > c1.radius) { circle temp = c1; c1 = c2; c2 = temp; } circle c0 = new circle(c1.radius - c2.radius, c1.center); Vector2[] tans = new Vector2[2]; Vector2 dir = _point - _center; float len = (float)Math.Sqrt((dir.X * dir.X) + (dir.Y * dir.Y)); float angle = (float)Math.Atan2(dir.X, dir.Y); float tan_length = (float)Math.Sqrt((len * len) - (_radius * _radius)); float tan_angle = (float)Math.Asin(_radius / len); tans[0] = new Vector2((float)Math.Cos(angle + tan_angle), (float)Math.Sin(angle + tan_angle)); tans[1] = new Vector2((float)Math.Cos(angle - tan_angle), (float)Math.Sin(angle - tan_angle)); Vector2 dir0 = c0.center - tans[0]; Vector2 dir1 = c0.center - tans[1]; Vector2 tan00 = Vector2.Add(Vector2.Multiply(tans[0], (float)c2.radius), c1.center); Vector2 tan01 = c2.center; Vector2 tan10 = Vector2.Add(Vector2.Multiply(tans[1], (float)c2.radius), c1.center); Vector2 tan11 = c2.center; }

    Read the article

  • Why don't Normal maps in tangent space have a single blue color?

    - by seahorse
    Normal maps are predominantly blue in color because the z component maps to Blue and since normals point out of the surface in the z direction we see Blue as the predominant component. If the above is true then why are normal maps just of one color i.e. blue and they should not be having any other shades(not even shades of blue) Since by definition tangent space is perpendicular to normal at any point we should have the normal always pointing in the Z (Blue direction) with no X(Red component) and Y(Green component). Thus the normal map(since it is a "normal map") should have had color of normals which is just the Blue(Z =Blue compoennt = 1, R=0, G=0) and the normal map should have been of only Blue color with no shades in between. But even then normal maps are not so, and they have gradients of shades in them, why is this so?

    Read the article

  • Tessellation Texture Coordinates

    - by Stuart Martin
    Firstly some info - I'm using DirectX 11 , C++ and I'm a fairly good programmer but new to tessellation and not a master graphics programmer. I'm currently implementing a tessellation system for a terrain model, but i have reached a snag. My current system produces a terrain model from a height map complete with multiple texture coordinates, normals, binormals and tangents for rendering. Now when i was using a simple vertex and pixel shader combination everything worked perfectly but since moving to include a hull and domain shader I'm slightly confused and getting strange results. My terrain is a high detail model but the textured results are very large patches of solid colour. My current setup passes the model data into the vertex shader then through the hull into the domain and then finally into the pixel shader for use in rendering. My only thought is that in my hull shader i pass the information into the domain shader per patch and this is producing the large areas of solid colour because each patch has identical information. Lighting and normal data are also slightly off but not as visibly as texturing. Below is a copy of my hull shader that does not work correctly because i think the way that i am passing the data through is incorrect. If anyone can help me out but suggesting an alternative way to get the required data into the pixel shader? or by showing me the correct way to handle the data in the hull shader id be very thankful! cbuffer TessellationBuffer { float tessellationAmount; float3 padding; }; struct HullInputType { float3 position : POSITION; float2 tex : TEXCOORD0; float3 normal : NORMAL; float3 tangent : TANGENT; float3 binormal : BINORMAL; float2 tex2 : TEXCOORD1; }; struct ConstantOutputType { float edges[3] : SV_TessFactor; float inside : SV_InsideTessFactor; }; struct HullOutputType { float3 position : POSITION; float2 tex : TEXCOORD0; float3 normal : NORMAL; float3 tangent : TANGENT; float3 binormal : BINORMAL; float2 tex2 : TEXCOORD1; float4 depthPosition : TEXCOORD2; }; ConstantOutputType ColorPatchConstantFunction(InputPatch<HullInputType, 3> 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("ColorPatchConstantFunction")] HullOutputType ColorHullShader(InputPatch<HullInputType, 3> patch, uint pointId : SV_OutputControlPointID, uint patchId : SV_PrimitiveID) { HullOutputType output; output.position = patch[pointId].position; output.tex = patch[pointId].tex; output.tex2 = patch[pointId].tex2; output.normal = patch[pointId].normal; output.tangent = patch[pointId].tangent; output.binormal = patch[pointId].binormal; return output; } Edited to include the domain shader:- [domain("tri")] PixelInputType ColorDomainShader(ConstantOutputType input, float3 uvwCoord : SV_DomainLocation, const OutputPatch<HullOutputType, 3> patch) { float3 vertexPosition; PixelInputType output; // Determine the position of the new vertex. vertexPosition = uvwCoord.x * patch[0].position + uvwCoord.y * patch[1].position + uvwCoord.z * patch[2].position; output.position = mul(float4(vertexPosition, 1.0f), worldMatrix); output.position = mul(output.position, viewMatrix); output.position = mul(output.position, projectionMatrix); output.depthPosition = output.position; output.tex = patch[0].tex; output.tex2 = patch[0].tex2; output.normal = patch[0].normal; output.tangent = patch[0].tangent; output.binormal = patch[0].binormal; return output; }

    Read the article

  • Calculate cubic bezier T value where tangent is perpendicular to anchor line.

    - by drawnonward
    Project a cubic bezier p1,p2,p3,p4 onto the line p1,p4. When p2 or p3 does not project onto the line segment between p1 and p4, the curve will bulge out from the anchor points. Is there a way to calculate the T value where the tangent of the curve is perpendicular to the anchor line? This could also be stated as finding the T values where the projected curve is farthest from the center of the line segment p1,p4. When p2 and p3 project onto the line segment, then the solutions are 0 and 1 respectively. Is there an equation for solving the more interesting case? The T value seems to depend only on the distance of the mapped control points from the anchor line segment. I can determine the value by refining guesses, but I am hoping there is a better way.

    Read the article

  • What is the recommended way to output values to FBO targets? (OpenGL 3.3 + GLSL 330)

    - by datSilencer
    I'll begin by apologizing for any dumb assumptions you might find in the code below since I'm still pretty much green when it comes to OpenGL programming. I'm currently trying to implement deferred shading by using FBO's and their associated targets (textures in my case). I have a simple (I think :P) geometry+fragment shader program and I'd like to write its Fragment Shader stage output to three different render targets (previously bound by a call to glDrawBuffers()), like so: #version 330 in vec3 WorldPos0; in vec2 TexCoord0; in vec3 Normal0; in vec3 Tangent0; layout(location = 0) out vec3 WorldPos; layout(location = 1) out vec3 Diffuse; layout(location = 2) out vec3 Normal; uniform sampler2D gColorMap; uniform sampler2D gNormalMap; vec3 CalcBumpedNormal() { vec3 Normal = normalize(Normal0); vec3 Tangent = normalize(Tangent0); Tangent = normalize(Tangent - dot(Tangent, Normal) * Normal); vec3 Bitangent = cross(Tangent, Normal); vec3 BumpMapNormal = texture(gNormalMap, TexCoord0).xyz; BumpMapNormal = 2 * BumpMapNormal - vec3(1.0, 1.0, -1.0); vec3 NewNormal; mat3 TBN = mat3(Tangent, Bitangent, Normal); NewNormal = TBN * BumpMapNormal; NewNormal = normalize(NewNormal); return NewNormal; } void main() { WorldPos = WorldPos0; Diffuse = texture(gColorMap, TexCoord0).xyz; Normal = CalcBumpedNormal(); } If my render target textures are configured as: RT1:(GL_RGB32F, GL_RGB, GL_FLOAT, GL_TEXTURE0, GL_COLOR_ATTACHMENT0) RT2:(GL_RGB32F, GL_RGB, GL_FLOAT, GL_TEXTURE1, GL_COLOR_ATTACHMENT1) RT3:(GL_RGB32F, GL_RGB, GL_FLOAT, GL_TEXTURE2, GL_COLOR_ATTACHMENT2) And assuming that each texture has an internal format capable of contaning the incoming data, will the fragment shader write the corresponding values to the expected texture targets? On a related note, do the textures need to be bound to the OpenGL context when they are Multiple Render Targets? From some Googling, I think there are two other ways to output to MRTs: 1: Output each component to gl_FragData[n]. Some forum posts say this method is deprecated. However, looking at the latest OpenGL 3.3 and 4.0 specifications at opengl.org, the core profiles still mention this approach. 2: Use a typed output array variable for the expected type. In this case, I think it would be something like this: out vec3 [3] output; void main() { output[0] = WorldPos0; output[1] = texture(gColorMap, TexCoord0).xyz; output[2] = CalcBumpedNormal(); } So which is then the recommended approach? Is there a recommended approach at all if I plan to code on top of OpenGL 3.3? Thanks for your time and help!

    Read the article

  • Don’t miss rare Venus transit across Sun on June 5th. Once in a life time event.

    - by Gopinath
    Space lovers here is a rare event you don’t want to miss. On June 5th or 6th of 2012,depending on which part of the globe you live, the planet Venus will pass across Sun and it will not happen again until 2117. During the six hour long spectacular transit you can see the shadow of Venus cross Sun. The transit of Venus occurs in pairs eight years apart, with the previous one taking place in 2004. The next pair of transits occurs after 105.5 & 121.5 years later. The best place to watch the event would be a planetarium nearby with telescope facility. If not you watch it directly but must protect your eyes at all times with proper solar filters. Where can we see the transit? The transit of Venus is going to be clearly visible in Europe, Asia, United States and some part of Australia. Americans will be able to see transit in the evening of Tuesday, June 5, 2012. Eurasians and Africans can see the transit in the morning of June 6, 2012. At what time the event occurs? The principal events occurring during a transit are conveniently characterized by contacts, analogous to the contacts of an annular solar eclipse. The transit begins with contact I, the instant the planet’s disk is externally tangent to the Sun. Shortly after contact I, the planet can be seen as a small notch along the solar limb. The entire disk of the planet is first seen at contact II when the planet is internally tangent to the Sun. Over the course of several hours, the silhouetted planet slowly traverses the solar disk. At contact III, the planet reaches the opposite limb and once again is internally tangent to the Sun. Finally, the transit ends at contact IV when the planet’s limb is externally tangent to the Sun. Event Universal Time Contact I 22:09:38 Contact II 22:27:34 Greatest 01:29:36 Contact III 04:31:39 Contact IV 04:49:35   Transit of Venus animation Here is a nice video animation on the transit of Venus Map courtesy of Steven van Roode, source NASA

    Read the article

  • Opposite Force to Apply to a Collided Rigid Body?

    - by Milo
    I'm working on the physics for my GTA2-like game so I can learn more about game physics. The collision detection and resolution are working great. I'm now just unsure how to compute the force to apply to a body after it collides with a wall. My rigid body looks like this: /our simulation object class RigidBody extends Entity { //linear private Vector2D velocity = new Vector2D(); private Vector2D forces = new Vector2D(); private float mass; private Vector2D v = new Vector2D(); //angular private float angularVelocity; private float torque; private float inertia; //graphical private Vector2D halfSize = new Vector2D(); private Bitmap image; private Matrix mat = new Matrix(); private float[] Vector2Ds = new float[2]; private Vector2D tangent = new Vector2D(); private static Vector2D worldRelVec = new Vector2D(); private static Vector2D relWorldVec = new Vector2D(); private static Vector2D pointVelVec = new Vector2D(); private static Vector2D acceleration = new Vector2D(); public RigidBody() { //set these defaults so we don't get divide by zeros mass = 1.0f; inertia = 1.0f; setLayer(LAYER_OBJECTS); } protected void rectChanged() { if(getWorld() != null) { getWorld().updateDynamic(this); } } //intialize out parameters public void initialize(Vector2D halfSize, float mass, Bitmap bitmap) { //store physical parameters this.halfSize = halfSize; this.mass = mass; image = bitmap; inertia = (1.0f / 20.0f) * (halfSize.x * halfSize.x) * (halfSize.y * halfSize.y) * mass; RectF rect = new RectF(); float scalar = 10.0f; rect.left = (int)-halfSize.x * scalar; rect.top = (int)-halfSize.y * scalar; rect.right = rect.left + (int)(halfSize.x * 2.0f * scalar); rect.bottom = rect.top + (int)(halfSize.y * 2.0f * scalar); setRect(rect); } public void setLocation(Vector2D position, float angle) { getRect().set(position.x,position.y, getWidth(), getHeight(), angle); rectChanged(); } public Vector2D getPosition() { return getRect().getCenter(); } @Override public void update(float timeStep) { doUpdate(timeStep); } public void doUpdate(float timeStep) { //integrate physics //linear acceleration.x = forces.x / mass; acceleration.y = forces.y / mass; velocity.x += (acceleration.x * timeStep); velocity.y += (acceleration.y * timeStep); //velocity = Vector2D.add(velocity, Vector2D.scalarMultiply(acceleration, timeStep)); Vector2D c = getRect().getCenter(); v.x = getRect().getCenter().getX() + (velocity.x * timeStep); v.y = getRect().getCenter().getY() + (velocity.y * timeStep); setCenter(v.x, v.y); forces.x = 0; //clear forces forces.y = 0; //angular float angAcc = torque / inertia; angularVelocity += angAcc * timeStep; setAngle(getAngle() + angularVelocity * timeStep); torque = 0; //clear torque } //take a relative Vector2D and make it a world Vector2D public Vector2D relativeToWorld(Vector2D relative) { mat.reset(); Vector2Ds[0] = relative.x; Vector2Ds[1] = relative.y; mat.postRotate(JMath.radToDeg(getAngle())); mat.mapVectors(Vector2Ds); relWorldVec.x = Vector2Ds[0]; relWorldVec.y = Vector2Ds[1]; return relWorldVec; } //take a world Vector2D and make it a relative Vector2D public Vector2D worldToRelative(Vector2D world) { mat.reset(); Vector2Ds[0] = world.x; Vector2Ds[1] = world.y; mat.postRotate(JMath.radToDeg(-getAngle())); mat.mapVectors(Vector2Ds); worldRelVec.x = Vector2Ds[0]; worldRelVec.y = Vector2Ds[1]; return worldRelVec; } //velocity of a point on body public Vector2D pointVelocity(Vector2D worldOffset) { tangent.x = -worldOffset.y; tangent.y = worldOffset.x; pointVelVec.x = (tangent.x * angularVelocity) + velocity.x; pointVelVec.y = (tangent.y * angularVelocity) + velocity.y; return pointVelVec; } public void applyForce(Vector2D worldForce, Vector2D worldOffset) { //add linear force forces.x += worldForce.x; forces.y += worldForce.y; //add associated torque torque += Vector2D.cross(worldOffset, worldForce); } @Override public void draw( GraphicsContext c) { c.drawRotatedScaledBitmap(image, getPosition().x, getPosition().y, getWidth(), getHeight(), getAngle()); } public Vector2D getVelocity() { return velocity; } public void setVelocity(Vector2D velocity) { this.velocity = velocity; } } The way it is given force is by the applyForce method, this method considers angular torque. I'm just not sure how to come up with the vectors in the case where: RigidBody hits static entity RigidBody hits other RigidBody that may or may not be in motion. Would anyone know a way (without too complex math) that I could figure out the opposite force I need to apply to the car? I know the normal it is colliding with and how deep it collided. My main goal is so that say I hit a building from the side, well the car should not just stay there, it should slowly rotate out of it if I'm more than 45 degrees. Right now when I hit a wall I only change the velocity directly which does not consider angular force. Thanks!

    Read the article

  • Understanding normal maps on terrain

    - by JohnB
    I'm having trouble understanding some of the math behind normal map textures even though I've got it to work using borrowed code, I want to understand it. I have a terrain based on a heightmap. I'm generating a mesh of triangles at load time and rendering that mesh. Now for each vertex I need to calculate a normal, a tangent, and a bitangent. My understanding is as follows, have I got this right? normal is a unit vector facing outwards from the surface of the triangle. For a vertex I take the average of the normals of the triangles using that vertex. tangent is a unit vector in the direction of the 'u' coordinates of the texture map. As my texture u,v coordinates follow the x and y coordinates of the terrain, then my understanding is that this vector is simply the vector along the surface in the x direction. So should be able to calculate this as simply the difference between vertices in the x direction to get a vector, (and normalize it). bitangent is a unit vector in the direction of the 'v' coordinates of the texture map. As my texture u,v coordinates follow the x and y coordinates of the terrain, then my understanding is that this vector is simply the vector along the surface in the y direction. So should be able to calculate this as simply the difference between vertices in the y direction to get a vector, (and normalize it). However the code I have borrowed seems much more complicated than this and takes into account the actual values of u, and v at each vertex which I don't understand the need for as they increase in exactly the same direction as x, and y. I implemented what I thought from above, and it simply doesn't work, the normals are clearly not working for lighting. Have I misunderstood something? Or can someone explain to me the physical meaning of the tangent and bitangent vectors when applied to a mesh generated from a hightmap like this, when u and v texture coordinates map along the x and y directions. Thanks for any help understanding this.

    Read the article

  • Reflection velocity

    - by MindSeeker
    I'm trying to get a moving circular object to bounce (elastically) off of an immovable circular object. Am I doing this right? (The results look right, but I hate to trust that alone, and I can't find a tutorial that tackles this problem and includes the nitty gritty math/code to verify what I'm doing). If it is right, is there a better/faster/more elegant way to do this? Note that the object (this) is the moving circle, and the EntPointer object is the immovable circle. //take vector separating the two centers <x, y>, and then get unit vector of the result: MathVector2d unitnormal = MathVector2d(this -> Retxpos() - EntPointer -> Retxpos(), this -> Retypos() - EntPointer -> Retypos()).UnitVector(); //take tangent <-y, x> of the unitnormal: MathVector2d unittangent = MathVector2d(-unitnormal.ycomp, unitnormal.xcomp); MathVector2d V1 = MathVector2d(this -> Retxvel(), this -> Retyvel()); //Calculate the normal and tangent vector lengths of the velocity: (the normal changes, the tangent stays the same) double LengthNormal = DotProduct(unitnormal, V1); double LengthTangent = DotProduct(unittangent, V1); MathVector2d VelVecNewNormal = unitnormal.ScalarMultiplication(-LengthNormal); //the negative of what it was before MathVector2d VelVecNewTangent = unittangent.ScalarMultiplication(LengthTangent); //this stays the same MathVector2d NewVel = VectorAddition(VelVecNewNormal, VelVecNewTangent); //combine them xvel = NewVel.xcomp; //and then apply them yvel = NewVel.ycomp; Note also that this question is just about velocity, the position code is handled elsewhere (in other words, assume that this code is implemented at the exact moment that the circles begin to overlap). Thanks in advance for your help and time!

    Read the article

  • Combining two operators in Evil-mode Emacs

    - by Dyslexic Tangent
    In vim I've remapped > and < when in visual mode to >gv and <gv respectively, like so: vnoremap > >gv vnoremap < <gv Since my target for this question are folks experienced with emacs and not vim, what > and < do is indent/dedent visually selected text. What gv does is reselect the previously selected text. These maps cause > and < to indent/dedent and then reselect the previously selected text. I'm trying out emacs with evil-mode and I'd like to do the same, but I'm having some difficulty figuring out how, exactly, to accomplish the automatic reselection. It looks like I need to somehow call evil-shift-right and evil-visual-restore sequentially, but I don't know how to create a map that will do both, so I tried creating my own function which would call both sequentially and map that instead, but it didn't work, possibly due to the fact that both of them are defined, not as functions with defun but instead as operators with evil-define-operator. I tried creating my own operators: (evil-define-operator shift-left-reselect (beg end) (evil-shift-left beg end) (evil-visual-restore)) (evil-define-operator shift-right-reselect (beg end) (evil-shift-right beg end) (evil-visual-restore)) but that doesn't restore visual as expected. A stab in the dark gave me this: (evil-define-operator shift-left-reselect (beg end) (evil-shift-left beg end) ('evil-visual-restore)) (evil-define-operator shift-right-reselect (beg end) (evil-shift-right beg end) ('evil-visual-restore)) but that selects one additional line whenever it is supposed to reselect. For now I've been using the following, which only has the problem where it reselects an additional line in the < operator. (evil-define-operator shift-right-reselect (beg end) (evil-shift-right beg end) (evil-visual-make-selection beg end)) (evil-define-operator shift-left-reselect (beg end) (evil-shift-left beg end) (evil-visual-make-selection beg end)) and I've mapped them: (define-key evil-visual-state-map ">" 'shift-right-reselect) (define-key evil-visual-state-map "<" 'shift-left-reselect) any help / pointers / tips would be greatly appreciated. Thanks in advance.

    Read the article

  • ssao implementation

    - by Irbis
    I try to implement a ssao based on this tutorial: link I use a deferred rendering and world coordinates for shading calculations. When saving gbuffer a vertex shader output looks like this: worldPosition = vec3(ModelMatrix * vec4(inPosition, 1.0)); normal = normalize(normalModelMatrix * inNormal); gl_Position = ProjectionMatrix * ViewMatrix * ModelMatrix * vec4(inPosition, 1.0); Next for a ssao calculations I render a scene as a full screen quad and I save an occlusion parameter in a texture. (Vertex positions in the world space: link Normals in the world space: link) SSAO implementation: subroutine (RenderPassType) void ssao() { vec2 texCoord = CalcTexCoord(); vec3 worldPos = texture(texture0, texCoord).xyz; vec3 normal = normalize(texture(texture1, texCoord).xyz); vec2 noiseScale = vec2(screenSize.x / 4, screenSize.y / 4); vec3 rvec = texture(texture2, texCoord * noiseScale).xyz; vec3 tangent = normalize(rvec - normal * dot(rvec, normal)); vec3 bitangent = cross(normal, tangent); mat3 tbn = mat3(tangent, bitangent, normal); float occlusion = 0.0; float radius = 4.0; for (int i = 0; i < kernelSize; ++i) { vec3 pix = tbn * kernel[i]; pix = pix * radius + worldPos; vec4 offset = vec4(pix, 1.0); offset = ProjectionMatrix * ViewMatrix * offset; offset.xy /= offset.w; offset.xy = offset.xy * 0.5 + 0.5; float sample_depth = texture(texture0, offset.xy).z; float range_check = abs(worldPos.z - sample_depth) < radius ? 1.0 : 0.0; occlusion += (sample_depth <= pix.z ? 1.0 : 0.0); } outputColor = vec4(occlusion, occlusion, occlusion, 1); } That code gives following results: camera looking towards -z world space: link camera looking towards +z world space: link I wonder if it is possible to use world coordinates in the above code ? When I move camera I get different results because world space positions don't change. Can I treat worldPos.z as a linear depth ? What should I change to get a correct results ? I except the white areas in place of occlusion, so the ground should has the white areas only near to the object.

    Read the article

  • A "Trig" Calculating Class

    - by Clinton Scott
    I have been trying to create a gui that calculates trigonometric functions based off of the user's input. I have had success in the GUI part, but my class that I wrote to hold information using inheritance seems to be messed up, because when I run it gives an error saying: Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - constructor ArcTrigCalcCon in class TrigCalc.ArcTrigCalcCon cannot be applied to given types; required: double,double,double,double,double,double found: java.lang.Double,java.lang.Double,java.lang.Double reason: actual and formal argument lists differ in length at TrigCalc.TrigCalcGUI.(TrigCalcGUI.java:31) at TrigCalc.TrigCalcGUI.main(TrigCalcGUI.java:87) Java Result: 1 and says it is the object causing the problem. Below Will be my code. First I will put up my inheritance class with cosecant secant and cotangent and then my original class with the original 3 trig functions: { public ArcTrigCalcCon(double s, double cs, double t, double csc, double sc, double ct) { // Inherit from the Trig Calc class super(s, cs, t); cosecant = 1/s; secant = 1/cs; cotangent = 1/t; } public void setCsc(double csc) { cosecant = csc; } public void setSec(double sc) { secant = sc; } public void setCot(double ct) { cotangent = ct; } } Here is the first Trigonometric class: public class TrigCalcCon { public double sine; public double cosine; public double tangent; public TrigCalcCon(double s, double cs, double t) { sine = s; cosine = cs; tangent = t; } public void setSin(double s) { sine = s; } public void setCos(double cs) { cosine = cs; } public void setTan(double t) { tangent = t; } public void set(double s, double cs, double t) { sine = s; cosine = cs; tangent = t; } public double getSin() { return Math.sin(sine); } public double getCos() { return Math.cos(cosine); } public double getTan() { return Math.tan(tangent); } } and here is the demo class to run the gui: public class TrigCalcGUI extends JFrame implements ActionListener { // Instance Variables private String input; private Double s, cs, t, csc, sc, ct; private JPanel mainPanel, sinPanel, cosPanel, tanPanel, cscPanel, secPanel, cotPanel, buttonPanel, inputPanel, displayPanel; // Panel Display private JLabel sinLabel, cosLabel, tanLabel, secLabel, cscLabel, cotLabel, inputLabel; private JTextField sinTF, cosTF, tanTF, secTF, cscTF, cotTF, inputTF; //Text Fields for sin, cos, and tan, and inverse private JButton calcButton, clearButton; // Calculate and Exit Buttons // Object ArcTrigCalcCon trC = new ArcTrigCalcCon(s, cs, t); public TrigCalcGUI() { // title bar text. super("Trig Calculator"); // Corner exit button action. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create main panel to add each panel to mainPanel = new JPanel(); mainPanel.setLayout(new GridLayout(3,2)); displayPanel = new JPanel(); displayPanel.setLayout(new GridLayout(3,2)); // Assign Panel to each variable inputPanel = new JPanel(); sinPanel = new JPanel(); cosPanel = new JPanel(); tanPanel = new JPanel(); cscPanel = new JPanel(); secPanel = new JPanel(); cotPanel = new JPanel(); buttonPanel = new JPanel(); // Call each constructor buildInputPanel(); buildSinCosTanPanels(); buildCscSecCotPanels(); buildButtonPanel(); // Add each panel to content pane displayPanel.add(sinPanel); displayPanel.add(cscPanel); displayPanel.add(cosPanel); displayPanel.add(secPanel); displayPanel.add(tanPanel); displayPanel.add(cotPanel); // Add three content panes to GUI mainPanel.add(inputPanel, BorderLayout.NORTH); mainPanel.add(displayPanel, BorderLayout.CENTER); mainPanel.add(buttonPanel, BorderLayout.SOUTH); //add mainPanel this.add(mainPanel); // size of window to content this.pack(); // display window setVisible(true); } public static void main(String[] args) { new TrigCalcGUI(); } private void buildInputPanel() { inputLabel = new JLabel("Enter a Value: "); inputTF = new JTextField(5); inputPanel.add(inputLabel); inputPanel.add(inputTF); } // Building Constructor for sinPanel cosPanel, and tanPanel private void buildSinCosTanPanels() { // Set layout and border for sinPanel sinPanel.setLayout(new GridLayout(2,2)); sinPanel.setBorder(BorderFactory.createTitledBorder("Sine")); // sinTF = new JTextField(5); sinTF.setEditable(false); sinPanel.add(sinTF); // Set layout and border for cosPanel cosPanel.setLayout(new GridLayout(2,2)); cosPanel.setBorder(BorderFactory.createTitledBorder("Cosine")); cosTF = new JTextField(5); cosTF.setEditable(false); cosPanel.add(cosTF); // Set layout and border for tanPanel tanPanel.setLayout(new GridLayout(2,2)); tanPanel.setBorder(BorderFactory.createTitledBorder("Tangent")); tanTF = new JTextField(5); tanTF.setEditable(false); tanPanel.add(tanTF); } // Building Constructor for cscPanel secPanel, and cotPanel private void buildCscSecCotPanels() { // Set layout and border for cscPanel cscPanel.setLayout(new GridLayout(2,2)); cscPanel.setBorder(BorderFactory.createTitledBorder("Cosecant")); // cscTF = new JTextField(5); cscTF.setEditable(false); cscPanel.add(cscTF); // Set layout and border for secPanel secPanel.setLayout(new GridLayout(2,2)); secPanel.setBorder(BorderFactory.createTitledBorder("Secant")); secTF = new JTextField(5); secTF.setEditable(false); secPanel.add(secTF); // Set layout and border for cotPanel cotPanel.setLayout(new GridLayout(2,2)); cotPanel.setBorder(BorderFactory.createTitledBorder("Cotangent")); cotTF = new JTextField(5); cotTF.setEditable(false); cotPanel.add(cotTF); } private void buildButtonPanel() { // Create buttons and add events calcButton = new JButton("Calculate"); calcButton.addActionListener(new CalcButtonListener()); clearButton = new JButton("Clear"); clearButton.addActionListener(new ClearButtonListener()); buttonPanel.add(calcButton); buttonPanel.add(clearButton); } @Override public void actionPerformed(ActionEvent e) { } private class CalcButtonListener implements ActionListener { public void actionPerformed(ActionEvent ae) { // Declare boolean variable boolean incorrect = true; // Set input variable to input text field text input = inputTF.getText(); ImageIcon newIcon; ImageIcon frowny = new ImageIcon(TrigCalcGUI.class.getResource("/Sad_Face.png")); Image gm = frowny.getImage(); Image newFrowny = gm.getScaledInstance(100, 100, java.awt.Image.SCALE_FAST); newIcon = new ImageIcon(newFrowny); // If boolean is true, throw exception if(incorrect) { try{Double.parseDouble(input); incorrect = false;} catch(NumberFormatException nfe) { String s = "Invalid Input " + "/n Input Must Be a Numerical value." + "/nPlease Press Ok and Try Again"; JOptionPane.showMessageDialog(null, s, "Invalid", JOptionPane.ERROR_MESSAGE, newIcon); inputTF.setText(""); inputTF.requestFocus(); } } // If boolean is not true, proceed with output if (incorrect != true) { /* Set each text field's output to the String double value * of inputTF */ sinTF.setText(input); cosTF.setText(input); tanTF.setText(input); cscTF.setText(input); secTF.setText(input); cotTF.setText(input); } } } /** * Private inner class that handles the event when * the user clicks the Exit button. */ private class ClearButtonListener implements ActionListener { public void actionPerformed(ActionEvent ae) { // Clear field sinTF.setText(""); cosTF.setText(""); tanTF.setText(""); cscTF.setText(""); secTF.setText(""); cotTF.setText(""); // Clear textfield and set cursor focus to field inputTF.setText(""); inputTF.requestFocus(); } } }

    Read the article

  • Midiplayer stops playing sounds after 16 notes.

    - by user349673
    Hi. I am currently programming a Piano Keyboard editor, much like the one you can find in Cubase, Logic, Reason etc.. I have this big grid, double array new int [13][9], which makes it 13 rows, 9 columns. The first column [0-12][0] is the Keyboard, at the top there's "high C" (midi note 72) and at the bottom there's "low C" (midi note 60). That column is an array of JButtons and when you press for example "low C", note 60 is being played by the Synthesizer. I've gotten this to work pretty OK as for now, but one problem I have is that I can only play 16 notes in a row, then it's like the Synthesizer shuts down or something. Do you guys have ANY idea of what the problem is? A bit of the code: import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; import javax.sound.midi.*; actionPerformed(ActionEvent ae){ for(int i = 0; i<13; i++){ if(o== instr[i]){//instr is the button array SpelaTangent(i); } } } public void SpelaTangent(int tangent){ int [] klaviatur = new int[13]; for(int i = 0; i<13; i++){ klaviatur[i] = (72-i); } try { Synthesizer synth = MidiSystem.getSynthesizer(); synth.open(); final MidiChannel[] mc = synth.getChannels(); Instrument[] instrument = synth.getDefaultSoundbank().getInstruments(); synth.loadInstrument(instrument[1]); mc[0].noteOn(klaviatur[tangent],350); mc[0].noteOff(klaviatur[tangent],350); } catch (MidiUnavailableException e) {} } Help is very much appreciated!

    Read the article

  • Extreme Optimization – Curves (Function Mapping) Part 1

    - by JoshReuben
    Overview ·        a curve is a functional map relationship between two factors (i.e. a function - However, the word function is a reserved word). ·        You can use the EO API to create common types of functions, find zeroes and calculate derivatives - currently supports constants, lines, quadratic curves, polynomials and Chebyshev approximations. ·        A function basis is a set of functions that can be combined to form a particular class of functions.   The Curve class ·        the abstract base class from which all other curve classes are derived – it provides the following methods: ·        ValueAt(Double) - evaluates the curve at a specific point. ·        SlopeAt(Double) - evaluates the derivative ·        Integral(Double, Double) - evaluates the definite integral over a specified interval. ·        TangentAt(Double) - returns a Line curve that is the tangent to the curve at a specific point. ·        FindRoots() - attempts to find all the roots or zeroes of the curve. ·        A particular type of curve is defined by a Parameters property, of type ParameterCollection   The GeneralCurve class ·        defines a curve whose value and, optionally, derivative and integrals, are calculated using arbitrary methods. A general curve has no parameters. ·        Constructor params:  RealFunction delegates – 1 for the function, and optionally another 2 for the derivative and integral ·        If no derivative  or integral function is supplied, they are calculated via the NumericalDifferentiation  and AdaptiveIntegrator classes in the Extreme.Mathematics.Calculus namespace. // the function is 1/(1+x^2) private double f(double x) {     return 1 / (1 + x*x); }   // Its derivative is -2x/(1+x^2)^2 private double df(double x) {     double y = 1 + x*x;     return -2*x* / (y*y); }   // The integral of f is Arctan(x), which is available from the Math class. var c1 = new GeneralCurve (new RealFunction(f), new RealFunction(df), new RealFunction(System.Math.Atan)); // Find the tangent to this curve at x=1 (the Line class is derived from Curve) Line l1 = c1.TangentAt(1);

    Read the article

  • Deferred Rendering With Diffuse,Specular, and Normal maps

    - by John
    I have been reading up on deferred rendering and I am trying to implement a renderer using the Sponza atrium model, which can be found here, as my sandbox.Note I am also using OpenGL 3.3 and GLSL. I am loading the model from a Wavefront OBJ file using Assimp. I extract all geometry information including tangents and bitangents. For all the aiMaterials,I extract the following information which essentially comes from the sponza.mtl file. Ambient/Diffuse/Specular/Emissive Reflectivity Coefficients(Ka,Kd,Ks,Ke) Shininess Diffuse Map Specular Map Normal Map I understand that I must render vertex attributes such as position ,normals,texture coordinates to textures as well as depth for the second render pass. A lot of resources mention putting colour information into a g-buffer in the initial render pass but do you not require the diffuse,specular and normal maps and therefore lights to determine the fragment colour? I know that doesnt make since sense because lighting should be done in the second render pass. In terms of normal mapping, do you essentially just pass the tangent,bitangents, and normals into g-buffers and then construct the tangent matrix and apply it to the sampled normal from the normal map. Ultimately, I would like to know how to incorporate this material information into my deferred renderer.

    Read the article

1 2 3  | Next Page >