Advertisement
matrefeytontias

n2DLib rotosprite implementation

Apr 24th, 2016
396
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.85 KB | None | 0 0
  1. void rotate(int x, int y, int cx, int cy, Fixed angle, Rect *out)
  2. {
  3.     x -= cx;
  4.     y -= cy;
  5.     out->x = fixtoi(fixmul(itofix(x), fixcos(angle)) + fixmul(itofix(y), fixsin(angle))) + cx;
  6.     out->y = fixtoi(fixmul(itofix(x), -fixsin(angle)) + fixmul(itofix(y), fixcos(angle))) + cy;
  7. }
  8.  
  9. void getBoundingBox(int x, int y, int w, int h, int cx, int cy, Fixed angle, Rect *out)
  10. {
  11.     Rect tl, tr, bl, br;
  12.     rotate(x, y, cx, cy, angle, &tl);
  13.     rotate(x + w, y, cx, cy, angle, &tr);
  14.     rotate(x, y + h, cx, cy, angle, &bl);
  15.     rotate(x + w, y + h, cx, cy, angle, &br);
  16.     out->x = min(min(min(tl.x, tr.x), bl.x), br.x);
  17.     out->y = min(min(min(tl.y, tr.y), bl.y), br.y);
  18.     out->w = max(max(max(tl.x, tr.x), bl.x), br.x) - out->x;
  19.     out->h = max(max(max(tl.y, tr.y), bl.y), br.y) - out->y;
  20. }
  21.  
  22. void drawSpriteRotated(const unsigned short* source, const Rect* sr, const Rect* rc, Fixed angle, int flash, unsigned short flashColor)
  23. {
  24.     Rect defaultRect = { source[0] / 2, source[1] / 2, 0, 0 };
  25.     Rect fr;
  26.     unsigned short currentPixel;
  27.     Fixed dX = fixcos(angle), dY = fixsin(angle);
  28.    
  29.     if(rc == NULL)
  30.         rc = &defaultRect;
  31.    
  32.     getBoundingBox(-rc->x, -rc->y, source[0], source[1], 0, 0, angle, &fr);
  33.     fr.x += sr->x;
  34.     fr.y += sr->y;
  35.     fr.w += fr.x;
  36.     fr.h += fr.y;
  37.    
  38.     Rect cp, lsp, cdrp;
  39.    
  40.     // Feed fixed-point to get fixed-point
  41.     rotate(itofix(fr.x - sr->x), itofix(fr.y - sr->y), 0, 0, -angle, &lsp);
  42.    
  43.     for(cp.y = fr.y; cp.y <= fr.h; cp.y++)
  44.     {
  45.         cdrp.x = lsp.x;
  46.         cdrp.y = lsp.y;
  47.        
  48.         for(cp.x = fr.x; cp.x <= fr.w; cp.x++)
  49.         {
  50.             if(cp.x >= 0 && cp.x < 320 && cp.y >= 0 && cp.y < 240)
  51.             {
  52.                 currentPixel = getPixel(source, fixtoi(cdrp.x) + rc->x, fixtoi(cdrp.y) + rc->y);
  53.                 if(currentPixel != source[2])
  54.                 {
  55.                     setPixelUnsafe(cp.x, cp.y, flash ? flashColor : currentPixel);
  56.                 }
  57.             }
  58.             cdrp.x += dX;
  59.             cdrp.y += dY;
  60.         }
  61.        
  62.         lsp.x -= dY;
  63.         lsp.y += dX;
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement