VM: guarda de travamento por tempo; vm_push sem memset de 420 bytes

Com a VM rápida, um render 3D normal passa de 500 mil comandos dentro
da fatia de 12 ms, e o limite de passos por quadro abortava o programa
("limite de passos atingido") em parte das vezes, conforme onde o
quadro cortava. O guarda agora é por tempo: um laço que fica 3 s sem
pausa (corpo de Meus Blocos) é parado; laços comuns pausam a cada volta.

vm_push zerava o TinyBlocks_Flow inteiro (dois textos de erro) a cada
"se" executado; agora só os campos. shape_of só para comandos comuns.

vm_bench: diagnóstico (variáveis e pilhas) quando um render não termina.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mguinhosandClaude Opus 5.5 committed 2026-10-23 17:28:47 -03:00
1 parent b4a27f0180
commit f4313417c0
3 files changed
+99 -52

No files matched your search

@@ -190,7 +190,6 @@ enum { IT_SEL = 0, IT_BRUSH, IT_LINE, IT_RECT, IT_ELLIPSE,
#define MAX_FLY 192
#define MAX_CATS 24
#define MAX_CALL_DEPTH 32
#define MAX_STEPS 500000L
#define MAX_RUN_BLOCKS 200000
#define STAGE_BUF 16384
#define LIT_TEXT_CAP 512
@@ -871,6 +870,7 @@ typedef struct Ed {
CallFrame frames[MAX_CALL_DEPTH];
int frame_n;
long steps;
unsigned vm_t0; /* inicio do quadro da VM (guarda de travamento) */
bool abort;
char abort_msg[160];
TinyBlocks_Block** run_blocks; /* instâncias criadas na última execução */
+19 -5
View File
@@ -1399,8 +1399,15 @@ static void err_uncaught(Ed* ed, const char* msg) {
stage_append(ed, line);
}
/* Guarda contra um laco que nunca devolve o controle (corpo de Meus Blocos
roda sem pausas): por tempo, nao por passos, que a VM rapida faz meio
milhao de passos num render normal. Laços comuns pausam a cada volta e o
quadro ja corta em vm_frame_ms. */
#define VM_STALL_MS 3000u
static unsigned now_ms(void);
static bool step(Ed* ed) {
if (++ed->steps > MAX_STEPS) run_abort(ed, "limite de passos atingido (laço infinito?)");
if ((++ed->steps & 1023) == 0 && now_ms() - ed->vm_t0 > VM_STALL_MS)
run_abort(ed, "o script ficou 3 s sem pausa (laço infinito?)");
return !ed->abort;
}
@@ -1438,7 +1445,12 @@ static void vm_push(Ed* ed, VmThread* th, Tab* T, int bi, int kind) {
if (th->sp >= VM_STACK) { run_abort(ed, "blocos aninhados demais"); return; }
VmFrame* f = &th->st[th->sp++];
f->T = T; f->bi = bi; f->kind = kind;
memset(&f->flow, 0, sizeof(f->flow));
/* sem memset: a struct tem ~420 bytes (textos de erro) e isto roda a
cada "se" executado; as strings so precisam comecar vazias */
f->flow.step = 0;
f->flow.count = 0;
f->flow.pending[0] = 0;
f->flow.saved[0] = 0;
f->flow.rt = ed->rt;
f->flow.arg = flow_arg;
}
@@ -1493,10 +1505,10 @@ static bool vm_step(Ed* ed, VmThread* th, bool sync) {
if (!step(ed)) break;
TinyBlocks_TypeBlock* t = blk_type(ed, b);
if (!t) continue;
Shape sh = shape_of(t);
if (sh == SH_HAT || shape_is_value(sh)) continue;
if (t->flow) { vm_push(ed, th, T, bi, VF_FLOW); continue; }
if ((t->pure == TB_PURE_SET_VAR || t->pure == TB_PURE_CHANGE_VAR) && jit_stmt(ed, T, bi, t)) continue;
Shape sh = shape_of(t);
if (sh == SH_HAT || shape_is_value(sh)) continue;
TinyBlocks_Block* r = get_rt(ed, T, bi);
if (r) tb_block_eval(r, ed->rt);
if (t->flags & TB_TYPE_REDRAW) ed->redraw_req = true; /* caneta: mostra este quadro */
@@ -1573,6 +1585,7 @@ static void run_begin(Ed* ed, bool clear) {
define_sync(ed); /* "devolva" novo no corpo de um "defina" */
run_reset(ed);
ed->steps = 0; ed->abort = false; ed->abort_msg[0] = 0; ed->frame_n = 0;
ed->vm_t0 = now_ms();
ed->live_tab = &CT;
ed->vm_var_n = tb_variables_count();
if (clear) ed->stage_buf[0] = 0;
@@ -1593,7 +1606,8 @@ static void vm_frame(Ed* ed) {
cap_begin(ed);
unsigned t0 = now_ms();
ed->redraw_req = false;
ed->steps = 0; /* limite de passos vale por quadro */
ed->steps = 0;
ed->vm_t0 = t0; /* guarda de travamento (step) */
bool alive;
do {
alive = false;
+79 -46
View File
@@ -1,8 +1,12 @@
#define _POSIX_C_SOURCE 200809L
/* vm_bench.c - mede a VM do editor rodando um projeto sem janela.
* Uso: build/vm_bench projeto.json [quadros]
* Clica a bandeira e, a cada quadro do editor, liga a variavel "mudou"
* (o Minecraft so redesenha quando a camera mexe) e mede o tempo do quadro. */
* Uso: build/vm_bench projeto.json [renders]
* Clica a bandeira e, a cada render, liga a variavel "mudou" (o Minecraft so
* redesenha quando a camera mexe) e mede quanto o render leva.
* BENCH_STEP=n gira a camera n graus por render (padrao 3)
* BENCH_CAM=x,y,z,p camera fixa (cx, cy, cz, pit)
* BENCH_PROFILE=1 so renderiza, sem medir (para o callgrind)
* TINYBLOCKS_NO_JIT=1 desliga o compilador; TINYBLOCKS_VM_MS troca a fatia. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -30,9 +34,15 @@
static TinyBlocks* rt;
static TinyBlocks_Block *ev, *scene;
static double now(void);
static double t_eval, t_draw;
static double now(void) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return t.tv_sec + t.tv_nsec / 1e9;
}
/* Um quadro do editor: entrada + VM (eval) e desenho */
static void frame(void) {
tb_block_set_output(ev, GFX_IN_WIN_W, tb_value_integer(1280));
tb_block_set_output(ev, GFX_IN_WIN_H, tb_value_integer(720));
@@ -43,19 +53,52 @@ static void frame(void) {
double b = now();
TinyBlocks_RenderableBlock* rb = NULL;
scene->type->on_draw(scene, rt, &rb);
t_eval += b - a; t_draw += now() - b;
t_eval += b - a;
t_draw += now() - b;
tb_renderable_release_all();
}
static double now(void) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return t.tv_sec + t.tv_nsec / 1e9;
static double var_num(const char* name) {
const TinyBlocks_Value* v = tb_vars_get(name);
return v ? tb_value_as_number(*v, 0) : 0;
}
/* Diagnostico: a VM nao terminou o que devia (variaveis e pilhas) */
static void diag(Ed* ed) {
const char* show[] = { "i", "j", "nf", "f", "mudou", "k", "tt", "pyy", "pxx", "y0", "y1", "x0", "x1" };
for (int q = 0; q < (int)(sizeof(show) / sizeof(show[0])); q++) {
const TinyBlocks_Value* v = tb_vars_get(show[q]);
char buf[64] = "-";
if (v) tb_value_to_text(*v, buf, sizeof(buf));
fprintf(stderr, " %s=%s", show[q], buf);
}
fprintf(stderr, "\nvm_running=%d vm_n=%d\n", ed->vm_running, ed->vm_n);
for (int t = 0; t < ed->vm_n; t++)
for (int k = 0; k < ed->vm[t].sp; k++) {
VmFrame* f = &ed->vm[t].st[k];
int bi = f->bi;
const char* ty = bi >= 0 && f->T->ws[bi].type ? f->T->ws[bi].type->type_name : "?";
fprintf(stderr, " thread %d nivel %d: %s bi=%d %s count=%lld\n", t, k,
f->kind == VF_FLOW ? "C" : "pilha", bi, ty, (long long)f->flow.count);
}
}
/* Camera fixa (BENCH_CAM) */
static void set_cam(int yaw) {
tb_vars_set("yaw", tb_value_integer(yaw));
const char* cam = getenv("BENCH_CAM");
if (!cam) return;
double c[4] = {0};
sscanf(cam, "%lf,%lf,%lf,%lf", &c[0], &c[1], &c[2], &c[3]);
const char* nm[4] = { "cx", "cy", "cz", "pit" };
for (int q = 0; q < 4; q++) tb_vars_set(nm[q], tb_value_real(c[q]));
}
int main(int argc, char** argv) {
if (argc < 2) { fprintf(stderr, "uso: %s projeto.json [quadros]\n", argv[0]); return 2; }
if (argc < 2) { fprintf(stderr, "uso: %s projeto.json [renders]\n", argv[0]); return 2; }
int frames = argc > 2 ? atoi(argv[2]) : 20;
int step = getenv("BENCH_STEP") ? atoi(getenv("BENCH_STEP")) : 3;
setvbuf(stdout, NULL, _IOLBF, 0);
setenv("XDG_CONFIG_HOME", "/tmp/tb_bench_cfg", 1);
setenv("TINYBLOCKS_MCP_PORT", "0", 1);
tinyblocks_init(&rt, NULL);
@@ -83,61 +126,51 @@ int main(int argc, char** argv) {
tab_select(ed, ed->tab_n - 1); /* a ultima aba (o programa) */
frame();
run_flag(ed);
/* quadros do editor ate o primeiro desenho completo (setup + 1o render) */
if (getenv("BENCH_PROFILE")) { /* so render: "mudou" sempre ligado */
if (getenv("BENCH_PROFILE")) { /* so render: "mudou" sempre ligado */
for (int k = 0; k < frames; k++) {
tb_vars_set("mudou", tb_value_integer(1));
const char* cam = getenv("BENCH_CAM");
if (cam) {
double c[4] = {0};
sscanf(cam, "%lf,%lf,%lf,%lf", &c[0], &c[1], &c[2], &c[3]);
const char* nm[4] = { "cx", "cy", "cz", "pit" };
for (int q = 0; q < 4; q++) tb_vars_set(nm[q], tb_value_real(c[q]));
tb_vars_set("yaw", tb_value_integer(270));
}
set_cam(270);
frame();
}
return 0;
}
/* preparacao + 1o render: ate "f" chegar em "nf" com "mudou" desligado */
double t0 = now();
int n = 0;
while (ed->vm_running && n < 100000) { frame(); n++; const TinyBlocks_Value* m = tb_vars_get("nf"); if (m && n > 2 && tb_vars_get("mudou") && tb_vars_get("mudou")->as.integer == 0 && tb_vars_get("f") && tb_value_as_number(*tb_vars_get("f"), 0) >= tb_value_as_number(*m, 0)) break; }
printf("setup + 1o quadro: %.3f s (%d quadros do editor)\n", now() - t0, n);
for (; ed->vm_running && n < 3000; n++) {
frame();
if (n > 2 && var_num("mudou") == 0 && var_num("nf") > 0 && var_num("f") >= var_num("nf")) break;
}
if (n >= 3000) { fprintf(stderr, "preparacao nao terminou\n"); diag(ed); return 1; }
printf("preparacao + 1o render: %.3f s (%d quadros do editor)\n", now() - t0, n);
double best = 1e9, sum = 0;
for (int k = 0; k < frames; k++) {
tb_vars_set("mudou", tb_value_integer(1));
const char* cam = getenv("BENCH_CAM"); /* "cx,cy,cz,pit": camera fixa */
if (cam) {
double c[4] = {0};
sscanf(cam, "%lf,%lf,%lf,%lf", &c[0], &c[1], &c[2], &c[3]);
const char* nm[4] = { "cx", "cy", "cz", "pit" };
for (int q = 0; q < 4; q++) tb_vars_set(nm[q], tb_value_real(c[q]));
}
tb_vars_set("yaw", tb_value_integer(k * (getenv("BENCH_STEP") ? atoi(getenv("BENCH_STEP")) : 3)));
set_cam(k * step);
double a = now();
t_eval = t_draw = 0;
int m = 0;
do { frame(); m++; } while (tb_vars_get("mudou")->as.integer == 1 || tb_value_as_number(*tb_vars_get("f"), 0) < tb_value_as_number(*tb_vars_get("nf"), 0));
/* o render termina quando f chega em nf de novo */
/* o render comeca quando o programa ve "mudou" e termina quando f chega em nf */
do {
frame();
if (++m == 3000) { fprintf(stderr, "render %d nao terminou\n", k); diag(ed); return 1; }
} while (var_num("mudou") == 1 || var_num("f") < var_num("nf"));
double dt = now() - a;
sum += dt; if (dt < best) best = dt;
printf("render %2d: %.1f ms (%d quadros do editor; VM+entrada %.1f ms, desenho %.1f ms = %.1f ms/quadro)\n",
k, dt * 1000, m, t_eval * 1000, t_draw * 1000, t_draw * 1000 / m);
}
const char* show[] = { "nf", "f", "tela", "x0", "pyy", "ok", "vis" };
for (int i = 0; i < 7; i++) {
const TinyBlocks_Value* v = tb_vars_get(show[i]);
char buf[64] = "(nao existe)";
if (v) tb_value_to_text(*v, buf, sizeof(buf));
printf(" %s = %s\n", show[i], buf);
sum += dt;
if (dt < best) best = dt;
printf("render %2d: %.1f ms (%d quadros do editor; VM+entrada %.1f ms, desenho %.1f ms)\n",
k, dt * 1000, m, t_eval * 1000, t_draw * 1000);
}
const TinyBlocks_Value* tv = tb_vars_get("tela");
if (tv && tv->kind == TB_VALUE_IMAGE) { /* checksum da tela (FNV-1a) */
if (tv && tv->kind == TB_VALUE_IMAGE) { /* checksum da tela (FNV-1a) */
const TinyBlocks_Image* im = tv->as.image;
const uint8_t* d = tb_image_data_const(im);
size_t n = (size_t)tb_image_width(im) * tb_image_height(im) * tb_image_channels(im);
size_t len = (size_t)tb_image_width(im) * tb_image_height(im) * tb_image_channels(im);
uint32_t h = 2166136261u;
for (size_t i = 0; i < n; i++) { h ^= d[i]; h *= 16777619u; }
for (size_t i = 0; i < len; i++) { h ^= d[i]; h *= 16777619u; }
printf(" checksum da tela: %08x\n", h);
}
printf("media %.1f ms, melhor %.1f ms\n", sum / frames * 1000, best * 1000);