-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathRenderTarget.cpp
More file actions
1227 lines (1031 loc) · 40.9 KB
/
RenderTarget.cpp
File metadata and controls
1227 lines (1031 loc) · 40.9 KB
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2014 Laurent Gomila ([email protected])
//
// 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.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <cpp3ds/Graphics/RenderTarget.hpp>
#include <cpp3ds/Graphics/Drawable.hpp>
#include <cpp3ds/Graphics/Shader.hpp>
#include <cpp3ds/Graphics/Texture.hpp>
#include <cpp3ds/Graphics/VertexArray.hpp>
#include <cpp3ds/Graphics/VertexBuffer.hpp>
#include <cpp3ds/Graphics/Light.hpp>
#include <cpp3ds/OpenGL.hpp>
#include <cpp3ds/System/Mutex.hpp>
#include <cpp3ds/System/Lock.hpp>
#include <cpp3ds/System/Err.hpp>
#include <sstream>
#include <cstddef>
namespace
{
// Convert an cpp3ds::BlendMode::Factor constant to the corresponding OpenGL constant.
cpp3ds::Uint32 factorToGlConstant(cpp3ds::BlendMode::Factor blendFactor)
{
switch (blendFactor)
{
default:
case cpp3ds::BlendMode::Zero: return GL_ZERO;
case cpp3ds::BlendMode::One: return GL_ONE;
case cpp3ds::BlendMode::SrcColor: return GL_SRC_COLOR;
case cpp3ds::BlendMode::OneMinusSrcColor: return GL_ONE_MINUS_SRC_COLOR;
case cpp3ds::BlendMode::DstColor: return GL_DST_COLOR;
case cpp3ds::BlendMode::OneMinusDstColor: return GL_ONE_MINUS_DST_COLOR;
case cpp3ds::BlendMode::SrcAlpha: return GL_SRC_ALPHA;
case cpp3ds::BlendMode::OneMinusSrcAlpha: return GL_ONE_MINUS_SRC_ALPHA;
case cpp3ds::BlendMode::DstAlpha: return GL_DST_ALPHA;
case cpp3ds::BlendMode::OneMinusDstAlpha: return GL_ONE_MINUS_DST_ALPHA;
}
}
// Convert an cpp3ds::BlendMode::BlendEquation constant to the corresponding OpenGL constant.
cpp3ds::Uint32 equationToGlConstant(cpp3ds::BlendMode::Equation blendEquation)
{
switch (blendEquation)
{
default:
case cpp3ds::BlendMode::Add: return GL_FUNC_ADD;
case cpp3ds::BlendMode::Subtract: return GL_FUNC_SUBTRACT;
}
}
// Thread-safe unique identifier generator,
// is used for id
cpp3ds::Uint64 getUniqueId()
{
static cpp3ds::Uint64 id = 1;
static cpp3ds::Mutex mutex;
cpp3ds::Lock lock(mutex);
return id++;
}
}
namespace cpp3ds
{
////////////////////////////////////////////////////////////
RenderTarget::RenderTarget() :
m_defaultView (),
m_view (NULL),
m_cache (),
m_depthTest (false),
m_clearDepth (false),
m_defaultShader (NULL),
m_currentNonLegacyShader(NULL),
m_lastNonLegacyShader (NULL),
m_id (getUniqueId()),
m_previousViewport (-1, -1, -1, -1),
m_previousClearColor (0, 0, 0, 0)
{
m_cache.vertexCache = new Vertex[StatesCache::VertexCacheSize];
m_cache.glStatesSet = false;
Light::increaseLightReferences();
}
////////////////////////////////////////////////////////////
RenderTarget::~RenderTarget()
{
Light::decreaseLightReferences();
delete m_defaultShader;
delete m_view;
delete[] m_cache.vertexCache;
}
////////////////////////////////////////////////////////////
void RenderTarget::clear(const Color& color)
{
if (activate(true))
{
// Unbind texture to fix RenderTexture preventing clear
applyTexture(NULL);
if (color != m_previousClearColor)
{
#ifdef EMULATION
glCheck(glClearColor(color.r / 255.f, color.g / 255.f, color.b / 255.f, color.a / 255.f));
#else
// Use glClearColorIiEXT to avoid unnecessary float conversion
glCheck(glClearColorIiEXT(color.r, color.g, color.b, color.a));
#endif
m_previousClearColor = color;
}
glCheck(glClear(GL_COLOR_BUFFER_BIT | (m_clearDepth ? GL_DEPTH_BUFFER_BIT : 0)));
}
}
////////////////////////////////////////////////////////////
void RenderTarget::enableDepthTest(bool enable)
{
m_depthTest = enable;
if(enable) {
glCheck(glEnable(GL_DEPTH_TEST));
} else {
glCheck(glDisable(GL_DEPTH_TEST));
}
}
////////////////////////////////////////////////////////////
const View& RenderTarget::getView() const
{
return *m_view;
}
////////////////////////////////////////////////////////////
const View& RenderTarget::getDefaultView() const
{
return m_defaultView;
}
////////////////////////////////////////////////////////////
IntRect RenderTarget::getViewport(const View& view) const
{
float width = static_cast<float>(getSize().x);
float height = static_cast<float>(getSize().y);
const FloatRect& viewport = view.getViewport();
return IntRect(static_cast<int>(0.5f + width * viewport.left),
static_cast<int>(0.5f + height * viewport.top),
static_cast<int>(0.5f + width * viewport.width),
static_cast<int>(0.5f + height * viewport.height));
}
////////////////////////////////////////////////////////////
Vector2f RenderTarget::mapPixelToCoords(const Vector2i& point) const
{
return mapPixelToCoords(point, getView());
}
////////////////////////////////////////////////////////////
Vector2f RenderTarget::mapPixelToCoords(const Vector2i& point, const View& view) const
{
// First, convert from viewport coordinates to homogeneous coordinates
Vector2f normalized;
IntRect viewport = getViewport(view);
normalized.x = -1.f + 2.f * (point.x - viewport.left) / viewport.width;
normalized.y = 1.f - 2.f * (point.y - viewport.top) / viewport.height;
// Then transform by the inverse of the view matrix
return view.getInverseTransform().transformPoint(normalized);
}
////////////////////////////////////////////////////////////
Vector2i RenderTarget::mapCoordsToPixel(const Vector3f& point) const
{
return mapCoordsToPixel(point, getView());
}
////////////////////////////////////////////////////////////
Vector2i RenderTarget::mapCoordsToPixel(const Vector3f& point, const View& view) const
{
// First, transform the point by the modelview and projection matrix
Vector3f normalized = (view.getTransform() * view.getViewTransform()).transformPoint(point);
// Then convert to viewport coordinates
Vector2i pixel;
IntRect viewport = getViewport(view);
pixel.x = static_cast<int>(( normalized.x + 1.f) / 2.f * viewport.width + viewport.left);
pixel.y = static_cast<int>((-normalized.y + 1.f) / 2.f * viewport.height + viewport.top);
return pixel;
}
////////////////////////////////////////////////////////////
void RenderTarget::draw(const Drawable& drawable, const RenderStates& states)
{
drawable.draw(*this, states);
}
////////////////////////////////////////////////////////////
void RenderTarget::draw(const VertexBuffer& buffer, const RenderStates& states)
{
// Nothing to draw?
if (!buffer.getVertexCount())
return;
draw(&buffer.m_vertices[0], buffer.getVertexCount(), buffer.m_primitiveType, states);
return;
if (activate(true))
{
// First set the persistent OpenGL states if it's the very first call
if (!m_cache.glStatesSet)
resetGLStates();
// Track if we need to set uniforms again for current shader
bool shaderChanged = false;
bool previousShaderWarnSetting = true;
// if (m_defaultShader)
// {
// // Non-legacy rendering, need to set uniforms
// if (states.shader)
// {
// m_currentNonLegacyShader = states.shader;
// previousShaderWarnSetting = states.shader->warnMissing(false);
// }
// else
// m_currentNonLegacyShader = m_defaultShader;
//
// shaderChanged = (m_currentNonLegacyShader != m_lastNonLegacyShader);
//
// m_currentNonLegacyShader->beginParameterBlock();
// }
applyTransform(states.transform);
// Apply the view
if (shaderChanged || m_cache.viewChanged)
applyCurrentView();
// Apply the blend mode
if (states.blendMode != m_cache.lastBlendMode)
applyBlendMode(states.blendMode);
// Apply the texture
Uint64 textureId = states.texture ? states.texture->m_cacheId : 0;
if (shaderChanged || (textureId != m_cache.lastTextureId))
applyTexture(states.texture);
// Apply the shader
// if (states.shader)
// applyShader(states.shader);
// else if (m_defaultShader)
// applyShader(m_defaultShader);
// Find the OpenGL primitive type
static const GLenum modes[] = {GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN};
GLenum mode = modes[buffer.getPrimitiveType()];
// Setup the pointers to the vertices' components
if (!m_defaultShader)
{
#ifdef EMULATION
// Apply the vertex buffer
Uint64 vertexBufferId = buffer.m_cacheId;
if (vertexBufferId != m_cache.lastVertexBufferId)
applyVertexBuffer(&buffer);
glCheck(glVertexPointer(3, GL_FLOAT, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, position))));
glCheck(glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, color))));
glCheck(glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, texCoords))));
glCheck(glNormalPointer(GL_FLOAT, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, normal))));
#else
// Temorary workaround until gl3ds can get VAO gl*Pointer functions working
u32 bufferOffsets[] = {0};
u64 bufferPermutations[] = {0x3210};
u8 bufferAttribCounts[] = {4};
GPU_SetAttributeBuffers(
4, // number of attributes
(u32 *) osConvertVirtToPhys((u32) &buffer.m_vertices[0]),
GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 4, GPU_UNSIGNED_BYTE) |
GPU_ATTRIBFMT(2, 2, GPU_FLOAT) | GPU_ATTRIBFMT(3, 3, GPU_FLOAT),
0xFF8, //0b1100
0x3210,
1, //number of buffers
bufferOffsets,
bufferPermutations,
bufferAttribCounts // number of attributes for each buffer
);
#endif
// Draw the primitives
glCheck(glDrawArrays(mode, 0, buffer.getVertexCount()));
}
else
{
Light::addLightsToShader(*m_currentNonLegacyShader);
unsigned int arrayObject = 0;
bool newArray = true;
bool needUpload = false;
if (VertexBuffer::hasVertexArrayObjects())
{
// Lookup the current context (id, shader id) in the VertexBuffer
std::pair<Uint64, Uint64> contextIdentifier(m_id, m_currentNonLegacyShader->m_id);
VertexBuffer::ArrayObjects::iterator arrayObjectIter = buffer.m_arrayObjects.find(contextIdentifier);
if (arrayObjectIter == buffer.m_arrayObjects.end())
{
// VertexBuffer doesn't have a VAO in this context
// Create a new VAO
glCheck(glGenVertexArrays(1, &arrayObject));
// Register the VAO with the VertexBuffer
buffer.m_arrayObjects[contextIdentifier] = arrayObject;
// Mark the VAO age as 0
m_arrayAgeCount[arrayObject] = 0;
}
else
{
// VertexBuffer has/had a VAO in this context
// Grab the VAO identifier from the VertexBuffer
arrayObject = arrayObjectIter->second;
// Still need to check if it still exists
ArrayAgeCount::iterator arrayAge = m_arrayAgeCount.find(arrayObject);
if (arrayAge != m_arrayAgeCount.end())
{
// VAO still exists in this context
newArray = false;
// Check if the VertexBuffer data needs to be re-uploaded
needUpload = buffer.m_needUpload;
// Mark the VAO age as 0
arrayAge->second = 0;
}
else
{
// VAO needs to be recreated in this context
// Create a new VAO
glCheck(glGenVertexArrays(1, &arrayObject));
// Register the VAO with the VertexBuffer
arrayObjectIter->second = arrayObject;
// Mark the VAO age as 0
m_arrayAgeCount[arrayObject] = 0;
}
}
glBindVertexArray(arrayObject);
// Maximum array object age in draw calls before being purged
// If an array object was not used to draw this many
// calls, it will be considered expired and purged
// from the context owned by this RenderTarget
const static unsigned int maxArrayObjectAge = 10000;
// Increment age counters and purge all expired VAOs
for (ArrayAgeCount::iterator arrayAge = m_arrayAgeCount.begin(); arrayAge != m_arrayAgeCount.end();)
{
arrayAge->second++;
if (arrayAge->second > maxArrayObjectAge)
{
glCheck(glDeleteVertexArrays(1, &(arrayAge->first)));
m_arrayAgeCount.erase(arrayAge++);
continue;
}
++arrayAge;
}
}
int vertexLocation = -1;
int colorLocation = -1;
int texCoordLocation = -1;
int normalLocation = -1;
// If we are creating a new array object or buffer data
// needs to be re-uploaded, we need to rebind even if
// it is still currently bound
if (newArray || needUpload)
{
// Apply the vertex buffer
Uint64 vertexBufferId = buffer.m_cacheId;
applyVertexBuffer(&buffer);
}
if (newArray)
{
vertexLocation = m_currentNonLegacyShader->getVertexAttributeLocation("sf_Vertex");
colorLocation = m_currentNonLegacyShader->getVertexAttributeLocation("sf_Color");
texCoordLocation = m_currentNonLegacyShader->getVertexAttributeLocation("sf_MultiTexCoord0");
normalLocation = m_currentNonLegacyShader->getVertexAttributeLocation("sf_Normal");
if (vertexLocation >= 0)
{
glCheck(glEnableVertexAttribArray(vertexLocation));
glCheck(glVertexAttribPointer(vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, position))));
}
if (colorLocation >= 0)
{
glCheck(glEnableVertexAttribArray(colorLocation));
glCheck(glVertexAttribPointer(colorLocation, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, color))));
}
if (texCoordLocation >= 0)
{
glCheck(glEnableVertexAttribArray(texCoordLocation));
glCheck(glVertexAttribPointer(texCoordLocation, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, texCoords))));
}
if (normalLocation >= 0)
{
glCheck(glEnableVertexAttribArray(normalLocation));
glCheck(glVertexAttribPointer(normalLocation, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, normal))));
}
}
// Draw the primitives
glCheck(glDrawArrays(mode, 0, buffer.getVertexCount()));
if (arrayObject)
glBindVertexArray(0);
if (vertexLocation >= 0)
glCheck(glDisableVertexAttribArray(vertexLocation));
if (colorLocation >= 0)
glCheck(glDisableVertexAttribArray(colorLocation));
if (texCoordLocation >= 0)
glCheck(glDisableVertexAttribArray(texCoordLocation));
if (normalLocation >= 0)
glCheck(glDisableVertexAttribArray(normalLocation));
}
// Unbind the shader, if any was bound in legacy mode
// if (states.shader && !m_defaultShader)
// applyShader(NULL);
// if (m_defaultShader)
// {
// m_currentNonLegacyShader->endParameterBlock();
//
// if (states.shader)
// states.shader->warnMissing(previousShaderWarnSetting);
//
// m_lastNonLegacyShader = m_currentNonLegacyShader;
// m_currentNonLegacyShader = NULL;
// }
}
}
////////////////////////////////////////////////////////////
void RenderTarget::draw(const Vertex* vertices, unsigned int vertexCount,
PrimitiveType type, const RenderStates& states)
{
// Nothing to draw?
if (!vertices || (vertexCount == 0))
return;
// Vertices allocated in the stack (common) can't be converted to physical address
#ifndef EMULATION
if (osConvertVirtToPhys((u32)vertices) == 0)
{
err() << "RenderTarget::draw() called with vertex array in inaccessible memory space." << std::endl;
return;
}
#endif
if (activate(true))
{
// First set the persistent OpenGL states if it's the very first call
if (!m_cache.glStatesSet)
resetGLStates();
// Track if we need to set uniforms again for current shader
bool shaderChanged = false;
bool previousShaderWarnSetting = true;
// if (m_defaultShader)
// {
// // Non-legacy rendering, need to set uniforms
// if (states.shader)
// {
// m_currentNonLegacyShader = states.shader;
// previousShaderWarnSetting = states.shader->warnMissing(false);
// }
// else
// m_currentNonLegacyShader = m_defaultShader;
//
// shaderChanged = (m_currentNonLegacyShader != m_lastNonLegacyShader);
//
// m_currentNonLegacyShader->beginParameterBlock();
// }
// Check if the vertex count is low enough so that we can pre-transform them
bool useVertexCache = (vertexCount <= StatesCache::VertexCacheSize);
if (useVertexCache)
{
// Pre-transform the vertices and store them into the vertex cache
for (unsigned int i = 0; i < vertexCount; ++i)
{
Vertex& vertex = m_cache.vertexCache[i];
vertex.position = states.transform * vertices[i].position;
vertex.color = vertices[i].color;
vertex.texCoords = vertices[i].texCoords;
}
// Since vertices are transformed, we must use an identity transform to render them
if (!m_cache.useVertexCache)
applyTransform(Transform::Identity);
}
else
{
applyTransform(states.transform);
}
// Apply the view
if (shaderChanged || m_cache.viewChanged)
applyCurrentView();
// Apply the blend mode
if (states.blendMode != m_cache.lastBlendMode)
applyBlendMode(states.blendMode);
// Apply the texture
Uint64 textureId = states.texture ? states.texture->m_cacheId : 0;
if (shaderChanged || (textureId != m_cache.lastTextureId))
applyTexture(states.texture);
// Apply the shader
// if (states.shader)
// applyShader(states.shader);
// else if (m_defaultShader)
// applyShader(m_defaultShader);
// Unbind any bound vertex buffer
if (m_cache.lastVertexBufferId)
applyVertexBuffer(NULL);
// If we pre-transform the vertices, we must use our internal vertex cache
if (useVertexCache)
{
// ... and if we already used it previously, we don't need to set the pointers again
if (!m_cache.useVertexCache)
vertices = m_cache.vertexCache;
else
vertices = NULL;
}
// Find the OpenGL primitive type
static const GLenum modes[] = {GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN};
GLenum mode = modes[type];
// Setup the pointers to the vertices' components
if (!m_defaultShader)
{
if (vertices) {
#ifdef EMULATION
const char* data = reinterpret_cast<const char*>(vertices);
glCheck(glVertexPointer(3, GL_FLOAT, sizeof(Vertex), data + offsetof(Vertex, position)));
glCheck(glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), data + offsetof(Vertex, color)));
glCheck(glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), data + offsetof(Vertex, texCoords)));
glCheck(glNormalPointer(GL_FLOAT, sizeof(Vertex), data + offsetof(Vertex, normal)));
#else
// Temorary workaround until gl3ds can get VAO gl*Pointer functions working
u32 bufferOffsets[] = {0};
u64 bufferPermutations[] = {0x3210};
u8 bufferAttribCounts[] = {4};
GPU_SetAttributeBuffers(
4, // number of attributes
(u32 *) osConvertVirtToPhys((u32) vertices),
GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 4, GPU_UNSIGNED_BYTE) |
GPU_ATTRIBFMT(2, 2, GPU_FLOAT) | GPU_ATTRIBFMT(3, 3, GPU_FLOAT),
0xFFF << 4, //0b1100
0x3210,
1, //number of buffers
bufferOffsets,
bufferPermutations,
bufferAttribCounts // number of attributes for each buffer
);
#endif
}
// Draw the primitives
glCheck(glDrawArrays(mode, 0, vertexCount));
} else {
Light::addLightsToShader(*m_currentNonLegacyShader);
int vertexLocation = m_currentNonLegacyShader->getVertexAttributeLocation("sf_Vertex");
int colorLocation = m_currentNonLegacyShader->getVertexAttributeLocation("sf_Color");
int texCoordLocation = m_currentNonLegacyShader->getVertexAttributeLocation("sf_MultiTexCoord0");
int normalLocation = m_currentNonLegacyShader->getVertexAttributeLocation("sf_Normal");
const char* data = reinterpret_cast<const char*>(vertices);
if (vertexLocation >= 0) {
glCheck(glEnableVertexAttribArray(vertexLocation));
glCheck(glVertexAttribPointer(vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), data + offsetof(Vertex, position)));
}
if (colorLocation >= 0) {
glCheck(glEnableVertexAttribArray(colorLocation));
glCheck(glVertexAttribPointer(colorLocation, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), data + offsetof(Vertex, color)));
}
if (texCoordLocation >= 0) {
glCheck(glEnableVertexAttribArray(texCoordLocation));
glCheck(glVertexAttribPointer(texCoordLocation, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), data + offsetof(Vertex, texCoords)));
}
if (normalLocation >= 0) {
glCheck(glEnableVertexAttribArray(normalLocation));
glCheck(glVertexAttribPointer(normalLocation, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), data + offsetof(Vertex, normal)));
}
// Draw the primitives
glCheck(glDrawArrays(mode, 0, vertexCount));
if (vertexLocation >= 0)
glCheck(glDisableVertexAttribArray(vertexLocation));
if (colorLocation >= 0)
glCheck(glDisableVertexAttribArray(colorLocation));
if (texCoordLocation >= 0)
glCheck(glDisableVertexAttribArray(texCoordLocation));
if (normalLocation >= 0)
glCheck(glDisableVertexAttribArray(normalLocation));
}
// Unbind the shader, if any was bound in legacy mode
// if (states.shader && !m_defaultShader)
// applyShader(NULL);
// if (m_defaultShader)
// {
// m_currentNonLegacyShader->endParameterBlock();
//
// if (states.shader)
// states.shader->warnMissing(previousShaderWarnSetting);
//
// m_lastNonLegacyShader = m_currentNonLegacyShader;
// m_currentNonLegacyShader = NULL;
// }
// Update the cache
m_cache.useVertexCache = useVertexCache;
}
}
////////////////////////////////////////////////////////////
void RenderTarget::pushGLStates()
{
if (activate(true))
{
#ifdef CPP3DS_DEBUG
// make sure that the user didn't leave an unchecked OpenGL error
GLenum error = glGetError();
if (error != GL_NO_ERROR)
{
err() << "OpenGL error (" << error << ") detected in user code, "
<< "you should check for errors with glGetError()"
<< std::endl;
}
#endif
glCheck(glPushAttrib(GL_ALL_ATTRIB_BITS));
if (!m_defaultShader)
{
glCheck(glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS));
glCheck(glMatrixMode(GL_MODELVIEW));
glCheck(glPushMatrix());
glCheck(glMatrixMode(GL_PROJECTION));
glCheck(glPushMatrix());
glCheck(glMatrixMode(GL_TEXTURE));
glCheck(glPushMatrix());
}
}
resetGLStates();
}
////////////////////////////////////////////////////////////
void RenderTarget::popGLStates()
{
if (activate(true))
{
if (m_defaultShader)
applyShader(NULL);
if (!m_defaultShader)
{
glCheck(glMatrixMode(GL_PROJECTION));
glCheck(glPopMatrix());
glCheck(glMatrixMode(GL_MODELVIEW));
glCheck(glPopMatrix());
glCheck(glMatrixMode(GL_TEXTURE));
glCheck(glPopMatrix());
glCheck(glPopClientAttrib());
}
glCheck(glPopAttrib());
}
}
////////////////////////////////////////////////////////////
void RenderTarget::resetGLStates()
{
// Check here to make sure a context change does not happen after activate(true)
bool shaderAvailable = Shader::isAvailable();
if (activate(true))
{
// Make sure that the texture unit which is active is the number 0
if (GLEXT_multitexture)
{
glCheck(GLEXT_glClientActiveTexture(GLEXT_GL_TEXTURE0));
glCheck(GLEXT_glActiveTexture(GLEXT_GL_TEXTURE0));
}
// Define the default OpenGL states
glCheck(glDisable(GL_LIGHTING));
if(!m_depthTest)
glCheck(glDisable(GL_DEPTH_TEST));
glCheck(glDisable(GL_ALPHA_TEST));
glCheck(glEnable(GL_CULL_FACE));
glCheck(glEnable(GL_BLEND));
glCheck(glMatrixMode(GL_MODELVIEW));
glCheck(glDepthFunc(GL_GEQUAL));
glCheck(glClearDepth(0.f));
glCheck(glDepthRangef(1.f, 0.f));
if (!m_defaultShader)
{
glCheck(glEnable(GL_TEXTURE_2D));
glCheck(glEnable(GL_COLOR_MATERIAL));
glCheck(glEnable(GL_NORMALIZE));
glCheck(glMatrixMode(GL_MODELVIEW));
glCheck(glEnableClientState(GL_VERTEX_ARRAY));
glCheck(glEnableClientState(GL_COLOR_ARRAY));
glCheck(glEnableClientState(GL_TEXTURE_COORD_ARRAY));
glCheck(glEnableClientState(GL_NORMAL_ARRAY));
}
glCheck(glPolygonMode(GL_FRONT_AND_BACK, GL_FILL));
m_cache.glStatesSet = true;
// Apply the default SFML states
applyBlendMode(BlendAlpha);
applyTransform(Transform::Identity);
applyTexture(NULL);
if (shaderAvailable)
{
if (!m_defaultShader)
applyShader(NULL);
else
applyShader(m_defaultShader);
}
if (VertexBuffer::isAvailable())
applyVertexBuffer(NULL);
m_cache.useVertexCache = false;
// Set the default view
setView(m_defaultView);
}
}
////////////////////////////////////////////////////////////
void RenderTarget::initialize()
{
// Setup the default and current views
m_defaultView.reset(FloatRect(0, 0, static_cast<float>(getSize().x), static_cast<float>(getSize().y)));
delete m_view;
m_view = new View(m_defaultView);
// Set GL states only on first draw, so that we don't pollute user's states
m_cache.glStatesSet = false;
// Try to set up non-legacy pipeline if available
// setupNonLegacyPipeline();
}
////////////////////////////////////////////////////////////
void RenderTarget::applyCurrentView()
{
// Set the viewport
IntRect viewport = getViewport(*m_view);
if (viewport != m_previousViewport)
{
int top = getSize().y - (viewport.top + viewport.height);
glCheck(glViewport(viewport.left, top, viewport.width, viewport.height));
m_previousViewport = viewport;
}
if (m_defaultShader)
{
const Shader* shader = NULL;
if (m_currentNonLegacyShader)
shader = m_currentNonLegacyShader;
else
shader = m_defaultShader;
shader->setParameter("sf_ProjectionMatrix", m_view->getTransform());
shader->setParameter("sf_ViewMatrix", m_view->getViewTransform());
shader->setParameter("sf_ViewerPosition", m_view->getPosition());
}
else
{
// Set the projection matrix
glCheck(glMatrixMode(GL_PROJECTION));
glCheck(glLoadMatrixf(m_view->getTransform().getMatrix()));
// Go back to model-view mode
glCheck(glMatrixMode(GL_MODELVIEW));
}
m_cache.viewChanged = false;
}
////////////////////////////////////////////////////////////
void RenderTarget::applyBlendMode(const BlendMode& mode)
{
// Apply the blend mode
glCheck(glBlendFuncSeparate(
factorToGlConstant(mode.colorSrcFactor), factorToGlConstant(mode.colorDstFactor),
factorToGlConstant(mode.alphaSrcFactor), factorToGlConstant(mode.alphaDstFactor)));
glCheck(glBlendEquationSeparate(
equationToGlConstant(mode.colorEquation),
equationToGlConstant(mode.alphaEquation)));
m_cache.lastBlendMode = mode;
}
////////////////////////////////////////////////////////////
void RenderTarget::applyTransform(const Transform& transform)
{
if (m_defaultShader)
{
const Shader* shader = NULL;
if (m_currentNonLegacyShader)
shader = m_currentNonLegacyShader;
else
shader = m_defaultShader;
shader->setParameter("sf_ModelMatrix", transform);
const float* modelMatrix = transform.getMatrix();
Transform normalMatrix(modelMatrix[0], modelMatrix[4], modelMatrix[8], 0.f,
modelMatrix[1], modelMatrix[5], modelMatrix[9], 0.f,
modelMatrix[2], modelMatrix[6], modelMatrix[10], 0.f,
0.f, 0.f, 0.f, 1.f);
if (Light::isLightingEnabled())
shader->setParameter("sf_NormalMatrix", normalMatrix.getInverse().getTranspose());
}
else
// No need to call glMatrixMode(GL_MODELVIEW), it is always the
// current mode (for optimization purpose, since it's the most used)
glCheck(glLoadMatrixf((m_view->getViewTransform() * transform).getMatrix()));
}
////////////////////////////////////////////////////////////
void RenderTarget::applyViewTransform()
{
if (!m_defaultShader)
// No need to call glMatrixMode(GL_MODELVIEW), it is always the
// current mode (for optimization purpose, since it's the most used)
glCheck(glLoadMatrixf(m_view->getViewTransform().getMatrix()));
}
////////////////////////////////////////////////////////////
void RenderTarget::applyTexture(const Texture* texture)
{
if (m_defaultShader)
{
const Shader* shader = NULL;
if (m_currentNonLegacyShader)
shader = m_currentNonLegacyShader;
else
shader = m_defaultShader;
float xScale = 1.f;
float yScale = 1.f;
float yFlip = 0.f;
if (texture)
{
// Setup scale factors that convert the range [0 .. size] to [0 .. 1]
xScale = 1.f / texture->m_actualSize.x;
yScale = 1.f / texture->m_actualSize.y;
// If pixels are flipped we must invert the Y axis
if (texture->m_pixelsFlipped)
{
yScale = -yScale;
yFlip = static_cast<float>(texture->m_size.y) / texture->m_actualSize.y;
}
Transform textureMatrix(xScale, 0.f, 0.f, 0.f,
0.f, yScale, 0.f, yFlip,
0.f, 0.f, 1.f, 0.f,
0.f, 0.f, 0.f, 1.f);
shader->setParameter("sf_TextureMatrix", textureMatrix);
shader->setParameter("sf_Texture0", *texture);
shader->setParameter("sf_TextureEnabled", 1);
}
else
shader->setParameter("sf_TextureEnabled", 0);
}
else
Texture::bind(texture, Texture::Pixels);
m_cache.lastTextureId = texture ? texture->m_cacheId : 0;
}
////////////////////////////////////////////////////////////
void RenderTarget::applyShader(const Shader* shader)
{
Shader::bind(shader);
}
////////////////////////////////////////////////////////////