I've simplified things down to cubes/a single cube colliding with an infinite-mass rectangle and the following code:
The problem is, the boxes tend to spin too much and get stuck together spinning and, if the binary search is included, just hit and spin a lot.
Thanks for any and all help.
/// <summary>
/// Projects an abstract 1D line "perpendicular" to the axis,
/// stretching across the width of the model,
/// measured from that axis.
/// </summary>
/// <param name="Axis"></param>
/// <param name="Min"></param>
/// <param name="Max"></param>
protected virtual void ProjectToAxis(Vector2 Axis, IMotionData motionData, out double Min, out double Max)
{
Double DotP = Axis.Dot(motionData.PositionGS + (this.Vertices[0].Position * this.Model.Scale).Rotate(motionData.RotationGS));
Min = Max = DotP;
for (int t = 1; t < this.Vertices.Count(); ++t)
{
DotP = Axis.Dot(motionData.PositionGS + (this.Vertices[t].Position * this.Model.Scale).Rotate(motionData.RotationGS));
Min = Math.Min(DotP, Min);
Max = Math.Max(DotP, Max);
}
}
/// <summary>
/// Projects two imaginary lines even with each edge,
/// equal to the width of each object while looking at
/// that edge, then checks to see if they intersect.
/// </summary>
/// <param name="B1"></param>
/// <param name="B2"></param>
/// <returns></returns>
public static bool DetectCollision(Body B1, Body B2, Double elapsedSeconds)
{
CollisionData collisionInfo = new CollisionData();
double lowestDistance = double.MaxValue;
double distance;
Vector2 normalB1ToB2 = (B2.MotionHandler.PositionGS - B1.MotionHandler.PositionGS).Normalized;
foreach (Edge edge in B1.Edges)
{
if (edge.Normal.RelativePosition.Dot(normalB1ToB2) >= 0.0)
{
double minA, minB, maxA, maxB;
B1.ProjectToAxis(edge.Normal.RelativePosition, B1.MotionHandler.MotionDataGet, out minA, out maxA);
B2.ProjectToAxis(edge.Normal.RelativePosition, B2.MotionHandler.MotionDataGet, out minB, out maxB);
if (minA < minB)
distance = minB - maxA;
else
distance = minA - maxB;
if (distance > 0.0f)
return false;
else if (Math.Abs(distance) < lowestDistance)
{
lowestDistance = Math.Abs(distance);
collisionInfo.Normal = edge.Normal.RelativePosition;
collisionInfo.Edge = edge;
}
}
}
Vector2 normalB2ToB1 = -normalB1ToB2;
foreach (Edge edge in B2.Edges)
{
if (edge.Normal.RelativePosition.Dot(normalB2ToB1) >= 0.0)
{
double minA, minB, maxA, maxB;
B1.ProjectToAxis(edge.Normal.RelativePosition, B1.MotionHandler.MotionDataGet, out minA, out maxA);
B2.ProjectToAxis(edge.Normal.RelativePosition, B2.MotionHandler.MotionDataGet, out minB, out maxB);
if (minA < minB)
distance = minB - maxA;
else
distance = minA - maxB;
if (distance > 0.0f)
return false;
else if (Math.Abs(distance) < lowestDistance)
{
lowestDistance = Math.Abs(distance);
collisionInfo.Normal = edge.Normal.RelativePosition;
collisionInfo.Edge = edge;
}
}
}
collisionInfo.Depth = lowestDistance;
/* Double lowHighSeconds = elapsedSeconds;
Double highLowSeconds = 0.0;
Double seconds;
IMotionData md1;
IMotionData md2;
bool collision;
do
{
md1 = B1.MotionHandler.MotionDataLastGet.Copy;
md2 = B2.MotionHandler.MotionDataLastGet.Copy;
collision = true;
lowestDistance = Double.MaxValue;
seconds = MathExtensions.MathExt.Lerp(highLowSeconds, lowHighSeconds, 0.5);
B1.MotionHandler.Simulate(seconds, ref md1);
B2.MotionHandler.Simulate(seconds, ref md2);
normalB1ToB2 = (md2.PositionGS - md1.PositionGS).Normalized;
foreach (Edge edge in B1.Edges)
{
if ((edge.Normal.Position * B1.Model.Scale).Rotate(md1.RotationGS).Dot(normalB1ToB2) >= 0.0)
{
double minA, minB, maxA, maxB;
B1.ProjectToAxis((edge.Normal.Position * B1.Model.Scale).Rotate(md1.RotationGS), md1, out minA, out maxA);
B2.ProjectToAxis((edge.Normal.Position * B1.Model.Scale).Rotate(md1.RotationGS), md2, out minB, out maxB);
if (minA < minB)
distance = minB - maxA;
else
distance = minA - maxB;
if (distance > 0.0f)
collision = false;
else if (Math.Abs(distance) < lowestDistance)
{
lowestDistance = Math.Abs(distance);
collisionInfo.Normal = (edge.Normal.Position * B1.Model.Scale).Rotate(md1.RotationGS);
collisionInfo.Edge = edge;
}
}
}
normalB2ToB1 = -normalB1ToB2;
foreach (Edge edge in B2.Edges)
{
if ((edge.Normal.Position * B2.Model.Scale).Rotate(md2.RotationGS).Dot(normalB2ToB1) >= 0.0)
{
double minA, minB, maxA, maxB;
B2.ProjectToAxis((edge.Normal.Position * B2.Model.Scale).Rotate(md2.RotationGS), md2, out minA, out maxA);
B1.ProjectToAxis((edge.Normal.Position * B2.Model.Scale).Rotate(md2.RotationGS), md1, out minB, out maxB);
if (minA < minB)
distance = minB - maxA;
else
distance = minA - maxB;
if (distance > 0.0f)
collision = false;
else if (Math.Abs(distance) < lowestDistance)
{
lowestDistance = Math.Abs(distance);
collisionInfo.Normal = (edge.Normal.Position * B2.Model.Scale).Rotate(md2.RotationGS);
collisionInfo.Edge = edge;
}
}
}
collisionInfo.Depth = lowestDistance;
if (!collision)
{
lowHighSeconds = seconds;
}
else
{
highLowSeconds = seconds;
}
} while (Math.Abs(highLowSeconds - lowHighSeconds) > 0.0001);
B1.MotionHandler.MotionDataSet = md1;
B2.MotionHandler.MotionDataSet = md2; */
// bool flip = false;
if (collisionInfo.Edge.Parent != B2.Model)
{
Body temp = B1;
B1 = B2;
B2 = temp;
}
//This is needed to make sure that the collision normal is pointing at B1
int Sign = Math.Sign(
collisionInfo.Normal.Dot(
B1.MotionHandler.MotionDataGet.PositionGS + (B1.Center * B1.Model.Scale).Rotate(B1.MotionHandler.MotionDataGet.RotationGS) -
B2.MotionHandler.MotionDataGet.PositionGS + (B2.Center * B2.Model.Scale).Rotate(B2.MotionHandler.MotionDataGet.RotationGS)
)
);
//Remember that the line equation is N*( R - R0 ). We choose B2->Center
//as R0; the normal N is given by the collision normal
if (Sign != 1)
collisionInfo.Normal = -collisionInfo.Normal; //Revert the collision normal if it points away from B1
double SmallestD = double.MaxValue; //Initialize the smallest distance to a high value
//Measure the distance of the vertex from the line using the line equation
for (int t = 0; t < B1.Vertices.Count(); ++t)
{
double Distance = collisionInfo.Normal.Dot(B1.Vertices[t].WorldPosition - B2.Center);
// If the measured distance is smaller than the smallest distance reported
// so far, set the smallest distance and the collision vertex
if (Distance < SmallestD)
{
SmallestD = Distance;
collisionInfo.Vertex = B1.Vertices[t];
}
}
if ((Body.CollisionType & CollisionType.Velocity) > 0)
{
Vector2 vab1 = B1.MotionHandler.VelocityGS - B2.MotionHandler.VelocityGS;
Vector2 rap = (B1.MotionHandler.PositionGS - collisionInfo.Normal);
Vector2 rbp = (B2.MotionHandler.PositionGS - collisionInfo.Normal);
Double rap2 = (rap.Cross(collisionInfo.Normal));
Double rbp2 = (rbp.Cross(collisionInfo.Normal));
Vector2 one = (collisionInfo.Vertex.WorldPosition - B1.MotionHandler.PositionGS).GetPerpendicular;
Vector2 two = (collisionInfo.Vertex.WorldPosition - B2.MotionHandler.PositionGS).GetPerpendicular;
Double j = (-(1 + 0.0) * vab1.Dot(collisionInfo.Normal)) /
((collisionInfo.Normal.Dot(collisionInfo.Normal) * (B1.MotionHandler.InverseMassGS + B2.MotionHandler.InverseMassGS)) +
(one.Dot(one) * B1.MotionHandler.InverseInertiaGS) + (two.Dot(two) * B2.MotionHandler.InverseInertiaGS));
B1.MotionHandler.AddImpulse = new Force(
collisionInfo.Normal,
j /* ,
one */
);
B2.MotionHandler.AddImpulse = new Force(
collisionInfo.Normal,
-(j) /* ,
two */
);
NewtonianMotionData data1 = (NewtonianMotionData)B1.MotionHandler.MotionDataGet;
NewtonianMotionData data2 = (NewtonianMotionData)B2.MotionHandler.MotionDataGet;
data1.AngularVelocity += (one.Dot(j * collisionInfo.Normal)) * data1.inverseInertia;
data2.AngularVelocity += (two.Dot(-j * collisionInfo.Normal)) * data2.inverseInertia;
B1.MotionHandler.MotionDataSet = data1;
B2.MotionHandler.MotionDataSet = data2;
}
return true;
}
You've got two problems.
1) There's something wrong with the code. You need to fix that.
2) You don't know how to figure out what "something" is.
Solving the first problem is gated on your solving the second problem. You need to learn how to debug a program you just wrote.
You've already tested it and gotten a result which you've identified as nonsensical. That's a good first step. Now break it down even farther. Pick a simple problem in this domain that you can solve yourself with pencil and paper; do so, and then watch your algorithm solve the same problem in the debugger, checking every step along the way. Listen to quiet nagging doubts. When there is anything that looks slightly off or unexpected, stop what you're doing and investigate the issue until you understand whether things are working correctly or not. Eventually you'll find a step where things aren't as they should be, and that's where the bug is.
Yes, this is tedious. When you've found the bug and fixed it, pause and reflect upon what caused you to write the bug in the first place, and figure out how to not write that kind of bug ever again.
UPDATE:
Re: your recent comments.
Apology accepted. Now calm down. You're never going to find this bug if you're this worked up. Your brain will not let you. Humans who are in a panicky, worked-up state lose the ability to reason. That's why fire doors open outwards; humans fleeing a burning building literally will not stop to think "I'm pushing on this door and its not opening, maybe I should try pulling". They just push harder. I suspect you are pushing harder.
Debugging requires rationality and careful attention to small details. If you're all worked up about this problem then that's going to go out the window and its just going to get worse. Take it from someone who has been there. We've all been there. It's a deeply frustrating thing to have caused a bug in your own program that you then cannot find.
The reason no one is helping you is because... well, let me list the set of preconditions that have to be met for me to help you with more than vague platitudes and suggestions of how to focus your debugging efforts:
1) I have to know something about simulation of 3d physics. I had a pretty decent grasp of the differential equations of simple of Newtonian mechanics in 1992, but I haven't used it since. And the equation of a damped driven spring is rather different than the equations of rigid body collisions. If I spent a couple weeks reviewing my notes I could get the math back, but that's not realistic. You need someone who is deeply conversant right now with 3d collision physics simulations.
2) I have to be able to read and understand your code, code which is hundreds of lines long, written by someone other than me, to solve a problem I'm not familiar with. Worse, a hundred lines of that code is commented out. Why? Is it relevant? Is the bug in there? Moreover, I need to be able to read and understand the code without running it in a debugger. Heck, I can't even compile that code. It depends on libraries that I don't have.
And even worse still, one of those libraries might contain the bug. For all I know, the bug is a typo in some code that calculates a normal somewhere that you haven't shown us. The code shown could be perfect.
3) I need to have the free time to work on someone else's hard problem; a problem that the person who wrote the code and understands the physics is making no headway on.
All of these are requirements; if any one of them is missing, the reader cannot effectively help you. You're asking people you don't know to help you find a black cat in a dark warehouse at midnight without a flashlight -- a cat that might not even be there. It's not surprising you're getting few takers. Of the 74 stack overflow users who have read your question, how many of them meet all three requirements? I meet none of them.
If you want help on this site then post an easier problem. Narrow the problem down to a problem that requires less special knowledge of physics and simulation algorithms and has only the relevant code, preferably code that can be compiled and run.
This may not be good news, but I have a couple of things to add to Eric Lippert's analysis, and a suggestion.
Your comments are misleading. I know that if you're not familiar with math and physics it's hard to be precise, but take a look at "ProjectToAxis":
/// Projects an abstract 1D line "perpendicular" to the axis,
/// stretching across the width of the model,
/// measured from that axis.
Forgive me if this sounds harsh, but
"abstract 1d line" is kind of meaningless, it should just say "line".
It's not really projecting a line.
It's measuring extent parallel to the axis, not perpendicular to it.
It's not "across the width", exactly, it's just the greatest extent.
"measured from that axis" is either meaningless or wrong, I can't tell which.
Believe me, I'm not trying to pick nits, it's just that I'm trying to figure out what this code is supposed to do, and a bad comment is worse than none. I can see what this function does (assuming that functions like "Dot" work as advertised), but I still don't know whether it does what you want it to do.
Now I take a look at DetectCollision (which does more than just detect a collision):
/// Projects two imaginary lines even with each edge,
/// equal to the width of each object while looking at
/// that edge, then checks to see if they intersect.
What? All I can do is ignore this and look at the code... There are parts of it that don't make much sense (e.g. why the heck do you project a body onto every one of its edges?), so reverse-engineering is going to be very difficult.
If I knew the algorithm you were trying for, I could try to find the bug. If the code worked, I could try to deduce the algorithm. But if the code doesn't work and (as I suspect) you don't really know the algorithm yourself, we're kind of stuck.
Here's an approach that might work: This function is too long, it does a lot, and you don't know which parts it does correctly. Ergo you should break it down into several functions and test them individually. (I can't do that myself, for the reasons Eric Lippert spelled out.) You could start by breaking into two functions, one that calculates CollisionInfo (leaving the bodies constant) and another that adjusts the motion of the bodies (leaving CollisionInfo constant).
Related
im trying to make a script for automated, dynamic adjustment of thrusters to maintain the speed of a vehicle.
in case u want to know its for a game^^
well anyway it keeps getting me that index was out of range error.
Heres my Code i added comments to make it more clearly
List<IMyTerminalBlock> blocks = new List<IMyTerminalBlock>();
string ThrusterControl = "Thrusters.Forward"; //the name of my thrusters.
string CruiseControl = "AI.Computer"; //The name of the block running this code.
double setSpeed=0.250; //my desired speed (units/tick).
double maxSpeed=3.000; //This script disengages thruster overrides while im are above this speed.
double checkSpeed=0.75; //Determines the acceptable speed range.
double decelerationRate=0.9; //Thrust override reduction factor
float speedBoost=500; //Gives a boost when im not moving
float minThrust=125; //Minimum legal value of thrust override.
double x0,dx;
double y0,dy;
double z0,dz;
double speed;
float newThrust;
void Main(){
//Determine ship speed.
GridTerminalSystem.SearchBlocksOfName(CruiseControl,blocks);
double x = Math.Round(blocks[0].GetPosition().GetDim(0),3);
double y = Math.Round(blocks[0].GetPosition().GetDim(1),3);
double z = Math.Round(blocks[0].GetPosition().GetDim(2),3);
dx=x-x0;dy=y-y0;dz=z-z0;x0=x;y0=y;z0=z;
speed=Math.Round(Math.Sqrt(dx*dx+dy*dy+dz*dz),5);
blocks[0].SetCustomName(CruiseControl+":"+"\n"+"speed (units/tick) "+speed );
//Increase thrust override if im going too slow.
if(speed < setSpeed * checkSpeed){
GridTerminalSystem.SearchBlocksOfName(ThrusterControl, blocks);
for(int i=0; i < blocks.Count;){
blocks[0].GetActionWithName("IncreaseOverride").Apply(blocks[0]);
i++;}
//Give an extra thrust boost if you're im not moving at all.
if(speed < setSpeed * 0.05){
newThrust = (float)Math.Round(blocks[0].GetValueFloat("Override") + speedBoost,4);
for(int i=0; i < blocks.Count;){
blocks[i].SetValueFloat("Override", newThrust);
i++;}
}
}
//Slowly reduces thrust override if im going too fast.
if(speed > setSpeed / checkSpeed){
GridTerminalSystem.SearchBlocksOfName(ThrusterControl, blocks);
newThrust = (float)Math.Round(blocks[0].GetValueFloat("Override") * decelerationRate, 4);
if( newThrust > minThrust){ //Prevents this script from disabling the thruster override.
for(int i=0; i < blocks.Count;){
blocks[i].SetValueFloat("Override", newThrust);
i++;}
}
//Reset thruster overrides if moving too fast. Allows inertial dampers to regain control of vehicle.
if(speed > maxSpeed){
for(int i=0; i < blocks.Count;){
blocks[i].SetValueFloat("Override", 0);
i++;}
}
}
}
can someone correct my code please?
Instead of having someone correct your code, wouldn't it be nice to understand exactly what's going on?
This exception is quite easy to debug. Visual Studio will stop execution where it occurs, and highlight the exact line. While this line is highlighted, you can mouse-over your variables and see their values to:
Inspect the collection, and the number of items in it
Inspect the variable that holds the index which is causing the problem
The index variable will then either be less than 0 or greater or equal to the number of items in the collection.
With that information, you might be able to solve the issue yourself, but if not, you'll be able to ask a totally different question on SO.
EDIT:
If you're unable to debug this properly, you can always do a range check yourself, ie:
public void MyFunction()
{
for (int i = ...)
{
if (i < 0 || i >= blocks.Count)
{
System.IO.File.AppendAllText(#"error.log", "Error in MyFunction(), i = " + i + ", blocks.Count = " + blocks.Count);
}
blocks[i].SetValue(...);
}
}
It takes alot more time, but it will at least give you insight in what's going on.
I am currently trying to write some fourier transform algorithm. I started with a simple DFT algorithm as described in the mathematical definition:
public class DFT {
public static Complex[] Transform(Complex[] input) {
int N = input.Length;
Complex[] output = new Complex[N];
double arg = -2.0 * Math.PI / (double)N;
for (int n = 0; n < N; n++) {
output[n] = new Complex();
for (int k = 0; k < N; k++)
output[n] += input[k] * Complex.Polar(1, arg * (double)n * (double)k);
}
return output;
}
}
So I tested this algorithm with the following code:
private int samplingFrequency = 120;
private int numberValues = 240;
private void doCalc(object sender, EventArgs e) {
Complex[] input = new Complex[numberValues];
Complex[] output = new Complex[numberValues];
double t = 0;
double y = 0;
for (int i = 0; i < numberValues; i++) {
t = (double)i / (double)samplingFrequency;
y = Math.Sin(2 * Math.PI * t);
input[i] = new Complex(y, 0);
}
output = DFT.Transform(input);
printFunc(input);
printAbs(output);
}
The transformation works fine, but only if numberValues is a multiple number of the samplingFrequency (in this case: 120, 240, 360,...). Thats my result for 240 values:
The transformation just worked fine.
If i am trying to calculate 280 values I get this result:
Why I am getting a incorrect result if I change the number of my calculated values?
I am not sure if my problem here is a problem with my code or a misunderstanding of the mathematical definition of the DFT. In either way, can anybody help me with my problem? Thanks.
What you are experiencing is called Spectral Leakage.
This is caused because the underlying mathematics of the Fourier transform assumes a continuous function from -infinity to + infinity. So the range of samples you provide is effectively repeated an infinite number of times. If you don't have a complete number of cycles of the waveform in the window the ends won't line up and you will get a discontinuity which manifests its self as the frequency smearing out to either side.
The normal way to handle this is called Windowing. However, this does come with a downside as it causes the amplitudes to be slightly off. This is the process of multiply the whole window of samples you are going to process by some function which tends towards 0 at both ends of the window causing the ends to line up but with some amplitude distortion because this process lowers the total signal power.
So to summarise there is no error in your code, and the result is as expected. The artefacts can be reduced using a window function, however this will effect the accuracy of the amplitudes. You will need to investigate and determine what solution best fits the requirements of your project.
You are NOT getting the incorrect result for a non-periodic sinusoid. And they are not just "artifacts". Your result is actually the more complete DFT result which you don't see with a periodic sinusoid. Those other non-zero values contain useful information which can be used to, for example, interpolate the frequency of a single non-periodic-in-aperture sinusoid.
A DFT can be thought of as convolving a rectangular window with your sine wave. This produces (something very close to) a Sinc function, which has infinite extent, BUT just happens to be zero at every DFT bin frequency other than its central DFT bin for any sinusoid centered exactly on a DFT bin. This happens only when the frequency is exactly periodic in the FFT aperture, not for any other. The Sinc function has lots of "humps" which are all hidden in your first plot.
I've got a table of values telling me how the signal level changes over time and I want to simulate a harmonic oscillator driven by this signal. It does not matter if the simulation is not 100% accurate.
I know the frequency of the oscillator.
I found lots of formulas but they all use a sine wave as driver.
I guess you want to perform some time-discrete simulation. The well-known formulae require analytic input (see Green's function). If you have a table of forces at some point in time, the typical analytical formulae won't help you too much.
The idea is this: For each point in time t0, the oscillator has some given acceleration, velocity, etc. Now a force acts on it -according to the table you were given- which will change it's acceleration (F = m * a). For the next time step t1, we assume the acceleration stays at that constant, so we can apply simple Newtonian equations (v = a * dt) with dt = (t1-t0) for this time frame. Iterate until the desired range in time is simulated.
The most important parameter of this simulation is dt, that is, how fine-grained the calculation is. For example, you might want to have 10 steps per second, but that completely depends on your input parameters. What we're doing here, in essence, is an Eulerian integration of the equations.
This, of course, isn't all there is - such simulations can be quite complicated, esp. in not-so-well behaved cases where extreme accelerations, etc. In those cases you need to perform numerical sanity checks within a frame, because something 'extreme' happens in a single frame. Also some numerical integration might become necessary, e.g. the Runge-Kutta algorithm. I guess that leads to far at this point, however.
EDIT: Just after I posted this, somebody posted a comment to the original question pointing to the "Verlet Algorithm", which is basically an implementation of what I described above.
http://en.wikipedia.org/wiki/Simple_harmonic_motion
http://en.wikipedia.org/wiki/Hooke's_Law
http://en.wikipedia.org/wiki/Euler_method
Ok, i finally figured it out and wrote a gui app to test it until it worked. But my pc is not very happy with doing it 1000*44100 times per second, even without gui^^
Whatever: here is my test code (wich worked quite well):
double lastTime;
const double deltaT = 1 / 44100.0;//length of a frame in seconds
double rFreq;
private void InitPendulum()
{
double freq = 2;//frequency in herz
rFreq = FToRSpeed(freq);
damp = Math.Pow(0.8, freq * deltaT);
}
private static double FToRSpeed(double p)
{
p *= 2;
p = Math.PI * p;
return p * p;
}
double damp;
double bHeight;
double bSpeed;
double lastchange;
private void timer1_Tick(object sender, EventArgs e)
{
double now=sw.ElapsedTicks/(double)Stopwatch.Frequency;
while (lastTime+deltaT <= now)
{
bHeight += bSpeed * deltaT;
double prevSpeed=bSpeed;
bSpeed += (mouseY - bHeight) * (rFreq*deltaT);
bSpeed *= damp;
if ((bSpeed > 0) != (prevSpeed > 0))
{
Console.WriteLine(lastTime - lastchange);
lastchange = lastTime;
}
lastTime += deltaT;
}
Invalidate();//No, i am not using gdi^^
}
I load multiple meshs from .x files in different mesh variables.
Now I would like to calculate the bounding sphere across all the meshes I have loaded (and which are being displayed)
Please guide me how this could be achieved.
Can VertexBuffers be appended togather in one variable and the boundingSphere be computed using that? (if yes how are they vertexBuffers added togather)
Otherwise what alternative would you suggest!?
Thankx
Its surprisingly easy to do this:
You need to, firstly, average all your vertices. This gives you the center position.
This is done as follows in C++ (Sorry my C# is pretty rusty but it should give ya an idea):
D3DXVECTOR3 avgPos;
const rcpNum = 1.0f / (float)numVerts; // Do this here as divides are far more epxensive than multiplies.
int count = 0;
while( count < numVerts )
{
// Instead of adding everything up and then dividing by the number (which could lead
// to overflows) I'll divide by the number as I go along. The result is the same.
avgPos.x += vert[count].pos.x * rcpNum;
avgPos.y += vert[count].pos.y * rcpNum;
avgPos.z += vert[count].pos.z * rcpNum;
count++;
}
Now you need to go through every vert and work out which vert is the furthest away from the center point.
Something like this would work (in C++):
float maxSqDist = 0.0f;
int count = 0;
while( count < numVerts )
{
D3DXVECTOR3 diff = avgPos - vert[count].pos;
// Note we may as well use the square length as the sqrt is very expensive and the
// maximum square length will ALSO be the maximum length and yet we only need to
// do one sqrt this way :)
const float sqDist = D3DXVec3LengthSq( diff );
if ( sqDist > maxSqDist )
{
maxSqDist = sqDist;
}
count++;
}
const float radius = sqrtf( maxSqDist );
And you now have your center position (avgPos) and your radius (radius) and, thus, all the info you need to define a bounding sphere.
I have an idea, what I would do is that I would determine the center of every single mesh object, and then determine the center of the collection of mesh objects by using the aforementioned information ...
I'm trying to write a simple raytracer as a hobby project and it's all working fine now, except I can't get soft-shadows to work at all. My idea of soft-shadows is that the lightsource is considered to have a location and a radius. To do a shadow test on this light I take the point where the primary ray hit an object in the scene and cast an n-amount of rays towards the lightsource where each new ray has a random component to every axis, where the random component varies between -radius and radius.
If such a ray hits an object in the scene, I increment a hitcounter (if a ray hits multiple objects, it still only increments with one). If it makes it to the lightsource without collisions, I add the distance of the primary ray's intersect point to the lightsource's center to a variable.
When n samples have been taken, I calculate the ratio of rays that have collided and multiply the color of the light by this ratio (so a light with color 1000,1000,1000 will become 500,500,500 with a ratio of 0.5, where half the rays have collided). Then I calculate the average distance to the lightsource by dividing the distance variable of earlier by the amount of non-colliding rays. I return that variable and the function exits.
The problem is: it doesn't work. Not quite at least. What it looks like can be seen here. You can see it sort of resembles soft-shadows, if you squint real hard.
I don't get it, am I making some sort of fundamental flaw here, or is it something tiny? I'm fairly sure the problem is in this method, because when I count the number of partially lit pixels produced directly by this method, there are only about 250, when there should be a lot more. And when you look closely at the picture, you can see there's some partially lit pixels, suggesting the rest of the code processes the partially lit pixels just fine.
Here's the actual light for soft-shadows class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyFirstRayTracer
{
public class AreaLight : ILight
{
private const int _radius = 5;
private const int _samples = 16;
public Color Color { get; set; }
public Vector Location { get; set; }
#region ILight Members
public float GetLightingInformation(Vector point, ISceneObject[] scene, out Color color)
{
int intersectCount = 0;
float distance = -1;
for(int i = 0; i < _samples; i++)
{
bool intersects = false;
float rand = 0;
rand = _radius - (float)(new Random().NextDouble()*(2*_radius));
foreach (ISceneObject obj in scene)
{
Vector iPoint;
Vector loc = new Vector(Location.X + rand, Location.Y + rand, Location.Z + rand);
if (!obj.Intersect(new Ray(point, loc), out iPoint))
{
distance += (Location - point).SqLength;
}
else
{
intersects = true;
distance -= (Location - point).SqLength;
}
}
if (intersects)
intersectCount++;
}
float factor = 1-((float)intersectCount/_samples);
color = new Color(factor*Color.R, factor*Color.G, factor*Color.B);
return (float)Math.Sqrt(distance / (_samples - intersectCount));
}
#endregion
}
}
minor point but is this the best use of the random class..
for(int i = 0; i < _samples; i++)
{
bool intersects = false;
float rand = 0;
rand = _radius - (float)(new Random().NextDouble()*(2*_radius));
should this not be..
var rnd = new Random()
for(int i = 0; i < _samples; i++)
{
bool intersects = false;
float rand = 0;
rand = _radius - (float)(rnd.NextDouble()*(2*_radius));
Try generating a different "rand" for each component of "loc". As is, your jittered points all lie on a line.
You actually generate the point on the line on a line with direction (1, 1, 1). Is the lightsource really linear?
Also, I can barely see anything in your example. Could you make your camera nearer the to-be shadow and not pointing from the direction of the light?
See, this is why I come to this site :)
Every axis has its own random now, and it looks a lot better. It's still a little weird looking, increasing the number of samples helps though. It now looks like this.
Do you know a more efficient way to reduce the pattern-forming?
The biggest help though: not instantiating Random for every sample. It seriously tripled my rendering speed with soft shadows! I never knew that Random was so costly to instantiate. Wow.
Thanks a lot.
In your response you asked for an improved way to make soft shadows. An improvement could be, instead of randomizing all the rays from the same point, to give each ray a different offset on all axes to effectively give them a seperate little window to randomize in. This should result in a more even distribution. I don't know if that was clear but another way to describe it is as a grid which is perpendicular to the shadow ray. Each tile in the grid contains one of the n shadow rays but the location in the grid is random. Here you can find a part of a tutorial which describes how this can be used for soft shadows.