- TinyBlocks_Result (tb_result.h): Ok | Erro com tag (enum) e payload,
ref-counted, que flui como TB_VALUE_RESULT. A library de erros passa a
produzir/consumir Result em vez de objetos JSON {"ok"/"erro"}.
- TinyBlocks_ValueClass (tb_value_class.h): cada kind de valor tem uma
"interface" (copy, release, to_text, to_number, truthy, equals,
type_name) numa tabela; tb_value_clone/free e as operacoes genericas
(tb_value_to_text, tb_value_to_number, tb_value_truthy, tb_value_equals,
tb_value_type_name) despacham por ela. Sem libm no core.
- Editor e as conversoes "texto de" / "número de" usam o despacho.
- make test-value: classes de valor e Result.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
313 lines
14 KiB
C
313 lines
14 KiB
C
/*
|
|
* TinyBlocks - tb_number.c
|
|
* Categoria "Números": matematica com numeros reais. Number.Div / Pow /
|
|
* Sqrt / Round / Floor / Ceil / RoundTo / Sin / Cos / Tan / Asin / Acos /
|
|
* Atan / Log10 / Ln / Exp / Pi / Random / Clamp / Format, os booleanos
|
|
* Number.IsEven / IsPrime / IsInteger e as conversoes Number.From (qualquer
|
|
* valor -> numero), Number.ToBase / FromBase (binario, hexadecimal, ...).
|
|
*
|
|
* Angulos em GRAUS, como no Scratch. Resultados inteiros saem como inteiro
|
|
* ("3", nao "3.0"); trigonometria e arredondada em 10 casas (sen 180 = 0).
|
|
*/
|
|
#define _DEFAULT_SOURCE
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <stdint.h>
|
|
#include <math.h>
|
|
#include <time.h>
|
|
|
|
#include <ctype.h>
|
|
#include <tinyblocks/tinyblocks.h>
|
|
#include "tb_number.h"
|
|
|
|
#ifndef M_PI
|
|
#define M_PI 3.14159265358979323846
|
|
#endif
|
|
#define DEG (M_PI / 180.0)
|
|
|
|
/* -- API ------------------------------------------------------------------ */
|
|
|
|
TB_API double tb_number_round_to(double x, int places) {
|
|
if (places < 0) places = 0;
|
|
if (places > 12) places = 12;
|
|
double k = pow(10.0, places);
|
|
return round(x * k) / k;
|
|
}
|
|
|
|
TB_API bool tb_number_is_prime(long long n) {
|
|
if (n < 2) return false;
|
|
if (n < 4) return true;
|
|
if (n % 2 == 0 || n % 3 == 0) return false;
|
|
for (long long i = 5; i <= n / i; i += 6)
|
|
if (n % i == 0 || n % (i + 2) == 0) return false;
|
|
return true;
|
|
}
|
|
|
|
TB_API void tb_number_format(double x, int places, char* out, size_t cap) {
|
|
if (!out || !cap) return;
|
|
if (places >= 0) {
|
|
if (places > 12) places = 12;
|
|
snprintf(out, cap, "%.*f", places, x);
|
|
return;
|
|
}
|
|
snprintf(out, cap, "%.10f", x); /* sem zeros a direita */
|
|
char* dot = strchr(out, '.');
|
|
if (dot) {
|
|
char* e = out + strlen(out) - 1;
|
|
while (e > dot && *e == '0') *e-- = 0;
|
|
if (e == dot) *e = 0;
|
|
}
|
|
}
|
|
|
|
/* -- Entradas/saidas ------------------------------------------------------ */
|
|
|
|
static double num(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
|
|
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
|
|
if (v.kind == TB_VALUE_INTEGER) return (double)v.as.integer;
|
|
if (v.kind == TB_VALUE_REAL) return v.as.real;
|
|
if (v.kind == TB_VALUE_TEXT && v.as.text) return strtod(v.as.text, NULL);
|
|
return 0.0;
|
|
}
|
|
|
|
/* Inteiro quando o resultado for exato (e couber), senao real */
|
|
static void out_num(TinyBlocks_Block* self, double x) {
|
|
if (isfinite(x) && x == floor(x) && fabs(x) < 1e15)
|
|
tb_block_set_output(self, 0, tb_value_integer((int64_t)x));
|
|
else
|
|
tb_block_set_output(self, 0, tb_value_real(isfinite(x) ? x : 0.0));
|
|
self->dirty = false;
|
|
}
|
|
|
|
static void out_bool(TinyBlocks_Block* self, bool b) {
|
|
tb_block_set_output(self, 0, tb_value_integer(b ? 1 : 0));
|
|
self->dirty = false;
|
|
}
|
|
|
|
/* trigonometria: corta o ruido de ponto flutuante (sen 180 = 0, nao 1e-16) */
|
|
static double trig(double x) { return tb_number_round_to(x, 10); }
|
|
|
|
/* -- Blocos --------------------------------------------------------------- */
|
|
|
|
#define N(i) num(self, rt, (i))
|
|
|
|
static void eval_div(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
double b = N(1);
|
|
out_num(self, b == 0.0 ? 0.0 : N(0) / b);
|
|
}
|
|
static void eval_pow(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, pow(N(0), N(1))); }
|
|
static void eval_sqrt(TinyBlocks_Block* self, TinyBlocks* rt) { double x = N(0); out_num(self, x < 0 ? 0.0 : sqrt(x)); }
|
|
static void eval_round(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, round(N(0))); }
|
|
static void eval_floor(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, floor(N(0))); }
|
|
static void eval_ceil(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, ceil(N(0))); }
|
|
static void eval_round_to(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
out_num(self, tb_number_round_to(N(0), (int)N(1)));
|
|
}
|
|
static void eval_sin(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, trig(sin(N(0) * DEG))); }
|
|
static void eval_cos(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, trig(cos(N(0) * DEG))); }
|
|
static void eval_tan(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, trig(tan(N(0) * DEG))); }
|
|
static void eval_asin(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
double x = N(0);
|
|
out_num(self, (x < -1 || x > 1) ? 0.0 : trig(asin(x) / DEG));
|
|
}
|
|
static void eval_acos(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
double x = N(0);
|
|
out_num(self, (x < -1 || x > 1) ? 0.0 : trig(acos(x) / DEG));
|
|
}
|
|
static void eval_atan(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, trig(atan(N(0)) / DEG)); }
|
|
static void eval_log10(TinyBlocks_Block* self, TinyBlocks* rt) { double x = N(0); out_num(self, x > 0 ? log10(x) : 0.0); }
|
|
static void eval_ln(TinyBlocks_Block* self, TinyBlocks* rt) { double x = N(0); out_num(self, x > 0 ? log(x) : 0.0); }
|
|
static void eval_exp(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, exp(N(0))); }
|
|
static void eval_pi(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_num(self, M_PI); }
|
|
|
|
static void eval_random(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
double a = N(0), b = N(1);
|
|
if (a > b) { double t = a; a = b; b = t; }
|
|
double r = a + (b - a) * ((double)rand() / ((double)RAND_MAX + 1.0));
|
|
tb_block_set_output(self, 0, tb_value_real(r)); /* sempre real */
|
|
self->dirty = false;
|
|
}
|
|
|
|
static void eval_clamp(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
double x = N(0), lo = N(1), hi = N(2);
|
|
if (lo > hi) { double t = lo; lo = hi; hi = t; }
|
|
out_num(self, x < lo ? lo : x > hi ? hi : x);
|
|
}
|
|
|
|
static void eval_format(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
char buf[64];
|
|
tb_number_format(N(0), (int)N(1), buf, sizeof(buf));
|
|
tb_block_set_output(self, 0, tb_value_text(buf));
|
|
self->dirty = false;
|
|
}
|
|
|
|
static void eval_is_even(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
double x = N(0);
|
|
out_bool(self, x == floor(x) && fmod(fabs(x), 2.0) == 0.0);
|
|
}
|
|
static void eval_is_prime(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
double x = N(0);
|
|
out_bool(self, x == floor(x) && x < 9e15 && tb_number_is_prime((long long)x));
|
|
}
|
|
static void eval_is_int(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
double x = N(0);
|
|
out_bool(self, isfinite(x) && x == floor(x));
|
|
}
|
|
|
|
/* -- Conversoes ----------------------------------------------------------- */
|
|
|
|
/* Texto -> numero: o mesmo do core (espacos nas pontas, virgula decimal) */
|
|
TB_API bool tb_number_parse(const char* s, double* out) {
|
|
return tb_text_to_number(s, out);
|
|
}
|
|
|
|
/* "número de (x)": cada tipo de valor sabe virar numero (classe do valor);
|
|
o que nao vira e 0, e "verdadeiro"/"true" e 1 */
|
|
static void eval_from(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
|
|
double d = 0;
|
|
if (!tb_value_to_number(v, &d)) {
|
|
char t[16];
|
|
tb_value_to_text(v, t, sizeof(t));
|
|
d = (!strcmp(t, "verdadeiro") || !strcmp(t, "true")) ? 1 : 0;
|
|
}
|
|
out_num(self, d);
|
|
}
|
|
|
|
static int in_base(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
|
|
int b = (int)llround(num(self, rt, i));
|
|
return b < 2 ? 2 : b > 36 ? 36 : b;
|
|
}
|
|
|
|
/* "(255) na base (16)" -> "ff" */
|
|
static void eval_to_base(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
long long x = llround(num(self, rt, 0));
|
|
int b = in_base(self, rt, 1);
|
|
char buf[72], *p = buf + sizeof(buf) - 1;
|
|
*p = 0;
|
|
unsigned long long u = x < 0 ? 0ull - (unsigned long long)x : (unsigned long long)x;
|
|
do { *--p = "0123456789abcdefghijklmnopqrstuvwxyz"[u % (unsigned)b]; u /= (unsigned)b; } while (u);
|
|
if (x < 0) *--p = '-';
|
|
tb_block_set_output(self, 0, tb_value_text(p));
|
|
self->dirty = false;
|
|
}
|
|
|
|
/* "(ff) da base (16)" -> 255; digito invalido = erro */
|
|
static void eval_from_base(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
|
|
char buf[72];
|
|
const char* s = buf;
|
|
if (v.kind == TB_VALUE_TEXT) s = v.as.text ? v.as.text : "";
|
|
else snprintf(buf, sizeof(buf), "%lld", llround(num(self, rt, 0)));
|
|
int b = in_base(self, rt, 1);
|
|
while (isspace((unsigned char)*s)) s++;
|
|
char* e;
|
|
long long r = strtoll(s, &e, b);
|
|
while (isspace((unsigned char)*e)) e++;
|
|
if (e == s || *e) tinyblocks_set_error(rt, "'%s' não é um número na base %d", s, b);
|
|
out_num(self, (double)r);
|
|
}
|
|
|
|
/* -- Registro ------------------------------------------------------------- */
|
|
|
|
static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name,
|
|
const TinyBlocks_SlotDesc* in, uint32_t ni,
|
|
const TinyBlocks_SlotDesc* out, uint32_t no,
|
|
void (*fn)(TinyBlocks_Block*, TinyBlocks*)) {
|
|
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn);
|
|
return t && tb_library_add(lib, &t->base);
|
|
}
|
|
|
|
static bool number_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
|
srand((unsigned)time(NULL) ^ 0x5bd1e995u);
|
|
static const TinyBlocks_Category cat = {
|
|
"Números",
|
|
{139/255.f, 195/255.f, 74/255.f, 1.f},
|
|
{104/255.f, 159/255.f, 56/255.f, 1.f},
|
|
};
|
|
tb_library_set_category(lib, &cat);
|
|
|
|
TB_BLOCK_META("Number.Div", "eval_div", "Divisao com casas decimais (por 0 da 0)");
|
|
TB_BLOCK_META("Number.Pow", "eval_pow", "A elevado a B");
|
|
TB_BLOCK_META("Number.Sqrt", "eval_sqrt", "Raiz quadrada");
|
|
TB_BLOCK_META("Number.Round", "eval_round", "Arredonda para o inteiro mais proximo");
|
|
TB_BLOCK_META("Number.Floor", "eval_floor", "Arredonda para baixo");
|
|
TB_BLOCK_META("Number.Ceil", "eval_ceil", "Arredonda para cima");
|
|
TB_BLOCK_META("Number.RoundTo", "tb_number_round_to", "Arredonda mantendo N casas decimais");
|
|
TB_BLOCK_META("Number.Sin", "eval_sin", "Seno (angulo em graus)");
|
|
TB_BLOCK_META("Number.Cos", "eval_cos", "Cosseno (angulo em graus)");
|
|
TB_BLOCK_META("Number.Tan", "eval_tan", "Tangente (angulo em graus)");
|
|
TB_BLOCK_META("Number.Asin", "eval_asin", "Arco-seno, em graus");
|
|
TB_BLOCK_META("Number.Acos", "eval_acos", "Arco-cosseno, em graus");
|
|
TB_BLOCK_META("Number.Atan", "eval_atan", "Arco-tangente, em graus");
|
|
TB_BLOCK_META("Number.Log10", "eval_log10", "Logaritmo na base 10");
|
|
TB_BLOCK_META("Number.Ln", "eval_ln", "Logaritmo natural (base e)");
|
|
TB_BLOCK_META("Number.Exp", "eval_exp", "e elevado a X");
|
|
TB_BLOCK_META("Number.Pi", "eval_pi", "O numero pi (3,14159...)");
|
|
TB_BLOCK_META("Number.Random", "eval_random", "Numero real aleatorio entre A e B");
|
|
TB_BLOCK_META("Number.Clamp", "eval_clamp", "Prende o numero entre o minimo e o maximo");
|
|
TB_BLOCK_META("Number.Format", "tb_number_format", "Texto do numero com N casas decimais");
|
|
TB_BLOCK_META("Number.IsEven", "eval_is_even", "Verdadeiro se o numero for par");
|
|
TB_BLOCK_META("Number.IsPrime", "tb_number_is_prime", "Verdadeiro se o numero for primo");
|
|
TB_BLOCK_META("Number.IsInteger", "eval_is_int", "Verdadeiro se o numero nao tiver casas decimais");
|
|
TB_BLOCK_META("Number.From", "tb_number_parse", "Converte texto (ou outro valor) em numero; aceita virgula decimal");
|
|
TB_BLOCK_META("Number.ToBase", "eval_to_base", "Texto do numero em outra base (2 = binario, 16 = hexadecimal)");
|
|
TB_BLOCK_META("Number.FromBase", "eval_from_base", "Numero a partir de um texto escrito em outra base");
|
|
|
|
static const TinyBlocks_SlotDesc n1[] = {{"x", TB_VALUE_REAL}};
|
|
static const TinyBlocks_SlotDesc n2[] = {{"a", TB_VALUE_REAL}, {"b", TB_VALUE_REAL}};
|
|
static const TinyBlocks_SlotDesc n3[] = {{"x", TB_VALUE_REAL}, {"min", TB_VALUE_REAL}, {"max", TB_VALUE_REAL}};
|
|
static const TinyBlocks_SlotDesc nk[] = {{"x", TB_VALUE_REAL}, {"casas", TB_VALUE_INTEGER}};
|
|
static const TinyBlocks_SlotDesc any1[] = {{"valor", TB_VALUE_NONE}};
|
|
static const TinyBlocks_SlotDesc nb[] = {{"x", TB_VALUE_REAL}, {"base", TB_VALUE_INTEGER}};
|
|
static const TinyBlocks_SlotDesc tb[] = {{"texto", TB_VALUE_TEXT}, {"base", TB_VALUE_INTEGER}};
|
|
/* saida "qualquer": inteiro quando exato, senao real */
|
|
static const TinyBlocks_SlotDesc out[] = {{"numero", TB_VALUE_NONE}};
|
|
static const TinyBlocks_SlotDesc text_out[] = {{"texto", TB_VALUE_TEXT}};
|
|
/* saidas terminadas em '?' = blocos booleanos (hexagonais no editor) */
|
|
static const TinyBlocks_SlotDesc even_out[] = {{"é par?", TB_VALUE_INTEGER}};
|
|
static const TinyBlocks_SlotDesc prime_out[] = {{"é primo?", TB_VALUE_INTEGER}};
|
|
static const TinyBlocks_SlotDesc int_out[] = {{"é inteiro?", TB_VALUE_INTEGER}};
|
|
|
|
return reg(rt, lib, "Number.Div", n2, 2, out, 1, eval_div)
|
|
&& reg(rt, lib, "Number.Pow", n2, 2, out, 1, eval_pow)
|
|
&& reg(rt, lib, "Number.Sqrt", n1, 1, out, 1, eval_sqrt)
|
|
&& reg(rt, lib, "Number.Round", n1, 1, out, 1, eval_round)
|
|
&& reg(rt, lib, "Number.Floor", n1, 1, out, 1, eval_floor)
|
|
&& reg(rt, lib, "Number.Ceil", n1, 1, out, 1, eval_ceil)
|
|
&& reg(rt, lib, "Number.RoundTo", nk, 2, out, 1, eval_round_to)
|
|
&& reg(rt, lib, "Number.Sin", n1, 1, out, 1, eval_sin)
|
|
&& reg(rt, lib, "Number.Cos", n1, 1, out, 1, eval_cos)
|
|
&& reg(rt, lib, "Number.Tan", n1, 1, out, 1, eval_tan)
|
|
&& reg(rt, lib, "Number.Asin", n1, 1, out, 1, eval_asin)
|
|
&& reg(rt, lib, "Number.Acos", n1, 1, out, 1, eval_acos)
|
|
&& reg(rt, lib, "Number.Atan", n1, 1, out, 1, eval_atan)
|
|
&& reg(rt, lib, "Number.Log10", n1, 1, out, 1, eval_log10)
|
|
&& reg(rt, lib, "Number.Ln", n1, 1, out, 1, eval_ln)
|
|
&& reg(rt, lib, "Number.Exp", n1, 1, out, 1, eval_exp)
|
|
&& reg(rt, lib, "Number.Pi", NULL, 0, out, 1, eval_pi)
|
|
&& reg(rt, lib, "Number.Random", n2, 2, out, 1, eval_random)
|
|
&& reg(rt, lib, "Number.Clamp", n3, 3, out, 1, eval_clamp)
|
|
&& reg(rt, lib, "Number.Format", nk, 2, text_out, 1, eval_format)
|
|
&& reg(rt, lib, "Number.IsEven", n1, 1, even_out, 1, eval_is_even)
|
|
&& reg(rt, lib, "Number.IsPrime", n1, 1, prime_out, 1, eval_is_prime)
|
|
&& reg(rt, lib, "Number.IsInteger", n1, 1, int_out, 1, eval_is_int)
|
|
&& reg(rt, lib, "Number.From", any1, 1, out, 1, eval_from)
|
|
&& reg(rt, lib, "Number.ToBase", nb, 2, text_out, 1, eval_to_base)
|
|
&& reg(rt, lib, "Number.FromBase", tb, 2, out, 1, eval_from_base);
|
|
}
|
|
|
|
static void number_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
|
(void)rt; (void)lib;
|
|
}
|
|
|
|
TINYBLOCKS_DEFINE_LIBRARY(number,
|
|
"tinyblocks-number",
|
|
"1.0.0",
|
|
number_init,
|
|
number_deinit)
|
|
|
|
const TinyBlocks_LibraryDescriptor* tb_number_get_library(void) {
|
|
return &_tb_lib_desc_number;
|
|
}
|