Skip to content

Commit b165871

Browse files
committed
[Maintenance] [th01] graph_r_line(): Make slope calculations more explicit
The previous macros suggested optimizations that could easily lead to crashes. Part of P0197, funded by Yanga and Ember2528.
1 parent b4033b5 commit b165871

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

th01/hardware/graph.cpp

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -519,24 +519,22 @@ void graph_r_line(
519519
vram_y_t y_vram;
520520
dots16_t pixels;
521521

522-
#define slope_x ((bottom - top) / (right - left))
523-
#define slope_y ((right - left) / (bottom - top))
524522
#define lerp(m, x) static_cast<int>(m * static_cast<float>(x))
525523

526-
#define clip_lerp_min(low, high, lerp_point, slope, minimum) \
524+
#define clip_lerp_min(low, high, lerp_point, slope_dividend, minimum) \
527525
if(low < minimum) { \
528526
if(high < minimum) { \
529527
return; \
530528
} \
531-
lerp_point += lerp(slope, (minimum - low)); \
529+
lerp_point += lerp((slope_dividend / (high - low)), (minimum - low)); \
532530
low = minimum; \
533531
}
534-
#define clip_lerp_max(low, high, lerp_point, slope, maximum) \
532+
#define clip_lerp_max(low, high, lerp_point, slope_dividend, maximum) \
535533
if(high > maximum) { \
536534
if(low > maximum) { \
537535
return; \
538536
} \
539-
lerp_point -= lerp(slope, (high - maximum)); \
537+
lerp_point -= lerp((slope_dividend / (high - low)), (high - maximum)); \
540538
high = maximum; \
541539
}
542540

@@ -596,10 +594,14 @@ void graph_r_line(
596594
bottom = order_tmp;
597595
}
598596

599-
clip_lerp_min(left, right, top, slope_x, 0);
600-
clip_lerp_max(left, right, bottom, slope_x, (RES_X - 1));
601-
clip_lerp_min(top, bottom, left, slope_y, 0);
602-
clip_lerp_max(top, bottom, right, slope_y, (RES_Y - 1));
597+
clip_lerp_min(left, right, top, (bottom - top), 0);
598+
clip_lerp_max(left, right, bottom, (bottom - top), (RES_X - 1));
599+
clip_lerp_min(top, bottom, left, (right - left), 0);
600+
clip_lerp_max(top, bottom, right, (right - left), (RES_Y - 1));
601+
602+
// This division is safe at this point.
603+
#define slope_y ((right - left) / (bottom - top))
604+
603605
if(bottom < 0) {
604606
right += lerp(slope_y, 0 - bottom);
605607
bottom = 0;
@@ -639,7 +641,7 @@ void graph_r_line(
639641
#undef unput32_at
640642
#undef clip_lerp_min
641643
#undef clip_lerp_max
642-
#undef slope
644+
#undef slope_x
643645
}
644646
/// -----------------------
645647

0 commit comments

Comments
 (0)