use std::collections::HashMap;
use std::time::Instant;
use gl;
use cognitive_graphics::egl_tools::HwImage;
use qualia::SurfaceId;
#[derive(Clone)]
pub struct TextureInfo {
texture: gl::types::GLuint,
image: Option<HwImage>,
time_stamp: Option<Instant>,
}
impl TextureInfo {
pub fn new(texture: gl::types::GLuint) -> Self {
TextureInfo {
texture: texture,
image: None,
time_stamp: None,
}
}
#[inline]
pub fn get_texture(&self) -> gl::types::GLuint {
self.texture
}
#[inline]
pub fn get_image(&self) -> Option<HwImage> {
self.image.clone()
}
#[inline]
pub fn update(&mut self, image: Option<HwImage>) {
self.time_stamp = Some(Instant::now());
self.image = image;
}
pub fn is_younger(&self, other_time_stamp: Instant) -> bool {
if let Some(my_time_stamp) = self.time_stamp {
my_time_stamp < other_time_stamp
} else {
true
}
}
}
pub struct CacheGl {
textures: HashMap<SurfaceId, TextureInfo>,
}
impl CacheGl {
pub fn new() -> Self {
CacheGl { textures: HashMap::new() }
}
pub fn get_or_generate_info(&mut self, sid: SurfaceId) -> TextureInfo {
if let Some(texture) = self.get_texture_info(sid) {
texture
} else {
let mut texture: gl::types::GLuint = 0;
unsafe {
gl::GenTextures(1, &mut texture);
gl::BindTexture(gl::TEXTURE_2D, texture);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as i32);
}
self.insert_texture(sid, texture)
}
}
pub fn update(&mut self, sid: SurfaceId, image: Option<HwImage>) {
if let Some(ref mut info) = self.textures.get_mut(&sid) {
info.update(image);
}
}
}
impl CacheGl {
fn get_texture_info(&self, sid: SurfaceId) -> Option<TextureInfo> {
self.textures.get(&sid).cloned()
}
fn insert_texture(&mut self, sid: SurfaceId, texture: gl::types::GLuint) -> TextureInfo {
let info = TextureInfo::new(texture);
self.textures.insert(sid, info.clone());
info
}
}