draw_validate.c revision b8e80941
1/*
2 * Mesa 3-D graphics library
3 *
4 * Copyright (C) 1999-2007  Brian Paul   All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included
14 * in all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22 * OTHER DEALINGS IN THE SOFTWARE.
23 */
24
25#include <stdbool.h>
26#include "glheader.h"
27#include "draw_validate.h"
28#include "arrayobj.h"
29#include "bufferobj.h"
30#include "context.h"
31#include "imports.h"
32#include "mtypes.h"
33#include "pipelineobj.h"
34#include "enums.h"
35#include "state.h"
36#include "transformfeedback.h"
37#include "uniforms.h"
38#include "program/prog_print.h"
39
40
41static bool
42check_blend_func_error(struct gl_context *ctx)
43{
44   /* The ARB_blend_func_extended spec's ERRORS section says:
45    *
46    *    "The error INVALID_OPERATION is generated by Begin or any procedure
47    *     that implicitly calls Begin if any draw buffer has a blend function
48    *     requiring the second color input (SRC1_COLOR, ONE_MINUS_SRC1_COLOR,
49    *     SRC1_ALPHA or ONE_MINUS_SRC1_ALPHA), and a framebuffer is bound that
50    *     has more than the value of MAX_DUAL_SOURCE_DRAW_BUFFERS-1 active
51    *     color attachements."
52    */
53   for (unsigned i = ctx->Const.MaxDualSourceDrawBuffers;
54	i < ctx->DrawBuffer->_NumColorDrawBuffers;
55	i++) {
56      if (ctx->Color.Blend[i]._UsesDualSrc) {
57	 _mesa_error(ctx, GL_INVALID_OPERATION,
58		     "dual source blend on illegal attachment");
59	 return false;
60      }
61   }
62
63   if (ctx->Color.BlendEnabled && ctx->Color._AdvancedBlendMode) {
64      /* The KHR_blend_equation_advanced spec says:
65       *
66       *    "If any non-NONE draw buffer uses a blend equation found in table
67       *     X.1 or X.2, the error INVALID_OPERATION is generated by Begin or
68       *     any operation that implicitly calls Begin (such as DrawElements)
69       *     if:
70       *
71       *       * the draw buffer for color output zero selects multiple color
72       *         buffers (e.g., FRONT_AND_BACK in the default framebuffer); or
73       *
74       *       * the draw buffer for any other color output is not NONE."
75       */
76      if (ctx->DrawBuffer->ColorDrawBuffer[0] == GL_FRONT_AND_BACK) {
77         _mesa_error(ctx, GL_INVALID_OPERATION,
78                     "advanced blending is active and draw buffer for color "
79                     "output zero selects multiple color buffers");
80         return false;
81      }
82
83      for (unsigned i = 1; i < ctx->DrawBuffer->_NumColorDrawBuffers; i++) {
84         if (ctx->DrawBuffer->ColorDrawBuffer[i] != GL_NONE) {
85            _mesa_error(ctx, GL_INVALID_OPERATION,
86                        "advanced blending is active with multiple color "
87                        "draw buffers");
88            return false;
89         }
90      }
91
92      /* The KHR_blend_equation_advanced spec says:
93       *
94       *    "Advanced blending equations require the use of a fragment shader
95       *     with a matching "blend_support" layout qualifier.  If the current
96       *     blend equation is found in table X.1 or X.2, and the active
97       *     fragment shader does not include the layout qualifier matching
98       *     the blend equation or "blend_support_all_equations", the error
99       *     INVALID_OPERATION is generated [...]"
100       */
101      const struct gl_program *prog = ctx->FragmentProgram._Current;
102      const GLbitfield blend_support = !prog ? 0 : prog->sh.fs.BlendSupport;
103
104      if ((blend_support & ctx->Color._AdvancedBlendMode) == 0) {
105         _mesa_error(ctx, GL_INVALID_OPERATION,
106                     "fragment shader does not allow advanced blending mode "
107                     "(%s)",
108                      _mesa_enum_to_string(ctx->Color.Blend[0].EquationRGB));
109      }
110   }
111
112   return true;
113}
114
115
116/**
117 * Prior to drawing anything with glBegin, glDrawArrays, etc. this function
118 * is called to see if it's valid to render.  This involves checking that
119 * the current shader is valid and the framebuffer is complete.
120 * It also check the current pipeline object is valid if any.
121 * If an error is detected it'll be recorded here.
122 * \return GL_TRUE if OK to render, GL_FALSE if not
123 */
124GLboolean
125_mesa_valid_to_render(struct gl_context *ctx, const char *where)
126{
127   /* This depends on having up to date derived state (shaders) */
128   if (ctx->NewState)
129      _mesa_update_state(ctx);
130
131   if (ctx->API == API_OPENGL_COMPAT) {
132      /* Any shader stages that are not supplied by the GLSL shader and have
133       * assembly shaders enabled must now be validated.
134       */
135      if (!ctx->_Shader->CurrentProgram[MESA_SHADER_VERTEX] &&
136          ctx->VertexProgram.Enabled &&
137          !_mesa_arb_vertex_program_enabled(ctx)) {
138         _mesa_error(ctx, GL_INVALID_OPERATION,
139                     "%s(vertex program not valid)", where);
140         return GL_FALSE;
141      }
142
143      if (!ctx->_Shader->CurrentProgram[MESA_SHADER_FRAGMENT]) {
144         if (ctx->FragmentProgram.Enabled &&
145             !_mesa_arb_fragment_program_enabled(ctx)) {
146            _mesa_error(ctx, GL_INVALID_OPERATION,
147                        "%s(fragment program not valid)", where);
148            return GL_FALSE;
149         }
150
151         /* If drawing to integer-valued color buffers, there must be an
152          * active fragment shader (GL_EXT_texture_integer).
153          */
154         if (ctx->DrawBuffer && ctx->DrawBuffer->_IntegerBuffers) {
155            _mesa_error(ctx, GL_INVALID_OPERATION,
156                        "%s(integer format but no fragment shader)", where);
157            return GL_FALSE;
158         }
159      }
160   }
161
162   /* A pipeline object is bound */
163   if (ctx->_Shader->Name && !ctx->_Shader->Validated) {
164      if (!_mesa_validate_program_pipeline(ctx, ctx->_Shader)) {
165         _mesa_error(ctx, GL_INVALID_OPERATION,
166                     "glValidateProgramPipeline failed to validate the "
167                     "pipeline");
168         return GL_FALSE;
169      }
170   }
171
172   /* If a program is active and SSO not in use, check if validation of
173    * samplers succeeded for the active program. */
174   if (ctx->_Shader->ActiveProgram && ctx->_Shader != ctx->Pipeline.Current) {
175      char errMsg[100];
176      if (!_mesa_sampler_uniforms_are_valid(ctx->_Shader->ActiveProgram,
177                                            errMsg, 100)) {
178         _mesa_error(ctx, GL_INVALID_OPERATION, "%s", errMsg);
179         return GL_FALSE;
180      }
181   }
182
183   if (ctx->DrawBuffer->_Status != GL_FRAMEBUFFER_COMPLETE_EXT) {
184      _mesa_error(ctx, GL_INVALID_FRAMEBUFFER_OPERATION_EXT,
185                  "%s(incomplete framebuffer)", where);
186      return GL_FALSE;
187   }
188
189   if (!check_blend_func_error(ctx)) {
190      return GL_FALSE;
191   }
192
193   /* From the GL_NV_fill_rectangle spec:
194    *
195    * "An INVALID_OPERATION error is generated by Begin or any Draw command if
196    *  only one of the front and back polygon mode is FILL_RECTANGLE_NV."
197    */
198   if ((ctx->Polygon.FrontMode == GL_FILL_RECTANGLE_NV) !=
199       (ctx->Polygon.BackMode == GL_FILL_RECTANGLE_NV)) {
200      _mesa_error(ctx, GL_INVALID_OPERATION,
201                  "GL_FILL_RECTANGLE_NV must be used as both front/back "
202                  "polygon mode or neither");
203      return GL_FALSE;
204   }
205
206#ifdef DEBUG
207   if (ctx->_Shader->Flags & GLSL_LOG) {
208      struct gl_program **prog = ctx->_Shader->CurrentProgram;
209
210      for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
211	 if (prog[i] == NULL || prog[i]->_Used)
212	    continue;
213
214	 /* This is the first time this shader is being used.
215	  * Append shader's constants/uniforms to log file.
216	  *
217	  * Only log data for the program target that matches the shader
218	  * target.  It's possible to have a program bound to the vertex
219	  * shader target that also supplied a fragment shader.  If that
220	  * program isn't also bound to the fragment shader target we don't
221	  * want to log its fragment data.
222	  */
223	 _mesa_append_uniforms_to_file(prog[i]);
224      }
225
226      for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
227	 if (prog[i] != NULL)
228	    prog[i]->_Used = GL_TRUE;
229      }
230   }
231#endif
232
233   return GL_TRUE;
234}
235
236
237/**
238 * Check if OK to draw arrays/elements.
239 */
240static bool
241check_valid_to_render(struct gl_context *ctx, const char *function)
242{
243   if (!_mesa_valid_to_render(ctx, function)) {
244      return false;
245   }
246
247   /* Section 6.3.2 from the GL 4.5:
248    * "Any GL command which attempts to read from, write to, or change
249    *  the state of a buffer object may generate an INVALID_OPERATION error if
250    *  all or part of the buffer object is mapped ... However, only commands
251    *  which explicitly describe this error are required to do so. If an error
252    *  is not generated, such commands will have undefined results and may
253    *  result in GL interruption or termination."
254    *
255    * Only some buffer API functions require INVALID_OPERATION with mapped
256    * buffers. No other functions list such an error, thus it's not required
257    * to report INVALID_OPERATION for draw calls with mapped buffers.
258    */
259   if (!ctx->Const.AllowMappedBuffersDuringExecution &&
260       !_mesa_all_buffers_are_unmapped(ctx->Array.VAO)) {
261      _mesa_error(ctx, GL_INVALID_OPERATION,
262                  "%s(vertex buffers are mapped)", function);
263      return false;
264   }
265
266   /* Section 11.2 (Tessellation) of the ES 3.2 spec says:
267    *
268    * "An INVALID_OPERATION error is generated by any command that
269    *  transfers vertices to the GL if the current program state has
270    *  one but not both of a tessellation control shader and tessellation
271    *  evaluation shader."
272    *
273    * The OpenGL spec argues that this is allowed because a tess ctrl shader
274    * without a tess eval shader can be used with transform feedback.
275    * However, glBeginTransformFeedback doesn't allow GL_PATCHES and
276    * therefore doesn't allow tessellation.
277    *
278    * Further investigation showed that this is indeed a spec bug and
279    * a tess ctrl shader without a tess eval shader shouldn't have been
280    * allowed, because there is no API in GL 4.0 that can make use this
281    * to produce something useful.
282    *
283    * Also, all vendors except one don't support a tess ctrl shader without
284    * a tess eval shader anyway.
285    */
286   if (ctx->TessCtrlProgram._Current && !ctx->TessEvalProgram._Current) {
287      _mesa_error(ctx, GL_INVALID_OPERATION,
288                  "%s(tess eval shader is missing)", function);
289      return false;
290   }
291
292   switch (ctx->API) {
293   case API_OPENGLES2:
294      /* Section 11.2 (Tessellation) of the ES 3.2 spec says:
295       *
296       * "An INVALID_OPERATION error is generated by any command that
297       *  transfers vertices to the GL if the current program state has
298       *  one but not both of a tessellation control shader and tessellation
299       *  evaluation shader."
300       */
301      if (_mesa_is_gles3(ctx) &&
302          ctx->TessEvalProgram._Current && !ctx->TessCtrlProgram._Current) {
303         _mesa_error(ctx, GL_INVALID_OPERATION,
304                     "%s(tess ctrl shader is missing)", function);
305         return false;
306      }
307
308      /* From GL_EXT_color_buffer_float:
309       *
310       *     "Blending applies only if the color buffer has a fixed-point or
311       *     or floating-point format. If the color buffer has an integer
312       *     format, proceed to the next operation.  Furthermore, an
313       *     INVALID_OPERATION error is generated by DrawArrays and the other
314       *     drawing commands defined in section 2.8.3 (10.5 in ES 3.1) if
315       *     blending is enabled (see below) and any draw buffer has 32-bit
316       *     floating-point format components."
317       *
318       * However GL_EXT_float_blend removes this text.
319       */
320      if (!ctx->Extensions.EXT_float_blend &&
321          (ctx->DrawBuffer->_FP32Buffers & ctx->Color.BlendEnabled)) {
322         _mesa_error(ctx, GL_INVALID_OPERATION,
323                     "%s(32-bit float output + blending)", function);
324         return false;
325      }
326      break;
327
328   case API_OPENGL_CORE:
329      /* Section 10.4 (Drawing Commands Using Vertex Arrays) of the OpenGL 4.5
330       * Core Profile spec says:
331       *
332       *     "An INVALID_OPERATION error is generated if no vertex array
333       *     object is bound (see section 10.3.1)."
334       */
335      if (ctx->Array.VAO == ctx->Array.DefaultVAO) {
336         _mesa_error(ctx, GL_INVALID_OPERATION, "%s(no VAO bound)", function);
337         return false;
338      }
339      break;
340
341   case API_OPENGLES:
342   case API_OPENGL_COMPAT:
343      break;
344
345   default:
346      unreachable("Invalid API value in check_valid_to_render()");
347   }
348
349   return true;
350}
351
352
353/**
354 * Is 'mode' a valid value for glBegin(), glDrawArrays(), glDrawElements(),
355 * etc?  The set of legal values depends on whether geometry shaders/programs
356 * are supported.
357 * Note: This may be called during display list compilation.
358 */
359bool
360_mesa_is_valid_prim_mode(const struct gl_context *ctx, GLenum mode)
361{
362   /* The overwhelmingly common case is (mode <= GL_TRIANGLE_FAN).  Test that
363    * first and exit.  You would think that a switch-statement would be the
364    * right approach, but at least GCC 4.7.2 generates some pretty dire code
365    * for the common case.
366    */
367   if (likely(mode <= GL_TRIANGLE_FAN))
368      return true;
369
370   if (mode <= GL_POLYGON)
371      return (ctx->API == API_OPENGL_COMPAT);
372
373   if (mode <= GL_TRIANGLE_STRIP_ADJACENCY)
374      return _mesa_has_geometry_shaders(ctx);
375
376   if (mode == GL_PATCHES)
377      return _mesa_has_tessellation(ctx);
378
379   return false;
380}
381
382
383/**
384 * Is 'mode' a valid value for glBegin(), glDrawArrays(), glDrawElements(),
385 * etc?  Also, do additional checking related to transformation feedback.
386 * Note: this function cannot be called during glNewList(GL_COMPILE) because
387 * this code depends on current transform feedback state.
388 * Also, do additional checking related to tessellation shaders.
389 */
390GLboolean
391_mesa_valid_prim_mode(struct gl_context *ctx, GLenum mode, const char *name)
392{
393   bool valid_enum = _mesa_is_valid_prim_mode(ctx, mode);
394
395   if (!valid_enum) {
396      _mesa_error(ctx, GL_INVALID_ENUM, "%s(mode=%x)", name, mode);
397      return GL_FALSE;
398   }
399
400   /* From the OpenGL 4.5 specification, section 11.3.1:
401    *
402    * The error INVALID_OPERATION is generated if Begin, or any command that
403    * implicitly calls Begin, is called when a geometry shader is active and:
404    *
405    * * the input primitive type of the current geometry shader is
406    *   POINTS and <mode> is not POINTS,
407    *
408    * * the input primitive type of the current geometry shader is
409    *   LINES and <mode> is not LINES, LINE_STRIP, or LINE_LOOP,
410    *
411    * * the input primitive type of the current geometry shader is
412    *   TRIANGLES and <mode> is not TRIANGLES, TRIANGLE_STRIP or
413    *   TRIANGLE_FAN,
414    *
415    * * the input primitive type of the current geometry shader is
416    *   LINES_ADJACENCY_ARB and <mode> is not LINES_ADJACENCY_ARB or
417    *   LINE_STRIP_ADJACENCY_ARB, or
418    *
419    * * the input primitive type of the current geometry shader is
420    *   TRIANGLES_ADJACENCY_ARB and <mode> is not
421    *   TRIANGLES_ADJACENCY_ARB or TRIANGLE_STRIP_ADJACENCY_ARB.
422    *
423    * The GL spec doesn't mention any interaction with tessellation, which
424    * is clearly a spec bug. The same rule should apply, but instead of
425    * the draw primitive mode, the tessellation evaluation shader primitive
426    * mode should be used for the checking.
427   */
428   if (ctx->_Shader->CurrentProgram[MESA_SHADER_GEOMETRY]) {
429      const GLenum geom_mode =
430         ctx->_Shader->CurrentProgram[MESA_SHADER_GEOMETRY]->
431            info.gs.input_primitive;
432      struct gl_program *tes =
433         ctx->_Shader->CurrentProgram[MESA_SHADER_TESS_EVAL];
434      GLenum mode_before_gs = mode;
435
436      if (tes) {
437         if (tes->info.tess.point_mode)
438            mode_before_gs = GL_POINTS;
439         else if (tes->info.tess.primitive_mode == GL_ISOLINES)
440            mode_before_gs = GL_LINES;
441         else
442            /* the GL_QUADS mode generates triangles too */
443            mode_before_gs = GL_TRIANGLES;
444      }
445
446      switch (mode_before_gs) {
447      case GL_POINTS:
448         valid_enum = (geom_mode == GL_POINTS);
449         break;
450      case GL_LINES:
451      case GL_LINE_LOOP:
452      case GL_LINE_STRIP:
453         valid_enum = (geom_mode == GL_LINES);
454         break;
455      case GL_TRIANGLES:
456      case GL_TRIANGLE_STRIP:
457      case GL_TRIANGLE_FAN:
458         valid_enum = (geom_mode == GL_TRIANGLES);
459         break;
460      case GL_QUADS:
461      case GL_QUAD_STRIP:
462      case GL_POLYGON:
463         valid_enum = false;
464         break;
465      case GL_LINES_ADJACENCY:
466      case GL_LINE_STRIP_ADJACENCY:
467         valid_enum = (geom_mode == GL_LINES_ADJACENCY);
468         break;
469      case GL_TRIANGLES_ADJACENCY:
470      case GL_TRIANGLE_STRIP_ADJACENCY:
471         valid_enum = (geom_mode == GL_TRIANGLES_ADJACENCY);
472         break;
473      default:
474         valid_enum = false;
475         break;
476      }
477      if (!valid_enum) {
478         _mesa_error(ctx, GL_INVALID_OPERATION,
479                     "%s(mode=%s vs geometry shader input %s)",
480                     name,
481                     _mesa_lookup_prim_by_nr(mode_before_gs),
482                     _mesa_lookup_prim_by_nr(geom_mode));
483         return GL_FALSE;
484      }
485   }
486
487   /* From the OpenGL 4.0 (Core Profile) spec (section 2.12):
488    *
489    *     "Tessellation operates only on patch primitives. If tessellation is
490    *      active, any command that transfers vertices to the GL will
491    *      generate an INVALID_OPERATION error if the primitive mode is not
492    *      PATCHES.
493    *      Patch primitives are not supported by pipeline stages below the
494    *      tessellation evaluation shader. If there is no active program
495    *      object or the active program object does not contain a tessellation
496    *      evaluation shader, the error INVALID_OPERATION is generated by any
497    *      command that transfers vertices to the GL if the primitive mode is
498    *      PATCHES."
499    *
500    */
501   if (ctx->_Shader->CurrentProgram[MESA_SHADER_TESS_EVAL] ||
502       ctx->_Shader->CurrentProgram[MESA_SHADER_TESS_CTRL]) {
503      if (mode != GL_PATCHES) {
504         _mesa_error(ctx, GL_INVALID_OPERATION,
505                     "only GL_PATCHES valid with tessellation");
506         return GL_FALSE;
507      }
508   }
509   else {
510      if (mode == GL_PATCHES) {
511         _mesa_error(ctx, GL_INVALID_OPERATION,
512                     "GL_PATCHES only valid with tessellation");
513         return GL_FALSE;
514      }
515   }
516
517   /* From the GL_EXT_transform_feedback spec:
518    *
519    *     "The error INVALID_OPERATION is generated if Begin, or any command
520    *      that performs an explicit Begin, is called when:
521    *
522    *      * a geometry shader is not active and <mode> does not match the
523    *        allowed begin modes for the current transform feedback state as
524    *        given by table X.1.
525    *
526    *      * a geometry shader is active and the output primitive type of the
527    *        geometry shader does not match the allowed begin modes for the
528    *        current transform feedback state as given by table X.1.
529    *
530    */
531   if (_mesa_is_xfb_active_and_unpaused(ctx)) {
532      GLboolean pass = GL_TRUE;
533
534      if(ctx->_Shader->CurrentProgram[MESA_SHADER_GEOMETRY]) {
535         switch (ctx->_Shader->CurrentProgram[MESA_SHADER_GEOMETRY]->
536                    info.gs.output_primitive) {
537         case GL_POINTS:
538            pass = ctx->TransformFeedback.Mode == GL_POINTS;
539            break;
540         case GL_LINE_STRIP:
541            pass = ctx->TransformFeedback.Mode == GL_LINES;
542            break;
543         case GL_TRIANGLE_STRIP:
544            pass = ctx->TransformFeedback.Mode == GL_TRIANGLES;
545            break;
546         default:
547            pass = GL_FALSE;
548         }
549      }
550      else if (ctx->_Shader->CurrentProgram[MESA_SHADER_TESS_EVAL]) {
551         struct gl_program *tes =
552            ctx->_Shader->CurrentProgram[MESA_SHADER_TESS_EVAL];
553         if (tes->info.tess.point_mode)
554            pass = ctx->TransformFeedback.Mode == GL_POINTS;
555         else if (tes->info.tess.primitive_mode == GL_ISOLINES)
556            pass = ctx->TransformFeedback.Mode == GL_LINES;
557         else
558            pass = ctx->TransformFeedback.Mode == GL_TRIANGLES;
559      }
560      else {
561         switch (mode) {
562         case GL_POINTS:
563            pass = ctx->TransformFeedback.Mode == GL_POINTS;
564            break;
565         case GL_LINES:
566         case GL_LINE_STRIP:
567         case GL_LINE_LOOP:
568            pass = ctx->TransformFeedback.Mode == GL_LINES;
569            break;
570         default:
571            pass = ctx->TransformFeedback.Mode == GL_TRIANGLES;
572            break;
573         }
574      }
575      if (!pass) {
576         _mesa_error(ctx, GL_INVALID_OPERATION,
577                         "%s(mode=%s vs transform feedback %s)",
578                         name,
579                         _mesa_lookup_prim_by_nr(mode),
580                         _mesa_lookup_prim_by_nr(ctx->TransformFeedback.Mode));
581         return GL_FALSE;
582      }
583   }
584
585   /* From GL_INTEL_conservative_rasterization spec:
586    *
587    * The conservative rasterization option applies only to polygons with
588    * PolygonMode state set to FILL. Draw requests for polygons with different
589    * PolygonMode setting or for other primitive types (points/lines) generate
590    * INVALID_OPERATION error.
591    */
592   if (ctx->IntelConservativeRasterization) {
593      GLboolean pass = GL_TRUE;
594
595      switch (mode) {
596      case GL_POINTS:
597      case GL_LINES:
598      case GL_LINE_LOOP:
599      case GL_LINE_STRIP:
600      case GL_LINES_ADJACENCY:
601      case GL_LINE_STRIP_ADJACENCY:
602         pass = GL_FALSE;
603         break;
604      case GL_TRIANGLES:
605      case GL_TRIANGLE_STRIP:
606      case GL_TRIANGLE_FAN:
607      case GL_QUADS:
608      case GL_QUAD_STRIP:
609      case GL_POLYGON:
610      case GL_TRIANGLES_ADJACENCY:
611      case GL_TRIANGLE_STRIP_ADJACENCY:
612         if (ctx->Polygon.FrontMode != GL_FILL ||
613             ctx->Polygon.BackMode != GL_FILL)
614            pass = GL_FALSE;
615         break;
616      default:
617         pass = GL_FALSE;
618      }
619      if (!pass) {
620         _mesa_error(ctx, GL_INVALID_OPERATION,
621                     "mode=%s invalid with GL_INTEL_conservative_rasterization",
622                     _mesa_lookup_prim_by_nr(mode));
623         return GL_FALSE;
624      }
625   }
626
627   return GL_TRUE;
628}
629
630/**
631 * Verify that the element type is valid.
632 *
633 * Generates \c GL_INVALID_ENUM and returns \c false if it is not.
634 */
635static bool
636valid_elements_type(struct gl_context *ctx, GLenum type, const char *name)
637{
638   switch (type) {
639   case GL_UNSIGNED_BYTE:
640   case GL_UNSIGNED_SHORT:
641   case GL_UNSIGNED_INT:
642      return true;
643
644   default:
645      _mesa_error(ctx, GL_INVALID_ENUM, "%s(type = %s)", name,
646                  _mesa_enum_to_string(type));
647      return false;
648   }
649}
650
651static bool
652validate_DrawElements_common(struct gl_context *ctx,
653                             GLenum mode, GLsizei count, GLenum type,
654                             const GLvoid *indices,
655                             const char *caller)
656{
657   /* Section 2.14.2 (Transform Feedback Primitive Capture) of the OpenGL ES
658    * 3.1 spec says:
659    *
660    *   The error INVALID_OPERATION is also generated by DrawElements,
661    *   DrawElementsInstanced, and DrawRangeElements while transform feedback
662    *   is active and not paused, regardless of mode.
663    *
664    * The OES_geometry_shader_spec says:
665    *
666    *    Issues:
667    *
668    *    ...
669    *
670    *    (13) Does this extension change how transform feedback operates
671    *    compared to unextended OpenGL ES 3.0 or 3.1?
672    *
673    *    RESOLVED: Yes... Since we no longer require being able to predict how
674    *    much geometry will be generated, we also lift the restriction that
675    *    only DrawArray* commands are supported and also support the
676    *    DrawElements* commands for transform feedback.
677    *
678    * This should also be reflected in the body of the spec, but that appears
679    * to have been overlooked.  The body of the spec only explicitly allows
680    * the indirect versions.
681    */
682   if (_mesa_is_gles3(ctx) &&
683       !_mesa_has_OES_geometry_shader(ctx) &&
684       _mesa_is_xfb_active_and_unpaused(ctx)) {
685      _mesa_error(ctx, GL_INVALID_OPERATION,
686                  "%s(transform feedback active)", caller);
687      return false;
688   }
689
690   if (count < 0) {
691      _mesa_error(ctx, GL_INVALID_VALUE, "%s(count)", caller);
692      return false;
693   }
694
695   if (!_mesa_valid_prim_mode(ctx, mode, caller)) {
696      return false;
697   }
698
699   if (!valid_elements_type(ctx, type, caller))
700      return false;
701
702   if (!check_valid_to_render(ctx, caller))
703      return false;
704
705   return true;
706}
707
708/**
709 * Error checking for glDrawElements().  Includes parameter checking
710 * and VBO bounds checking.
711 * \return GL_TRUE if OK to render, GL_FALSE if error found
712 */
713GLboolean
714_mesa_validate_DrawElements(struct gl_context *ctx,
715                            GLenum mode, GLsizei count, GLenum type,
716                            const GLvoid *indices)
717{
718   return validate_DrawElements_common(ctx, mode, count, type, indices,
719                                       "glDrawElements");
720}
721
722
723/**
724 * Error checking for glMultiDrawElements().  Includes parameter checking
725 * and VBO bounds checking.
726 * \return GL_TRUE if OK to render, GL_FALSE if error found
727 */
728GLboolean
729_mesa_validate_MultiDrawElements(struct gl_context *ctx,
730                                 GLenum mode, const GLsizei *count,
731                                 GLenum type, const GLvoid * const *indices,
732                                 GLsizei primcount)
733{
734   GLsizei i;
735
736   /*
737    * Section 2.3.1 (Errors) of the OpenGL 4.5 (Core Profile) spec says:
738    *
739    *    "If a negative number is provided where an argument of type sizei or
740    *     sizeiptr is specified, an INVALID_VALUE error is generated."
741    *
742    * and in the same section:
743    *
744    *    "In other cases, there are no side effects unless otherwise noted;
745    *     the command which generates the error is ignored so that it has no
746    *     effect on GL state or framebuffer contents."
747    *
748    * Hence, check both primcount and all the count[i].
749    */
750   if (primcount < 0) {
751      _mesa_error(ctx, GL_INVALID_VALUE,
752                  "glMultiDrawElements(primcount=%d)", primcount);
753      return GL_FALSE;
754   }
755
756   for (i = 0; i < primcount; i++) {
757      if (count[i] < 0) {
758         _mesa_error(ctx, GL_INVALID_VALUE,
759                     "glMultiDrawElements(count)" );
760         return GL_FALSE;
761      }
762   }
763
764   if (!_mesa_valid_prim_mode(ctx, mode, "glMultiDrawElements")) {
765      return GL_FALSE;
766   }
767
768   if (!valid_elements_type(ctx, type, "glMultiDrawElements"))
769      return GL_FALSE;
770
771   if (!check_valid_to_render(ctx, "glMultiDrawElements"))
772      return GL_FALSE;
773
774   /* Not using a VBO for indices, so avoid NULL pointer derefs later.
775    */
776   if (!_mesa_is_bufferobj(ctx->Array.VAO->IndexBufferObj)) {
777      for (i = 0; i < primcount; i++) {
778         if (!indices[i])
779            return GL_FALSE;
780      }
781   }
782
783   return GL_TRUE;
784}
785
786
787/**
788 * Error checking for glDrawRangeElements().  Includes parameter checking
789 * and VBO bounds checking.
790 * \return GL_TRUE if OK to render, GL_FALSE if error found
791 */
792GLboolean
793_mesa_validate_DrawRangeElements(struct gl_context *ctx, GLenum mode,
794                                 GLuint start, GLuint end,
795                                 GLsizei count, GLenum type,
796                                 const GLvoid *indices)
797{
798   if (end < start) {
799      _mesa_error(ctx, GL_INVALID_VALUE, "glDrawRangeElements(end<start)");
800      return GL_FALSE;
801   }
802
803   return validate_DrawElements_common(ctx, mode, count, type, indices,
804                                       "glDrawRangeElements");
805}
806
807
808static bool
809need_xfb_remaining_prims_check(const struct gl_context *ctx)
810{
811   /* From the GLES3 specification, section 2.14.2 (Transform Feedback
812    * Primitive Capture):
813    *
814    *   The error INVALID_OPERATION is generated by DrawArrays and
815    *   DrawArraysInstanced if recording the vertices of a primitive to the
816    *   buffer objects being used for transform feedback purposes would result
817    *   in either exceeding the limits of any buffer object’s size, or in
818    *   exceeding the end position offset + size − 1, as set by
819    *   BindBufferRange.
820    *
821    * This is in contrast to the behaviour of desktop GL, where the extra
822    * primitives are silently dropped from the transform feedback buffer.
823    *
824    * This text is removed in ES 3.2, presumably because it's not really
825    * implementable with geometry and tessellation shaders.  In fact,
826    * the OES_geometry_shader spec says:
827    *
828    *    "(13) Does this extension change how transform feedback operates
829    *     compared to unextended OpenGL ES 3.0 or 3.1?
830    *
831    *     RESOLVED: Yes. Because dynamic geometry amplification in a geometry
832    *     shader can make it difficult if not impossible to predict the amount
833    *     of geometry that may be generated in advance of executing the shader,
834    *     the draw-time error for transform feedback buffer overflow conditions
835    *     is removed and replaced with the GL behavior (primitives are not
836    *     written and the corresponding counter is not updated)..."
837    */
838   return _mesa_is_gles3(ctx) && _mesa_is_xfb_active_and_unpaused(ctx) &&
839          !_mesa_has_OES_geometry_shader(ctx) &&
840          !_mesa_has_OES_tessellation_shader(ctx);
841}
842
843
844/**
845 * Figure out the number of transform feedback primitives that will be output
846 * considering the drawing mode, number of vertices, and instance count,
847 * assuming that no geometry shading is done and primitive restart is not
848 * used.
849 *
850 * This is used by driver back-ends in implementing the PRIMITIVES_GENERATED
851 * and TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN queries.  It is also used to
852 * pre-validate draw calls in GLES3 (where draw calls only succeed if there is
853 * enough room in the transform feedback buffer for the result).
854 */
855static size_t
856count_tessellated_primitives(GLenum mode, GLuint count, GLuint num_instances)
857{
858   size_t num_primitives;
859   switch (mode) {
860   case GL_POINTS:
861      num_primitives = count;
862      break;
863   case GL_LINE_STRIP:
864      num_primitives = count >= 2 ? count - 1 : 0;
865      break;
866   case GL_LINE_LOOP:
867      num_primitives = count >= 2 ? count : 0;
868      break;
869   case GL_LINES:
870      num_primitives = count / 2;
871      break;
872   case GL_TRIANGLE_STRIP:
873   case GL_TRIANGLE_FAN:
874   case GL_POLYGON:
875      num_primitives = count >= 3 ? count - 2 : 0;
876      break;
877   case GL_TRIANGLES:
878      num_primitives = count / 3;
879      break;
880   case GL_QUAD_STRIP:
881      num_primitives = count >= 4 ? ((count / 2) - 1) * 2 : 0;
882      break;
883   case GL_QUADS:
884      num_primitives = (count / 4) * 2;
885      break;
886   case GL_LINES_ADJACENCY:
887      num_primitives = count / 4;
888      break;
889   case GL_LINE_STRIP_ADJACENCY:
890      num_primitives = count >= 4 ? count - 3 : 0;
891      break;
892   case GL_TRIANGLES_ADJACENCY:
893      num_primitives = count / 6;
894      break;
895   case GL_TRIANGLE_STRIP_ADJACENCY:
896      num_primitives = count >= 6 ? (count - 4) / 2 : 0;
897      break;
898   default:
899      assert(!"Unexpected primitive type in count_tessellated_primitives");
900      num_primitives = 0;
901      break;
902   }
903   return num_primitives * num_instances;
904}
905
906
907static bool
908validate_draw_arrays(struct gl_context *ctx, const char *func,
909                     GLenum mode, GLsizei count, GLsizei numInstances)
910{
911   if (count < 0) {
912      _mesa_error(ctx, GL_INVALID_VALUE, "%s(count)", func);
913      return false;
914   }
915
916   if (!_mesa_valid_prim_mode(ctx, mode, func))
917      return false;
918
919   if (!check_valid_to_render(ctx, func))
920      return false;
921
922   if (need_xfb_remaining_prims_check(ctx)) {
923      struct gl_transform_feedback_object *xfb_obj
924         = ctx->TransformFeedback.CurrentObject;
925      size_t prim_count = count_tessellated_primitives(mode, count, numInstances);
926      if (xfb_obj->GlesRemainingPrims < prim_count) {
927         _mesa_error(ctx, GL_INVALID_OPERATION,
928                     "%s(exceeds transform feedback size)", func);
929         return false;
930      }
931      xfb_obj->GlesRemainingPrims -= prim_count;
932   }
933
934   if (count == 0)
935      return false;
936
937   return true;
938}
939
940/**
941 * Called from the tnl module to error check the function parameters and
942 * verify that we really can draw something.
943 * \return GL_TRUE if OK to render, GL_FALSE if error found
944 */
945GLboolean
946_mesa_validate_DrawArrays(struct gl_context *ctx, GLenum mode, GLsizei count)
947{
948   return validate_draw_arrays(ctx, "glDrawArrays", mode, count, 1);
949}
950
951
952GLboolean
953_mesa_validate_DrawArraysInstanced(struct gl_context *ctx, GLenum mode, GLint first,
954                                   GLsizei count, GLsizei numInstances)
955{
956   if (first < 0) {
957      _mesa_error(ctx, GL_INVALID_VALUE,
958                  "glDrawArraysInstanced(start=%d)", first);
959      return GL_FALSE;
960   }
961
962   if (numInstances <= 0) {
963      if (numInstances < 0)
964         _mesa_error(ctx, GL_INVALID_VALUE,
965                     "glDrawArraysInstanced(numInstances=%d)", numInstances);
966      return GL_FALSE;
967   }
968
969   return validate_draw_arrays(ctx, "glDrawArraysInstanced", mode, count, 1);
970}
971
972
973/**
974 * Called to error check the function parameters.
975 *
976 * Note that glMultiDrawArrays is not part of GLES, so there's limited scope
977 * for sharing code with the validation of glDrawArrays.
978 */
979bool
980_mesa_validate_MultiDrawArrays(struct gl_context *ctx, GLenum mode,
981                               const GLsizei *count, GLsizei primcount)
982{
983   int i;
984
985   if (!_mesa_valid_prim_mode(ctx, mode, "glMultiDrawArrays"))
986      return false;
987
988   if (!check_valid_to_render(ctx, "glMultiDrawArrays"))
989      return false;
990
991   if (primcount < 0) {
992      _mesa_error(ctx, GL_INVALID_VALUE, "glMultiDrawArrays(primcount=%d)",
993                  primcount);
994      return false;
995   }
996
997   for (i = 0; i < primcount; ++i) {
998      if (count[i] < 0) {
999         _mesa_error(ctx, GL_INVALID_VALUE, "glMultiDrawArrays(count[%d]=%d)",
1000                     i, count[i]);
1001         return false;
1002      }
1003   }
1004
1005   if (need_xfb_remaining_prims_check(ctx)) {
1006      struct gl_transform_feedback_object *xfb_obj
1007         = ctx->TransformFeedback.CurrentObject;
1008      size_t xfb_prim_count = 0;
1009
1010      for (i = 0; i < primcount; ++i)
1011         xfb_prim_count += count_tessellated_primitives(mode, count[i], 1);
1012
1013      if (xfb_obj->GlesRemainingPrims < xfb_prim_count) {
1014         _mesa_error(ctx, GL_INVALID_OPERATION,
1015                     "glMultiDrawArrays(exceeds transform feedback size)");
1016         return false;
1017      }
1018      xfb_obj->GlesRemainingPrims -= xfb_prim_count;
1019   }
1020
1021   return true;
1022}
1023
1024
1025GLboolean
1026_mesa_validate_DrawElementsInstanced(struct gl_context *ctx,
1027                                     GLenum mode, GLsizei count, GLenum type,
1028                                     const GLvoid *indices, GLsizei numInstances)
1029{
1030   if (numInstances < 0) {
1031      _mesa_error(ctx, GL_INVALID_VALUE,
1032                  "glDrawElementsInstanced(numInstances=%d)", numInstances);
1033      return GL_FALSE;
1034   }
1035
1036   return validate_DrawElements_common(ctx, mode, count, type, indices,
1037                                       "glDrawElementsInstanced")
1038      && (numInstances > 0);
1039}
1040
1041
1042GLboolean
1043_mesa_validate_DrawTransformFeedback(struct gl_context *ctx,
1044                                     GLenum mode,
1045                                     struct gl_transform_feedback_object *obj,
1046                                     GLuint stream,
1047                                     GLsizei numInstances)
1048{
1049   if (!_mesa_valid_prim_mode(ctx, mode, "glDrawTransformFeedback*(mode)")) {
1050      return GL_FALSE;
1051   }
1052
1053   if (!obj) {
1054      _mesa_error(ctx, GL_INVALID_VALUE, "glDrawTransformFeedback*(name)");
1055      return GL_FALSE;
1056   }
1057
1058   /* From the GL 4.5 specification, page 429:
1059    * "An INVALID_VALUE error is generated if id is not the name of a
1060    *  transform feedback object."
1061    */
1062   if (!obj->EverBound) {
1063      _mesa_error(ctx, GL_INVALID_VALUE, "glDrawTransformFeedback*(name)");
1064      return GL_FALSE;
1065   }
1066
1067   if (stream >= ctx->Const.MaxVertexStreams) {
1068      _mesa_error(ctx, GL_INVALID_VALUE,
1069                  "glDrawTransformFeedbackStream*(index>=MaxVertexStream)");
1070      return GL_FALSE;
1071   }
1072
1073   if (!obj->EndedAnytime) {
1074      _mesa_error(ctx, GL_INVALID_OPERATION, "glDrawTransformFeedback*");
1075      return GL_FALSE;
1076   }
1077
1078   if (numInstances <= 0) {
1079      if (numInstances < 0)
1080         _mesa_error(ctx, GL_INVALID_VALUE,
1081                     "glDrawTransformFeedback*Instanced(numInstances=%d)",
1082                     numInstances);
1083      return GL_FALSE;
1084   }
1085
1086   if (!check_valid_to_render(ctx, "glDrawTransformFeedback*")) {
1087      return GL_FALSE;
1088   }
1089
1090   return GL_TRUE;
1091}
1092
1093static GLboolean
1094valid_draw_indirect(struct gl_context *ctx,
1095                    GLenum mode, const GLvoid *indirect,
1096                    GLsizei size, const char *name)
1097{
1098   const uint64_t end = (uint64_t) (uintptr_t) indirect + size;
1099
1100   /* OpenGL ES 3.1 spec. section 10.5:
1101    *
1102    *      "DrawArraysIndirect requires that all data sourced for the
1103    *      command, including the DrawArraysIndirectCommand
1104    *      structure,  be in buffer objects,  and may not be called when
1105    *      the default vertex array object is bound."
1106    */
1107   if (ctx->API != API_OPENGL_COMPAT &&
1108       ctx->Array.VAO == ctx->Array.DefaultVAO) {
1109      _mesa_error(ctx, GL_INVALID_OPERATION, "(no VAO bound)");
1110      return GL_FALSE;
1111   }
1112
1113   /* From OpenGL ES 3.1 spec. section 10.5:
1114    *     "An INVALID_OPERATION error is generated if zero is bound to
1115    *     VERTEX_ARRAY_BINDING, DRAW_INDIRECT_BUFFER or to any enabled
1116    *     vertex array."
1117    *
1118    * Here we check that for each enabled vertex array we have a vertex
1119    * buffer bound.
1120    */
1121   if (_mesa_is_gles31(ctx) &&
1122       ctx->Array.VAO->Enabled & ~ctx->Array.VAO->VertexAttribBufferMask) {
1123      _mesa_error(ctx, GL_INVALID_OPERATION, "%s(No VBO bound)", name);
1124      return GL_FALSE;
1125   }
1126
1127   if (!_mesa_valid_prim_mode(ctx, mode, name))
1128      return GL_FALSE;
1129
1130   /* OpenGL ES 3.1 specification, section 10.5:
1131    *
1132    *      "An INVALID_OPERATION error is generated if
1133    *      transform feedback is active and not paused."
1134    *
1135    * The OES_geometry_shader spec says:
1136    *
1137    *    On p. 250 in the errors section for the DrawArraysIndirect command,
1138    *    and on p. 254 in the errors section for the DrawElementsIndirect
1139    *    command, delete the errors which state:
1140    *
1141    *    "An INVALID_OPERATION error is generated if transform feedback is
1142    *    active and not paused."
1143    *
1144    *    (thus allowing transform feedback to work with indirect draw commands).
1145    */
1146   if (_mesa_is_gles31(ctx) && !ctx->Extensions.OES_geometry_shader &&
1147       _mesa_is_xfb_active_and_unpaused(ctx)) {
1148      _mesa_error(ctx, GL_INVALID_OPERATION,
1149                  "%s(TransformFeedback is active and not paused)", name);
1150   }
1151
1152   /* From OpenGL version 4.4. section 10.5
1153    * and OpenGL ES 3.1, section 10.6:
1154    *
1155    *      "An INVALID_VALUE error is generated if indirect is not a
1156    *       multiple of the size, in basic machine units, of uint."
1157    */
1158   if ((GLsizeiptr)indirect & (sizeof(GLuint) - 1)) {
1159      _mesa_error(ctx, GL_INVALID_VALUE,
1160                  "%s(indirect is not aligned)", name);
1161      return GL_FALSE;
1162   }
1163
1164   if (!_mesa_is_bufferobj(ctx->DrawIndirectBuffer)) {
1165      _mesa_error(ctx, GL_INVALID_OPERATION,
1166                  "%s: no buffer bound to DRAW_INDIRECT_BUFFER", name);
1167      return GL_FALSE;
1168   }
1169
1170   if (_mesa_check_disallowed_mapping(ctx->DrawIndirectBuffer)) {
1171      _mesa_error(ctx, GL_INVALID_OPERATION,
1172                  "%s(DRAW_INDIRECT_BUFFER is mapped)", name);
1173      return GL_FALSE;
1174   }
1175
1176   /* From the ARB_draw_indirect specification:
1177    * "An INVALID_OPERATION error is generated if the commands source data
1178    *  beyond the end of the buffer object [...]"
1179    */
1180   if (ctx->DrawIndirectBuffer->Size < end) {
1181      _mesa_error(ctx, GL_INVALID_OPERATION,
1182                  "%s(DRAW_INDIRECT_BUFFER too small)", name);
1183      return GL_FALSE;
1184   }
1185
1186   if (!check_valid_to_render(ctx, name))
1187      return GL_FALSE;
1188
1189   return GL_TRUE;
1190}
1191
1192static inline GLboolean
1193valid_draw_indirect_elements(struct gl_context *ctx,
1194                             GLenum mode, GLenum type, const GLvoid *indirect,
1195                             GLsizeiptr size, const char *name)
1196{
1197   if (!valid_elements_type(ctx, type, name))
1198      return GL_FALSE;
1199
1200   /*
1201    * Unlike regular DrawElementsInstancedBaseVertex commands, the indices
1202    * may not come from a client array and must come from an index buffer.
1203    * If no element array buffer is bound, an INVALID_OPERATION error is
1204    * generated.
1205    */
1206   if (!_mesa_is_bufferobj(ctx->Array.VAO->IndexBufferObj)) {
1207      _mesa_error(ctx, GL_INVALID_OPERATION,
1208                  "%s(no buffer bound to GL_ELEMENT_ARRAY_BUFFER)", name);
1209      return GL_FALSE;
1210   }
1211
1212   return valid_draw_indirect(ctx, mode, indirect, size, name);
1213}
1214
1215GLboolean
1216_mesa_valid_draw_indirect_multi(struct gl_context *ctx,
1217                                GLsizei primcount, GLsizei stride,
1218                                const char *name)
1219{
1220
1221   /* From the ARB_multi_draw_indirect specification:
1222    * "INVALID_VALUE is generated by MultiDrawArraysIndirect or
1223    *  MultiDrawElementsIndirect if <primcount> is negative."
1224    *
1225    * "<primcount> must be positive, otherwise an INVALID_VALUE error will
1226    *  be generated."
1227    */
1228   if (primcount < 0) {
1229      _mesa_error(ctx, GL_INVALID_VALUE, "%s(primcount < 0)", name);
1230      return GL_FALSE;
1231   }
1232
1233
1234   /* From the ARB_multi_draw_indirect specification:
1235    * "<stride> must be a multiple of four, otherwise an INVALID_VALUE
1236    *  error is generated."
1237    */
1238   if (stride % 4) {
1239      _mesa_error(ctx, GL_INVALID_VALUE, "%s(stride %% 4)", name);
1240      return GL_FALSE;
1241   }
1242
1243   return GL_TRUE;
1244}
1245
1246GLboolean
1247_mesa_validate_DrawArraysIndirect(struct gl_context *ctx,
1248                                  GLenum mode,
1249                                  const GLvoid *indirect)
1250{
1251   const unsigned drawArraysNumParams = 4;
1252
1253   return valid_draw_indirect(ctx, mode,
1254                              indirect, drawArraysNumParams * sizeof(GLuint),
1255                              "glDrawArraysIndirect");
1256}
1257
1258GLboolean
1259_mesa_validate_DrawElementsIndirect(struct gl_context *ctx,
1260                                    GLenum mode, GLenum type,
1261                                    const GLvoid *indirect)
1262{
1263   const unsigned drawElementsNumParams = 5;
1264
1265   return valid_draw_indirect_elements(ctx, mode, type,
1266                                       indirect, drawElementsNumParams * sizeof(GLuint),
1267                                       "glDrawElementsIndirect");
1268}
1269
1270GLboolean
1271_mesa_validate_MultiDrawArraysIndirect(struct gl_context *ctx,
1272                                       GLenum mode,
1273                                       const GLvoid *indirect,
1274                                       GLsizei primcount, GLsizei stride)
1275{
1276   GLsizeiptr size = 0;
1277   const unsigned drawArraysNumParams = 4;
1278
1279   /* caller has converted stride==0 to drawArraysNumParams * sizeof(GLuint) */
1280   assert(stride != 0);
1281
1282   if (!_mesa_valid_draw_indirect_multi(ctx, primcount, stride,
1283                                        "glMultiDrawArraysIndirect"))
1284      return GL_FALSE;
1285
1286   /* number of bytes of the indirect buffer which will be read */
1287   size = primcount
1288      ? (primcount - 1) * stride + drawArraysNumParams * sizeof(GLuint)
1289      : 0;
1290
1291   if (!valid_draw_indirect(ctx, mode, indirect, size,
1292                            "glMultiDrawArraysIndirect"))
1293      return GL_FALSE;
1294
1295   return GL_TRUE;
1296}
1297
1298GLboolean
1299_mesa_validate_MultiDrawElementsIndirect(struct gl_context *ctx,
1300                                         GLenum mode, GLenum type,
1301                                         const GLvoid *indirect,
1302                                         GLsizei primcount, GLsizei stride)
1303{
1304   GLsizeiptr size = 0;
1305   const unsigned drawElementsNumParams = 5;
1306
1307   /* caller has converted stride==0 to drawElementsNumParams * sizeof(GLuint) */
1308   assert(stride != 0);
1309
1310   if (!_mesa_valid_draw_indirect_multi(ctx, primcount, stride,
1311                                        "glMultiDrawElementsIndirect"))
1312      return GL_FALSE;
1313
1314   /* number of bytes of the indirect buffer which will be read */
1315   size = primcount
1316      ? (primcount - 1) * stride + drawElementsNumParams * sizeof(GLuint)
1317      : 0;
1318
1319   if (!valid_draw_indirect_elements(ctx, mode, type,
1320                                     indirect, size,
1321                                     "glMultiDrawElementsIndirect"))
1322      return GL_FALSE;
1323
1324   return GL_TRUE;
1325}
1326
1327static GLboolean
1328valid_draw_indirect_parameters(struct gl_context *ctx,
1329                               const char *name,
1330                               GLintptr drawcount)
1331{
1332   /* From the ARB_indirect_parameters specification:
1333    * "INVALID_VALUE is generated by MultiDrawArraysIndirectCountARB or
1334    *  MultiDrawElementsIndirectCountARB if <drawcount> is not a multiple of
1335    *  four."
1336    */
1337   if (drawcount & 3) {
1338      _mesa_error(ctx, GL_INVALID_VALUE,
1339                  "%s(drawcount is not a multiple of 4)", name);
1340      return GL_FALSE;
1341   }
1342
1343   /* From the ARB_indirect_parameters specification:
1344    * "INVALID_OPERATION is generated by MultiDrawArraysIndirectCountARB or
1345    *  MultiDrawElementsIndirectCountARB if no buffer is bound to the
1346    *  PARAMETER_BUFFER_ARB binding point."
1347    */
1348   if (!_mesa_is_bufferobj(ctx->ParameterBuffer)) {
1349      _mesa_error(ctx, GL_INVALID_OPERATION,
1350                  "%s: no buffer bound to PARAMETER_BUFFER", name);
1351      return GL_FALSE;
1352   }
1353
1354   if (_mesa_check_disallowed_mapping(ctx->ParameterBuffer)) {
1355      _mesa_error(ctx, GL_INVALID_OPERATION,
1356                  "%s(PARAMETER_BUFFER is mapped)", name);
1357      return GL_FALSE;
1358   }
1359
1360   /* From the ARB_indirect_parameters specification:
1361    * "INVALID_OPERATION is generated by MultiDrawArraysIndirectCountARB or
1362    *  MultiDrawElementsIndirectCountARB if reading a <sizei> typed value
1363    *  from the buffer bound to the PARAMETER_BUFFER_ARB target at the offset
1364    *  specified by <drawcount> would result in an out-of-bounds access."
1365    */
1366   if (ctx->ParameterBuffer->Size < drawcount + sizeof(GLsizei)) {
1367      _mesa_error(ctx, GL_INVALID_OPERATION,
1368                  "%s(PARAMETER_BUFFER too small)", name);
1369      return GL_FALSE;
1370   }
1371
1372   return GL_TRUE;
1373}
1374
1375GLboolean
1376_mesa_validate_MultiDrawArraysIndirectCount(struct gl_context *ctx,
1377                                            GLenum mode,
1378                                            GLintptr indirect,
1379                                            GLintptr drawcount,
1380                                            GLsizei maxdrawcount,
1381                                            GLsizei stride)
1382{
1383   GLsizeiptr size = 0;
1384   const unsigned drawArraysNumParams = 4;
1385
1386   /* caller has converted stride==0 to drawArraysNumParams * sizeof(GLuint) */
1387   assert(stride != 0);
1388
1389   if (!_mesa_valid_draw_indirect_multi(ctx, maxdrawcount, stride,
1390                                        "glMultiDrawArraysIndirectCountARB"))
1391      return GL_FALSE;
1392
1393   /* number of bytes of the indirect buffer which will be read */
1394   size = maxdrawcount
1395      ? (maxdrawcount - 1) * stride + drawArraysNumParams * sizeof(GLuint)
1396      : 0;
1397
1398   if (!valid_draw_indirect(ctx, mode, (void *)indirect, size,
1399                            "glMultiDrawArraysIndirectCountARB"))
1400      return GL_FALSE;
1401
1402   return valid_draw_indirect_parameters(
1403         ctx, "glMultiDrawArraysIndirectCountARB", drawcount);
1404}
1405
1406GLboolean
1407_mesa_validate_MultiDrawElementsIndirectCount(struct gl_context *ctx,
1408                                              GLenum mode, GLenum type,
1409                                              GLintptr indirect,
1410                                              GLintptr drawcount,
1411                                              GLsizei maxdrawcount,
1412                                              GLsizei stride)
1413{
1414   GLsizeiptr size = 0;
1415   const unsigned drawElementsNumParams = 5;
1416
1417   /* caller has converted stride==0 to drawElementsNumParams * sizeof(GLuint) */
1418   assert(stride != 0);
1419
1420   if (!_mesa_valid_draw_indirect_multi(ctx, maxdrawcount, stride,
1421                                        "glMultiDrawElementsIndirectCountARB"))
1422      return GL_FALSE;
1423
1424   /* number of bytes of the indirect buffer which will be read */
1425   size = maxdrawcount
1426      ? (maxdrawcount - 1) * stride + drawElementsNumParams * sizeof(GLuint)
1427      : 0;
1428
1429   if (!valid_draw_indirect_elements(ctx, mode, type,
1430                                     (void *)indirect, size,
1431                                     "glMultiDrawElementsIndirectCountARB"))
1432      return GL_FALSE;
1433
1434   return valid_draw_indirect_parameters(
1435         ctx, "glMultiDrawElementsIndirectCountARB", drawcount);
1436}
1437