ogl_beamforming

Ultrasound Beamforming Implemented with OpenGL
git clone anongit@rnpnr.xyz:ogl_beamforming.git
Log | Files | Refs | Feed | Submodules | README | LICENSE

ui.c (141380B)


      1 /* See LICENSE for license details. */
      2 /* TODO(rnp):
      3  * [ ]: bug: draw_view_ruler() needs to use a ray intersection instead of clamping
      4  * [ ]: bug: plane rotation and offset position only work if plane is Z aligned
      5  * [ ]: refactor: ui and views need to store current uv coordinates for expected transform
      6  * [ ]: refactor: there shouldn't need to be if 1d checks all over
      7  * [ ]: refactor: ui kind of needs to be mostly thrown away
      8  *      - want all drawing to be immediate mode
      9  *      - only layout information should be retained
     10  *        - leaf nodes of layout have a kind associated which
     11  *          instructs the builder code on how to build the view
     12  *      - ui items (currently called Variables) are stored in a hash
     13  *        table and are looked up for state information at frame building time
     14  *        - removed/recycled when last building frame index is less than drawing frame index
     15  *      - building:
     16  *        - loop over tiled layout tree and floating layout tree as is currently done
     17  *          - this will build current frame ui draw tree
     18  *        - for each view use a stack structure with grouping, similar to how tables are made
     19  *          - more general though: sub groups contain a draw axis (x or y)
     20  *        - each ui item gets looked up in the hash table for previous frame drawing info
     21  *          - this can then be used to construct a "ui comm" which contains relevant info
     22  *            about how that ui item is being interacted with
     23  *      - drawing:
     24  *        - must be separated into layout constraint solving and rendering
     25  *        - layout constraint solving handles sizing, clipping, etc.
     26  *          - this will need multiple passes per subgroup to allow for autosizing
     27  *          - pay attention to the fixed size points in the hierarchy. fixed size
     28  *            items are complete once their children are complete.
     29  *        - rendering simply uses the rect/clipping regions produced by layout
     30  *          to send draw commands
     31  * [ ]: bug: resizing live view causes texture to jump around
     32  * [ ]: bug: group at end of parameter listing
     33  * [ ]: refactor: ui should be in its own thread and that thread should only be concerned with the ui
     34  * [ ]: refactor: remove all the excessive measure_texts (cell drawing, hover_interaction in params table)
     35  * [ ]: refactor: move remaining fragment shader stuff into ui
     36  * [ ]: refactor: scale table to rect
     37  * [ ]: scroll bar for views that don't have enough space
     38  * [ ]: allow views to collapse to just their title bar
     39  *      - title bar struct with expanded. Check when pushing onto draw stack; if expanded
     40  *        do normal behaviour else make size title bar size and ignore the splits fraction.
     41  * [ ]: enforce a minimum region size or allow regions themselves to scroll
     42  * [ ]: refactor: add_variable_no_link()
     43  * [ ]: refactor: draw_text_limited should clamp to rect and measure text itself
     44  * [ ]: draw the ui with a post-order traversal instead of pre-order traversal
     45  * [ ]: consider V_HOVER_GROUP and use that to implement submenus
     46  * [ ]: menu's need to support nested groups
     47  * [ ]: don't redraw on every refresh; instead redraw on mouse movement/event or when a new frame
     48  *      arrives. For animations the ui can have a list of "timers" which while active will
     49  *      do a redraw on every refresh until completed.
     50  * [ ]: show full non-truncated string on hover
     51  * [ ]: refactor: hovered element type and show hovered element in full even when truncated
     52  * [ ]: bug: cross-plane view with different dimensions for each plane
     53  * [ ]: refactor: make table_skip_rows useful
     54  * [ ]: refactor: better method of grouping variables for views such as FrameView/ComputeStatsView
     55  */
     56 
     57 #include "assets/generated/assets.c"
     58 
     59 #define BG_COLOUR              (v4){{0.15f, 0.12f, 0.13f, 1.0f}}
     60 #define FG_COLOUR              (v4){{0.92f, 0.88f, 0.78f, 1.0f}}
     61 #define FOCUSED_COLOUR         (v4){{0.86f, 0.28f, 0.21f, 1.0f}}
     62 #define HOVERED_COLOUR         (v4){{0.11f, 0.50f, 0.59f, 1.0f}}
     63 #define RULER_COLOUR           (v4){{1.00f, 0.70f, 0.00f, 1.0f}}
     64 #define BORDER_COLOUR          v4_lerp(FG_COLOUR, BG_COLOUR, 0.85f)
     65 
     66 #define MENU_PLUS_COLOUR       (v4){{0.33f, 0.42f, 1.00f, 1.00f}}
     67 #define MENU_CLOSE_COLOUR      FOCUSED_COLOUR
     68 
     69 read_only global v4 g_colour_palette[] = {
     70 	{{0.32f, 0.20f, 0.50f, 1.00f}},
     71 	{{0.14f, 0.39f, 0.61f, 1.00f}},
     72 	{{0.61f, 0.14f, 0.25f, 1.00f}},
     73 	{{0.20f, 0.60f, 0.24f, 1.00f}},
     74 	{{0.80f, 0.60f, 0.20f, 1.00f}},
     75 	{{0.15f, 0.51f, 0.74f, 1.00f}},
     76 };
     77 
     78 #define HOVER_SPEED            5.0f
     79 #define BLINK_SPEED            1.5f
     80 
     81 #define TABLE_CELL_PAD_HEIGHT  2.0f
     82 #define TABLE_CELL_PAD_WIDTH   8.0f
     83 
     84 #define RULER_TEXT_PAD         10.0f
     85 #define RULER_TICK_LENGTH      20.0f
     86 
     87 #define UI_SPLIT_HANDLE_THICK  8.0f
     88 #define UI_REGION_PAD          32.0f
     89 
     90 /* TODO(rnp) smooth scroll */
     91 #define UI_SCROLL_SPEED 12.0f
     92 
     93 #define LISTING_LINE_PAD    6.0f
     94 #define TITLE_BAR_PAD       6.0f
     95 
     96 typedef struct v2_sll {
     97 	struct v2_sll *next;
     98 	v2             v;
     99 } v2_sll;
    100 
    101 typedef struct {
    102 	f32 t;
    103 	f32 scale;
    104 } UIBlinker;
    105 
    106 typedef struct BeamformerUI BeamformerUI;
    107 typedef struct Variable     Variable;
    108 
    109 typedef struct {
    110 	u8   buf[128];
    111 	i32  count;
    112 	i32  cursor;
    113 	b32  numeric;
    114 	UIBlinker cursor_blink;
    115 	Font *font, *hot_font;
    116 	Variable *container;
    117 } InputState;
    118 
    119 typedef enum {
    120 	RulerState_None,
    121 	RulerState_Start,
    122 	RulerState_Hold,
    123 } RulerState;
    124 
    125 typedef struct {
    126 	v3 start;
    127 	v3 end;
    128 	RulerState state;
    129 } Ruler;
    130 
    131 typedef enum {
    132 	SB_LATERAL,
    133 	SB_AXIAL,
    134 } ScaleBarDirection;
    135 
    136 typedef struct {
    137 	f32    *min_value, *max_value;
    138 	v2_sll *savepoint_stack;
    139 	v2      scroll_scale;
    140 	f32     zoom_starting_coord;
    141 	ScaleBarDirection direction;
    142 } ScaleBar;
    143 
    144 typedef struct { f32 val, scale; } scaled_f32;
    145 
    146 typedef enum {
    147 	RSD_VERTICAL,
    148 	RSD_HORIZONTAL,
    149 } RegionSplitDirection;
    150 
    151 typedef struct {
    152 	Variable *left;
    153 	Variable *right;
    154 	f32       fraction;
    155 	RegionSplitDirection direction;
    156 } RegionSplit;
    157 
    158 #define COMPUTE_STATS_VIEW_LIST \
    159 	X(Average, "Average") \
    160 	X(Bar,     "Bar")
    161 
    162 #define X(kind, ...) ComputeStatsViewKind_ ##kind,
    163 typedef enum {COMPUTE_STATS_VIEW_LIST ComputeStatsViewKind_Count} ComputeStatsViewKind;
    164 #undef X
    165 
    166 typedef struct {
    167 	ComputeShaderStats *compute_shader_stats;
    168 	Variable           *cycler;
    169 	ComputeStatsViewKind kind;
    170 	UIBlinker blink;
    171 } ComputeStatsView;
    172 
    173 typedef struct {
    174 	b32 *processing;
    175 	f32 *progress;
    176 	f32 display_t;
    177 	f32 display_t_velocity;
    178 } ComputeProgressBar;
    179 
    180 typedef enum {
    181 	VT_NULL,
    182 	VT_B32,
    183 	VT_F32,
    184 	VT_I32,
    185 	VT_U32,
    186 	VT_GROUP,
    187 	VT_CYCLER,
    188 	VT_SCALED_F32,
    189 	VT_BEAMFORMER_VARIABLE,
    190 	VT_BEAMFORMER_FRAME_VIEW,
    191 	VT_COMPUTE_STATS_VIEW,
    192 	VT_COMPUTE_PROGRESS_BAR,
    193 	VT_LIVE_CONTROLS_VIEW,
    194 	VT_LIVE_CONTROLS_STRING,
    195 	VT_SCALE_BAR,
    196 	VT_UI_BUTTON,
    197 	VT_UI_MENU,
    198 	VT_UI_REGION_SPLIT,
    199 	VT_UI_TEXT_BOX,
    200 	VT_UI_VIEW,
    201 	VT_X_PLANE_SHIFT,
    202 } VariableType;
    203 
    204 typedef enum {
    205 	VariableGroupKind_List,
    206 	/* NOTE(rnp): special group for vectors with components
    207 	 * stored in separate memory locations */
    208 	VariableGroupKind_Vector,
    209 } VariableGroupKind;
    210 
    211 typedef struct {
    212 	VariableGroupKind kind;
    213 	b32       expanded;
    214 	Variable *first;
    215 	Variable *last;
    216 	Variable *container;
    217 } VariableGroup;
    218 
    219 typedef enum {
    220 	UIViewFlag_CustomText = 1 << 0,
    221 	UIViewFlag_Floating   = 1 << 1,
    222 } UIViewFlags;
    223 
    224 typedef struct {
    225 	Variable *child;
    226 	Variable *close;
    227 	Variable *menu;
    228 	Rect      rect;
    229 	UIViewFlags flags;
    230 } UIView;
    231 
    232 /* X(id, text) */
    233 #define FRAME_VIEW_BUTTONS \
    234 	X(FV_COPY_HORIZONTAL, "Copy Horizontal") \
    235 	X(FV_COPY_VERTICAL,   "Copy Vertical")
    236 
    237 #define GLOBAL_MENU_BUTTONS \
    238 	X(GM_OPEN_VIEW_RIGHT,   "Open View Right") \
    239 	X(GM_OPEN_VIEW_BELOW,   "Open View Below")
    240 
    241 #define X(id, text) UI_BID_ ##id,
    242 typedef enum {
    243 	UI_BID_VIEW_CLOSE,
    244 	GLOBAL_MENU_BUTTONS
    245 	FRAME_VIEW_BUTTONS
    246 } UIButtonID;
    247 #undef X
    248 
    249 typedef struct {
    250 	s8  *labels;
    251 	u32 *state;
    252 	u32  cycle_length;
    253 } VariableCycler;
    254 
    255 typedef struct {
    256 	s8  suffix;
    257 	f32 display_scale;
    258 	f32 scroll_scale;
    259 	v2  limits;
    260 	f32 *store;
    261 } BeamformerVariable;
    262 
    263 typedef struct {
    264 	v3 start_point;
    265 	v3 end_point;
    266 } XPlaneShift;
    267 
    268 typedef enum {
    269 	V_INPUT          = 1 << 0,
    270 	V_TEXT           = 1 << 1,
    271 	V_RADIO_BUTTON   = 1 << 2,
    272 	V_EXTRA_ACTION   = 1 << 3,
    273 	V_HIDES_CURSOR   = 1 << 4,
    274 	V_LIVE_CONTROL   = 1 << 28,
    275 	V_CAUSES_COMPUTE = 1 << 29,
    276 	V_UPDATE_VIEW    = 1 << 30,
    277 } VariableFlags;
    278 
    279 struct Variable {
    280 	s8 name;
    281 	union {
    282 		void               *generic;
    283 		BeamformerVariable  beamformer_variable;
    284 		ComputeProgressBar  compute_progress_bar;
    285 		ComputeStatsView    compute_stats_view;
    286 		RegionSplit         region_split;
    287 		ScaleBar            scale_bar;
    288 		UIButtonID          button;
    289 		UIView              view;
    290 		VariableCycler      cycler;
    291 		VariableGroup       group;
    292 		XPlaneShift         x_plane_shift;
    293 		scaled_f32          scaled_real32;
    294 		b32                 bool32;
    295 		i32                 signed32;
    296 		u32                 unsigned32;
    297 		f32                 real32;
    298 	};
    299 	Variable *next;
    300 	Variable *parent;
    301 	VariableFlags flags;
    302 	VariableType  type;
    303 
    304 	f32 hover_t;
    305 	f32 name_width;
    306 };
    307 
    308 #define BEAMFORMER_FRAME_VIEW_KIND_LIST \
    309 	X(Latest,   "Latest")     \
    310 	X(3DXPlane, "3D X-Plane") \
    311 	X(Indexed,  "Indexed")    \
    312 	X(Copy,     "Copy")
    313 
    314 typedef enum {
    315 	#define X(kind, ...) BeamformerFrameViewKind_##kind,
    316 	BEAMFORMER_FRAME_VIEW_KIND_LIST
    317 	#undef X
    318 	BeamformerFrameViewKind_Count,
    319 } BeamformerFrameViewKind;
    320 
    321 typedef struct BeamformerFrameView BeamformerFrameView;
    322 struct BeamformerFrameView {
    323 	BeamformerFrameViewKind kind;
    324 	b32 dirty;
    325 	BeamformerFrame     *frame;
    326 	BeamformerFrameView *prev, *next;
    327 
    328 	u32 texture;
    329 	i32 texture_mipmaps;
    330 	iv2 texture_dim;
    331 
    332 	/* NOTE(rnp): any pointers to variables are added to the menu and will
    333 	 * be put onto the freelist if the view is closed. */
    334 
    335 	Variable *kind_cycler;
    336 	Variable *log_scale;
    337 	Variable threshold;
    338 	Variable dynamic_range;
    339 	Variable gamma;
    340 
    341 	union {
    342 		/* BeamformerFrameViewKind_Latest/BeamformerFrameViewKind_Indexed */
    343 		struct {
    344 			Variable lateral_scale_bar;
    345 			Variable axial_scale_bar;
    346 			Variable *lateral_scale_bar_active;
    347 			Variable *axial_scale_bar_active;
    348 			/* NOTE(rnp): if kind is Latest  selects which plane to use
    349 			 *            if kind is Indexed selects the index */
    350 			Variable *cycler;
    351 			u32 cycler_state;
    352 
    353 			Ruler ruler;
    354 
    355 			v3 min_coordinate;
    356 			v3 max_coordinate;
    357 		};
    358 
    359 		/* BeamformerFrameViewKind_3DXPlane */
    360 		struct {
    361 			Variable x_plane_shifts[2];
    362 			Variable *demo;
    363 			f32 rotation;
    364 			v3  hit_test_point;
    365 		};
    366 	};
    367 };
    368 
    369 typedef struct BeamformerLiveControlsView BeamformerLiveControlsView;
    370 struct BeamformerLiveControlsView {
    371 	Variable transmit_power;
    372 	Variable tgc_control_points[countof(((BeamformerLiveImagingParameters *)0)->tgc_control_points)];
    373 	Variable save_button;
    374 	Variable stop_button;
    375 	Variable save_text;
    376 	UIBlinker save_button_blink;
    377 	u32      hot_field_flag;
    378 	u32      active_field_flag;
    379 };
    380 
    381 typedef enum {
    382 	InteractionKind_None,
    383 	InteractionKind_Nop,
    384 	InteractionKind_Auto,
    385 	InteractionKind_Button,
    386 	InteractionKind_Drag,
    387 	InteractionKind_Menu,
    388 	InteractionKind_Ruler,
    389 	InteractionKind_Scroll,
    390 	InteractionKind_Set,
    391 	InteractionKind_Text,
    392 } InteractionKind;
    393 
    394 typedef struct {
    395 	InteractionKind kind;
    396 	union {
    397 		void     *generic;
    398 		Variable *var;
    399 	};
    400 	Rect rect;
    401 } Interaction;
    402 
    403 #define auto_interaction(r, v) (Interaction){.kind = InteractionKind_Auto, .var = v, .rect = r}
    404 
    405 struct BeamformerUI {
    406 	Arena arena;
    407 
    408 	Font font;
    409 	Font small_font;
    410 
    411 	Variable *regions;
    412 	Variable *variable_freelist;
    413 
    414 	Variable floating_widget_sentinal;
    415 
    416 	BeamformerFrameView *views;
    417 	BeamformerFrameView *view_freelist;
    418 	BeamformerFrame     *frame_freelist;
    419 
    420 	Interaction interaction;
    421 	Interaction hot_interaction;
    422 	Interaction next_interaction;
    423 
    424 	InputState  text_input_state;
    425 
    426 	/* TODO(rnp): ideally this isn't copied all over the place */
    427 	BeamformerRenderModel unit_cube_model;
    428 
    429 	v2_sll *scale_bar_savepoint_freelist;
    430 
    431 	BeamformerFrame *latest_plane[BeamformerViewPlaneTag_Count + 1];
    432 
    433 	BeamformerUIParameters params;
    434 	b32                    flush_params;
    435 	u32 selected_parameter_block;
    436 
    437 	m4  das_transform;
    438 	v3  min_coordinate;
    439 	v3  max_coordinate;
    440 	f32 off_axis_position;
    441 	f32 beamform_plane;
    442 
    443 	FrameViewRenderContext *frame_view_render_context;
    444 
    445 	BeamformerSharedMemory * shared_memory;
    446 	BeamformerCtx *          beamformer_context;
    447 };
    448 
    449 typedef enum {
    450 	TF_NONE     = 0,
    451 	TF_ROTATED  = 1 << 0,
    452 	TF_LIMITED  = 1 << 1,
    453 	TF_OUTLINED = 1 << 2,
    454 } TextFlags;
    455 
    456 typedef enum {
    457 	TextAlignment_Center,
    458 	TextAlignment_Left,
    459 	TextAlignment_Right,
    460 } TextAlignment;
    461 
    462 typedef struct {
    463 	Font  *font;
    464 	Rect  limits;
    465 	v4    colour;
    466 	v4    outline_colour;
    467 	f32   outline_thick;
    468 	f32   rotation;
    469 	TextAlignment align;
    470 	TextFlags     flags;
    471 } TextSpec;
    472 
    473 typedef enum {
    474 	TRK_CELLS,
    475 	TRK_TABLE,
    476 } TableRowKind;
    477 
    478 typedef enum {
    479 	TableCellKind_None,
    480 	TableCellKind_Variable,
    481 	TableCellKind_VariableGroup,
    482 } TableCellKind;
    483 
    484 typedef struct {
    485 	s8 text;
    486 	union {
    487 		i64       integer;
    488 		Variable *var;
    489 		void     *generic;
    490 	};
    491 	TableCellKind kind;
    492 	f32 width;
    493 } TableCell;
    494 
    495 typedef struct {
    496 	void         *data;
    497 	TableRowKind  kind;
    498 } TableRow;
    499 
    500 typedef struct Table {
    501 	TableRow *data;
    502 	iz        count;
    503 	iz        capacity;
    504 
    505 	/* NOTE(rnp): counted by columns */
    506 	TextAlignment *alignment;
    507 	f32           *widths;
    508 
    509 	v4  border_colour;
    510 	f32 column_border_thick;
    511 	f32 row_border_thick;
    512 	v2  size;
    513 	v2  cell_pad;
    514 
    515 	/* NOTE(rnp): row count including nested tables */
    516 	i32 rows;
    517 	i32 columns;
    518 
    519 	struct Table *parent;
    520 } Table;
    521 
    522 typedef struct {
    523 	Table *table;
    524 	i32    row_index;
    525 } TableStackFrame;
    526 
    527 typedef struct {
    528 	TableStackFrame *data;
    529 	iz count;
    530 	iz capacity;
    531 } TableStack;
    532 
    533 typedef enum {
    534 	TIK_ROWS,
    535 	TIK_CELLS,
    536 } TableIteratorKind;
    537 
    538 typedef struct {
    539 	TableStack      stack;
    540 	TableStackFrame frame;
    541 
    542 	TableRow *row;
    543 	i16       column;
    544 	i16       sub_table_depth;
    545 
    546 	TableIteratorKind kind;
    547 
    548 	f32           start_x;
    549 	TextAlignment alignment;
    550 	Rect          cell_rect;
    551 } TableIterator;
    552 
    553 function Vector2
    554 rl_v2(v2 a)
    555 {
    556 	Vector2 result = {a.x, a.y};
    557 	return result;
    558 }
    559 
    560 function Rectangle
    561 rl_rect(Rect a)
    562 {
    563 	Rectangle result = {a.pos.x, a.pos.y, a.size.w, a.size.h};
    564 	return result;
    565 }
    566 
    567 function f32
    568 ui_blinker_update(UIBlinker *b, f32 scale)
    569 {
    570 	b->t += b->scale * dt_for_frame;
    571 	if (b->t >= 1.0f) b->scale = -scale;
    572 	if (b->t <= 0.0f) b->scale =  scale;
    573 	f32 result = b->t;
    574 	return result;
    575 }
    576 
    577 function v2
    578 measure_glyph(Font font, u32 glyph)
    579 {
    580 	assert(glyph >= 0x20);
    581 	v2 result = {.y = (f32)font.baseSize};
    582 	/* NOTE: assumes font glyphs are ordered ASCII */
    583 	result.x = (f32)font.glyphs[glyph - 0x20].advanceX;
    584 	if (result.x == 0)
    585 		result.x = (font.recs[glyph - 0x20].width + (f32)font.glyphs[glyph - 0x20].offsetX);
    586 	return result;
    587 }
    588 
    589 function v2
    590 measure_text(Font font, s8 text)
    591 {
    592 	v2 result = {.y = (f32)font.baseSize};
    593 	for (iz i = 0; i < text.len; i++)
    594 		result.x += measure_glyph(font, text.data[i]).x;
    595 	return result;
    596 }
    597 
    598 function s8
    599 clamp_text_to_width(Font font, s8 text, f32 limit)
    600 {
    601 	s8  result = text;
    602 	f32 width  = 0;
    603 	for (iz i = 0; i < text.len; i++) {
    604 		f32 next = measure_glyph(font, text.data[i]).w;
    605 		if (width + next > limit) {
    606 			result.len = i;
    607 			break;
    608 		}
    609 		width += next;
    610 	}
    611 	return result;
    612 }
    613 
    614 function v2
    615 align_text_in_rect(s8 text, Rect r, Font font)
    616 {
    617 	v2 size   = measure_text(font, text);
    618 	v2 pos    = v2_add(r.pos, v2_scale(v2_sub(r.size, size), 0.5));
    619 	v2 result = clamp_v2_rect(pos, r);
    620 	return result;
    621 }
    622 
    623 function Texture
    624 make_raylib_texture(BeamformerFrameView *v)
    625 {
    626 	Texture result;
    627 	result.id      = v->texture;
    628 	result.width   = v->texture_dim.w;
    629 	result.height  = v->texture_dim.h;
    630 	result.mipmaps = v->texture_mipmaps;
    631 	result.format  = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
    632 	return result;
    633 }
    634 
    635 function void
    636 stream_append_variable(Stream *s, Variable *var)
    637 {
    638 	switch (var->type) {
    639 	case VT_UI_BUTTON:
    640 	case VT_GROUP:{ stream_append_s8(s, var->name); }break;
    641 	case VT_F32:{   stream_append_f64(s, var->real32, 100); }break;
    642 	case VT_B32:{   stream_append_s8(s, var->bool32 ? s8("True") : s8("False")); }break;
    643 	case VT_SCALED_F32:{ stream_append_f64(s, var->scaled_real32.val, 100); }break;
    644 	case VT_BEAMFORMER_VARIABLE:{
    645 		BeamformerVariable *bv = &var->beamformer_variable;
    646 		stream_append_f64(s, *bv->store * bv->display_scale, 100);
    647 	}break;
    648 	case VT_CYCLER:{
    649 		u32 index = *var->cycler.state;
    650 		if (var->cycler.labels) stream_append_s8(s, var->cycler.labels[index]);
    651 		else                    stream_append_u64(s, index);
    652 	}break;
    653 	case VT_LIVE_CONTROLS_STRING:{
    654 		BeamformerLiveImagingParameters *lip = var->generic;
    655 		stream_append_s8(s, (s8){.data = (u8 *)lip->save_name_tag, .len = lip->save_name_tag_length});
    656 		if (lip->save_name_tag_length <= 0) stream_append_s8(s, s8("Tag..."));
    657 	}break;
    658 	InvalidDefaultCase;
    659 	}
    660 }
    661 
    662 function void
    663 stream_append_variable_group(Stream *s, Variable *var)
    664 {
    665 	switch (var->type) {
    666 	case VT_GROUP:{
    667 		switch (var->group.kind) {
    668 		case VariableGroupKind_Vector:{
    669 			Variable *v = var->group.first;
    670 			stream_append_s8(s, s8("{"));
    671 			while (v) {
    672 				stream_append_variable(s, v);
    673 				v = v->next;
    674 				if (v) stream_append_s8(s, s8(", "));
    675 			}
    676 			stream_append_s8(s, s8("}"));
    677 		}break;
    678 		InvalidDefaultCase;
    679 		}
    680 	}break;
    681 	InvalidDefaultCase;
    682 	}
    683 }
    684 
    685 function s8
    686 push_acquisition_kind(Stream *s, BeamformerAcquisitionKind kind, u32 transmit_count)
    687 {
    688 	s8 name             = beamformer_acquisition_kind_strings[kind];
    689 	b32 fixed_transmits = beamformer_acquisition_kind_has_fixed_transmits[kind];
    690 	if (kind >= BeamformerAcquisitionKind_Count || kind < 0) {
    691 		fixed_transmits = 0;
    692 		name            = s8("Invalid");
    693 	}
    694 
    695 	stream_append_s8(s, name);
    696 	if (!fixed_transmits) {
    697 		stream_append_byte(s, '-');
    698 		stream_append_u64(s, transmit_count);
    699 	}
    700 
    701 	return stream_to_s8(s);
    702 }
    703 
    704 function s8
    705 push_custom_view_title(Stream *s, Variable *var)
    706 {
    707 	switch (var->type) {
    708 	case VT_COMPUTE_STATS_VIEW:{
    709 		stream_append_s8(s, s8("Compute Stats: "));
    710 		stream_append_variable(s, var->compute_stats_view.cycler);
    711 	}break;
    712 	case VT_COMPUTE_PROGRESS_BAR:{
    713 		stream_append_s8(s, s8("Compute Progress: "));
    714 		stream_append_f64(s, 100 * *var->compute_progress_bar.progress, 100);
    715 		stream_append_byte(s, '%');
    716 	} break;
    717 	case VT_BEAMFORMER_FRAME_VIEW:{
    718 		BeamformerFrameView *bv = var->generic;
    719 		stream_append_s8(s, s8("Frame View"));
    720 		switch (bv->kind) {
    721 		case BeamformerFrameViewKind_Copy:{ stream_append_s8(s, s8(": Copy [")); }break;
    722 		case BeamformerFrameViewKind_Latest:{
    723 			#define X(plane, id, pretty) s8_comp(": " pretty " ["),
    724 			read_only local_persist s8 labels[BeamformerViewPlaneTag_Count + 1] = {
    725 				BEAMFORMER_VIEW_PLANE_TAG_LIST
    726 				s8_comp(": Live [")
    727 			};
    728 			#undef X
    729 			stream_append_s8(s, labels[*bv->cycler->cycler.state % (BeamformerViewPlaneTag_Count + 1)]);
    730 		}break;
    731 		case BeamformerFrameViewKind_Indexed:{
    732 			stream_append_s8(s, s8(": Index {"));
    733 			stream_append_u64(s, *bv->cycler->cycler.state % BeamformerMaxSavedFrames);
    734 			stream_append_s8(s, s8("} ["));
    735 		}break;
    736 		case BeamformerFrameViewKind_3DXPlane:{ stream_append_s8(s, s8(": 3D X-Plane")); }break;
    737 		InvalidDefaultCase;
    738 		}
    739 		if (bv->kind != BeamformerFrameViewKind_3DXPlane) {
    740 			stream_append_hex_u64(s, bv->frame? bv->frame->id : 0);
    741 			stream_append_byte(s, ']');
    742 		}
    743 	}break;
    744 	InvalidDefaultCase;
    745 	}
    746 	return stream_to_s8(s);
    747 }
    748 
    749 #define table_new(a, init, ...) table_new_(a, init, arg_list(TextAlignment, ##__VA_ARGS__))
    750 function Table *
    751 table_new_(Arena *a, i32 initial_capacity, TextAlignment *alignment, i32 columns)
    752 {
    753 	Table *result = push_struct(a, Table);
    754 	da_reserve(a, result, initial_capacity);
    755 	result->columns   = columns;
    756 	result->alignment = push_array(a, TextAlignment, columns);
    757 	result->widths    = push_array(a, f32, columns);
    758 	result->cell_pad  = (v2){{TABLE_CELL_PAD_WIDTH, TABLE_CELL_PAD_HEIGHT}};
    759 	mem_copy(result->alignment, alignment, sizeof(*alignment) * (u32)columns);
    760 	return result;
    761 }
    762 
    763 function i32
    764 table_skip_rows(Table *t, f32 draw_height, f32 text_height)
    765 {
    766 	i32 max_rows = (i32)(draw_height / (text_height + t->cell_pad.h));
    767 	i32 result   = t->rows - MIN(t->rows, max_rows);
    768 	return result;
    769 }
    770 
    771 function TableIterator *
    772 table_iterator_new(Table *table, TableIteratorKind kind, Arena *a, i32 starting_row, v2 at, Font *font)
    773 {
    774 	TableIterator *result    = push_struct(a, TableIterator);
    775 	result->kind             = kind;
    776 	result->frame.table      = table;
    777 	result->frame.row_index  = starting_row;
    778 	result->start_x          = at.x;
    779 	result->cell_rect.size.h = (f32)font->baseSize;
    780 	result->cell_rect.pos    = v2_add(at, v2_scale(table->cell_pad, 0.5f));
    781 	result->cell_rect.pos.y += (f32)(starting_row - 1) * (result->cell_rect.size.h + table->cell_pad.h + table->row_border_thick);
    782 	da_reserve(a, &result->stack, 4);
    783 	return result;
    784 }
    785 
    786 function void *
    787 table_iterator_next(TableIterator *it, Arena *a)
    788 {
    789 	void *result = 0;
    790 
    791 	if (!it->row || it->kind == TIK_ROWS) {
    792 		for (;;) {
    793 			TableRow *row = it->frame.table->data + it->frame.row_index++;
    794 			if (it->frame.row_index <= it->frame.table->count) {
    795 				if (row->kind == TRK_TABLE) {
    796 					*da_push(a, &it->stack) = it->frame;
    797 					it->frame = (TableStackFrame){.table = row->data};
    798 					it->sub_table_depth++;
    799 				} else {
    800 					result = row;
    801 					break;
    802 				}
    803 			} else if (it->stack.count) {
    804 				it->frame = it->stack.data[--it->stack.count];
    805 				it->sub_table_depth--;
    806 			} else {
    807 				break;
    808 			}
    809 		}
    810 		Table *t   = it->frame.table;
    811 		it->row    = result;
    812 		it->column = 0;
    813 		it->cell_rect.pos.x  = it->start_x + t->cell_pad.w / 2 +
    814 		                       it->cell_rect.size.h * it->sub_table_depth;
    815 		it->cell_rect.pos.y += it->cell_rect.size.h + t->row_border_thick + t->cell_pad.h;
    816 	}
    817 
    818 	if (it->row && it->kind == TIK_CELLS) {
    819 		Table *t   = it->frame.table;
    820 		i32 column = it->column++;
    821 		it->cell_rect.pos.x  += column > 0 ? it->cell_rect.size.w + t->cell_pad.w : 0;
    822 		it->cell_rect.size.w  = t->widths[column];
    823 		it->alignment         = t->alignment[column];
    824 		result                = (TableCell *)it->row->data + column;
    825 
    826 		if (it->column == t->columns)
    827 			it->row = 0;
    828 	}
    829 
    830 	return result;
    831 }
    832 
    833 function f32
    834 table_width(Table *t)
    835 {
    836 	f32 result = 0;
    837 	i32 valid  = 0;
    838 	for (i32 i = 0; i < t->columns; i++) {
    839 		result += t->widths[i];
    840 		if (t->widths[i] > 0) valid++;
    841 	}
    842 	result += t->cell_pad.w * (f32)valid;
    843 	result += MAX(0, ((f32)valid - 1)) * t->column_border_thick;
    844 	return result;
    845 }
    846 
    847 function v2
    848 table_extent(Table *t, Arena arena, Font *font)
    849 {
    850 	TableIterator *it = table_iterator_new(t, TIK_ROWS, &arena, 0, (v2){0}, font);
    851 	for (TableRow *row = table_iterator_next(it, &arena);
    852 	     row;
    853 	     row = table_iterator_next(it, &arena))
    854 	{
    855 		for (i32 i = 0; i < it->frame.table->columns; i++) {
    856 			TableCell *cell = (TableCell *)row->data + i;
    857 			if (!cell->text.len && cell->var && cell->var->flags & V_RADIO_BUTTON) {
    858 				cell->width = (f32)font->baseSize;
    859 			} else {
    860 				cell->width = measure_text(*font, cell->text).w;
    861 			}
    862 			it->frame.table->widths[i] = MAX(cell->width, it->frame.table->widths[i]);
    863 		}
    864 	}
    865 
    866 	t->size = (v2){.x = table_width(t), .y = it->cell_rect.pos.y - t->cell_pad.h / 2};
    867 	v2 result = t->size;
    868 	return result;
    869 }
    870 
    871 function v2
    872 table_cell_align(TableCell *cell, TextAlignment align, Rect r)
    873 {
    874 	v2 result = r.pos;
    875 	if (r.size.w >= cell->width) {
    876 		switch (align) {
    877 		case TextAlignment_Left:{}break;
    878 		case TextAlignment_Right:{  result.x += (r.size.w - cell->width);     }break;
    879 		case TextAlignment_Center:{ result.x += (r.size.w - cell->width) / 2; }break;
    880 		}
    881 	}
    882 	return result;
    883 }
    884 
    885 function TableCell
    886 table_variable_cell(Arena *a, Variable *var)
    887 {
    888 	TableCell result = {.var = var, .kind = TableCellKind_Variable};
    889 	if ((var->flags & V_RADIO_BUTTON) == 0) {
    890 		Stream text = arena_stream(*a);
    891 		stream_append_variable(&text, var);
    892 		result.text = arena_stream_commit(a, &text);
    893 	}
    894 	return result;
    895 }
    896 
    897 function TableRow *
    898 table_push_row(Table *t, Arena *a, TableRowKind kind)
    899 {
    900 	TableRow *result = da_push(a, t);
    901 	if (kind == TRK_CELLS) {
    902 		result->data = push_array(a, TableCell, t->columns);
    903 		/* NOTE(rnp): do not increase rows for an empty subtable */
    904 		t->rows++;
    905 	}
    906 	result->kind = kind;
    907 	return result;
    908 }
    909 
    910 function TableRow *
    911 table_push_parameter_row(Table *t, Arena *a, s8 label, Variable *var, s8 suffix)
    912 {
    913 	ASSERT(t->columns >= 3);
    914 	TableRow *result = table_push_row(t, a, TRK_CELLS);
    915 	TableCell *cells = result->data;
    916 
    917 	cells[0].text  = label;
    918 	cells[1]       = table_variable_cell(a, var);
    919 	cells[2].text  = suffix;
    920 
    921 	return result;
    922 }
    923 
    924 #define table_begin_subtable(t, a, ...) table_begin_subtable_(t, a, arg_list(TextAlignment, ##__VA_ARGS__))
    925 function Table *
    926 table_begin_subtable_(Table *table, Arena *a, TextAlignment *alignment, i32 columns)
    927 {
    928 	TableRow *row = table_push_row(table, a, TRK_TABLE);
    929 	Table *result = row->data = table_new_(a, 0, alignment, columns);
    930 	result->parent = table;
    931 	return result;
    932 }
    933 
    934 function Table *
    935 table_end_subtable(Table *table)
    936 {
    937 	Table *result = table->parent ? table->parent : table;
    938 	return result;
    939 }
    940 
    941 function void
    942 resize_frame_view(BeamformerFrameView *view, iv2 dim)
    943 {
    944 	glDeleteTextures(1, &view->texture);
    945 	glCreateTextures(GL_TEXTURE_2D, 1, &view->texture);
    946 
    947 	view->texture_dim     = dim;
    948 	view->texture_mipmaps = (i32)ctz_u32((u32)Max(dim.x, dim.y)) + 1;
    949 	glTextureStorage2D(view->texture, view->texture_mipmaps, GL_RGBA8, dim.x, dim.y);
    950 
    951 	glGenerateTextureMipmap(view->texture);
    952 
    953 	/* NOTE(rnp): work around raylib's janky texture sampling */
    954 	v4 border_colour = (v4){{0, 0, 0, 1}};
    955 	if (view->kind != BeamformerFrameViewKind_Copy) border_colour = (v4){0};
    956 	glTextureParameteri(view->texture, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
    957 	glTextureParameteri(view->texture, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
    958 	glTextureParameterfv(view->texture, GL_TEXTURE_BORDER_COLOR, border_colour.E);
    959 	/* TODO(rnp): better choice when depth component is included */
    960 	glTextureParameteri(view->texture, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    961 	glTextureParameteri(view->texture, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    962 
    963 	/* TODO(rnp): add some ID for the specific view here */
    964 	s8 label = s8("Frame View Texture");
    965 	glObjectLabel(GL_TEXTURE, view->texture, (i32)label.len, (char *)label.data);
    966 }
    967 
    968 function void
    969 ui_beamformer_frame_view_release_subresources(BeamformerUI *ui, BeamformerFrameView *bv, BeamformerFrameViewKind kind)
    970 {
    971 	if (kind == BeamformerFrameViewKind_Copy && bv->frame) {
    972 		glDeleteTextures(1, &bv->frame->texture);
    973 		bv->frame->texture = 0;
    974 		SLLPushFreelist(bv->frame, ui->frame_freelist);
    975 	}
    976 
    977 	if (kind != BeamformerFrameViewKind_3DXPlane) {
    978 		if (bv->axial_scale_bar.scale_bar.savepoint_stack)
    979 			SLLPushFreelist(bv->axial_scale_bar.scale_bar.savepoint_stack, ui->scale_bar_savepoint_freelist);
    980 		if (bv->lateral_scale_bar.scale_bar.savepoint_stack)
    981 			SLLPushFreelist(bv->lateral_scale_bar.scale_bar.savepoint_stack, ui->scale_bar_savepoint_freelist);
    982 	}
    983 }
    984 
    985 function void
    986 ui_variable_free(BeamformerUI *ui, Variable *var)
    987 {
    988 	if (var) {
    989 		var->parent = 0;
    990 		while (var) {
    991 			if (var->type == VT_GROUP) {
    992 				var = var->group.first;
    993 			} else {
    994 				if (var->type == VT_BEAMFORMER_FRAME_VIEW) {
    995 					/* TODO(rnp): instead there should be a way of linking these up */
    996 					BeamformerFrameView *bv = var->generic;
    997 					ui_beamformer_frame_view_release_subresources(ui, bv, bv->kind);
    998 					DLLRemove(bv);
    999 					/* TODO(rnp): hack; use a sentinal */
   1000 					if (bv == ui->views)
   1001 						ui->views = bv->next;
   1002 					SLLPushFreelist(bv, ui->view_freelist);
   1003 				}
   1004 
   1005 				Variable *dead = var;
   1006 				if (var->next) {
   1007 					var = var->next;
   1008 				} else {
   1009 					var = var->parent;
   1010 					/* NOTE(rnp): when we assign parent here we have already
   1011 					 * released the children. Assign type so we don't loop */
   1012 					if (var) var->type = VT_NULL;
   1013 				}
   1014 				SLLPushFreelist(dead, ui->variable_freelist);
   1015 			}
   1016 		}
   1017 	}
   1018 }
   1019 
   1020 function void
   1021 ui_variable_free_group_items(BeamformerUI *ui, Variable *group)
   1022 {
   1023 	assert(group->type == VT_GROUP);
   1024 	/* NOTE(rnp): prevent traversal back to us */
   1025 	group->group.last->parent = 0;
   1026 	ui_variable_free(ui, group->group.first);
   1027 	group->group.first = group->group.last = 0;
   1028 }
   1029 
   1030 function void
   1031 ui_view_free(BeamformerUI *ui, Variable *view)
   1032 {
   1033 	assert(view->type == VT_UI_VIEW);
   1034 	ui_variable_free(ui, view->view.child);
   1035 	ui_variable_free(ui, view->view.close);
   1036 	ui_variable_free(ui, view->view.menu);
   1037 	ui_variable_free(ui, view);
   1038 }
   1039 
   1040 function Variable *
   1041 fill_variable(Variable *var, Variable *group, s8 name, u32 flags, VariableType type, Font font)
   1042 {
   1043 	var->flags      = flags;
   1044 	var->type       = type;
   1045 	var->name       = name;
   1046 	var->parent     = group;
   1047 	var->name_width = measure_text(font, name).x;
   1048 
   1049 	if (group && group->type == VT_GROUP) {
   1050 		if (group->group.last) group->group.last = group->group.last->next = var;
   1051 		else                   group->group.last = group->group.first      = var;
   1052 	}
   1053 
   1054 	return var;
   1055 }
   1056 
   1057 function Variable *
   1058 add_variable(BeamformerUI *ui, Variable *group, Arena *arena, s8 name, u32 flags,
   1059              VariableType type, Font font)
   1060 {
   1061 	Variable *result = SLLPopFreelist(ui->variable_freelist);
   1062 	if (!result) result = push_struct_no_zero(arena, Variable);
   1063 	zero_struct(result);
   1064 	return fill_variable(result, group, name, flags, type, font);
   1065 }
   1066 
   1067 function Variable *
   1068 add_variable_group(BeamformerUI *ui, Variable *group, Arena *arena, s8 name, VariableGroupKind kind, Font font)
   1069 {
   1070 	Variable *result   = add_variable(ui, group, arena, name, V_INPUT, VT_GROUP, font);
   1071 	result->group.kind = kind;
   1072 	return result;
   1073 }
   1074 
   1075 function Variable *
   1076 end_variable_group(Variable *group)
   1077 {
   1078 	ASSERT(group->type == VT_GROUP);
   1079 	return group->parent;
   1080 }
   1081 
   1082 function void
   1083 fill_variable_cycler(Variable *cycler, u32 *store, s8 *labels, u32 cycle_count)
   1084 {
   1085 	cycler->cycler.cycle_length = cycle_count;
   1086 	cycler->cycler.state        = store;
   1087 	cycler->cycler.labels       = labels;
   1088 }
   1089 
   1090 function Variable *
   1091 add_variable_cycler(BeamformerUI *ui, Variable *group, Arena *arena, u32 flags, Font font, s8 name,
   1092                     u32 *store, s8 *labels, u32 cycle_count)
   1093 {
   1094 	Variable *result = add_variable(ui, group, arena, name, V_INPUT|flags, VT_CYCLER, font);
   1095 	fill_variable_cycler(result, store, labels, cycle_count);
   1096 	return result;
   1097 }
   1098 
   1099 function Variable *
   1100 add_button(BeamformerUI *ui, Variable *group, Arena *arena, s8 name, UIButtonID id,
   1101            u32 flags, Font font)
   1102 {
   1103 	Variable *result = add_variable(ui, group, arena, name, V_INPUT|flags, VT_UI_BUTTON, font);
   1104 	result->button   = id;
   1105 	return result;
   1106 }
   1107 
   1108 function Variable *
   1109 add_ui_split(BeamformerUI *ui, Variable *parent, Arena *arena, s8 name, f32 fraction,
   1110              RegionSplitDirection direction, Font font)
   1111 {
   1112 	Variable *result = add_variable(ui, parent, arena, name, V_HIDES_CURSOR, VT_UI_REGION_SPLIT, font);
   1113 	result->region_split.direction = direction;
   1114 	result->region_split.fraction  = fraction;
   1115 	return result;
   1116 }
   1117 
   1118 function Variable *
   1119 add_global_menu_to_group(BeamformerUI *ui, Arena *arena, Variable *group)
   1120 {
   1121 	#define X(id, text) add_button(ui, group, arena, s8(text), UI_BID_ ##id, 0, ui->small_font);
   1122 	GLOBAL_MENU_BUTTONS
   1123 	#undef X
   1124 	return group;
   1125 }
   1126 
   1127 function Variable *
   1128 add_global_menu(BeamformerUI *ui, Arena *arena, Variable *parent)
   1129 {
   1130 	Variable *result = add_variable_group(ui, 0, arena, s8(""), VariableGroupKind_List, ui->small_font);
   1131 	result->parent = parent;
   1132 	return add_global_menu_to_group(ui, arena, result);
   1133 }
   1134 
   1135 function Variable *
   1136 add_ui_view(BeamformerUI *ui, Variable *parent, Arena *arena, s8 name, u32 view_flags, b32 menu, b32 closable)
   1137 {
   1138 	Variable *result = add_variable(ui, parent, arena, name, 0, VT_UI_VIEW, ui->small_font);
   1139 	UIView   *view   = &result->view;
   1140 	view->flags      = view_flags;
   1141 	if (menu) view->menu = add_global_menu(ui, arena, result);
   1142 	if (closable) {
   1143 		view->close = add_button(ui, 0, arena, s8(""), UI_BID_VIEW_CLOSE, 0, ui->small_font);
   1144 		/* NOTE(rnp): we do this explicitly so that close doesn't end up in the view group */
   1145 		view->close->parent = result;
   1146 	}
   1147 	return result;
   1148 }
   1149 
   1150 function Variable *
   1151 add_floating_view(BeamformerUI *ui, Arena *arena, VariableType type, v2 at, Variable *child, b32 closable)
   1152 {
   1153 	Variable *result = add_ui_view(ui, 0, arena, s8(""), UIViewFlag_Floating, 0, closable);
   1154 	result->type          = type;
   1155 	result->view.rect.pos = at;
   1156 	result->view.child    = child;
   1157 
   1158 	result->parent = &ui->floating_widget_sentinal;
   1159 	result->next   = ui->floating_widget_sentinal.next;
   1160 	result->next->parent = result;
   1161 	ui->floating_widget_sentinal.next = result;
   1162 	return result;
   1163 }
   1164 
   1165 function void
   1166 fill_beamformer_variable(Variable *var, s8 suffix, f32 *store, v2 limits, f32 display_scale, f32 scroll_scale)
   1167 {
   1168 	BeamformerVariable *bv = &var->beamformer_variable;
   1169 	bv->suffix        = suffix;
   1170 	bv->store         = store;
   1171 	bv->display_scale = display_scale;
   1172 	bv->scroll_scale  = scroll_scale;
   1173 	bv->limits        = limits;
   1174 }
   1175 
   1176 function void
   1177 add_beamformer_variable(BeamformerUI *ui, Variable *group, Arena *arena, s8 name, s8 suffix, f32 *store,
   1178                         v2 limits, f32 display_scale, f32 scroll_scale, u32 flags, Font font)
   1179 {
   1180 	Variable *var = add_variable(ui, group, arena, name, flags, VT_BEAMFORMER_VARIABLE, font);
   1181 	fill_beamformer_variable(var, suffix, store, limits, display_scale, scroll_scale);
   1182 }
   1183 
   1184 function Variable *
   1185 add_beamformer_parameters_view(Variable *parent, BeamformerCtx *ctx)
   1186 {
   1187 	BeamformerUI *ui           = ctx->ui;
   1188 	BeamformerUIParameters *bp = &ui->params;
   1189 
   1190 	v2 v2_inf = {.x = -F32_INFINITY, .y = F32_INFINITY};
   1191 
   1192 	/* TODO(rnp): this can be closable once we have a way of opening new views */
   1193 	Variable *result = add_ui_view(ui, parent, &ui->arena, s8("Parameters"), 0, 1, 0);
   1194 	Variable *group  = result->view.child = add_variable(ui, result, &ui->arena, s8(""), 0,
   1195 	                                                     VT_GROUP, ui->font);
   1196 
   1197 	add_beamformer_variable(ui, group, &ui->arena, s8("Sampling Frequency:"), s8("[MHz]"),
   1198 	                        &bp->sampling_frequency, (v2){0}, 1e-6f, 0, 0, ui->font);
   1199 
   1200 	add_beamformer_variable(ui, group, &ui->arena, s8("Demodulation Frequency:"), s8("[MHz]"),
   1201 	                        &bp->demodulation_frequency, (v2){.y = 100e6f}, 1e-6f, 0, 0, ui->font);
   1202 
   1203 	add_beamformer_variable(ui, group, &ui->arena, s8("Speed of Sound:"), s8("[m/s]"),
   1204 	                        &bp->speed_of_sound, (v2){.y = 1e6f}, 1.0f, 10.0f,
   1205 	                        V_INPUT|V_TEXT|V_CAUSES_COMPUTE, ui->font);
   1206 
   1207 	group = add_variable_group(ui, group, &ui->arena, s8("Lateral Extent:"),
   1208 	                           VariableGroupKind_Vector, ui->font);
   1209 	{
   1210 		add_beamformer_variable(ui, group, &ui->arena, s8("Min:"), s8("[mm]"),
   1211 		                       ui->min_coordinate.E + 0, v2_inf, 1e3f, 0.5e-3f,
   1212 		                       V_INPUT|V_TEXT|V_CAUSES_COMPUTE, ui->font);
   1213 
   1214 		add_beamformer_variable(ui, group, &ui->arena, s8("Max:"), s8("[mm]"),
   1215 		                        ui->max_coordinate.E + 0, v2_inf, 1e3f, 0.5e-3f,
   1216 		                        V_INPUT|V_TEXT|V_CAUSES_COMPUTE, ui->font);
   1217 	}
   1218 	group = end_variable_group(group);
   1219 
   1220 	group = add_variable_group(ui, group, &ui->arena, s8("Axial Extent:"),
   1221 	                           VariableGroupKind_Vector, ui->font);
   1222 	{
   1223 		add_beamformer_variable(ui, group, &ui->arena, s8("Min:"), s8("[mm]"),
   1224 		                        ui->min_coordinate.E + 2, v2_inf, 1e3f, 0.5e-3f,
   1225 		                        V_INPUT|V_TEXT|V_CAUSES_COMPUTE, ui->font);
   1226 
   1227 		add_beamformer_variable(ui, group, &ui->arena, s8("Max:"), s8("[mm]"),
   1228 		                        ui->max_coordinate.E + 2, v2_inf, 1e3f, 0.5e-3f,
   1229 		                        V_INPUT|V_TEXT|V_CAUSES_COMPUTE, ui->font);
   1230 	}
   1231 	group = end_variable_group(group);
   1232 
   1233 	add_beamformer_variable(ui, group, &ui->arena, s8("Off Axis Position:"), s8("[mm]"),
   1234 	                        &ui->off_axis_position, v2_inf, 1e3f, 0.5e-3f,
   1235 	                        V_INPUT|V_TEXT|V_CAUSES_COMPUTE, ui->font);
   1236 
   1237 	add_beamformer_variable(ui, group, &ui->arena, s8("Beamform Plane:"), s8(""),
   1238 	                        &ui->beamform_plane, (v2){{0, 1.0f}}, 1.0f, 0.025f,
   1239 	                        V_INPUT|V_TEXT|V_CAUSES_COMPUTE, ui->font);
   1240 
   1241 	add_beamformer_variable(ui, group, &ui->arena, s8("F#:"), s8(""), &bp->f_number, (v2){.y = 1e3f},
   1242 	                        1, 0.1f, V_INPUT|V_TEXT|V_CAUSES_COMPUTE, ui->font);
   1243 
   1244 	add_variable_cycler(ui, group, &ui->arena, V_CAUSES_COMPUTE, ui->font, s8("Interpolation:"),
   1245 	                    &bp->interpolation_mode, beamformer_interpolation_mode_strings,
   1246 	                    countof(beamformer_interpolation_mode_strings));
   1247 
   1248 	read_only local_persist s8 true_false_labels[] = {s8_comp("False"), s8_comp("True")};
   1249 	add_variable_cycler(ui, group, &ui->arena, V_CAUSES_COMPUTE, ui->font, s8("Coherency Weighting:"),
   1250 	                    &bp->coherency_weighting, true_false_labels, countof(true_false_labels));
   1251 
   1252 	return result;
   1253 }
   1254 
   1255 function void
   1256 ui_beamformer_frame_view_convert(BeamformerUI *ui, Arena *arena, Variable *view, Variable *menu,
   1257                                  BeamformerFrameViewKind kind, BeamformerFrameView *old, b32 log_scale)
   1258 {
   1259 	assert(menu->group.first == menu->group.last && menu->group.first == 0);
   1260 	assert(view->type == VT_BEAMFORMER_FRAME_VIEW);
   1261 
   1262 	BeamformerFrameView *bv = view->generic;
   1263 	bv->kind  = kind;
   1264 	bv->dirty = 1;
   1265 
   1266 	fill_variable(&bv->dynamic_range, view, s8("Dynamic Range:"), V_INPUT|V_TEXT|V_UPDATE_VIEW,
   1267 	              VT_F32, ui->small_font);
   1268 	fill_variable(&bv->threshold, view, s8("Threshold:"), V_INPUT|V_TEXT|V_UPDATE_VIEW,
   1269 	              VT_F32, ui->small_font);
   1270 	fill_variable(&bv->gamma, view, s8("Gamma:"), V_INPUT|V_TEXT|V_UPDATE_VIEW,
   1271 	              VT_SCALED_F32, ui->small_font);
   1272 
   1273 	bv->dynamic_range.real32      = old? old->dynamic_range.real32      : 50.0f;
   1274 	bv->threshold.real32          = old? old->threshold.real32          : 55.0f;
   1275 	bv->gamma.scaled_real32.val   = old? old->gamma.scaled_real32.val   : 1.0f;
   1276 	bv->gamma.scaled_real32.scale = old? old->gamma.scaled_real32.scale : 0.05f;
   1277 	bv->min_coordinate = (old && old->frame) ? m4_mul_v4(old->frame->voxel_transform, (v4){{0.0f, 0.0f, 0.0f, 1.0f}}).xyz
   1278 	                                         : (v3){0};
   1279 	bv->max_coordinate = (old && old->frame) ? m4_mul_v4(old->frame->voxel_transform, (v4){{1.0f, 1.0f, 1.0f, 1.0f}}).xyz
   1280 	                                         : (v3){0};
   1281 
   1282 	#define X(_t, pretty) s8_comp(pretty),
   1283 	read_only local_persist s8 kind_labels[] = {BEAMFORMER_FRAME_VIEW_KIND_LIST};
   1284 	#undef X
   1285 	bv->kind_cycler = add_variable_cycler(ui, menu, arena, V_EXTRA_ACTION, ui->small_font,
   1286 	                                      s8("Kind:"), (u32 *)&bv->kind, kind_labels, countof(kind_labels));
   1287 
   1288 	/* TODO(rnp): this is quite dumb. what we actually want is to render directly
   1289 	 * into the view region with the appropriate size for that region (scissor) */
   1290 	resize_frame_view(bv, (iv2){{FRAME_VIEW_RENDER_TARGET_SIZE}});
   1291 
   1292 	switch (kind) {
   1293 	case BeamformerFrameViewKind_3DXPlane:{
   1294 		view->flags |= V_HIDES_CURSOR;
   1295 		glTextureParameteri(bv->texture, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   1296 		glTextureParameteri(bv->texture, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
   1297 		fill_variable(bv->x_plane_shifts + 0, view, s8("XZ Shift"), V_INPUT|V_HIDES_CURSOR,
   1298 		              VT_X_PLANE_SHIFT, ui->small_font);
   1299 		fill_variable(bv->x_plane_shifts + 1, view, s8("YZ Shift"), V_INPUT|V_HIDES_CURSOR,
   1300 		              VT_X_PLANE_SHIFT, ui->small_font);
   1301 		bv->demo = add_variable(ui, menu, arena, s8("Demo Mode"), V_INPUT|V_RADIO_BUTTON, VT_B32, ui->small_font);
   1302 	}break;
   1303 	default:{
   1304 		view->flags &= ~(u32)V_HIDES_CURSOR;
   1305 		fill_variable(&bv->lateral_scale_bar, view, s8(""), V_INPUT, VT_SCALE_BAR, ui->small_font);
   1306 		fill_variable(&bv->axial_scale_bar,   view, s8(""), V_INPUT, VT_SCALE_BAR, ui->small_font);
   1307 		ScaleBar *lateral            = &bv->lateral_scale_bar.scale_bar;
   1308 		ScaleBar *axial              = &bv->axial_scale_bar.scale_bar;
   1309 		lateral->direction           = SB_LATERAL;
   1310 		axial->direction             = SB_AXIAL;
   1311 		lateral->scroll_scale        = (v2){{-0.5e-3f, 0.5e-3f}};
   1312 		axial->scroll_scale          = (v2){{ 0,       1.0e-3f}};
   1313 		lateral->zoom_starting_coord = F32_INFINITY;
   1314 		axial->zoom_starting_coord   = F32_INFINITY;
   1315 
   1316 		b32 copy = kind == BeamformerFrameViewKind_Copy;
   1317 		lateral->min_value = copy ? &bv->min_coordinate.x : &ui->min_coordinate.x;
   1318 		lateral->max_value = copy ? &bv->max_coordinate.x : &ui->max_coordinate.x;
   1319 		axial->min_value   = copy ? &bv->min_coordinate.z : &ui->min_coordinate.z;
   1320 		axial->max_value   = copy ? &bv->max_coordinate.z : &ui->max_coordinate.z;
   1321 
   1322 		#define X(id, text) add_button(ui, menu, arena, s8(text), UI_BID_ ##id, 0, ui->small_font);
   1323 		FRAME_VIEW_BUTTONS
   1324 		#undef X
   1325 
   1326 		bv->axial_scale_bar_active   = add_variable(ui, menu, arena, s8("Axial Scale Bar"),
   1327 		                                            V_INPUT|V_RADIO_BUTTON, VT_B32, ui->small_font);
   1328 		bv->lateral_scale_bar_active = add_variable(ui, menu, arena, s8("Lateral Scale Bar"),
   1329 		                                            V_INPUT|V_RADIO_BUTTON, VT_B32, ui->small_font);
   1330 
   1331 		if (kind == BeamformerFrameViewKind_Latest) {
   1332 			bv->axial_scale_bar_active->bool32   = 1;
   1333 			bv->lateral_scale_bar_active->bool32 = 1;
   1334 			bv->axial_scale_bar.flags   |= V_CAUSES_COMPUTE;
   1335 			bv->lateral_scale_bar.flags |= V_CAUSES_COMPUTE;
   1336 		}
   1337 	}break;
   1338 	}
   1339 
   1340 	bv->log_scale = add_variable(ui, menu, arena, s8("Log Scale"),
   1341 	                             V_INPUT|V_UPDATE_VIEW|V_RADIO_BUTTON, VT_B32, ui->small_font);
   1342 	bv->log_scale->bool32 = log_scale;
   1343 
   1344 	switch (kind) {
   1345 	case BeamformerFrameViewKind_Latest:{
   1346 		#define X(_type, _id, pretty) s8_comp(pretty),
   1347 		read_only local_persist s8 labels[] = {BEAMFORMER_VIEW_PLANE_TAG_LIST s8_comp("Any")};
   1348 		#undef X
   1349 		bv->cycler = add_variable_cycler(ui, menu, arena, 0, ui->small_font, s8("Live:"),
   1350 		                                 &bv->cycler_state, labels, countof(labels));
   1351 		bv->cycler_state = BeamformerViewPlaneTag_Count;
   1352 	}break;
   1353 	case BeamformerFrameViewKind_Indexed:{
   1354 		bv->cycler = add_variable_cycler(ui, menu, arena, 0, ui->small_font, s8("Index:"),
   1355 		                                 &bv->cycler_state, 0, BeamformerMaxSavedFrames);
   1356 	}break;
   1357 	default:{}break;
   1358 	}
   1359 
   1360 	add_global_menu_to_group(ui, arena, menu);
   1361 }
   1362 
   1363 function BeamformerFrameView *
   1364 ui_beamformer_frame_view_new(BeamformerUI *ui, Arena *arena)
   1365 {
   1366 	BeamformerFrameView *result = SLLPopFreelist(ui->view_freelist);
   1367 	if (!result) result = push_struct_no_zero(arena, typeof(*result));
   1368 	zero_struct(result);
   1369 	DLLPushDown(result, ui->views);
   1370 	return result;
   1371 }
   1372 
   1373 function Variable *
   1374 add_beamformer_frame_view(BeamformerUI *ui, Variable *parent, Arena *arena,
   1375                           BeamformerFrameViewKind kind, b32 closable, BeamformerFrameView *old)
   1376 {
   1377 	/* TODO(rnp): this can be always closable once we have a way of opening new views */
   1378 	Variable *result = add_ui_view(ui, parent, arena, s8(""), UIViewFlag_CustomText, 1, closable);
   1379 	Variable *var = result->view.child = add_variable(ui, result, arena, s8(""), 0,
   1380 	                                                  VT_BEAMFORMER_FRAME_VIEW, ui->small_font);
   1381 	Variable *menu = result->view.menu = add_variable_group(ui, 0, arena, s8(""),
   1382 	                                                        VariableGroupKind_List, ui->small_font);
   1383 	menu->parent = result;
   1384 	var->generic = ui_beamformer_frame_view_new(ui, arena);
   1385 	ui_beamformer_frame_view_convert(ui, arena, var, menu, kind, old, old? old->log_scale->bool32 : 0);
   1386 	return result;
   1387 }
   1388 
   1389 function Variable *
   1390 add_compute_progress_bar(Variable *parent, BeamformerCtx *ctx)
   1391 {
   1392 	BeamformerUI *ui = ctx->ui;
   1393 	/* TODO(rnp): this can be closable once we have a way of opening new views */
   1394 	Variable *result = add_ui_view(ui, parent, &ui->arena, s8(""), UIViewFlag_CustomText, 1, 0);
   1395 	result->view.child = add_variable(ui, result, &ui->arena, s8(""), 0,
   1396 	                                  VT_COMPUTE_PROGRESS_BAR, ui->small_font);
   1397 	ComputeProgressBar *bar = &result->view.child->compute_progress_bar;
   1398 	bar->progress   = &ctx->compute_context.processing_progress;
   1399 	bar->processing = &ctx->compute_context.processing_compute;
   1400 
   1401 	return result;
   1402 }
   1403 
   1404 function Variable *
   1405 add_compute_stats_view(BeamformerUI *ui, Variable *parent, Arena *arena, BeamformerCtx *ctx)
   1406 {
   1407 	/* TODO(rnp): this can be closable once we have a way of opening new views */
   1408 	Variable *result   = add_ui_view(ui, parent, arena, s8(""), UIViewFlag_CustomText, 0, 0);
   1409 	result->view.child = add_variable(ui, result, &ui->arena, s8(""), 0,
   1410 	                                  VT_COMPUTE_STATS_VIEW, ui->small_font);
   1411 
   1412 	Variable *menu = result->view.menu = add_variable_group(ui, 0, arena, s8(""),
   1413 	                                                        VariableGroupKind_List, ui->small_font);
   1414 	menu->parent = result;
   1415 
   1416 	#define X(_k, label) s8_comp(label),
   1417 	read_only local_persist s8 labels[] = {COMPUTE_STATS_VIEW_LIST};
   1418 	#undef X
   1419 
   1420 	ComputeStatsView *csv = &result->view.child->compute_stats_view;
   1421 	csv->compute_shader_stats = ctx->compute_shader_stats;
   1422 	csv->cycler = add_variable_cycler(ui, menu, arena, 0, ui->small_font, s8("Stats View:"),
   1423 	                                  (u32 *)&csv->kind, labels, countof(labels));
   1424 	add_global_menu_to_group(ui, arena, menu);
   1425 	return result;
   1426 }
   1427 
   1428 function Variable *
   1429 add_live_controls_view(BeamformerUI *ui, Variable *parent, Arena *arena)
   1430 {
   1431 	BeamformerLiveImagingParameters *lip = &ui->shared_memory->live_imaging_parameters;
   1432 	/* TODO(rnp): this can be closable once we have a way of opening new views */
   1433 	Variable *result = add_ui_view(ui, parent, &ui->arena, s8("Live Controls"), 0, 1, 0);
   1434 	result->view.child = add_variable(ui, result, &ui->arena, s8(""), 0,
   1435 	                                  VT_LIVE_CONTROLS_VIEW, ui->small_font);
   1436 	Variable *view = result->view.child;
   1437 	BeamformerLiveControlsView *lv = view->generic = push_struct(arena, typeof(*lv));
   1438 
   1439 	fill_variable(&lv->transmit_power, view, s8(""), V_INPUT|V_LIVE_CONTROL,
   1440 	              VT_BEAMFORMER_VARIABLE, ui->small_font);
   1441 	fill_beamformer_variable(&lv->transmit_power, s8(""), &lip->transmit_power, (v2){{0, 1.0f}}, 100.0f, 0.05f);
   1442 
   1443 	for (u32 i = 0; i < countof(lv->tgc_control_points); i++) {
   1444 		Variable *v = lv->tgc_control_points + i;
   1445 		fill_variable(v, view, s8(""), V_INPUT|V_LIVE_CONTROL, VT_BEAMFORMER_VARIABLE, ui->small_font);
   1446 		fill_beamformer_variable(v, s8(""), lip->tgc_control_points + i, (v2){{0, 1.0f}}, 0, 0.05f);
   1447 	}
   1448 
   1449 	fill_variable(&lv->stop_button, view, s8("Stop Imaging"), V_INPUT|V_LIVE_CONTROL,
   1450 	              VT_B32, ui->small_font);
   1451 
   1452 	read_only local_persist s8 save_labels[] = {s8_comp("Save Data"), s8_comp("Saving...")};
   1453 	fill_variable(&lv->save_button, view, s8("Save Data"), V_INPUT|V_LIVE_CONTROL,
   1454 	              VT_CYCLER, ui->small_font);
   1455 	fill_variable_cycler(&lv->save_button, &lip->save_active, save_labels, countof(save_labels));
   1456 
   1457 	fill_variable(&lv->save_text, view, s8(""), V_INPUT|V_TEXT|V_LIVE_CONTROL,
   1458 	              VT_LIVE_CONTROLS_STRING, ui->small_font);
   1459 	lv->save_text.generic = lip;
   1460 
   1461 	return result;
   1462 }
   1463 
   1464 function Variable *
   1465 ui_split_region(BeamformerUI *ui, Variable *region, Variable *split_side, RegionSplitDirection direction)
   1466 {
   1467 	Variable *result = add_ui_split(ui, region, &ui->arena, s8(""), 0.5, direction, ui->small_font);
   1468 	if (split_side == region->region_split.left) {
   1469 		region->region_split.left  = result;
   1470 	} else {
   1471 		region->region_split.right = result;
   1472 	}
   1473 	split_side->parent = result;
   1474 	result->region_split.left = split_side;
   1475 	return result;
   1476 }
   1477 
   1478 function void
   1479 ui_add_live_frame_view(BeamformerUI *ui, Variable *view, RegionSplitDirection direction,
   1480                        BeamformerFrameViewKind kind)
   1481 {
   1482 	Variable *region = view->parent;
   1483 	assert(region->type == VT_UI_REGION_SPLIT);
   1484 	assert(view->type   == VT_UI_VIEW);
   1485 	Variable *new_region = ui_split_region(ui, region, view, direction);
   1486 	new_region->region_split.right = add_beamformer_frame_view(ui, new_region, &ui->arena, kind, 1, 0);
   1487 }
   1488 
   1489 function void
   1490 ui_beamformer_frame_view_copy_frame(BeamformerUI *ui, BeamformerFrameView *new, BeamformerFrameView *old)
   1491 {
   1492 	assert(old->frame);
   1493 	new->frame = SLLPopFreelist(ui->frame_freelist);
   1494 	if (!new->frame) new->frame = push_struct(&ui->arena, typeof(*new->frame));
   1495 
   1496 	mem_copy(new->frame, old->frame, sizeof(*new->frame));
   1497 	new->frame->texture = 0;
   1498 	new->frame->next    = 0;
   1499 	alloc_beamform_frame(new->frame, old->frame->dim, old->frame->gl_kind, s8("Frame Copy: "), ui->arena);
   1500 
   1501 	glCopyImageSubData(old->frame->texture, GL_TEXTURE_3D, 0, 0, 0, 0,
   1502 	                   new->frame->texture, GL_TEXTURE_3D, 0, 0, 0, 0,
   1503 	                   new->frame->dim.x, new->frame->dim.y, new->frame->dim.z);
   1504 	glMemoryBarrier(GL_TEXTURE_UPDATE_BARRIER_BIT);
   1505 }
   1506 
   1507 function void
   1508 ui_copy_frame(BeamformerUI *ui, Variable *view, RegionSplitDirection direction)
   1509 {
   1510 	Variable *region = view->parent;
   1511 	assert(region->type == VT_UI_REGION_SPLIT);
   1512 	assert(view->type   == VT_UI_VIEW);
   1513 
   1514 	BeamformerFrameView *old = view->view.child->generic;
   1515 	/* TODO(rnp): hack; it would be better if this was unreachable with a 0 old->frame */
   1516 	if (!old->frame)
   1517 		return;
   1518 
   1519 	Variable *new_region = ui_split_region(ui, region, view, direction);
   1520 	new_region->region_split.right = add_beamformer_frame_view(ui, new_region, &ui->arena,
   1521 	                                                           BeamformerFrameViewKind_Copy, 1, old);
   1522 
   1523 	BeamformerFrameView *bv = new_region->region_split.right->view.child->generic;
   1524 	ui_beamformer_frame_view_copy_frame(ui, bv, old);
   1525 }
   1526 
   1527 function v3
   1528 beamformer_frame_view_plane_size(BeamformerUI *ui, BeamformerFrameView *view)
   1529 {
   1530 	v3 result;
   1531 	if (view->kind == BeamformerFrameViewKind_3DXPlane) {
   1532 		result = v3_sub(ui->max_coordinate, ui->min_coordinate);
   1533 		swap(result.y, result.z);
   1534 		result.x = Max(1e-3f, result.x);
   1535 		result.y = Max(1e-3f, result.y);
   1536 		result.z = Max(1e-3f, result.z);
   1537 	} else {
   1538 		v2 size = v2_sub(XZ(view->max_coordinate), XZ(view->min_coordinate));
   1539 		result  = (v3){.x = size.x, .y = size.y};
   1540 	}
   1541 	return result;
   1542 }
   1543 
   1544 function f32
   1545 x_plane_rotation_for_view_plane(BeamformerFrameView *view, BeamformerViewPlaneTag tag)
   1546 {
   1547 	f32 result = view->rotation;
   1548 	if (tag == BeamformerViewPlaneTag_YZ)
   1549 		result += 0.25f;
   1550 	return result;
   1551 }
   1552 
   1553 function v2
   1554 normalized_p_in_rect(Rect r, v2 p, b32 invert_y)
   1555 {
   1556 	v2 result = v2_div(v2_scale(v2_sub(p, r.pos), 2.0f), r.size);
   1557 	if (invert_y) result = (v2){{result.x - 1.0f, 1.0f - result.y}};
   1558 	else          result = v2_sub(result, (v2){{1.0f, 1.0f}});
   1559 	return result;
   1560 }
   1561 
   1562 function v3
   1563 x_plane_position(BeamformerUI *ui)
   1564 {
   1565 	f32 y_min = ui->min_coordinate.E[2];
   1566 	f32 y_max = ui->max_coordinate.E[2];
   1567 	v3 result = {.y = y_min + (y_max - y_min) / 2};
   1568 	return result;
   1569 }
   1570 
   1571 function v3
   1572 offset_x_plane_position(BeamformerUI *ui, BeamformerFrameView *view, BeamformerViewPlaneTag tag)
   1573 {
   1574 	BeamformerLiveImagingParameters *li = &ui->shared_memory->live_imaging_parameters;
   1575 	m4 x_rotation = m4_rotation_about_y(x_plane_rotation_for_view_plane(view, tag));
   1576 	v3 Z = x_rotation.c[2].xyz;
   1577 	v3 offset = v3_scale(Z, li->image_plane_offsets[tag]);
   1578 	v3 result = v3_add(x_plane_position(ui), offset);
   1579 	return result;
   1580 }
   1581 
   1582 function v3
   1583 camera_for_x_plane_view(BeamformerUI *ui, BeamformerFrameView *view)
   1584 {
   1585 	v3 size   = beamformer_frame_view_plane_size(ui, view);
   1586 	v3 target = x_plane_position(ui);
   1587 	f32 dist  = v2_magnitude(XY(size));
   1588 	v3 result = v3_add(target, (v3){{dist, -0.5f * size.y * tan_f32(50.0f * PI / 180.0f), dist}});
   1589 	return result;
   1590 }
   1591 
   1592 function m4
   1593 view_matrix_for_x_plane_view(BeamformerUI *ui, BeamformerFrameView *view, v3 camera)
   1594 {
   1595 	assert(view->kind == BeamformerFrameViewKind_3DXPlane);
   1596 	m4 result = camera_look_at(camera, x_plane_position(ui));
   1597 	return result;
   1598 }
   1599 
   1600 function m4
   1601 projection_matrix_for_x_plane_view(BeamformerFrameView *view)
   1602 {
   1603 	assert(view->kind == BeamformerFrameViewKind_3DXPlane);
   1604 	f32 aspect = (f32)view->texture_dim.w / (f32)view->texture_dim.h;
   1605 	m4 result = perspective_projection(10e-3f, 500e-3f, 45.0f * PI / 180.0f, aspect);
   1606 	return result;
   1607 }
   1608 
   1609 function ray
   1610 ray_for_x_plane_view(BeamformerUI *ui, BeamformerFrameView *view, v2 uv)
   1611 {
   1612 	assert(view->kind == BeamformerFrameViewKind_3DXPlane);
   1613 	ray result  = {.origin = camera_for_x_plane_view(ui, view)};
   1614 	v4 ray_clip = {{uv.x, uv.y, -1.0f, 1.0f}};
   1615 
   1616 	/* TODO(rnp): combine these so we only do one matrix inversion */
   1617 	m4 proj_m   = projection_matrix_for_x_plane_view(view);
   1618 	m4 view_m   = view_matrix_for_x_plane_view(ui, view, result.origin);
   1619 	m4 proj_inv = m4_inverse(proj_m);
   1620 	m4 view_inv = m4_inverse(view_m);
   1621 
   1622 	v4 ray_eye  = {.z = -1};
   1623 	ray_eye.x   = v4_dot(m4_row(proj_inv, 0), ray_clip);
   1624 	ray_eye.y   = v4_dot(m4_row(proj_inv, 1), ray_clip);
   1625 	result.direction = v3_normalize(m4_mul_v4(view_inv, ray_eye).xyz);
   1626 
   1627 	return result;
   1628 }
   1629 
   1630 function BeamformerViewPlaneTag
   1631 view_plane_tag_from_x_plane_shift(BeamformerFrameView *view, Variable *x_plane_shift)
   1632 {
   1633 	assert(BETWEEN(x_plane_shift, view->x_plane_shifts + 0, view->x_plane_shifts + 1));
   1634 	BeamformerViewPlaneTag result = BeamformerViewPlaneTag_XZ;
   1635 	if (x_plane_shift == view->x_plane_shifts + 1)
   1636 		result = BeamformerViewPlaneTag_YZ;
   1637 	return result;
   1638 }
   1639 
   1640 function void
   1641 render_single_xplane(BeamformerUI *ui, BeamformerFrameView *view, Variable *x_plane_shift,
   1642                      u32 program, f32 rotation_turns, v3 translate, BeamformerViewPlaneTag tag)
   1643 {
   1644 	u32 texture = 0;
   1645 	if (ui->latest_plane[tag])
   1646 		texture = ui->latest_plane[tag]->texture;
   1647 
   1648 	v3 scale = beamformer_frame_view_plane_size(ui, view);
   1649 	m4 model_transform = y_aligned_volume_transform(scale, translate, rotation_turns);
   1650 
   1651 	v4 colour = v4_lerp(FG_COLOUR, HOVERED_COLOUR, x_plane_shift->hover_t);
   1652 	glProgramUniformMatrix4fv(program, FRAME_VIEW_MODEL_MATRIX_LOC, 1, 0, model_transform.E);
   1653 	glProgramUniform4fv(program, FRAME_VIEW_BB_COLOUR_LOC, 1, colour.E);
   1654 	glProgramUniform1ui(program, FRAME_VIEW_SOLID_BB_LOC, 0);
   1655 	glBindTextureUnit(0, texture);
   1656 	glDrawElements(GL_TRIANGLES, ui->unit_cube_model.elements, GL_UNSIGNED_SHORT,
   1657 	               (void *)ui->unit_cube_model.elements_offset);
   1658 
   1659 	XPlaneShift *xp = &x_plane_shift->x_plane_shift;
   1660 	v3 xp_delta = v3_sub(xp->end_point, xp->start_point);
   1661 	if (!f32_equal(v3_magnitude(xp_delta), 0)) {
   1662 		m4 x_rotation = m4_rotation_about_y(rotation_turns);
   1663 		v3 Z = x_rotation.c[2].xyz;
   1664 		v3 f = v3_scale(Z, v3_dot(Z, v3_sub(xp->end_point, xp->start_point)));
   1665 
   1666 		/* TODO(rnp): there is no reason to compute the rotation matrix again */
   1667 		model_transform = y_aligned_volume_transform(scale, v3_add(f, translate), rotation_turns);
   1668 
   1669 		glProgramUniformMatrix4fv(program, FRAME_VIEW_MODEL_MATRIX_LOC, 1, 0, model_transform.E);
   1670 		glProgramUniform1ui(program, FRAME_VIEW_SOLID_BB_LOC, 1);
   1671 		glProgramUniform4fv(program, FRAME_VIEW_BB_COLOUR_LOC, 1, HOVERED_COLOUR.E);
   1672 		glDrawElements(GL_TRIANGLES, ui->unit_cube_model.elements, GL_UNSIGNED_SHORT,
   1673 		               (void *)ui->unit_cube_model.elements_offset);
   1674 	}
   1675 }
   1676 
   1677 function void
   1678 render_3D_xplane(BeamformerUI *ui, BeamformerFrameView *view, u32 program)
   1679 {
   1680 	if (view->demo->bool32) {
   1681 		view->rotation += dt_for_frame * 0.125f;
   1682 		if (view->rotation > 1.0f) view->rotation -= 1.0f;
   1683 	}
   1684 
   1685 	v3 camera     = camera_for_x_plane_view(ui, view);
   1686 	m4 view_m     = view_matrix_for_x_plane_view(ui, view, camera);
   1687 	m4 projection = projection_matrix_for_x_plane_view(view);
   1688 
   1689 	glProgramUniformMatrix4fv(program, FRAME_VIEW_VIEW_MATRIX_LOC,  1, 0, view_m.E);
   1690 	glProgramUniformMatrix4fv(program, FRAME_VIEW_PROJ_MATRIX_LOC,  1, 0, projection.E);
   1691 	glProgramUniform1f(program, FRAME_VIEW_BB_FRACTION_LOC, FRAME_VIEW_BB_FRACTION);
   1692 
   1693 	v3 model_translate = offset_x_plane_position(ui, view, BeamformerViewPlaneTag_XZ);
   1694 	render_single_xplane(ui, view, view->x_plane_shifts + 0, program,
   1695 	                     x_plane_rotation_for_view_plane(view, BeamformerViewPlaneTag_XZ),
   1696 	                     model_translate, BeamformerViewPlaneTag_XZ);
   1697 	model_translate = offset_x_plane_position(ui, view, BeamformerViewPlaneTag_YZ);
   1698 	model_translate.y -= 0.0001f;
   1699 	render_single_xplane(ui, view, view->x_plane_shifts + 1, program,
   1700 	                     x_plane_rotation_for_view_plane(view, BeamformerViewPlaneTag_YZ),
   1701 	                     model_translate, BeamformerViewPlaneTag_YZ);
   1702 }
   1703 
   1704 function void
   1705 render_2D_plane(BeamformerUI *ui, BeamformerFrameView *view, u32 program)
   1706 {
   1707 	m4 view_m     = m4_identity();
   1708 	m4 model      = m4_scale((v3){{2.0f, 2.0f, 0.0f}});
   1709 	m4 projection = orthographic_projection(0, 1, 1, 1);
   1710 
   1711 	glProgramUniformMatrix4fv(program, FRAME_VIEW_MODEL_MATRIX_LOC, 1, 0, model.E);
   1712 	glProgramUniformMatrix4fv(program, FRAME_VIEW_VIEW_MATRIX_LOC,  1, 0, view_m.E);
   1713 	glProgramUniformMatrix4fv(program, FRAME_VIEW_PROJ_MATRIX_LOC,  1, 0, projection.E);
   1714 
   1715 	glProgramUniform1f(program, FRAME_VIEW_BB_FRACTION_LOC, 0);
   1716 	glBindTextureUnit(0, view->frame->texture);
   1717 	glDrawElements(GL_TRIANGLES, ui->unit_cube_model.elements, GL_UNSIGNED_SHORT,
   1718 	               (void *)ui->unit_cube_model.elements_offset);
   1719 }
   1720 
   1721 function b32
   1722 frame_view_ready_to_present(BeamformerUI *ui, BeamformerFrameView *view)
   1723 {
   1724 	b32 result  = !iv2_equal((iv2){0}, view->texture_dim) && view->frame;
   1725 	result     |= view->kind == BeamformerFrameViewKind_3DXPlane &&
   1726 	              ui->latest_plane[BeamformerViewPlaneTag_Count];
   1727 	return result;
   1728 }
   1729 
   1730 function b32
   1731 view_update(BeamformerUI *ui, BeamformerFrameView *view)
   1732 {
   1733 	if (view->kind == BeamformerFrameViewKind_Latest) {
   1734 		u32 index = *view->cycler->cycler.state;
   1735 		view->dirty |= view->frame != ui->latest_plane[index];
   1736 		view->frame  = ui->latest_plane[index];
   1737 		if (view->dirty && view->frame) {
   1738 			view->min_coordinate = m4_mul_v4(view->frame->voxel_transform, (v4){{0.0f, 0.0f, 0.0f, 1.0f}}).xyz;
   1739 			view->max_coordinate = m4_mul_v4(view->frame->voxel_transform, (v4){{1.0f, 1.0f, 1.0f, 1.0f}}).xyz;
   1740 		}
   1741 	}
   1742 
   1743 	/* TODO(rnp): x-z or y-z */
   1744 	view->dirty |= ui->frame_view_render_context->updated;
   1745 	view->dirty |= view->kind == BeamformerFrameViewKind_3DXPlane;
   1746 
   1747 	b32 result = frame_view_ready_to_present(ui, view) && view->dirty;
   1748 	return result;
   1749 }
   1750 
   1751 function void
   1752 update_frame_views(BeamformerUI *ui, Rect window)
   1753 {
   1754 	FrameViewRenderContext *ctx = ui->frame_view_render_context;
   1755 	b32 fbo_bound = 0;
   1756 	for (BeamformerFrameView *view = ui->views; view; view = view->next) {
   1757 		if (view_update(ui, view)) {
   1758 			//start_renderdoc_capture(0);
   1759 
   1760 			if (!fbo_bound) {
   1761 				fbo_bound = 1;
   1762 				glBindFramebuffer(GL_FRAMEBUFFER, ctx->framebuffers[0]);
   1763 				glUseProgram(ctx->shader);
   1764 				glBindVertexArray(ui->unit_cube_model.vao);
   1765 				glEnable(GL_DEPTH_TEST);
   1766 			}
   1767 
   1768 			u32 fb      = ctx->framebuffers[0];
   1769 			u32 program = ctx->shader;
   1770 			glViewport(0, 0, view->texture_dim.w, view->texture_dim.h);
   1771 			glProgramUniform1f(program,  FRAME_VIEW_THRESHOLD_LOC,     view->threshold.real32);
   1772 			glProgramUniform1f(program,  FRAME_VIEW_DYNAMIC_RANGE_LOC, view->dynamic_range.real32);
   1773 			glProgramUniform1f(program,  FRAME_VIEW_GAMMA_LOC,         view->gamma.scaled_real32.val);
   1774 			glProgramUniform1ui(program, FRAME_VIEW_LOG_SCALE_LOC,     view->log_scale->bool32);
   1775 
   1776 			glNamedFramebufferRenderbuffer(fb, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, ctx->renderbuffers[0]);
   1777 			glNamedFramebufferRenderbuffer(fb, GL_DEPTH_ATTACHMENT,  GL_RENDERBUFFER, ctx->renderbuffers[1]);
   1778 			glClearNamedFramebufferfv(fb, GL_COLOR, 0, (f32 []){0, 0, 0, 0});
   1779 			glClearNamedFramebufferfv(fb, GL_DEPTH, 0, (f32 []){1});
   1780 
   1781 			if (view->kind == BeamformerFrameViewKind_3DXPlane) {
   1782 				render_3D_xplane(ui, view, program);
   1783 			} else {
   1784 				render_2D_plane(ui, view, program);
   1785 			}
   1786 
   1787 			/* NOTE(rnp): resolve multisampled scene */
   1788 			glNamedFramebufferTexture(ctx->framebuffers[1], GL_COLOR_ATTACHMENT0, view->texture, 0);
   1789 			glBlitNamedFramebuffer(fb, ctx->framebuffers[1], 0, 0, FRAME_VIEW_RENDER_TARGET_SIZE,
   1790 			                       0, 0, view->texture_dim.w, view->texture_dim.h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
   1791 
   1792 			glGenerateTextureMipmap(view->texture);
   1793 			view->dirty = 0;
   1794 
   1795 			//end_renderdoc_capture(0);
   1796 		}
   1797 	}
   1798 	if (fbo_bound) {
   1799 		glBindFramebuffer(GL_FRAMEBUFFER, 0);
   1800 		glViewport((i32)window.pos.x, (i32)window.pos.y, (i32)window.size.w, (i32)window.size.h);
   1801 		/* NOTE(rnp): I don't trust raylib to not mess with us */
   1802 		glBindVertexArray(0);
   1803 		glDisable(GL_DEPTH_TEST);
   1804 	}
   1805 }
   1806 
   1807 function Color
   1808 colour_from_normalized(v4 rgba)
   1809 {
   1810 	Color result = {.r = (u8)(rgba.r * 255.0f), .g = (u8)(rgba.g * 255.0f),
   1811 	                .b = (u8)(rgba.b * 255.0f), .a = (u8)(rgba.a * 255.0f)};
   1812 	return result;
   1813 }
   1814 
   1815 function Color
   1816 fade(Color a, f32 visibility)
   1817 {
   1818 	a.a = (u8)((f32)a.a * visibility);
   1819 	return a;
   1820 }
   1821 
   1822 function v2
   1823 draw_text_base(Font font, s8 text, v2 pos, Color colour)
   1824 {
   1825 	v2 off = v2_floor(pos);
   1826 	f32 glyph_pad = (f32)font.glyphPadding;
   1827 	for (iz i = 0; i < text.len; i++) {
   1828 		/* NOTE: assumes font glyphs are ordered ASCII */
   1829 		i32 idx = text.data[i] - 0x20;
   1830 		Rectangle dst = {
   1831 			off.x + (f32)font.glyphs[idx].offsetX - glyph_pad,
   1832 			off.y + (f32)font.glyphs[idx].offsetY - glyph_pad,
   1833 			font.recs[idx].width  + 2.0f * glyph_pad,
   1834 			font.recs[idx].height + 2.0f * glyph_pad
   1835 		};
   1836 		Rectangle src = {
   1837 			font.recs[idx].x - glyph_pad,
   1838 			font.recs[idx].y - glyph_pad,
   1839 			font.recs[idx].width  + 2.0f * glyph_pad,
   1840 			font.recs[idx].height + 2.0f * glyph_pad
   1841 		};
   1842 		DrawTexturePro(font.texture, src, dst, (Vector2){0}, 0, colour);
   1843 
   1844 		off.x += (f32)font.glyphs[idx].advanceX;
   1845 		if (font.glyphs[idx].advanceX == 0)
   1846 			off.x += font.recs[idx].width;
   1847 	}
   1848 	v2 result = {{off.x - pos.x, (f32)font.baseSize}};
   1849 	return result;
   1850 }
   1851 
   1852 /* NOTE(rnp): expensive but of the available options in raylib this gives the best results */
   1853 function v2
   1854 draw_outlined_text(s8 text, v2 pos, TextSpec *ts)
   1855 {
   1856 	f32 ow = ts->outline_thick;
   1857 	Color outline = colour_from_normalized(ts->outline_colour);
   1858 	Color colour  = colour_from_normalized(ts->colour);
   1859 	draw_text_base(*ts->font, text, v2_sub(pos, (v2){{ ow,  ow}}), outline);
   1860 	draw_text_base(*ts->font, text, v2_sub(pos, (v2){{ ow, -ow}}), outline);
   1861 	draw_text_base(*ts->font, text, v2_sub(pos, (v2){{-ow,  ow}}), outline);
   1862 	draw_text_base(*ts->font, text, v2_sub(pos, (v2){{-ow, -ow}}), outline);
   1863 
   1864 	v2 result = draw_text_base(*ts->font, text, pos, colour);
   1865 
   1866 	return result;
   1867 }
   1868 
   1869 function v2
   1870 draw_text(s8 text, v2 pos, TextSpec *ts)
   1871 {
   1872 	if (ts->flags & TF_ROTATED) {
   1873 		rlPushMatrix();
   1874 		rlTranslatef(pos.x, pos.y, 0);
   1875 		rlRotatef(ts->rotation, 0, 0, 1);
   1876 		pos = (v2){0};
   1877 	}
   1878 
   1879 	v2 result   = measure_text(*ts->font, text);
   1880 	/* TODO(rnp): the size of this should be stored for each font */
   1881 	s8 ellipsis = s8("...");
   1882 	b32 clamped = ts->flags & TF_LIMITED && result.w > ts->limits.size.w;
   1883 	if (clamped) {
   1884 		f32 ellipsis_width = measure_text(*ts->font, ellipsis).x;
   1885 		if (ellipsis_width < ts->limits.size.w) {
   1886 			text = clamp_text_to_width(*ts->font, text, ts->limits.size.w - ellipsis_width);
   1887 		} else {
   1888 			text.len     = 0;
   1889 			ellipsis.len = 0;
   1890 		}
   1891 	}
   1892 
   1893 	Color colour = colour_from_normalized(ts->colour);
   1894 	if (ts->flags & TF_OUTLINED) result.x = draw_outlined_text(text, pos, ts).x;
   1895 	else                         result.x = draw_text_base(*ts->font, text, pos, colour).x;
   1896 
   1897 	if (clamped) {
   1898 		pos.x += result.x;
   1899 		if (ts->flags & TF_OUTLINED) result.x += draw_outlined_text(ellipsis, pos, ts).x;
   1900 		else                         result.x += draw_text_base(*ts->font, ellipsis, pos,
   1901 		                                                        colour).x;
   1902 	}
   1903 
   1904 	if (ts->flags & TF_ROTATED) rlPopMatrix();
   1905 
   1906 	return result;
   1907 }
   1908 
   1909 function Rect
   1910 extend_rect_centered(Rect r, v2 delta)
   1911 {
   1912 	r.size.w += delta.x;
   1913 	r.size.h += delta.y;
   1914 	r.pos.x  -= delta.x / 2;
   1915 	r.pos.y  -= delta.y / 2;
   1916 	return r;
   1917 }
   1918 
   1919 function Rect
   1920 shrink_rect_centered(Rect r, v2 delta)
   1921 {
   1922 	delta.x   = MIN(delta.x, r.size.w);
   1923 	delta.y   = MIN(delta.y, r.size.h);
   1924 	r.size.w -= delta.x;
   1925 	r.size.h -= delta.y;
   1926 	r.pos.x  += delta.x / 2;
   1927 	r.pos.y  += delta.y / 2;
   1928 	return r;
   1929 }
   1930 
   1931 function Rect
   1932 scale_rect_centered(Rect r, v2 scale)
   1933 {
   1934 	Rect or   = r;
   1935 	r.size.w *= scale.x;
   1936 	r.size.h *= scale.y;
   1937 	r.pos.x  += (or.size.w - r.size.w) / 2;
   1938 	r.pos.y  += (or.size.h - r.size.h) / 2;
   1939 	return r;
   1940 }
   1941 
   1942 function b32
   1943 interactions_equal(Interaction a, Interaction b)
   1944 {
   1945 	b32 result = (a.kind == b.kind) && (a.generic == b.generic);
   1946 	return result;
   1947 }
   1948 
   1949 function b32
   1950 interaction_is_sticky(Interaction a)
   1951 {
   1952 	b32 result = a.kind == InteractionKind_Text || a.kind == InteractionKind_Ruler;
   1953 	return result;
   1954 }
   1955 
   1956 function b32
   1957 interaction_is_hot(BeamformerUI *ui, Interaction a)
   1958 {
   1959 	b32 result = interactions_equal(ui->hot_interaction, a);
   1960 	return result;
   1961 }
   1962 
   1963 function b32
   1964 point_in_rect(v2 p, Rect r)
   1965 {
   1966 	v2  end    = v2_add(r.pos, r.size);
   1967 	b32 result = Between(p.x, r.pos.x, end.x) & Between(p.y, r.pos.y, end.y);
   1968 	return result;
   1969 }
   1970 
   1971 function v2
   1972 rect_uv(v2 p, Rect r)
   1973 {
   1974 	v2 result = v2_div(v2_sub(p, r.pos), r.size);
   1975 	return result;
   1976 }
   1977 
   1978 function v3
   1979 world_point_from_plane_uv(m4 world, v2 uv)
   1980 {
   1981 	v3 U   = world.c[0].xyz;
   1982 	v3 V   = world.c[1].xyz;
   1983 	v3 min = world.c[3].xyz;
   1984 	v3 result =  v3_add(v3_add(v3_scale(U, uv.x), v3_scale(V, uv.y)), min);
   1985 	return result;
   1986 }
   1987 
   1988 function v2
   1989 screen_point_to_world_2d(v2 p, v2 screen_min, v2 screen_max, v2 world_min, v2 world_max)
   1990 {
   1991 	v2 pixels_to_m = v2_div(v2_sub(world_max, world_min), v2_sub(screen_max, screen_min));
   1992 	v2 result      = v2_add(v2_mul(v2_sub(p, screen_min), pixels_to_m), world_min);
   1993 	return result;
   1994 }
   1995 
   1996 function v2
   1997 world_point_to_screen_2d(v2 p, v2 world_min, v2 world_max, v2 screen_min, v2 screen_max)
   1998 {
   1999 	v2 m_to_pixels = v2_div(v2_sub(screen_max, screen_min), v2_sub(world_max, world_min));
   2000 	v2 result      = v2_add(v2_mul(v2_sub(p, world_min), m_to_pixels), screen_min);
   2001 	return result;
   2002 }
   2003 
   2004 function b32
   2005 hover_interaction(BeamformerUI *ui, v2 mouse, Interaction interaction)
   2006 {
   2007 	Variable *var = interaction.var;
   2008 	b32 result = point_in_rect(mouse, interaction.rect);
   2009 	if (result) ui->next_interaction = interaction;
   2010 	if (interaction_is_hot(ui, interaction)) var->hover_t += HOVER_SPEED * dt_for_frame;
   2011 	else                                     var->hover_t -= HOVER_SPEED * dt_for_frame;
   2012 	var->hover_t = CLAMP01(var->hover_t);
   2013 	return result;
   2014 }
   2015 
   2016 function void
   2017 draw_close_button(BeamformerUI *ui, Variable *close, v2 mouse, Rect r, v2 x_scale)
   2018 {
   2019 	assert(close->type == VT_UI_BUTTON);
   2020 	hover_interaction(ui, mouse, auto_interaction(r, close));
   2021 
   2022 	Color colour = colour_from_normalized(v4_lerp(MENU_CLOSE_COLOUR, FG_COLOUR, close->hover_t));
   2023 	r = scale_rect_centered(r, x_scale);
   2024 	DrawLineEx(rl_v2(r.pos), rl_v2(v2_add(r.pos, r.size)), 4, colour);
   2025 	DrawLineEx(rl_v2(v2_add(r.pos, (v2){.x = r.size.w})),
   2026 	           rl_v2(v2_add(r.pos, (v2){.y = r.size.h})), 4, colour);
   2027 }
   2028 
   2029 function Rect
   2030 draw_title_bar(BeamformerUI *ui, Arena arena, Variable *ui_view, Rect r, v2 mouse)
   2031 {
   2032 	assert(ui_view->type == VT_UI_VIEW);
   2033 	UIView *view = &ui_view->view;
   2034 
   2035 	s8 title = ui_view->name;
   2036 	if (view->flags & UIViewFlag_CustomText) {
   2037 		Stream buf = arena_stream(arena);
   2038 		push_custom_view_title(&buf, ui_view->view.child);
   2039 		title = arena_stream_commit(&arena, &buf);
   2040 	}
   2041 
   2042 	Rect result, title_rect;
   2043 	cut_rect_vertical(r, (f32)ui->small_font.baseSize + TITLE_BAR_PAD, &title_rect, &result);
   2044 	cut_rect_vertical(result, LISTING_LINE_PAD, 0, &result);
   2045 
   2046 	DrawRectangleRec(rl_rect(title_rect), BLACK);
   2047 
   2048 	title_rect = shrink_rect_centered(title_rect, (v2){.x = 1.5f * TITLE_BAR_PAD});
   2049 	DrawRectangleRounded(rl_rect(title_rect), 0.5f, 0, fade(colour_from_normalized(BG_COLOUR), 0.55f));
   2050 	title_rect = shrink_rect_centered(title_rect, (v2){.x = 3.0f * TITLE_BAR_PAD});
   2051 
   2052 	if (view->close) {
   2053 		Rect close;
   2054 		cut_rect_horizontal(title_rect, title_rect.size.w - title_rect.size.h, &title_rect, &close);
   2055 		draw_close_button(ui, view->close, mouse, close, (v2){{0.4f, 0.4f}});
   2056 	}
   2057 
   2058 	if (view->menu) {
   2059 		Rect menu;
   2060 		cut_rect_horizontal(title_rect, title_rect.size.w - title_rect.size.h, &title_rect, &menu);
   2061 		Interaction interaction = {.kind = InteractionKind_Menu, .var = view->menu, .rect = menu};
   2062 		hover_interaction(ui, mouse, interaction);
   2063 
   2064 		Color colour = colour_from_normalized(v4_lerp(MENU_PLUS_COLOUR, FG_COLOUR, view->menu->hover_t));
   2065 		menu = shrink_rect_centered(menu, (v2){{14.0f, 14.0f}});
   2066 		DrawLineEx(rl_v2(v2_add(menu.pos, (v2){.x = menu.size.w / 2})),
   2067 		           rl_v2(v2_add(menu.pos, (v2){.x = menu.size.w / 2, .y = menu.size.h})), 4, colour);
   2068 		DrawLineEx(rl_v2(v2_add(menu.pos, (v2){.y = menu.size.h / 2})),
   2069 		           rl_v2(v2_add(menu.pos, (v2){.x = menu.size.w, .y = menu.size.h / 2})), 4, colour);
   2070 	}
   2071 
   2072 	v2 title_pos = title_rect.pos;
   2073 	title_pos.y += 0.5f * TITLE_BAR_PAD;
   2074 	TextSpec text_spec = {.font = &ui->small_font, .flags = TF_LIMITED, .colour = FG_COLOUR,
   2075 	                      .limits.size = title_rect.size};
   2076 	draw_text(title, title_pos, &text_spec);
   2077 
   2078 	return result;
   2079 }
   2080 
   2081 /* TODO(rnp): once this has more callers decide if it would be better for this to take
   2082  * an orientation rather than force CCW/right-handed */
   2083 function void
   2084 draw_ruler(BeamformerUI *ui, Arena arena, v2 start_point, v2 end_point,
   2085            f32 start_value, f32 end_value, f32 *markers, u32 marker_count,
   2086            u32 segments, s8 suffix, v4 marker_colour, v4 txt_colour)
   2087 {
   2088 	b32 draw_plus = SIGN(start_value) != SIGN(end_value);
   2089 
   2090 	end_point    = v2_sub(end_point, start_point);
   2091 	f32 rotation = atan2_f32(end_point.y, end_point.x) * 180 / PI;
   2092 
   2093 	rlPushMatrix();
   2094 	rlTranslatef(start_point.x, start_point.y, 0);
   2095 	rlRotatef(rotation, 0, 0, 1);
   2096 
   2097 	f32 inc       = v2_magnitude(end_point) / (f32)segments;
   2098 	f32 value_inc = (end_value - start_value) / (f32)segments;
   2099 	f32 value     = start_value;
   2100 
   2101 	Stream buf = arena_stream(arena);
   2102 	v2 sp = {0}, ep = {.y = RULER_TICK_LENGTH};
   2103 	v2 tp = {{(f32)ui->small_font.baseSize / 2.0f, ep.y + RULER_TEXT_PAD}};
   2104 	TextSpec text_spec = {.font = &ui->small_font, .rotation = 90.0f, .colour = txt_colour, .flags = TF_ROTATED};
   2105 	Color rl_txt_colour = colour_from_normalized(txt_colour);
   2106 
   2107 	for (u32 j = 0; j <= segments; j++) {
   2108 		DrawLineEx(rl_v2(sp), rl_v2(ep), 3, rl_txt_colour);
   2109 
   2110 		stream_reset(&buf, 0);
   2111 		if (draw_plus && value > 0) stream_append_byte(&buf, '+');
   2112 		stream_append_f64(&buf, value, Abs(value_inc) < 1 ? 100 : 10);
   2113 		stream_append_s8(&buf, suffix);
   2114 		draw_text(stream_to_s8(&buf), tp, &text_spec);
   2115 
   2116 		value += value_inc;
   2117 		sp.x  += inc;
   2118 		ep.x  += inc;
   2119 		tp.x  += inc;
   2120 	}
   2121 
   2122 	Color rl_marker_colour = colour_from_normalized(marker_colour);
   2123 	ep.y += RULER_TICK_LENGTH;
   2124 	for (u32 i = 0; i < marker_count; i++) {
   2125 		if (markers[i] < F32_INFINITY) {
   2126 			ep.x  = sp.x = markers[i];
   2127 			DrawLineEx(rl_v2(sp), rl_v2(ep), 3, rl_marker_colour);
   2128 			DrawCircleV(rl_v2(ep), 3, rl_marker_colour);
   2129 		}
   2130 	}
   2131 
   2132 	rlPopMatrix();
   2133 }
   2134 
   2135 function void
   2136 do_scale_bar(BeamformerUI *ui, Arena arena, Variable *scale_bar, v2 mouse, Rect draw_rect,
   2137              f32 start_value, f32 end_value, s8 suffix)
   2138 {
   2139 	assert(scale_bar->type == VT_SCALE_BAR);
   2140 	ScaleBar *sb = &scale_bar->scale_bar;
   2141 
   2142 	v2 txt_s = measure_text(ui->small_font, s8("-288.8 mm"));
   2143 
   2144 	Rect tick_rect = draw_rect;
   2145 	v2   start_pos = tick_rect.pos;
   2146 	v2   end_pos   = tick_rect.pos;
   2147 	v2   relative_mouse = v2_sub(mouse, tick_rect.pos);
   2148 
   2149 	f32  markers[2];
   2150 	u32  marker_count = 1;
   2151 
   2152 	v2 world_zoom_point  = {{sb->zoom_starting_coord, sb->zoom_starting_coord}};
   2153 	v2 screen_zoom_point = world_point_to_screen_2d(world_zoom_point,
   2154 	                                                (v2){{*sb->min_value, *sb->min_value}},
   2155 	                                                (v2){{*sb->max_value, *sb->max_value}},
   2156 	                                                (v2){0}, tick_rect.size);
   2157 	u32  tick_count;
   2158 	if (sb->direction == SB_AXIAL) {
   2159 		tick_rect.size.x  = RULER_TEXT_PAD + RULER_TICK_LENGTH + txt_s.x;
   2160 		tick_count        = (u32)(tick_rect.size.y / (1.5f * (f32)ui->small_font.baseSize));
   2161 		start_pos.y      += tick_rect.size.y;
   2162 		markers[0]        = tick_rect.size.y - screen_zoom_point.y;
   2163 		markers[1]        = tick_rect.size.y - relative_mouse.y;
   2164 	} else {
   2165 		tick_rect.size.y  = RULER_TEXT_PAD + RULER_TICK_LENGTH + txt_s.x;
   2166 		tick_count        = (u32)(tick_rect.size.x / (1.5f * (f32)ui->small_font.baseSize));
   2167 		end_pos.x        += tick_rect.size.x;
   2168 		markers[0]        = screen_zoom_point.x;
   2169 		markers[1]        = relative_mouse.x;
   2170 	}
   2171 
   2172 	if (hover_interaction(ui, mouse, auto_interaction(tick_rect, scale_bar)))
   2173 		marker_count = 2;
   2174 
   2175 	draw_ruler(ui, arena, start_pos, end_pos, start_value, end_value, markers, marker_count,
   2176 	           tick_count, suffix, RULER_COLOUR, v4_lerp(FG_COLOUR, HOVERED_COLOUR, scale_bar->hover_t));
   2177 }
   2178 
   2179 function v2
   2180 draw_radio_button(BeamformerUI *ui, Variable *var, v2 at, v2 mouse, v4 base_colour, f32 size)
   2181 {
   2182 	assert(var->type == VT_B32);
   2183 	b32 value = var->bool32;
   2184 
   2185 	v2 result = (v2){.x = size, .y = size};
   2186 	Rect hover_rect   = {.pos = at, .size = result};
   2187 	hover_rect.pos.y += 1;
   2188 	hover_interaction(ui, mouse, auto_interaction(hover_rect, var));
   2189 
   2190 	hover_rect = shrink_rect_centered(hover_rect, (v2){{8.0f, 8.0f}});
   2191 	Rect inner = shrink_rect_centered(hover_rect, (v2){{4.0f, 4.0f}});
   2192 	v4 fill = v4_lerp(value? base_colour : (v4){0}, HOVERED_COLOUR, var->hover_t);
   2193 	DrawRectangleRoundedLinesEx(rl_rect(hover_rect), 0.2f, 0, 2, colour_from_normalized(base_colour));
   2194 	DrawRectangleRec(rl_rect(inner), colour_from_normalized(fill));
   2195 
   2196 	return result;
   2197 }
   2198 
   2199 function f32
   2200 draw_variable_slider(BeamformerUI *ui, Variable *var, Rect r, f32 fill, v4 fill_colour, v2 mouse)
   2201 {
   2202 	f32  border_thick    = 3.0f;
   2203 	f32  bar_height_frac = 0.8f;
   2204 	v2   bar_size        = {{6.0f, bar_height_frac * r.size.y}};
   2205 
   2206 	Rect inner  = shrink_rect_centered(r, (v2){{2.0f * border_thick, // NOTE(rnp): raylib jank
   2207 	                                            MAX(0, 2.0f * (r.size.y - bar_size.y))}});
   2208 	Rect filled = inner;
   2209 	filled.size.w *= fill;
   2210 
   2211 	Rect bar;
   2212 	bar.pos  = v2_add(r.pos, (v2){{fill * (r.size.w - bar_size.w), (1 - bar_height_frac) * 0.5f * r.size.y}});
   2213 	bar.size = bar_size;
   2214 	v4 bar_colour = v4_lerp(FG_COLOUR, FOCUSED_COLOUR, var->hover_t);
   2215 
   2216 	hover_interaction(ui, mouse, auto_interaction(inner, var));
   2217 
   2218 	DrawRectangleRec(rl_rect(filled), colour_from_normalized(fill_colour));
   2219 	DrawRectangleRoundedLinesEx(rl_rect(inner), 0.2f, 0, border_thick, BLACK);
   2220 	DrawRectangleRounded(rl_rect(bar), 0.6f, 1, colour_from_normalized(bar_colour));
   2221 
   2222 	return r.size.y;
   2223 }
   2224 
   2225 function v2
   2226 draw_fancy_button(BeamformerUI *ui, Variable *var, s8 label, Rect r, v4 border_colour, v2 mouse, TextSpec ts)
   2227 {
   2228 	assert((f32)ts.font->baseSize <= r.size.h * 0.8f);
   2229 	f32 pad = 0.1f * r.size.h;
   2230 
   2231 	v2   shadow_off   = {{2.5f, 3.0f}};
   2232 	f32  border_thick = 3.0f;
   2233 	v2   border_size  = v2_add((v2){{pad + 2.0f * border_thick, pad}}, shadow_off);
   2234 
   2235 	Rect border = shrink_rect_centered(r,      border_size);
   2236 	Rect inner  = shrink_rect_centered(border, (v2){{pad, pad}});
   2237 
   2238 	ts.limits.size = inner.size;
   2239 	hover_interaction(ui, mouse, auto_interaction(inner, var));
   2240 
   2241 	border.pos = v2_add(border.pos, shadow_off);
   2242 
   2243 	DrawRectangleRoundedLinesEx(rl_rect(border), 0.6f, 0, border_thick, fade(BLACK, 0.8f));
   2244 	border.pos = v2_sub(border.pos, shadow_off);
   2245 	DrawRectangleRounded(rl_rect(border), 0.6f, 1, colour_from_normalized(BG_COLOUR));
   2246 	DrawRectangleRoundedLinesEx(rl_rect(border), 0.6f, 0, border_thick, colour_from_normalized(border_colour));
   2247 
   2248 	/* TODO(rnp): teach draw_text() about alignment */
   2249 	v2 at = align_text_in_rect(label, inner, *ts.font);
   2250 	at = v2_add(at, (v2){{3.0f, 3.0f}});
   2251 	v4 base_colour = ts.colour;
   2252 	ts.colour = (v4){{0, 0, 0, 0.8f}};
   2253 	draw_text(label, at, &ts);
   2254 
   2255 	at = v2_sub(at, (v2){{3.0f, 3.0f}});
   2256 	ts.colour = v4_lerp(base_colour, HOVERED_COLOUR, var->hover_t);
   2257 	draw_text(label, at, &ts);
   2258 
   2259 	v2 result = v2_add(r.size, border_size);
   2260 	return result;
   2261 }
   2262 
   2263 function v2
   2264 draw_variable(BeamformerUI *ui, Arena arena, Variable *var, v2 at, v2 mouse, v4 base_colour, TextSpec text_spec)
   2265 {
   2266 	v2 result;
   2267 	if (var->flags & V_RADIO_BUTTON) {
   2268 		result = draw_radio_button(ui, var, at, mouse, base_colour, (f32)text_spec.font->baseSize);
   2269 	} else {
   2270 		Stream buf = arena_stream(arena);
   2271 		stream_append_variable(&buf, var);
   2272 		s8 text = arena_stream_commit(&arena, &buf);
   2273 		result = measure_text(*text_spec.font, text);
   2274 
   2275 		if (var->flags & V_INPUT) {
   2276 			Rect text_rect = {.pos = at, .size = result};
   2277 			text_rect = extend_rect_centered(text_rect, (v2){.x = 8});
   2278 			if (hover_interaction(ui, mouse, auto_interaction(text_rect, var)) && (var->flags & V_TEXT))
   2279 				ui->text_input_state.hot_font = text_spec.font;
   2280 			text_spec.colour = v4_lerp(base_colour, HOVERED_COLOUR, var->hover_t);
   2281 		}
   2282 
   2283 		draw_text(text, at, &text_spec);
   2284 	}
   2285 	return result;
   2286 }
   2287 
   2288 function void
   2289 draw_table_cell(BeamformerUI *ui, Arena arena, TableCell *cell, Rect cell_rect,
   2290                 TextAlignment alignment, TextSpec ts, v2 mouse)
   2291 {
   2292 	f32 x_off  = cell_rect.pos.x;
   2293 	v2 cell_at = table_cell_align(cell, alignment, cell_rect);
   2294 	ts.limits.size.w -= (cell_at.x - x_off);
   2295 	cell_rect.size.w  = MIN(ts.limits.size.w, cell_rect.size.w);
   2296 
   2297 	/* TODO(rnp): push truncated text for hovering */
   2298 	switch (cell->kind) {
   2299 	case TableCellKind_None:{ draw_text(cell->text, cell_at, &ts); }break;
   2300 	case TableCellKind_Variable:{
   2301 		if (cell->var->flags & V_INPUT) {
   2302 			draw_variable(ui, arena, cell->var, cell_at, mouse, ts.colour, ts);
   2303 		} else if (cell->text.len) {
   2304 			draw_text(cell->text, cell_at, &ts);
   2305 		}
   2306 	}break;
   2307 	case TableCellKind_VariableGroup:{
   2308 		Variable *v = cell->var->group.first;
   2309 		f32 dw = draw_text(s8("{"), cell_at, &ts).x;
   2310 		while (v) {
   2311 			cell_at.x        += dw;
   2312 			ts.limits.size.w -= dw;
   2313 			dw = draw_variable(ui, arena, v, cell_at, mouse, ts.colour, ts).x;
   2314 
   2315 			v = v->next;
   2316 			if (v) {
   2317 				cell_at.x        += dw;
   2318 				ts.limits.size.w -= dw;
   2319 				dw = draw_text(s8(", "), cell_at, &ts).x;
   2320 			}
   2321 		}
   2322 		cell_at.x        += dw;
   2323 		ts.limits.size.w -= dw;
   2324 		draw_text(s8("}"), cell_at, &ts);
   2325 	}break;
   2326 	}
   2327 }
   2328 
   2329 function void
   2330 draw_table_borders(Table *t, Rect r, f32 line_height)
   2331 {
   2332 	if (t->column_border_thick > 0) {
   2333 		v2 start  = {.x = r.pos.x, .y = r.pos.y + t->cell_pad.h / 2};
   2334 		v2 end    = start;
   2335 		end.y    += t->size.y - t->cell_pad.y;
   2336 		for (i32 i = 0; i < t->columns - 1; i++) {
   2337 			f32 dx = t->widths[i] + t->cell_pad.w + t->column_border_thick;
   2338 			start.x += dx;
   2339 			end.x   += dx;
   2340 			if (t->widths[i + 1] > 0)
   2341 				DrawLineEx(rl_v2(start), rl_v2(end), t->column_border_thick, fade(BLACK, 0.8f));
   2342 		}
   2343 	}
   2344 
   2345 	if (t->row_border_thick > 0) {
   2346 		v2 start  = {.x = r.pos.x + t->cell_pad.w / 2, .y = r.pos.y};
   2347 		v2 end    = start;
   2348 		end.x    += t->size.x - t->cell_pad.x;
   2349 		for (i32 i = 0; i < t->rows - 1; i++) {
   2350 			f32 dy   = line_height + t->cell_pad.y + t->row_border_thick;
   2351 			start.y += dy;
   2352 			end.y   += dy;
   2353 			DrawLineEx(rl_v2(start), rl_v2(end), t->row_border_thick, fade(BLACK, 0.8f));
   2354 		}
   2355 	}
   2356 }
   2357 
   2358 function v2
   2359 draw_table(BeamformerUI *ui, Arena arena, Table *table, Rect draw_rect, TextSpec ts, v2 mouse, b32 skip_rows)
   2360 {
   2361 	ts.flags |= TF_LIMITED;
   2362 
   2363 	v2 result         = {.x = table_width(table)};
   2364 	i32 row_index     = skip_rows? table_skip_rows(table, draw_rect.size.h, (f32)ts.font->baseSize) : 0;
   2365 	TableIterator *it = table_iterator_new(table, TIK_CELLS, &arena, row_index, draw_rect.pos, ts.font);
   2366 	for (TableCell *cell = table_iterator_next(it, &arena);
   2367 	     cell;
   2368 	     cell = table_iterator_next(it, &arena))
   2369 	{
   2370 		ts.limits.size.w = draw_rect.size.w - (it->cell_rect.pos.x - it->start_x);
   2371 		draw_table_cell(ui, arena, cell, it->cell_rect, it->alignment, ts, mouse);
   2372 	}
   2373 	draw_table_borders(table, draw_rect, (f32)ts.font->baseSize);
   2374 	result.y = it->cell_rect.pos.y - draw_rect.pos.y - table->cell_pad.h / 2.0f;
   2375 	return result;
   2376 }
   2377 
   2378 function void
   2379 draw_view_ruler(BeamformerFrameView *view, Arena a, Rect view_rect, TextSpec ts)
   2380 {
   2381 	v2 vr_max_p = v2_add(view_rect.pos, view_rect.size);
   2382 
   2383 	v3 U   = view->frame->voxel_transform.c[0].xyz;
   2384 	v3 V   = view->frame->voxel_transform.c[1].xyz;
   2385 	v3 min = view->frame->voxel_transform.c[3].xyz;
   2386 
   2387 	v2 start_uv = plane_uv(v3_sub(view->ruler.start, min), U, V);
   2388 	v2 end_uv   = plane_uv(v3_sub(view->ruler.end,   min), U, V);
   2389 
   2390 	v2 start_p  = v2_add(view_rect.pos, v2_mul(start_uv, view_rect.size));
   2391 	v2 end_p    = v2_add(view_rect.pos, v2_mul(end_uv,   view_rect.size));
   2392 
   2393 	b32 start_in_bounds = point_in_rect(start_p, view_rect);
   2394 	b32 end_in_bounds   = point_in_rect(end_p,   view_rect);
   2395 
   2396 	// TODO(rnp): this should be a ray intersection not a clamp
   2397 	start_p = clamp_v2_rect(start_p, view_rect);
   2398 	end_p   = clamp_v2_rect(end_p, view_rect);
   2399 
   2400 	Color rl_colour = colour_from_normalized(ts.colour);
   2401 	DrawLineEx(rl_v2(end_p), rl_v2(start_p), 2, rl_colour);
   2402 	if (start_in_bounds) DrawCircleV(rl_v2(start_p), 3, rl_colour);
   2403 	if (end_in_bounds)   DrawCircleV(rl_v2(end_p),   3, rl_colour);
   2404 
   2405 	Stream buf = arena_stream(a);
   2406 	stream_append_f64(&buf, 1e3 * v3_magnitude(v3_sub(view->ruler.end, view->ruler.start)), 100);
   2407 	stream_append_s8(&buf, s8(" mm"));
   2408 
   2409 	v2 txt_p = start_p;
   2410 	v2 txt_s = measure_text(*ts.font, stream_to_s8(&buf));
   2411 	v2 pixel_delta = v2_sub(start_p, end_p);
   2412 	if (pixel_delta.y < 0) txt_p.y -= txt_s.y;
   2413 	if (pixel_delta.x < 0) txt_p.x -= txt_s.x;
   2414 	if (txt_p.x < view_rect.pos.x) txt_p.x = view_rect.pos.x;
   2415 	if (txt_p.x + txt_s.x > vr_max_p.x) txt_p.x -= (txt_p.x + txt_s.x) - vr_max_p.x;
   2416 
   2417 	draw_text(stream_to_s8(&buf), txt_p, &ts);
   2418 }
   2419 
   2420 function v2
   2421 draw_frame_view_controls(BeamformerUI *ui, Arena arena, BeamformerFrameView *view, Rect vr, v2 mouse)
   2422 {
   2423 	TextSpec text_spec = {.font = &ui->small_font, .flags = TF_LIMITED|TF_OUTLINED,
   2424 	                      .colour = RULER_COLOUR, .outline_thick = 1, .outline_colour.a = 1,
   2425 	                      .limits.size.x = vr.size.w};
   2426 
   2427 	Table *table = table_new(&arena, 3, TextAlignment_Left, TextAlignment_Left, TextAlignment_Left);
   2428 	table_push_parameter_row(table, &arena, view->gamma.name,     &view->gamma,     s8(""));
   2429 	table_push_parameter_row(table, &arena, view->threshold.name, &view->threshold, s8(""));
   2430 	if (view->log_scale->bool32)
   2431 		table_push_parameter_row(table, &arena, view->dynamic_range.name, &view->dynamic_range, s8("[dB]"));
   2432 
   2433 	Rect table_rect = vr;
   2434 	f32 height      = table_extent(table, arena, text_spec.font).y;
   2435 	height          = MIN(height, vr.size.h);
   2436 	table_rect.pos.w  += 8;
   2437 	table_rect.pos.y  += vr.size.h - height - 8;
   2438 	table_rect.size.h  = height;
   2439 	table_rect.size.w  = vr.size.w - 16;
   2440 
   2441 	return draw_table(ui, arena, table, table_rect, text_spec, mouse, 0);
   2442 }
   2443 
   2444 function void
   2445 draw_3D_xplane_frame_view(BeamformerUI *ui, Arena arena, Variable *var, Rect display_rect, v2 mouse)
   2446 {
   2447 	assert(var->type == VT_BEAMFORMER_FRAME_VIEW);
   2448 	BeamformerFrameView *view  = var->generic;
   2449 
   2450 	f32 aspect = (f32)view->texture_dim.w / (f32)view->texture_dim.h;
   2451 	Rect vr = display_rect;
   2452 	if (aspect > 1.0f) vr.size.w = vr.size.h;
   2453 	else               vr.size.h = vr.size.w;
   2454 
   2455 	if (vr.size.w > display_rect.size.w) {
   2456 		vr.size.w -= (vr.size.w - display_rect.size.w);
   2457 		vr.size.h  = vr.size.w / aspect;
   2458 	} else if (vr.size.h > display_rect.size.h) {
   2459 		vr.size.h -= (vr.size.h - display_rect.size.h);
   2460 		vr.size.w  = vr.size.h * aspect;
   2461 	}
   2462 	vr.pos = v2_add(vr.pos, v2_scale(v2_sub(display_rect.size, vr.size), 0.5));
   2463 
   2464 	i32 id = -1;
   2465 	if (hover_interaction(ui, mouse, auto_interaction(vr, var))) {
   2466 		ray mouse_ray  = ray_for_x_plane_view(ui, view, normalized_p_in_rect(vr, mouse, 0));
   2467 		v3  x_size     = v3_scale(beamformer_frame_view_plane_size(ui, view), 0.5f);
   2468 
   2469 		f32 rotation   = x_plane_rotation_for_view_plane(view, BeamformerViewPlaneTag_XZ);
   2470 		m4  x_rotation = m4_rotation_about_y(rotation);
   2471 		v3  x_position = offset_x_plane_position(ui, view, BeamformerViewPlaneTag_XZ);
   2472 
   2473 		f32 test[2] = {0};
   2474 		test[0] = obb_raycast(x_rotation, x_size, x_position, mouse_ray);
   2475 
   2476 		x_position = offset_x_plane_position(ui, view, BeamformerViewPlaneTag_YZ);
   2477 		rotation   = x_plane_rotation_for_view_plane(view, BeamformerViewPlaneTag_YZ);
   2478 		x_rotation = m4_rotation_about_y(rotation);
   2479 		test[1] = obb_raycast(x_rotation, x_size, x_position, mouse_ray);
   2480 
   2481 		if (test[0] >= 0 && test[1] >= 0) id = test[1] < test[0]? 1 : 0;
   2482 		else if (test[0] >= 0) id = 0;
   2483 		else if (test[1] >= 0) id = 1;
   2484 
   2485 		if (id != -1) {
   2486 			view->hit_test_point = v3_add(mouse_ray.origin, v3_scale(mouse_ray.direction, test[id]));
   2487 		}
   2488 	}
   2489 
   2490 	for (i32 i = 0; i < countof(view->x_plane_shifts); i++) {
   2491 		Variable *it = view->x_plane_shifts + i;
   2492 		Interaction interaction = auto_interaction(vr, it);
   2493 		if (id == i) ui->next_interaction = interaction;
   2494 		if (interaction_is_hot(ui, interaction)) it->hover_t += HOVER_SPEED * dt_for_frame;
   2495 		else                                     it->hover_t -= HOVER_SPEED * dt_for_frame;
   2496 		it->hover_t = CLAMP01(it->hover_t);
   2497 	}
   2498 
   2499 	Rectangle  tex_r  = {0, 0, (f32)view->texture_dim.w, (f32)view->texture_dim.h};
   2500 	NPatchInfo tex_np = {tex_r, 0, 0, 0, 0, NPATCH_NINE_PATCH};
   2501 	DrawTextureNPatch(make_raylib_texture(view), tex_np, rl_rect(vr), (Vector2){0}, 0, WHITE);
   2502 
   2503 	draw_frame_view_controls(ui, arena, view, vr, mouse);
   2504 }
   2505 
   2506 function void
   2507 draw_beamformer_frame_view(BeamformerUI *ui, Arena a, Variable *var, Rect display_rect, v2 mouse)
   2508 {
   2509 	assert(var->type == VT_BEAMFORMER_FRAME_VIEW);
   2510 	BeamformerFrameView *view  = var->generic;
   2511 	BeamformerFrame     *frame = view->frame;
   2512 
   2513 	b32 is_1d = iv3_dimension(frame->dim) == 1;
   2514 
   2515 	f32 txt_w = measure_text(ui->small_font, s8("-288.8 mm")).w;
   2516 	f32 scale_bar_size = 1.2f * txt_w + RULER_TICK_LENGTH;
   2517 
   2518 	v3 U = frame->voxel_transform.c[0].xyz;
   2519 	v3 V = frame->voxel_transform.c[1].xyz;
   2520 
   2521 	v2 min_uv = plane_uv(view->min_coordinate, U, V);
   2522 	v2 max_uv = plane_uv(view->max_coordinate, U, V);
   2523 
   2524 	v2 output_dim;
   2525 	output_dim.x = v3_magnitude(U);
   2526 	output_dim.y = v3_magnitude(V);
   2527 
   2528 	// NOTE(rnp): may be different from UV if recompute in progress or Copy View
   2529 	v2 requested_dim;
   2530 	requested_dim.x = v3_magnitude(v3_sub(v3_scale(U, max_uv.x), v3_scale(U, min_uv.x)));
   2531 	requested_dim.y = v3_magnitude(v3_sub(v3_scale(V, max_uv.y), v3_scale(V, min_uv.y)));
   2532 
   2533 	f32 aspect = is_1d ? 1.0f : output_dim.w / output_dim.h;
   2534 
   2535 	Rect vr = display_rect;
   2536 	v2 scale_bar_area = {0};
   2537 	if (view->axial_scale_bar_active->bool32) {
   2538 		vr.pos.y         += 0.5f * (f32)ui->small_font.baseSize;
   2539 		scale_bar_area.x += scale_bar_size;
   2540 		scale_bar_area.y += (f32)ui->small_font.baseSize;
   2541 	}
   2542 
   2543 	if (view->lateral_scale_bar_active->bool32) {
   2544 		vr.pos.x         += 0.5f * (f32)ui->small_font.baseSize;
   2545 		scale_bar_area.x += (f32)ui->small_font.baseSize;
   2546 		scale_bar_area.y += scale_bar_size;
   2547 	}
   2548 
   2549 	vr.size = v2_sub(vr.size, scale_bar_area);
   2550 	if (aspect > 1) vr.size.h = vr.size.w / aspect;
   2551 	else            vr.size.w = vr.size.h * aspect;
   2552 
   2553 	v2 occupied = v2_add(vr.size, scale_bar_area);
   2554 	if (occupied.w > display_rect.size.w) {
   2555 		vr.size.w -= (occupied.w - display_rect.size.w);
   2556 		vr.size.h  = vr.size.w / aspect;
   2557 	} else if (occupied.h > display_rect.size.h) {
   2558 		vr.size.h -= (occupied.h - display_rect.size.h);
   2559 		vr.size.w  = vr.size.h * aspect;
   2560 	}
   2561 	occupied = v2_add(vr.size, scale_bar_area);
   2562 	vr.pos   = v2_add(vr.pos, v2_scale(v2_sub(display_rect.size, occupied), 0.5));
   2563 
   2564 	Rectangle tex_r;
   2565 	if (is_1d) {
   2566 		tex_r  = (Rectangle){0, 0, view->texture_dim.x, -view->texture_dim.y};
   2567 	} else {
   2568 		v2 pixels_per_meter = {
   2569 			.w = (f32)view->texture_dim.w / output_dim.w,
   2570 			.h = (f32)view->texture_dim.h / output_dim.h,
   2571 		};
   2572 
   2573 		/* NOTE(rnp): math to resize the texture without stretching when the view changes
   2574 		 * but the texture hasn't been (or cannot be) rebeamformed */
   2575 		v2 texture_points  = v2_mul(pixels_per_meter, requested_dim);
   2576 		v2 texture_start   = {
   2577 			.x = pixels_per_meter.x * 0.5f * (output_dim.x - requested_dim.x),
   2578 			.y = pixels_per_meter.y * (output_dim.y - requested_dim.y),
   2579 		};
   2580 
   2581 		tex_r = (Rectangle){texture_start.x, texture_start.y, texture_points.x, texture_points.y};
   2582 	}
   2583 
   2584 	NPatchInfo tex_np = { tex_r, 0, 0, 0, 0, NPATCH_NINE_PATCH };
   2585 	DrawTextureNPatch(make_raylib_texture(view), tex_np, rl_rect(vr), (Vector2){0}, 0, WHITE);
   2586 
   2587 	v2 start_pos  = vr.pos;
   2588 	start_pos.y  += vr.size.y;
   2589 
   2590 	if (vr.size.w > 0 && view->lateral_scale_bar_active->bool32) {
   2591 		do_scale_bar(ui, a, &view->lateral_scale_bar, mouse,
   2592 		             (Rect){.pos = start_pos, .size = vr.size},
   2593 		             *view->lateral_scale_bar.scale_bar.min_value * 1e3f,
   2594 		             *view->lateral_scale_bar.scale_bar.max_value * 1e3f, s8(" mm"));
   2595 	}
   2596 
   2597 	start_pos    = vr.pos;
   2598 	start_pos.x += vr.size.x;
   2599 
   2600 	if (vr.size.h > 0 && view->axial_scale_bar_active->bool32) {
   2601 		if (is_1d) {
   2602 			v2 end_pos = start_pos;
   2603 			u32 tick_count  = (u32)(vr.size.y / (1.5f * (f32)ui->small_font.baseSize));
   2604 			start_pos.y    += vr.size.y;
   2605 			draw_ruler(ui, a, start_pos, end_pos, 0.0f, 1.0f, 0, 0, tick_count, s8(""), RULER_COLOUR, FG_COLOUR);
   2606 		} else {
   2607 			do_scale_bar(ui, a, &view->axial_scale_bar, mouse, (Rect){.pos = start_pos, .size = vr.size},
   2608 			             *view->axial_scale_bar.scale_bar.max_value * 1e3f,
   2609 			             *view->axial_scale_bar.scale_bar.min_value * 1e3f, s8(" mm"));
   2610 		}
   2611 	}
   2612 
   2613 	TextSpec text_spec = {.font = &ui->small_font, .flags = TF_LIMITED|TF_OUTLINED,
   2614 	                      .colour = RULER_COLOUR, .outline_thick = 1, .outline_colour.a = 1,
   2615 	                      .limits.size.x = vr.size.w};
   2616 
   2617 	f32 draw_table_width = vr.size.w;
   2618 	/* NOTE: avoid hover_t modification */
   2619 	Interaction viewer = auto_interaction(vr, var);
   2620 	if (point_in_rect(mouse, viewer.rect)) {
   2621 		ui->next_interaction = viewer;
   2622 
   2623 		v2 world = screen_point_to_world_2d(mouse, vr.pos, v2_add(vr.pos, vr.size),
   2624 		                                    XZ(view->min_coordinate),
   2625 		                                    XZ(view->max_coordinate));
   2626 		world = v2_scale(world, 1e3f);
   2627 
   2628 		if (is_1d) world.y = ((vr.pos.y + vr.size.y) - mouse.y) / vr.size.y;
   2629 
   2630 		Stream buf = arena_stream(a);
   2631 		stream_append_s8(&buf, s8("{"));
   2632 		stream_append_f64(&buf, world.x, 100);
   2633 		if (is_1d) stream_append_s8(&buf, s8(" mm"));
   2634 		stream_append_s8(&buf, s8(", "));
   2635 		stream_append_f64(&buf, world.y, 100);
   2636 		stream_append_s8(&buf, s8("}"));
   2637 
   2638 		text_spec.limits.size.w -= 4.0f;
   2639 		v2 txt_s = measure_text(*text_spec.font, stream_to_s8(&buf));
   2640 		v2 txt_p = {
   2641 			.x = vr.pos.x + vr.size.w - txt_s.w - 4.0f,
   2642 			.y = vr.pos.y + vr.size.h - txt_s.h - 4.0f,
   2643 		};
   2644 		txt_p.x = Max(vr.pos.x, txt_p.x);
   2645 		draw_table_width -= draw_text(stream_to_s8(&buf), txt_p, &text_spec).w;
   2646 		text_spec.limits.size.w += 4.0f;
   2647 	}
   2648 
   2649 	{
   2650 		Stream buf = arena_stream(a);
   2651 		s8 shader  = push_acquisition_kind(&buf, frame->acquisition_kind, frame->compound_count);
   2652 		text_spec.font = &ui->font;
   2653 		text_spec.limits.size.w -= 16;
   2654 		v2 txt_s  = measure_text(*text_spec.font, shader);
   2655 		v2 txt_p  = {
   2656 			.x = vr.pos.x + vr.size.w - txt_s.w - 16,
   2657 			.y = vr.pos.y + 4,
   2658 		};
   2659 		txt_p.x = Max(vr.pos.x, txt_p.x);
   2660 		draw_text(stream_to_s8(&buf), txt_p, &text_spec);
   2661 		text_spec.font = &ui->small_font;
   2662 		text_spec.limits.size.w += 16;
   2663 	}
   2664 
   2665 	if (view->ruler.state != RulerState_None) draw_view_ruler(view, a, vr, text_spec);
   2666 
   2667 	vr.size.w = draw_table_width;
   2668 	draw_frame_view_controls(ui, a, view, vr, mouse);
   2669 }
   2670 
   2671 function v2
   2672 draw_compute_progress_bar(BeamformerUI *ui, ComputeProgressBar *state, Rect r)
   2673 {
   2674 	if (*state->processing) state->display_t_velocity += 65.0f * dt_for_frame;
   2675 	else                    state->display_t_velocity -= 45.0f * dt_for_frame;
   2676 
   2677 	state->display_t_velocity = CLAMP(state->display_t_velocity, -10.0f, 10.0f);
   2678 	state->display_t += state->display_t_velocity * dt_for_frame;
   2679 	state->display_t  = CLAMP01(state->display_t);
   2680 
   2681 	if (state->display_t > (1.0f / 255.0f)) {
   2682 		Rect outline = {.pos = r.pos, .size = {{r.size.w, (f32)ui->font.baseSize}}};
   2683 		outline      = scale_rect_centered(outline, (v2){{0.96f, 0.7f}});
   2684 		Rect filled  = outline;
   2685 		filled.size.w *= *state->progress;
   2686 		DrawRectangleRounded(rl_rect(filled), 2.0f, 0, fade(colour_from_normalized(HOVERED_COLOUR), state->display_t));
   2687 		DrawRectangleRoundedLinesEx(rl_rect(outline), 2.0f, 0, 3, fade(BLACK, state->display_t));
   2688 	}
   2689 
   2690 	v2 result = {{r.size.w, (f32)ui->font.baseSize}};
   2691 	return result;
   2692 }
   2693 
   2694 function s8
   2695 push_compute_time(Arena *arena, s8 prefix, f32 time)
   2696 {
   2697 	Stream sb = arena_stream(*arena);
   2698 	stream_append_s8(&sb, prefix);
   2699 	stream_append_f64_e(&sb, time);
   2700 	return arena_stream_commit(arena, &sb);
   2701 }
   2702 
   2703 function v2
   2704 draw_compute_stats_bar_view(BeamformerUI *ui, Arena arena, ComputeShaderStats *stats,
   2705                             BeamformerShaderKind *stages, u32 stages_count, f32 compute_time_sum,
   2706                             TextSpec ts, Rect r, v2 mouse)
   2707 {
   2708 	read_only local_persist s8 frame_labels[] = {s8_comp("0:"), s8_comp("-1:"), s8_comp("-2:"), s8_comp("-3:")};
   2709 	f32 total_times[countof(frame_labels)] = {0};
   2710 	Table *table = table_new(&arena, countof(frame_labels), TextAlignment_Right, TextAlignment_Left);
   2711 	for (u32 i = 0; i < countof(frame_labels); i++) {
   2712 		TableCell *cells = table_push_row(table, &arena, TRK_CELLS)->data;
   2713 		cells[0].text = frame_labels[i];
   2714 		u32 frame_index = (stats->latest_frame_index - i) % countof(stats->table.times);
   2715 		u32 seen_shaders = 0;
   2716 		for (u32 j = 0; j < stages_count; j++) {
   2717 			if ((seen_shaders & (1u << stages[j])) == 0)
   2718 				total_times[i] += stats->table.times[frame_index][stages[j]];
   2719 			seen_shaders |= (1u << stages[j]);
   2720 		}
   2721 	}
   2722 
   2723 	v2 result = table_extent(table, arena, ts.font);
   2724 
   2725 	f32 remaining_width = r.size.w - result.w - table->cell_pad.w;
   2726 	f32 average_width   = 0.8f * remaining_width;
   2727 
   2728 	s8 mouse_text = s8("");
   2729 	v2 text_pos;
   2730 
   2731 	u32 row_index = 0;
   2732 	TableIterator *it = table_iterator_new(table, TIK_ROWS, &arena, 0, r.pos, ts.font);
   2733 	for (TableRow *row = table_iterator_next(it, &arena);
   2734 	     row;
   2735 	     row = table_iterator_next(it, &arena))
   2736 	{
   2737 		Rect cr   = it->cell_rect;
   2738 		cr.size.w = table->widths[0];
   2739 		ts.limits.size.w = cr.size.w;
   2740 		draw_table_cell(ui, arena, (TableCell *)row->data, cr, table->alignment[0], ts, mouse);
   2741 
   2742 		u32 frame_index = (stats->latest_frame_index - row_index) % countof(stats->table.times);
   2743 		f32 total_width = average_width * total_times[row_index] / compute_time_sum;
   2744 		Rect rect;
   2745 		rect.pos  = v2_add(cr.pos, (v2){{cr.size.w + table->cell_pad.w , cr.size.h * 0.15f}});
   2746 		rect.size = (v2){.y = 0.7f * cr.size.h};
   2747 		for (u32 i = 0; i < stages_count; i++) {
   2748 			rect.size.w = total_width * stats->table.times[frame_index][stages[i]] / total_times[row_index];
   2749 			Color color = colour_from_normalized(g_colour_palette[i % countof(g_colour_palette)]);
   2750 			DrawRectangleRec(rl_rect(rect), color);
   2751 			if (point_in_rect(mouse, rect)) {
   2752 				text_pos   = v2_add(rect.pos, (v2){.x = table->cell_pad.w});
   2753 				s8 name    = push_s8_from_parts(&arena, s8(""), beamformer_shader_names[stages[i]], s8(": "));
   2754 				mouse_text = push_compute_time(&arena, name, stats->table.times[frame_index][stages[i]]);
   2755 			}
   2756 			rect.pos.x += rect.size.w;
   2757 		}
   2758 		row_index++;
   2759 	}
   2760 
   2761 	v2 start = v2_add(r.pos, (v2){.x = table->widths[0] + average_width + table->cell_pad.w});
   2762 	v2 end   = v2_add(start, (v2){.y = result.y});
   2763 	DrawLineEx(rl_v2(start), rl_v2(end), 4, colour_from_normalized(FG_COLOUR));
   2764 
   2765 	if (mouse_text.len) {
   2766 		ts.font = &ui->small_font;
   2767 		ts.flags &= ~(u32)TF_LIMITED;
   2768 		ts.flags |=  (u32)TF_OUTLINED;
   2769 		ts.outline_colour = (v4){.a = 1};
   2770 		ts.outline_thick  = 1;
   2771 		draw_text(mouse_text, text_pos, &ts);
   2772 	}
   2773 
   2774 	return result;
   2775 }
   2776 
   2777 function void
   2778 push_table_time_row(Table *table, Arena *arena, s8 label, f32 time)
   2779 {
   2780 	assert(table->columns == 3);
   2781 	TableCell *cells = table_push_row(table, arena, TRK_CELLS)->data;
   2782 	cells[0].text = push_s8_from_parts(arena, s8(""), label, s8(":"));
   2783 	cells[1].text = push_compute_time(arena, s8(""), time);
   2784 	cells[2].text = s8("[s]");
   2785 }
   2786 
   2787 function void
   2788 push_table_time_row_with_fps(Table *table, Arena *arena, s8 label, f32 time)
   2789 {
   2790 	assert(table->columns == 3);
   2791 	TableCell *cells = table_push_row(table, arena, TRK_CELLS)->data;
   2792 
   2793 	Stream sb = arena_stream(*arena);
   2794 	stream_append_f64_e(&sb, time);
   2795 	stream_append_s8(&sb, s8(" ("));
   2796 	stream_append_f64(&sb, time > 0 ? 1.0f / time : 0, 100);
   2797 	stream_append_s8(&sb, s8(")"));
   2798 
   2799 	cells[0].text = label;
   2800 	cells[1].text = arena_stream_commit(arena, &sb);
   2801 	cells[2].text = s8("[s] (FPS)");
   2802 }
   2803 
   2804 function void
   2805 push_table_memory_size_row(Table *table, Arena *arena, s8 label, u64 memory_size)
   2806 {
   2807 		TableCell *cells = table_push_row(table, arena, TRK_CELLS)->data;
   2808 		Stream sb = arena_stream(*arena);
   2809 		stream_append_u64(&sb, memory_size);
   2810 		cells[0].text = label;
   2811 		cells[1].text = arena_stream_commit(arena, &sb);
   2812 		cells[2].text = s8("[B/F]");
   2813 }
   2814 
   2815 function v2
   2816 draw_compute_stats_view(BeamformerUI *ui, Arena arena, Variable *view, Rect r, v2 mouse)
   2817 {
   2818 	assert(view->type == VT_COMPUTE_STATS_VIEW);
   2819 
   2820 	read_only local_persist BeamformerComputePlan dummy_plan = {0};
   2821 	u32 selected_plan = ui->selected_parameter_block % BeamformerMaxParameterBlockSlots;
   2822 	BeamformerComputePlan *cp = ui->beamformer_context->compute_context.compute_plans[selected_plan];
   2823 	if (!cp) cp = &dummy_plan;
   2824 
   2825 	ComputeStatsView   *csv   = &view->compute_stats_view;
   2826 	ComputeShaderStats *stats = csv->compute_shader_stats;
   2827 	f32 compute_time_sum = 0;
   2828 	u32 stages           = cp->pipeline.shader_count;
   2829 	TextSpec text_spec   = {.font = &ui->font, .colour = FG_COLOUR, .flags = TF_LIMITED};
   2830 
   2831 	ui_blinker_update(&csv->blink, BLINK_SPEED);
   2832 
   2833 	static_assert(BeamformerShaderKind_ComputeCount <= 32, "shader kind bitfield test");
   2834 	u32 seen_shaders = 0;
   2835 	for (u32 i = 0; i < stages; i++) {
   2836 		BeamformerShaderKind index = cp->pipeline.shaders[i];
   2837 		if ((seen_shaders & (1u << index)) == 0)
   2838 			compute_time_sum += stats->average_times[index];
   2839 		seen_shaders |= (1u << index);
   2840 	}
   2841 
   2842 	v2 result = {0};
   2843 
   2844 	Table *table = table_new(&arena, 2, TextAlignment_Left, TextAlignment_Left, TextAlignment_Left);
   2845 	switch (csv->kind) {
   2846 	case ComputeStatsViewKind_Average:{
   2847 		da_reserve(&arena, table, stages);
   2848 		for (u32 i = 0; i < stages; i++) {
   2849 			push_table_time_row(table, &arena, beamformer_shader_names[cp->pipeline.shaders[i]],
   2850 			                    stats->average_times[cp->pipeline.shaders[i]]);
   2851 		}
   2852 	}break;
   2853 	case ComputeStatsViewKind_Bar:{
   2854 		result = draw_compute_stats_bar_view(ui, arena, stats, cp->pipeline.shaders, stages,
   2855 		                                     compute_time_sum, text_spec, r, mouse);
   2856 		r.pos = v2_add(r.pos, (v2){.y = result.y});
   2857 	}break;
   2858 	InvalidDefaultCase;
   2859 	}
   2860 
   2861 	u32 rf_size = ui->beamformer_context->compute_context.rf_buffer.active_rf_size;
   2862 	push_table_time_row_with_fps(table, &arena, s8("Compute Total:"),   compute_time_sum);
   2863 	push_table_time_row_with_fps(table, &arena, s8("RF Upload Delta:"), stats->rf_time_delta_average);
   2864 	push_table_memory_size_row(table, &arena, s8("Input RF Size:"), rf_size);
   2865 	if (rf_size != cp->rf_size)
   2866 		push_table_memory_size_row(table, &arena, s8("DAS RF Size:"), cp->rf_size);
   2867 
   2868 	result = v2_add(result, table_extent(table, arena, text_spec.font));
   2869 
   2870 	u32 row_index = 0;
   2871 	TableIterator *it = table_iterator_new(table, TIK_ROWS, &arena, 0, r.pos, text_spec.font);
   2872 	for (TableRow *row = table_iterator_next(it, &arena);
   2873 	     row;
   2874 	     row = table_iterator_next(it, &arena), row_index++)
   2875 	{
   2876 		Table *t = it->frame.table;
   2877 		Rect cell_rect = it->cell_rect;
   2878 		for (i32 column = 0; column < t->columns; column++) {
   2879 			TableCell *cell = (TableCell *)it->row->data + column;
   2880 			cell_rect.size.w = t->widths[column];
   2881 			text_spec.limits.size.w = r.size.w - (cell_rect.pos.x - it->start_x);
   2882 
   2883 			if (column == 0 && row_index < stages && cp->programs[row_index] == 0 &&
   2884 			    cp->pipeline.shaders[row_index] != BeamformerShaderKind_CudaHilbert &&
   2885 			    cp->pipeline.shaders[row_index] != BeamformerShaderKind_CudaDecode)
   2886 			{
   2887 				text_spec.colour = v4_lerp(FG_COLOUR, FOCUSED_COLOUR, ease_in_out_quartic(csv->blink.t));
   2888 			} else {
   2889 				text_spec.colour = FG_COLOUR;
   2890 			}
   2891 
   2892 			draw_table_cell(ui, arena, cell, cell_rect, t->alignment[column], text_spec, mouse);
   2893 
   2894 			cell_rect.pos.x += cell_rect.size.w + t->cell_pad.w;
   2895 		}
   2896 	}
   2897 
   2898 	return result;
   2899 }
   2900 
   2901 function v2
   2902 draw_live_controls_view(BeamformerUI *ui, Variable *var, Rect r, v2 mouse, Arena arena)
   2903 {
   2904 	BeamformerLiveImagingParameters *lip = &ui->shared_memory->live_imaging_parameters;
   2905 	BeamformerLiveControlsView      *lv  = var->generic;
   2906 
   2907 	TextSpec text_spec = {.font = &ui->font, .colour = FG_COLOUR, .flags = TF_LIMITED};
   2908 
   2909 	v2 slider_size = {{MIN(140.0f, r.size.w), (f32)ui->font.baseSize}};
   2910 	v2 button_size = {{MIN(r.size.w, slider_size.x + (f32)ui->font.baseSize), (f32)ui->font.baseSize * 1.5f}};
   2911 
   2912 	f32 text_off   = r.pos.x + 0.5f * MAX(0, (r.size.w - slider_size.w - (f32)ui->font.baseSize));
   2913 	f32 slider_off = r.pos.x + 0.5f * (r.size.w - slider_size.w);
   2914 	f32 button_off = r.pos.x + 0.5f * (r.size.w - button_size.w);
   2915 
   2916 	text_spec.limits.size.w = r.size.w - (text_off - r.pos.x);
   2917 
   2918 	v2 at = {{text_off, r.pos.y}};
   2919 
   2920 	v4 hsv_power_slider = {{0.35f * ease_in_out_cubic(1.0f - lip->transmit_power), 0.65f, 0.65f, 1}};
   2921 	at.y += draw_text(s8("Power:"), at, &text_spec).y;
   2922 	at.x  = slider_off;
   2923 	at.y += draw_variable_slider(ui, &lv->transmit_power, (Rect){.pos = at, .size = slider_size},
   2924 	                             lip->transmit_power, hsv_to_rgb(hsv_power_slider), mouse);
   2925 
   2926 	at.x  = text_off;
   2927 	at.y += draw_text(s8("TGC:"), at, &text_spec).y;
   2928 	at.x  = slider_off;
   2929 	for (u32 i = 0; i < countof(lip->tgc_control_points); i++) {
   2930 		Variable *v = lv->tgc_control_points + i;
   2931 		at.y += draw_variable_slider(ui, v, (Rect){.pos = at, .size = slider_size},
   2932 		                             lip->tgc_control_points[i], g_colour_palette[1], mouse);
   2933 
   2934 		if (interaction_is_hot(ui, auto_interaction(r, v)))
   2935 			lv->hot_field_flag = BeamformerLiveImagingDirtyFlags_TGCControlPoints;
   2936 	}
   2937 
   2938 	at.x  = button_off;
   2939 	at.y += (f32)ui->font.baseSize * 0.5f;
   2940 	at.y += draw_fancy_button(ui, &lv->stop_button, lv->stop_button.name,
   2941 	                          (Rect){.pos = at, .size = button_size},
   2942 	                          BORDER_COLOUR, mouse, text_spec).y;
   2943 
   2944 	if (lip->save_enabled) {
   2945 		b32 active = lip->save_active;
   2946 		s8  label  = lv->save_button.cycler.labels[active % lv->save_button.cycler.cycle_length];
   2947 
   2948 		f32 save_t = ui_blinker_update(&lv->save_button_blink, BLINK_SPEED);
   2949 		v4 border_colour = BORDER_COLOUR;
   2950 		if (active) border_colour = v4_lerp(BORDER_COLOUR, FOCUSED_COLOUR, ease_in_out_cubic(save_t));
   2951 
   2952 		at.x  = text_off;
   2953 		at.y += draw_text(s8("File Tag:"), at, &text_spec).y;
   2954 		at.x += (f32)text_spec.font->baseSize / 2;
   2955 		text_spec.limits.size.w -= (f32)text_spec.font->baseSize;
   2956 
   2957 		v4 save_text_colour = FG_COLOUR;
   2958 		if (lip->save_name_tag_length <= 0)
   2959 			save_text_colour.a = 0.6f;
   2960 		at.y += draw_variable(ui, arena, &lv->save_text, at, mouse, save_text_colour, text_spec).y;
   2961 		text_spec.limits.size.w += (f32)text_spec.font->baseSize;
   2962 
   2963 		at.x  = button_off;
   2964 		at.y += (f32)ui->font.baseSize * 0.25f;
   2965 		at.y += draw_fancy_button(ui, &lv->save_button, label, (Rect){.pos = at, .size = button_size},
   2966 		                          border_colour, mouse, text_spec).y;
   2967 
   2968 		if (interaction_is_hot(ui, auto_interaction(r, &lv->save_text)))
   2969 			lv->hot_field_flag = BeamformerLiveImagingDirtyFlags_SaveNameTag;
   2970 		if (interaction_is_hot(ui, auto_interaction(r, &lv->save_button)))
   2971 			lv->hot_field_flag = BeamformerLiveImagingDirtyFlags_SaveData;
   2972 	}
   2973 
   2974 	if (interaction_is_hot(ui, auto_interaction(r, &lv->transmit_power)))
   2975 		lv->hot_field_flag = BeamformerLiveImagingDirtyFlags_TransmitPower;
   2976 	if (interaction_is_hot(ui, auto_interaction(r, &lv->stop_button)))
   2977 		lv->hot_field_flag = BeamformerLiveImagingDirtyFlags_StopImaging;
   2978 
   2979 	v2 result = {{r.size.w, at.y - r.pos.y}};
   2980 	return result;
   2981 }
   2982 
   2983 struct variable_iterator { Variable *current; };
   2984 function i32
   2985 variable_iterator_next(struct variable_iterator *it)
   2986 {
   2987 	i32 result = 0;
   2988 
   2989 	if (it->current->type == VT_GROUP && it->current->group.expanded) {
   2990 		it->current = it->current->group.first;
   2991 		result++;
   2992 	} else {
   2993 		while (it->current) {
   2994 			if (it->current->next) {
   2995 				it->current = it->current->next;
   2996 				break;
   2997 			}
   2998 			it->current = it->current->parent;
   2999 			result--;
   3000 		}
   3001 	}
   3002 
   3003 	return result;
   3004 }
   3005 
   3006 function v2
   3007 draw_ui_view_menu(BeamformerUI *ui, Variable *group, Arena arena, Rect r, v2 mouse, TextSpec text_spec)
   3008 {
   3009 	assert(group->type == VT_GROUP);
   3010 	Table *table = table_new(&arena, 0, TextAlignment_Left, TextAlignment_Right);
   3011 	table->row_border_thick = 2.0f;
   3012 	table->cell_pad         = (v2){{16.0f, 8.0f}};
   3013 
   3014 	i32 nesting = 0;
   3015 	for (struct variable_iterator it = {group->group.first};
   3016 	     it.current;
   3017 	     nesting = variable_iterator_next(&it))
   3018 	{
   3019 		(void)nesting;
   3020 		assert(nesting == 0);
   3021 		Variable *var = it.current;
   3022 		TableCell *cells = table_push_row(table, &arena, TRK_CELLS)->data;
   3023 		switch (var->type) {
   3024 		case VT_B32:
   3025 		case VT_CYCLER:
   3026 		{
   3027 			cells[0] = (TableCell){.text = var->name};
   3028 			cells[1] = table_variable_cell(&arena, var);
   3029 		}break;
   3030 		case VT_UI_BUTTON:{
   3031 			cells[0] = (TableCell){.text = var->name, .kind = TableCellKind_Variable, .var = var};
   3032 		}break;
   3033 		InvalidDefaultCase;
   3034 		}
   3035 	}
   3036 
   3037 	r.size = table_extent(table, arena, text_spec.font);
   3038 	return draw_table(ui, arena, table, r, text_spec, mouse, 0);
   3039 }
   3040 
   3041 function v2
   3042 draw_ui_view_listing(BeamformerUI *ui, Variable *group, Arena arena, Rect r, v2 mouse, TextSpec text_spec)
   3043 {
   3044 	assert(group->type == VT_GROUP);
   3045 	Table *table = table_new(&arena, 0, TextAlignment_Left, TextAlignment_Left, TextAlignment_Right);
   3046 
   3047 	i32 nesting = 0;
   3048 	for (struct variable_iterator it = {group->group.first};
   3049 	     it.current;
   3050 	     nesting = variable_iterator_next(&it))
   3051 	{
   3052 		while (nesting > 0) {
   3053 			table = table_begin_subtable(table, &arena, TextAlignment_Left,
   3054 			                             TextAlignment_Center, TextAlignment_Right);
   3055 			nesting--;
   3056 		}
   3057 		while (nesting < 0) { table = table_end_subtable(table); nesting++; }
   3058 
   3059 		Variable *var = it.current;
   3060 		switch (var->type) {
   3061 		case VT_CYCLER:
   3062 		case VT_BEAMFORMER_VARIABLE:
   3063 		{
   3064 			s8 suffix = s8("");
   3065 			if (var->type == VT_BEAMFORMER_VARIABLE)
   3066 				suffix = var->beamformer_variable.suffix;
   3067 			table_push_parameter_row(table, &arena, var->name, var, suffix);
   3068 		}break;
   3069 		case VT_GROUP:{
   3070 			VariableGroup *g = &var->group;
   3071 
   3072 			TableCell *cells = table_push_row(table, &arena, TRK_CELLS)->data;
   3073 			cells[0] = (TableCell){.text = var->name, .kind = TableCellKind_Variable, .var = var};
   3074 
   3075 			if (!g->expanded) {
   3076 				Stream sb = arena_stream(arena);
   3077 				stream_append_variable_group(&sb, var);
   3078 				cells[1].kind = TableCellKind_VariableGroup;
   3079 				cells[1].text = arena_stream_commit(&arena, &sb);
   3080 				cells[1].var  = var;
   3081 
   3082 				Variable *v = g->first;
   3083 				assert(!v || v->type == VT_BEAMFORMER_VARIABLE);
   3084 				/* NOTE(rnp): assume the suffix is the same for all elements */
   3085 				if (v) cells[2].text = v->beamformer_variable.suffix;
   3086 			}
   3087 		}break;
   3088 		InvalidDefaultCase;
   3089 		}
   3090 	}
   3091 
   3092 	v2 result = table_extent(table, arena, text_spec.font);
   3093 	draw_table(ui, arena, table, r, text_spec, mouse, 0);
   3094 	return result;
   3095 }
   3096 
   3097 function Rect
   3098 draw_ui_view_container(BeamformerUI *ui, Variable *var, v2 mouse, Rect bounds)
   3099 {
   3100 	UIView *fw = &var->view;
   3101 	Rect result = fw->rect;
   3102 	if (fw->rect.size.x > 0 && fw->rect.size.y > 0) {
   3103 		f32 line_height = (f32)ui->small_font.baseSize;
   3104 
   3105 		f32 pad = MAX(line_height + 5.0f, UI_REGION_PAD);
   3106 		if (fw->rect.pos.y < pad)
   3107 			fw->rect.pos.y += pad - fw->rect.pos.y;
   3108 		result = fw->rect;
   3109 
   3110 		f32 delta_x = (result.pos.x + result.size.x) - (bounds.size.x + bounds.pos.x);
   3111 		if (delta_x > 0) {
   3112 			result.pos.x -= delta_x;
   3113 			result.pos.x  = MAX(0, result.pos.x);
   3114 		}
   3115 
   3116 		Rect container = result;
   3117 		if (fw->close) {
   3118 			container.pos.y  -= 5 + line_height;
   3119 			container.size.y += 2 + line_height;
   3120 			Rect handle = {container.pos, (v2){.x = container.size.w, .y = 2 + line_height}};
   3121 			Rect close;
   3122 			hover_interaction(ui, mouse, auto_interaction(container, var));
   3123 			cut_rect_horizontal(handle, handle.size.w - handle.size.h - 6, 0, &close);
   3124 			close.size.w = close.size.h;
   3125 			DrawRectangleRounded(rl_rect(handle), 0.1f, 0, colour_from_normalized(BG_COLOUR));
   3126 			DrawRectangleRoundedLinesEx(rl_rect(handle), 0.2f, 0, 2, BLACK);
   3127 			draw_close_button(ui, fw->close, mouse, close, (v2){{0.45f, 0.45f}});
   3128 		} else {
   3129 			hover_interaction(ui, mouse, auto_interaction(container, var));
   3130 		}
   3131 		f32 roundness = 12.0f / fw->rect.size.y;
   3132 		DrawRectangleRounded(rl_rect(result), roundness / 2.0f, 0, colour_from_normalized(BG_COLOUR));
   3133 		DrawRectangleRoundedLinesEx(rl_rect(result), roundness, 0, 2, BLACK);
   3134 	}
   3135 	return result;
   3136 }
   3137 
   3138 function void
   3139 draw_ui_view(BeamformerUI *ui, Variable *ui_view, Rect r, v2 mouse, TextSpec text_spec)
   3140 {
   3141 	assert(ui_view->type == VT_UI_VIEW || ui_view->type == VT_UI_MENU || ui_view->type == VT_UI_TEXT_BOX);
   3142 
   3143 	UIView *view = &ui_view->view;
   3144 
   3145 	if (view->flags & UIViewFlag_Floating) {
   3146 		r = draw_ui_view_container(ui, ui_view, mouse, r);
   3147 	} else {
   3148 		if (view->rect.size.h - r.size.h < view->rect.pos.h)
   3149 			view->rect.pos.h = view->rect.size.h - r.size.h;
   3150 
   3151 		if (view->rect.size.h - r.size.h < 0)
   3152 			view->rect.pos.h = 0;
   3153 
   3154 		r.pos.y -= view->rect.pos.h;
   3155 	}
   3156 
   3157 	v2 size = {0};
   3158 
   3159 	Variable *var = view->child;
   3160 	switch (var->type) {
   3161 	case VT_GROUP:{
   3162 		if (ui_view->type == VT_UI_MENU)
   3163 			size = draw_ui_view_menu(ui, var, ui->arena, r, mouse, text_spec);
   3164 		else {
   3165 			size = draw_ui_view_listing(ui, var, ui->arena, r, mouse, text_spec);
   3166 		}
   3167 	}break;
   3168 	case VT_BEAMFORMER_FRAME_VIEW: {
   3169 		BeamformerFrameView *bv = var->generic;
   3170 		if (frame_view_ready_to_present(ui, bv)) {
   3171 			if (bv->kind == BeamformerFrameViewKind_3DXPlane)
   3172 				draw_3D_xplane_frame_view(ui, ui->arena, var, r, mouse);
   3173 			else
   3174 				draw_beamformer_frame_view(ui, ui->arena, var, r, mouse);
   3175 		}
   3176 	} break;
   3177 	case VT_COMPUTE_PROGRESS_BAR: {
   3178 		size = draw_compute_progress_bar(ui, &var->compute_progress_bar, r);
   3179 	} break;
   3180 	case VT_COMPUTE_STATS_VIEW:{ size = draw_compute_stats_view(ui, ui->arena, var, r, mouse); }break;
   3181 	case VT_LIVE_CONTROLS_VIEW:{
   3182 		if (view->rect.size.h - r.size.h < 0)
   3183 			r.pos.y += 0.5f * (r.size.h - view->rect.size.h);
   3184 		if (ui->shared_memory->live_imaging_parameters.active)
   3185 			size = draw_live_controls_view(ui, var, r, mouse, ui->arena);
   3186 	}break;
   3187 	InvalidDefaultCase;
   3188 	}
   3189 
   3190 	view->rect.size = size;
   3191 }
   3192 
   3193 function void
   3194 draw_layout_variable(BeamformerUI *ui, Variable *var, Rect draw_rect, v2 mouse)
   3195 {
   3196 	if (var->type != VT_UI_REGION_SPLIT) {
   3197 		v2 shrink = {.x = UI_REGION_PAD, .y = UI_REGION_PAD};
   3198 		draw_rect = shrink_rect_centered(draw_rect, shrink);
   3199 		draw_rect.size = v2_floor(draw_rect.size);
   3200 		BeginScissorMode((i32)draw_rect.pos.x, (i32)draw_rect.pos.y, (i32)draw_rect.size.w, (i32)draw_rect.size.h);
   3201 		draw_rect = draw_title_bar(ui, ui->arena, var, draw_rect, mouse);
   3202 		EndScissorMode();
   3203 	}
   3204 
   3205 	/* TODO(rnp): post order traversal of the ui tree will remove the need for this */
   3206 	if (!CheckCollisionPointRec(rl_v2(mouse), rl_rect(draw_rect)))
   3207 		mouse = (v2){.x = F32_INFINITY, .y = F32_INFINITY};
   3208 
   3209 	draw_rect.size = v2_floor(draw_rect.size);
   3210 	BeginScissorMode((i32)draw_rect.pos.x, (i32)draw_rect.pos.y, (i32)draw_rect.size.w, (i32)draw_rect.size.h);
   3211 	switch (var->type) {
   3212 	case VT_UI_VIEW: {
   3213 		hover_interaction(ui, mouse, auto_interaction(draw_rect, var));
   3214 		TextSpec text_spec = {.font = &ui->font, .colour = FG_COLOUR, .flags = TF_LIMITED};
   3215 		draw_ui_view(ui, var, draw_rect, mouse, text_spec);
   3216 	} break;
   3217 	case VT_UI_REGION_SPLIT: {
   3218 		RegionSplit *rs = &var->region_split;
   3219 
   3220 		Rect split = {0}, hover = {0};
   3221 		switch (rs->direction) {
   3222 		case RSD_VERTICAL: {
   3223 			split_rect_vertical(draw_rect, rs->fraction, 0, &split);
   3224 			split.pos.x  += UI_REGION_PAD;
   3225 			split.pos.y  -= UI_SPLIT_HANDLE_THICK / 2;
   3226 			split.size.h  = UI_SPLIT_HANDLE_THICK;
   3227 			split.size.w -= 2 * UI_REGION_PAD;
   3228 			hover = extend_rect_centered(split, (v2){.y = 0.75f * UI_REGION_PAD});
   3229 		} break;
   3230 		case RSD_HORIZONTAL: {
   3231 			split_rect_horizontal(draw_rect, rs->fraction, 0, &split);
   3232 			split.pos.x  -= UI_SPLIT_HANDLE_THICK / 2;
   3233 			split.pos.y  += UI_REGION_PAD;
   3234 			split.size.w  = UI_SPLIT_HANDLE_THICK;
   3235 			split.size.h -= 2 * UI_REGION_PAD;
   3236 			hover = extend_rect_centered(split, (v2){.x = 0.75f * UI_REGION_PAD});
   3237 		} break;
   3238 		}
   3239 
   3240 		Interaction drag = {.kind = InteractionKind_Drag, .rect = hover, .var = var};
   3241 		hover_interaction(ui, mouse, drag);
   3242 
   3243 		v4 colour = HOVERED_COLOUR;
   3244 		colour.a  = var->hover_t;
   3245 		DrawRectangleRounded(rl_rect(split), 0.6f, 0, colour_from_normalized(colour));
   3246 	} break;
   3247 	InvalidDefaultCase;
   3248 	}
   3249 	EndScissorMode();
   3250 }
   3251 
   3252 function void
   3253 draw_ui_regions(BeamformerUI *ui, Rect window, v2 mouse)
   3254 {
   3255 	struct region_frame {
   3256 		Variable *var;
   3257 		Rect      rect;
   3258 	} init[16];
   3259 
   3260 	struct {
   3261 		struct region_frame *data;
   3262 		iz count;
   3263 		iz capacity;
   3264 	} stack = {init, 0, ARRAY_COUNT(init)};
   3265 
   3266 	TempArena arena_savepoint = begin_temp_arena(&ui->arena);
   3267 
   3268 	*da_push(&ui->arena, &stack) = (struct region_frame){ui->regions, window};
   3269 	while (stack.count) {
   3270 		struct region_frame *top = stack.data + --stack.count;
   3271 		Rect rect = top->rect;
   3272 		draw_layout_variable(ui, top->var, rect, mouse);
   3273 
   3274 		if (top->var->type == VT_UI_REGION_SPLIT) {
   3275 			Rect first, second;
   3276 			RegionSplit *rs = &top->var->region_split;
   3277 			switch (rs->direction) {
   3278 			case RSD_VERTICAL: {
   3279 				split_rect_vertical(rect, rs->fraction, &first, &second);
   3280 			} break;
   3281 			case RSD_HORIZONTAL: {
   3282 				split_rect_horizontal(rect, rs->fraction, &first, &second);
   3283 			} break;
   3284 			}
   3285 
   3286 			*da_push(&ui->arena, &stack) = (struct region_frame){rs->right, second};
   3287 			*da_push(&ui->arena, &stack) = (struct region_frame){rs->left,  first};
   3288 		}
   3289 	}
   3290 
   3291 	end_temp_arena(arena_savepoint);
   3292 }
   3293 
   3294 function void
   3295 draw_floating_widgets(BeamformerUI *ui, Rect window_rect, v2 mouse)
   3296 {
   3297 	TextSpec text_spec = {.font = &ui->small_font, .colour = FG_COLOUR};
   3298 	window_rect = shrink_rect_centered(window_rect, (v2){{UI_REGION_PAD, UI_REGION_PAD}});
   3299 	for (Variable *var = ui->floating_widget_sentinal.parent;
   3300 	     var != &ui->floating_widget_sentinal;
   3301 	     var = var->parent)
   3302 	{
   3303 		if (var->type == VT_UI_TEXT_BOX) {
   3304 			UIView *fw = &var->view;
   3305 			InputState *is = &ui->text_input_state;
   3306 
   3307 			draw_ui_view_container(ui, var, mouse, fw->rect);
   3308 
   3309 			f32 cursor_width = (is->cursor == is->count) ? 0.55f * (f32)is->font->baseSize : 4.0f;
   3310 			s8 text      = {.len = is->count, .data = is->buf};
   3311 			v2 text_size = measure_text(*is->font, text);
   3312 
   3313 			f32 text_pad = 4.0f;
   3314 			f32 desired_width = text_pad + text_size.w + cursor_width;
   3315 			fw->rect.size = (v2){{MAX(desired_width, fw->rect.size.w), text_size.h + text_pad}};
   3316 
   3317 			v2 text_position   = {{fw->rect.pos.x + text_pad / 2, fw->rect.pos.y + text_pad / 2}};
   3318 			f32 cursor_offset  = measure_text(*is->font, (s8){is->cursor, text.data}).w;
   3319 			cursor_offset     += text_position.x;
   3320 
   3321 			Rect cursor;
   3322 			cursor.pos  = (v2){{cursor_offset, text_position.y}};
   3323 			cursor.size = (v2){{cursor_width,  text_size.h}};
   3324 
   3325 			v4 cursor_colour = FOCUSED_COLOUR;
   3326 			cursor_colour.a  = ease_in_out_cubic(is->cursor_blink.t);
   3327 			v4 text_colour   = v4_lerp(FG_COLOUR, HOVERED_COLOUR, fw->child->hover_t);
   3328 
   3329 			TextSpec input_text_spec = {.font = is->font, .colour = text_colour};
   3330 			draw_text(text, text_position, &input_text_spec);
   3331 			DrawRectanglePro(rl_rect(cursor), (Vector2){0}, 0, colour_from_normalized(cursor_colour));
   3332 		} else {
   3333 			draw_ui_view(ui, var, window_rect, mouse, text_spec);
   3334 		}
   3335 	}
   3336 }
   3337 
   3338 function void
   3339 scroll_interaction(Variable *var, f32 delta)
   3340 {
   3341 	switch (var->type) {
   3342 	case VT_B32:{ var->bool32  = !var->bool32; }break;
   3343 	case VT_F32:{ var->real32 += delta;        }break;
   3344 	case VT_I32:{ var->signed32 += (i32)delta; }break;
   3345 	case VT_SCALED_F32:{ var->scaled_real32.val += delta * var->scaled_real32.scale; }break;
   3346 	case VT_BEAMFORMER_FRAME_VIEW:{
   3347 		BeamformerFrameView *bv = var->generic;
   3348 		bv->threshold.real32 += delta;
   3349 		bv->dirty = 1;
   3350 	} break;
   3351 	case VT_BEAMFORMER_VARIABLE:{
   3352 		BeamformerVariable *bv = &var->beamformer_variable;
   3353 		f32 value  = *bv->store + delta * bv->scroll_scale;
   3354 		*bv->store = CLAMP(value, bv->limits.x, bv->limits.y);
   3355 	}break;
   3356 	case VT_CYCLER:{
   3357 		if (delta > 0) *var->cycler.state += 1;
   3358 		else           *var->cycler.state -= 1;
   3359 		*var->cycler.state %= var->cycler.cycle_length;
   3360 	}break;
   3361 	case VT_UI_VIEW:{
   3362 		var->view.rect.pos.h += UI_SCROLL_SPEED * delta;
   3363 		var->view.rect.pos.h  = MAX(0, var->view.rect.pos.h);
   3364 	}break;
   3365 	InvalidDefaultCase;
   3366 	}
   3367 }
   3368 
   3369 function void
   3370 begin_text_input(InputState *is, Rect r, Variable *container, v2 mouse)
   3371 {
   3372 	assert(container->type == VT_UI_TEXT_BOX);
   3373 	Font *font = is->font = is->hot_font;
   3374 	Stream s = {.cap = countof(is->buf), .data = is->buf};
   3375 	stream_append_variable(&s, container->view.child);
   3376 	is->count = s.widx;
   3377 	is->container = container;
   3378 
   3379 	is->numeric = container->view.child->type != VT_LIVE_CONTROLS_STRING;
   3380 	if (container->view.child->type == VT_LIVE_CONTROLS_STRING) {
   3381 		BeamformerLiveImagingParameters *lip = container->view.child->generic;
   3382 		if (lip->save_name_tag_length <= 0)
   3383 			is->count = 0;
   3384 	}
   3385 
   3386 	/* NOTE: extra offset to help with putting a cursor at idx 0 */
   3387 	f32 text_half_char_width = 10.0f;
   3388 	f32 hover_p = CLAMP01((mouse.x - r.pos.x) / r.size.w);
   3389 	i32 i;
   3390 	f32 x_off = text_half_char_width, x_bounds = r.size.w * hover_p;
   3391 	for (i = 0; i < is->count && x_off < x_bounds; i++) {
   3392 		/* NOTE: assumes font glyphs are ordered ASCII */
   3393 		i32 idx  = is->buf[i] - 0x20;
   3394 		x_off   += (f32)font->glyphs[idx].advanceX;
   3395 		if (font->glyphs[idx].advanceX == 0)
   3396 			x_off += font->recs[idx].width;
   3397 	}
   3398 	is->cursor = i;
   3399 }
   3400 
   3401 function void
   3402 end_text_input(InputState *is, Variable *var)
   3403 {
   3404 	f32 value = 0;
   3405 	if (is->numeric) value = (f32)parse_f64((s8){.len = is->count, .data = is->buf});
   3406 
   3407 	switch (var->type) {
   3408 	case VT_SCALED_F32:{ var->scaled_real32.val = value; }break;
   3409 	case VT_F32:{        var->real32            = value; }break;
   3410 	case VT_BEAMFORMER_VARIABLE:{
   3411 		BeamformerVariable *bv = &var->beamformer_variable;
   3412 		*bv->store = CLAMP(value / bv->display_scale, bv->limits.x, bv->limits.y);
   3413 		var->hover_t = 0;
   3414 	}break;
   3415 	case VT_LIVE_CONTROLS_STRING:{
   3416 		BeamformerLiveImagingParameters *lip = var->generic;
   3417 		mem_copy(lip->save_name_tag, is->buf, (uz)is->count % countof(lip->save_name_tag));
   3418 		lip->save_name_tag_length = is->count % countof(lip->save_name_tag);
   3419 	}break;
   3420 	InvalidDefaultCase;
   3421 	}
   3422 }
   3423 
   3424 function b32
   3425 update_text_input(InputState *is, Variable *var)
   3426 {
   3427 	assert(is->cursor != -1);
   3428 
   3429 	ui_blinker_update(&is->cursor_blink, BLINK_SPEED);
   3430 
   3431 	var->hover_t -= 2 * HOVER_SPEED * dt_for_frame;
   3432 	var->hover_t  = CLAMP01(var->hover_t);
   3433 
   3434 	/* NOTE: handle multiple input keys on a single frame */
   3435 	for (i32 key = GetCharPressed();
   3436 	     is->count < countof(is->buf) && key > 0;
   3437 	     key = GetCharPressed())
   3438 	{
   3439 		b32 allow_key = !is->numeric || (BETWEEN(key, '0', '9') || (key == '.') ||
   3440 		                 (key == '-' && is->cursor == 0));
   3441 		if (allow_key) {
   3442 			mem_move(is->buf + is->cursor + 1,
   3443 			         is->buf + is->cursor,
   3444 			         (uz)(is->count - is->cursor));
   3445 			is->buf[is->cursor++] = (u8)key;
   3446 			is->count++;
   3447 		}
   3448 	}
   3449 
   3450 	is->cursor -= (IsKeyPressed(KEY_LEFT)  || IsKeyPressedRepeat(KEY_LEFT))  && is->cursor > 0;
   3451 	is->cursor += (IsKeyPressed(KEY_RIGHT) || IsKeyPressedRepeat(KEY_RIGHT)) && is->cursor < is->count;
   3452 
   3453 	if ((IsKeyPressed(KEY_BACKSPACE) || IsKeyPressedRepeat(KEY_BACKSPACE)) && is->cursor > 0) {
   3454 		is->cursor--;
   3455 		if (is->cursor < countof(is->buf) - 1) {
   3456 			mem_move(is->buf + is->cursor,
   3457 			         is->buf + is->cursor + 1,
   3458 			         (uz)(is->count - is->cursor - 1));
   3459 		}
   3460 		is->count--;
   3461 	}
   3462 
   3463 	if ((IsKeyPressed(KEY_DELETE) || IsKeyPressedRepeat(KEY_DELETE)) && is->cursor < is->count) {
   3464 		mem_move(is->buf + is->cursor,
   3465 		         is->buf + is->cursor + 1,
   3466 		         (uz)(is->count - is->cursor - 1));
   3467 		is->count--;
   3468 	}
   3469 
   3470 	b32 result = IsKeyPressed(KEY_ENTER);
   3471 	return result;
   3472 }
   3473 
   3474 function void
   3475 scale_bar_interaction(BeamformerUI *ui, ScaleBar *sb, v2 mouse)
   3476 {
   3477 	Interaction *it = &ui->interaction;
   3478 	b32 mouse_left_pressed  = IsMouseButtonPressed(MOUSE_BUTTON_LEFT);
   3479 	b32 mouse_right_pressed = IsMouseButtonPressed(MOUSE_BUTTON_RIGHT);
   3480 	f32 mouse_wheel         = GetMouseWheelMoveV().y;
   3481 
   3482 	if (mouse_left_pressed) {
   3483 		v2 world_mouse = screen_point_to_world_2d(mouse, it->rect.pos,
   3484 		                                          v2_add(it->rect.pos, it->rect.size),
   3485 		                                          (v2){{*sb->min_value, *sb->min_value}},
   3486 		                                          (v2){{*sb->max_value, *sb->max_value}});
   3487 		f32 new_coord = F32_INFINITY;
   3488 		switch (sb->direction) {
   3489 		case SB_LATERAL: new_coord = world_mouse.x; break;
   3490 		case SB_AXIAL:   new_coord = world_mouse.y; break;
   3491 		}
   3492 		if (sb->zoom_starting_coord == F32_INFINITY) {
   3493 			sb->zoom_starting_coord = new_coord;
   3494 		} else {
   3495 			f32 min = sb->zoom_starting_coord;
   3496 			f32 max = new_coord;
   3497 			if (min > max) swap(min, max);
   3498 
   3499 			v2_sll *savepoint = SLLPopFreelist(ui->scale_bar_savepoint_freelist);
   3500 			if (!savepoint) savepoint = push_struct(&ui->arena, v2_sll);
   3501 
   3502 			savepoint->v.x = *sb->min_value;
   3503 			savepoint->v.y = *sb->max_value;
   3504 			SLLPush(savepoint, sb->savepoint_stack);
   3505 
   3506 			*sb->min_value = min;
   3507 			*sb->max_value = max;
   3508 
   3509 			sb->zoom_starting_coord = F32_INFINITY;
   3510 		}
   3511 	}
   3512 
   3513 	if (mouse_right_pressed) {
   3514 		v2_sll *savepoint = sb->savepoint_stack;
   3515 		if (savepoint) {
   3516 			*sb->min_value      = savepoint->v.x;
   3517 			*sb->max_value      = savepoint->v.y;
   3518 			sb->savepoint_stack = savepoint->next;
   3519 			SLLPushFreelist(savepoint, ui->scale_bar_savepoint_freelist);
   3520 		}
   3521 		sb->zoom_starting_coord = F32_INFINITY;
   3522 	}
   3523 
   3524 	if (mouse_wheel != 0) {
   3525 		*sb->min_value += mouse_wheel * sb->scroll_scale.x;
   3526 		*sb->max_value += mouse_wheel * sb->scroll_scale.y;
   3527 	}
   3528 }
   3529 
   3530 function void
   3531 ui_widget_bring_to_front(Variable *sentinal, Variable *widget)
   3532 {
   3533 	/* TODO(rnp): clean up the linkage so this can be a macro */
   3534 	widget->parent->next = widget->next;
   3535 	widget->next->parent = widget->parent;
   3536 
   3537 	widget->parent = sentinal;
   3538 	widget->next   = sentinal->next;
   3539 	widget->next->parent = widget;
   3540 	sentinal->next = widget;
   3541 }
   3542 
   3543 function void
   3544 ui_view_close(BeamformerUI *ui, Variable *view)
   3545 {
   3546 	switch (view->type) {
   3547 	case VT_UI_MENU:
   3548 	case VT_UI_TEXT_BOX:
   3549 	{
   3550 		UIView *fw = &view->view;
   3551 		if (view->type == VT_UI_MENU) {
   3552 			assert(fw->child->type == VT_GROUP);
   3553 			fw->child->group.expanded  = 0;
   3554 			fw->child->group.container = 0;
   3555 		} else {
   3556 			end_text_input(&ui->text_input_state, fw->child);
   3557 		}
   3558 		view->parent->next = view->next;
   3559 		view->next->parent = view->parent;
   3560 		if (fw->close) SLLPushFreelist(fw->close, ui->variable_freelist);
   3561 		SLLPushFreelist(view, ui->variable_freelist);
   3562 	}break;
   3563 	case VT_UI_VIEW:{
   3564 		assert(view->parent->type == VT_UI_REGION_SPLIT);
   3565 		Variable *region = view->parent;
   3566 
   3567 		Variable *parent    = region->parent;
   3568 		Variable *remaining = region->region_split.left;
   3569 		if (remaining == view) remaining = region->region_split.right;
   3570 
   3571 		ui_view_free(ui, view);
   3572 
   3573 		assert(parent->type == VT_UI_REGION_SPLIT);
   3574 		if (parent->region_split.left == region) {
   3575 			parent->region_split.left  = remaining;
   3576 		} else {
   3577 			parent->region_split.right = remaining;
   3578 		}
   3579 		remaining->parent = parent;
   3580 
   3581 		SLLPushFreelist(region, ui->variable_freelist);
   3582 	}break;
   3583 	InvalidDefaultCase;
   3584 	}
   3585 }
   3586 
   3587 function void
   3588 ui_button_interaction(BeamformerUI *ui, Variable *button)
   3589 {
   3590 	assert(button->type == VT_UI_BUTTON);
   3591 	switch (button->button) {
   3592 	case UI_BID_VIEW_CLOSE:{ ui_view_close(ui, button->parent); }break;
   3593 	case UI_BID_FV_COPY_HORIZONTAL:{
   3594 		ui_copy_frame(ui, button->parent->parent, RSD_HORIZONTAL);
   3595 	}break;
   3596 	case UI_BID_FV_COPY_VERTICAL:{
   3597 		ui_copy_frame(ui, button->parent->parent, RSD_VERTICAL);
   3598 	}break;
   3599 	case UI_BID_GM_OPEN_VIEW_RIGHT:{
   3600 		ui_add_live_frame_view(ui, button->parent->parent, RSD_HORIZONTAL, BeamformerFrameViewKind_Latest);
   3601 	}break;
   3602 	case UI_BID_GM_OPEN_VIEW_BELOW:{
   3603 		ui_add_live_frame_view(ui, button->parent->parent, RSD_VERTICAL, BeamformerFrameViewKind_Latest);
   3604 	}break;
   3605 	}
   3606 }
   3607 
   3608 function void
   3609 ui_begin_interact(BeamformerUI *ui, v2 mouse, b32 scroll)
   3610 {
   3611 	Interaction hot = ui->hot_interaction;
   3612 	if (hot.kind != InteractionKind_None) {
   3613 		if (hot.kind == InteractionKind_Auto) {
   3614 			switch (hot.var->type) {
   3615 			case VT_NULL:{ hot.kind = InteractionKind_Nop; }break;
   3616 			case VT_B32:{ hot.kind  = InteractionKind_Set; }break;
   3617 			case VT_SCALE_BAR:{ hot.kind = InteractionKind_Set; }break;
   3618 			case VT_UI_BUTTON:{ hot.kind = InteractionKind_Button; }break;
   3619 			case VT_GROUP:{ hot.kind = InteractionKind_Set; }break;
   3620 			case VT_UI_TEXT_BOX:
   3621 			case VT_UI_MENU:
   3622 			{
   3623 				if (hot.var->type == VT_UI_MENU) {
   3624 					hot.kind = InteractionKind_Drag;
   3625 				} else {
   3626 					hot.kind = InteractionKind_Text;
   3627 					begin_text_input(&ui->text_input_state, hot.rect, hot.var, mouse);
   3628 				}
   3629 				ui_widget_bring_to_front(&ui->floating_widget_sentinal, hot.var);
   3630 
   3631 				// TODO(rnp): hack. this won't be needed with a proper immediate mode UI
   3632 				if (ui->interaction.kind == InteractionKind_Text)
   3633 					hot.var = hot.var->view.child;
   3634 			}break;
   3635 			case VT_UI_VIEW:{
   3636 				if (scroll) hot.kind = InteractionKind_Scroll;
   3637 				else        hot.kind = InteractionKind_Nop;
   3638 			}break;
   3639 			case VT_X_PLANE_SHIFT:{
   3640 				assert(hot.var->parent && hot.var->parent->type == VT_BEAMFORMER_FRAME_VIEW);
   3641 				BeamformerFrameView *bv = hot.var->parent->generic;
   3642 				if (IsMouseButtonDown(MOUSE_BUTTON_LEFT)) {
   3643 					XPlaneShift *xp = &hot.var->x_plane_shift;
   3644 					xp->start_point = xp->end_point = bv->hit_test_point;
   3645 					hot.kind = InteractionKind_Drag;
   3646 				} else {
   3647 					if (scroll) {
   3648 						hot.kind = InteractionKind_Scroll;
   3649 						hot.var  = &bv->threshold;
   3650 					} else {
   3651 						hot.kind = InteractionKind_Nop;
   3652 					}
   3653 				}
   3654 			}break;
   3655 			case VT_BEAMFORMER_FRAME_VIEW:{
   3656 				if (scroll) {
   3657 					hot.kind = InteractionKind_Scroll;
   3658 				} else {
   3659 					BeamformerFrameView *bv = hot.var->generic;
   3660 					switch (bv->kind) {
   3661 					case BeamformerFrameViewKind_3DXPlane:{ hot.kind = InteractionKind_Drag; }break;
   3662 					default:{
   3663 						hot.kind = InteractionKind_Nop;
   3664 						switch (++bv->ruler.state) {
   3665 						case RulerState_Start:{
   3666 							hot.kind = InteractionKind_Ruler;
   3667 							bv->ruler.start = world_point_from_plane_uv(bv->frame->voxel_transform,
   3668 							                                            rect_uv(mouse, hot.rect));
   3669 						}break;
   3670 						case RulerState_Hold:{}break;
   3671 						default:{ bv->ruler.state = RulerState_None; }break;
   3672 						}
   3673 					}break;
   3674 					}
   3675 				}
   3676 			}break;
   3677 			case VT_CYCLER:{
   3678 				if (scroll) hot.kind = InteractionKind_Scroll;
   3679 				else        hot.kind = InteractionKind_Set;
   3680 			}break;
   3681 			case VT_BEAMFORMER_VARIABLE:
   3682 			case VT_LIVE_CONTROLS_STRING:
   3683 			case VT_F32:
   3684 			case VT_SCALED_F32:
   3685 			{
   3686 				if (scroll) {
   3687 					hot.kind = InteractionKind_Scroll;
   3688 				} else if (hot.var->flags & V_TEXT) {
   3689 					hot.kind = InteractionKind_Text;
   3690 					Variable *w = add_floating_view(ui, &ui->arena, VT_UI_TEXT_BOX,
   3691 					                                hot.rect.pos, hot.var, 0);
   3692 					w->view.rect = hot.rect;
   3693 					begin_text_input(&ui->text_input_state, hot.rect, w, mouse);
   3694 				} else {
   3695 					hot.kind = InteractionKind_Drag;
   3696 				}
   3697 			}break;
   3698 			InvalidDefaultCase;
   3699 			}
   3700 		}
   3701 
   3702 		ui->interaction = hot;
   3703 
   3704 		if (ui->interaction.var->flags & V_LIVE_CONTROL) {
   3705 			assert(ui->interaction.var->parent->type == VT_LIVE_CONTROLS_VIEW);
   3706 			BeamformerLiveControlsView *lv = ui->interaction.var->parent->generic;
   3707 			lv->active_field_flag = lv->hot_field_flag;
   3708 		}
   3709 
   3710 		if (ui->interaction.var->flags & V_HIDES_CURSOR) {
   3711 			HideCursor();
   3712 			DisableCursor();
   3713 			/* wtf raylib */
   3714 			SetMousePosition((i32)mouse.x, (i32)mouse.y);
   3715 		}
   3716 	} else {
   3717 		ui->interaction.kind = InteractionKind_Nop;
   3718 	}
   3719 }
   3720 
   3721 function u32
   3722 ui_cycler_delta_for_frame(void)
   3723 {
   3724 	u32 result = (u32)GetMouseWheelMoveV().y;
   3725 	if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT))  result += 1;
   3726 	if (IsMouseButtonPressed(MOUSE_BUTTON_RIGHT)) result -= 1;
   3727 	return result;
   3728 }
   3729 
   3730 function void
   3731 ui_extra_actions(BeamformerUI *ui, Variable *var)
   3732 {
   3733 	switch (var->type) {
   3734 	case VT_CYCLER:{
   3735 		assert(var->parent && var->parent->parent && var->parent->parent->type == VT_UI_VIEW);
   3736 		Variable *view_var = var->parent->parent;
   3737 		UIView   *view     = &view_var->view;
   3738 		switch (view->child->type) {
   3739 		case VT_BEAMFORMER_FRAME_VIEW:{
   3740 			u32 delta = ui_cycler_delta_for_frame();
   3741 			BeamformerFrameView *old = view->child->generic;
   3742 			BeamformerFrameView *new = view->child->generic = ui_beamformer_frame_view_new(ui, &ui->arena);
   3743 			BeamformerFrameViewKind last_kind = (old->kind - delta) % BeamformerFrameViewKind_Count;
   3744 
   3745 			/* NOTE(rnp): log_scale gets released below before its needed */
   3746 			b32 log_scale = old->log_scale->bool32;
   3747 			ui_variable_free_group_items(ui, view->menu);
   3748 
   3749 			ui_beamformer_frame_view_release_subresources(ui, old, last_kind);
   3750 			ui_beamformer_frame_view_convert(ui, &ui->arena, view->child, view->menu, old->kind, old, log_scale);
   3751 			if (new->kind == BeamformerFrameViewKind_Copy && old->frame)
   3752 				ui_beamformer_frame_view_copy_frame(ui, new, old);
   3753 
   3754 			DLLRemove(old);
   3755 			SLLPushFreelist(old, ui->view_freelist);
   3756 		}break;
   3757 		InvalidDefaultCase;
   3758 		}
   3759 	}break;
   3760 	InvalidDefaultCase;
   3761 	}
   3762 }
   3763 
   3764 function void
   3765 ui_live_control_update(BeamformerUI *ui, Variable *controls)
   3766 {
   3767 	assert(controls->type == VT_LIVE_CONTROLS_VIEW);
   3768 	BeamformerLiveControlsView *lv = controls->generic;
   3769 	atomic_or_u32(&ui->shared_memory->live_imaging_dirty_flags, lv->active_field_flag);
   3770 }
   3771 
   3772 function void
   3773 ui_end_interact(BeamformerUI *ui, v2 mouse)
   3774 {
   3775 	Interaction *it = &ui->interaction;
   3776 	Variable *parent = it->var->parent;
   3777 	u32 flags = it->var->flags;
   3778 
   3779 	switch (it->kind) {
   3780 	case InteractionKind_Nop:{}break;
   3781 	case InteractionKind_Drag:{
   3782 		switch (it->var->type) {
   3783 		case VT_X_PLANE_SHIFT:{
   3784 			assert(parent && parent->type == VT_BEAMFORMER_FRAME_VIEW);
   3785 			XPlaneShift *xp = &it->var->x_plane_shift;
   3786 			BeamformerFrameView *view = parent->generic;
   3787 			BeamformerViewPlaneTag plane = view_plane_tag_from_x_plane_shift(view, it->var);
   3788 			f32 rotation  = x_plane_rotation_for_view_plane(view, plane);
   3789 			m4 x_rotation = m4_rotation_about_y(rotation);
   3790 			v3 Z = x_rotation.c[2].xyz;
   3791 			f32 delta = v3_dot(Z, v3_sub(xp->end_point, xp->start_point));
   3792 			xp->start_point = xp->end_point;
   3793 
   3794 			BeamformerSharedMemory *          sm = ui->shared_memory;
   3795 			BeamformerLiveImagingParameters * li = &sm->live_imaging_parameters;
   3796 			li->image_plane_offsets[plane] += delta;
   3797 			atomic_or_u32(&sm->live_imaging_dirty_flags, BeamformerLiveImagingDirtyFlags_ImagePlaneOffsets);
   3798 		}break;
   3799 		default:{}break;
   3800 		}
   3801 	}break;
   3802 	case InteractionKind_Set:{
   3803 		switch (it->var->type) {
   3804 		case VT_B32:{ it->var->bool32 = !it->var->bool32; }break;
   3805 		case VT_GROUP:{ it->var->group.expanded = !it->var->group.expanded; }break;
   3806 		case VT_SCALE_BAR:{ scale_bar_interaction(ui, &it->var->scale_bar, mouse); }break;
   3807 		case VT_CYCLER:{
   3808 			*it->var->cycler.state += ui_cycler_delta_for_frame();
   3809 			*it->var->cycler.state %= it->var->cycler.cycle_length;
   3810 		}break;
   3811 		InvalidDefaultCase;
   3812 		}
   3813 	}break;
   3814 	case InteractionKind_Menu:{
   3815 		assert(it->var->type == VT_GROUP);
   3816 		VariableGroup *g = &it->var->group;
   3817 		if (g->container) {
   3818 			ui_widget_bring_to_front(&ui->floating_widget_sentinal, g->container);
   3819 		} else {
   3820 			g->container = add_floating_view(ui, &ui->arena, VT_UI_MENU, mouse, it->var, 1);
   3821 		}
   3822 	}break;
   3823 	case InteractionKind_Ruler:{
   3824 		assert(it->var->type == VT_BEAMFORMER_FRAME_VIEW);
   3825 		((BeamformerFrameView *)it->var->generic)->ruler.state = RulerState_None;
   3826 	}break;
   3827 	case InteractionKind_Button:{ ui_button_interaction(ui, it->var); }break;
   3828 	case InteractionKind_Scroll:{ scroll_interaction(it->var, GetMouseWheelMoveV().y); }break;
   3829 	case InteractionKind_Text:{ ui_view_close(ui, ui->text_input_state.container); }break;
   3830 	InvalidDefaultCase;
   3831 	}
   3832 
   3833 	if (flags & V_CAUSES_COMPUTE)
   3834 		ui->flush_params = 1;
   3835 
   3836 	if (flags & V_UPDATE_VIEW) {
   3837 		BeamformerFrameView *frame = parent->generic;
   3838 		/* TODO(rnp): more straight forward way of achieving this */
   3839 		if (parent->type != VT_BEAMFORMER_FRAME_VIEW) {
   3840 			assert(parent->parent->type == VT_UI_VIEW);
   3841 			assert(parent->parent->view.child->type == VT_BEAMFORMER_FRAME_VIEW);
   3842 			frame = parent->parent->view.child->generic;
   3843 		}
   3844 		frame->dirty = 1;
   3845 	}
   3846 
   3847 	if (flags & V_LIVE_CONTROL)
   3848 		ui_live_control_update(ui, it->var->parent);
   3849 
   3850 	if (flags & V_HIDES_CURSOR)
   3851 		EnableCursor();
   3852 
   3853 	if (flags & V_EXTRA_ACTION)
   3854 		ui_extra_actions(ui, it->var);
   3855 
   3856 	ui->interaction = (Interaction){.kind = InteractionKind_None};
   3857 }
   3858 
   3859 function void
   3860 ui_sticky_interaction_check_end(BeamformerUI *ui, v2 mouse)
   3861 {
   3862 	Interaction *it = &ui->interaction;
   3863 	switch (it->kind) {
   3864 	case InteractionKind_Ruler:{
   3865 		if (IsMouseButtonPressed(MOUSE_BUTTON_RIGHT) || !point_in_rect(mouse, it->rect))
   3866 			ui_end_interact(ui, mouse);
   3867 	}break;
   3868 	case InteractionKind_Text:{
   3869 		Interaction text_box = auto_interaction({0}, ui->text_input_state.container);
   3870 		if (!interactions_equal(text_box, ui->hot_interaction))
   3871 			ui_end_interact(ui, mouse);
   3872 	}break;
   3873 	InvalidDefaultCase;
   3874 	}
   3875 }
   3876 
   3877 function void
   3878 ui_interact(BeamformerUI *ui, BeamformerInput *input, Rect window_rect)
   3879 {
   3880 	v2 input_mouse = {{input->mouse_x, input->mouse_y}};
   3881 	v2 last_mouse  = {{input->last_mouse_x, input->last_mouse_y}};
   3882 	Interaction *it = &ui->interaction;
   3883 	if (it->kind == InteractionKind_None || interaction_is_sticky(*it)) {
   3884 		ui->hot_interaction = ui->next_interaction;
   3885 
   3886 		b32 mouse_left_pressed  = IsMouseButtonPressed(MOUSE_BUTTON_LEFT);
   3887 		b32 mouse_right_pressed = IsMouseButtonPressed(MOUSE_BUTTON_RIGHT);
   3888 		b32 wheel_moved         = GetMouseWheelMoveV().y != 0;
   3889 		if (mouse_right_pressed || mouse_left_pressed || wheel_moved) {
   3890 			if (it->kind != InteractionKind_None)
   3891 				ui_sticky_interaction_check_end(ui, input_mouse);
   3892 			ui_begin_interact(ui, input_mouse, wheel_moved);
   3893 		}
   3894 	}
   3895 
   3896 	switch (it->kind) {
   3897 	case InteractionKind_Nop:{ it->kind = InteractionKind_None; }break;
   3898 	case InteractionKind_None:{}break;
   3899 	case InteractionKind_Text:{
   3900 		if (update_text_input(&ui->text_input_state, it->var))
   3901 			ui_end_interact(ui, input_mouse);
   3902 	}break;
   3903 	case InteractionKind_Ruler:{
   3904 		assert(it->var->type == VT_BEAMFORMER_FRAME_VIEW);
   3905 		BeamformerFrameView *bv = it->var->generic;
   3906 		v2 mouse = clamp_v2_rect(input_mouse, it->rect);
   3907 		bv->ruler.end = world_point_from_plane_uv(bv->frame->voxel_transform, rect_uv(mouse, it->rect));
   3908 	}break;
   3909 	case InteractionKind_Drag:{
   3910 		if (!IsMouseButtonDown(MOUSE_BUTTON_LEFT) && !IsMouseButtonDown(MOUSE_BUTTON_RIGHT)) {
   3911 			ui_end_interact(ui, input_mouse);
   3912 		} else {
   3913 			v2 ws     = window_rect.size;
   3914 			v2 dMouse = v2_sub(input_mouse, last_mouse);
   3915 
   3916 			switch (it->var->type) {
   3917 			case VT_BEAMFORMER_VARIABLE:{
   3918 				BeamformerVariable *bv = &it->var->beamformer_variable;
   3919 				/* TODO(rnp): vertical sliders? */
   3920 				f32 mouse_frac = CLAMP01((input_mouse.x - it->rect.pos.x) / it->rect.size.w);
   3921 				*bv->store     = bv->limits.x + mouse_frac * (bv->limits.y - bv->limits.x);
   3922 			}break;
   3923 			case VT_X_PLANE_SHIFT:{
   3924 				assert(it->var->parent && it->var->parent->type == VT_BEAMFORMER_FRAME_VIEW);
   3925 				v2 mouse = clamp_v2_rect(input_mouse, it->rect);
   3926 				XPlaneShift *xp = &it->var->x_plane_shift;
   3927 				ray mouse_ray = ray_for_x_plane_view(ui, it->var->parent->generic,
   3928 				                                     normalized_p_in_rect(it->rect, mouse, 0));
   3929 				/* NOTE(rnp): project start point onto ray */
   3930 				v3 s = v3_sub(xp->start_point, mouse_ray.origin);
   3931 				v3 r = v3_sub(mouse_ray.direction, mouse_ray.origin);
   3932 				f32 scale     = v3_dot(s, r) / v3_magnitude_squared(r);
   3933 				xp->end_point = v3_add(mouse_ray.origin, v3_scale(r, scale));
   3934 			}break;
   3935 			case VT_BEAMFORMER_FRAME_VIEW:{
   3936 				BeamformerFrameView *bv = it->var->generic;
   3937 				switch (bv->kind) {
   3938 				case BeamformerFrameViewKind_3DXPlane:{
   3939 					bv->rotation -= dMouse.x / ws.w;
   3940 					if (bv->rotation > 1.0f) bv->rotation -= 1.0f;
   3941 					if (bv->rotation < 0.0f) bv->rotation += 1.0f;
   3942 				}break;
   3943 				InvalidDefaultCase;
   3944 				}
   3945 			}break;
   3946 			case VT_UI_MENU:{
   3947 				v2 *pos = &ui->interaction.var->view.rect.pos;
   3948 				*pos = clamp_v2_rect(v2_add(*pos, dMouse), window_rect);
   3949 			}break;
   3950 			case VT_UI_REGION_SPLIT:{
   3951 				f32 min_fraction = 0;
   3952 				dMouse = v2_mul(dMouse, (v2){{1.0f / ws.w, 1.0f / ws.h}});
   3953 				RegionSplit *rs = &ui->interaction.var->region_split;
   3954 				switch (rs->direction) {
   3955 				case RSD_VERTICAL: {
   3956 					min_fraction  = (UI_SPLIT_HANDLE_THICK + 0.5f * UI_REGION_PAD) / ws.h;
   3957 					rs->fraction += dMouse.y;
   3958 				} break;
   3959 				case RSD_HORIZONTAL: {
   3960 					min_fraction  = (UI_SPLIT_HANDLE_THICK + 0.5f * UI_REGION_PAD) / ws.w;
   3961 					rs->fraction += dMouse.x;
   3962 				} break;
   3963 				}
   3964 				rs->fraction = CLAMP(rs->fraction, min_fraction, 1 - min_fraction);
   3965 			}break;
   3966 			default:{}break;
   3967 			}
   3968 			if (it->var->flags & V_LIVE_CONTROL)
   3969 				ui_live_control_update(ui, it->var->parent);
   3970 		}
   3971 	} break;
   3972 	default:{ ui_end_interact(ui, input_mouse); }break;
   3973 	}
   3974 
   3975 	ui->next_interaction = (Interaction){.kind = InteractionKind_None};
   3976 }
   3977 
   3978 /* NOTE(rnp): this only exists to make asan less annoying. do not waste
   3979  * people's time by freeing, closing, etc... */
   3980 DEBUG_EXPORT BEAMFORMER_DEBUG_UI_DEINIT_FN(beamformer_debug_ui_deinit)
   3981 {
   3982 #if ASAN_ACTIVE
   3983 	BeamformerUI *ui = ctx->ui;
   3984 	UnloadFont(ui->font);
   3985 	UnloadFont(ui->small_font);
   3986 	CloseWindow();
   3987 #endif
   3988 }
   3989 
   3990 function void
   3991 ui_init(BeamformerCtx *ctx, Arena store)
   3992 {
   3993 	BeamformerUI *ui = ctx->ui;
   3994 	if (!ui) {
   3995 		ui = ctx->ui = push_struct(&store, typeof(*ui));
   3996 		ui->arena = store;
   3997 		ui->frame_view_render_context = &ctx->frame_view_render_context;
   3998 		ui->unit_cube_model = ctx->compute_context.unit_cube_model;
   3999 		ui->shared_memory   = ctx->shared_memory;
   4000 		ui->beamformer_context = ctx;
   4001 
   4002 		/* TODO(rnp): better font, this one is jank at small sizes */
   4003 		ui->font       = LoadFontFromMemory(".ttf", beamformer_base_font, sizeof(beamformer_base_font), 28, 0, 0);
   4004 		ui->small_font = LoadFontFromMemory(".ttf", beamformer_base_font, sizeof(beamformer_base_font), 20, 0, 0);
   4005 
   4006 		ui->floating_widget_sentinal.parent = &ui->floating_widget_sentinal;
   4007 		ui->floating_widget_sentinal.next   = &ui->floating_widget_sentinal;
   4008 
   4009 		Variable *split = ui->regions = add_ui_split(ui, 0, &ui->arena, s8("UI Root"), 0.36f,
   4010 		                                             RSD_HORIZONTAL, ui->font);
   4011 		split->region_split.left = add_ui_split(ui, split, &ui->arena, s8(""), 0.475f,
   4012 		                                        RSD_VERTICAL, ui->font);
   4013 
   4014 		split = split->region_split.right = add_ui_split(ui, split, &ui->arena, s8(""), 0.70f,
   4015 		                                                 RSD_HORIZONTAL, ui->font);
   4016 		{
   4017 			split->region_split.left  = add_beamformer_frame_view(ui, split, &ui->arena,
   4018 			                                                      BeamformerFrameViewKind_Latest, 0, 0);
   4019 			split->region_split.right = add_live_controls_view(ui, split, &ui->arena);
   4020 		}
   4021 		split = split->parent;
   4022 
   4023 		split = split->region_split.left;
   4024 		split->region_split.left  = add_beamformer_parameters_view(split, ctx);
   4025 		split->region_split.right = add_ui_split(ui, split, &ui->arena, s8(""), 0.22f,
   4026 		                                         RSD_VERTICAL, ui->font);
   4027 		split = split->region_split.right;
   4028 
   4029 		split->region_split.left  = add_compute_progress_bar(split, ctx);
   4030 		split->region_split.right = add_compute_stats_view(ui, split, &ui->arena, ctx);
   4031 
   4032 		/* NOTE(rnp): shrink variable size once this fires */
   4033 		assert((uz)(ui->arena.beg - (u8 *)ui) < KB(64));
   4034 	}
   4035 }
   4036 
   4037 function void
   4038 validate_ui_parameters(BeamformerUI *ui)
   4039 {
   4040 	if (ui->min_coordinate.x > ui->max_coordinate.x)
   4041 		swap(ui->min_coordinate.x, ui->max_coordinate.x);
   4042 	if (ui->min_coordinate.z > ui->max_coordinate.z)
   4043 		swap(ui->min_coordinate.z, ui->max_coordinate.z);
   4044 }
   4045 
   4046 function void
   4047 draw_ui(BeamformerCtx *ctx, BeamformerInput *input, BeamformerFrame *frame_to_draw, BeamformerViewPlaneTag frame_plane)
   4048 {
   4049 	BeamformerUI *ui = ctx->ui;
   4050 
   4051 	ui->latest_plane[BeamformerViewPlaneTag_Count] = frame_to_draw;
   4052 	ui->latest_plane[frame_plane]                  = frame_to_draw;
   4053 
   4054 	asan_poison_region(ui->arena.beg, ui->arena.end - ui->arena.beg);
   4055 
   4056 	u32 selected_block = ui->selected_parameter_block % BeamformerMaxParameterBlockSlots;
   4057 	u32 selected_mask  = 1 << selected_block;
   4058 	if (ctx->ui_dirty_parameter_blocks & selected_mask) {
   4059 		BeamformerParameterBlock *pb = beamformer_parameter_block_lock(ui->shared_memory, selected_block, 0);
   4060 		if (pb) {
   4061 			ui->flush_params = 0;
   4062 
   4063 			mem_copy(&ui->params, &pb->parameters_ui, sizeof(ui->params));
   4064 			mem_copy(ui->das_transform.E, pb->parameters.das_voxel_transform.E, sizeof(ui->das_transform));
   4065 
   4066 			atomic_and_u32(&ctx->ui_dirty_parameter_blocks, ~selected_mask);
   4067 			beamformer_parameter_block_unlock(ui->shared_memory, selected_block);
   4068 
   4069 			ui->min_coordinate = m4_mul_v4(ui->das_transform, (v4){{0.0f, 0.0f, 0.0f, 1.0f}}).xyz;
   4070 			ui->max_coordinate = m4_mul_v4(ui->das_transform, (v4){{1.0f, 1.0f, 1.0f, 1.0f}}).xyz;
   4071 		}
   4072 	}
   4073 
   4074 	/* NOTE: process interactions first because the user interacted with
   4075 	 * the ui that was presented last frame */
   4076 	Rect window_rect = {.size = {{(f32)ctx->window_size.w, (f32)ctx->window_size.h}}};
   4077 	ui_interact(ui, input, window_rect);
   4078 
   4079 	if (ui->flush_params) {
   4080 		validate_ui_parameters(ui);
   4081 		if (ctx->latest_frame) {
   4082 			BeamformerParameterBlock *pb = beamformer_parameter_block_lock(ui->shared_memory, selected_block, 0);
   4083 			if (pb) {
   4084 				ui->flush_params = 0;
   4085 
   4086 				v3 min_coordinate = ui->min_coordinate;
   4087 				v3 max_coordinate = ui->max_coordinate;
   4088 
   4089 				iv3 points    = ctx->latest_frame->dim;
   4090 				i32 dimension = iv3_dimension(points);
   4091 
   4092 				// TODO(rnp): this is immediate mode code that should be in the ui building code
   4093 				swap(min_coordinate.y, min_coordinate.z);
   4094 				swap(max_coordinate.y, max_coordinate.z);
   4095 				m4  new_transform = das_transform(min_coordinate, max_coordinate, &points);
   4096 				switch (dimension) {
   4097 				case 1:{}break;
   4098 
   4099 				case 2:{
   4100 					v3 U = ui->das_transform.c[0].xyz;
   4101 					v3 V = ui->das_transform.c[1].xyz;
   4102 					v3 N = v3_normalize(cross(V, U));
   4103 
   4104 					v3 rotation_axis = v3_normalize(cross(U, N));
   4105 
   4106 					m4 T = m4_translation(v3_scale(N, ui->off_axis_position));
   4107 					m4 R = m4_rotation_about_axis(rotation_axis, ui->beamform_plane);
   4108 
   4109 					new_transform = m4_mul(R, m4_mul(T, new_transform));
   4110 				}break;
   4111 
   4112 				case 3:{
   4113 				}break;
   4114 				}
   4115 
   4116 				// TODO(rnp): super janky code because of the retained mode parameters list.
   4117 				// when this code is run in the correct place we can just decide inline
   4118 				b32 recompute = 0;
   4119 				for EachElement(new_transform.E, it)
   4120 					recompute |= !f32_equal(new_transform.E[it], pb->parameters.das_voxel_transform.E[it]);
   4121 				recompute |= !memory_equal(&pb->parameters_ui, &ui->params, sizeof(ui->params));
   4122 
   4123 				mem_copy(&pb->parameters_ui, &ui->params, sizeof(ui->params));
   4124 				mem_copy(pb->parameters.das_voxel_transform.E, new_transform.E, sizeof(new_transform));
   4125 
   4126 				mark_parameter_block_region_dirty(ui->shared_memory, selected_block,
   4127 				                                  BeamformerParameterBlockRegion_Parameters);
   4128 				beamformer_parameter_block_unlock(ui->shared_memory, selected_block);
   4129 
   4130 				if (recompute)
   4131 					beamformer_queue_compute(ctx, frame_to_draw, selected_block);
   4132 			}
   4133 		}
   4134 	}
   4135 
   4136 	/* NOTE(rnp): can't render to a different framebuffer in the middle of BeginDrawing()... */
   4137 	update_frame_views(ui, window_rect);
   4138 
   4139 	BeginDrawing();
   4140 		v2 mouse = {{input->mouse_x, input->mouse_y}};
   4141 		glClearNamedFramebufferfv(0, GL_COLOR, 0, BG_COLOUR.E);
   4142 		glClearNamedFramebufferfv(0, GL_DEPTH, 0, (f32 []){1});
   4143 
   4144 		draw_ui_regions(ui, window_rect, mouse);
   4145 		draw_floating_widgets(ui, window_rect, mouse);
   4146 	EndDrawing();
   4147 }