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
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn ppm_writer_for_fname(fname string, settings ImageSettings) ?&PPMWriter {
|
|
|
|
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-05-13 06:56:21 +03:00
|
|
|
writer.start_for_file(fname, settings)?
|
2022-02-12 20:38:07 +03:00
|
|
|
return writer
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn (mut writer PPMWriter) start_for_file(fname string, settings ImageSettings) ? {
|
2022-05-13 06:56:21 +03:00
|
|
|
writer.file = os.create(fname)?
|
|
|
|
writer.file.writeln('P6 $settings.width $settings.height 255')?
|
2022-02-12 20:38:07 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn (mut writer PPMWriter) handle_pixel(p gx.Color) ? {
|
|
|
|
if writer.cache.len >= writer.cache_size {
|
2022-05-13 06:56:21 +03:00
|
|
|
writer.write()?
|
|
|
|
writer.flush()?
|
2022-02-12 20:38:07 +03:00
|
|
|
}
|
|
|
|
writer.cache << [p.r, p.g, p.b]
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn (mut writer PPMWriter) flush() ? {
|
|
|
|
writer.cache.clear()
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn (mut writer PPMWriter) write() ? {
|
2022-05-13 06:56:21 +03:00
|
|
|
writer.file.write(writer.cache)?
|
2022-02-12 20:38:07 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn (mut writer PPMWriter) close() {
|
|
|
|
writer.file.close()
|
|
|
|
}
|