[Gambas-user] "wrapping" function based on recent Mod thread

Kevin Fishburne kevinfishburne at ...1887...
Sat Oct 12 23:54:12 CEST 2013


On 10/11/2013 08:20 AM, Jussi Lahtinen wrote:
> My brains jammed to think about that wrap function, and I think if you want
> function that wraps screen like in old video
> games, then is that C implementation really correct?
>
> They say that Wrap(-1, 1, 4) should return 3, but if you have traveled two
> steps over border of the screen (1 -> 0, 0 -> -1),
> then you should come up two steps from other border (4 -> 3, 3 -> 2).
> So Wrap(-1,
> 1, 4) should be 2.
>
> C implementation is only for integers, but if you also need to use floats
> then,
> Wrap(0.5, 1, 4) should be 3.5, and Wrap(4.5, 1, 4) should be 1.5.
>
> Because if Wrap(0, 1, 4) = 4, then what would be Wrap(0.5, 1, 4) and Wrap(-0.5,
> 1, 4)?
> They cannot both be 3.5!!
>
> C implementation connects borders with one step between them, my
> implementation connects the borders
> with zero steps. So that Wrap(0.999, 1, 4) = 3.999, Wrap(4.001, 1, 4) =
> 1.001, Wrap(1,1,4) = 1 and Wrap(4,1,4)=4.
>
> So I think this gives correct answers:
>
> Private Function MyWrap(fX As Float, fLowerBound As Float, fUpperBound As
> Float) As Float
>
>    Dim fRange As Float = fUpperBound - fLowerBound
>
>    If fX < fLowerBound Then
>    Return fUpperBound - Abs(fmod((fX - fLowerBound), fRange))
>    Else If fX > fUpperBound Then
>    Return fmod(fX - fLowerBound, fRange) + fLowerBound
>    Else
>    Return fX
>    Endif
>
> End
>
>
> It needs declaration of fmod:
> Private Extern fmod(fNumber As Float, fDenom As Float) As Float In "libm:6"
>
>
> Jussi

Thou art a genius. It works brilliantly. Here's my final code:

---

Public Extern fmod(fNumber As Float, fDenom As Float) As Float In "libm:6"

Public Function Wrap_Single(Minimum As Single, Maximum As Single, Value 
As Single) As Single

   ' Constrain value to specified range.

   ' General declarations.
   Dim Spread As Single  ' Range between minimum and maximum values.

   ' Calculate and return wrapped value.
   If Value < Minimum Then
     Spread = Maximum - Minimum
     Return Maximum - Abs(fmod((Value - Minimum), Spread))
   Else If Value > Maximum Then
     Spread = Maximum - Minimum
     Return fmod(Value - Minimum, Spread) + Minimum
   Else
     Return Value
   Endif

End

---

Thanks for the help. I've been on an code efficiency binge lately and 
this helps a lot.

-- 
Kevin Fishburne
Eight Virtues
www: http://sales.eightvirtues.com
e-mail: sales at ...1887...
phone: (770) 853-6271





More information about the User mailing list