Guest User

raycast

a guest
Mar 23rd, 2026
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. static const s32 w = SCREEN_WIDTH;
  2. static const s32 h = SCREEN_HEIGHT;
  3.  
  4. static f32 pos_x;
  5. static f32 pos_y;
  6.  
  7. static f32 dir_x;
  8. static f32 dir_y;
  9.  
  10. static f32 plane_x;
  11. static f32 plane_y;
  12.  
  13. void
  14. raycast_draw_walls(void)
  15. {
  16. const u8 max_steps = 32;
  17.  
  18. for (s32 x = 0; x < w; x++) {
  19. u8 map_x = pos_x;
  20. u8 map_y = pos_y;
  21.  
  22. // x-coordinate in camera space
  23. f32 cam_x = (f32)x / w * 2 - 1;
  24.  
  25. f32 ray_dir_x = dir_x + plane_x * cam_x;
  26. f32 ray_dir_y = dir_y + plane_y * cam_x;
  27.  
  28. f32 delta_x = ABS(1 / ray_dir_x);
  29. f32 delta_y = ABS(1 / ray_dir_y);
  30.  
  31. s8 step_x = SIGN(ray_dir_x);
  32. s8 step_y = SIGN(ray_dir_y);
  33.  
  34. // distance from starting pos to first grid intersection
  35. f32 dist_x = step_x < 0 ?
  36. delta_x * (pos_x - map_x) :
  37. delta_x * (map_x - pos_x + 1);
  38. f32 dist_y = step_y < 0 ?
  39. delta_y * (pos_y - map_y) :
  40. delta_y * (map_y - pos_y + 1);
  41.  
  42. BOOL side;
  43. u8 tile;
  44. u8 steps = 0;
  45.  
  46. while (1) {
  47. if (++steps > max_steps)
  48. goto next_ray;
  49.  
  50. if (dist_x < dist_y) {
  51. dist_x += delta_x;
  52. map_x += step_x;
  53. side = 0;
  54. } else {
  55. dist_y += delta_y;
  56. map_y += step_y;
  57. side = 1;
  58. }
  59.  
  60. tile = map_at(map_x, map_y, MAP_WALL);
  61. if (tile)
  62. break;
  63. }
  64.  
  65. f32 dist = side ?
  66. (dist_y - delta_y) :
  67. (dist_x - delta_x);
  68.  
  69. s32 line_h = h / dist;
  70.  
  71. s32 y0 = (h - line_h) / 2;
  72. s32 y1 = (h + line_h) / 2;
  73.  
  74. f32 wall_x = side ?
  75. pos_x + dist * ray_dir_x :
  76. pos_y + dist * ray_dir_y;
  77. wall_x -= (s32)wall_x;
  78.  
  79. s32 tex_x = wall_x * 64;
  80. if (side == 0 && ray_dir_x > 0) tex_x = 64 - tex_x - 1;
  81. if (side == 1 && ray_dir_y < 0) tex_x = 64 - tex_x - 1;
  82.  
  83. tex_x += (tile - 1) * 64;
  84.  
  85. f32 tex_step = 64.0 / line_h;
  86. f32 tex_pos = 0;
  87.  
  88. s32 tex_y = 0;
  89.  
  90. for (s32 y = y0; y < y1; y++) {
  91. tex_pos += tex_step;
  92.  
  93. if (y < 0 || y >= h)
  94. continue;
  95.  
  96. u32 col = PIXEL(g_bitmaps[BITMAP_TILES], tex_x, tex_y);
  97.  
  98. tex_y = roundf(tex_pos);
  99.  
  100. if (side)
  101. col = (col >> 1) & 0x7F7F7F;
  102.  
  103. col = video_blend_color(col, 0, (f32)steps / max_steps);
  104.  
  105. PIXEL(g_screen, x, y) = col;
  106. }
  107.  
  108. next_ray:
  109. }
  110. }
Advertisement
Add Comment
Please, Sign In to add comment