code / hill-noise

Lines837 Lua675 GLSL103 Markdown59
(70 lines)
1 local Histogram = setmetatable({}, {__call=function(self,options)
2 local h = setmetatable({},{__index=self})
3 h:init(options)
4 return h
5 end})
7 function Histogram:init(options)
8 self.pos = options.pos
9 self.size = options.size
10 local total = 0
11 for _,entry in ipairs(options.data) do
12 local x, count = unpack(entry)
13 total = total + count
14 end
15 local t = 0
16 local iqrMin, iqrMax
17 for _,entry in ipairs(options.data) do
18 local x, count = unpack(entry)
19 t = t + count
20 if not iqrMin and t >= .25*total then iqrMin = x end
21 if not iqrMax and t >= .75*total then iqrMax = x end
22 end
23 local h = 2*(iqrMax-iqrMin)*total^(1/3)
24 local xmin, xmax = options.xmin or options.data[1][1], options.xmax or options.data[#options.data][1]
25 local numBuckets = options.numBuckets or math.max(3, math.min(options.size.x/10, math.ceil((xmax - xmin) * total / h)))
26 local buckets = {}
27 for i=1,numBuckets do
28 buckets[i] = 0
29 end
30 local ymax = 0
31 for _,entry in ipairs(options.data) do
32 local x, count = unpack(entry)
33 local b = 1 + math.floor((x - xmin)/(xmax - xmin) * (numBuckets-1))
34 buckets[b] = (buckets[b] or 0) + count
35 ymax = math.max(buckets[b], ymax)
36 end
37 self.ymax = ymax
38 self.xmax = xmax
39 self.buckets = buckets
40 function self:getX(x)
41 return self.pos.x + self.size.x * (x-xmin)/(xmax-xmin)
42 end
43 end
45 function Histogram:fromList(list, options)
46 table.sort(list)
47 local data = {}
48 for _,x in ipairs(list) do
49 if not data[#data] or data[#data][1] ~= x then
50 table.insert(data, {x,1})
51 else
52 data[#data][2] = data[#data][2] + 1
53 end
54 end
55 options.data = data
56 return Histogram(options)
57 end
59 function Histogram:draw()
60 local height = self.size.y / (#self.buckets-1)
61 for i,count in ipairs(self.buckets) do
62 if count > 0 then
63 local width = count/self.ymax * self.size.x
64 love.graphics.rectangle('fill', self.pos.x,
65 self.pos.y+(#self.buckets-i-1)*height, width, height)
66 end
67 end
68 end
70 return Histogram