info = { type = "image", title = "Gears", category = "patterns", author = "BRRRO", version = "1.0", license = "MIT", desc = "Three brass gears turning", api = 33, } local TAU, K = 6.2831853, 40.7436654 local SIN = {} for i = 0, 255 do SIN[i] = math.sin(i * TAU / 256) end local GEAR = { { 12, 14, 9, 8, 0.06, 200, 166, 94 }, { 52, 50, 11, 10, -0.05, 178, 144, 76 }, { 50, 11, 7, 7, 0.09, 214, 182, 108 }, } local RUN, TOOTH local STEP_HZ = 30 function render() local W, H = gfx.W, gfx.H local t = frame * STEP_HZ // gfx.FPS local rect, px = gfx.rect, gfx.px if not RUN then RUN, TOOTH = {}, {} local floor, sqrt, atan = math.floor, math.sqrt, math.atan for g = 1, 3 do local G = GEAR[g] local r, teeth = G[3], G[4] local A, B, C = r * r, (r - 3) * (r - 3), (r + 2) * (r + 2) local runs, tt = {}, {} for yy = -r, r do local m = A - yy * yy if m >= 0 then local xo = floor(sqrt(m)) local mi = B - yy * yy if mi < 0 then runs[#runs + 1] = { -xo, yy, 2 * xo + 1 } else local xi = floor(sqrt(mi)) + 1 if xi <= xo then runs[#runs + 1] = { -xo, yy, xo - xi + 1 } runs[#runs + 1] = { xi, yy, xo - xi + 1 } end end end end for yy = -r - 2, r + 2 do for xx = -r - 2, r + 2 do local d2 = xx * xx + yy * yy if d2 > A and d2 <= C then tt[#tt + 1] = xx tt[#tt + 1] = yy tt[#tt + 1] = atan(yy, xx) * teeth * K + 2048 + 64 end end end RUN[g], TOOTH[g] = runs, tt end end for y = 0, H - 1 do local f = y / H rect(0, y, W, 1, 120 + 36 * f, 96 + 32 * f, 56 + 22 * f) end local sin = SIN for g = 1, 3 do local G = GEAR[g] local cx, cy = G[1], G[2] local cr, cg, cb = G[6], G[7], G[8] local runs = RUN[g] for i = 1, #runs do local R = runs[i] rect(cx + R[1], cy + R[2], R[3], 1, cr, cg, cb) end rect(cx - 2, cy - 2, 5, 5, cr * 0.7, cg * 0.7, cb * 0.7) local ph = ((t * G[5] * G[4]) % TAU) * K local tt = TOOTH[g] for i = 1, #tt, 3 do if sin[(tt[i + 2] + ph) // 1 & 255] > 0.3 then px(cx + tt[i], cy + tt[i + 1], cr, cg, cb) end end end end