about summary refs log tree commit diff
path: root/src/engine/external/glfw/lib/image.c
blob: 3caa151864279c7189dfcce1b976677d88ba064d (plain)
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//========================================================================
// GLFW - An OpenGL framework
// File:        image.c
// Platform:    Any
// API version: 2.6
// WWW:         http://glfw.sourceforge.net
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Camilla Berglund
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//    claim that you wrote the original software. If you use this software
//    in a product, an acknowledgment in the product documentation would
//    be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
//    be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
//    distribution.
//
//========================================================================

//========================================================================
// Description:
//
// This module acts as an interface for different image file formats (the
// image file format is detected automatically).
//
// By default the loaded image is rescaled (using bilinear interpolation)
// to the next higher 2^N x 2^M resolution, unless it has a valid
// 2^N x 2^M resolution. The interpolation is quite slow, even if the
// routine has been optimized for speed (a 200x200 RGB image is scaled to
// 256x256 in ~30 ms on a P3-500).
//
// Paletted images are converted to RGB/RGBA images.
//
// A convenience function is also included (glfwLoadTexture2D), which
// loads a texture image from a file directly to OpenGL texture memory,
// with an option to generate all mipmap levels. GL_SGIS_generate_mipmap
// is used whenever available, which should give an optimal mipmap
// generation speed (possibly performed in hardware). A software fallback
// method is included when GL_SGIS_generate_mipmap is not supported (it
// generates all mipmaps of a 256x256 RGB texture in ~3 ms on a P3-500).
//
//========================================================================


#include "internal.h"


// We want to support automatic mipmap generation
#ifndef GL_SGIS_generate_mipmap
 #define GL_GENERATE_MIPMAP_SGIS       0x8191
 #define GL_GENERATE_MIPMAP_HINT_SGIS  0x8192
 #define GL_SGIS_generate_mipmap    1
#endif // GL_SGIS_generate_mipmap


//************************************************************************
//****                  GLFW internal functions                       ****
//************************************************************************

//========================================================================
// _glfwUpsampleImage() - Upsample image, from size w1 x h1 to w2 x h2
//========================================================================

static void _glfwUpsampleImage( unsigned char *src, unsigned char *dst,
    int w1, int h1, int w2, int h2, int bpp )
{
    int m, n, k, x, y, col8;
    float dx, dy, xstep, ystep, col, col1, col2;
    unsigned char *src1, *src2, *src3, *src4;

    // Calculate scaling factor
    xstep = (float)(w1-1) / (float)(w2-1);
    ystep = (float)(h1-1) / (float)(h2-1);

    // Copy source data to destination data with bilinear interpolation
    // Note: The rather strange look of this routine is a direct result of
    // my attempts at optimizing it. Improvements are welcome!
    dy = 0.0f;
    y = 0;
    for( n = 0; n < h2; n ++ )
    {
        dx = 0.0f;
        src1 = &src[ y*w1*bpp ];
        src3 = y < (h1-1) ? src1 + w1*bpp : src1;
        src2 = src1 + bpp;
        src4 = src3 + bpp;
        x = 0;
        for( m = 0; m < w2; m ++ )
        {
            for( k = 0; k < bpp; k ++ )
            {
                col1 = *src1 ++;
                col2 = *src2 ++;
                col = col1 + (col2 - col1) * dx;
                col1 = *src3 ++;
                col2 = *src4 ++;
                col2 = col1 + (col2 - col1) * dx;
                col += (col2 - col) * dy;
                col8 = (int) (col + 0.5);
                if( col8 >= 256 ) col8 = 255;
                *dst++ = (unsigned char) col8;
            }
            dx += xstep;
            if( dx >= 1.0f )
            {
                x ++;
                dx -= 1.0f;
                if( x >= (w1-1) )
                {
                    src2 = src1;
                    src4 = src3;
                }
            }
            else
            {
                src1 -= bpp;
                src2 -= bpp;
                src3 -= bpp;
                src4 -= bpp;
            }
        }
        dy += ystep;
        if( dy >= 1.0f )
        {
            y ++;
            dy -= 1.0f;
        }
    }
}


//========================================================================
// _glfwHalveImage() - Build the next mip-map level
//========================================================================

static int _glfwHalveImage( GLubyte *src, int *width, int *height,
    int components )
{
    int     halfwidth, halfheight, m, n, k, idx1, idx2;
    GLubyte *dst;

    // Last level?
    if( *width <= 1 && *height <= 1 )
    {
        return GL_FALSE;
    }

    // Calculate new width and height (handle 1D case)
    halfwidth  = *width > 1 ? *width / 2 : 1;
    halfheight = *height > 1 ? *height / 2 : 1;

    // Downsample image with a simple box-filter
    dst = src;
    if( *width == 1 || *height == 1 )
    {
        // 1D case
        for( m = 0; m < halfwidth+halfheight-1; m ++ )
        {
            for( k = 0; k < components; k ++ )
            {
                *dst ++ = (GLubyte) (((int)*src +
                                      (int)src[components] + 1) >> 1);
                src ++;
            }
            src += components;
        }
    }
    else
    {
        // 2D case
        idx1 = *width*components;
        idx2 = (*width+1)*components;
        for( m = 0; m < halfheight; m ++ )
        {
            for( n = 0; n < halfwidth; n ++ )
            {
                for( k = 0; k < components; k ++ )
                {
                    *dst ++ = (GLubyte) (((int)*src +
                                          (int)src[components] +
                                          (int)src[idx1] +
                                          (int)src[idx2] + 2) >> 2);
                    src ++;
                }
                src += components;
            }
            src += components * (*width);
        }
    }

    // Return new width and height
    *width = halfwidth;
    *height = halfheight;

    return GL_TRUE;
}


//========================================================================
// _glfwRescaleImage() - Rescales an image into power-of-two dimensions
//========================================================================

static int _glfwRescaleImage( GLFWimage* image )
{
    int     width, height, log2, newsize;
    unsigned char *data;

    // Calculate next larger 2^N width
    for( log2 = 0, width = image->Width; width > 1; width >>= 1, log2 ++ )
      ;
    width  = (int) 1 << log2;
    if( width < image->Width )
    {
	width <<= 1;
    }

    // Calculate next larger 2^M height
    for( log2 = 0, height = image->Height; height > 1; height >>= 1, log2 ++ )
      ;
    height = (int) 1 << log2;
    if( height < image->Height )
    {
	height <<= 1;
    }

    // Do we really need to rescale?
    if( width != image->Width || height != image->Height )
    {
        // Allocate memory for new (upsampled) image data
        newsize = width * height * image->BytesPerPixel;
        data = (unsigned char *) malloc( newsize );
        if( data == NULL )
        {
            free( image->Data );
            return GL_FALSE;
        }

        // Copy old image data to new image data with interpolation
        _glfwUpsampleImage( image->Data, data, image->Width, image->Height,
                            width, height, image->BytesPerPixel );

        // Free memory for old image data (not needed anymore)
        free( image->Data );

        // Set pointer to new image data, and set new image dimensions
        image->Data   = data;
        image->Width  = width;
        image->Height = height;
    }

    return GL_TRUE;
}


//************************************************************************
//****                    GLFW user functions                         ****
//************************************************************************

//========================================================================
// glfwReadImage() - Read an image from a named file
//========================================================================

GLFWAPI int GLFWAPIENTRY glfwReadImage( const char *name, GLFWimage *img,
    int flags )
{
    _GLFWstream stream;

    // Is GLFW initialized?
    if( !_glfwInitialized )
    {
        return GL_FALSE;
    }

    // Start with an empty image descriptor
    img->Width         = 0;
    img->Height        = 0;
    img->BytesPerPixel = 0;
    img->Data          = NULL;

    // Open file
    if( !_glfwOpenFileStream( &stream, name, "rb" ) )
    {
        return GL_FALSE;
    }

    // We only support TGA files at the moment
    if( !_glfwReadTGA( &stream, img, flags ) )
    {
	_glfwCloseStream( &stream );
        return GL_FALSE;
    }

    // Close stream
    _glfwCloseStream( &stream );

    // Should we rescale the image to closest 2^N x 2^M resolution?
    if( !(flags & GLFW_NO_RESCALE_BIT) )
    {
	if( !_glfwRescaleImage( img ) )
	{
	    return GL_FALSE;
	}
    }

    // Interpret BytesPerPixel as an OpenGL format
    switch( img->BytesPerPixel )
    {
        default:
        case 1:
            if( flags & GLFW_ALPHA_MAP_BIT )
            {
                img->Format = GL_ALPHA;
            }
            else
            {
                img->Format = GL_LUMINANCE;
            }
            break;
        case 3:
            img->Format = GL_RGB;
            break;
        case 4:
            img->Format = GL_RGBA;
            break;
    }

    return GL_TRUE;
}


//========================================================================
// glfwReadMemoryImage() - Read an image file from a memory buffer
//========================================================================

GLFWAPI int  GLFWAPIENTRY glfwReadMemoryImage( const void *data, long size, GLFWimage *img, int flags )
{
    _GLFWstream stream;

    // Is GLFW initialized?
    if( !_glfwInitialized )
    {
        return GL_FALSE;
    }

    // Start with an empty image descriptor
    img->Width         = 0;
    img->Height        = 0;
    img->BytesPerPixel = 0;
    img->Data          = NULL;

    // Open buffer
    if( !_glfwOpenBufferStream( &stream, (void*) data, size ) )
    {
        return GL_FALSE;
    }

    // We only support TGA files at the moment
    if( !_glfwReadTGA( &stream, img, flags ) )
    {
	_glfwCloseStream( &stream );
        return GL_FALSE;
    }

    // Close stream
    _glfwCloseStream( &stream );

    // Should we rescale the image to closest 2^N x 2^M resolution?
    if( !(flags & GLFW_NO_RESCALE_BIT) )
    {
	if( !_glfwRescaleImage( img ) )
	{
	    return GL_FALSE;
	}
    }

    // Interpret BytesPerPixel as an OpenGL format
    switch( img->BytesPerPixel )
    {
        default:
        case 1:
            if( flags & GLFW_ALPHA_MAP_BIT )
            {
                img->Format = GL_ALPHA;
            }
            else
            {
                img->Format = GL_LUMINANCE;
            }
            break;
        case 3:
            img->Format = GL_RGB;
            break;
        case 4:
            img->Format = GL_RGBA;
            break;
    }

    return GL_TRUE;
}


//========================================================================
// glfwFreeImage() - Free allocated memory for an image
//========================================================================

GLFWAPI void GLFWAPIENTRY glfwFreeImage( GLFWimage *img )
{
    // Is GLFW initialized?
    if( !_glfwInitialized )
    {
        return;
    }

    // Free memory
    if( img->Data != NULL )
    {
        free( img->Data );
        img->Data = NULL;
    }

    // Clear all fields
    img->Width         = 0;
    img->Height        = 0;
    img->Format        = 0;
    img->BytesPerPixel = 0;
}


//========================================================================
// glfwLoadTexture2D() - Read an image from a file, and upload it to
// texture memory
//========================================================================

GLFWAPI int GLFWAPIENTRY glfwLoadTexture2D( const char *name, int flags )
{
    GLFWimage img;

    // Is GLFW initialized?
    if( !_glfwInitialized || !_glfwWin.Opened )
    {
        return GL_FALSE;
    }

    // Force rescaling if necessary
    if( !_glfwWin.Has_GL_ARB_texture_non_power_of_two )
    {
      flags &= (~GLFW_NO_RESCALE_BIT);
    }

    // Read image from file
    if( !glfwReadImage( name, &img, flags ) )
    {
        return GL_FALSE;
    }

    if( !glfwLoadTextureImage2D( &img, flags ) )
    {
	return GL_FALSE;
    }

    // Data buffer is not needed anymore
    glfwFreeImage( &img );

    return GL_TRUE;
}


//========================================================================
// glfwLoadMemoryTexture2D() - Read an image from a buffer, and upload it to
// texture memory
//========================================================================

GLFWAPI int  GLFWAPIENTRY glfwLoadMemoryTexture2D( const void *data, long size, int flags )
{
    GLFWimage img;

    // Is GLFW initialized?
    if( !_glfwInitialized || !_glfwWin.Opened )
    {
        return GL_FALSE;
    }

    // Force rescaling if necessary
    if( !_glfwWin.Has_GL_ARB_texture_non_power_of_two )
    {
      flags &= (~GLFW_NO_RESCALE_BIT);
    }

    // Read image from file
    if( !glfwReadMemoryImage( data, size, &img, flags ) )
    {
        return GL_FALSE;
    }

    if( !glfwLoadTextureImage2D( &img, flags ) )
    {
	return GL_FALSE;
    }

    // Data buffer is not needed anymore
    glfwFreeImage( &img );

    return GL_TRUE;
}


//========================================================================
// glfwLoadTextureImage2D() - Upload an image object to texture memory
//========================================================================

GLFWAPI int  GLFWAPIENTRY glfwLoadTextureImage2D( GLFWimage *img, int flags )
{
    GLint   UnpackAlignment, GenMipMap;
    int     level, format, AutoGen, newsize, n;
    unsigned char *data, *dataptr;

    // Is GLFW initialized?
    if( !_glfwInitialized || !_glfwWin.Opened )
    {
        return GL_FALSE;
    }

    // TODO: Use GL_MAX_TEXTURE_SIZE or GL_PROXY_TEXTURE_2D to determine
    //       whether the image size is valid.
    // NOTE: May require box filter downsampling routine.

    // Do we need to convert the alpha map to RGBA format (OpenGL 1.0)?
    if( (_glfwWin.GLVerMajor == 1) && (_glfwWin.GLVerMinor == 0) &&
        (img->Format == GL_ALPHA) )
    {
        // We go to RGBA representation instead
        img->BytesPerPixel = 4;

        // Allocate memory for new RGBA image data
        newsize = img->Width * img->Height * img->BytesPerPixel;
        data = (unsigned char *) malloc( newsize );
        if( data == NULL )
        {
            free( img->Data );
            return GL_FALSE;
        }

        // Convert Alpha map to RGBA
        dataptr = data;
        for( n = 0; n < (img->Width*img->Height); ++ n )
        {
            *dataptr ++ = 255;
            *dataptr ++ = 255;
            *dataptr ++ = 255;
            *dataptr ++ = img->Data[n];
        }

        // Free memory for old image data (not needed anymore)
        free( img->Data );

        // Set pointer to new image data
        img->Data = data;
    }

    // Set unpack alignment to one byte
    glGetIntegerv( GL_UNPACK_ALIGNMENT, &UnpackAlignment );
    glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );

    // Should we use automatic mipmap generation?
    AutoGen = ( flags & GLFW_BUILD_MIPMAPS_BIT ) &&
              _glfwWin.Has_GL_SGIS_generate_mipmap;

    // Enable automatic mipmap generation
    if( AutoGen )
    {
        glGetTexParameteriv( GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,
            &GenMipMap );
        glTexParameteri( GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,
            GL_TRUE );
    }

    // Format specification is different for OpenGL 1.0
    if( _glfwWin.GLVerMajor == 1 && _glfwWin.GLVerMinor == 0 )
    {
        format = img->BytesPerPixel;
    }
    else
    {
        format = img->Format;
    }

    // Upload to texture memeory
    level = 0;
    do
    {
        // Upload this mipmap level
        glTexImage2D( GL_TEXTURE_2D, level, format,
            img->Width, img->Height, 0, format,
            GL_UNSIGNED_BYTE, (void*) img->Data );

        // Build next mipmap level manually, if required
        if( ( flags & GLFW_BUILD_MIPMAPS_BIT ) && !AutoGen )
        {
            level = _glfwHalveImage( img->Data, &img->Width,
                        &img->Height, img->BytesPerPixel ) ?
                    level + 1 : 0;
        }
    }
    while( level != 0 );

    // Restore old automatic mipmap generation state
    if( AutoGen )
    {
        glTexParameteri( GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,
            GenMipMap );
    }

    // Restore old unpack alignment
    glPixelStorei( GL_UNPACK_ALIGNMENT, UnpackAlignment );

    return GL_TRUE;
}