hud_context.c revision 848b8605
1/**************************************************************************
2 *
3 * Copyright 2013 Marek Olšák <maraeo@gmail.com>
4 * All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sub license, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * The above copyright notice and this permission notice (including the
15 * next paragraph) shall be included in all copies or substantial portions
16 * of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
21 * IN NO EVENT SHALL THE AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR
22 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 *
26 **************************************************************************/
27
28/* This head-up display module can draw transparent graphs on top of what
29 * the app is rendering, visualizing various data like framerate, cpu load,
30 * performance counters, etc. It can be hook up into any state tracker.
31 *
32 * The HUD is controlled with the GALLIUM_HUD environment variable.
33 * Set GALLIUM_HUD=help for more info.
34 */
35
36#include <stdio.h>
37
38#include "hud/hud_context.h"
39#include "hud/hud_private.h"
40#include "hud/font.h"
41
42#include "cso_cache/cso_context.h"
43#include "util/u_draw_quad.h"
44#include "util/u_inlines.h"
45#include "util/u_memory.h"
46#include "util/u_math.h"
47#include "util/u_simple_shaders.h"
48#include "util/u_string.h"
49#include "util/u_upload_mgr.h"
50#include "tgsi/tgsi_text.h"
51#include "tgsi/tgsi_dump.h"
52
53
54struct hud_context {
55   struct pipe_context *pipe;
56   struct cso_context *cso;
57   struct u_upload_mgr *uploader;
58
59   struct list_head pane_list;
60
61   /* states */
62   struct pipe_blend_state alpha_blend;
63   struct pipe_depth_stencil_alpha_state dsa;
64   void *fs_color, *fs_text;
65   struct pipe_rasterizer_state rasterizer;
66   void *vs;
67   struct pipe_vertex_element velems[2];
68
69   /* font */
70   struct util_font font;
71   struct pipe_sampler_view *font_sampler_view;
72   struct pipe_sampler_state font_sampler_state;
73
74   /* VS constant buffer */
75   struct {
76      float color[4];
77      float two_div_fb_width;
78      float two_div_fb_height;
79      float translate[2];
80      float scale[2];
81      float padding[2];
82   } constants;
83   struct pipe_constant_buffer constbuf;
84
85   unsigned fb_width, fb_height;
86
87   /* vertices for text and background drawing are accumulated here and then
88    * drawn all at once */
89   struct vertex_queue {
90      float *vertices;
91      struct pipe_vertex_buffer vbuf;
92      unsigned max_num_vertices;
93      unsigned num_vertices;
94   } text, bg, whitelines;
95};
96
97
98static void
99hud_draw_colored_prims(struct hud_context *hud, unsigned prim,
100                       float *buffer, unsigned num_vertices,
101                       float r, float g, float b, float a,
102                       int xoffset, int yoffset, float yscale)
103{
104   struct cso_context *cso = hud->cso;
105   struct pipe_vertex_buffer vbuffer = {0};
106
107   hud->constants.color[0] = r;
108   hud->constants.color[1] = g;
109   hud->constants.color[2] = b;
110   hud->constants.color[3] = a;
111   hud->constants.translate[0] = (float) xoffset;
112   hud->constants.translate[1] = (float) yoffset;
113   hud->constants.scale[0] = 1;
114   hud->constants.scale[1] = yscale;
115   cso_set_constant_buffer(cso, PIPE_SHADER_VERTEX, 0, &hud->constbuf);
116
117   vbuffer.user_buffer = buffer;
118   vbuffer.stride = 2 * sizeof(float);
119
120   cso_set_vertex_buffers(cso, cso_get_aux_vertex_buffer_slot(cso),
121                          1, &vbuffer);
122   cso_set_fragment_shader_handle(hud->cso, hud->fs_color);
123   cso_draw_arrays(cso, prim, 0, num_vertices);
124}
125
126static void
127hud_draw_colored_quad(struct hud_context *hud, unsigned prim,
128                      unsigned x1, unsigned y1, unsigned x2, unsigned y2,
129                      float r, float g, float b, float a)
130{
131   float buffer[] = {
132      (float) x1, (float) y1,
133      (float) x1, (float) y2,
134      (float) x2, (float) y2,
135      (float) x2, (float) y1,
136   };
137
138   hud_draw_colored_prims(hud, prim, buffer, 4, r, g, b, a, 0, 0, 1);
139}
140
141static void
142hud_draw_background_quad(struct hud_context *hud,
143                         unsigned x1, unsigned y1, unsigned x2, unsigned y2)
144{
145   float *vertices = hud->bg.vertices + hud->bg.num_vertices*2;
146   unsigned num = 0;
147
148   assert(hud->bg.num_vertices + 4 <= hud->bg.max_num_vertices);
149
150   vertices[num++] = (float) x1;
151   vertices[num++] = (float) y1;
152
153   vertices[num++] = (float) x1;
154   vertices[num++] = (float) y2;
155
156   vertices[num++] = (float) x2;
157   vertices[num++] = (float) y2;
158
159   vertices[num++] = (float) x2;
160   vertices[num++] = (float) y1;
161
162   hud->bg.num_vertices += num/2;
163}
164
165static void
166hud_draw_string(struct hud_context *hud, unsigned x, unsigned y,
167                const char *str, ...)
168{
169   char buf[256];
170   char *s = buf;
171   float *vertices = hud->text.vertices + hud->text.num_vertices*4;
172   unsigned num = 0;
173
174   va_list ap;
175   va_start(ap, str);
176   util_vsnprintf(buf, sizeof(buf), str, ap);
177   va_end(ap);
178
179   if (!*s)
180      return;
181
182   hud_draw_background_quad(hud,
183                            x, y,
184                            x + strlen(buf)*hud->font.glyph_width,
185                            y + hud->font.glyph_height);
186
187   while (*s) {
188      unsigned x1 = x;
189      unsigned y1 = y;
190      unsigned x2 = x + hud->font.glyph_width;
191      unsigned y2 = y + hud->font.glyph_height;
192      unsigned tx1 = (*s % 16) * hud->font.glyph_width;
193      unsigned ty1 = (*s / 16) * hud->font.glyph_height;
194      unsigned tx2 = tx1 + hud->font.glyph_width;
195      unsigned ty2 = ty1 + hud->font.glyph_height;
196
197      if (*s == ' ') {
198         x += hud->font.glyph_width;
199         s++;
200         continue;
201      }
202
203      assert(hud->text.num_vertices + num/4 + 4 <= hud->text.max_num_vertices);
204
205      vertices[num++] = (float) x1;
206      vertices[num++] = (float) y1;
207      vertices[num++] = (float) tx1;
208      vertices[num++] = (float) ty1;
209
210      vertices[num++] = (float) x1;
211      vertices[num++] = (float) y2;
212      vertices[num++] = (float) tx1;
213      vertices[num++] = (float) ty2;
214
215      vertices[num++] = (float) x2;
216      vertices[num++] = (float) y2;
217      vertices[num++] = (float) tx2;
218      vertices[num++] = (float) ty2;
219
220      vertices[num++] = (float) x2;
221      vertices[num++] = (float) y1;
222      vertices[num++] = (float) tx2;
223      vertices[num++] = (float) ty1;
224
225      x += hud->font.glyph_width;
226      s++;
227   }
228
229   hud->text.num_vertices += num/4;
230}
231
232static void
233number_to_human_readable(uint64_t num, boolean is_in_bytes, char *out)
234{
235   static const char *byte_units[] =
236      {"", " KB", " MB", " GB", " TB", " PB", " EB"};
237   static const char *metric_units[] =
238      {"", " k", " M", " G", " T", " P", " E"};
239   const char **units = is_in_bytes ? byte_units : metric_units;
240   double divisor = is_in_bytes ? 1024 : 1000;
241   int unit = 0;
242   double d = num;
243
244   while (d > divisor) {
245      d /= divisor;
246      unit++;
247   }
248
249   if (d >= 100 || d == (int)d)
250      sprintf(out, "%.0f%s", d, units[unit]);
251   else if (d >= 10 || d*10 == (int)(d*10))
252      sprintf(out, "%.1f%s", d, units[unit]);
253   else
254      sprintf(out, "%.2f%s", d, units[unit]);
255}
256
257static void
258hud_draw_graph_line_strip(struct hud_context *hud, const struct hud_graph *gr,
259                          unsigned xoffset, unsigned yoffset, float yscale)
260{
261   if (gr->num_vertices <= 1)
262      return;
263
264   assert(gr->index <= gr->num_vertices);
265
266   hud_draw_colored_prims(hud, PIPE_PRIM_LINE_STRIP,
267                          gr->vertices, gr->index,
268                          gr->color[0], gr->color[1], gr->color[2], 1,
269                          xoffset + (gr->pane->max_num_vertices - gr->index - 1) * 2 - 1,
270                          yoffset, yscale);
271
272   if (gr->num_vertices <= gr->index)
273      return;
274
275   hud_draw_colored_prims(hud, PIPE_PRIM_LINE_STRIP,
276                          gr->vertices + gr->index*2,
277                          gr->num_vertices - gr->index,
278                          gr->color[0], gr->color[1], gr->color[2], 1,
279                          xoffset - gr->index*2 - 1, yoffset, yscale);
280}
281
282static void
283hud_pane_accumulate_vertices(struct hud_context *hud,
284                             const struct hud_pane *pane)
285{
286   struct hud_graph *gr;
287   float *line_verts = hud->whitelines.vertices + hud->whitelines.num_vertices*2;
288   unsigned i, num = 0;
289   char str[32];
290
291   /* draw background */
292   hud_draw_background_quad(hud,
293                            pane->x1, pane->y1,
294                            pane->x2, pane->y2);
295
296   /* draw numbers on the right-hand side */
297   for (i = 0; i < 6; i++) {
298      unsigned x = pane->x2 + 2;
299      unsigned y = pane->inner_y1 + pane->inner_height * (5 - i) / 5 -
300                   hud->font.glyph_height / 2;
301
302      number_to_human_readable(pane->max_value * i / 5,
303                               pane->uses_byte_units, str);
304      hud_draw_string(hud, x, y, str);
305   }
306
307   /* draw info below the pane */
308   i = 0;
309   LIST_FOR_EACH_ENTRY(gr, &pane->graph_list, head) {
310      unsigned x = pane->x1 + 2;
311      unsigned y = pane->y2 + 2 + i*hud->font.glyph_height;
312
313      number_to_human_readable(gr->current_value,
314                               pane->uses_byte_units, str);
315      hud_draw_string(hud, x, y, "  %s: %s", gr->name, str);
316      i++;
317   }
318
319   /* draw border */
320   assert(hud->whitelines.num_vertices + num/2 + 8 <= hud->whitelines.max_num_vertices);
321   line_verts[num++] = (float) pane->x1;
322   line_verts[num++] = (float) pane->y1;
323   line_verts[num++] = (float) pane->x2;
324   line_verts[num++] = (float) pane->y1;
325
326   line_verts[num++] = (float) pane->x2;
327   line_verts[num++] = (float) pane->y1;
328   line_verts[num++] = (float) pane->x2;
329   line_verts[num++] = (float) pane->y2;
330
331   line_verts[num++] = (float) pane->x1;
332   line_verts[num++] = (float) pane->y2;
333   line_verts[num++] = (float) pane->x2;
334   line_verts[num++] = (float) pane->y2;
335
336   line_verts[num++] = (float) pane->x1;
337   line_verts[num++] = (float) pane->y1;
338   line_verts[num++] = (float) pane->x1;
339   line_verts[num++] = (float) pane->y2;
340
341   /* draw horizontal lines inside the graph */
342   for (i = 0; i <= 5; i++) {
343      float y = round((pane->max_value * i / 5.0) * pane->yscale + pane->inner_y2);
344
345      assert(hud->whitelines.num_vertices + num/2 + 2 <= hud->whitelines.max_num_vertices);
346      line_verts[num++] = pane->x1;
347      line_verts[num++] = y;
348      line_verts[num++] = pane->x2;
349      line_verts[num++] = y;
350   }
351
352   hud->whitelines.num_vertices += num/2;
353}
354
355static void
356hud_pane_draw_colored_objects(struct hud_context *hud,
357                              const struct hud_pane *pane)
358{
359   struct hud_graph *gr;
360   unsigned i;
361
362   /* draw colored quads below the pane */
363   i = 0;
364   LIST_FOR_EACH_ENTRY(gr, &pane->graph_list, head) {
365      unsigned x = pane->x1 + 2;
366      unsigned y = pane->y2 + 2 + i*hud->font.glyph_height;
367
368      hud_draw_colored_quad(hud, PIPE_PRIM_QUADS, x + 1, y + 1, x + 12, y + 13,
369                            gr->color[0], gr->color[1], gr->color[2], 1);
370      i++;
371   }
372
373   /* draw the line strips */
374   LIST_FOR_EACH_ENTRY(gr, &pane->graph_list, head) {
375      hud_draw_graph_line_strip(hud, gr, pane->inner_x1, pane->inner_y2, pane->yscale);
376   }
377}
378
379static void
380hud_alloc_vertices(struct hud_context *hud, struct vertex_queue *v,
381                   unsigned num_vertices, unsigned stride)
382{
383   v->num_vertices = 0;
384   v->max_num_vertices = num_vertices;
385   v->vbuf.stride = stride;
386   u_upload_alloc(hud->uploader, 0, v->vbuf.stride * v->max_num_vertices,
387                  &v->vbuf.buffer_offset, &v->vbuf.buffer,
388                  (void**)&v->vertices);
389}
390
391/**
392 * Draw the HUD to the texture \p tex.
393 * The texture is usually the back buffer being displayed.
394 */
395void
396hud_draw(struct hud_context *hud, struct pipe_resource *tex)
397{
398   struct cso_context *cso = hud->cso;
399   struct pipe_context *pipe = hud->pipe;
400   struct pipe_framebuffer_state fb;
401   struct pipe_surface surf_templ, *surf;
402   struct pipe_viewport_state viewport;
403   const struct pipe_sampler_state *sampler_states[] =
404         { &hud->font_sampler_state };
405   struct hud_pane *pane;
406   struct hud_graph *gr;
407
408   hud->fb_width = tex->width0;
409   hud->fb_height = tex->height0;
410   hud->constants.two_div_fb_width = 2.0f / hud->fb_width;
411   hud->constants.two_div_fb_height = 2.0f / hud->fb_height;
412
413   cso_save_framebuffer(cso);
414   cso_save_sample_mask(cso);
415   cso_save_min_samples(cso);
416   cso_save_blend(cso);
417   cso_save_depth_stencil_alpha(cso);
418   cso_save_fragment_shader(cso);
419   cso_save_sampler_views(cso, PIPE_SHADER_FRAGMENT);
420   cso_save_samplers(cso, PIPE_SHADER_FRAGMENT);
421   cso_save_rasterizer(cso);
422   cso_save_viewport(cso);
423   cso_save_stream_outputs(cso);
424   cso_save_geometry_shader(cso);
425   cso_save_vertex_shader(cso);
426   cso_save_vertex_elements(cso);
427   cso_save_aux_vertex_buffer_slot(cso);
428   cso_save_constant_buffer_slot0(cso, PIPE_SHADER_VERTEX);
429   cso_save_render_condition(cso);
430
431   /* set states */
432   memset(&surf_templ, 0, sizeof(surf_templ));
433   surf_templ.format = tex->format;
434   surf = pipe->create_surface(pipe, tex, &surf_templ);
435
436   memset(&fb, 0, sizeof(fb));
437   fb.nr_cbufs = 1;
438   fb.cbufs[0] = surf;
439   fb.zsbuf = NULL;
440   fb.width = hud->fb_width;
441   fb.height = hud->fb_height;
442
443   viewport.scale[0] = 0.5f * hud->fb_width;
444   viewport.scale[1] = 0.5f * hud->fb_height;
445   viewport.scale[2] = 1.0f;
446   viewport.scale[3] = 1.0f;
447   viewport.translate[0] = 0.5f * hud->fb_width;
448   viewport.translate[1] = 0.5f * hud->fb_height;
449   viewport.translate[2] = 0.0f;
450   viewport.translate[3] = 0.0f;
451
452   cso_set_framebuffer(cso, &fb);
453   cso_set_sample_mask(cso, ~0);
454   cso_set_min_samples(cso, 1);
455   cso_set_blend(cso, &hud->alpha_blend);
456   cso_set_depth_stencil_alpha(cso, &hud->dsa);
457   cso_set_rasterizer(cso, &hud->rasterizer);
458   cso_set_viewport(cso, &viewport);
459   cso_set_stream_outputs(cso, 0, NULL, NULL);
460   cso_set_geometry_shader_handle(cso, NULL);
461   cso_set_vertex_shader_handle(cso, hud->vs);
462   cso_set_vertex_elements(cso, 2, hud->velems);
463   cso_set_render_condition(cso, NULL, FALSE, 0);
464   cso_set_sampler_views(cso, PIPE_SHADER_FRAGMENT, 1,
465                         &hud->font_sampler_view);
466   cso_set_samplers(cso, PIPE_SHADER_FRAGMENT, 1, sampler_states);
467   cso_set_constant_buffer(cso, PIPE_SHADER_VERTEX, 0, &hud->constbuf);
468
469   /* prepare vertex buffers */
470   hud_alloc_vertices(hud, &hud->bg, 4 * 128, 2 * sizeof(float));
471   hud_alloc_vertices(hud, &hud->whitelines, 4 * 256, 2 * sizeof(float));
472   hud_alloc_vertices(hud, &hud->text, 4 * 512, 4 * sizeof(float));
473
474   /* prepare all graphs */
475   LIST_FOR_EACH_ENTRY(pane, &hud->pane_list, head) {
476      LIST_FOR_EACH_ENTRY(gr, &pane->graph_list, head) {
477         gr->query_new_value(gr);
478      }
479
480      hud_pane_accumulate_vertices(hud, pane);
481   }
482
483   /* unmap the uploader's vertex buffer before drawing */
484   u_upload_unmap(hud->uploader);
485
486   /* draw accumulated vertices for background quads */
487   cso_set_fragment_shader_handle(hud->cso, hud->fs_color);
488
489   if (hud->bg.num_vertices) {
490      hud->constants.color[0] = 0;
491      hud->constants.color[1] = 0;
492      hud->constants.color[2] = 0;
493      hud->constants.color[3] = 0.666f;
494      hud->constants.translate[0] = 0;
495      hud->constants.translate[1] = 0;
496      hud->constants.scale[0] = 1;
497      hud->constants.scale[1] = 1;
498
499      cso_set_constant_buffer(cso, PIPE_SHADER_VERTEX, 0, &hud->constbuf);
500      cso_set_vertex_buffers(cso, cso_get_aux_vertex_buffer_slot(cso), 1,
501                             &hud->bg.vbuf);
502      cso_draw_arrays(cso, PIPE_PRIM_QUADS, 0, hud->bg.num_vertices);
503   }
504   pipe_resource_reference(&hud->bg.vbuf.buffer, NULL);
505
506   /* draw accumulated vertices for white lines */
507   hud->constants.color[0] = 1;
508   hud->constants.color[1] = 1;
509   hud->constants.color[2] = 1;
510   hud->constants.color[3] = 1;
511   hud->constants.translate[0] = 0;
512   hud->constants.translate[1] = 0;
513   hud->constants.scale[0] = 1;
514   hud->constants.scale[1] = 1;
515   cso_set_constant_buffer(cso, PIPE_SHADER_VERTEX, 0, &hud->constbuf);
516
517   if (hud->whitelines.num_vertices) {
518      cso_set_vertex_buffers(cso, cso_get_aux_vertex_buffer_slot(cso), 1,
519                             &hud->whitelines.vbuf);
520      cso_set_fragment_shader_handle(hud->cso, hud->fs_color);
521      cso_draw_arrays(cso, PIPE_PRIM_LINES, 0, hud->whitelines.num_vertices);
522   }
523   pipe_resource_reference(&hud->whitelines.vbuf.buffer, NULL);
524
525   /* draw accumulated vertices for text */
526   if (hud->text.num_vertices) {
527      cso_set_vertex_buffers(cso, cso_get_aux_vertex_buffer_slot(cso), 1,
528                             &hud->text.vbuf);
529      cso_set_fragment_shader_handle(hud->cso, hud->fs_text);
530      cso_draw_arrays(cso, PIPE_PRIM_QUADS, 0, hud->text.num_vertices);
531   }
532   pipe_resource_reference(&hud->text.vbuf.buffer, NULL);
533
534   /* draw the rest */
535   LIST_FOR_EACH_ENTRY(pane, &hud->pane_list, head) {
536      if (pane)
537         hud_pane_draw_colored_objects(hud, pane);
538   }
539
540   /* restore states */
541   cso_restore_framebuffer(cso);
542   cso_restore_sample_mask(cso);
543   cso_restore_min_samples(cso);
544   cso_restore_blend(cso);
545   cso_restore_depth_stencil_alpha(cso);
546   cso_restore_fragment_shader(cso);
547   cso_restore_sampler_views(cso, PIPE_SHADER_FRAGMENT);
548   cso_restore_samplers(cso, PIPE_SHADER_FRAGMENT);
549   cso_restore_rasterizer(cso);
550   cso_restore_viewport(cso);
551   cso_restore_stream_outputs(cso);
552   cso_restore_geometry_shader(cso);
553   cso_restore_vertex_shader(cso);
554   cso_restore_vertex_elements(cso);
555   cso_restore_aux_vertex_buffer_slot(cso);
556   cso_restore_constant_buffer_slot0(cso, PIPE_SHADER_VERTEX);
557   cso_restore_render_condition(cso);
558
559   pipe_surface_reference(&surf, NULL);
560}
561
562/**
563 * Set the maximum value for the Y axis of the graph.
564 * This scales the graph accordingly.
565 */
566void
567hud_pane_set_max_value(struct hud_pane *pane, uint64_t value)
568{
569   pane->max_value = value;
570   pane->yscale = -(int)pane->inner_height / (float)pane->max_value;
571}
572
573static struct hud_pane *
574hud_pane_create(unsigned x1, unsigned y1, unsigned x2, unsigned y2,
575                unsigned period, uint64_t max_value)
576{
577   struct hud_pane *pane = CALLOC_STRUCT(hud_pane);
578
579   if (!pane)
580      return NULL;
581
582   pane->x1 = x1;
583   pane->y1 = y1;
584   pane->x2 = x2;
585   pane->y2 = y2;
586   pane->inner_x1 = x1 + 1;
587   pane->inner_x2 = x2 - 1;
588   pane->inner_y1 = y1 + 1;
589   pane->inner_y2 = y2 - 1;
590   pane->inner_width = pane->inner_x2 - pane->inner_x1;
591   pane->inner_height = pane->inner_y2 - pane->inner_y1;
592   pane->period = period;
593   pane->max_num_vertices = (x2 - x1 + 2) / 2;
594   hud_pane_set_max_value(pane, max_value);
595   LIST_INITHEAD(&pane->graph_list);
596   return pane;
597}
598
599/**
600 * Add a graph to an existing pane.
601 * One pane can contain multiple graphs over each other.
602 */
603void
604hud_pane_add_graph(struct hud_pane *pane, struct hud_graph *gr)
605{
606   static const float colors[][3] = {
607      {0, 1, 0},
608      {1, 0, 0},
609      {0, 1, 1},
610      {1, 0, 1},
611      {1, 1, 0},
612      {0.5, 0.5, 1},
613      {0.5, 0.5, 0.5},
614   };
615   char *name = gr->name;
616
617   /* replace '-' with a space */
618   while (*name) {
619      if (*name == '-')
620         *name = ' ';
621      name++;
622   }
623
624   assert(pane->num_graphs < Elements(colors));
625   gr->vertices = MALLOC(pane->max_num_vertices * sizeof(float) * 2);
626   gr->color[0] = colors[pane->num_graphs][0];
627   gr->color[1] = colors[pane->num_graphs][1];
628   gr->color[2] = colors[pane->num_graphs][2];
629   gr->pane = pane;
630   LIST_ADDTAIL(&gr->head, &pane->graph_list);
631   pane->num_graphs++;
632}
633
634void
635hud_graph_add_value(struct hud_graph *gr, uint64_t value)
636{
637   if (gr->index == gr->pane->max_num_vertices) {
638      gr->vertices[0] = 0;
639      gr->vertices[1] = gr->vertices[(gr->index-1)*2+1];
640      gr->index = 1;
641   }
642   gr->vertices[(gr->index)*2+0] = (float) (gr->index * 2);
643   gr->vertices[(gr->index)*2+1] = (float) value;
644   gr->index++;
645
646   if (gr->num_vertices < gr->pane->max_num_vertices) {
647      gr->num_vertices++;
648   }
649
650   gr->current_value = value;
651   if (value > gr->pane->max_value) {
652      hud_pane_set_max_value(gr->pane, value);
653   }
654}
655
656static void
657hud_graph_destroy(struct hud_graph *graph)
658{
659   FREE(graph->vertices);
660   if (graph->free_query_data)
661      graph->free_query_data(graph->query_data);
662   FREE(graph);
663}
664
665/**
666 * Read a string from the environment variable.
667 * The separators "+", ",", ":", and ";" terminate the string.
668 * Return the number of read characters.
669 */
670static int
671parse_string(const char *s, char *out)
672{
673   int i;
674
675   for (i = 0; *s && *s != '+' && *s != ',' && *s != ':' && *s != ';';
676        s++, out++, i++)
677      *out = *s;
678
679   *out = 0;
680
681   if (*s && !i)
682      fprintf(stderr, "gallium_hud: syntax error: unexpected '%c' (%i) while "
683              "parsing a string\n", *s, *s);
684   return i;
685}
686
687static boolean
688has_occlusion_query(struct pipe_screen *screen)
689{
690   return screen->get_param(screen, PIPE_CAP_OCCLUSION_QUERY) != 0;
691}
692
693static boolean
694has_streamout(struct pipe_screen *screen)
695{
696   return screen->get_param(screen, PIPE_CAP_MAX_STREAM_OUTPUT_BUFFERS) != 0;
697}
698
699static boolean
700has_pipeline_stats_query(struct pipe_screen *screen)
701{
702   return screen->get_param(screen, PIPE_CAP_QUERY_PIPELINE_STATISTICS) != 0;
703}
704
705static void
706hud_parse_env_var(struct hud_context *hud, const char *env)
707{
708   unsigned num, i;
709   char name[256], s[256];
710   struct hud_pane *pane = NULL;
711   unsigned x = 10, y = 10;
712   unsigned width = 251, height = 100;
713   unsigned period = 500 * 1000;  /* default period (1/2 second) */
714   const char *period_env;
715
716   /*
717    * The GALLIUM_HUD_PERIOD env var sets the graph update rate.
718    * The env var is in seconds (a float).
719    * Zero means update after every frame.
720    */
721   period_env = getenv("GALLIUM_HUD_PERIOD");
722   if (period_env) {
723      float p = (float) atof(period_env);
724      if (p >= 0.0f) {
725         period = (unsigned) (p * 1000 * 1000);
726      }
727   }
728
729   while ((num = parse_string(env, name)) != 0) {
730      env += num;
731
732      if (!pane) {
733         pane = hud_pane_create(x, y, x + width, y + height, period, 10);
734         if (!pane)
735            return;
736      }
737
738      /* Add a graph. */
739      /* IF YOU CHANGE THIS, UPDATE print_help! */
740      if (strcmp(name, "fps") == 0) {
741         hud_fps_graph_install(pane);
742      }
743      else if (strcmp(name, "cpu") == 0) {
744         hud_cpu_graph_install(pane, ALL_CPUS);
745      }
746      else if (sscanf(name, "cpu%u%s", &i, s) == 1) {
747         hud_cpu_graph_install(pane, i);
748      }
749      else if (strcmp(name, "samples-passed") == 0 &&
750               has_occlusion_query(hud->pipe->screen)) {
751         hud_pipe_query_install(pane, hud->pipe, "samples-passed",
752                                PIPE_QUERY_OCCLUSION_COUNTER, 0, 0, FALSE);
753      }
754      else if (strcmp(name, "primitives-generated") == 0 &&
755               has_streamout(hud->pipe->screen)) {
756         hud_pipe_query_install(pane, hud->pipe, "primitives-generated",
757                                PIPE_QUERY_PRIMITIVES_GENERATED, 0, 0, FALSE);
758      }
759      else {
760         boolean processed = FALSE;
761
762         /* pipeline statistics queries */
763         if (has_pipeline_stats_query(hud->pipe->screen)) {
764            static const char *pipeline_statistics_names[] =
765            {
766               "ia-vertices",
767               "ia-primitives",
768               "vs-invocations",
769               "gs-invocations",
770               "gs-primitives",
771               "clipper-invocations",
772               "clipper-primitives-generated",
773               "ps-invocations",
774               "hs-invocations",
775               "ds-invocations",
776               "cs-invocations"
777            };
778            for (i = 0; i < Elements(pipeline_statistics_names); ++i)
779               if (strcmp(name, pipeline_statistics_names[i]) == 0)
780                  break;
781            if (i < Elements(pipeline_statistics_names)) {
782               hud_pipe_query_install(pane, hud->pipe, name,
783                                      PIPE_QUERY_PIPELINE_STATISTICS, i,
784                                      0, FALSE);
785               processed = TRUE;
786            }
787         }
788
789         /* driver queries */
790         if (!processed) {
791            if (!hud_driver_query_install(pane, hud->pipe, name)){
792               fprintf(stderr, "gallium_hud: unknown driver query '%s'\n", name);
793            }
794         }
795      }
796
797      if (*env == ':') {
798         env++;
799
800         if (!pane) {
801            fprintf(stderr, "gallium_hud: syntax error: unexpected ':', "
802                    "expected a name\n");
803            break;
804         }
805
806         num = parse_string(env, s);
807         env += num;
808
809         if (num && sscanf(s, "%u", &i) == 1) {
810            hud_pane_set_max_value(pane, i);
811         }
812         else {
813            fprintf(stderr, "gallium_hud: syntax error: unexpected '%c' (%i) "
814                    "after ':'\n", *env, *env);
815         }
816      }
817
818      if (*env == 0)
819         break;
820
821      /* parse a separator */
822      switch (*env) {
823      case '+':
824         env++;
825         break;
826
827      case ',':
828         env++;
829         y += height + hud->font.glyph_height * (pane->num_graphs + 2);
830
831         if (pane && pane->num_graphs) {
832            LIST_ADDTAIL(&pane->head, &hud->pane_list);
833            pane = NULL;
834         }
835         break;
836
837      case ';':
838         env++;
839         y = 10;
840         x += width + hud->font.glyph_width * 7;
841
842         if (pane && pane->num_graphs) {
843            LIST_ADDTAIL(&pane->head, &hud->pane_list);
844            pane = NULL;
845         }
846         break;
847
848      default:
849         fprintf(stderr, "gallium_hud: syntax error: unexpected '%c'\n", *env);
850      }
851   }
852
853   if (pane) {
854      if (pane->num_graphs) {
855         LIST_ADDTAIL(&pane->head, &hud->pane_list);
856      }
857      else {
858         FREE(pane);
859      }
860   }
861}
862
863static void
864print_help(struct pipe_screen *screen)
865{
866   int i, num_queries, num_cpus = hud_get_num_cpus();
867
868   puts("Syntax: GALLIUM_HUD=name1[+name2][...][:value1][,nameI...][;nameJ...]");
869   puts("");
870   puts("  Names are identifiers of data sources which will be drawn as graphs");
871   puts("  in panes. Multiple graphs can be drawn in the same pane.");
872   puts("  There can be multiple panes placed in rows and columns.");
873   puts("");
874   puts("  '+' separates names which will share a pane.");
875   puts("  ':[value]' specifies the initial maximum value of the Y axis");
876   puts("             for the given pane.");
877   puts("  ',' creates a new pane below the last one.");
878   puts("  ';' creates a new pane at the top of the next column.");
879   puts("");
880   puts("  Example: GALLIUM_HUD=\"cpu,fps;primitives-generated\"");
881   puts("");
882   puts("  Available names:");
883   puts("    fps");
884   puts("    cpu");
885
886   for (i = 0; i < num_cpus; i++)
887      printf("    cpu%i\n", i);
888
889   if (has_occlusion_query(screen))
890      puts("    samples-passed");
891   if (has_streamout(screen))
892      puts("    primitives-generated");
893
894   if (has_pipeline_stats_query(screen)) {
895      puts("    ia-vertices");
896      puts("    ia-primitives");
897      puts("    vs-invocations");
898      puts("    gs-invocations");
899      puts("    gs-primitives");
900      puts("    clipper-invocations");
901      puts("    clipper-primitives-generated");
902      puts("    ps-invocations");
903      puts("    hs-invocations");
904      puts("    ds-invocations");
905      puts("    cs-invocations");
906   }
907
908   if (screen->get_driver_query_info){
909      struct pipe_driver_query_info info;
910      num_queries = screen->get_driver_query_info(screen, 0, NULL);
911
912      for (i = 0; i < num_queries; i++){
913         screen->get_driver_query_info(screen, i, &info);
914         printf("    %s\n", info.name);
915      }
916   }
917
918   puts("");
919}
920
921struct hud_context *
922hud_create(struct pipe_context *pipe, struct cso_context *cso)
923{
924   struct hud_context *hud;
925   struct pipe_sampler_view view_templ;
926   unsigned i;
927   const char *env = debug_get_option("GALLIUM_HUD", NULL);
928
929   if (!env || !*env)
930      return NULL;
931
932   if (strcmp(env, "help") == 0) {
933      print_help(pipe->screen);
934      return NULL;
935   }
936
937   hud = CALLOC_STRUCT(hud_context);
938   if (!hud)
939      return NULL;
940
941   hud->pipe = pipe;
942   hud->cso = cso;
943   hud->uploader = u_upload_create(pipe, 256 * 1024, 16,
944                                   PIPE_BIND_VERTEX_BUFFER);
945
946   /* font */
947   if (!util_font_create(pipe, UTIL_FONT_FIXED_8X13, &hud->font)) {
948      u_upload_destroy(hud->uploader);
949      FREE(hud);
950      return NULL;
951   }
952
953   /* blend state */
954   hud->alpha_blend.rt[0].colormask = PIPE_MASK_RGBA;
955   hud->alpha_blend.rt[0].blend_enable = 1;
956   hud->alpha_blend.rt[0].rgb_func = PIPE_BLEND_ADD;
957   hud->alpha_blend.rt[0].rgb_src_factor = PIPE_BLENDFACTOR_SRC_ALPHA;
958   hud->alpha_blend.rt[0].rgb_dst_factor = PIPE_BLENDFACTOR_INV_SRC_ALPHA;
959   hud->alpha_blend.rt[0].alpha_func = PIPE_BLEND_ADD;
960   hud->alpha_blend.rt[0].alpha_src_factor = PIPE_BLENDFACTOR_ZERO;
961   hud->alpha_blend.rt[0].alpha_dst_factor = PIPE_BLENDFACTOR_ONE;
962
963   /* fragment shader */
964   hud->fs_color =
965         util_make_fragment_passthrough_shader(pipe,
966                                               TGSI_SEMANTIC_COLOR,
967                                               TGSI_INTERPOLATE_CONSTANT,
968                                               TRUE);
969
970   {
971      /* Read a texture and do .xxxx swizzling. */
972      static const char *fragment_shader_text = {
973         "FRAG\n"
974         "DCL IN[0], GENERIC[0], LINEAR\n"
975         "DCL SAMP[0]\n"
976         "DCL OUT[0], COLOR[0]\n"
977         "DCL TEMP[0]\n"
978
979         "TEX TEMP[0], IN[0], SAMP[0], RECT\n"
980         "MOV OUT[0], TEMP[0].xxxx\n"
981         "END\n"
982      };
983
984      struct tgsi_token tokens[1000];
985      struct pipe_shader_state state = {tokens};
986
987      if (!tgsi_text_translate(fragment_shader_text, tokens, Elements(tokens))) {
988         assert(0);
989         pipe_resource_reference(&hud->font.texture, NULL);
990         u_upload_destroy(hud->uploader);
991         FREE(hud);
992         return NULL;
993      }
994
995      hud->fs_text = pipe->create_fs_state(pipe, &state);
996   }
997
998   /* rasterizer */
999   hud->rasterizer.half_pixel_center = 1;
1000   hud->rasterizer.bottom_edge_rule = 1;
1001   hud->rasterizer.depth_clip = 1;
1002   hud->rasterizer.line_width = 1;
1003   hud->rasterizer.line_last_pixel = 1;
1004
1005   /* vertex shader */
1006   {
1007      static const char *vertex_shader_text = {
1008         "VERT\n"
1009         "DCL IN[0..1]\n"
1010         "DCL OUT[0], POSITION\n"
1011         "DCL OUT[1], COLOR[0]\n" /* color */
1012         "DCL OUT[2], GENERIC[0]\n" /* texcoord */
1013         /* [0] = color,
1014          * [1] = (2/fb_width, 2/fb_height, xoffset, yoffset)
1015          * [2] = (xscale, yscale, 0, 0) */
1016         "DCL CONST[0..2]\n"
1017         "DCL TEMP[0]\n"
1018         "IMM[0] FLT32 { -1, 0, 0, 1 }\n"
1019
1020         /* v = in * (xscale, yscale) + (xoffset, yoffset) */
1021         "MAD TEMP[0].xy, IN[0], CONST[2].xyyy, CONST[1].zwww\n"
1022         /* pos = v * (2 / fb_width, 2 / fb_height) - (1, 1) */
1023         "MAD OUT[0].xy, TEMP[0], CONST[1].xyyy, IMM[0].xxxx\n"
1024         "MOV OUT[0].zw, IMM[0]\n"
1025
1026         "MOV OUT[1], CONST[0]\n"
1027         "MOV OUT[2], IN[1]\n"
1028         "END\n"
1029      };
1030
1031      struct tgsi_token tokens[1000];
1032      struct pipe_shader_state state = {tokens};
1033
1034      if (!tgsi_text_translate(vertex_shader_text, tokens, Elements(tokens))) {
1035         assert(0);
1036         pipe_resource_reference(&hud->font.texture, NULL);
1037         u_upload_destroy(hud->uploader);
1038         FREE(hud);
1039         return NULL;
1040      }
1041
1042      hud->vs = pipe->create_vs_state(pipe, &state);
1043   }
1044
1045   /* vertex elements */
1046   for (i = 0; i < 2; i++) {
1047      hud->velems[i].src_offset = i * 2 * sizeof(float);
1048      hud->velems[i].src_format = PIPE_FORMAT_R32G32_FLOAT;
1049      hud->velems[i].vertex_buffer_index = cso_get_aux_vertex_buffer_slot(cso);
1050   }
1051
1052   /* sampler view */
1053   memset(&view_templ, 0, sizeof(view_templ));
1054   view_templ.format = hud->font.texture->format;
1055   view_templ.swizzle_r = PIPE_SWIZZLE_RED;
1056   view_templ.swizzle_g = PIPE_SWIZZLE_GREEN;
1057   view_templ.swizzle_b = PIPE_SWIZZLE_BLUE;
1058   view_templ.swizzle_a = PIPE_SWIZZLE_ALPHA;
1059   hud->font_sampler_view = pipe->create_sampler_view(pipe, hud->font.texture,
1060                                                      &view_templ);
1061
1062   /* sampler state (for font drawing) */
1063   hud->font_sampler_state.wrap_s = PIPE_TEX_WRAP_CLAMP_TO_EDGE;
1064   hud->font_sampler_state.wrap_t = PIPE_TEX_WRAP_CLAMP_TO_EDGE;
1065   hud->font_sampler_state.wrap_r = PIPE_TEX_WRAP_CLAMP_TO_EDGE;
1066   hud->font_sampler_state.normalized_coords = 0;
1067
1068   /* constants */
1069   hud->constbuf.buffer_size = sizeof(hud->constants);
1070   hud->constbuf.user_buffer = &hud->constants;
1071
1072   LIST_INITHEAD(&hud->pane_list);
1073
1074   hud_parse_env_var(hud, env);
1075   return hud;
1076}
1077
1078void
1079hud_destroy(struct hud_context *hud)
1080{
1081   struct pipe_context *pipe = hud->pipe;
1082   struct hud_pane *pane, *pane_tmp;
1083   struct hud_graph *graph, *graph_tmp;
1084
1085   LIST_FOR_EACH_ENTRY_SAFE(pane, pane_tmp, &hud->pane_list, head) {
1086      LIST_FOR_EACH_ENTRY_SAFE(graph, graph_tmp, &pane->graph_list, head) {
1087         LIST_DEL(&graph->head);
1088         hud_graph_destroy(graph);
1089      }
1090      LIST_DEL(&pane->head);
1091      FREE(pane);
1092   }
1093
1094   pipe->delete_fs_state(pipe, hud->fs_color);
1095   pipe->delete_fs_state(pipe, hud->fs_text);
1096   pipe->delete_vs_state(pipe, hud->vs);
1097   pipe_sampler_view_reference(&hud->font_sampler_view, NULL);
1098   pipe_resource_reference(&hud->font.texture, NULL);
1099   u_upload_destroy(hud->uploader);
1100   FREE(hud);
1101}
1102