-
Notifications
You must be signed in to change notification settings - Fork 0
/
texture.rs
378 lines (347 loc) · 10.7 KB
/
texture.rs
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
use super::*;
use std::{thread,time};
use std::sync::{Arc, Mutex};
use std::sync::mpsc::channel;
use std::collections::{VecDeque};
use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc;
use std::time::Duration;
static NTHREADS: i32 = 3;
pub static mut g_textures:[GLuint;6]=[0;6];
pub type TextureIndex=usize;
#[cfg(target_os="emscripten")]
pub fn load_texture(filename:&str)->GLuint{
return 0;
}
pub fn load_texture_async_at(ti:TextureIndex, filename:&str){
load_req(ti,filename);
}
#[cfg(not(target_os="emscripten"))]
pub fn load_texture(filename:&str)->GLuint{
let x=get_load_req();
use std::io::prelude::*;
use std::fs::File;
let mut data=Vec::<u8>::new();
if let Ok(mut f)=File::open(filename){
println!("opened {}",filename);
if let Err(_)=f.read_to_end(&mut data){
println!("error in reading");
return 0;
}
}
else {
println!("could not open {}",filename);
return 0;
}
println!("loaded {} bytes from {}",data.len(),filename);
load_texture_from_memory(&data)
}
pub fn load_texture_from_memory(data:&Vec<u8>)->GLuint{
use image::*;
let imr=image::load_from_memory(data);
match imr{
Err(x)=>{println!("failed to init image file data"); return 0;},
Ok(mut dimg)=>{
let (mut usize,mut vsize)=dimg.dimensions();
let mut usize1=1; let mut vsize1=1;
while usize1<usize{usize1*=2;}
while vsize1<vsize{vsize1*=2;}
if !(usize1==usize && vsize1==vsize){
println!("scaling to {}x{}",usize1,vsize1);
dimg=dimg.resize(usize1,vsize1,FilterType::Gaussian);
}
println!("rescaling done\n");
if let DynamicImage::ImageRgb8(img)=dimg{
let (mut usize,mut vsize)=img.dimensions();
let mut usize1=1; let mut vsize1=1;
while usize1<usize{usize1*=2;}
while vsize1<vsize{vsize1*=2;}
println!("loaded rgb image {}x{}",usize,vsize);
// let bfr=img.into_raw();
let mut texid:GLuint=0;
let fmt=GL_RGB;
let mut my=Vec::<u8>::new();
let ustep =usize/16;
let vstep=vsize/16;
for j in 0..vsize/vstep{
for i in 0..usize/ustep{
let p=img.get_pixel(i*ustep as u32,j*vstep as u32);
my.push(p.data[0]);
my.push(p.data[1]);
my.push(p.data[2]);
print!("{}",if p.data[1]>128{if p.data[1]>192{"O"}else{"o"}}else{if p.data[1]>64{"."}else{" "}});
}
print!("\n");
}
unsafe {
glGenTextures(1,&mut texid);
glBindTexture(GL_TEXTURE_2D,texid);
glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE as GLint);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR as GLint);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR as GLint);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT as GLint);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT as GLint);
let bfr=img.into_vec();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB as GLint, usize as GLint,vsize as GLint, 0, fmt, GL_UNSIGNED_BYTE, (&bfr[0]));
return texid;
}
} else{
println!("not rgb image, not supported");
return 0;
}
},
Ok(image::DynamicImage::ImageRgba8(img))=>{
// return create_tex(img,GL_RGBA)
return 0;
},
_=>{println!("image not handled");return 0;}
}
}
pub fn create_textures() {
// static_assert(sizeof(GLuint)==sizeof(int));
// hardcoded test pattern
unsafe {
glGenTextures(1,&mut g_textures[0]);
glBindTexture(GL_TEXTURE_2D,g_textures[0]);
glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE as GLint);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR as GLint);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR as GLint);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT as GLint);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT as GLint);
let (usize,vsize)=(256,256);
let buffer:Vec<u32> = vec_from_fn(usize*vsize,&|index|{
let (i,j)=div_rem(index,usize);
(i+j*256+255*256*256) as u32
});
// for i in 0 as GLint..8 as GLint {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB as GLint, usize as GLint,vsize as GLint, 0, GL_RGB, GL_UNSIGNED_BYTE, &buffer[0] as *const _ as _);
// }
glBindTexture(GL_TEXTURE_2D,0);
#[cfg(emscripten)]
{
println!("bypass texture load");
for i in 1..5 {g_textures[i]=g_textures[0];}
}
#[cfg(not(emscripten))]
{
println!("texture loading");
load_texture_async_at(1,"data/metal.jpg");
load_texture_async_at(2,"data/mossy_rock.jpg");
load_texture_async_at(3,"data/stone.jpg");
// load_texture_async_at(4,"data/metal.jpg");
// load_texture_async_at(2,"data/stone.jpg");
// load_texture_async_at(3,"data/metal.jpg");
load_texture_async_at(4,"data/grass_dry.jpg");
load_texture_async_at(5,"Brick_07_UV_H_CM_1.jpg");
}
println!("texture load done");
}
}
pub fn load_file(fname:&str)->Option<Vec<u8>>{
match File::open(fname){
Ok(mut f)=>{
let mut buffer=Vec::<u8>::new();
f.read_to_end(&mut buffer);
Some(buffer)
}
Err(_)=>{None}
}
}
// todo - async..
fn create_texture_from_url(url:&str,waiting_color:u32)->GLuint{
// todo - make a tmp filename hash
unsafe {
emscripten::emscripten_wget(c_str(url),c_str("tmp_image1.dat\0"));
let buffer=load_file("tmp_image1.dat\0").unwrap();
let mut texname:GLuint=0;
glGenTextures(1,&mut texname);
glBindTexture(GL_TEXTURE_2D,texname);
dump!(texname);
glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE as GLint);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR as GLint);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR as GLint);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT as GLint);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT as GLint);
let (usize,vsize)=(16,16);
let buffer:Vec<u32> = vec_from_fn(usize*vsize,&|index|{
waiting_color
});
for i in 0 as GLint..8 as GLint {
glTexImage2D(GL_TEXTURE_2D, i, GL_RGB as GLint, usize as GLint,vsize as GLint, 0, GL_RGB, GL_UNSIGNED_BYTE, &buffer[0] as *const _ as _);
}
texname
}
}
// async texture loading system?
#[cfg(not(target_os="emscripten"))]
pub type LoadReq=(i32,String);
#[cfg(not(target_os="emscripten"))]
static mut g_load_req:Option<Arc<Mutex<VecDeque<LoadReq>>>>=None;
#[cfg(not(target_os="emscripten"))]
//static mut g_file_ready:Option<Arc<Mutex<VecDeque<(i32,Vec<u8>)>>>>=None;
static mut g_file_ready:Option<Mutex<VecDeque<(i32,Vec<u8>)>>>=None;
fn sleep_ms(x:u64){thread::sleep(Duration::from_millis(x))}
#[cfg(not(target_os="emscripten"))]
fn async_loader_func(arclq:Arc<Mutex<VecDeque<LoadReq>>>){
println!("async loader thread init");
loop {
sleep_ms(1000);
unsafe{g_file_ready=Some(Mutex::new(VecDeque::new()));}
println!("async loader is active");
// access the mutex,
if let Ok(ref mut q)=arclq.try_lock() {
if let Some(ref item)=q.pop_front(){
println!("ASL.received request - {:?}",item.1);
if let Some(data)=load_file(&item.1){
//push_ready_data(item.0,data)
println!("ASL:loaded {} bytes*****",data.len());
unsafe {match g_file_ready{
Some(ref mtx)=>{
mtx.lock().unwrap().push_front((item.0,data));
}
None=>{}
}
}
}
}
} else {
println!("ASl could not check q");
}
}
}
#[cfg(not(target_os="emscripten"))]
pub fn get_load_req()->Arc<Mutex<VecDeque<LoadReq>>>{
unsafe {
match g_load_req{
None=>{
let asl=Arc::new(Mutex::new(VecDeque::new()));
g_load_req=Some(asl.clone());
let asl2=asl.clone();
thread::spawn(move||{async_loader_func(asl2)});
asl
}
Some(ref x)=>{ x.clone() }
}
}
}
#[cfg(not(target_os="emscripten"))]
pub fn load_req(index:usize,fname:&str){
//TODO - we seemed to need to do this to fix borrow issues?!
// is there a better way?
(|mq:Arc<Mutex<VecDeque<LoadReq>>>|
{ match (*mq).lock(){
Ok(mut q)=>{
println!("push a request");
q.push_front((index as i32,String::from(fname)));
}
,
_=>{println!("load req failed\n");}
}
})(get_load_req())
}
// for this to be sane we need a global-able Channel type.
pub fn poll() {
unsafe {
if let Some(ref frq)=g_file_ready{
if let Ok(mut q)=frq.lock(){
if let Some(item)=q.pop_front(){
println!("got a file: {},{}",item.0,item.1.len());
println!("initializing texture..\n");
// todo - this also needs to happen asynchronously
let gltex=load_texture_from_memory(&item.1);
g_textures[item.0 as usize]=gltex;
println!("..initializing texture done\n");
}
}
}
}
}
type ResName=String;
#[derive(Clone,Debug)]
pub enum AsyncReq {
DebugMessage(String),
LoadTexture(i32,ResName)
//..Models,..
}
type FileData=Vec<u8>;
type ReadyData=Vec<u8>;
#[derive(Clone,Debug)]
enum DecomReq{
DebugMessage(String),
SomeFileData(AsyncReq,FileData)
}
#[derive(Clone,Debug)]
pub enum AsyncResult {
TextureData(i32,ResName,ReadyData)
// ModelData(i32,ResName)
}
static mut g_async_req_ch:Option<Mutex<Sender<AsyncReq>>>=None;
static mut g_async_result_ch:Option<Mutex<Receiver<AsyncResult>>>=None;
macro_rules! spawn_thread_loop_channel_match{
([$recver:expr]$($a:pat=>$b:expr,)*)=>{
thread::spawn(move||{
let chname=stringify!($channel);
loop{
println!("{}:procesing message:-", chname);
let rmsg:Result<_,_>=$recver.recv(); // poll instead??
match rmsg{
Ok(msg)=>match msg{
$(
$a=>$b,
)*
}
Err(_)=>{
println!("{}:no msg",chname);
}
}
}
});};
}
// TODO - want to make this library code,
// with generic types for of AsyncReq/AsyncResult
// sticking point is the global decl.
fn async_loader_ch(
// g_async_req_ch, result_ch would be params here to enable generics
makechannel:&Fn()-> (Sender<AsyncReq>,Receiver<AsyncResult>),
do_with_channel:&Fn(&mut Sender<AsyncReq>))
{
unsafe{
match g_async_req_ch {
Some( ref mut x)=>{do_with_channel(&mut x.lock().unwrap());return},
None=>{
let mut newch=makechannel();
do_with_channel(&mut newch.0);
g_async_req_ch=Some(Mutex::new(newch.0));
g_async_result_ch=Some(Mutex::new(newch.1));
}
}
}
}
fn make_threads_and_channels()->(Sender<AsyncReq>,Receiver<AsyncResult>){
// create the channels and worker threads
//ch.0=sender,ch.1=receiver
let (file_loader_send,file_loader_rec) = mpsc::channel();
let decompression_worker_ch = mpsc::channel(); // in practice might be multiple
let (result_send,result_rec) = mpsc::channel();
spawn_thread_loop_channel_match!{[file_loader_rec]
AsyncReq::DebugMessage(m)=>{println!("{}",m)},
AsyncReq::LoadTexture(_,_)=>println!("got a request"),
// _=>sleep_ms(500),
}
spawn_thread_loop_channel_match!{[decompression_worker_ch.1]
DecomReq::DebugMessage(_)=>{},
DecomReq::SomeFileData(_,_)=>println!("got some data"),
// _=>,
}
// return the channel endpoints that the main program deals with
(file_loader_send,result_rec)
}
// client interface
pub fn async_req(a:AsyncReq){
async_loader_ch(
&||make_threads_and_channels(),
&|snd:&mut Sender<AsyncReq>|{
snd.send(a.clone());
}
);
}