molx 0.1.9

Interactive protein structure exploration in the terminal
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
use font8x8::{BASIC_FONTS, UnicodeFonts};

pub type Color = [u8; 4];

pub struct Canvas {
    pub width: u32,
    pub height: u32,
    pub pixels: Vec<u8>,
    depth: Vec<f32>,
    text_scale: u32,
}

impl Canvas {
    pub fn new(width: u32, height: u32, background: Color) -> Self {
        let mut pixels = vec![0; width as usize * height as usize * 4];
        for pixel in pixels.chunks_exact_mut(4) {
            pixel.copy_from_slice(&background);
        }
        Self {
            width,
            height,
            pixels,
            depth: vec![f32::NEG_INFINITY; width as usize * height as usize],
            text_scale: 1,
        }
    }

    pub fn set_text_scale(&mut self, scale: u32) {
        self.text_scale = scale.clamp(1, 3);
    }

    pub fn text_cell_width(&self) -> u32 {
        8 * self.text_scale
    }

    pub fn text_cell_height(&self) -> u32 {
        8 * self.text_scale
    }

    pub fn vertical_gradient(&mut self, top: Color, bottom: Color) {
        let denominator = self.height.saturating_sub(1).max(1) as f32;
        for y in 0..self.height {
            let amount = y as f32 / denominator;
            let color = mix(top, bottom, amount);
            let start = y as usize * self.width as usize * 4;
            let end = start + self.width as usize * 4;
            for pixel in self.pixels[start..end].chunks_exact_mut(4) {
                pixel.copy_from_slice(&color);
            }
        }
    }

    pub fn line_3d(
        &mut self,
        from: [f32; 3],
        to: [f32; 3],
        thickness: f32,
        from_color: Color,
        to_color: Color,
    ) {
        let dx = to[0] - from[0];
        let dy = to[1] - from[1];
        let distance = (dx * dx + dy * dy).sqrt();
        let steps = distance.ceil().max(1.0) as usize;
        for step in 0..=steps {
            let amount = step as f32 / steps as f32;
            let x = from[0] + dx * amount;
            let y = from[1] + dy * amount;
            let z = from[2] + (to[2] - from[2]) * amount;
            self.disc_3d(x, y, z, thickness * 0.5, mix(from_color, to_color, amount));
        }
    }

    /// Draws a screen-space cylinder with interpolated color, depth, and lighting.
    ///
    /// Atom spheres normally cover the rounded endpoints, so this concentrates on
    /// the shaded cylindrical body while retaining circular caps for isolated
    /// segments and dashed interactions.
    pub fn cylinder_3d(
        &mut self,
        from: [f32; 3],
        to: [f32; 3],
        radius: f32,
        from_color: Color,
        to_color: Color,
    ) {
        let radius = radius.max(0.8);
        let dx = to[0] - from[0];
        let dy = to[1] - from[1];
        let squared_length = dx * dx + dy * dy;
        if squared_length < 0.01 {
            self.sphere(from[0], from[1], from[2], radius, from_color);
            return;
        }
        let min_x = (from[0].min(to[0]) - radius).floor() as i32;
        let max_x = (from[0].max(to[0]) + radius).ceil() as i32;
        let min_y = (from[1].min(to[1]) - radius).floor() as i32;
        let max_y = (from[1].max(to[1]) + radius).ceil() as i32;
        let light = [-0.42_f32, -0.55_f32, 0.72_f32];
        for py in min_y..=max_y {
            for px in min_x..=max_x {
                let sample_x = px as f32 + 0.5;
                let sample_y = py as f32 + 0.5;
                let amount = (((sample_x - from[0]) * dx + (sample_y - from[1]) * dy)
                    / squared_length)
                    .clamp(0.0, 1.0);
                let center_x = from[0] + dx * amount;
                let center_y = from[1] + dy * amount;
                let nx = (sample_x - center_x) / radius;
                let ny = (sample_y - center_y) / radius;
                let radial = nx * nx + ny * ny;
                if radial > 1.0 {
                    continue;
                }
                let nz = (1.0 - radial).sqrt();
                let center_z = from[2] + (to[2] - from[2]) * amount;
                let surface_z = center_z + nz * radius * 0.0025;
                let diffuse = (nx * light[0] + ny * light[1] + nz * light[2]).max(0.0);
                let rim = (1.0 - nz).powi(2) * 0.08;
                let shade = (0.60 + diffuse * 0.48 - rim).clamp(0.44, 1.12);
                self.pixel_3d(
                    px,
                    py,
                    surface_z,
                    scale(mix(from_color, to_color, amount), shade),
                );
            }
        }
    }

    pub fn sphere(&mut self, x: f32, y: f32, z: f32, radius: f32, color: Color) {
        let radius = radius.max(1.0);
        let min_x = (x - radius).floor() as i32;
        let max_x = (x + radius).ceil() as i32;
        let min_y = (y - radius).floor() as i32;
        let max_y = (y + radius).ceil() as i32;
        let light = [-0.42_f32, -0.55_f32, 0.72_f32];
        for py in min_y..=max_y {
            for px in min_x..=max_x {
                let nx = (px as f32 + 0.5 - x) / radius;
                let ny = (py as f32 + 0.5 - y) / radius;
                let radial = nx * nx + ny * ny;
                if radial > 1.0 {
                    continue;
                }
                let nz = (1.0 - radial).sqrt();
                let surface_z = z + nz * radius * 0.0025;
                let diffuse = (nx * light[0] + ny * light[1] + nz * light[2]).max(0.0);
                let rim = (1.0 - nz).powi(2) * 0.08;
                let shade = (0.58 + diffuse * 0.52 - rim).clamp(0.42, 1.14);
                self.pixel_3d(px, py, surface_z, scale(color, shade));
            }
        }
    }

    pub fn triangle_3d(
        &mut self,
        first: [f32; 3],
        second: [f32; 3],
        third: [f32; 3],
        color: Color,
    ) {
        self.triangle_3d_gradient(first, second, third, color, color, color);
    }

    pub fn triangle_3d_gradient(
        &mut self,
        first: [f32; 3],
        second: [f32; 3],
        third: [f32; 3],
        first_color: Color,
        second_color: Color,
        third_color: Color,
    ) {
        let area = edge(first, second, third[0], third[1]);
        if area.abs() < 0.001 {
            return;
        }
        let sign = area.signum();
        let min_x = first[0].min(second[0]).min(third[0]).floor().max(0.0) as i32;
        let max_x = first[0]
            .max(second[0])
            .max(third[0])
            .ceil()
            .min(self.width.saturating_sub(1) as f32) as i32;
        let min_y = first[1].min(second[1]).min(third[1]).floor().max(0.0) as i32;
        let max_y = first[1]
            .max(second[1])
            .max(third[1])
            .ceil()
            .min(self.height.saturating_sub(1) as f32) as i32;
        let inverse_area = 1.0 / area.abs();
        for y in min_y..=max_y {
            for x in min_x..=max_x {
                let px = x as f32 + 0.5;
                let py = y as f32 + 0.5;
                let w0 = edge(second, third, px, py) * sign;
                let w1 = edge(third, first, px, py) * sign;
                let w2 = edge(first, second, px, py) * sign;
                if w0 < 0.0 || w1 < 0.0 || w2 < 0.0 {
                    continue;
                }
                let z = (w0 * first[2] + w1 * second[2] + w2 * third[2]) * inverse_area;
                let weights = [w0 * inverse_area, w1 * inverse_area, w2 * inverse_area];
                let mut color = [0_u8; 4];
                for channel in 0..4 {
                    color[channel] = (first_color[channel] as f32 * weights[0]
                        + second_color[channel] as f32 * weights[1]
                        + third_color[channel] as f32 * weights[2])
                        .round()
                        .clamp(0.0, 255.0) as u8;
                }
                self.pixel_3d(x, y, z, color);
            }
        }
    }

    pub fn disc_3d(&mut self, x: f32, y: f32, z: f32, radius: f32, color: Color) {
        let radius = radius.max(0.8);
        let min_x = (x - radius).floor() as i32;
        let max_x = (x + radius).ceil() as i32;
        let min_y = (y - radius).floor() as i32;
        let max_y = (y + radius).ceil() as i32;
        let squared = radius * radius;
        for py in min_y..=max_y {
            for px in min_x..=max_x {
                let dx = px as f32 + 0.5 - x;
                let dy = py as f32 + 0.5 - y;
                if dx * dx + dy * dy <= squared {
                    self.pixel_3d(px, py, z, color);
                }
            }
        }
    }

    pub fn fill_rect(&mut self, x: u32, y: u32, width: u32, height: u32, color: Color) {
        for py in y..y.saturating_add(height).min(self.height) {
            for px in x..x.saturating_add(width).min(self.width) {
                self.pixel(px as i32, py as i32, color);
            }
        }
    }

    pub fn horizontal_line(&mut self, y: u32, color: Color) {
        if y >= self.height {
            return;
        }
        for x in 0..self.width {
            self.pixel(x as i32, y as i32, color);
        }
    }

    pub fn stroke_rect(&mut self, x: u32, y: u32, width: u32, height: u32, color: Color) {
        if width == 0 || height == 0 {
            return;
        }
        for px in x..x.saturating_add(width).min(self.width) {
            self.pixel(px as i32, y as i32, color);
            self.pixel(
                px as i32,
                y.saturating_add(height.saturating_sub(1)) as i32,
                color,
            );
        }
        for py in y..y.saturating_add(height).min(self.height) {
            self.pixel(x as i32, py as i32, color);
            self.pixel(
                x.saturating_add(width.saturating_sub(1)) as i32,
                py as i32,
                color,
            );
        }
    }

    pub fn set_pixel(&mut self, x: u32, y: u32, color: Color) {
        self.pixel(x as i32, y as i32, color);
    }

    pub fn text(&mut self, x: u32, y: u32, value: &str, color: Color) {
        let mut cursor = x;
        let scale = self.text_scale;
        let cell_width = self.text_cell_width();
        for character in value.chars() {
            if cursor + cell_width > self.width {
                break;
            }
            if let Some(glyph) = BASIC_FONTS.get(character) {
                for (row, bits) in glyph.iter().enumerate() {
                    for column in 0..8 {
                        if bits & (1 << column) != 0 {
                            let pixel_x = cursor + column * scale;
                            let pixel_y = y + row as u32 * scale;
                            for offset_y in 0..scale {
                                for offset_x in 0..scale {
                                    self.pixel(
                                        (pixel_x + offset_x) as i32,
                                        (pixel_y + offset_y) as i32,
                                        color,
                                    );
                                }
                            }
                        }
                    }
                }
            }
            cursor += cell_width;
        }
    }

    fn pixel_3d(&mut self, x: i32, y: i32, z: f32, color: Color) {
        if x < 0 || y < 0 || x >= self.width as i32 || y >= self.height as i32 {
            return;
        }
        let index = y as usize * self.width as usize + x as usize;
        if z < self.depth[index] {
            return;
        }
        self.depth[index] = z;
        let offset = index * 4;
        self.pixels[offset..offset + 4].copy_from_slice(&color);
    }

    fn pixel(&mut self, x: i32, y: i32, color: Color) {
        if x < 0 || y < 0 || x >= self.width as i32 || y >= self.height as i32 {
            return;
        }
        let offset = (y as usize * self.width as usize + x as usize) * 4;
        if color[3] == 255 {
            self.pixels[offset..offset + 4].copy_from_slice(&color);
            return;
        }
        let alpha = color[3] as f32 / 255.0;
        for (channel, source) in color.iter().take(3).enumerate() {
            self.pixels[offset + channel] = (self.pixels[offset + channel] as f32 * (1.0 - alpha)
                + *source as f32 * alpha)
                .round() as u8;
        }
        self.pixels[offset + 3] = 255;
    }
}

fn edge(first: [f32; 3], second: [f32; 3], x: f32, y: f32) -> f32 {
    (x - first[0]) * (second[1] - first[1]) - (y - first[1]) * (second[0] - first[0])
}

pub fn mix(from: Color, to: Color, amount: f32) -> Color {
    let amount = amount.clamp(0.0, 1.0);
    [
        (from[0] as f32 + (to[0] as f32 - from[0] as f32) * amount).round() as u8,
        (from[1] as f32 + (to[1] as f32 - from[1] as f32) * amount).round() as u8,
        (from[2] as f32 + (to[2] as f32 - from[2] as f32) * amount).round() as u8,
        255,
    ]
}

pub fn scale(color: Color, amount: f32) -> Color {
    [
        (color[0] as f32 * amount).clamp(0.0, 255.0) as u8,
        (color[1] as f32 * amount).clamp(0.0, 255.0) as u8,
        (color[2] as f32 * amount).clamp(0.0, 255.0) as u8,
        color[3],
    ]
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn nearer_pixels_win_depth_test() {
        let mut canvas = Canvas::new(2, 2, [0, 0, 0, 255]);
        canvas.pixel_3d(0, 0, 1.0, [255, 0, 0, 255]);
        canvas.pixel_3d(0, 0, 0.0, [0, 255, 0, 255]);
        assert_eq!(&canvas.pixels[..4], &[255, 0, 0, 255]);
    }

    #[test]
    fn triangle_rasterizes_its_interior() {
        let mut canvas = Canvas::new(8, 8, [0, 0, 0, 255]);
        canvas.triangle_3d(
            [1.0, 1.0, 0.5],
            [6.0, 1.0, 0.5],
            [1.0, 6.0, 0.5],
            [10, 20, 30, 255],
        );
        let offset = (2 * 8 + 2) * 4;
        assert_eq!(&canvas.pixels[offset..offset + 4], &[10, 20, 30, 255]);
    }

    #[test]
    fn triangle_interpolates_vertex_colors() {
        let mut canvas = Canvas::new(8, 8, [0, 0, 0, 255]);
        canvas.triangle_3d_gradient(
            [1.0, 1.0, 0.5],
            [6.0, 1.0, 0.5],
            [1.0, 6.0, 0.5],
            [255, 0, 0, 255],
            [0, 255, 0, 255],
            [0, 0, 255, 255],
        );
        let offset = (2 * 8 + 2) * 4;
        let color = &canvas.pixels[offset..offset + 4];
        assert!(color[0] > 0 && color[1] > 0 && color[2] > 0);
    }

    #[test]
    fn cylinder_has_lit_body_and_depth() {
        let mut canvas = Canvas::new(20, 12, [0, 0, 0, 255]);
        canvas.cylinder_3d(
            [3.0, 6.0, 0.2],
            [16.0, 6.0, 0.2],
            3.0,
            [200, 200, 200, 255],
            [200, 0, 0, 255],
        );
        let center = ((6 * 20 + 9) * 4) as usize;
        let edge = ((3 * 20 + 9) * 4) as usize;
        assert_ne!(&canvas.pixels[center..center + 4], &[0, 0, 0, 255]);
        assert_ne!(
            &canvas.pixels[center..center + 4],
            &canvas.pixels[edge..edge + 4]
        );
    }
}