1use std::cell::RefCell;
10
11const CHUNK: usize = 512;
12
13#[derive(Clone, Debug)]
14struct Chunk {
15 heights: Vec<f32>,
16 sum: f64,
17}
18
19impl Chunk {
20 fn new(heights: Vec<f32>) -> Self {
21 let sum = heights.iter().map(|&h| h as f64).sum();
22 Self { heights, sum }
23 }
24}
25
26#[derive(Clone, Debug, Default)]
30struct Index {
31 prefix: Vec<f64>,
32 starts: Vec<usize>,
33 valid: usize,
34}
35
36#[derive(Clone, Debug)]
37pub struct HeightMap {
38 chunks: Vec<Chunk>,
39 index: RefCell<Index>,
40 lines: usize,
41}
42
43impl HeightMap {
44 pub fn new(lines: usize, height: f32) -> Self {
46 let mut map = Self { chunks: Vec::new(), index: RefCell::default(), lines: 0 };
47 map.splice(0, 0, std::iter::repeat_n(height, lines));
48 map
49 }
50
51 pub fn len(&self) -> usize {
52 self.lines
53 }
54
55 pub fn is_empty(&self) -> bool {
56 self.lines == 0
57 }
58
59 pub fn height(&self, line: usize) -> f32 {
60 let (c, i) = self.locate(line);
61 self.chunks[c].heights[i]
62 }
63
64 pub fn set(&mut self, line: usize, height: f32) -> f64 {
66 let (c, i) = self.locate(line);
67 let chunk = &mut self.chunks[c];
68 let old = std::mem::replace(&mut chunk.heights[i], height);
69 if old == height {
70 return 0.0;
71 }
72 let delta = height as f64 - old as f64;
73 chunk.sum += delta;
74 self.invalidate(c + 1);
75 delta
76 }
77
78 pub fn fill(&mut self, lines: std::ops::Range<usize>, height: f32) {
80 let end = lines.end.min(self.lines);
81 if lines.start >= end {
82 return;
83 }
84 let (mut c, mut i) = self.locate(lines.start);
85 self.invalidate(c + 1);
86 let mut left = end - lines.start;
87 while left > 0 {
88 let chunk = &mut self.chunks[c];
89 let take = (chunk.heights.len() - i).min(left);
90 chunk.heights[i..i + take].fill(height);
91 chunk.sum = chunk.heights.iter().map(|&h| h as f64).sum();
92 left -= take;
93 c += 1;
94 i = 0;
95 }
96 }
97
98 pub fn splice(&mut self, line: usize, removed: usize, inserted: impl IntoIterator<Item = f32>) {
100 assert!(line + removed <= self.lines, "splice past the end");
101 let inserted: Vec<f32> = inserted.into_iter().collect();
102 if self.chunks.is_empty() {
103 self.lines = inserted.len();
104 self.chunks = inserted.chunks(CHUNK).map(|c| Chunk::new(c.to_vec())).collect();
105 self.invalidate(0);
106 return;
107 }
108 let (first, offset) = if line == self.lines { (self.chunks.len() - 1, usize::MAX) } else { self.locate(line) };
110 let offset = if offset == usize::MAX { self.chunks[first].heights.len() } else { offset };
111 let mut last = first;
112 let mut covered = self.chunks[first].heights.len() - offset;
113 while covered < removed {
114 last += 1;
115 covered += self.chunks[last].heights.len();
116 }
117 let mut merged: Vec<f32> = Vec::with_capacity(covered + offset + inserted.len());
118 for c in &self.chunks[first..=last] {
119 merged.extend_from_slice(&c.heights);
120 }
121 merged.splice(offset..offset + removed, inserted.iter().copied());
122 self.lines = self.lines - removed + inserted.len();
123 let replacement: Vec<Chunk> = if merged.len() <= 2 * CHUNK {
124 if merged.is_empty() { Vec::new() } else { vec![Chunk::new(merged)] }
125 } else {
126 merged.chunks(CHUNK).map(|c| Chunk::new(c.to_vec())).collect()
127 };
128 self.chunks.splice(first..=last, replacement);
129 self.invalidate(first);
130 }
131
132 pub fn total(&self) -> f64 {
134 let index = self.index();
135 match self.chunks.last() {
136 Some(c) => index.prefix[self.chunks.len() - 1] + c.sum,
137 None => 0.0,
138 }
139 }
140
141 pub fn top(&self, line: usize) -> f64 {
144 if line >= self.lines {
145 return self.total();
146 }
147 let (c, i) = self.locate(line);
148 self.index().prefix[c] + self.chunks[c].heights[..i].iter().map(|&h| h as f64).sum::<f64>()
149 }
150
151 pub fn line_at(&self, y: f64) -> usize {
154 if self.lines == 0 {
155 return 0;
156 }
157 let index = self.index();
158 let n = self.chunks.len();
159 let c = index.prefix[..n].partition_point(|&p| p <= y).saturating_sub(1);
161 let mut acc = index.prefix[c];
162 let mut found = None;
163 let mut chunk = c;
164 'outer: while chunk < n {
166 for (i, &h) in self.chunks[chunk].heights.iter().enumerate() {
167 if h > 0.0 {
168 if acc + h as f64 > y {
169 found = Some(index.starts[chunk] + i);
170 break 'outer;
171 }
172 found = Some(index.starts[chunk] + i);
173 }
174 acc += h as f64;
175 }
176 chunk += 1;
177 }
178 found.unwrap_or(self.lines - 1)
179 }
180
181 fn locate(&self, line: usize) -> (usize, usize) {
183 assert!(line < self.lines, "line {line} out of {}", self.lines);
184 let index = self.index();
185 let c = index.starts.partition_point(|&s| s <= line) - 1;
186 (c, line - index.starts[c])
187 }
188
189 fn invalidate(&mut self, chunk: usize) {
190 let index = self.index.get_mut();
191 index.valid = index.valid.min(chunk);
192 }
193
194 fn index(&self) -> std::cell::Ref<'_, Index> {
196 {
197 let mut index = self.index.borrow_mut();
198 let n = self.chunks.len();
199 if index.valid < n || index.prefix.len() != n {
200 index.prefix.resize(n, 0.0);
201 index.starts.resize(n, 0);
202 for i in index.valid.min(n)..n {
203 if i == 0 {
204 index.prefix[0] = 0.0;
205 index.starts[0] = 0;
206 } else {
207 index.prefix[i] = index.prefix[i - 1] + self.chunks[i - 1].sum;
208 index.starts[i] = index.starts[i - 1] + self.chunks[i - 1].heights.len();
209 }
210 }
211 index.valid = n;
212 }
213 }
214 self.index.borrow()
215 }
216}
217
218#[cfg(test)]
219mod tests {
220 use super::*;
221
222 fn check(map: &HeightMap, plain: &[f32]) {
224 assert_eq!(map.len(), plain.len());
225 let mut top = 0.0f64;
226 for (line, &h) in plain.iter().enumerate() {
227 assert_eq!(map.height(line), h, "height of {line}");
228 assert!((map.top(line) - top).abs() < 1e-6, "top of {line}");
229 if h > 0.0 {
230 assert_eq!(map.line_at(top), line, "line at top of {line}");
231 assert_eq!(map.line_at(top + h as f64 * 0.99), line, "line near bottom of {line}");
232 }
233 top += h as f64;
234 }
235 assert!((map.total() - top).abs() < 1e-6);
236 }
237
238 #[test]
239 fn uniform_lines() {
240 let map = HeightMap::new(2000, 20.0);
241 assert_eq!(map.top(1500), 30000.0);
242 assert_eq!(map.line_at(30010.0), 1500);
243 assert_eq!(map.line_at(-5.0), 0);
244 assert_eq!(map.line_at(1e9), 1999);
245 }
246
247 #[test]
248 fn hidden_lines_are_skipped() {
249 let mut map = HeightMap::new(10, 20.0);
250 for l in 3..7 {
251 map.set(l, 0.0);
252 }
253 assert_eq!(map.top(7), 60.0);
254 assert_eq!(map.line_at(59.0), 2);
255 assert_eq!(map.line_at(60.0), 7);
256 }
257
258 #[test]
259 fn matches_a_plain_vector_under_random_edits() {
260 let mut seed = 0x2545_f491_u64;
261 let mut rand = move |n: usize| {
262 seed ^= seed << 13;
263 seed ^= seed >> 7;
264 seed ^= seed << 17;
265 (seed % n.max(1) as u64) as usize
266 };
267 let mut plain = vec![20.0f32; 3000];
268 let mut map = HeightMap::new(plain.len(), 20.0);
269 for _ in 0..300 {
270 match rand(3) {
271 0 => {
272 let l = rand(plain.len());
273 let h = [0.0, 20.0, 40.0, 60.0][rand(4)];
274 plain[l] = h;
275 map.set(l, h);
276 }
277 _ => {
278 let at = rand(plain.len() + 1);
279 let removed = rand((plain.len() - at).min(1500) + 1);
280 let inserted: Vec<f32> = (0..rand(1500)).map(|i| if i % 3 == 0 { 40.0 } else { 20.0 }).collect();
281 plain.splice(at..at + removed, inserted.iter().copied());
282 map.splice(at, removed, inserted);
283 }
284 }
285 if plain.is_empty() {
286 plain.push(20.0);
287 map.splice(0, 0, [20.0]);
288 }
289 }
290 check(&map, &plain);
291 }
292}