1 #include "grid.h"
2 #include "resourcemanager.h"
3 #include <iostream>
4 
5 using namespace std;
6 
7 
Grid(ResourceManager * _res,int columns,int offset)8 Grid::Grid(ResourceManager *_res, int columns, int offset) :
9 		res(_res),
10 		column_count(-1),
11 		width(NULL), height(NULL),
12 		page_offset(offset) {
13 	set_columns(columns);
14 }
15 
~Grid()16 Grid::~Grid() {
17 	delete[] width;
18 	delete[] height;
19 }
20 
set_columns(int columns)21 bool Grid::set_columns(int columns) {
22 	int old_column_count = column_count;
23 	column_count = columns;
24 	if (column_count > res->get_page_count()) {
25 		column_count = res->get_page_count();
26 	}
27 	if (column_count < 1) {
28 		column_count = 1;
29 	}
30 
31 	set_offset(page_offset);
32 
33 	return old_column_count != column_count;
34 }
35 
set_offset(int offset)36 bool Grid::set_offset(int offset) {
37 	int old_page_offset = page_offset;
38 	page_offset = offset;
39 	if (page_offset < 0) {
40 		page_offset = 0;
41 	}
42 	if (page_offset > column_count - 1) {
43 		page_offset = column_count - 1;
44 	}
45 
46 	rebuild_cells();
47 	return old_page_offset != page_offset;
48 }
49 
get_width(int col) const50 float Grid::get_width(int col) const {
51 	// bounds check
52 	if (col < 0 || col >= column_count) {
53 		return -1;
54 	}
55 
56 	return width[col];
57 }
58 
get_height(int row) const59 float Grid::get_height(int row) const {
60 	// bounds check
61 	if (row < 0 || row >= row_count) {
62 		return -1;
63 	}
64 
65 	return height[row];
66 }
67 
get_column_count() const68 int Grid::get_column_count() const {
69 	return column_count;
70 }
71 
get_row_count() const72 int Grid::get_row_count() const {
73 	return row_count;
74 }
75 
get_offset() const76 int Grid::get_offset() const {
77 	return page_offset;
78 }
79 
rebuild_cells()80 void Grid::rebuild_cells() {
81 	delete[] width;
82 	delete[] height;
83 
84 	// implicit ceil
85 	row_count = (res->get_page_count() + column_count - 1 + page_offset) / column_count;
86 
87 	width = new float[column_count];
88 	height = new float[row_count];
89 
90 	for (int i = 0; i < column_count; i++) {
91 		width[i] = -1.0f;
92 	}
93 	for (int i = 0; i < row_count; i++) {
94 		height[i] = -1.0f;
95 	}
96 
97 	for (int i = 0; i < res->get_page_count(); i++) {
98 		int col = ((i + page_offset) % column_count);
99 		int row = ((i + page_offset) / column_count);
100 
101 		// calculate column width
102 		float new_width = res->get_page_width(i);
103 		if (width[col] < 0 || width[col] < new_width) {
104 			width[col] = new_width;
105 		}
106 
107 		// calculate row height
108 		float new_height = res->get_page_height(i);
109 		if (height[row] < 0 || height[row] < new_height) {
110 			height[row] = new_height;
111 		}
112 	}
113 }
114 
115