dbsdk-rs 0.1.19

API for creating Rust games for the DreamBox fantasy console
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
use std::convert::TryInto;
use std::fmt::Debug;

use crate::db_internal::{vdp_allocRenderTexture, vdp_allocTexture, vdp_bindTexture, vdp_bindTextureSlot, vdp_blendEquation, vdp_blendFunc, vdp_clearColor, vdp_clearDepth, vdp_copyFbToTexture, vdp_depthFunc, vdp_depthWrite, vdp_drawGeometry, vdp_drawGeometryPacked, vdp_getDepthQueryResult, vdp_getUsage, vdp_releaseTexture, vdp_setCulling, vdp_setRenderTarget, vdp_setSampleParams, vdp_setSampleParamsSlot, vdp_setTexCombine, vdp_setTextureData, vdp_setTextureDataRegion, vdp_setTextureDataYUV, vdp_setVUCData, vdp_setVULayout, vdp_setVUStride, vdp_setVsyncHandler, vdp_setWinding, vdp_submitDepthQuery, vdp_submitVU, vdp_uploadVUProgram, vdp_viewport};
use crate::math::{Vector4, Vector2};

static mut VSYNC_HANDLER: Option<fn()> = Option::None;

#[repr(C)]
#[derive(Clone, Copy)]
pub struct Color32 {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

impl Color32 {
    pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Color32 {
        return Color32 { r: r, g: g, b: b, a: a };
    }
}

#[repr(C)]
#[derive(Clone, Copy)]
pub struct Vertex {
    pub position: Vector4,
    pub color: Vector4,
    pub ocolor: Vector4,
    pub texcoord: Vector4,
}

impl Vertex {
    pub const fn new(position: Vector4, color: Vector4, ocolor: Vector4, texcoord: Vector4) -> Vertex {
        return Vertex { position: position, color: color, ocolor: ocolor, texcoord: texcoord };
    }
}

#[repr(C)]
#[derive(Clone, Copy)]
pub struct PackedVertex {
    pub position: Vector4,
    pub texcoord: Vector2,
    pub color: Color32,
    pub ocolor: Color32,
}

impl PackedVertex {
    pub const fn new(position: Vector4, texcoord: Vector2, color: Color32, ocolor: Color32) -> PackedVertex {
        return PackedVertex { position: position, texcoord: texcoord, color: color, ocolor: ocolor };
    }
}

#[repr(C)]
#[derive(Clone, Copy)]
pub struct Rectangle {
    pub x: i32,
    pub y: i32,
    pub width: i32,
    pub height: i32,
}

impl Rectangle {
    pub const fn new(x: i32, y: i32, width: i32, height: i32) -> Rectangle {
        return Rectangle { x: x, y: y, width: width, height: height };
    }
}

#[derive(Clone, Copy, Debug)]
pub enum TextureError {
    DimensionsInvalid,
    AllocationFailed
}

pub trait DBTex {
    fn get_handle(self: &Self) -> i32;
}

#[repr(C)]
pub struct Texture {
    pub format: TextureFormat,
    pub width: i32,
    pub height: i32,
    pub mipmap: bool,
    handle: i32,
}

#[repr(C)]
pub struct RenderTexture {
    pub width: i32,
    pub height: i32,
    handle: i32,
}

impl DBTex for Texture {
    fn get_handle(self: &Self) -> i32 {
        self.handle
    }
}

impl DBTex for RenderTexture {
    fn get_handle(self: &Self) -> i32 {
        self.handle
    }
}

impl Texture {
    pub fn new(width: i32, height: i32, mipmap: bool, format: TextureFormat) -> Result<Texture,TextureError> {
        // dimensions must be power of two (unless this is a YUV420 image)
        if format != TextureFormat::YUV420 && ((width & (width - 1)) != 0 || (height & (height - 1)) != 0) {
            return Result::Err(TextureError::DimensionsInvalid);
        }

        // allocate and check to see if allocation failed
        let handle = unsafe { vdp_allocTexture(mipmap, format, width, height) };
        if handle == -1 {
            return Result::Err(TextureError::AllocationFailed);
        }

        return Result::Ok(Texture {
            format: format,
            mipmap: mipmap,
            width: width,
            height: height,
            handle: handle
        });
    }

    /// Upload texture data for the given mip level of this texture
    pub fn set_texture_data<T>(&self, level: i32, data: &[T]) {
        unsafe {
            let len_bytes = data.len() * size_of::<T>();
            vdp_setTextureData(self.handle, level, data.as_ptr().cast(), len_bytes.try_into().unwrap());
        }
    }

    /// Upload individual planes for this YUV texture
    pub fn set_texture_data_yuv(&self, y_data: &[u8], u_data: &[u8], v_data: &[u8]) {
        unsafe {
            vdp_setTextureDataYUV(self.handle, 
                y_data.as_ptr().cast(), y_data.len().try_into().unwrap(),
                u_data.as_ptr().cast(), u_data.len().try_into().unwrap(),
                v_data.as_ptr().cast(), v_data.len().try_into().unwrap());
        }
    }

    /// Upload texture data for the given mip level and region of this texture
    pub fn set_texture_data_region<T>(&self, level: i32, dst_rect: Option<Rectangle>, data: &[T]) {
        unsafe {
            match dst_rect {
                Some(v) => {
                    let len_bytes = data.len() * size_of::<T>();
                    vdp_setTextureDataRegion(self.handle, level, &v, data.as_ptr().cast(), len_bytes.try_into().unwrap());
                }
                None => {
                    vdp_setTextureData(self.handle, level, data.as_ptr().cast(), data.len().try_into().unwrap());
                }
            }
        }
    }

    /// Copy a region of the framebuffer into a region of the given texture
    pub fn copy_framebuffer_to_texture(target: &Texture, src_rect: Rectangle, dst_rect: Rectangle) {
        unsafe {
            vdp_copyFbToTexture(&src_rect, &dst_rect, target.handle);
        }
    }
}

impl Drop for Texture {
    fn drop(&mut self) {
        unsafe { vdp_releaseTexture(self.handle) };
    }
}

impl RenderTexture {
    pub fn new(width: i32, height: i32) -> Result<RenderTexture,TextureError> {
        // dimensions must be power of two
        if (width & (width - 1)) != 0 || (height & (height - 1)) != 0 {
            return Result::Err(TextureError::DimensionsInvalid);
        }

        // allocate and check to see if allocation failed
        let handle = unsafe { vdp_allocRenderTexture(width, height) };
        if handle == -1 {
            return Result::Err(TextureError::AllocationFailed);
        }

        return Result::Ok(RenderTexture {
            width: width,
            height: height,
            handle: handle
        });
    }
}

impl Drop for RenderTexture {
    fn drop(&mut self) {
        unsafe { vdp_releaseTexture(self.handle) };
    }
}

#[repr(C)]
#[derive(Clone, Copy)]
pub enum Compare {
    Never           = 0x0200,
    Less            = 0x0201,
    Equal           = 0x0202,
    LessOrEqual     = 0x0203,
    Greater         = 0x0204,
    NotEqual        = 0x0205,
    GreaterOrEqual  = 0x0206,
    Always          = 0x0207,
}

#[repr(C)]
#[derive(Clone, Copy)]
pub enum BlendEquation {
    Add                 = 0x8006,
    Subtract            = 0x800A,
    ReverseSubtract     = 0x800B,
}

#[repr(C)]
#[derive(Clone, Copy)]
pub enum BlendFactor {
    Zero                = 0,
    One                 = 1,
    SrcColor            = 0x0300,
    OneMinusSrcColor    = 0x0301,
    SrcAlpha            = 0x0302,
    OneMinusSrcAlpha    = 0x0303,
    DstAlpha            = 0x0304,
    OneMinusDstAlpha    = 0x0305,
    DstColor            = 0x0306,
    OneMinusDstColor    = 0x0307,
}

#[repr(C)]
#[derive(Clone, Copy)]
pub enum WindingOrder {
    Clockwise  = 0x0900,
    CounterClockwise = 0x0901,
}

#[repr(C)]
#[derive(Clone, Copy)]
pub enum Topology {
    LineList       = 0x0000,
    LineStrip      = 0x0001,
    TriangleList   = 0x0002,
    TriangleStrip  = 0x0003,
}

#[repr(C)]
#[derive(Clone, Copy)]
#[derive(PartialEq)]
pub enum TextureFormat {
    RGB565   = 0,
    RGBA4444 = 1,
    RGBA8888 = 2,
    DXT1     = 3,
    DXT3     = 4,
    YUV420   = 5,
}

#[repr(C)]
#[derive(Clone, Copy)]
pub enum TextureFilter {
    Nearest     = 0x2600,
    Linear      = 0x2601,
}

#[repr(C)]
#[derive(Clone, Copy)]
pub enum TextureWrap {
    Clamp       = 0x812F,
    Repeat      = 0x2901,
    Mirror      = 0x8370,
}

#[repr(C)]
#[derive(Clone, Copy)]
#[derive(PartialEq)]
pub enum VertexSlotFormat {
    FLOAT1   = 0,
    FLOAT2   = 1,
    FLOAT3   = 2,
    FLOAT4   = 3,
    UNORM4   = 4,
    SNORM4   = 5,
}

#[repr(C)]
#[derive(Clone, Copy)]
#[derive(PartialEq)]
pub enum TexCombine {
    None    = 0,
    Mul     = 1,
    Add     = 2,
    Sub     = 3,
    Mix     = 4,
    Dot3    = 5,
}

#[repr(C)]
#[derive(Clone, Copy)]
#[derive(PartialEq)]
pub enum TextureUnit {
    TU0 = 0,
    TU1 = 1,
}

unsafe extern "C" fn real_vsync_handler() {
    if let Some(handler) = VSYNC_HANDLER {
        handler();
    }
}

/// Clear the backbuffer to the given color
pub fn clear_color(color: Color32) {
    unsafe { vdp_clearColor(&color); }
}

/// Clear the depth buffer to the given depth value
pub fn clear_depth(depth: f32) {
    unsafe { vdp_clearDepth(depth); }
}

/// Set whether depth writes are enabled
pub fn depth_write(enable: bool) {
    unsafe { vdp_depthWrite(enable) };
}

/// Set the current depth test comparison
pub fn depth_func(compare: Compare) {
    unsafe { vdp_depthFunc(compare) };
}

/// Set the blend equation mode
pub fn blend_equation(mode: BlendEquation) {
    unsafe { vdp_blendEquation(mode) };
}

/// Set the source and destination blend factors
pub fn blend_func(src_factor: BlendFactor, dst_factor: BlendFactor) {
    unsafe { vdp_blendFunc(src_factor, dst_factor) };
}

/// Set the winding order for backface culling
pub fn set_winding(winding: WindingOrder) {
    unsafe { vdp_setWinding(winding) };
}

/// Set backface culling enabled or disabled
pub fn set_culling(enabled: bool) {
    unsafe { vdp_setCulling(enabled) };
}

/// Submit a buffer of geometry to draw
#[deprecated(since = "0.1.16", note = "New apps should prefer a custom vertex layout in combination with submit_vu instead")]
pub fn draw_geometry(topology: Topology, vertex_data: &[Vertex]) {
    unsafe { vdp_drawGeometry(topology, 0, vertex_data.len().try_into().unwrap(), vertex_data.as_ptr()) };
}

/// Submit a buffer of geometry to draw
#[deprecated(since = "0.1.16", note = "Use submit_vu instead")]
pub fn draw_geometry_packed(topology: Topology, vertex_data: &[PackedVertex]) {
    unsafe { vdp_drawGeometryPacked(topology, 0, vertex_data.len().try_into().unwrap(), vertex_data.as_ptr()) };
}

/// Get total texture memory usage in bytes
pub fn get_usage() -> i32 {
    unsafe { return vdp_getUsage() };
}

/// Set currently active texture sampling parameters
#[deprecated(since = "0.1.16", note = "Use set_sample_params_slot instead")]
pub fn set_sample_params(filter: TextureFilter, wrap_u: TextureWrap, wrap_v: TextureWrap) {
    unsafe { vdp_setSampleParams(filter, wrap_u, wrap_v) };
}

/// Bind a texture for drawing
#[deprecated(since = "0.1.16", note = "Use bind_texture_slot instead")]
pub fn bind_texture(texture: Option<&Texture>) {
    if texture.is_some() {
        unsafe { vdp_bindTexture(texture.unwrap().handle) };
    } else {
        unsafe { vdp_bindTexture(-1) };
    }
}

/// Set the current viewport rect
pub fn viewport(rect: Rectangle) {
    unsafe {
        vdp_viewport(rect.x, rect.y, rect.width, rect.height);
    }
}

/// Compare a region of the depth buffer against the given reference value
pub fn submit_depth_query(ref_val: f32, compare: Compare, rect: Rectangle) {
    unsafe {
        vdp_submitDepthQuery(ref_val, compare, rect.x, rect.y, rect.width, rect.height);
    }
}

/// Get the number of pixels which passed the submitted depth query
pub fn get_depth_query_result() -> i32 {
    unsafe {
        return vdp_getDepthQueryResult();
    }
}

/// Set one of VU's 16 const data slots to given vector
pub fn set_vu_cdata(offset: usize, data: &Vector4) {
    unsafe {
        vdp_setVUCData(offset as i32, (data as *const Vector4).cast());
    }
}

/// Configure input vertex element slot layout
pub fn set_vu_layout(slot: usize, offset: usize, format: VertexSlotFormat) {
    unsafe {
        vdp_setVULayout(slot as i32, offset as i32, format);
    }
}

/// Set stride of input vertex data (size of each vertex in bytes)
pub fn set_vu_stride(stride: usize) {
    unsafe {
        vdp_setVUStride(stride as i32);
    }
}

/// Upload a new VU program
pub fn upload_vu_program(program: &[u32]) {
    unsafe {
        let program_len = program.len() * 4;
        vdp_uploadVUProgram(program.as_ptr().cast(), program_len as i32);
    }
}

/// Submit geometry to be processed by the VU
pub fn submit_vu<T>(topology: Topology, data: &[T]) {
    unsafe {
        let data_len = data.len() * size_of::<T>();
        vdp_submitVU(topology, data.as_ptr().cast(), data_len as i32);
    }
}

/// Set the current render target
pub fn set_render_target(texture: Option<RenderTexture>) {
    unsafe {
        match texture {
            Some(v) => {
                vdp_setRenderTarget(v.handle);
            }
            None => {
                vdp_setRenderTarget(-1);
            }
        }
    }
}

/// Set texture sample params for the given texture unit
pub fn set_sample_params_slot(slot: TextureUnit, filter: TextureFilter, wrap_u: TextureWrap, wrap_v: TextureWrap) {
    unsafe {
        vdp_setSampleParamsSlot(slot, filter, wrap_u, wrap_v);
    }
}

/// Bind a texture to the given texture unit
pub fn bind_texture_slot<T: DBTex>(slot: TextureUnit, texture: Option<&T>) {
    unsafe {
        match texture {
            Some(v) => {
                vdp_bindTextureSlot(slot, v.get_handle());
            }
            None => {
                vdp_bindTextureSlot(slot, -1);
            }
        }
    }
}

/// Set texture combiner mode
pub fn set_tex_combine(tex_combine: TexCombine, vtx_combine: TexCombine) {
    unsafe {
        vdp_setTexCombine(tex_combine, vtx_combine);
    }
}

/// Set an optional handler for vertical sync
pub fn set_vsync_handler(handler: Option<fn()>) {
    unsafe {
        VSYNC_HANDLER = handler;
        vdp_setVsyncHandler(real_vsync_handler);
    }
}