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
/*!
FontStash integration for Rokol (`rokol::gfx`)
*/

pub use fontstash::{self, Align, FonsQuad, FontStash};

use std::os::raw::{c_int, c_uchar, c_void};

use crate::gfx::{self as rg, BakedResource};

/// Be sure to set alignment of the [`FontStash`] to draw text as you want.
#[derive(Debug)]
pub struct FontTexture {
    /// Give fixed memory location
    inner: Box<FontTextureImpl>,
}

impl std::ops::Deref for FontTexture {
    type Target = FontTextureImpl;
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl std::ops::DerefMut for FontTexture {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl FontTexture {
    pub fn new(w: u32, h: u32) -> Self {
        let mut inner = Box::new(FontTextureImpl {
            stash: FontStash::uninitialized(),
            img: Default::default(),
            w,
            h,
            is_dirty: false,
            tex_data: Vec::with_capacity((w * h) as usize),
        });

        let inner_ptr = inner.as_ref() as *const _ as *mut FontTextureImpl;
        // create internal image with the `create` callback:
        inner.stash.init_mut(w, h, inner_ptr);

        fontstash::set_error_callback(
            inner.stash().raw(),
            fons_error_callback,
            inner_ptr as *mut _,
        );

        return FontTexture { inner };

        unsafe extern "C" fn fons_error_callback(
            _uptr: *mut c_void,
            error_code: c_int,
            _val: c_int,
        ) {
            match fontstash::ErrorCode::from_u32(error_code as u32) {
                Some(error) => {
                    log::warn!("fons error: {:?}", error);
                }
                None => {
                    log::warn!("fons error error: given broken erroor code");
                }
            }
        }
    }
}

/// We have to give fixed memory location to `FontTextureImpl` so that `fontstash` (a C library) can
/// call callback methods.
#[derive(Debug)]
pub struct FontTextureImpl {
    stash: fontstash::FontStash,
    img: rg::Image,
    /// The texture size, which is always synced with the fontstash size
    w: u32,
    /// The texture size, which is always synced with the fontstash size
    h: u32,
    /// We store texture data here because be can update our texture only once a frame
    tex_data: Vec<u8>,
    /// Shall we update the texture data in this frame?
    is_dirty: bool,
}

impl Drop for FontTextureImpl {
    fn drop(&mut self) {
        log::trace!("FontTextureImpl::drop");

        if self.img.id != 0 {
            log::trace!("==> destroy GPU font texture");
            rg::Image::destroy(self.img);
        }
    }
}

impl std::ops::Deref for FontTextureImpl {
    type Target = FontStash;
    fn deref(&self) -> &Self::Target {
        &self.stash
    }
}

impl std::ops::DerefMut for FontTextureImpl {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.stash
    }
}

/// Interface
impl FontTextureImpl {
    pub fn img(&self) -> rg::Image {
        self.img
    }

    pub fn cpu_texture(&self) -> (&Vec<u8>, [u32; 2]) {
        (&self.tex_data, [self.w, self.h])
    }

    pub fn stash(&self) -> &FontStash {
        &self.stash
    }

    /// Copies the shared ownership of Fontstash
    /// Returns [x, y, w, h]
    pub fn text_bounds_multiline(
        &self,
        text: &str,
        pos: impl Into<[f32; 2]>,
        fontsize: f32,
        line_spacing: f32,
    ) -> [f32; 4] {
        // TODO: apply fontsize automatially?
        let mut lines = text.lines();

        self.stash.set_size(fontsize);

        let [x, y, mut w, mut h] = {
            let [x1, y1, x2, y2] = self
                .stash
                .text_bounds_oneline(pos.into(), lines.next().unwrap());
            [x1, y1, x2 - x1, y2 - y1]
        };

        for line in lines {
            if line.is_empty() {
                h += fontsize + line_spacing;
            } else {
                let [x1, _y1, x2, _y2] = self.stash.text_bounds_oneline([0.0, 0.0], line);

                if x2 - x1 > w {
                    w = x2 - x1;
                }

                // h += (y2 - y1) + line_spacing;
                h += fontsize + line_spacing;
            }
        }

        [x, y, w, h]
    }

    /// Returns [x, y, w, h]
    pub fn text_size_multiline(&self, text: &str, fontsize: f32, line_spacing: f32) -> [f32; 2] {
        // TODO: apply fontsize automatially?
        let mut lines = text.lines();

        self.stash.set_size(fontsize);

        let [mut w, mut h] = self.stash.text_size_oneline(lines.next().unwrap());

        for line in lines {
            if line.is_empty() {
                h += fontsize + line_spacing;
                continue;
            } else {
                let [w2, _h2] = self.stash.text_size_oneline(line);

                if w2 > w {
                    w = w2
                }

                // h += h2 + line_spacing;
                h += fontsize + line_spacing;
            }
        }

        [w, h]
    }
}

// --------------------------------------------------------------------------------
// Callback and texture updating

/// Renderer implementation
///
/// Return `1` to represent success.
unsafe impl fontstash::Renderer for FontTextureImpl {
    /// Creates font texture
    unsafe extern "C" fn create(uptr: *mut c_void, width: c_int, height: c_int) -> c_int {
        let me = &mut *(uptr as *const _ as *mut Self);

        if me.img.id != 0 {
            log::trace!("FontTextureImpl::create -- dispose old image");
            rg::Image::destroy(me.img);
        }

        log::trace!("FontTextureImpl::create [{}, {}]", width, height);

        me.img = rg::Image::create(&rg::ImageDesc {
            type_: rg::ImageType::Dim2.to_ffi(),
            width,
            height,
            usage: rg::ResourceUsage::Dynamic.to_ffi(),
            ..Default::default()
        });

        me.w = width as u32;
        me.h = height as u32;

        me.is_dirty = true;

        true as c_int // success
    }

    unsafe extern "C" fn resize(uptr: *mut c_void, width: c_int, height: c_int) -> c_int {
        log::trace!("FontTextureImpl::resize");

        Self::create(uptr, width, height);
        true as c_int // success
    }

    /// Try to double the texture size when the atlas is full
    unsafe extern "C" fn expand(uptr: *mut c_void) -> c_int {
        log::trace!("FontTextureImpl::expand");

        let me = &mut *(uptr as *const _ as *mut Self);

        // Self::create(uptr, (me.w * 2) as i32, (me.h * 2) as i32);

        if let Err(why) = me.stash.expand_atlas(me.w * 2, me.h * 2) {
            log::warn!("fontstash: error on resize: {:?}", why);
            false as c_int // fail
        } else {
            true as c_int // success
        }
    }

    unsafe extern "C" fn update(
        uptr: *mut c_void,
        // TODO: what is the dirty rect
        _rect: *mut c_int,
        _data: *const c_uchar,
    ) -> c_int {
        let me = &mut *(uptr as *const _ as *mut Self);
        me.is_dirty = true;
        true as c_int // success
    }
}

impl FontTextureImpl {
    fn update_cpu_image(&mut self) {
        let tex_data = &mut self.tex_data;
        tex_data.clear();

        self.stash.with_pixels(|pixels, w, h| {
            log::trace!("FontTextureImpl: [{}, {}] update CPU texture", w, h);

            let area = (w * h) as usize;
            // self.tex_data.ensure_capacity(area);

            // four channels (RGBA)
            for i in 0..area {
                tex_data.push(255);
                tex_data.push(255);
                tex_data.push(255);
                tex_data.push(pixels[i]);
            }
        });

        // self.w = w;
        // self.h = h;
    }

    /// Call it every frame but only once
    pub unsafe fn maybe_update_image(&mut self) {
        if !self.is_dirty {
            return;
        }
        self.is_dirty = false;

        self.update_cpu_image();
        rg::update_image(self.img, &{
            let mut data = rg::ImageData::default();
            data.subimage[0][0] = self.tex_data.as_slice().into();
            data
        });
    }
}