-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathwebgl_rendering_context_base.cc
8363 lines (7582 loc) · 300 KB
/
webgl_rendering_context_base.cc
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
/*
* Copyright (C) 2009 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.h"
#include <memory>
#include <utility>
#include "base/feature_list.h"
#include "base/numerics/checked_math.h"
#include "base/stl_util.h"
#include "build/build_config.h"
#include "gpu/GLES2/gl2extchromium.h"
#include "gpu/command_buffer/client/gles2_interface.h"
#include "gpu/command_buffer/common/capabilities.h"
#include "gpu/config/gpu_feature_info.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/bindings/modules/v8/html_canvas_element_or_offscreen_canvas.h"
#include "third_party/blink/renderer/bindings/modules/v8/webgl_any.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/dactyloscoper.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.h"
#include "third_party/blink/renderer/core/html/canvas/html_canvas_element.h"
#include "third_party/blink/renderer/core/html/canvas/image_data.h"
#include "third_party/blink/renderer/core/html/html_image_element.h"
#include "third_party/blink/renderer/core/html/media/html_video_element.h"
#include "third_party/blink/renderer/core/imagebitmap/image_bitmap.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trials.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/core/svg/graphics/svg_image.h"
#include "third_party/blink/renderer/core/typed_arrays/array_buffer/array_buffer_contents.h"
#include "third_party/blink/renderer/core/typed_arrays/array_buffer_view_helpers.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_typed_array.h"
#include "third_party/blink/renderer/core/typed_arrays/flexible_array_buffer_view.h"
#include "third_party/blink/renderer/modules/webgl/angle_instanced_arrays.h"
#include "third_party/blink/renderer/modules/webgl/ext_blend_min_max.h"
#include "third_party/blink/renderer/modules/webgl/ext_frag_depth.h"
#include "third_party/blink/renderer/modules/webgl/ext_shader_texture_lod.h"
#include "third_party/blink/renderer/modules/webgl/ext_texture_filter_anisotropic.h"
#include "third_party/blink/renderer/modules/webgl/gl_string_query.h"
#include "third_party/blink/renderer/modules/webgl/oes_element_index_uint.h"
#include "third_party/blink/renderer/modules/webgl/oes_standard_derivatives.h"
#include "third_party/blink/renderer/modules/webgl/oes_texture_float.h"
#include "third_party/blink/renderer/modules/webgl/oes_texture_float_linear.h"
#include "third_party/blink/renderer/modules/webgl/oes_texture_half_float.h"
#include "third_party/blink/renderer/modules/webgl/oes_texture_half_float_linear.h"
#include "third_party/blink/renderer/modules/webgl/oes_vertex_array_object.h"
#include "third_party/blink/renderer/modules/webgl/webgl_active_info.h"
#include "third_party/blink/renderer/modules/webgl/webgl_buffer.h"
#include "third_party/blink/renderer/modules/webgl/webgl_compressed_texture_astc.h"
#include "third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc.h"
#include "third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc1.h"
#include "third_party/blink/renderer/modules/webgl/webgl_compressed_texture_pvrtc.h"
#include "third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc.h"
#include "third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc_srgb.h"
#include "third_party/blink/renderer/modules/webgl/webgl_context_attribute_helpers.h"
#include "third_party/blink/renderer/modules/webgl/webgl_context_event.h"
#include "third_party/blink/renderer/modules/webgl/webgl_context_group.h"
#include "third_party/blink/renderer/modules/webgl/webgl_debug_renderer_info.h"
#include "third_party/blink/renderer/modules/webgl/webgl_debug_shaders.h"
#include "third_party/blink/renderer/modules/webgl/webgl_depth_texture.h"
#include "third_party/blink/renderer/modules/webgl/webgl_draw_buffers.h"
#include "third_party/blink/renderer/modules/webgl/webgl_framebuffer.h"
#include "third_party/blink/renderer/modules/webgl/webgl_lose_context.h"
#include "third_party/blink/renderer/modules/webgl/webgl_program.h"
#include "third_party/blink/renderer/modules/webgl/webgl_renderbuffer.h"
#include "third_party/blink/renderer/modules/webgl/webgl_shader.h"
#include "third_party/blink/renderer/modules/webgl/webgl_shader_precision_format.h"
#include "third_party/blink/renderer/modules/webgl/webgl_uniform_location.h"
#include "third_party/blink/renderer/modules/webgl/webgl_vertex_array_object.h"
#include "third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_oes.h"
#include "third_party/blink/renderer/modules/webgl/webgl_video_texture.h"
#include "third_party/blink/renderer/modules/webgl/webgl_video_texture_enum.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_binding_macros.h"
#include "third_party/blink/renderer/platform/geometry/int_size.h"
#include "third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.h"
#include "third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.h"
#include "third_party/blink/renderer/platform/graphics/canvas_resource_provider.h"
#include "third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h"
#include "third_party/blink/renderer/platform/wtf/threading_primitives.h"
namespace blink {
bool WebGLRenderingContextBase::webgl_context_limits_initialized_ = false;
unsigned WebGLRenderingContextBase::max_active_webgl_contexts_ = 0;
unsigned WebGLRenderingContextBase::max_active_webgl_contexts_on_worker_ = 0;
namespace {
constexpr base::TimeDelta kDurationBetweenRestoreAttempts =
base::TimeDelta::FromSeconds(1);
const int kMaxGLErrorsAllowedToConsole = 256;
Mutex& WebGLContextLimitMutex() {
DEFINE_THREAD_SAFE_STATIC_LOCAL(Mutex, mutex, ());
return mutex;
}
using WebGLRenderingContextBaseSet =
HeapHashSet<WeakMember<WebGLRenderingContextBase>>;
WebGLRenderingContextBaseSet& ActiveContexts() {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
ThreadSpecific<Persistent<WebGLRenderingContextBaseSet>>, active_contexts,
());
Persistent<WebGLRenderingContextBaseSet>& active_contexts_persistent =
*active_contexts;
if (!active_contexts_persistent) {
active_contexts_persistent =
MakeGarbageCollected<WebGLRenderingContextBaseSet>();
active_contexts_persistent.RegisterAsStaticReference();
}
return *active_contexts_persistent;
}
using WebGLRenderingContextBaseMap =
HeapHashMap<WeakMember<WebGLRenderingContextBase>, int>;
WebGLRenderingContextBaseMap& ForciblyEvictedContexts() {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
ThreadSpecific<Persistent<WebGLRenderingContextBaseMap>>,
forcibly_evicted_contexts, ());
Persistent<WebGLRenderingContextBaseMap>&
forcibly_evicted_contexts_persistent = *forcibly_evicted_contexts;
if (!forcibly_evicted_contexts_persistent) {
forcibly_evicted_contexts_persistent =
MakeGarbageCollected<WebGLRenderingContextBaseMap>();
forcibly_evicted_contexts_persistent.RegisterAsStaticReference();
}
return *forcibly_evicted_contexts_persistent;
}
} // namespace
ScopedRGBEmulationColorMask::ScopedRGBEmulationColorMask(
WebGLRenderingContextBase* context,
GLboolean* color_mask,
DrawingBuffer* drawing_buffer)
: context_(context),
requires_emulation_(drawing_buffer->RequiresAlphaChannelToBePreserved()) {
if (requires_emulation_) {
context_->active_scoped_rgb_emulation_color_masks_++;
memcpy(color_mask_, color_mask, 4 * sizeof(GLboolean));
context_->ContextGL()->ColorMask(color_mask_[0], color_mask_[1],
color_mask_[2], false);
}
}
ScopedRGBEmulationColorMask::~ScopedRGBEmulationColorMask() {
if (requires_emulation_) {
DCHECK(context_->active_scoped_rgb_emulation_color_masks_);
context_->active_scoped_rgb_emulation_color_masks_--;
context_->ContextGL()->ColorMask(color_mask_[0], color_mask_[1],
color_mask_[2], color_mask_[3]);
}
}
void WebGLRenderingContextBase::InitializeWebGLContextLimits(
WebGraphicsContext3DProvider* context_provider) {
MutexLocker locker(WebGLContextLimitMutex());
if (!webgl_context_limits_initialized_) {
// These do not change over the lifetime of the browser.
auto webgl_preferences = context_provider->GetWebglPreferences();
max_active_webgl_contexts_ = webgl_preferences.max_active_webgl_contexts;
max_active_webgl_contexts_on_worker_ =
webgl_preferences.max_active_webgl_contexts_on_worker;
webgl_context_limits_initialized_ = true;
}
}
unsigned WebGLRenderingContextBase::CurrentMaxGLContexts() {
MutexLocker locker(WebGLContextLimitMutex());
DCHECK(webgl_context_limits_initialized_);
return IsMainThread() ? max_active_webgl_contexts_
: max_active_webgl_contexts_on_worker_;
}
void WebGLRenderingContextBase::ForciblyLoseOldestContext(
const String& reason) {
WebGLRenderingContextBase* candidate = OldestContext();
if (!candidate)
return;
candidate->PrintWarningToConsole(reason);
probe::DidFireWebGLWarning(candidate->canvas());
// This will call deactivateContext once the context has actually been lost.
candidate->ForceLostContext(WebGLRenderingContextBase::kSyntheticLostContext,
WebGLRenderingContextBase::kWhenAvailable);
}
WebGLRenderingContextBase* WebGLRenderingContextBase::OldestContext() {
if (ActiveContexts().IsEmpty())
return nullptr;
WebGLRenderingContextBase* candidate = *(ActiveContexts().begin());
DCHECK(!candidate->isContextLost());
for (WebGLRenderingContextBase* context : ActiveContexts()) {
DCHECK(!context->isContextLost());
if (context->ContextGL()->GetLastFlushIdCHROMIUM() <
candidate->ContextGL()->GetLastFlushIdCHROMIUM()) {
candidate = context;
}
}
return candidate;
}
WebGLRenderingContextBase* WebGLRenderingContextBase::OldestEvictedContext() {
if (ForciblyEvictedContexts().IsEmpty())
return nullptr;
WebGLRenderingContextBase* candidate = nullptr;
int generation = -1;
for (WebGLRenderingContextBase* context : ForciblyEvictedContexts().Keys()) {
if (!candidate || ForciblyEvictedContexts().at(context) < generation) {
candidate = context;
generation = ForciblyEvictedContexts().at(context);
}
}
return candidate;
}
void WebGLRenderingContextBase::ActivateContext(
WebGLRenderingContextBase* context) {
unsigned max_gl_contexts = CurrentMaxGLContexts();
unsigned removed_contexts = 0;
while (ActiveContexts().size() >= max_gl_contexts &&
removed_contexts < max_gl_contexts) {
ForciblyLoseOldestContext(
"WARNING: Too many active WebGL contexts. Oldest context will be "
"lost.");
removed_contexts++;
}
DCHECK(!context->isContextLost());
ActiveContexts().insert(context);
}
void WebGLRenderingContextBase::DeactivateContext(
WebGLRenderingContextBase* context) {
ActiveContexts().erase(context);
}
void WebGLRenderingContextBase::AddToEvictedList(
WebGLRenderingContextBase* context) {
static int generation = 0;
ForciblyEvictedContexts().Set(context, generation++);
}
void WebGLRenderingContextBase::RemoveFromEvictedList(
WebGLRenderingContextBase* context) {
ForciblyEvictedContexts().erase(context);
}
void WebGLRenderingContextBase::RestoreEvictedContext(
WebGLRenderingContextBase* context) {
// These two sets keep weak references to their contexts;
// verify that the GC already removed the |context| entries.
DCHECK(!ForciblyEvictedContexts().Contains(context));
DCHECK(!ActiveContexts().Contains(context));
unsigned max_gl_contexts = CurrentMaxGLContexts();
// Try to re-enable the oldest inactive contexts.
while (ActiveContexts().size() < max_gl_contexts &&
ForciblyEvictedContexts().size()) {
WebGLRenderingContextBase* evicted_context = OldestEvictedContext();
if (!evicted_context->restore_allowed_) {
ForciblyEvictedContexts().erase(evicted_context);
continue;
}
IntSize desired_size = DrawingBuffer::AdjustSize(
evicted_context->ClampedCanvasSize(), IntSize(),
evicted_context->max_texture_size_);
// If there's room in the pixel budget for this context, restore it.
if (!desired_size.IsEmpty()) {
ForciblyEvictedContexts().erase(evicted_context);
evicted_context->ForceRestoreContext();
}
break;
}
}
namespace {
GLint Clamp(GLint value, GLint min, GLint max) {
if (value < min)
value = min;
if (value > max)
value = max;
return value;
}
// Strips comments from shader text. This allows non-ASCII characters
// to be used in comments without potentially breaking OpenGL
// implementations not expecting characters outside the GLSL ES set.
class StripComments {
public:
StripComments(const String& str)
: parse_state_(kBeginningOfLine),
source_string_(str),
length_(str.length()),
position_(0) {
Parse();
}
String Result() { return builder_.ToString(); }
private:
bool HasMoreCharacters() const { return (position_ < length_); }
void Parse() {
while (HasMoreCharacters()) {
Process(Current());
// process() might advance the position.
if (HasMoreCharacters())
Advance();
}
}
void Process(UChar);
bool Peek(UChar& character) const {
if (position_ + 1 >= length_)
return false;
character = source_string_[position_ + 1];
return true;
}
UChar Current() {
SECURITY_DCHECK(position_ < length_);
return source_string_[position_];
}
void Advance() { ++position_; }
static bool IsNewline(UChar character) {
// Don't attempt to canonicalize newline related characters.
return (character == '\n' || character == '\r');
}
void Emit(UChar character) { builder_.Append(character); }
enum ParseState {
// Have not seen an ASCII non-whitespace character yet on
// this line. Possible that we might see a preprocessor
// directive.
kBeginningOfLine,
// Have seen at least one ASCII non-whitespace character
// on this line.
kMiddleOfLine,
// Handling a preprocessor directive. Passes through all
// characters up to the end of the line. Disables comment
// processing.
kInPreprocessorDirective,
// Handling a single-line comment. The comment text is
// replaced with a single space.
kInSingleLineComment,
// Handling a multi-line comment. Newlines are passed
// through to preserve line numbers.
kInMultiLineComment
};
ParseState parse_state_;
String source_string_;
unsigned length_;
unsigned position_;
StringBuilder builder_;
};
void StripComments::Process(UChar c) {
if (IsNewline(c)) {
// No matter what state we are in, pass through newlines
// so we preserve line numbers.
Emit(c);
if (parse_state_ != kInMultiLineComment)
parse_state_ = kBeginningOfLine;
return;
}
UChar temp = 0;
switch (parse_state_) {
case kBeginningOfLine:
if (WTF::IsASCIISpace(c)) {
Emit(c);
break;
}
if (c == '#') {
parse_state_ = kInPreprocessorDirective;
Emit(c);
break;
}
// Transition to normal state and re-handle character.
parse_state_ = kMiddleOfLine;
Process(c);
break;
case kMiddleOfLine:
case kInPreprocessorDirective:
if (c == '/' && Peek(temp)) {
if (temp == '/') {
parse_state_ = kInSingleLineComment;
Emit(' ');
Advance();
break;
}
if (temp == '*') {
parse_state_ = kInMultiLineComment;
// Emit the comment start in case the user has
// an unclosed comment and we want to later
// signal an error.
Emit('/');
Emit('*');
Advance();
break;
}
}
Emit(c);
break;
case kInSingleLineComment:
// Line-continuation characters are processed before comment processing.
// Advance string if a new line character is immediately behind
// line-continuation character.
if (c == '\\') {
if (Peek(temp) && IsNewline(temp))
Advance();
}
// The newline code at the top of this function takes care
// of resetting our state when we get out of the
// single-line comment. Swallow all other characters.
break;
case kInMultiLineComment:
if (c == '*' && Peek(temp) && temp == '/') {
Emit('*');
Emit('/');
parse_state_ = kMiddleOfLine;
Advance();
break;
}
// Swallow all other characters. Unclear whether we may
// want or need to just emit a space per character to try
// to preserve column numbers for debugging purposes.
break;
}
}
static bool g_should_fail_context_creation_for_testing = false;
} // namespace
class ScopedTexture2DRestorer {
STACK_ALLOCATED();
public:
explicit ScopedTexture2DRestorer(WebGLRenderingContextBase* context)
: context_(context) {}
~ScopedTexture2DRestorer() { context_->RestoreCurrentTexture2D(); }
private:
WebGLRenderingContextBase* context_;
};
class ScopedFramebufferRestorer {
STACK_ALLOCATED();
public:
explicit ScopedFramebufferRestorer(WebGLRenderingContextBase* context)
: context_(context) {}
~ScopedFramebufferRestorer() { context_->RestoreCurrentFramebuffer(); }
private:
WebGLRenderingContextBase* context_;
};
class ScopedUnpackParametersResetRestore {
STACK_ALLOCATED();
public:
explicit ScopedUnpackParametersResetRestore(
WebGLRenderingContextBase* context,
bool enabled = true)
: context_(context), enabled_(enabled) {
if (enabled)
context_->ResetUnpackParameters();
}
~ScopedUnpackParametersResetRestore() {
if (enabled_)
context_->RestoreUnpackParameters();
}
private:
WebGLRenderingContextBase* context_;
bool enabled_;
};
static void FormatWebGLStatusString(const StringView& gl_info,
const StringView& info_string,
StringBuilder& builder) {
if (info_string.IsEmpty())
return;
builder.Append(", ");
builder.Append(gl_info);
builder.Append(" = ");
builder.Append(info_string);
}
static String ExtractWebGLContextCreationError(
const Platform::GraphicsInfo& info) {
StringBuilder builder;
builder.Append("Could not create a WebGL context");
FormatWebGLStatusString(
"VENDOR",
info.vendor_id ? String::Format("0x%04x", info.vendor_id) : "0xffff",
builder);
FormatWebGLStatusString(
"DEVICE",
info.device_id ? String::Format("0x%04x", info.device_id) : "0xffff",
builder);
FormatWebGLStatusString("GL_VENDOR", info.vendor_info, builder);
FormatWebGLStatusString("GL_RENDERER", info.renderer_info, builder);
FormatWebGLStatusString("GL_VERSION", info.driver_version, builder);
FormatWebGLStatusString("Sandboxed", info.sandboxed ? "yes" : "no", builder);
FormatWebGLStatusString("Optimus", info.optimus ? "yes" : "no", builder);
FormatWebGLStatusString("AMD switchable", info.amd_switchable ? "yes" : "no",
builder);
FormatWebGLStatusString(
"Reset notification strategy",
String::Format("0x%04x", info.reset_notification_strategy).Utf8().c_str(),
builder);
FormatWebGLStatusString("ErrorMessage", info.error_message.Utf8().c_str(),
builder);
builder.Append('.');
return builder.ToString();
}
struct ContextProviderCreationInfo {
// Inputs.
Platform::ContextAttributes context_attributes;
Platform::GraphicsInfo* gl_info;
KURL url;
// Outputs.
std::unique_ptr<WebGraphicsContext3DProvider> created_context_provider;
bool* using_gpu_compositing;
};
static void CreateContextProviderOnMainThread(
ContextProviderCreationInfo* creation_info,
base::WaitableEvent* waitable_event) {
DCHECK(IsMainThread());
// Ask for gpu compositing mode when making the context. The context will be
// lost if the mode changes.
*creation_info->using_gpu_compositing =
!Platform::Current()->IsGpuCompositingDisabled();
creation_info->created_context_provider =
Platform::Current()->CreateOffscreenGraphicsContext3DProvider(
creation_info->context_attributes, creation_info->url,
creation_info->gl_info);
waitable_event->Signal();
}
static std::unique_ptr<WebGraphicsContext3DProvider>
CreateContextProviderOnWorkerThread(
Platform::ContextAttributes context_attributes,
Platform::GraphicsInfo* gl_info,
bool* using_gpu_compositing,
const KURL& url) {
base::WaitableEvent waitable_event;
ContextProviderCreationInfo creation_info;
creation_info.context_attributes = context_attributes;
creation_info.gl_info = gl_info;
creation_info.url = url.Copy();
creation_info.using_gpu_compositing = using_gpu_compositing;
scoped_refptr<base::SingleThreadTaskRunner> task_runner =
Thread::MainThread()->GetTaskRunner();
PostCrossThreadTask(
*task_runner, FROM_HERE,
CrossThreadBindOnce(&CreateContextProviderOnMainThread,
CrossThreadUnretained(&creation_info),
CrossThreadUnretained(&waitable_event)));
waitable_event.Wait();
return std::move(creation_info.created_context_provider);
}
bool WebGLRenderingContextBase::SupportOwnOffscreenSurface(
ExecutionContext* execution_context) {
// Using an own offscreen surface disables virtualized contexts, and this
// doesn't currently work properly, see https://crbug.com/691102.
// TODO(https://crbug.com/791755): Remove this function and related code once
// the replacement is ready.
return false;
}
std::unique_ptr<WebGraphicsContext3DProvider>
WebGLRenderingContextBase::CreateContextProviderInternal(
CanvasRenderingContextHost* host,
const CanvasContextCreationAttributesCore& attributes,
Platform::ContextType context_type,
bool* using_gpu_compositing) {
DCHECK(host);
ExecutionContext* execution_context = host->GetTopExecutionContext();
DCHECK(execution_context);
Platform::ContextAttributes context_attributes = ToPlatformContextAttributes(
attributes, context_type, SupportOwnOffscreenSurface(execution_context));
Platform::GraphicsInfo gl_info;
std::unique_ptr<WebGraphicsContext3DProvider> context_provider;
const auto& url = execution_context->Url();
if (IsMainThread()) {
// Ask for gpu compositing mode when making the context. The context will be
// lost if the mode changes.
*using_gpu_compositing = !Platform::Current()->IsGpuCompositingDisabled();
context_provider =
Platform::Current()->CreateOffscreenGraphicsContext3DProvider(
context_attributes, url, &gl_info);
} else {
context_provider = CreateContextProviderOnWorkerThread(
context_attributes, &gl_info, using_gpu_compositing, url);
}
if (context_provider && !context_provider->BindToCurrentThread()) {
context_provider = nullptr;
gl_info.error_message =
String("bindToCurrentThread failed: " + String(gl_info.error_message));
}
if (!context_provider || g_should_fail_context_creation_for_testing) {
g_should_fail_context_creation_for_testing = false;
host->HostDispatchEvent(
WebGLContextEvent::Create(event_type_names::kWebglcontextcreationerror,
ExtractWebGLContextCreationError(gl_info)));
return nullptr;
}
gpu::gles2::GLES2Interface* gl = context_provider->ContextGL();
if (!String(gl->GetString(GL_EXTENSIONS))
.Contains("GL_OES_packed_depth_stencil")) {
host->HostDispatchEvent(WebGLContextEvent::Create(
event_type_names::kWebglcontextcreationerror,
"OES_packed_depth_stencil support is required."));
return nullptr;
}
return context_provider;
}
std::unique_ptr<WebGraphicsContext3DProvider>
WebGLRenderingContextBase::CreateWebGraphicsContext3DProvider(
CanvasRenderingContextHost* host,
const CanvasContextCreationAttributesCore& attributes,
Platform::ContextType context_type,
bool* using_gpu_compositing) {
// The host might block creation of a new WebGL context despite the
// page settings; in particular, if WebGL contexts were lost one or
// more times via the GL_ARB_robustness extension.
if (host->IsWebGLBlocked()) {
host->SetContextCreationWasBlocked();
host->HostDispatchEvent(WebGLContextEvent::Create(
event_type_names::kWebglcontextcreationerror,
"Web page caused context loss and was blocked"));
return nullptr;
}
if ((context_type == Platform::kWebGL1ContextType &&
!host->IsWebGL1Enabled()) ||
(context_type == Platform::kWebGL2ContextType &&
!host->IsWebGL2Enabled()) ||
(context_type == Platform::kWebGL2ComputeContextType &&
!host->IsWebGL2Enabled())) {
host->HostDispatchEvent(WebGLContextEvent::Create(
event_type_names::kWebglcontextcreationerror,
"disabled by enterprise policy or commandline switch"));
return nullptr;
}
return CreateContextProviderInternal(host, attributes, context_type,
using_gpu_compositing);
}
void WebGLRenderingContextBase::ForceNextWebGLContextCreationToFail() {
g_should_fail_context_creation_for_testing = true;
}
ImageBitmap* WebGLRenderingContextBase::TransferToImageBitmapBase(
ScriptState* script_state) {
WebFeature feature = WebFeature::kOffscreenCanvasTransferToImageBitmapWebGL;
UseCounter::Count(ExecutionContext::From(script_state), feature);
return MakeGarbageCollected<ImageBitmap>(
GetDrawingBuffer()->TransferToStaticBitmapImage());
}
void WebGLRenderingContextBase::commit() {
if (!GetDrawingBuffer() || (Host() && Host()->IsOffscreenCanvas()))
return;
int width = GetDrawingBuffer()->Size().Width();
int height = GetDrawingBuffer()->Size().Height();
if (PaintRenderingResultsToCanvas(kBackBuffer)) {
if (Host()->GetOrCreateCanvasResourceProvider(kPreferAcceleration)) {
Host()->Commit(Host()->ResourceProvider()->ProduceCanvasResource(),
SkIRect::MakeWH(width, height));
}
}
MarkLayerComposited();
}
scoped_refptr<StaticBitmapImage> WebGLRenderingContextBase::GetImage(
AccelerationHint hint) {
if (!GetDrawingBuffer())
return nullptr;
ScopedFramebufferRestorer fbo_restorer(this);
GetDrawingBuffer()->ResolveAndBindForReadAndDraw();
// Use the drawing buffer size here instead of the canvas size to ensure that
// sizing is consistent. The forced downsizing logic in Reshape() can lead to
// the drawing buffer being smaller than the canvas size.
// See https://crbug.com/845742.
IntSize size = GetDrawingBuffer()->Size();
// Since we are grabbing a snapshot that is not for compositing, we use a
// custom resource provider. This avoids consuming compositing-specific
// resources (e.g. GpuMemoryBuffer)
std::unique_ptr<CanvasResourceProvider> resource_provider =
CanvasResourceProvider::Create(
size,
CanvasResourceProvider::ResourceUsage::kAcceleratedResourceUsage,
SharedGpuContext::ContextProviderWrapper(), 0,
GetDrawingBuffer()->FilterQuality(), ColorParams(),
CanvasResourceProvider::kDefaultPresentationMode,
nullptr /* canvas_resource_dispatcher */, is_origin_top_left_);
if (!resource_provider || !resource_provider->IsValid())
return nullptr;
if (!CopyRenderingResultsFromDrawingBuffer(resource_provider.get(),
kBackBuffer)) {
// copyRenderingResultsFromDrawingBuffer is expected to always succeed
// because we've explicitly created an Accelerated surface and have
// already validated it.
NOTREACHED();
return nullptr;
}
return resource_provider->Snapshot();
}
ScriptPromise WebGLRenderingContextBase::makeXRCompatible(
ScriptState* script_state,
ExceptionState& exception_state) {
if (isContextLost()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
"Context lost.");
return ScriptPromise();
}
if (xr_compatible_) {
// Returns a script promise resolved with undefined.
return ScriptPromise::CastUndefined(script_state);
}
if (ContextCreatedOnXRCompatibleAdapter()) {
xr_compatible_ = true;
return ScriptPromise::CastUndefined(script_state);
}
// TODO(http://crbug.com/876140) Trigger context loss and recreate on
// compatible GPU.
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"Context is not compatible. Switching not yet implemented.");
return ScriptPromise();
}
bool WebGLRenderingContextBase::IsXRCompatible() {
return xr_compatible_;
}
void WebGLRenderingContextBase::
UpdateNumberOfUserAllocatedMultisampledRenderbuffers(int delta) {
DCHECK(delta >= -1 && delta <= 1);
number_of_user_allocated_multisampled_renderbuffers_ += delta;
DCHECK_GE(number_of_user_allocated_multisampled_renderbuffers_, 0);
}
namespace {
// Exposed by GL_ANGLE_depth_texture
static const GLenum kSupportedInternalFormatsOESDepthTex[] = {
GL_DEPTH_COMPONENT, GL_DEPTH_STENCIL,
};
// Exposed by GL_EXT_sRGB
static const GLenum kSupportedInternalFormatsEXTsRGB[] = {
GL_SRGB, GL_SRGB_ALPHA_EXT,
};
// ES3 enums supported by both CopyTexImage and TexImage.
static const GLenum kSupportedInternalFormatsES3[] = {
GL_R8, GL_RG8, GL_RGB565, GL_RGB8, GL_RGBA4,
GL_RGB5_A1, GL_RGBA8, GL_RGB10_A2, GL_RGB10_A2UI, GL_SRGB8,
GL_SRGB8_ALPHA8, GL_R8I, GL_R8UI, GL_R16I, GL_R16UI,
GL_R32I, GL_R32UI, GL_RG8I, GL_RG8UI, GL_RG16I,
GL_RG16UI, GL_RG32I, GL_RG32UI, GL_RGBA8I, GL_RGBA8UI,
GL_RGBA16I, GL_RGBA16UI, GL_RGBA32I, GL_RGBA32UI, GL_RGB32I,
GL_RGB32UI, GL_RGB8I, GL_RGB8UI, GL_RGB16I, GL_RGB16UI,
};
// ES3 enums only supported by TexImage
static const GLenum kSupportedInternalFormatsTexImageES3[] = {
GL_R8_SNORM,
GL_R16F,
GL_R32F,
GL_RG8_SNORM,
GL_RG16F,
GL_RG32F,
GL_RGB8_SNORM,
GL_R11F_G11F_B10F,
GL_RGB9_E5,
GL_RGB16F,
GL_RGB32F,
GL_RGBA8_SNORM,
GL_RGBA16F,
GL_RGBA32F,
GL_DEPTH_COMPONENT16,
GL_DEPTH_COMPONENT24,
GL_DEPTH_COMPONENT32F,
GL_DEPTH24_STENCIL8,
GL_DEPTH32F_STENCIL8,
};
// Exposed by EXT_texture_norm16
static constexpr GLenum kSupportedInternalFormatsEXTTextureNorm16ES3[] = {
GL_R16_EXT, GL_RG16_EXT, GL_RGB16_EXT,
GL_RGBA16_EXT, GL_R16_SNORM_EXT, GL_RG16_SNORM_EXT,
GL_RGB16_SNORM_EXT, GL_RGBA16_SNORM_EXT};
static constexpr GLenum kSupportedFormatsEXTTextureNorm16ES3[] = {GL_RED,
GL_RG};
static constexpr GLenum kSupportedTypesEXTTextureNorm16ES3[] = {
GL_SHORT, GL_UNSIGNED_SHORT};
// Exposed by EXT_color_buffer_float
static const GLenum kSupportedInternalFormatsCopyTexImageFloatES3[] = {
GL_R16F, GL_R32F, GL_RG16F, GL_RG32F, GL_RGB16F,
GL_RGB32F, GL_RGBA16F, GL_RGBA32F, GL_R11F_G11F_B10F};
// ES3 enums supported by TexImageSource
static const GLenum kSupportedInternalFormatsTexImageSourceES3[] = {
GL_R8, GL_R16F, GL_R32F, GL_R8UI, GL_RG8,
GL_RG16F, GL_RG32F, GL_RG8UI, GL_RGB8, GL_SRGB8,
GL_RGB565, GL_R11F_G11F_B10F, GL_RGB9_E5, GL_RGB16F, GL_RGB32F,
GL_RGB8UI, GL_RGBA8, GL_SRGB8_ALPHA8, GL_RGB5_A1, GL_RGBA4,
GL_RGBA16F, GL_RGBA32F, GL_RGBA8UI, GL_RGB10_A2,
};
// ES2 enums
// Internalformat must equal format in ES2.
static const GLenum kSupportedFormatsES2[] = {
GL_RGB, GL_RGBA, GL_LUMINANCE_ALPHA, GL_LUMINANCE, GL_ALPHA,
};
// Exposed by GL_ANGLE_depth_texture
static const GLenum kSupportedFormatsOESDepthTex[] = {
GL_DEPTH_COMPONENT, GL_DEPTH_STENCIL,
};
// Exposed by GL_EXT_sRGB
static const GLenum kSupportedFormatsEXTsRGB[] = {
GL_SRGB, GL_SRGB_ALPHA_EXT,
};
// ES3 enums
static const GLenum kSupportedFormatsES3[] = {
GL_RED, GL_RED_INTEGER, GL_RG,
GL_RG_INTEGER, GL_RGB, GL_RGB_INTEGER,
GL_RGBA, GL_RGBA_INTEGER, GL_DEPTH_COMPONENT,
GL_DEPTH_STENCIL,
};
// ES3 enums supported by TexImageSource
static const GLenum kSupportedFormatsTexImageSourceES3[] = {
GL_RED, GL_RED_INTEGER, GL_RG, GL_RG_INTEGER,
GL_RGB, GL_RGB_INTEGER, GL_RGBA, GL_RGBA_INTEGER,
};
// ES2 enums
static const GLenum kSupportedTypesES2[] = {
GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_4_4_4_4,
GL_UNSIGNED_SHORT_5_5_5_1,
};
// Exposed by GL_OES_texture_float
static const GLenum kSupportedTypesOESTexFloat[] = {
GL_FLOAT,
};
// Exposed by GL_OES_texture_half_float
static const GLenum kSupportedTypesOESTexHalfFloat[] = {
GL_HALF_FLOAT_OES,
};
// Exposed by GL_ANGLE_depth_texture
static const GLenum kSupportedTypesOESDepthTex[] = {
GL_UNSIGNED_SHORT, GL_UNSIGNED_INT, GL_UNSIGNED_INT_24_8,
};
// ES3 enums
static const GLenum kSupportedTypesES3[] = {
GL_BYTE,
GL_UNSIGNED_SHORT,
GL_SHORT,
GL_UNSIGNED_INT,
GL_INT,
GL_HALF_FLOAT,
GL_FLOAT,
GL_UNSIGNED_INT_2_10_10_10_REV,
GL_UNSIGNED_INT_10F_11F_11F_REV,
GL_UNSIGNED_INT_5_9_9_9_REV,
GL_UNSIGNED_INT_24_8,
GL_FLOAT_32_UNSIGNED_INT_24_8_REV,
};
// ES3 enums supported by TexImageSource
static const GLenum kSupportedTypesTexImageSourceES3[] = {
GL_HALF_FLOAT, GL_FLOAT, GL_UNSIGNED_INT_10F_11F_11F_REV,
GL_UNSIGNED_INT_2_10_10_10_REV,
};
} // namespace
WebGLRenderingContextBase::WebGLRenderingContextBase(
CanvasRenderingContextHost* host,
std::unique_ptr<WebGraphicsContext3DProvider> context_provider,
bool using_gpu_compositing,
const CanvasContextCreationAttributesCore& requested_attributes,
Platform::ContextType version)
: WebGLRenderingContextBase(
host,
host->GetTopExecutionContext()->GetTaskRunner(TaskType::kWebGL),
std::move(context_provider),
using_gpu_compositing,
requested_attributes,
version) {}
WebGLRenderingContextBase::WebGLRenderingContextBase(
CanvasRenderingContextHost* host,
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
std::unique_ptr<WebGraphicsContext3DProvider> context_provider,
bool using_gpu_compositing,
const CanvasContextCreationAttributesCore& requested_attributes,
Platform::ContextType context_type)