3d,directx,shader,hlsl , Draw a sphere on a billboard with world normal from a pointlist

## Question:

I am drawing spheres on billboards by passing center world positions via a StructuredBuffer and use the geometry shader to build a billboard facing the camera. The sphere is drawn correctly and I can figure out the UVs. Now I would like to light it but I cannot figure how to calculate the normals in world coordinates...

The code look like this:

``````StructuredBuffer<float3> bufferPositions;

VS_OUTPUT VS_Main(uint vertexId : SV_VertexId)
{
VS_OUTPUT res = (VS_OUTPUT)0;

res.position = float4(bufferPositions[vertexId], 1);
res.vertexId = vertexId;

return res;
}

[maxvertexcount(4)]
void GS_Main(point VS_OUTPUT input[1], inout TriangleStream<VS_OUTPUT> OutputStream)
{
float halfWidth = SIZE / 2.0f;

float3 objToCam = normalize(input[0].position.xyz - fCameraPos);
float3 upVector = float3(0.0f, 1.0f, 0.0f);
float3 rightVector = normalize(cross(objToCam, upVector));

rightVector = rightVector * halfWidth;
upVector = normalize(cross(rightVector, objToCam)) * halfWidth;

float3 vert[4];

vert[0] = input[0].position.xyz - rightVector - upVector; // Get bottom left vertex
vert[1] = input[0].position.xyz + rightVector - upVector; // Get bottom right vertex
vert[2] = input[0].position.xyz - rightVector + upVector; // Get top left vertex
vert[3] = input[0].position.xyz + rightVector + upVector; // Get top right vertex

float2 texCoord[4];
texCoord[0] = float2(-1, -1);
texCoord[1] = float2(1, -1);
texCoord[2] = float2(-1, 1);
texCoord[3] = float2(1, 1);

VS_OUTPUT outputVert;
for(int i = 0; i < 4; i++)
{
outputVert.position = mul(float4(vert[i], 1.0f), fViewProj);
outputVert.wpos = vert[i];
outputVert.normal = objToCam;
outputVert.texcoord0 = texCoord[i];
outputVert.vertexId = input[0].vertexId;

OutputStream.Append(outputVert);
}
}

PS_OUTPUT PS_Main(VS_OUTPUT input)
{
PS_OUTPUT res = (PS_OUTPUT)0;

float3 n = float3(input.texcoord0.x, input.texcoord0.y, 0);
float r2 = dot(n.xy, n.xy);

// if the texel is not inside the sphere
if(r2 > 1.0f)

n.z = sqrt(1 - r2);

// calculate UV mapping
float u = 0.5 + atan2(n.z, n.x) / (2.0 * PI);
float v = 0.5 - asin(n.y) / PI;

// how to calculate normal in world space ?

return res;
}
``````

I should have way more information than required to do the calculations but I cannot wrap my head about the calculation to make

UPDATE: I tried to create an Axis-Normal from the plane vector and create a rotation matrix that I would apply to the local normal n without success

The following describes a way, which should work for your situation.

1. Compute normal in billboard space

For example, you could use your texture coordinates here

``````float3 normal = float3(Tex.x*2-1, 0, Tex.y*2-1);
normal.y = sqrt(normal.x*normal.x+normal.y*normal.y)
``````
1. Create an orthonormal transformation matrix (World -> Billboard)

This matrix consists of the three normalized base vectors (Left, Normal, Up) of your billboard, you will have to pass these to the pixel shader.

1. Inverse the matrix (Billboard -> World)

As the matrix is orthonormal the inverse is simply the transpose and the result transformes billdboardcoordinates to worldcoordinates.

1. Apply the matrix to the normal

An here you go, your worldspace normal is finished.

# Related:

## WhirlyGlobe Sample for android not working

android,opengl-es,3d
I have tried whirlyglobe sample code but it didn't work, can you check and make it working for android. " MapGlobeTestFragment " this one "fragment class" is missing for android sample and its not present in library.

## Why will my geometry not appear? (jMonkeyEngine)

java,3d,jmonkeyengine
I'm just now picking up jMonkeyEngine and I've encountered an issue I can't seem to solve. In the simpleInitApp method in the main class, I can use the following code to successfully render a box: Box playerBase = new Box(Vector3f.ZERO,1f,1f,1f); Geometry playerBaseGeom = new Geometry("playerBase", playerBase); Transform fixBaseHeight = new...

## DirectX libs in x64 program

64bit,directx
I'm trying to compile a program as 64 bits, it works perfectly with a simple console program but if I use my directX program it says me: error LNK1181: cannot open input file 'd3dx9.lib'. When I compile my directX program as 32 bits it works but in x64 it doesn't....

## Make Camera LookDirection look front face

c#,wpf,3d,camera
How to look at the front of 3D Model in WPF? I am confused to set X Y Z for LookDirection. I don't know what happens when I set xyz and I don't know where camera is looking at. I don't know the same thing for UpDirection. Below is my...

## Is there a way to convert a quaternion to angles?

c++,matrix,directx,quaternions,directxmath
I have a (world) matrix, and it applies translation, rotation and scale into an 3D object. It is created with the function XMMatrixTransformation (DirectXMath) and the parameter RotationQuaternion is made by a call to XMQuaternionRotationRollPitchYaw. Then it is stored in a file along with other data. Then I need to...

## D3D11 D3DX11CreateEffectFromMemory returns E_NOITERFACE

c++,directx
I'm reading the book Introduction to DirectX 11 Programming by Frank Luna and I'm having a problem with Effects11. void BoxApp::BuildFX() { DWORD shaderFlags = 0; #if defined( DEBUG ) || defined( _DEBUG ) shaderFlags |= D3D10_SHADER_DEBUG; shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION; #endif ID3D10Blob* compiledShader = 0; ID3D10Blob* compilationMsgs = 0; HRESULT...

## DirectX - Pixel Shader 3.0 doesn't work

I’ve been working on a 3D project for quite some time now, to display model files from a engine. I wrote it in C# and using the Managed DirectX wrapper (I know it is old and deprecated, but I have my own reasons to use it). I needed to write...

## Transforming surface normal vectors and tangent vectors

opengl,math,3d
According to a book Physically Based Rendering: From Theory to Implementation. By Matt Pharr, Greg Humphreys (link, p. 86-87), surface tangent vectors are transformed as common vectors, using transformation matrix M, but surface normal vectors are transformed using . I wonder why scaling does make a normal incorrect, but doesn't...

## How to use a huge array in HLSL (error X4505)

When I try to compile I get the error: X4505: sum of temp register and indexable temp registers exceeds limit of 4096. However my shader does work in FX Composer. The reason it crashes is probably because I use a very large array since I'm using marching cubes. const static...

## Constant buffer is empty when passed HLSL C++

So I moved from this problem: Previous problem to this one :). I made 2 constant buffers in C++ which I'm passing to my HLSL Shader but when I debug and look into the buffers they are just filled with zeros except the last 3 numbers (which are -572662307). I...

## Safe frame calculation

3d,3dsmax
How safe frame is calculated in 3ds Max. I want to know the relationship between Viewport width and height, Render width and height(aspect ratio) in the calculation of safe frame width and height. My final goal is to find the distance between top left corner of the plane and top...

## D3D11 Post Shader Results in Dark Image

c++,directx,direct3d,hlsl,direct3d11
I'm trying to implement post shaders (pixel shaders) as a test. I have a texture to which all stuff is rendered, and the post shader simply copies this texture to the back buffer. If this texture is larger than the back buffer, the post shading process results in dimming: However,...

## JavaFX 8 Transform to pitch, yaw and roll rotation angles

matrix,3d,rotation,javafx-8
Implementing the answer from this thread I have this code that translates the deltayaw, deltaroll and deltapitch angles into one angle and rotates a node around it. The angles that are taken as the parameters are momentary changes of angles since giving the whole angles would ignore the changes in...

## Best way to drag 3D point in 3D space with mouse picking in OpenGL?

c++,opengl,3d,drag-and-drop,mouse-picking
What is the best way to drag 3D point with mouse picking. Issue is not the picking but to dragging in 3D space. There are two ways I am thinking, one is to get the View to World coordinates using gluUnProject and translate the 3D point. The problem in this...

## Updating float4 declaration from dx9 to dx11

There's a shader which was given which I'm trying to update to be compatible with the newest Unity 5 (presumably dx11). I don't understand how float4 basic instantiation from dx9 was working. Can someone help me understand the following syntax and then provide an equivalent dx11 syntax? I understand that...

## Why translating matrix on Z axis is not the same as changing position on the Z axis by same number?

math,matrix,3d,three.js
I have a mesh that has origin point at the bottom. I want to move it by -132 on Z axis. If I change the position of the Mesh it is on the correct position. But If I translate it on the Z axis by -132, the mesh is off...

## CheckMultisampleQualityLevels(…) says the card does not support MSAA (which is not true for e.g. my GeForce GTX 780)?

c++,directx,directx-11,msaa
I use CheckMultisampleQualityLevels(...) to establish the MSAA support on my hardware. I do it in that order: D3D11CreateDevice(...) gives me device device->CheckMultisampleQualityLevels(...) Pass results to DXGI_SWAP_CHAIN_DESC.SampleDesc CreateSwapChain(...) with given DXGI_SWAP_CHAIN_DESC The problem is, CheckMultisampleQualityLevels(...) always gives me 0 for pNumQualityLevels. And I'm sure that my graphic card supports some MSAA...

## Displaying surface with non-rectangular boundary

matlab,image-processing,plot,3d,surface
Refer to the attached image. I want to display the image in Matlab using the function surf(). However, I only want to display the region of the actual object without the background (the pale-green region surrounding the actual object which has 0 value). How to do that? I tried replacing...

## 3D Lines disappear sometimes

javascript,d3.js,3d,three.js
I am building 3d line chart from data here is the code Demo the part of code that generate line is parentTransform = new THREE.Object3D(); var _color = d3.scale.category10(); for (var i = 5; i > 0; i--) { var material = new THREE.LineBasicMaterial({ // color: 0x0000ff,linewidth: 30 color: _color(i),...

## Plotting a imshow() image in 3d in matplotlib

python,matplotlib,3d
How to plot a imshow() image in 3d axes? I was trying with this post. In that post, the surface plot looks same as imshow() plot but actually they are not. To demonstrate, here I took different data: import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np...

## Invisible geometry in DX11

xna,alignment,directx,directx-11,xna-math-library
After struggling for many hours to understand and compensate for Microsoft's deprecation of D3DX in Windows 8, I've run into a problem that I can't shake off. The first time I started my program, it became immortal because of an access violation. After having restarted my computer and recompiling and...

## Unity WebPlayer “Failed to initialize player's 3D settings”?

web,unity3d,3d,augmented-reality,unity-web-player
I am trying to execute one of Daqri's AR demos, but I keep getting "Failed to initialize player's 3D settings" ...error every time I try to run the demo (Which is essentially a webpage). I am using unity 5.0.0f4 and even 4.5.3f3 (As a tried to implement a fix that...

## Finding 3D coordinate of object

opencv,image-processing,3d,camera-calibration
I try to find 3D coordinate (in world )of abject that I know his coordinate in image .so after some research in internet I succed to find X and Y cordinate. but I can't find Z that is my program in openCV void drawAndCalcul3D(int x,int y,Mat& frame) { cv::Mat uvPoint...

## DirectX 9 vertex colors ingored when lighting is enabled?

c++,directx,directx-9,lighting
Well, the question says it. When I have light disabled (pd3dDevice->SetRenderState(D3DRS_LIGHTING, TRUE);) I get the colors as expected, when I set it to true, I get pure black, even if I set the ambient light, but that's fixed when also setting a material. But the vertex colors are then ignored...

## Drawing a textured quad looks distorted

c++,directx,directx-9
I am following along on the book called Introduction To 3D Game Programming With Directx 9.0 and I've copied and pasted the following example out of the book: struct Vertex { float _x, _y, _z; float _nx, _ny, _nz; float _u, _v; // texture coordinates static const DWORD FVF; };...

## Linker error compiling DX10 program in Visual Studio 2015

I am trying to compile old program which works with DirectX 10. Full list of libraries used: #pragma comment(lib, "d3d10.lib") #pragma comment(lib, "d3dx10.lib") #pragma comment(lib, "dxgi.lib") #pragma comment(lib, "dxerr.lib") #pragma comment( lib, "dxguid.lib" ) Linker error: dxerr.lib(dxerrw.obj) : error LNK2019: unresolved external symbol _vsnwprintf referenced in function "long __cdecl StringVPrintfWorkerW(unsigned...

## creating a 3d array in python does not create array correctly

python,arrays,3d
I wish to make a 3d array by appending each element to the array in a loop, but instead of getting a 3d array I just get a 1d array with more elements in it. I'm working in Python 2.7 I want to get labels = [1,34,u'te],[2,44,u've],[4,43,u'ht] My code so...

## Clarification on Marching Cubes Algorithm

c++,algorithm,3d,marching-cubes
In regards of Marching Cubes, i have some doubts regarding its algorithm and implementation. I have gone through the excellent Paul Bourke article of Marching Cubes and also the available source code on the site, yet, i still encountered some problems in term of understanding as well as how to...

## Bid Rent Curves - Plotting Circles of Projected Radii from Another Dimension

r,plot,3d
The goal is to reproduce this Bid-Rent graph in R: The challenge is to draw the projected circles. So far I got: The 2D part is created by the R code below with the traditional graphic system in base R: #Distance X <- seq(0,7,1) #Bid Rent Curves: Commercial, Industrial, Residential...

## Converting 2D images to 3D

python,r,3d
I was trying to convert 2D images to 3D by rotating them about the axes (like a circle to a sphere). Currently my problem is that suppose I have two functions f(x) and g(x) both in one variable. I wish to make a plot of the functions and use rotation...

## plotting points in 3d surface using x,y,z coordinates

3d,gnuplot
I need to plot some points in 3d surface based on x,y,z coordiantes values in a file named as test.dat test.dat file contains At-No X Y Z 6 3.532210 -2.171743 0.921140 7 1.164869 -1.418981 0.782133 1 2.454732 2.332989 -0.907213 6 -3.246376 -1.047325 -0.602590 6 -2.620684 0.053348 -0.013310 6 -4.569969 -1.249720...

## How to calculate a random point inside a cube

math,vector,3d,cube
I'm trying to figure out the math to find a random point inside a cube. I have something small but it can't take into account the rotation of the cube. Here are some images of my results. Here you can see the cube is rotated to some degree but when...

## Pygame 3D: How to and is it possible?

python,performance,dictionary,3d,pygame
So I want to program a 3d-mesh viewer in pygame, no other 3rd-party modules wanted (panda3d is perfect, but it's very complicated). My idea is: list_of_surfs = {'85 50':'70deg'} #the 85 50 and the dimensions of the #side/surf, and 70 deg of rotation to be able to see it, then...

## DirectX 9 projection matrix infinite element?

c++,graphics,3d,directx-9
I've been banging my head on doing transformations in DirectX 9 and during debugging I finally noticed a problem, when calling D3DXMatrixPerspectiveFovLH(&projection, D3DX_PI/4, yRes/xRes, 1, 100); the first element (_11) of projection is #INF, which I'm pretty sure it should not be. This is directly after declaring this matrix and...

## DirectWrite align text center

c++,text,directx,direct2d,directwrite
I am trying to align center the text I have to draw. I use ID2D1RenderTarget::DrawTextLayout method. The problemn is that if I set the text horizontal alignment to DWRITE_TEXT_ALIGNMENT_LEADING (the default value) the text is drawn proberly, but if I change this value to DWRITE_TEXT_ALIGNMENT_CENTER the text is shifted right....

## MATLAB: How to make camera light follow 3D Rotation

matlab,user-interface,3d,rotation,lighting
I have come into a problem recently when trying to rotate 3D objects. I am building a GUI and I have a separate figure where an object is plotted. In the figure, I allow the user to use MATLAB's built-in rotate button to move the object around. However, I am...

## OpenGL cube not being rendered

c++,opengl,3d
I'm struggling to get a cube to render in opengl. When I pass in the MVP already calculated to the vertex shader it works fine, but when I pass in the model, view and projection then do the calculation in the vertex shader it doesn't show the cube. I'm also...

## Why osgviewer works while osgDB::readImageFile() fails?

3d,openscenegraph
I'm new to OpenSceneGraph, and now I met a problem. When trying out a simple skybox program, it gives Warning: Could not find plugin to read objects from file "xxx.jpg" when calling osgDB::readImageFile(), and I can only see a white screen; Then I tried using osgviewer --image xxx.jpg in cmd,...

## How to setup camera to point at object

ios,3d,scenekit
In my app I load models from different files (format is the same) and they have different geometry: big, small, wide, etc. I have object and camera position hard coded and for some cases I don't see anything because camera not point to object. Maybe there is a way to...

## How to apply flat shading to RGB colors?

graphics,colors,3d,rgb
I am creating a small 3d rendering application. I decided to use simple flat shading for my triangles - just calculate the cosine of angle between face normal and light source and scale light intensity by it. But I'm not sure about how exactly should I apply that shading coefficient...

## JavaFX 3D TriangleMesh with transparency

javafx,3d,transparency,transparent,javafx-3d
I have a texture I want to use for a TriangleMesh (it's a simple cube). Some parts of the texture are transparent. When I put the texture on the mesh, it's black. Is there a possibility to change that? I would like to make it transparent. Appreciate your help, thanks...

## How to check a point is inside an ellipsoid with orientation?

algorithm,3d,geometry,distance,computational-geometry
For an ellipsoid of the form with orientation vector and centre at point , how to find whether a point is inside the ellipsoid or not? An additional note that the geometry actually is with a=b (spheroid) and therefore one axis is sufficient to define orientation Note: I see a...

## DirectX 9 not rendering after adding transforms

c++,3d,directx,direct3d,directx-9
so far I got a cube rendered without any transforms (thus it was rendered in an orthographic perspective), and I am working on the previous code to get it into a perspective view, with all the matrices involved. I changed the Flexible Vertex Format so as not to have RHW...

## Draw a sphere on a billboard with world normal from a pointlist

I am drawing spheres on billboards by passing center world positions via a StructuredBuffer and use the geometry shader to build a billboard facing the camera. The sphere is drawn correctly and I can figure out the UVs. Now I would like to light it but I cannot figure how...

## how to create a 3D height map in python

python,matplotlib,plot,3d,surface
I have a 2D array Z that stores the height at that element's position. Other than using the method here in which I need to create array X and Y with the same size as Z, are there any simpler methods to create a 3D height map? The 3D surface...

## Is there any easy way to rotate an image about z axis using java without jumping into java 3d?

java,3d,image-rotation
I want to rotate an image about the z axis using java. I tried to search for ways to do that but it involves complex matrix manipulations and it works on 3d models and stuff. I will resort to that if there is no other way but would like to...

## Relationship between AFX_WM_DRAW2D and WM_PAINT in MFC Application

c++,graphics,mfc,directx,direct2d
What is the relationship between the two messages in the subject? When exactly the AFX_WM_DRAW2D is passed to application queue. I am asking because I have encountered the strangest recursive call of AFX_WM_DRAW2D handler. Whenever I am trying to paint something inside the AFX_WM_DRAW2Din compatibe render target the handler is...

## How to make 3D histogram in R

r,plot,3d,histogram
This is my goal: Plot the frequency of y according to x in the z axis. These are my problems: I have a two columns array (x and y) and need to divide x into classes (p.ex. 0.2 ou 0.5) and calculate the frequency of y for each class of...