From: Martin DeMello Date: 2007-02-08T04:25:22+09:00 Subject: Re: Algorithm Help - Grid Space Calculations Here you go: include Math BASE_GRID_SIZE = 40 def lg2(a) log(a) / log(2) end def grid_size( world_width, pixel_width ) ppu = pixel_width / world_width factor = 2 ** lg2(ppu).ceil low = BASE_GRID_SIZE / factor high = low * 2 $grid_spacing = ($grid_spacing - high).abs < ($grid_spacing - low).abs ? high : low px_per_grid_line = $grid_spacing * ppu puts "A %dcm wide camera mapped to %dpx " % [world_width,pixel_width] + "will have a grid every %dcm " % [$grid_spacing] + "drawn every %.2f pixels, " % [px_per_grid_line] + "resulting in %.2f lines being drawn." % [pixel_width/ px_per_grid_line] $grid_spacing end require 'test/unit/assertions' include Test::Unit::Assertions begin # Use a global to handle overlapping legal ranges $grid_spacing = BASE_GRID_SIZE # Changing window size assert_equal( BASE_GRID_SIZE, grid_size( 400.0, 400 ) ) assert_equal( BASE_GRID_SIZE*2, grid_size( 400.0, 190 ) ) assert_equal( BASE_GRID_SIZE/2, grid_size( 400.0, 810 ) ) assert_equal( BASE_GRID_SIZE/2, grid_size( 400.0, 1200 ) ) assert_equal( BASE_GRID_SIZE/2, grid_size( 400.0, 1600 ) ) assert_equal( BASE_GRID_SIZE/4, grid_size( 400.0, 1601 ) ) # Changing camera zoom assert_equal( BASE_GRID_SIZE, grid_size( 420.0, 400 ) ) assert_equal( BASE_GRID_SIZE, grid_size( 790.0, 400 ) ) assert_equal( BASE_GRID_SIZE*2, grid_size( 810.0, 400 ) ) # Overlapping range test assert_equal( BASE_GRID_SIZE*2, grid_size( 1595.0, 400 ) ) assert_equal( BASE_GRID_SIZE*4, grid_size( 1610.0, 400 ) ) assert_equal( BASE_GRID_SIZE*4, grid_size( 1595.0, 400 ) ) assert_equal( BASE_GRID_SIZE*4, grid_size( 810.0, 400 ) ) assert_equal( BASE_GRID_SIZE*2, grid_size( 790.0, 400 ) ) assert_equal( BASE_GRID_SIZE*2, grid_size( 400.0, 400 ) ) assert_equal( BASE_GRID_SIZE, grid_size( 399.0, 400 ) ) assert_equal( BASE_GRID_SIZE, grid_size( 790.0, 400 ) ) rescue Test::Unit::AssertionFailedError => e puts e end martin