GLBasic forum

Main forum => GLBasic - en => Topic started by: quangdx on 2011-Aug-25

Title: fast sorting paint algorithm. help.
Post by: quangdx on 2011-Aug-25
As anyone have any ideas on how I can quickly draw squares of different sizes and positions on screen,
the largest first to the smallest, so the smallest are always visible infront of the largest.
The squares positions and sizes change over time.

Currently I store the three variables, SquareXpos, SquareYpos, SquareSize, for each square.
The size of the squares are only ever gonna be a multiple of 8 from 16 to 80.
So I check all the squares to see if they're size 80 and draw those,
then the ones that at are size 72, then 64 etc.

I appreciate this is not the fastest way of doing it, hence I'm asking for any suggestions.
many thanks.
Title: Re: fast sorting paint algorithm. help.
Post by: Kitty Hello on 2011-Aug-25
Code (glbasic) Select

TYPE Tthing
width // make members in the order you want them sorted
z
ENDTYPE

LOCAL things[] as Tthing

FOR i=0 TO 10
    LOCAL t AS Tthing
    t.width=RND(1223)
    t.z=RND(123)
    DIMPUSH things[], t
NEXT

SORTARRAY things[]


Title: Re: fast sorting paint algorithm. help.
Post by: quangdx on 2011-Aug-25
Thank you very much, this is a great solution.
Simple and elegant.

I need to get into using TYPE and dynamic arrays a lot more.
Title: Re: fast sorting paint algorithm. help.
Post by: doimus on 2011-Aug-25
Neat trick when sorting types is to have "utility" field as first in type, and then just change its value for whatever sorting value is needed.

Code (glbasic) Select

TYPE TType
  sortvalue
  width
  height
  whatever
ENDTYPE

FUNCTION SortByWhatever: thing[] as TType

  FOREACH n in thing[]
     n.sortvalue = n.whatever
  NEXT

  SORTARRAY thing[]

ENDFUNCTION
Title: Re: fast sorting paint algorithm. help.
Post by: Slydog on 2011-Aug-25
@doimus - Brilliant! :good:

I've never done sorting in GLB before, and was wondering what Gernot's code was doing with the SORTARRAY command. 
How did it know how to sort a custom type?   :blink:

Well, your code explains that!  It uses the first member variable.
Title: Re: fast sorting paint algorithm. help.
Post by: Kitty Hello on 2011-Aug-25
No. Read the manual. It uses the first member. If it's equal, it uses the 2nd. Equal? 3rd...

You can write custom compare functions, too.
Title: Re: fast sorting paint algorithm. help.
Post by: Slydog on 2011-Aug-25
That's even better! 
Although I can't see any need for a sorting routine for my game yet, but will keep it in mind.
(I better double check if I do use sorting - I would usually just do my sorting by hand using a bubble-sort algo!)
Title: Re: fast sorting paint algorithm. help.
Post by: Kitty Hello on 2011-Aug-25
SORTARRAY uses qsort.