2022-02-12 20:38:07 +03:00
|
|
|
module img
|
|
|
|
|
|
|
|
import gx
|
|
|
|
import os
|
|
|
|
import sim
|
|
|
|
|
|
|
|
[params]
|
|
|
|
pub struct ImageSettings {
|
|
|
|
pub:
|
|
|
|
width int = sim.default_width
|
|
|
|
height int = sim.default_height
|
|
|
|
cache_size int = 200
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn new_image_settings(settings ImageSettings) ImageSettings {
|
|
|
|
return ImageSettings{
|
|
|
|
...settings
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn image_settings_from_grid(grid sim.GridSettings) ImageSettings {
|
|
|
|
return ImageSettings{
|
|
|
|
width: grid.width
|
|
|
|
height: grid.height
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn (s ImageSettings) to_grid_settings() sim.GridSettings {
|
|
|
|
return sim.GridSettings{
|
|
|
|
width: s.width
|
|
|
|
height: s.height
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct PPMWriter {
|
|
|
|
mut:
|
|
|
|
file os.File
|
2022-04-15 15:35:35 +03:00
|
|
|
cache []u8
|
2022-02-12 20:38:07 +03:00
|
|
|
cache_size int
|
|
|
|
}
|
|
|
|
|
2022-10-16 09:28:57 +03:00
|
|
|
pub fn ppm_writer_for_fname(fname string, settings ImageSettings) !&PPMWriter {
|
2022-02-12 20:38:07 +03:00
|
|
|
mut writer := &PPMWriter{
|
|
|
|
cache_size: settings.cache_size
|
2022-04-15 15:35:35 +03:00
|
|
|
cache: []u8{cap: settings.cache_size}
|
2022-02-12 20:38:07 +03:00
|
|
|
}
|
2022-10-16 09:28:57 +03:00
|
|
|
writer.start_for_file(fname, settings)!
|
2022-02-12 20:38:07 +03:00
|
|
|
return writer
|
|
|
|
}
|
|
|
|
|
2022-10-16 09:28:57 +03:00
|
|
|
pub fn (mut writer PPMWriter) start_for_file(fname string, settings ImageSettings) ! {
|
|
|
|
writer.file = os.create(fname)!
|
2022-11-15 16:53:13 +03:00
|
|
|
writer.file.writeln('P6 ${settings.width} ${settings.height} 255')!
|
2022-02-12 20:38:07 +03:00
|
|
|
}
|
|
|
|
|
2022-10-16 09:28:57 +03:00
|
|
|
pub fn (mut writer PPMWriter) handle_pixel(p gx.Color) ! {
|
2022-02-12 20:38:07 +03:00
|
|
|
if writer.cache.len >= writer.cache_size {
|
2022-10-16 09:28:57 +03:00
|
|
|
writer.write()!
|
|
|
|
writer.flush()!
|
2022-02-12 20:38:07 +03:00
|
|
|
}
|
|
|
|
writer.cache << [p.r, p.g, p.b]
|
|
|
|
}
|
|
|
|
|
2022-10-16 09:28:57 +03:00
|
|
|
pub fn (mut writer PPMWriter) flush() ! {
|
2022-02-12 20:38:07 +03:00
|
|
|
writer.cache.clear()
|
|
|
|
}
|
|
|
|
|
2022-10-16 09:28:57 +03:00
|
|
|
pub fn (mut writer PPMWriter) write() ! {
|
|
|
|
writer.file.write(writer.cache)!
|
2022-02-12 20:38:07 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn (mut writer PPMWriter) close() {
|
|
|
|
writer.file.close()
|
|
|
|
}
|