forked from vpinball/vpinball
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Texture.cpp
543 lines (454 loc) · 15.6 KB
/
Texture.cpp
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
#include "stdafx.h"
#include "Texture.h"
#include "freeimage.h"
#define STB_IMAGE_IMPLEMENTATION
#define STBI_ONLY_JPEG // only use the SSE2-JPG path from stbi, as all others are not faster than FreeImage //!! can remove stbi again if at some point FreeImage incorporates libjpeg-turbo or something similar
#define STBI_NO_STDIO
#define STBI_NO_FAILURE_STRINGS
#include "stb_image.h"
BaseTexture* BaseTexture::CreateFromFreeImage(FIBITMAP* dib)
{
// check if Textures exceed the maximum texture dimension
int maxTexDim = LoadValueIntWithDefault("Player", "MaxTexDimension", 0); // default: Don't resize textures
if (maxTexDim <= 0)
maxTexDim = 65536;
const int pictureWidth = FreeImage_GetWidth(dib);
const int pictureHeight = FreeImage_GetHeight(dib);
FIBITMAP* dibResized = dib;
FIBITMAP* dibConv = dib;
BaseTexture* tex = nullptr;
// do loading in a loop, in case memory runs out and we need to scale the texture down due to this
bool success = false;
while(!success)
{
// the mem is so low that the texture won't even be able to be rescaled -> return
if (maxTexDim <= 0)
{
FreeImage_Unload(dib);
return nullptr;
}
if ((pictureHeight > maxTexDim) || (pictureWidth > maxTexDim))
{
int newWidth = max(min(pictureWidth, maxTexDim), MIN_TEXTURE_SIZE);
int newHeight = max(min(pictureHeight, maxTexDim), MIN_TEXTURE_SIZE);
/*
* The following code tries to maintain the aspect ratio while resizing.
*/
if (pictureWidth - newWidth > pictureHeight - newHeight)
newHeight = min(pictureHeight * newWidth / pictureWidth, maxTexDim);
else
newWidth = min(pictureWidth * newHeight / pictureHeight, maxTexDim);
dibResized = FreeImage_Rescale(dib, newWidth, newHeight, FILTER_BILINEAR); //!! use a better filter in case scale ratio is pretty high?
}
else if (pictureWidth < MIN_TEXTURE_SIZE || pictureHeight < MIN_TEXTURE_SIZE)
{
// some drivers seem to choke on small (1x1) textures, so be safe by scaling them up
const int newWidth = max(pictureWidth, MIN_TEXTURE_SIZE);
const int newHeight = max(pictureHeight, MIN_TEXTURE_SIZE);
dibResized = FreeImage_Rescale(dib, newWidth, newHeight, FILTER_BOX);
}
// failed to get mem?
if (!dibResized)
{
maxTexDim /= 2;
while ((maxTexDim > pictureHeight) && (maxTexDim > pictureWidth))
maxTexDim /= 2;
continue;
}
const FREE_IMAGE_TYPE img_type = FreeImage_GetImageType(dibResized);
const bool rgbf = (img_type == FIT_FLOAT) || (img_type == FIT_DOUBLE) || (img_type == FIT_RGBF) || (img_type == FIT_RGBAF); //(FreeImage_GetBPP(dibResized) > 32);
const bool has_alpha = !!FreeImage_IsTransparent(dibResized);
// already in correct format?
if(((img_type == FIT_BITMAP) && (FreeImage_GetBPP(dibResized) == 32)) || (img_type == FIT_RGBF))
dibConv = dibResized;
else
{
dibConv = rgbf ? FreeImage_ConvertToRGBF(dibResized) : FreeImage_ConvertTo32Bits(dibResized);
if (dibResized != dib) // did we allocate a rescaled copy?
FreeImage_Unload(dibResized);
// failed to get mem?
if (!dibConv)
{
maxTexDim /= 2;
while ((maxTexDim > pictureHeight) && (maxTexDim > pictureWidth))
maxTexDim /= 2;
continue;
}
}
try
{
tex = new BaseTexture(FreeImage_GetWidth(dibConv), FreeImage_GetHeight(dibConv), rgbf ? RGB_FP : RGBA, rgbf ? false : has_alpha);
success = true;
}
// failed to get mem?
catch(...)
{
if (tex)
delete tex;
if (dibConv != dibResized) // did we allocate a copy from conversion?
FreeImage_Unload(dibConv);
else if (dibResized != dib) // did we allocate a rescaled copy?
FreeImage_Unload(dibResized);
maxTexDim /= 2;
while ((maxTexDim > pictureHeight) && (maxTexDim > pictureWidth))
maxTexDim /= 2;
}
}
tex->m_realWidth = pictureWidth;
tex->m_realHeight = pictureHeight;
const BYTE* const __restrict psrc = FreeImage_GetBits(dibConv);
BYTE* const __restrict pdst = tex->data();
const int pitchdst = tex->pitch(), pitchsrc = FreeImage_GetPitch(dibConv);
const int height = tex->height();
const int pitch = MIN(pitchsrc,pitchdst);
// flip upside down //!! meh, could this be done somewhere else to avoid additional overhead?
for (int y = 0; y < height; ++y)
memcpy(pdst + (height - y - 1)*pitchdst, psrc + y*pitchsrc, pitch);
if (dibConv != dibResized) // did we allocate a copy from conversion?
FreeImage_Unload(dibConv);
else if (dibResized != dib) // did we allocate a rescaled copy?
FreeImage_Unload(dibResized);
FreeImage_Unload(dib);
return tex;
}
BaseTexture* BaseTexture::CreateFromFile(const string& szfile)
{
if (szfile.empty())
return nullptr;
FREE_IMAGE_FORMAT fif;
// check the file signature and deduce its format
fif = FreeImage_GetFileType(szfile.c_str(), 0);
if (fif == FIF_UNKNOWN) {
// try to guess the file format from the file extension
fif = FreeImage_GetFIFFromFilename(szfile.c_str());
}
// check that the plugin has reading capabilities ...
if ((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
// ok, let's load the file
FIBITMAP * const dib = FreeImage_Load(fif, szfile.c_str(), 0);
if (!dib)
return nullptr;
BaseTexture* const mySurface = BaseTexture::CreateFromFreeImage(dib);
//if (bitsPerPixel == 24)
// mySurface->SetOpaque();
return mySurface;
}
else
return nullptr;
}
BaseTexture* BaseTexture::CreateFromData(const void *data, const size_t size)
{
// check the file signature and deduce its format
FIMEMORY * const dataHandle = FreeImage_OpenMemory((BYTE*)data, (DWORD)size);
if (!dataHandle)
return nullptr;
const FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(dataHandle, (int)size);
// check that the plugin has reading capabilities ...
if ((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
// ok, let's load the file
FIBITMAP * const dib = FreeImage_LoadFromMemory(fif, dataHandle, 0);
FreeImage_CloseMemory(dataHandle);
if (!dib)
return nullptr;
BaseTexture* const mySurface = BaseTexture::CreateFromFreeImage(dib);
//if (bitsPerPixel == 24)
// mySurface->SetOpaque();
return mySurface;
}
else
{
FreeImage_CloseMemory(dataHandle);
return nullptr;
}
}
// from the FreeImage FAQ page
static FIBITMAP* HBitmapToFreeImage(HBITMAP hbmp)
{
BITMAP bm;
GetObject(hbmp, sizeof(BITMAP), &bm);
FIBITMAP* dib = FreeImage_Allocate(bm.bmWidth, bm.bmHeight, bm.bmBitsPixel);
if (!dib)
return nullptr;
// The GetDIBits function clears the biClrUsed and biClrImportant BITMAPINFO members (dont't know why)
// So we save these infos below. This is needed for palettized images only.
const int nColors = FreeImage_GetColorsUsed(dib);
const HDC dc = GetDC(nullptr);
/*const int Success =*/ GetDIBits(dc, hbmp, 0, FreeImage_GetHeight(dib),
FreeImage_GetBits(dib), FreeImage_GetInfo(dib), DIB_RGB_COLORS);
ReleaseDC(nullptr, dc);
// restore BITMAPINFO members
FreeImage_GetInfoHeader(dib)->biClrUsed = nColors;
FreeImage_GetInfoHeader(dib)->biClrImportant = nColors;
return dib;
}
BaseTexture* BaseTexture::CreateFromHBitmap(const HBITMAP hbm)
{
FIBITMAP* const dib = HBitmapToFreeImage(hbm);
if (!dib)
return nullptr;
BaseTexture* const pdds = BaseTexture::CreateFromFreeImage(dib);
return pdds;
}
////////////////////////////////////////////////////////////////////////////////
Texture::Texture()
{
m_pdsBuffer = nullptr;
m_hbmGDIVersion = nullptr;
m_ppb = nullptr;
m_alphaTestValue = 1.0f;
}
Texture::Texture(BaseTexture * const base)
{
m_pdsBuffer = base;
SetSizeFrom(base);
m_hbmGDIVersion = nullptr;
m_ppb = nullptr;
m_alphaTestValue = 1.0f;
}
Texture::~Texture()
{
FreeStuff();
}
HRESULT Texture::SaveToStream(IStream *pstream, const PinTable *pt)
{
BiffWriter bw(pstream, 0);
bw.WriteString(FID(NAME), m_szName);
bw.WriteString(FID(PATH), m_szPath);
bw.WriteInt(FID(WDTH), m_width);
bw.WriteInt(FID(HGHT), m_height);
if (!m_ppb)
{
bw.WriteTag(FID(BITS));
// 32-bit picture
LZWWriter lzwwriter(pstream, (int *)m_pdsBuffer->data(), m_width * 4, m_height, m_pdsBuffer->pitch());
lzwwriter.CompressBits(8 + 1);
}
else // JPEG (or other binary format)
{
if (!pt->GetImageLink(this))
{
bw.WriteTag(FID(JPEG));
m_ppb->SaveToStream(pstream);
}
else
bw.WriteInt(FID(LINK), 1);
}
bw.WriteFloat(FID(ALTV), m_alphaTestValue);
bw.WriteTag(FID(ENDB));
return S_OK;
}
HRESULT Texture::LoadFromStream(IStream *pstream, int version, PinTable *pt)
{
BiffReader br(pstream, this, pt, version, 0, 0);
br.Load();
return ((m_pdsBuffer != nullptr) ? S_OK : E_FAIL);
}
bool Texture::LoadFromMemory(BYTE * const data, const DWORD size)
{
if (m_pdsBuffer)
FreeStuff();
const int maxTexDim = LoadValueIntWithDefault("Player", "MaxTexDimension", 0); // default: Don't resize textures
if(maxTexDim <= 0) // only use fast JPG path via stbi if no texture resize must be triggered
{
int x, y, channels_in_file;
unsigned char * const __restrict stbi_data = stbi_load_from_memory(data, size, &x, &y, &channels_in_file, 4);
if (stbi_data) // will only enter this path for JPG files
{
BaseTexture* tex = nullptr;
try
{
tex = new BaseTexture(x, y, BaseTexture::RGBA, channels_in_file == 4); //!! stbi at the moment does not support alpha channel JPGs, so channels_in_file will be 3 or 1
}
// failed to get mem?
catch(...)
{
if(tex)
delete tex;
goto freeimage_fallback;
}
// copy, but exchange R,B channels //!! meh, could this be done somewhere else to avoid additional overhead?
DWORD* const __restrict pdst = (DWORD*)tex->data();
const DWORD* const __restrict psrc = (DWORD*)stbi_data;
assert(tex->pitch() == x*4);
unsigned int o = 0;
for (int yo = 0; yo < y; ++yo)
for (int xo = 0; xo < x; ++xo,++o)
{
const DWORD src = psrc[o];
pdst[o] = (src & 0xFF00FF00u) | _rotl(src & 0x00FF00FFu, 16);
}
stbi_image_free(stbi_data);
tex->m_realWidth = x;
tex->m_realHeight = y;
m_pdsBuffer = tex;
SetSizeFrom(m_pdsBuffer);
return true;
}
}
freeimage_fallback:
FIMEMORY * const hmem = FreeImage_OpenMemory(data, size);
if (!hmem)
return false;
const FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(hmem, 0);
FIBITMAP * const dib = FreeImage_LoadFromMemory(fif, hmem, 0);
FreeImage_CloseMemory(hmem);
if (!dib)
return false;
m_pdsBuffer = BaseTexture::CreateFromFreeImage(dib);
SetSizeFrom(m_pdsBuffer);
return true;
}
bool Texture::LoadToken(const int id, BiffReader * const pbr)
{
switch(id)
{
case FID(NAME): pbr->GetString(m_szName); break;
case FID(PATH): pbr->GetString(m_szPath); break;
case FID(WDTH): pbr->GetInt(m_width); break;
case FID(HGHT): pbr->GetInt(m_height); break;
case FID(ALTV): pbr->GetFloat(m_alphaTestValue); break;
case FID(BITS):
{
if (m_pdsBuffer)
FreeStuff();
m_pdsBuffer = new BaseTexture(m_width, m_height, BaseTexture::RGBA, true);
SetSizeFrom(m_pdsBuffer);
// 32-bit picture
LZWReader lzwreader(pbr->m_pistream, (int *)m_pdsBuffer->data(), m_width * 4, m_height, m_pdsBuffer->pitch());
lzwreader.Decoder();
const int lpitch = m_pdsBuffer->pitch();
// Assume our 32 bit color structure
// Find out if all alpha values are zero
BYTE * const __restrict pch = (BYTE *)m_pdsBuffer->data();
bool allAlphaZero = true;
for (int i = 0; i < m_height; i++)
{
unsigned int o = i*lpitch + 3;
for (int l = 0; l < m_width; l++,o+=4)
{
if (pch[o] != 0)
{
allAlphaZero = false;
goto endAlphaCheck;
}
}
}
endAlphaCheck:
//!! if (allAlpha255)
// m_pdsBuffer->m_has_alpha = false;
// all alpha values are 0: set them all to 0xff
if (allAlphaZero)
{
m_pdsBuffer->m_has_alpha = false;
for (int i = 0; i < m_height; i++)
{
unsigned int o = i*lpitch + 3;
for (int l = 0; l < m_width; l++,o+=4)
pch[o] = 0xff;
}
}
break;
}
case FID(JPEG):
{
m_ppb = new PinBinary();
m_ppb->LoadFromStream(pbr->m_pistream, pbr->m_version);
// m_ppb->m_szPath has the original filename
// m_ppb->m_pdata() is the buffer
// m_ppb->m_cdata() is the filesize
return LoadFromMemory((BYTE*)m_ppb->m_pdata, m_ppb->m_cdata);
//break;
}
case FID(LINK):
{
int linkid;
pbr->GetInt(linkid);
PinTable * const pt = (PinTable *)pbr->m_pdata;
m_ppb = pt->GetImageLinkBinary(linkid);
return LoadFromMemory((BYTE*)m_ppb->m_pdata, m_ppb->m_cdata);
//break;
}
}
return true;
}
void Texture::FreeStuff()
{
delete m_pdsBuffer;
m_pdsBuffer = nullptr;
if (m_hbmGDIVersion)
{
if(m_hbmGDIVersion != g_pvp->m_hbmInPlayMode)
DeleteObject(m_hbmGDIVersion);
m_hbmGDIVersion = nullptr;
}
if (m_ppb)
{
delete m_ppb;
m_ppb = nullptr;
}
}
void Texture::CreateGDIVersion()
{
if (m_hbmGDIVersion)
return;
if (g_pvp->m_table_played_via_command_line || g_pvp->m_table_played_via_SelectTableOnStart) // only do anything in here (and waste memory/time on it) if UI needed (i.e. if not just -Play via command line is triggered or selected on VPX start with the file popup!)
{
m_hbmGDIVersion = g_pvp->m_hbmInPlayMode;
return;
}
const HDC hdcScreen = GetDC(nullptr);
m_hbmGDIVersion = CreateCompatibleBitmap(hdcScreen, m_width, m_height);
const HDC hdcNew = CreateCompatibleDC(hdcScreen);
const HBITMAP hbmOld = (HBITMAP)SelectObject(hdcNew, m_hbmGDIVersion);
BITMAPINFO bmi = {};
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = m_width;
bmi.bmiHeader.biHeight = -m_height;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biSizeImage = 0;
BYTE* tmp;
const bool needs_conversion = m_pdsBuffer->Needs_ConvertAlpha_Tonemap();
if (needs_conversion)
{
tmp = new BYTE[m_width*m_height * 4];
m_pdsBuffer->CopyTo_ConvertAlpha_Tonemap(tmp);
}
SetStretchBltMode(hdcNew, COLORONCOLOR);
StretchDIBits(hdcNew,
0, 0, m_width, m_height,
0, 0, m_width, m_height,
needs_conversion ? tmp : m_pdsBuffer->data(), &bmi, DIB_RGB_COLORS, SRCCOPY);
if (needs_conversion)
delete[] tmp;
SelectObject(hdcNew, hbmOld);
DeleteDC(hdcNew);
ReleaseDC(nullptr, hdcScreen);
}
void Texture::GetTextureDC(HDC *pdc)
{
CreateGDIVersion();
*pdc = CreateCompatibleDC(nullptr);
m_oldHBM = (HBITMAP)SelectObject(*pdc, m_hbmGDIVersion);
}
void Texture::ReleaseTextureDC(HDC dc)
{
SelectObject(dc, m_oldHBM);
DeleteDC(dc);
}
void Texture::CreateFromResource(const int id)
{
const HBITMAP hbm = (HBITMAP)LoadImage(g_pvp->theInstance, MAKEINTRESOURCE(id), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION);
if (m_pdsBuffer)
FreeStuff();
if (hbm == nullptr)
return;
m_pdsBuffer = CreateFromHBitmap(hbm);
}
BaseTexture* Texture::CreateFromHBitmap(const HBITMAP hbm)
{
BaseTexture* const pdds = BaseTexture::CreateFromHBitmap(hbm);
SetSizeFrom(pdds);
return pdds;
}