tinyblocks-plot: graficos no estilo do matplotlib
Figura atual como no pyplot: linha, linha x-y, pontos, barras com nomes, histograma, titulo, nomes dos eixos (y na vertical), legenda, grade, limites e series com nome que crescem a cada passo (curvas de treino). Desenha numa imagem (para o palco) ou grava em PNG/BMP/PPM. Valores de lista, de texto ou de tensor. Paleta tab10; marcas "redondas" (1, 2, 5 x 10^n) com folga de 5%; linhas e pontos com antisserrilhado; fonte DejaVu Sans 12 px embutida (tools/gen_font.c, via tinyblocks-opentype), com os acentos do portugues. Convolucoes da ai: "filtros de tamanho %3" (o rotulo repetia o campo). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
25bb30d12f
commit
2951535d93
10 files changed
+1957
-4
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,665 @@
|
||||
/*
|
||||
* TinyBlocks - tb_plot.c
|
||||
* A figura atual, o desenho dela numa imagem (linhas e pontos com
|
||||
* antisserrilhado, barras, eixos com marcas "redondas", legenda, grade,
|
||||
* texto com a fonte embutida) e os blocos da categoria "Gráficos".
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <ctype.h>
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
#include <tinyblocks/tb_json_block.h>
|
||||
#include <tinyblocks/tb_image.h>
|
||||
#include "tb_tensor.h"
|
||||
#include "tb_plot.h"
|
||||
#include "plot_font.h"
|
||||
|
||||
/* == Figura =========================================================== */
|
||||
enum { S_LINE, S_SCATTER, S_BAR };
|
||||
|
||||
typedef struct {
|
||||
int kind;
|
||||
float* x;
|
||||
float* y;
|
||||
int n;
|
||||
uint32_t color; /* 0xRRGGBB */
|
||||
char label[64];
|
||||
char** names; /* barras: nomes no eixo x (ou NULL) */
|
||||
} Series;
|
||||
|
||||
static struct {
|
||||
int w, h;
|
||||
char title[128], xlabel[96], ylabel[96];
|
||||
bool legend, grid;
|
||||
bool xlim, ylim;
|
||||
double x0, x1, y0, y1;
|
||||
Series* s;
|
||||
int n, cap, next_color;
|
||||
} F = { 480, 320, "", "", "", false, false, false, false, 0, 1, 0, 1, NULL, 0, 0, 0 };
|
||||
|
||||
static const uint32_t s_tab10[10] = {
|
||||
0x1f77b4, 0xff7f0e, 0x2ca02c, 0xd62728, 0x9467bd, 0x8c564b, 0xe377c2, 0x7f7f7f, 0xbcbd22, 0x17becf };
|
||||
static const char* s_names[] = { "azul", "laranja", "verde", "vermelho", "roxo", "marrom", "rosa", "cinza", "oliva", "ciano" };
|
||||
|
||||
static uint32_t color_of(const char* c) {
|
||||
while (c && isspace((unsigned char)*c)) c++;
|
||||
if (!c || !*c) return s_tab10[F.next_color++ % 10];
|
||||
if (c[0] == '#' && strlen(c) >= 7) return (uint32_t)strtoul(c + 1, NULL, 16) & 0xffffff;
|
||||
for (int i = 0; i < 10; i++) if (!strcasecmp(c, s_names[i])) return s_tab10[i];
|
||||
if (!strcasecmp(c, "preto")) return 0x000000;
|
||||
if (!strcasecmp(c, "branco")) return 0xffffff;
|
||||
return s_tab10[F.next_color++ % 10];
|
||||
}
|
||||
|
||||
static void series_free(Series* s) {
|
||||
free(s->x); free(s->y);
|
||||
for (int i = 0; s->names && i < s->n; i++) free(s->names[i]);
|
||||
free(s->names);
|
||||
}
|
||||
|
||||
void tb_plot_figure(int w, int h) {
|
||||
for (int i = 0; i < F.n; i++) series_free(&F.s[i]);
|
||||
F.n = 0;
|
||||
F.w = w < 64 ? 64 : w > 4096 ? 4096 : w;
|
||||
F.h = h < 64 ? 64 : h > 4096 ? 4096 : h;
|
||||
F.title[0] = F.xlabel[0] = F.ylabel[0] = 0;
|
||||
F.legend = F.grid = F.xlim = F.ylim = false;
|
||||
F.next_color = 0;
|
||||
}
|
||||
|
||||
/* Acrescenta uma serie (copia os vetores; x NULL = 1..n) */
|
||||
static Series* add(int kind, const float* x, const float* y, int n, const char* color, const char* label) {
|
||||
if (F.n == F.cap) {
|
||||
int nc = F.cap ? F.cap * 2 : 8;
|
||||
Series* p = realloc(F.s, (size_t)nc * sizeof(*p));
|
||||
if (!p) return NULL;
|
||||
F.s = p; F.cap = nc;
|
||||
}
|
||||
Series* s = &F.s[F.n];
|
||||
memset(s, 0, sizeof(*s));
|
||||
s->x = malloc((size_t)(n ? n : 1) * sizeof(float));
|
||||
s->y = malloc((size_t)(n ? n : 1) * sizeof(float));
|
||||
if (!s->x || !s->y) { free(s->x); free(s->y); return NULL; }
|
||||
for (int i = 0; i < n; i++) { s->x[i] = x ? x[i] : (float)(i + 1); s->y[i] = y[i]; }
|
||||
s->n = n; s->kind = kind;
|
||||
s->color = color_of(color);
|
||||
snprintf(s->label, sizeof(s->label), "%s", label ? label : "");
|
||||
F.n++;
|
||||
return s;
|
||||
}
|
||||
|
||||
void tb_plot_line(const float* x, const float* y, int n, const char* color, const char* label) {
|
||||
add(S_LINE, x, y, n, color, label);
|
||||
}
|
||||
|
||||
void tb_plot_title(const char* t) { snprintf(F.title, sizeof(F.title), "%s", t ? t : ""); }
|
||||
|
||||
/* == Desenho ========================================================== */
|
||||
typedef struct { uint8_t* p; int w, h; int cx0, cy0, cx1, cy1; } Canvas; /* recorte [cx0,cx1) */
|
||||
|
||||
static void blend(Canvas* c, int x, int y, uint32_t rgb, float a) {
|
||||
if (x < c->cx0 || y < c->cy0 || x >= c->cx1 || y >= c->cy1 || a <= 0) return;
|
||||
if (a > 1) a = 1;
|
||||
uint8_t* q = c->p + ((size_t)y * c->w + x) * 4;
|
||||
float r = (float)((rgb >> 16) & 255), g = (float)((rgb >> 8) & 255), b = (float)(rgb & 255);
|
||||
q[0] = (uint8_t)(q[0] + (r - q[0]) * a + .5f);
|
||||
q[1] = (uint8_t)(q[1] + (g - q[1]) * a + .5f);
|
||||
q[2] = (uint8_t)(q[2] + (b - q[2]) * a + .5f);
|
||||
q[3] = 255;
|
||||
}
|
||||
|
||||
static void fill_rect(Canvas* c, float x0, float y0, float x1, float y1, uint32_t rgb, float a) {
|
||||
if (x1 < x0) { float t = x0; x0 = x1; x1 = t; }
|
||||
if (y1 < y0) { float t = y0; y0 = y1; y1 = t; }
|
||||
for (int y = (int)floorf(y0); y < (int)ceilf(y1); y++)
|
||||
for (int x = (int)floorf(x0); x < (int)ceilf(x1); x++) {
|
||||
float cx = fminf(x + 1.f, x1) - fmaxf((float)x, x0), cy = fminf(y + 1.f, y1) - fmaxf((float)y, y0);
|
||||
if (cx > 0 && cy > 0) blend(c, x, y, rgb, a * cx * cy);
|
||||
}
|
||||
}
|
||||
|
||||
/* Segmento com espessura w: cobertura pela distancia ao segmento */
|
||||
static void line(Canvas* c, float x0, float y0, float x1, float y1, float w, uint32_t rgb) {
|
||||
float r = w * 0.5f;
|
||||
int bx0 = (int)floorf(fminf(x0, x1) - r - 1), bx1 = (int)ceilf(fmaxf(x0, x1) + r + 1);
|
||||
int by0 = (int)floorf(fminf(y0, y1) - r - 1), by1 = (int)ceilf(fmaxf(y0, y1) + r + 1);
|
||||
if (bx0 < c->cx0) bx0 = c->cx0;
|
||||
if (by0 < c->cy0) by0 = c->cy0;
|
||||
if (bx1 > c->cx1) bx1 = c->cx1;
|
||||
if (by1 > c->cy1) by1 = c->cy1;
|
||||
float dx = x1 - x0, dy = y1 - y0, L2 = dx * dx + dy * dy;
|
||||
for (int y = by0; y < by1; y++)
|
||||
for (int x = bx0; x < bx1; x++) {
|
||||
float px = x + .5f - x0, py = y + .5f - y0;
|
||||
float t = L2 > 0 ? (px * dx + py * dy) / L2 : 0;
|
||||
t = t < 0 ? 0 : t > 1 ? 1 : t;
|
||||
float ex = px - t * dx, ey = py - t * dy;
|
||||
float cov = r + 0.5f - sqrtf(ex * ex + ey * ey);
|
||||
if (cov > 0) blend(c, x, y, rgb, cov);
|
||||
}
|
||||
}
|
||||
|
||||
static void disc(Canvas* c, float cx, float cy, float r, uint32_t rgb) {
|
||||
for (int y = (int)(cy - r - 1); y <= (int)(cy + r + 1); y++)
|
||||
for (int x = (int)(cx - r - 1); x <= (int)(cx + r + 1); x++) {
|
||||
float d = sqrtf((x + .5f - cx) * (x + .5f - cx) + (y + .5f - cy) * (y + .5f - cy));
|
||||
blend(c, x, y, rgb, r + 0.5f - d);
|
||||
}
|
||||
}
|
||||
|
||||
/* -- texto ---------------------------------------------------------------- */
|
||||
static const PlotGlyph* glyph(unsigned cp) {
|
||||
if (cp >= 32 && cp < 127) return &s_glyphs[cp - 32];
|
||||
if (cp >= 160 && cp < 256) return &s_glyphs[95 + cp - 160];
|
||||
return &s_glyphs['?' - 32];
|
||||
}
|
||||
|
||||
static const char* next_cp(const char* p, unsigned* cp) {
|
||||
unsigned char c = (unsigned char)*p;
|
||||
if (c < 0x80) { *cp = c; return p + 1; }
|
||||
if ((c & 0xE0) == 0xC0 && p[1]) { *cp = ((c & 0x1Fu) << 6) | ((unsigned char)p[1] & 0x3Fu); return p + 2; }
|
||||
int n = (c & 0xF0) == 0xE0 ? 3 : (c & 0xF8) == 0xF0 ? 4 : 1;
|
||||
for (int i = 1; i < n && p[i]; i++) p++;
|
||||
*cp = '?';
|
||||
return p + 1;
|
||||
}
|
||||
|
||||
static int text_w(const char* s) {
|
||||
int w = 0;
|
||||
for (unsigned cp; *s; ) { s = next_cp(s, &cp); w += glyph(cp)->w; }
|
||||
return w;
|
||||
}
|
||||
|
||||
/* Texto com o topo em (x, y); vertical = de baixo para cima (eixo y) */
|
||||
static void text(Canvas* c, int x, int y, const char* s, uint32_t rgb, bool vertical) {
|
||||
int pen = 0;
|
||||
for (unsigned cp; *s; ) {
|
||||
s = next_cp(s, &cp);
|
||||
const PlotGlyph* g = glyph(cp);
|
||||
const uint8_t* a = s_font + g->off;
|
||||
for (int gy = 0; gy < PLOT_FONT_H; gy++)
|
||||
for (int gx = 0; gx < g->w; gx++) {
|
||||
float al = a[gy * g->w + gx] / 255.f;
|
||||
if (!al) continue;
|
||||
if (vertical) blend(c, x + gy, y - pen - gx, rgb, al);
|
||||
else blend(c, x + pen + gx, y + gy, rgb, al);
|
||||
}
|
||||
pen += g->w;
|
||||
}
|
||||
}
|
||||
|
||||
/* -- eixos ---------------------------------------------------------------- */
|
||||
static double nice_step(double range, int want) {
|
||||
double raw = range / (want > 0 ? want : 5);
|
||||
if (raw <= 0 || !isfinite(raw)) return 1;
|
||||
double p = pow(10, floor(log10(raw))), f = raw / p;
|
||||
return (f < 1.5 ? 1 : f < 3 ? 2 : f < 7 ? 5 : 10) * p;
|
||||
}
|
||||
|
||||
static void num_text(double v, double step, char* out, size_t cap) {
|
||||
if (fabs(v) < step * 1e-6) v = 0;
|
||||
int dec = step >= 1 ? 0 : (int)ceil(-log10(step) - 1e-9);
|
||||
if (dec > 6) dec = 6;
|
||||
if (fabs(v) >= 1e6 || (fabs(v) < 1e-4 && v != 0)) snprintf(out, cap, "%.2g", v);
|
||||
else snprintf(out, cap, "%.*f", dec, v);
|
||||
}
|
||||
|
||||
static void bounds(double* x0, double* x1, double* y0, double* y1) {
|
||||
bool any = false, bars = false;
|
||||
*x0 = *y0 = INFINITY; *x1 = *y1 = -INFINITY;
|
||||
for (int i = 0; i < F.n; i++) {
|
||||
const Series* s = &F.s[i];
|
||||
if (s->kind == S_BAR) bars = true;
|
||||
for (int k = 0; k < s->n; k++) {
|
||||
if (!isfinite(s->x[k]) || !isfinite(s->y[k])) continue;
|
||||
double bx = s->kind == S_BAR ? 0.4 : 0;
|
||||
if (s->x[k] - bx < *x0) *x0 = s->x[k] - bx;
|
||||
if (s->x[k] + bx > *x1) *x1 = s->x[k] + bx;
|
||||
if (s->y[k] < *y0) *y0 = s->y[k];
|
||||
if (s->y[k] > *y1) *y1 = s->y[k];
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
if (!any) { *x0 = 0; *x1 = 1; *y0 = 0; *y1 = 1; }
|
||||
if (bars && *y0 > 0) *y0 = 0;
|
||||
if (*x1 - *x0 < 1e-12) { *x0 -= 0.5; *x1 += 0.5; }
|
||||
if (*y1 - *y0 < 1e-12) { *y0 -= 0.5; *y1 += 0.5; }
|
||||
double mx = (*x1 - *x0) * 0.05, my = (*y1 - *y0) * 0.05; /* folga, como no matplotlib */
|
||||
*x0 -= mx; *x1 += mx;
|
||||
if (!(bars && *y0 == 0)) *y0 -= my;
|
||||
*y1 += my;
|
||||
if (F.xlim) { *x0 = F.x0; *x1 = F.x1; }
|
||||
if (F.ylim) { *y0 = F.y0; *y1 = F.y1; }
|
||||
}
|
||||
|
||||
TinyBlocks_Image* tb_plot_render(void) {
|
||||
int W = F.w, H = F.h;
|
||||
TinyBlocks_Image* img = tb_image_new(W, H, 4);
|
||||
if (!img) return NULL;
|
||||
Canvas c = { tb_image_data(img), W, H, 0, 0, W, H };
|
||||
memset(c.p, 255, (size_t)W * H * 4);
|
||||
double x0, x1, y0, y1;
|
||||
bounds(&x0, &x1, &y0, &y1);
|
||||
double xs = nice_step(x1 - x0, W / 90), ys = nice_step(y1 - y0, H / 55);
|
||||
/* margem esquerda pela largura das marcas do eixo y */
|
||||
int ylw = 0;
|
||||
char buf[64];
|
||||
for (double v = ceil(y0 / ys) * ys; v <= y1 + ys * 1e-9; v += ys) {
|
||||
num_text(v, ys, buf, sizeof(buf));
|
||||
int w = text_w(buf);
|
||||
if (w > ylw) ylw = w;
|
||||
}
|
||||
int L = 12 + ylw + 8 + (F.ylabel[0] ? PLOT_FONT_H + 4 : 0);
|
||||
int T = F.title[0] ? PLOT_FONT_H + 14 : 12;
|
||||
int R = 16, B = PLOT_FONT_H + 16 + (F.xlabel[0] ? PLOT_FONT_H + 4 : 0);
|
||||
int px0 = L, px1 = W - R, py0 = T, py1 = H - B;
|
||||
if (px1 - px0 < 20 || py1 - py0 < 20) return img;
|
||||
#define SX(v) (px0 + (float)(((v) - x0) / (x1 - x0)) * (px1 - px0))
|
||||
#define SY(v) (py1 - (float)(((v) - y0) / (y1 - y0)) * (py1 - py0))
|
||||
const uint32_t axis = 0x333333, gridc = 0xdddddd;
|
||||
/* barras com nomes: as marcas do x sao os nomes */
|
||||
const Series* named = NULL;
|
||||
for (int i = 0; i < F.n; i++) if (F.s[i].kind == S_BAR && F.s[i].names) named = &F.s[i];
|
||||
/* grade e marcas */
|
||||
for (double v = ceil(y0 / ys) * ys; v <= y1 + ys * 1e-9; v += ys) {
|
||||
float y = SY(v);
|
||||
if (F.grid) fill_rect(&c, px0, y - .5f, px1, y + .5f, gridc, 1);
|
||||
fill_rect(&c, px0 - 4, y - .5f, px0, y + .5f, axis, 1);
|
||||
num_text(v, ys, buf, sizeof(buf));
|
||||
text(&c, px0 - 7 - text_w(buf), (int)(y - PLOT_FONT_BASE * 0.5f - 3), buf, axis, false);
|
||||
}
|
||||
if (named) {
|
||||
float last = -1e9f; /* nomes que encostariam no anterior: pula */
|
||||
for (int k = 0; k < named->n; k++) {
|
||||
float x = SX(named->x[k]);
|
||||
fill_rect(&c, x - .5f, py1, x + .5f, py1 + 4, axis, 1);
|
||||
const char* nm = named->names[k] ? named->names[k] : "";
|
||||
int w = text_w(nm);
|
||||
if (!w || x - w * 0.5f < last + 6) continue;
|
||||
text(&c, (int)(x - w * 0.5f), py1 + 6, nm, axis, false);
|
||||
last = x + w * 0.5f;
|
||||
}
|
||||
} else {
|
||||
for (double v = ceil(x0 / xs) * xs; v <= x1 + xs * 1e-9; v += xs) {
|
||||
float x = SX(v);
|
||||
if (F.grid) fill_rect(&c, x - .5f, py0, x + .5f, py1, gridc, 1);
|
||||
fill_rect(&c, x - .5f, py1, x + .5f, py1 + 4, axis, 1);
|
||||
num_text(v, xs, buf, sizeof(buf));
|
||||
text(&c, (int)(x - text_w(buf) * 0.5f), py1 + 6, buf, axis, false);
|
||||
}
|
||||
}
|
||||
/* series, recortadas na area do grafico */
|
||||
Canvas in = c;
|
||||
in.cx0 = px0; in.cy0 = py0; in.cx1 = px1; in.cy1 = py1;
|
||||
for (int i = 0; i < F.n; i++) {
|
||||
const Series* s = &F.s[i];
|
||||
for (int k = 0; k < s->n; k++) {
|
||||
if (!isfinite(s->x[k]) || !isfinite(s->y[k])) continue;
|
||||
float x = SX(s->x[k]), y = SY(s->y[k]);
|
||||
if (s->kind == S_BAR) {
|
||||
float hw = (float)(0.4 / (x1 - x0) * (px1 - px0));
|
||||
double base = y0 > 0 ? y0 : y1 < 0 ? y1 : 0; /* barras partem do zero (ou da borda) */
|
||||
fill_rect(&in, x - hw, SY(base), x + hw, y, s->color, 1);
|
||||
} else if (s->kind == S_SCATTER) {
|
||||
disc(&in, x, y, 3.f, s->color);
|
||||
} else if (k > 0 && isfinite(s->x[k - 1]) && isfinite(s->y[k - 1])) {
|
||||
line(&in, SX(s->x[k - 1]), SY(s->y[k - 1]), x, y, 1.8f, s->color);
|
||||
} else if (s->n == 1) disc(&in, x, y, 2.f, s->color);
|
||||
}
|
||||
}
|
||||
/* moldura, titulo e nomes dos eixos */
|
||||
fill_rect(&c, px0 - .5f, py0, px0 + .5f, py1, axis, 1);
|
||||
fill_rect(&c, px0, py1 - .5f, px1, py1 + .5f, axis, 1);
|
||||
fill_rect(&c, px1 - .5f, py0, px1 + .5f, py1, 0xbbbbbb, 1);
|
||||
fill_rect(&c, px0, py0 - .5f, px1, py0 + .5f, 0xbbbbbb, 1);
|
||||
if (F.title[0]) text(&c, (px0 + px1 - text_w(F.title)) / 2, 5, F.title, 0x111111, false);
|
||||
if (F.xlabel[0]) text(&c, (px0 + px1 - text_w(F.xlabel)) / 2, H - PLOT_FONT_H - 4, F.xlabel, axis, false);
|
||||
if (F.ylabel[0]) text(&c, 4, (py0 + py1 + text_w(F.ylabel)) / 2, F.ylabel, axis, true);
|
||||
/* legenda: canto de cima a direita */
|
||||
if (F.legend) {
|
||||
int rows = 0, lw = 0;
|
||||
for (int i = 0; i < F.n; i++) if (F.s[i].label[0]) { rows++; int w = text_w(F.s[i].label); if (w > lw) lw = w; }
|
||||
if (rows) {
|
||||
int bw = lw + 40, bh = rows * (PLOT_FONT_H + 2) + 8;
|
||||
int bx = px1 - bw - 8, by = py0 + 8;
|
||||
fill_rect(&c, bx, by, bx + bw, by + bh, 0xffffff, 0.9f);
|
||||
fill_rect(&c, bx, by, bx + bw, by + 1, 0xcccccc, 1);
|
||||
fill_rect(&c, bx, by + bh - 1, bx + bw, by + bh, 0xcccccc, 1);
|
||||
fill_rect(&c, bx, by, bx + 1, by + bh, 0xcccccc, 1);
|
||||
fill_rect(&c, bx + bw - 1, by, bx + bw, by + bh, 0xcccccc, 1);
|
||||
int ry = by + 4;
|
||||
for (int i = 0; i < F.n; i++) {
|
||||
const Series* s = &F.s[i];
|
||||
if (!s->label[0]) continue;
|
||||
float cy = ry + PLOT_FONT_H * 0.5f;
|
||||
if (s->kind == S_LINE) line(&c, bx + 6, cy, bx + 24, cy, 1.8f, s->color);
|
||||
else if (s->kind == S_SCATTER) disc(&c, bx + 15, cy, 3.f, s->color);
|
||||
else fill_rect(&c, bx + 8, cy - 4, bx + 22, cy + 4, s->color, 1);
|
||||
text(&c, bx + 28, ry, s->label, 0x222222, false);
|
||||
ry += PLOT_FONT_H + 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
#undef SX
|
||||
#undef SY
|
||||
return img;
|
||||
}
|
||||
|
||||
/* == Valores ========================================================== */
|
||||
/* Numeros de um valor: tensor, lista ou texto "1, 2, 3"; malloc ou NULL */
|
||||
static float* numbers(TinyBlocks* rt, TinyBlocks_Value v, int* n) {
|
||||
*n = 0;
|
||||
const TbTensorApi* api = tb_tensor_api(rt);
|
||||
const TbTensor* t = api ? api->of_value(v) : NULL;
|
||||
if (t) {
|
||||
float* out = malloc((t->n ? t->n : 1) * sizeof(float));
|
||||
if (out) { memcpy(out, t->d, t->n * sizeof(float)); *n = (int)t->n; }
|
||||
return out;
|
||||
}
|
||||
TinyBlocks_JsonValue* j = v.kind == TB_VALUE_JSON ? v.as.json : NULL;
|
||||
bool own = false;
|
||||
if (!j && v.kind == TB_VALUE_TEXT && v.as.text) {
|
||||
const char* s = v.as.text;
|
||||
while (isspace((unsigned char)*s)) s++;
|
||||
if (*s == '[') { j = tb_json_parse(s, NULL, 0); own = j != NULL; }
|
||||
}
|
||||
if (j && tb_json_kind(j) == TB_JSON_ARRAY) {
|
||||
uint32_t len = tb_json_array_length(j);
|
||||
float* out = malloc((len ? len : 1) * sizeof(float));
|
||||
for (uint32_t i = 0; out && i < len; i++) {
|
||||
TinyBlocks_JsonValue* e = tb_json_array_get(j, i);
|
||||
const char* es = tb_json_as_string(e);
|
||||
out[i] = es ? (float)strtod(es, NULL) : (float)tb_json_as_number(e, 0);
|
||||
tb_json_release(e);
|
||||
}
|
||||
if (own) tb_json_release(j);
|
||||
*n = out ? (int)len : 0;
|
||||
return out;
|
||||
}
|
||||
if (own) tb_json_release(j);
|
||||
double d;
|
||||
if (v.kind != TB_VALUE_TEXT && tb_value_to_number(v, &d)) {
|
||||
float* out = malloc(sizeof(float));
|
||||
if (out) { out[0] = (float)d; *n = 1; }
|
||||
return out;
|
||||
}
|
||||
char* s = tb_value_to_string(v); /* "1, 2, 3" ou "1 2 3" */
|
||||
int cap = 64;
|
||||
float* out = malloc((size_t)cap * sizeof(float));
|
||||
for (char* p = s; out && p && *p; ) {
|
||||
while (*p && !(isdigit((unsigned char)*p) || *p == '-' || *p == '.' || *p == '+')) p++;
|
||||
if (!*p) break;
|
||||
char* e;
|
||||
double x = strtod(p, &e);
|
||||
if (e == p) { p++; continue; }
|
||||
if (*n == cap) { cap *= 2; float* q = realloc(out, (size_t)cap * sizeof(float)); if (!q) break; out = q; }
|
||||
out[(*n)++] = (float)x;
|
||||
p = e;
|
||||
}
|
||||
free(s);
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Nomes (barras): lista JSON ou "a, b, c" */
|
||||
static char** names_of(TinyBlocks_Value v, int n) {
|
||||
char** out = calloc((size_t)(n ? n : 1), sizeof(char*));
|
||||
if (!out) return NULL;
|
||||
if (v.kind == TB_VALUE_JSON && tb_json_kind(v.as.json) == TB_JSON_ARRAY) {
|
||||
for (int i = 0; i < n && i < (int)tb_json_array_length(v.as.json); i++) {
|
||||
TinyBlocks_JsonValue* e = tb_json_array_get(v.as.json, (uint32_t)i);
|
||||
TinyBlocks_Value ev = tb_value_json(e);
|
||||
out[i] = tb_value_to_string(ev);
|
||||
tb_value_free(&ev);
|
||||
tb_json_release(e);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
char* s = tb_value_to_string(v);
|
||||
char* p = s;
|
||||
for (int i = 0; p && *p && i < n; i++) {
|
||||
char* e = strchr(p, ',');
|
||||
size_t len = e ? (size_t)(e - p) : strlen(p);
|
||||
while (len && isspace((unsigned char)*p)) { p++; len--; }
|
||||
while (len && isspace((unsigned char)p[len - 1])) len--;
|
||||
out[i] = strndup(p, len);
|
||||
p = e ? e + 1 : NULL;
|
||||
}
|
||||
free(s);
|
||||
return out;
|
||||
}
|
||||
|
||||
/* == Series com nome (crescem a cada passo) =========================== */
|
||||
typedef struct { char name[64]; float* v; int n, cap; } Named;
|
||||
static Named* s_named;
|
||||
static int s_named_n;
|
||||
|
||||
static Named* named(const char* name, bool create) {
|
||||
for (int i = 0; i < s_named_n; i++) if (!strcmp(s_named[i].name, name)) return &s_named[i];
|
||||
if (!create) return NULL;
|
||||
Named* p = realloc(s_named, (size_t)(s_named_n + 1) * sizeof(*p));
|
||||
if (!p) return NULL;
|
||||
s_named = p;
|
||||
Named* s = &s_named[s_named_n++];
|
||||
memset(s, 0, sizeof(*s));
|
||||
snprintf(s->name, sizeof(s->name), "%s", name);
|
||||
return s;
|
||||
}
|
||||
|
||||
/* == Blocos =========================================================== */
|
||||
static void eval_figure(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
tb_plot_figure((int)tb_block_input_integer(self, rt, 0, 480), (int)tb_block_input_integer(self, rt, 1, 320));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void plot_xy(TinyBlocks_Block* self, TinyBlocks* rt, int kind, bool with_x) {
|
||||
int nx = 0, ny = 0;
|
||||
float* x = with_x ? numbers(rt, tb_block_get_input(self, rt, 0), &nx) : NULL;
|
||||
float* y = numbers(rt, tb_block_get_input(self, rt, with_x ? 1 : 0), &ny);
|
||||
uint32_t c0 = with_x ? 2 : 1;
|
||||
if (with_x && nx != ny) tinyblocks_set_error(rt, "o x tem %d números e o y tem %d", nx, ny);
|
||||
else if (y) add(kind, x, y, ny, tb_block_input_text(self, rt, c0), tb_block_input_text(self, rt, c0 + 1));
|
||||
free(x); free(y);
|
||||
self->dirty = false;
|
||||
}
|
||||
static void eval_line(TinyBlocks_Block* self, TinyBlocks* rt) { plot_xy(self, rt, S_LINE, false); }
|
||||
static void eval_line_xy(TinyBlocks_Block* self, TinyBlocks* rt) { plot_xy(self, rt, S_LINE, true); }
|
||||
static void eval_scatter(TinyBlocks_Block* self, TinyBlocks* rt) { plot_xy(self, rt, S_SCATTER, true); }
|
||||
|
||||
static void eval_bar(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
int n = 0;
|
||||
float* y = numbers(rt, tb_block_get_input(self, rt, 0), &n);
|
||||
Series* s = y ? add(S_BAR, NULL, y, n, tb_block_input_text(self, rt, 2), "") : NULL;
|
||||
TinyBlocks_Value nv = tb_block_get_input(self, rt, 1);
|
||||
if (s && nv.kind != TB_VALUE_NONE && tb_block_input_text(self, rt, 1)[0]) s->names = names_of(nv, n);
|
||||
free(y);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_hist(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
int n = 0, bins = (int)tb_block_input_integer(self, rt, 1, 10);
|
||||
if (bins < 1) bins = 1;
|
||||
if (bins > 1000) bins = 1000;
|
||||
float* v = numbers(rt, tb_block_get_input(self, rt, 0), &n);
|
||||
if (v && n) {
|
||||
float lo = v[0], hi = v[0];
|
||||
for (int i = 1; i < n; i++) { if (v[i] < lo) lo = v[i]; if (v[i] > hi) hi = v[i]; }
|
||||
if (hi <= lo) hi = lo + 1;
|
||||
float* cnt = calloc((size_t)bins, sizeof(float));
|
||||
float* xs = malloc((size_t)bins * sizeof(float));
|
||||
for (int i = 0; cnt && i < n; i++) {
|
||||
int b = (int)((v[i] - lo) / (hi - lo) * bins);
|
||||
if (b >= bins) b = bins - 1;
|
||||
cnt[b] += 1;
|
||||
}
|
||||
for (int b = 0; xs && b < bins; b++) xs[b] = lo + (b + 0.5f) * (hi - lo) / bins;
|
||||
if (cnt && xs) {
|
||||
Series* s = add(S_BAR, NULL, cnt, bins, tb_block_input_text(self, rt, 2), "");
|
||||
if (s) { /* barras no centro de cada faixa, numa escala 1..bins */
|
||||
for (int b = 0; b < bins; b++) s->x[b] = (float)(b + 1);
|
||||
s->names = calloc((size_t)bins, sizeof(char*));
|
||||
for (int b = 0; s->names && b < bins; b++) {
|
||||
char t[32];
|
||||
snprintf(t, sizeof(t), "%.3g", xs[b]);
|
||||
s->names[b] = strdup(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
free(cnt); free(xs);
|
||||
}
|
||||
free(v);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
#define TEXT_SETTER(name, field) \
|
||||
static void name(TinyBlocks_Block* self, TinyBlocks* rt) { \
|
||||
snprintf(F.field, sizeof(F.field), "%s", tb_block_input_text(self, rt, 0)); \
|
||||
self->dirty = false; }
|
||||
TEXT_SETTER(eval_title, title)
|
||||
TEXT_SETTER(eval_xlabel, xlabel)
|
||||
TEXT_SETTER(eval_ylabel, ylabel)
|
||||
|
||||
static void eval_legend(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; F.legend = true; self->dirty = false; }
|
||||
static void eval_grid(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; F.grid = true; self->dirty = false; }
|
||||
|
||||
static void eval_xlim(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
F.x0 = tb_block_input_number(self, rt, 0, 0); F.x1 = tb_block_input_number(self, rt, 1, 1);
|
||||
F.xlim = F.x1 > F.x0;
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_ylim(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
F.y0 = tb_block_input_number(self, rt, 0, 0); F.y1 = tb_block_input_number(self, rt, 1, 1);
|
||||
F.ylim = F.y1 > F.y0;
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_push(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
int n = 0;
|
||||
float* v = numbers(rt, tb_block_get_input(self, rt, 0), &n);
|
||||
Named* s = named(tb_block_input_text(self, rt, 1), true);
|
||||
for (int i = 0; s && v && i < n; i++) {
|
||||
if (s->n == s->cap) {
|
||||
int nc = s->cap ? s->cap * 2 : 256;
|
||||
float* p = realloc(s->v, (size_t)nc * sizeof(float));
|
||||
if (!p) break;
|
||||
s->v = p; s->cap = nc;
|
||||
}
|
||||
s->v[s->n++] = v[i];
|
||||
}
|
||||
free(v);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_series_plot(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
const char* nm = tb_block_input_text(self, rt, 0);
|
||||
Named* s = named(nm, false);
|
||||
if (s && s->n) add(S_LINE, NULL, s->v, s->n, tb_block_input_text(self, rt, 1), nm);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_series_clear(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
Named* s = named(tb_block_input_text(self, rt, 0), false);
|
||||
if (s) s->n = 0;
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_series_len(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
Named* s = named(tb_block_input_text(self, rt, 0), false);
|
||||
tb_block_set_output(self, 0, tb_value_integer(s ? s->n : 0));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_image(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
(void)rt;
|
||||
TinyBlocks_Image* img = tb_plot_render();
|
||||
if (img) { tb_block_set_output(self, 0, tb_value_image(img)); tb_image_release(img); }
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_save(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
const char* path = tb_block_input_text(self, rt, 0);
|
||||
TinyBlocks_Image* img = tb_plot_render();
|
||||
if (!img || !tb_image_save(img, path))
|
||||
tinyblocks_set_error(rt, "não gravou '%s' (o formato da extensão está carregado?)", path);
|
||||
tb_image_release(img);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
/* == Registro ========================================================= */
|
||||
typedef struct {
|
||||
const char* name; const char* label; const char* defs;
|
||||
int nin; TinyBlocks_ValueKind in[4];
|
||||
int out; /* 0 comando, 1 imagem, 2 numero */
|
||||
void (*fn)(TinyBlocks_Block*, TinyBlocks*); const char* fname; const char* doc;
|
||||
} Spec;
|
||||
|
||||
#define N TB_VALUE_NONE
|
||||
#define T TB_VALUE_TEXT
|
||||
#define I TB_VALUE_INTEGER
|
||||
#define R TB_VALUE_REAL
|
||||
#define S(fn) fn, #fn
|
||||
static const Spec s_specs[] = {
|
||||
{ "Plot.Figure", "nova figura de %1 por %2", "480|320", 2, {I,I}, 0, S(eval_figure), "Limpa a figura (largura e altura em pixels)" },
|
||||
{ "Plot.Line", "plote %1 cor %2 rótulo %3", "1, 4, 2, 5||", 3, {N,T,T}, 0, S(eval_line), "Linha dos valores (x = 1, 2, 3...)" },
|
||||
{ "Plot.LineXY", "plote %2 em função de %1 cor %3 rótulo %4", "1, 2, 3|1, 4, 9||", 4, {N,N,T,T}, 0, S(eval_line_xy), "Linha de y em função de x" },
|
||||
{ "Plot.Scatter", "pontos %2 em função de %1 cor %3 rótulo %4", "1, 2, 3|1, 4, 9||", 4, {N,N,T,T}, 0, S(eval_scatter), "Um ponto para cada (x, y)" },
|
||||
{ "Plot.Bar", "barras %1 com nomes %2 cor %3", "3, 5, 2|a, b, c|", 3, {N,N,T}, 0, S(eval_bar), "Barras dos valores, com nomes no eixo x" },
|
||||
{ "Plot.Hist", "histograma de %1 com %2 faixas cor %3", "|10|", 3, {N,I,T}, 0, S(eval_hist), "Quantos valores caem em cada faixa" },
|
||||
{ "Plot.Title", "título da figura %1", "Gráfico", 1, {T}, 0, S(eval_title), "Título no alto" },
|
||||
{ "Plot.XLabel", "nome do eixo x %1", "x", 1, {T}, 0, S(eval_xlabel), "Texto embaixo do eixo x" },
|
||||
{ "Plot.YLabel", "nome do eixo y %1", "y", 1, {T}, 0, S(eval_ylabel), "Texto ao lado do eixo y" },
|
||||
{ "Plot.Legend", "mostre a legenda", "", 0, {N}, 0, S(eval_legend), "Caixa com o rótulo de cada série" },
|
||||
{ "Plot.Grid", "mostre a grade", "", 0, {N}, 0, S(eval_grid), "Linhas de grade nas marcas" },
|
||||
{ "Plot.XLim", "eixo x de %1 até %2", "0|10", 2, {R,R}, 0, S(eval_xlim), "Limites do eixo x" },
|
||||
{ "Plot.YLim", "eixo y de %1 até %2", "0|10", 2, {R,R}, 0, S(eval_ylim), "Limites do eixo y" },
|
||||
{ "Plot.Push", "acrescente %1 à série %2", "0|perda", 2, {N,T}, 0, S(eval_push), "Junta valores no fim de uma série com nome" },
|
||||
{ "Plot.Series", "plote a série %1 cor %2", "perda|", 2, {T,T}, 0, S(eval_series_plot), "Linha da série com nome (rótulo = o nome)" },
|
||||
{ "Plot.SeriesClear", "apague a série %1", "perda", 1, {T}, 0, S(eval_series_clear), "Esvazia a série" },
|
||||
{ "Plot.SeriesLen", "tamanho da série %1", "perda", 1, {T}, 2, S(eval_series_len), "Quantos valores a série tem" },
|
||||
{ "Plot.Image", "imagem da figura", "", 0, {N}, 1, S(eval_image), "Desenha a figura numa imagem" },
|
||||
{ "Plot.Save", "salve a figura em %1", "grafico.png", 1, {T}, 0, S(eval_save), "Grava a figura (.png, .bmp ou .ppm)" },
|
||||
};
|
||||
#undef N
|
||||
#undef T
|
||||
#undef I
|
||||
#undef R
|
||||
|
||||
static bool plot_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
static const TinyBlocks_Category cat = { "Gráficos", {0.15f, 0.62f, 0.55f, 1.f}, {0.10f, 0.47f, 0.42f, 1.f} };
|
||||
tb_library_set_category(lib, &cat);
|
||||
static const char* names[] = { "a", "b", "c", "d" };
|
||||
static const TinyBlocks_SlotDesc out_img[] = {{"imagem", TB_VALUE_IMAGE}};
|
||||
static const TinyBlocks_SlotDesc out_num[] = {{"valor", TB_VALUE_INTEGER}};
|
||||
for (size_t i = 0; i < sizeof(s_specs) / sizeof(s_specs[0]); i++) {
|
||||
const Spec* sp = &s_specs[i];
|
||||
TinyBlocks_SlotDesc in[4];
|
||||
for (int k = 0; k < sp->nin; k++) in[k] = (TinyBlocks_SlotDesc){ names[k], sp->in[k] };
|
||||
const TinyBlocks_SlotDesc* out = sp->out == 1 ? out_img : sp->out == 2 ? out_num : NULL;
|
||||
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, sp->name, sp->nin ? in : NULL, (uint32_t)sp->nin,
|
||||
out, out ? 1u : 0u, sp->fn);
|
||||
if (!t) return false;
|
||||
tb_type_block_set_label(t, sp->label, sp->defs);
|
||||
tb_meta_declare(sp->name, sp->fname, __FILE__, sp->doc);
|
||||
if (!tb_library_add(lib, &t->base)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static void plot_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
(void)rt; (void)lib;
|
||||
tb_plot_figure(480, 320);
|
||||
free(F.s); F.s = NULL; F.cap = 0;
|
||||
for (int i = 0; i < s_named_n; i++) free(s_named[i].v);
|
||||
free(s_named); s_named = NULL; s_named_n = 0;
|
||||
}
|
||||
|
||||
TINYBLOCKS_DEFINE_LIBRARY(plot, "tinyblocks-plot", "1.0.0", plot_init, plot_deinit)
|
||||
|
||||
const TinyBlocks_LibraryDescriptor* tb_plot_get_library(void) {
|
||||
return &_tb_lib_desc_plot;
|
||||
}
|
||||
Reference in new issue
Block a user