Sunday, June 5, 2016

c# - Calculate average of arbitrary amount of quaternions (recursion)


Simply calculate the average for 2 Quaternions should work like follows right? :


Quaternion.Lerp(rotationlist[0].transform.rotation, rotationlist[1].transform.rotation, 0.5f);

And now I tried to put this into a recursive function, like this:


private Quaternion calcAvg(int pos, List rotationlist)

{
if (pos < rotationlist.Count)
{
return Quaternion.Lerp(rotationlist[pos].transform.rotation, calcAvg(++pos, rotationlist), 0.5f);
}
return ???;
}

But I'm not absolutely sure, what to put into the second return.


Edit, I added the last position into the second return but now I get an out of bounds exception:



private Quaternion calcAvg(int pos, List markerList)
{
if (pos < markerList.Count)
{
return Quaternion.Lerp(markerList[pos].transform.rotation, calcAvg(++pos, markerList), 0.5f);
}
return markerList[pos].transform.rotation;
}

Edit, fixed the issue, I will test this now but it looks alright :



private Quaternion calcAvg(int pos, List markerList)
{
if (pos < markerList.Count)
{
return Quaternion.Lerp(markerList[pos].transform.rotation, calcAvg(++pos, markerList), 0.5f);
}
return markerList[pos].transform.rotation;
}

Answer



In your approach, the first quat in the list gets weighted at 50%, and all the rest together will be weighted for the other 50%.



If you had 4 quats, with your approach, their relative weightings will be 0.5, 0.25, 0.125, 0.125.


You could fix this my changing the 0.5f to something computed based on list and position.


You could also make the recursion more balanced with something like:


calcAvg(List quats):
if(quats.size == 0): ERROR
if(quats.size == 1):
return quats[0]
List firstHalf = first half of quats list
List secondHalf = second half of quats list
q1 = calcAvg(firstHalf)

q2 = calcAvg(secondHalf)
return Lerp(q1, q2, firstHalf.size / quats.size)

I'm not completely certain of the geometric characteristics of this kind of Angle Averaging. Probably fine for game use...


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...