Bug 1787199 [wpt PR 35620] - Add tests for `VisibilityStateEntry`, a=testonly
[gecko.git] / dom / canvas / WebGLBuffer.cpp
blob54a2f21c839d2adea0e06666d1d0c5bd1d5bae1e
1 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "WebGLBuffer.h"
8 #include "GLContext.h"
9 #include "mozilla/dom/WebGLRenderingContextBinding.h"
10 #include "WebGLContext.h"
12 namespace mozilla {
14 WebGLBuffer::WebGLBuffer(WebGLContext* webgl, GLuint buf)
15 : WebGLContextBoundObject(webgl), mGLName(buf) {}
17 WebGLBuffer::~WebGLBuffer() {
18 mByteLength = 0;
19 mFetchInvalidator.InvalidateCaches();
21 mIndexCache.reset();
22 mIndexRanges.clear();
24 if (!mContext) return;
25 mContext->gl->fDeleteBuffers(1, &mGLName);
28 void WebGLBuffer::SetContentAfterBind(GLenum target) {
29 if (mContent != Kind::Undefined) return;
31 switch (target) {
32 case LOCAL_GL_ELEMENT_ARRAY_BUFFER:
33 mContent = Kind::ElementArray;
34 break;
36 case LOCAL_GL_ARRAY_BUFFER:
37 case LOCAL_GL_PIXEL_PACK_BUFFER:
38 case LOCAL_GL_PIXEL_UNPACK_BUFFER:
39 case LOCAL_GL_UNIFORM_BUFFER:
40 case LOCAL_GL_TRANSFORM_FEEDBACK_BUFFER:
41 case LOCAL_GL_COPY_READ_BUFFER:
42 case LOCAL_GL_COPY_WRITE_BUFFER:
43 mContent = Kind::OtherData;
44 break;
46 default:
47 MOZ_CRASH("GFX: invalid target");
51 ////////////////////////////////////////
53 static bool ValidateBufferUsageEnum(WebGLContext* webgl, GLenum usage) {
54 switch (usage) {
55 case LOCAL_GL_STREAM_DRAW:
56 case LOCAL_GL_STATIC_DRAW:
57 case LOCAL_GL_DYNAMIC_DRAW:
58 return true;
60 case LOCAL_GL_DYNAMIC_COPY:
61 case LOCAL_GL_DYNAMIC_READ:
62 case LOCAL_GL_STATIC_COPY:
63 case LOCAL_GL_STATIC_READ:
64 case LOCAL_GL_STREAM_COPY:
65 case LOCAL_GL_STREAM_READ:
66 if (MOZ_LIKELY(webgl->IsWebGL2())) return true;
67 break;
69 default:
70 break;
73 webgl->ErrorInvalidEnumInfo("usage", usage);
74 return false;
77 void WebGLBuffer::BufferData(const GLenum target, const uint64_t size,
78 const void* const maybeData, const GLenum usage) {
79 // The driver knows only GLsizeiptr, which is int32_t on 32bit!
80 bool sizeValid = CheckedInt<GLsizeiptr>(size).isValid();
82 if (mContext->gl->WorkAroundDriverBugs()) {
83 // Bug 790879
84 #if defined(XP_MACOSX) || defined(MOZ_WIDGET_GTK)
85 sizeValid &= CheckedInt<int32_t>(size).isValid();
86 #endif
88 // Bug 1610383
89 if (mContext->gl->IsANGLE()) {
90 // While ANGLE seems to support up to `unsigned int`, UINT32_MAX-4 causes
91 // GL_OUT_OF_MEMORY in glFlush??
92 sizeValid &= CheckedInt<int32_t>(size).isValid();
96 if (!sizeValid) {
97 mContext->ErrorOutOfMemory("Size not valid for platform: %" PRIu64, size);
98 return;
101 // -
103 if (!ValidateBufferUsageEnum(mContext, usage)) return;
105 const void* uploadData = maybeData;
106 UniqueBuffer maybeCalloc;
107 if (!uploadData) {
108 maybeCalloc = UniqueBuffer::Take(calloc(1, AssertedCast<size_t>(size)));
109 if (!maybeCalloc) {
110 mContext->ErrorOutOfMemory("Failed to alloc zeros.");
111 return;
113 uploadData = maybeCalloc.get();
115 MOZ_ASSERT(uploadData);
117 UniqueBuffer newIndexCache;
118 const bool needsIndexCache = mContext->mNeedsIndexValidation ||
119 mContext->mMaybeNeedsLegacyVertexAttrib0Handling;
120 if (target == LOCAL_GL_ELEMENT_ARRAY_BUFFER && needsIndexCache) {
121 newIndexCache = UniqueBuffer::Take(malloc(AssertedCast<size_t>(size)));
122 if (!newIndexCache) {
123 mContext->ErrorOutOfMemory("Failed to alloc index cache.");
124 return;
126 // memcpy out of SharedArrayBuffers can be racey, and should generally use
127 // memcpySafeWhenRacy. But it's safe here:
128 // * We only memcpy in one place.
129 // * We only read out of the single copy, and only after copying.
130 // * If we get data value corruption from racing read-during-write, that's
131 // fine.
132 memcpy(newIndexCache.get(), uploadData, size);
133 uploadData = newIndexCache.get();
136 const auto& gl = mContext->gl;
137 const ScopedLazyBind lazyBind(gl, target, this);
139 const bool sizeChanges = (size != ByteLength());
140 if (sizeChanges) {
141 gl::GLContext::LocalErrorScope errorScope(*gl);
142 gl->fBufferData(target, size, uploadData, usage);
143 const auto error = errorScope.GetError();
145 if (error) {
146 MOZ_ASSERT(error == LOCAL_GL_OUT_OF_MEMORY);
147 mContext->ErrorOutOfMemory("Error from driver: 0x%04x", error);
149 // Truncate
150 mByteLength = 0;
151 mFetchInvalidator.InvalidateCaches();
152 mIndexCache.reset();
153 return;
155 } else {
156 gl->fBufferData(target, size, uploadData, usage);
159 mContext->OnDataAllocCall();
161 mUsage = usage;
162 mByteLength = size;
163 mFetchInvalidator.InvalidateCaches();
164 mIndexCache = std::move(newIndexCache);
166 if (mIndexCache) {
167 if (!mIndexRanges.empty()) {
168 mContext->GeneratePerfWarning("[%p] Invalidating %u ranges.", this,
169 uint32_t(mIndexRanges.size()));
170 mIndexRanges.clear();
174 ResetLastUpdateFenceId();
177 void WebGLBuffer::BufferSubData(GLenum target, uint64_t dstByteOffset,
178 uint64_t dataLen, const void* data) const {
179 if (!ValidateRange(dstByteOffset, dataLen)) return;
181 if (!CheckedInt<GLintptr>(dstByteOffset).isValid() ||
182 !CheckedInt<GLsizeiptr>(dataLen).isValid())
183 return mContext->ErrorOutOfMemory("offset or size too large for platform.");
185 ////
187 if (!dataLen) return; // With validation successful, nothing else to do.
189 const void* uploadData = data;
190 if (mIndexCache) {
191 const auto cachedDataBegin = (uint8_t*)mIndexCache.get() + dstByteOffset;
192 memcpy(cachedDataBegin, data, dataLen);
193 uploadData = cachedDataBegin;
195 InvalidateCacheRange(dstByteOffset, dataLen);
198 ////
200 const auto& gl = mContext->gl;
201 const ScopedLazyBind lazyBind(gl, target, this);
203 gl->fBufferSubData(target, dstByteOffset, dataLen, uploadData);
205 ResetLastUpdateFenceId();
208 bool WebGLBuffer::ValidateRange(size_t byteOffset, size_t byteLen) const {
209 auto availLength = mByteLength;
210 if (byteOffset > availLength) {
211 mContext->ErrorInvalidValue("Offset passes the end of the buffer.");
212 return false;
214 availLength -= byteOffset;
216 if (byteLen > availLength) {
217 mContext->ErrorInvalidValue("Offset+size passes the end of the buffer.");
218 return false;
221 return true;
224 ////////////////////////////////////////
226 static uint8_t IndexByteSizeByType(GLenum type) {
227 switch (type) {
228 case LOCAL_GL_UNSIGNED_BYTE:
229 return 1;
230 case LOCAL_GL_UNSIGNED_SHORT:
231 return 2;
232 case LOCAL_GL_UNSIGNED_INT:
233 return 4;
234 default:
235 MOZ_CRASH();
239 void WebGLBuffer::InvalidateCacheRange(uint64_t byteOffset,
240 uint64_t byteLength) const {
241 MOZ_ASSERT(mIndexCache);
243 std::vector<IndexRange> invalids;
244 const uint64_t updateBegin = byteOffset;
245 const uint64_t updateEnd = updateBegin + byteLength;
246 for (const auto& cur : mIndexRanges) {
247 const auto& range = cur.first;
248 const auto& indexByteSize = IndexByteSizeByType(range.type);
249 const auto rangeBegin = range.byteOffset * indexByteSize;
250 const auto rangeEnd =
251 rangeBegin + uint64_t(range.indexCount) * indexByteSize;
252 if (rangeBegin >= updateEnd || rangeEnd <= updateBegin) continue;
253 invalids.push_back(range);
256 if (!invalids.empty()) {
257 mContext->GeneratePerfWarning("[%p] Invalidating %u/%u ranges.", this,
258 uint32_t(invalids.size()),
259 uint32_t(mIndexRanges.size()));
261 for (const auto& cur : invalids) {
262 mIndexRanges.erase(cur);
267 size_t WebGLBuffer::SizeOfIncludingThis(
268 mozilla::MallocSizeOf mallocSizeOf) const {
269 size_t size = mallocSizeOf(this);
270 if (mIndexCache) {
271 size += mByteLength;
273 return size;
276 template <typename T>
277 static Maybe<uint32_t> MaxForRange(const void* const start,
278 const uint32_t count,
279 const Maybe<uint32_t>& untypedIgnoredVal) {
280 const Maybe<T> ignoredVal =
281 (untypedIgnoredVal ? Some(T(untypedIgnoredVal.value())) : Nothing());
282 Maybe<uint32_t> maxVal;
284 auto itr = (const T*)start;
285 const auto end = itr + count;
287 for (; itr != end; ++itr) {
288 const auto& val = *itr;
289 if (ignoredVal && val == ignoredVal.value()) continue;
291 if (maxVal && val <= maxVal.value()) continue;
293 maxVal = Some(val);
296 return maxVal;
299 static const uint32_t kMaxIndexRanges = 256;
301 Maybe<uint32_t> WebGLBuffer::GetIndexedFetchMaxVert(
302 const GLenum type, const uint64_t byteOffset,
303 const uint32_t indexCount) const {
304 if (!mIndexCache) return Nothing();
306 const IndexRange range = {type, byteOffset, indexCount};
307 auto res = mIndexRanges.insert({range, Nothing()});
308 if (mIndexRanges.size() > kMaxIndexRanges) {
309 mContext->GeneratePerfWarning(
310 "[%p] Clearing mIndexRanges after exceeding %u.", this,
311 kMaxIndexRanges);
312 mIndexRanges.clear();
313 res = mIndexRanges.insert({range, Nothing()});
316 const auto& itr = res.first;
317 const auto& didInsert = res.second;
319 auto& maxFetchIndex = itr->second;
320 if (didInsert) {
321 const auto& data = mIndexCache.get();
323 const auto start = (const uint8_t*)data + byteOffset;
325 Maybe<uint32_t> ignoredVal;
326 if (mContext->IsWebGL2()) {
327 ignoredVal = Some(UINT32_MAX);
330 switch (type) {
331 case LOCAL_GL_UNSIGNED_BYTE:
332 maxFetchIndex = MaxForRange<uint8_t>(start, indexCount, ignoredVal);
333 break;
334 case LOCAL_GL_UNSIGNED_SHORT:
335 maxFetchIndex = MaxForRange<uint16_t>(start, indexCount, ignoredVal);
336 break;
337 case LOCAL_GL_UNSIGNED_INT:
338 maxFetchIndex = MaxForRange<uint32_t>(start, indexCount, ignoredVal);
339 break;
340 default:
341 MOZ_CRASH();
343 const auto displayMaxVertIndex =
344 maxFetchIndex ? int64_t(maxFetchIndex.value()) : -1;
345 mContext->GeneratePerfWarning("[%p] New range #%u: (0x%04x, %" PRIu64
346 ", %u):"
347 " %" PRIi64,
348 this, uint32_t(mIndexRanges.size()),
349 range.type, range.byteOffset,
350 range.indexCount, displayMaxVertIndex);
353 return maxFetchIndex;
356 ////
358 bool WebGLBuffer::ValidateCanBindToTarget(GLenum target) {
359 /* https://www.khronos.org/registry/webgl/specs/latest/2.0/#5.1
361 * In the WebGL 2 API, buffers have their WebGL buffer type
362 * initially set to undefined. Calling bindBuffer, bindBufferRange
363 * or bindBufferBase with the target argument set to any buffer
364 * binding point except COPY_READ_BUFFER or COPY_WRITE_BUFFER will
365 * then set the WebGL buffer type of the buffer being bound
366 * according to the table above.
368 * Any call to one of these functions which attempts to bind a
369 * WebGLBuffer that has the element array WebGL buffer type to a
370 * binding point that falls under other data, or bind a
371 * WebGLBuffer which has the other data WebGL buffer type to
372 * ELEMENT_ARRAY_BUFFER will generate an INVALID_OPERATION error,
373 * and the state of the binding point will remain untouched.
376 if (mContent == WebGLBuffer::Kind::Undefined) return true;
378 switch (target) {
379 case LOCAL_GL_COPY_READ_BUFFER:
380 case LOCAL_GL_COPY_WRITE_BUFFER:
381 return true;
383 case LOCAL_GL_ELEMENT_ARRAY_BUFFER:
384 if (mContent == WebGLBuffer::Kind::ElementArray) return true;
385 break;
387 case LOCAL_GL_ARRAY_BUFFER:
388 case LOCAL_GL_PIXEL_PACK_BUFFER:
389 case LOCAL_GL_PIXEL_UNPACK_BUFFER:
390 case LOCAL_GL_TRANSFORM_FEEDBACK_BUFFER:
391 case LOCAL_GL_UNIFORM_BUFFER:
392 if (mContent == WebGLBuffer::Kind::OtherData) return true;
393 break;
395 default:
396 MOZ_CRASH();
399 const auto dataType =
400 (mContent == WebGLBuffer::Kind::OtherData) ? "other" : "element";
401 mContext->ErrorInvalidOperation("Buffer already contains %s data.", dataType);
402 return false;
405 void WebGLBuffer::ResetLastUpdateFenceId() const {
406 mLastUpdateFenceId = mContext->mNextFenceId;
409 } // namespace mozilla