Rounding technique required?

Discuss using and improving Lua and the Lua Player specific to the PSP.

Moderators: Shine, Insert_witty_name

Post Reply
KawaGeo
Posts: 191
Joined: Sat Aug 27, 2005 6:52 am
Location: Calif Mountains

Rounding technique required?

Post by KawaGeo »

Hi, everybody!

We know all Lua numbers are floats, no integers available. However, integers are required for the arguments in most Lua Player functions. Hence, rounding technique is necessary. Here is the evidence in the code.

Code: Select all

-- circleTest.lua by Geo Massar, 2005  (aka kawageo)

PI2 = math.pi * 2

function math.round(num, dp)
  local mult = 10^(dp or 0)
  return math.floor(num  * mult + 0.5) / mult
end

function drawCircleOn(image, x0,y0, radius, segments, color)
  -- x0,y0 is the center of the circle
  local x1,y1, x2,y2
  x1, y1 = x0, y0 + radius
  for i = 1, segments do
    x2 = math.round(x0 + radius * math.sin(PI2*i/segments))
    y2 = math.round(y0 + radius * math.cos(PI2*i/segments))
    image:drawLine(x1,y1, x2,y2, color)
    x1,y1 = x2,y2
  end
end

function magnifyOn(image, mag)
  mag = mag or 2           -- 2 times in size by default
  local w = image:width()  
  local h = image:height()
  local result = Image.createEmpty(mag*w, mag*h)
  for x = 0, w-1 do
    for y = 0, h-1 do
      result:fillRect(mag*x, mag*y, mag,mag, image:pixel(x,y))
    end
  end
  return result
end

--------------------- main routine -------------------------

green = Color.new(0, 255, 0)

panel = Image.createEmpty(30, 30)

drawCircleOn(panel, 24,5,  5,  4, green)       -- a fat diamond
drawCircleOn(panel, 24,24, 5, 12, green)       -- a small circle
math.round = function(num, dp) return num end  -- no rounding
drawCircleOn(panel, 5,5,   5,  4, green)
drawCircleOn(panel, 5,24,  5, 12, green)

panel = magnifyOn(panel, 4)
left = (480 - panel:width()) / 2
top = (272 - panel:height()) / 2
screen:blit(left, top, panel)

screen.flip()
screen:save "screen.tga"

while true do
  screen.waitVblankStart()
end
The result is displayed below. The symbols on the left side are resulted without rounding. They are badly distorted whereas the symbols on the other side look perfect due to the rounding technique.

Image

The question: Is it our responsibility to make sure all arguments are in pure integers OR should Lua Player take care of the rounding business?

NOTE: The code was tested on Lau Player for Windows. I presumed the same thing for a real PSP. (I don't have a PSP with version 1.5 yet. It is on the way, by the way. :)
Geo Massar
Retired Engineer
Post Reply