Debian Codegraph @

CorsixTH/Lua/dialogs/fullscreen/graphs.lua

raw
1 --[[ Copyright (c) 2011 Ted "IntelOrca" John
2 2013 Edvin "Lego3" Linge
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy of
5 this software and associated documentation files (the "Software"), to deal in
6 the Software without restriction, including without limitation the rights to
7 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8 of the Software, and to permit persons to whom the Software is furnished to do
9 so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE. --]]
21
22 --! Charts fullscreen window
23 class "UIGraphs" (UIFullscreen)
24
25 ---@type UIGraphs
26 local UIGraphs = _G["UIGraphs"]
27
28 local TH = require("TH")
29
30 -- These values are based on the background colours of the pen symbols
31 local colours = {
32 money_in = {182, 32, 16},
33 money_out = {215, 81, 8},
34 wages = {194, 162, 0},
35 balance = {28, 138, 36},
36 visitors = {0, 101, 198},
37 cures = {36, 40, 154},
38 deaths = {130, 0, 178},
39 reputation = {215, 12, 101}
40 }
41
42 function UIGraphs:UIGraphs(ui)
43 self:UIFullscreen(ui)
44 local gfx = ui.app.gfx
45 if not pcall(function()
46 self.background = gfx:loadRaw("Graph01V", 640, 480, "QData", "QData", "Graph01V.pal", true)
47 local palette = gfx:getPalette("Graph01V.pal")
48 self.panel_sprites = gfx:loadSpriteTable("QData", "Graph02V", true, palette)
49 self.white_font = gfx:loadFontAndSpriteTable("QData", "Font01V", false, palette, { apply_ui_scale = true })
50 self.black_font = gfx:loadFontAndSpriteTable("QData", "Font00V", false, palette, { apply_ui_scale = true })
51 end) then
52 ui:addWindow(UIInformation(ui, {_S.errors.dialog_missing_graphics}))
53 self:close()
54 return
55 end
56
57 self.hospital = ui.hospital
58
59 -- Buttons
60 self:addPanel(0, 63, 384):makeButton(0, 0, 26, 26, 3, self.close):setTooltip(_S.tooltip.graphs.close)
61
62 self.graph_scale_panel = self:addPanel(0, 371, 384)
63 self.graph_scale_button = self.graph_scale_panel:makeButton(0, 0, 65, 26, 2, self.toggleGraphScale):setTooltip(_S.tooltip.graphs.scale)
64
65 local config = self:initRuntimeConfig()
66 self.graph_scale = config.graph_scale
67
68 local function toggleButton(sprite, x, y, option, str)
69 local panel = self:addPanel(sprite, x, y)
70 local btn = panel:makeToggleButton(0, 0, 42, 42, 1, --[[persistable:graphs_button]] function() self:toggleGraph(option) end):setTooltip(str)
71 btn:setToggleState(not config[option])
72 end
73 toggleButton(0, 590, 34, "money_in", _S.tooltip.graphs.money_in)
74 toggleButton(0, 590, 86, "money_out", _S.tooltip.graphs.money_out)
75 toggleButton(0, 590, 138, "wages", _S.tooltip.graphs.wages)
76 toggleButton(0, 590, 190, "balance", _S.tooltip.graphs.balance)
77 toggleButton(0, 590, 243, "visitors", _S.tooltip.graphs.visitors)
78 toggleButton(0, 590, 295, "cures", _S.tooltip.graphs.cures)
79 toggleButton(0, 590, 347, "deaths", _S.tooltip.graphs.deaths)
80 toggleButton(0, 590, 400, "reputation", _S.tooltip.graphs.reputation)
81
82 self.display_month = self.hospital.world.game_date:monthOfGame()
83 self:updateLines()
84 end
85
86 local TOP_Y = 85 -- Top of the graph area
87 local BOTTOM_Y = 353 -- Bottom of the graph area
88 local RIGHT_X = 346 -- Right side of the graph area
89 local VERT_DX = 25 -- Spacing between the vertical lines in the graph
90 local VERT_COUNT = 12 -- Number of vertical lines in the graph
91 local GRAPH_HEIGHT = BOTTOM_Y - TOP_Y
92
93 --! Compute the vertical position of a value in the graph given the line extremes
94 --!param graph_line (table) Meta data of the line, including extreme values.
95 --!param value (number) Value to position vertically in the graph.
96 --!return Y position in the graph of the value.
97 local function computeVerticalValuePosition(graph_line, value)
98 -- 0 is always included in the range.
99 assert(graph_line.maximum >= 0 and graph_line.minimum <= 0)
100 local range = graph_line.maximum - graph_line.minimum
101 if range == 0 then return BOTTOM_Y end
102
103 return BOTTOM_Y - math.floor(((value - graph_line.minimum) / range) * GRAPH_HEIGHT)
104 end
105
106 function UIGraphs:initRuntimeConfig()
107 -- config is a *runtime* configuration list; re-instantiations of the dialog
108 -- share the same values, but it's not saved across saves or sessions
109 local config = TheApp.runtime_config.graphs_dialog
110 if config == nil then
111 config = {}
112 TheApp.runtime_config.graphs_dialog = config
113 config.money_in = true
114 config.money_out = true
115 config.wages = true
116 config.balance = true
117 config.visitors = true
118 config.cures = true
119 config.deaths = true
120 config.reputation = true
121 config.graph_scale = 3
122 end
123 return config
124 end
125
126 --! Convert graph scale to a stepsize in months.
127 --!param graph_scale (int, 1 to 3) Graph scale to display.
128 --!return Number of months to jump between statistics values in the hospital statistics data.
129 local function getStatisticsStepsize(graph_scale)
130 local stepsize = 4 * 12 -- Four years
131 if graph_scale == 2 then
132 stepsize = 12 -- One year
133 elseif graph_scale == 3 then
134 stepsize = 1 -- A month
135 end
136 return stepsize
137 end
138
139 --! Get the statistics from the hospital that should be displayed.
140 --! Selection starts at the last (=newest) entry, and goes back in time.
141 --!return The values of all statistics to plot in the graph display.
142 function UIGraphs:getHospitalStatistics()
143 local statistics = self.hospital.statistics
144
145 local values = {}
146 local i = #statistics -- Picking hospital statistics from right to left (recent to old).
147 local stats_stepsize = getStatisticsStepsize(self.graph_scale)
148 while #values < VERT_COUNT and i >= 1 do
149 values[#values + 1] = statistics[i]
150 i = i - stats_stepsize
151 end
152 return values
153 end
154
155 --! Reposition the given sequence of text entries vertically such that the maximum
156 -- absolute deviation from the ideal position is minimized.
157 --!param label_datas (array) Text entries
158 --!param start_index (int) First entry to move.
159 --!param last_index (int) Last entry to move.
160 local function moveSequence(label_datas, start_index, last_index)
161 -- min_y, max_y Smallest and biggest vertical position of the labels. Since
162 -- they are sorted on y, it's the position of the first and last visible entry.
163 -- min_y_shift, max_y_shift Vertical movement of the label of the first and
164 -- last visible entry for vertically centering the text.
165 -- min_dev, max_dev Smallest and biggest deviation from the optimal position,
166 -- for all visible labels.
167 local min_y = nil
168 local max_y, min_y_shift, max_y_shift, min_dev, max_dev
169 for i = start_index, last_index do
170 local label = label_datas[i]
171 if label.pos_y then -- Label is visible
172 local deviation = label.pos_y - label.ideal_y -- Positive if moved down
173 if min_y then -- Updating the max y, and deviations
174 max_y = label.pos_y
175 max_y_shift = label.shift_y
176 min_dev = math.min(min_dev, deviation)
177 max_dev = math.max(max_dev, deviation)
178 else -- First time entering the loop
179 min_y = label.pos_y
180 max_y = label.pos_y
181 min_y_shift = label.shift_y
182 max_y_shift = label.shift_y
183 min_dev = deviation
184 max_dev = deviation
185 end
186 end
187 end
188
189 -- There should be at least one visible entry in the provided range.
190 assert(min_y ~= nil)
191
192 local move = -math.floor((max_dev + min_dev) / 2) -- Suggested movement of the sequence.
193
194 -- Verify the sequence will stay inside graph upper and lower limits, adjust otherwise.
195 if min_y + min_y_shift + move < TOP_Y then
196 move = TOP_Y - min_y - min_y_shift
197 elseif max_y + max_y_shift + move > BOTTOM_Y then
198 move = BOTTOM_Y - max_y - max_y_shift
199 end
200
201 -- And update the positions.
202 for i = start_index, last_index do
203 local label = label_datas[i]
204 if label.pos_y then label.pos_y = label.pos_y + move end
205 end
206 end
207
208 --! Compute new actual position of the labels.
209 --!param graph (UIGraphs) Graph window object
210 local function updateTextPositions(graph)
211 local config = TheApp.runtime_config.graphs_dialog
212
213 -- Reset vertical position of the text back to its ideal position.
214 -- Disable computations on invisible graphs by removing the actual y position of it.
215 for _, label in ipairs(graph.label_datas) do
216 if config[label.stat] then
217 label.pos_y = label.ideal_y
218 else
219 label.pos_y = nil
220 end
221 end
222
223 -- Move labels of the graphs such that they stay at the right of the graph
224 -- between their upper and lower boundaries.
225 local sequence_moved = true
226 local collision_count = 8 -- In theory the loop should terminate, but better safe than sorry.
227 while sequence_moved and collision_count > 0 do
228 collision_count = collision_count - 1
229 sequence_moved = false
230
231 -- Find sequences of text entries that partly overlap or have no vertical
232 -- space between them. Entries in such a sequence cannot be moved
233 -- individually, the sequence as a whole must move.
234 local start_index, last_index = nil, nil -- Start and end of the sequence.
235 local collision = false -- True collision detected in the sequence
236 local prev_index, prev_label = nil, nil
237 for i, label in ipairs(graph.label_datas) do
238 if label.pos_y then -- Label is visible
239 if prev_label then
240 -- Bottom y of previous label, top of current label
241 local bottom_prev = prev_label.pos_y + prev_label.shift_y + prev_label.size_y
242 local top_current = label.pos_y + label.shift_y
243
244 if top_current < bottom_prev then
245 -- True collision, text has to move
246 collision = true
247 sequence_moved = true
248 label.pos_y = bottom_prev - label.shift_y
249 if not start_index then start_index = prev_index end
250 last_index = i
251
252 elseif top_current == bottom_prev then
253 -- Entry is concatenated to the sequence, position is fine.
254 if not start_index then start_index = prev_index end
255 last_index = i
256 else
257 -- Entry is not part of the sequence, move previous sequence to its
258 -- optimal spot if required
259 if collision then
260 moveSequence(graph.label_datas, start_index, last_index)
261 end
262
263 collision = false
264 start_index = nil
265 last_index = nil
266 -- Do not consider the current text in this round. The next entry may
267 -- see it as the start of a next sequence.
268 end
269 end
270 prev_label = label
271 prev_index = i
272 end
273 end
274
275 if collision then
276 moveSequence(graph.label_datas, start_index, last_index)
277 end
278 end
279 end
280
281 function UIGraphs:updateLines()
282 local s = TheApp.config.ui_scale
283 self.values = self:getHospitalStatistics()
284
285 -- Construct meta data about each graph line.
286 local graph_datas = {} -- Table ordered by statistics name.
287 self.graph_datas = graph_datas
288 for stat, _ in pairs(self.values[1]) do
289 graph_datas[stat] = {line = nil, maximum = 0, minimum = 0}
290 end
291
292 -- Decide maximum and minimum for normalisation of each line.
293 -- 0 is always included in the computed range.
294 for _, stats in ipairs(self.values) do
295 for stat, value in pairs(stats) do
296 if value < graph_datas[stat].minimum then
297 graph_datas[stat].minimum = value
298 end
299 if value > graph_datas[stat].maximum then
300 graph_datas[stat].maximum = value
301 end
302 end
303 end
304
305 -- Add the line objects of the graph.
306 for stat, graph_data in pairs(self.graph_datas) do
307 local line = TH.line()
308 line:setWidth(2 * s)
309 local hue = colours[stat]
310 line:setColour(hue[1], hue[2], hue[3], 255)
311 graph_data.line = line
312 end
313
314 -- Add the graph line pieces. Doing this separately is more efficient as all
315 -- graph lines can be extended to the left in the same iteration.
316 local xpos = (RIGHT_X * s)
317 for i, stats in ipairs(self.values) do
318 for stat, value in pairs(stats) do
319 local line = graph_datas[stat].line
320 local ypos = computeVerticalValuePosition(graph_datas[stat], value) * s
321 if i == 1 then
322 line:moveTo(xpos, ypos)
323 else
324 line:lineTo(xpos, ypos)
325 end
326 end
327 xpos = xpos - (VERT_DX * s)
328 end
329
330 -- Compute label data for each statistic, and order by vertical position.
331 -- The newest statistic values are displayed at the right edge of the graph,
332 -- which decides the optimal position of the graph label text and value.
333 local label_datas = {}
334 self.label_datas = label_datas
335
336 for stat, value in pairs(self.values[1]) do
337 local ideal_y = computeVerticalValuePosition(graph_datas[stat], value)
338 local text = _S.graphs[stat] .. ":"
339 local _, size_y, _ = self.black_font:sizeOf(text)
340 size_y = math.ceil(size_y / s) -- Size in unscaled pixels
341 label_datas[#label_datas + 1] = {
342 stat = stat, -- Name of the statistic it belongs to.
343 text = text, -- Translated label text.
344 ideal_y = ideal_y, -- Ideal vertical position.
345 pos_y = nil, -- Actual position for drawing.
346 size_y = size_y, -- Vertical size of the text.
347 shift_y = -math.floor(size_y / 2), -- Amount of shift to center the text.
348 value = value} -- Numeric value to display.
349 end
350
351 -- Sort the labels of the graph on ideal y position, and compute actual position.
352 local function compare(a,b)
353 return a.ideal_y < b.ideal_y
354 end
355 table.sort(label_datas, compare)
356 updateTextPositions(self)
357
358 -- Create small lines going from the number of month name to the actual graph.
359 -- Like the lines, index runs from right to left at the screen.
360 local aux_lines = {}
361 self.aux_lines = aux_lines
362
363 xpos = (RIGHT_X * s)
364 for _ = 1, #self.values do
365 local line = TH.line()
366 line:setWidth(s)
367 line:moveTo(xpos, BOTTOM_Y * s + 4 * s)
368 line:lineTo(xpos, BOTTOM_Y * s + 8 * s)
369 aux_lines[#aux_lines + 1] = line
370 xpos = xpos - (VERT_DX * s)
371 end
372 end
373
374 function UIGraphs:draw(canvas, x, y)
375 local config = TheApp.runtime_config.graphs_dialog
376 if not config then
377 config = self:initRuntimeConfig()
378 end
379
380 -- Update graph automatically every month
381 if self.display_month ~= self.hospital.world.game_date:monthOfGame() then
382 self:updateLines()
383 end
384
385 local s = TheApp.config.ui_scale
386 canvas:scale(s, "bitmap")
387 self.background:draw(canvas, self.x * s + x, self.y * s + y)
388 canvas:scale(1, "bitmap")
389 UIFullscreen.draw(self, canvas, x, y)
390 x, y = self.x * s + x, self.y * s + y
391
392 local lx = x + 502 * s
393 local lw = 80 * s
394 local lh = 27 * s
395 self.white_font:draw(canvas, _S.graphs.money_in, lx, y + 41 * s, lw, lh)
396 self.white_font:draw(canvas, _S.graphs.money_out, lx, y + 93 * s, lw, lh)
397 self.white_font:draw(canvas, _S.graphs.wages, lx, y + 145 * s, lw, lh)
398 self.white_font:draw(canvas, _S.graphs.balance, lx, y + 197 * s, lw, lh)
399 self.white_font:draw(canvas, _S.graphs.visitors, lx, y + 249 * s, lw, lh)
400 self.white_font:draw(canvas, _S.graphs.cures, lx, y + 301 * s, lw, lh)
401 self.white_font:draw(canvas, _S.graphs.deaths, lx, y + 353 * s, lw, lh)
402 self.white_font:draw(canvas, _S.graphs.reputation, lx, y + 405 * s, lw, lh)
403
404 -- Draw the different lines
405 for stat, graph in pairs(self.graph_datas) do
406 if config[stat] then
407 graph.line:draw(canvas, x, y)
408 end
409 end
410
411 -- Draw strings showing what values each entry has at the moment just to the right of the graph.
412 -- TODO: These should be coloured according to the colour of the corresponding line.
413 for _, label in pairs(self.label_datas) do
414 if label.pos_y then
415 local ypos = label.pos_y + label.shift_y
416 self.black_font:draw(canvas, label.text, x + RIGHT_X * s + 3 * s, y + ypos * s)
417 self.black_font:draw(canvas, string.format("%.0f", label.value), x + RIGHT_X * s + 60 * s, y + ypos * s)
418 end
419 end
420
421 local stats_stepsize = getStatisticsStepsize(self.graph_scale)
422 local xpos = x + RIGHT_X * s - math.floor(VERT_DX / 2) * s
423
424 -- Draw numbers (or month names) below the graph
425 assert(#self.hospital.statistics > 0) -- Avoid negative months and years.
426 if stats_stepsize >= 12 then
427 -- Display years
428 local year_number = math.floor((#self.hospital.statistics - 1) / stats_stepsize)
429 local year_steps = math.floor(stats_stepsize / 12)
430 year_number = year_number * year_steps
431 for i = 1, #self.values do
432 self.black_font:drawWrapped(canvas, year_number, xpos, y + BOTTOM_Y * s + 10 * s, 25 * s, "center")
433 xpos = xpos - VERT_DX * s
434 year_number = year_number - year_steps
435
436 -- And the small black line
437 self.aux_lines[i]:draw(canvas, x, y)
438 end
439 else
440 -- Display months
441 local month_number = #self.hospital.statistics - math.floor((#self.hospital.statistics - 1) / 12) * 12
442 for i = 1, #self.values do
443 self.black_font:drawWrapped(canvas, _S.months[month_number], xpos, y + BOTTOM_Y * s + 10 * s, 25 * s, "center")
444 xpos = xpos - VERT_DX * s
445 month_number = month_number - stats_stepsize
446 if month_number < 1 then month_number = month_number + 12 end
447
448 -- And the small black line
449 self.aux_lines[i]:draw(canvas, x, y)
450 end
451 end
452 end
453
454 function UIGraphs:toggleGraphScale()
455 -- The possible scales are:
456 -- 1: Increments of four years per line
457 -- 2: Increments of one year per line
458 -- 3: Increments of one month per line
459 self.graph_scale = self.graph_scale - 1
460 if self.graph_scale == 0 then self.graph_scale = 3 end
461
462 local config = self.ui.app.runtime_config.graphs_dialog
463 config.graph_scale = self.graph_scale
464
465 self:updateLines()
466 self.ui:playSound("selectx.wav")
467 end
468
469 function UIGraphs:toggleGraph(name)
470 TheApp.runtime_config.graphs_dialog[name] = not TheApp.runtime_config.graphs_dialog[name]
471 self.ui:playSound("selectx.wav")
472 updateTextPositions(self)
473 end
474
475 function UIGraphs:close()
476 UIFullscreen.close(self)
477 self.ui:getWindow(UIBottomPanel):updateButtonStates()
478 end
479
480 function UIGraphs:onChangeResolution()
481 UIFullscreen.onChangeResolution(self)
482 -- onChangeResolution gets called during initialization before the data is ready.
483 if self.graph_scale then
484 self:updateLines()
485 end
486 end
487
488 function UIGraphs:afterLoad(old, new)
489 if old < 236 then
490 local gfx = TheApp.gfx
491
492 self.background = gfx:loadRaw("Graph01V", 640, 480, "QData", "QData", "Graph01V.pal", true)
493 local palette = gfx:getPalette("Graph01V.pal")
494 self.panel_sprites = gfx:loadSpriteTable("QData", "Graph02V", true, palette)
495 self.white_font = gfx:loadFontAndSpriteTable("QData", "Font01V", false, palette, { apply_ui_scale = true })
496 self.black_font = gfx:loadFontAndSpriteTable("QData", "Font00V", false, palette, { apply_ui_scale = true })
497 end
498 UIFullscreen.afterLoad(self, old, new)
499 if old < 231 then
500 self:close()
501 end
502 self:updateLines()
503 end