draw_validate.c revision 01e04c3f
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      break;
308
309   case API_OPENGL_CORE:
310      /* Section 10.4 (Drawing Commands Using Vertex Arrays) of the OpenGL 4.5
311       * Core Profile spec says:
312       *
313       *     "An INVALID_OPERATION error is generated if no vertex array
314       *     object is bound (see section 10.3.1)."
315       */
316      if (ctx->Array.VAO == ctx->Array.DefaultVAO) {
317         _mesa_error(ctx, GL_INVALID_OPERATION, "%s(no VAO bound)", function);
318         return false;
319      }
320      break;
321
322   case API_OPENGLES:
323   case API_OPENGL_COMPAT:
324      break;
325
326   default:
327      unreachable("Invalid API value in check_valid_to_render()");
328   }
329
330   return true;
331}
332
333
334/**
335 * Is 'mode' a valid value for glBegin(), glDrawArrays(), glDrawElements(),
336 * etc?  The set of legal values depends on whether geometry shaders/programs
337 * are supported.
338 * Note: This may be called during display list compilation.
339 */
340bool
341_mesa_is_valid_prim_mode(const struct gl_context *ctx, GLenum mode)
342{
343   /* The overwhelmingly common case is (mode <= GL_TRIANGLE_FAN).  Test that
344    * first and exit.  You would think that a switch-statement would be the
345    * right approach, but at least GCC 4.7.2 generates some pretty dire code
346    * for the common case.
347    */
348   if (likely(mode <= GL_TRIANGLE_FAN))
349      return true;
350
351   if (mode <= GL_POLYGON)
352      return (ctx->API == API_OPENGL_COMPAT);
353
354   if (mode <= GL_TRIANGLE_STRIP_ADJACENCY)
355      return _mesa_has_geometry_shaders(ctx);
356
357   if (mode == GL_PATCHES)
358      return _mesa_has_tessellation(ctx);
359
360   return false;
361}
362
363
364/**
365 * Is 'mode' a valid value for glBegin(), glDrawArrays(), glDrawElements(),
366 * etc?  Also, do additional checking related to transformation feedback.
367 * Note: this function cannot be called during glNewList(GL_COMPILE) because
368 * this code depends on current transform feedback state.
369 * Also, do additional checking related to tessellation shaders.
370 */
371GLboolean
372_mesa_valid_prim_mode(struct gl_context *ctx, GLenum mode, const char *name)
373{
374   bool valid_enum = _mesa_is_valid_prim_mode(ctx, mode);
375
376   if (!valid_enum) {
377      _mesa_error(ctx, GL_INVALID_ENUM, "%s(mode=%x)", name, mode);
378      return GL_FALSE;
379   }
380
381   /* From the OpenGL 4.5 specification, section 11.3.1:
382    *
383    * The error INVALID_OPERATION is generated if Begin, or any command that
384    * implicitly calls Begin, is called when a geometry shader is active and:
385    *
386    * * the input primitive type of the current geometry shader is
387    *   POINTS and <mode> is not POINTS,
388    *
389    * * the input primitive type of the current geometry shader is
390    *   LINES and <mode> is not LINES, LINE_STRIP, or LINE_LOOP,
391    *
392    * * the input primitive type of the current geometry shader is
393    *   TRIANGLES and <mode> is not TRIANGLES, TRIANGLE_STRIP or
394    *   TRIANGLE_FAN,
395    *
396    * * the input primitive type of the current geometry shader is
397    *   LINES_ADJACENCY_ARB and <mode> is not LINES_ADJACENCY_ARB or
398    *   LINE_STRIP_ADJACENCY_ARB, or
399    *
400    * * the input primitive type of the current geometry shader is
401    *   TRIANGLES_ADJACENCY_ARB and <mode> is not
402    *   TRIANGLES_ADJACENCY_ARB or TRIANGLE_STRIP_ADJACENCY_ARB.
403    *
404    * The GL spec doesn't mention any interaction with tessellation, which
405    * is clearly a spec bug. The same rule should apply, but instead of
406    * the draw primitive mode, the tessellation evaluation shader primitive
407    * mode should be used for the checking.
408   */
409   if (ctx->_Shader->CurrentProgram[MESA_SHADER_GEOMETRY]) {
410      const GLenum geom_mode =
411         ctx->_Shader->CurrentProgram[MESA_SHADER_GEOMETRY]->
412            info.gs.input_primitive;
413      struct gl_program *tes =
414         ctx->_Shader->CurrentProgram[MESA_SHADER_TESS_EVAL];
415      GLenum mode_before_gs = mode;
416
417      if (tes) {
418         if (tes->info.tess.point_mode)
419            mode_before_gs = GL_POINTS;
420         else if (tes->info.tess.primitive_mode == GL_ISOLINES)
421            mode_before_gs = GL_LINES;
422         else
423            /* the GL_QUADS mode generates triangles too */
424            mode_before_gs = GL_TRIANGLES;
425      }
426
427      switch (mode_before_gs) {
428      case GL_POINTS:
429         valid_enum = (geom_mode == GL_POINTS);
430         break;
431      case GL_LINES:
432      case GL_LINE_LOOP:
433      case GL_LINE_STRIP:
434         valid_enum = (geom_mode == GL_LINES);
435         break;
436      case GL_TRIANGLES:
437      case GL_TRIANGLE_STRIP:
438      case GL_TRIANGLE_FAN:
439         valid_enum = (geom_mode == GL_TRIANGLES);
440         break;
441      case GL_QUADS:
442      case GL_QUAD_STRIP:
443      case GL_POLYGON:
444         valid_enum = false;
445         break;
446      case GL_LINES_ADJACENCY:
447      case GL_LINE_STRIP_ADJACENCY:
448         valid_enum = (geom_mode == GL_LINES_ADJACENCY);
449         break;
450      case GL_TRIANGLES_ADJACENCY:
451      case GL_TRIANGLE_STRIP_ADJACENCY:
452         valid_enum = (geom_mode == GL_TRIANGLES_ADJACENCY);
453         break;
454      default:
455         valid_enum = false;
456         break;
457      }
458      if (!valid_enum) {
459         _mesa_error(ctx, GL_INVALID_OPERATION,
460                     "%s(mode=%s vs geometry shader input %s)",
461                     name,
462                     _mesa_lookup_prim_by_nr(mode_before_gs),
463                     _mesa_lookup_prim_by_nr(geom_mode));
464         return GL_FALSE;
465      }
466   }
467
468   /* From the OpenGL 4.0 (Core Profile) spec (section 2.12):
469    *
470    *     "Tessellation operates only on patch primitives. If tessellation is
471    *      active, any command that transfers vertices to the GL will
472    *      generate an INVALID_OPERATION error if the primitive mode is not
473    *      PATCHES.
474    *      Patch primitives are not supported by pipeline stages below the
475    *      tessellation evaluation shader. If there is no active program
476    *      object or the active program object does not contain a tessellation
477    *      evaluation shader, the error INVALID_OPERATION is generated by any
478    *      command that transfers vertices to the GL if the primitive mode is
479    *      PATCHES."
480    *
481    */
482   if (ctx->_Shader->CurrentProgram[MESA_SHADER_TESS_EVAL] ||
483       ctx->_Shader->CurrentProgram[MESA_SHADER_TESS_CTRL]) {
484      if (mode != GL_PATCHES) {
485         _mesa_error(ctx, GL_INVALID_OPERATION,
486                     "only GL_PATCHES valid with tessellation");
487         return GL_FALSE;
488      }
489   }
490   else {
491      if (mode == GL_PATCHES) {
492         _mesa_error(ctx, GL_INVALID_OPERATION,
493                     "GL_PATCHES only valid with tessellation");
494         return GL_FALSE;
495      }
496   }
497
498   /* From the GL_EXT_transform_feedback spec:
499    *
500    *     "The error INVALID_OPERATION is generated if Begin, or any command
501    *      that performs an explicit Begin, is called when:
502    *
503    *      * a geometry shader is not active and <mode> does not match the
504    *        allowed begin modes for the current transform feedback state as
505    *        given by table X.1.
506    *
507    *      * a geometry shader is active and the output primitive type of the
508    *        geometry shader does not match the allowed begin modes for the
509    *        current transform feedback state as given by table X.1.
510    *
511    */
512   if (_mesa_is_xfb_active_and_unpaused(ctx)) {
513      GLboolean pass = GL_TRUE;
514
515      if(ctx->_Shader->CurrentProgram[MESA_SHADER_GEOMETRY]) {
516         switch (ctx->_Shader->CurrentProgram[MESA_SHADER_GEOMETRY]->
517                    info.gs.output_primitive) {
518         case GL_POINTS:
519            pass = ctx->TransformFeedback.Mode == GL_POINTS;
520            break;
521         case GL_LINE_STRIP:
522            pass = ctx->TransformFeedback.Mode == GL_LINES;
523            break;
524         case GL_TRIANGLE_STRIP:
525            pass = ctx->TransformFeedback.Mode == GL_TRIANGLES;
526            break;
527         default:
528            pass = GL_FALSE;
529         }
530      }
531      else if (ctx->_Shader->CurrentProgram[MESA_SHADER_TESS_EVAL]) {
532         struct gl_program *tes =
533            ctx->_Shader->CurrentProgram[MESA_SHADER_TESS_EVAL];
534         if (tes->info.tess.point_mode)
535            pass = ctx->TransformFeedback.Mode == GL_POINTS;
536         else if (tes->info.tess.primitive_mode == GL_ISOLINES)
537            pass = ctx->TransformFeedback.Mode == GL_LINES;
538         else
539            pass = ctx->TransformFeedback.Mode == GL_TRIANGLES;
540      }
541      else {
542         switch (mode) {
543         case GL_POINTS:
544            pass = ctx->TransformFeedback.Mode == GL_POINTS;
545            break;
546         case GL_LINES:
547         case GL_LINE_STRIP:
548         case GL_LINE_LOOP:
549            pass = ctx->TransformFeedback.Mode == GL_LINES;
550            break;
551         default:
552            pass = ctx->TransformFeedback.Mode == GL_TRIANGLES;
553            break;
554         }
555      }
556      if (!pass) {
557         _mesa_error(ctx, GL_INVALID_OPERATION,
558                         "%s(mode=%s vs transform feedback %s)",
559                         name,
560                         _mesa_lookup_prim_by_nr(mode),
561                         _mesa_lookup_prim_by_nr(ctx->TransformFeedback.Mode));
562         return GL_FALSE;
563      }
564   }
565
566   /* From GL_INTEL_conservative_rasterization spec:
567    *
568    * The conservative rasterization option applies only to polygons with
569    * PolygonMode state set to FILL. Draw requests for polygons with different
570    * PolygonMode setting or for other primitive types (points/lines) generate
571    * INVALID_OPERATION error.
572    */
573   if (ctx->IntelConservativeRasterization) {
574      GLboolean pass = GL_TRUE;
575
576      switch (mode) {
577      case GL_POINTS:
578      case GL_LINES:
579      case GL_LINE_LOOP:
580      case GL_LINE_STRIP:
581      case GL_LINES_ADJACENCY:
582      case GL_LINE_STRIP_ADJACENCY:
583         pass = GL_FALSE;
584         break;
585      case GL_TRIANGLES:
586      case GL_TRIANGLE_STRIP:
587      case GL_TRIANGLE_FAN:
588      case GL_QUADS:
589      case GL_QUAD_STRIP:
590      case GL_POLYGON:
591      case GL_TRIANGLES_ADJACENCY:
592      case GL_TRIANGLE_STRIP_ADJACENCY:
593         if (ctx->Polygon.FrontMode != GL_FILL ||
594             ctx->Polygon.BackMode != GL_FILL)
595            pass = GL_FALSE;
596         break;
597      default:
598         pass = GL_FALSE;
599      }
600      if (!pass) {
601         _mesa_error(ctx, GL_INVALID_OPERATION,
602                     "mode=%s invalid with GL_INTEL_conservative_rasterization",
603                     _mesa_lookup_prim_by_nr(mode));
604         return GL_FALSE;
605      }
606   }
607
608   return GL_TRUE;
609}
610
611/**
612 * Verify that the element type is valid.
613 *
614 * Generates \c GL_INVALID_ENUM and returns \c false if it is not.
615 */
616static bool
617valid_elements_type(struct gl_context *ctx, GLenum type, const char *name)
618{
619   switch (type) {
620   case GL_UNSIGNED_BYTE:
621   case GL_UNSIGNED_SHORT:
622   case GL_UNSIGNED_INT:
623      return true;
624
625   default:
626      _mesa_error(ctx, GL_INVALID_ENUM, "%s(type = %s)", name,
627                  _mesa_enum_to_string(type));
628      return false;
629   }
630}
631
632static bool
633validate_DrawElements_common(struct gl_context *ctx,
634                             GLenum mode, GLsizei count, GLenum type,
635                             const GLvoid *indices,
636                             const char *caller)
637{
638   /* Section 2.14.2 (Transform Feedback Primitive Capture) of the OpenGL ES
639    * 3.1 spec says:
640    *
641    *   The error INVALID_OPERATION is also generated by DrawElements,
642    *   DrawElementsInstanced, and DrawRangeElements while transform feedback
643    *   is active and not paused, regardless of mode.
644    *
645    * The OES_geometry_shader_spec says:
646    *
647    *    Issues:
648    *
649    *    ...
650    *
651    *    (13) Does this extension change how transform feedback operates
652    *    compared to unextended OpenGL ES 3.0 or 3.1?
653    *
654    *    RESOLVED: Yes... Since we no longer require being able to predict how
655    *    much geometry will be generated, we also lift the restriction that
656    *    only DrawArray* commands are supported and also support the
657    *    DrawElements* commands for transform feedback.
658    *
659    * This should also be reflected in the body of the spec, but that appears
660    * to have been overlooked.  The body of the spec only explicitly allows
661    * the indirect versions.
662    */
663   if (_mesa_is_gles3(ctx) &&
664       !_mesa_has_OES_geometry_shader(ctx) &&
665       _mesa_is_xfb_active_and_unpaused(ctx)) {
666      _mesa_error(ctx, GL_INVALID_OPERATION,
667                  "%s(transform feedback active)", caller);
668      return false;
669   }
670
671   if (count < 0) {
672      _mesa_error(ctx, GL_INVALID_VALUE, "%s(count)", caller);
673      return false;
674   }
675
676   if (!_mesa_valid_prim_mode(ctx, mode, caller)) {
677      return false;
678   }
679
680   if (!valid_elements_type(ctx, type, caller))
681      return false;
682
683   if (!check_valid_to_render(ctx, caller))
684      return false;
685
686   return true;
687}
688
689/**
690 * Error checking for glDrawElements().  Includes parameter checking
691 * and VBO bounds checking.
692 * \return GL_TRUE if OK to render, GL_FALSE if error found
693 */
694GLboolean
695_mesa_validate_DrawElements(struct gl_context *ctx,
696                            GLenum mode, GLsizei count, GLenum type,
697                            const GLvoid *indices)
698{
699   return validate_DrawElements_common(ctx, mode, count, type, indices,
700                                       "glDrawElements");
701}
702
703
704/**
705 * Error checking for glMultiDrawElements().  Includes parameter checking
706 * and VBO bounds checking.
707 * \return GL_TRUE if OK to render, GL_FALSE if error found
708 */
709GLboolean
710_mesa_validate_MultiDrawElements(struct gl_context *ctx,
711                                 GLenum mode, const GLsizei *count,
712                                 GLenum type, const GLvoid * const *indices,
713                                 GLsizei primcount)
714{
715   GLsizei i;
716
717   /*
718    * Section 2.3.1 (Errors) of the OpenGL 4.5 (Core Profile) spec says:
719    *
720    *    "If a negative number is provided where an argument of type sizei or
721    *     sizeiptr is specified, an INVALID_VALUE error is generated."
722    *
723    * and in the same section:
724    *
725    *    "In other cases, there are no side effects unless otherwise noted;
726    *     the command which generates the error is ignored so that it has no
727    *     effect on GL state or framebuffer contents."
728    *
729    * Hence, check both primcount and all the count[i].
730    */
731   if (primcount < 0) {
732      _mesa_error(ctx, GL_INVALID_VALUE,
733                  "glMultiDrawElements(primcount=%d)", primcount);
734      return GL_FALSE;
735   }
736
737   for (i = 0; i < primcount; i++) {
738      if (count[i] < 0) {
739         _mesa_error(ctx, GL_INVALID_VALUE,
740                     "glMultiDrawElements(count)" );
741         return GL_FALSE;
742      }
743   }
744
745   if (!_mesa_valid_prim_mode(ctx, mode, "glMultiDrawElements")) {
746      return GL_FALSE;
747   }
748
749   if (!valid_elements_type(ctx, type, "glMultiDrawElements"))
750      return GL_FALSE;
751
752   if (!check_valid_to_render(ctx, "glMultiDrawElements"))
753      return GL_FALSE;
754
755   /* Not using a VBO for indices, so avoid NULL pointer derefs later.
756    */
757   if (!_mesa_is_bufferobj(ctx->Array.VAO->IndexBufferObj)) {
758      for (i = 0; i < primcount; i++) {
759         if (!indices[i])
760            return GL_FALSE;
761      }
762   }
763
764   return GL_TRUE;
765}
766
767
768/**
769 * Error checking for glDrawRangeElements().  Includes parameter checking
770 * and VBO bounds checking.
771 * \return GL_TRUE if OK to render, GL_FALSE if error found
772 */
773GLboolean
774_mesa_validate_DrawRangeElements(struct gl_context *ctx, GLenum mode,
775                                 GLuint start, GLuint end,
776                                 GLsizei count, GLenum type,
777                                 const GLvoid *indices)
778{
779   if (end < start) {
780      _mesa_error(ctx, GL_INVALID_VALUE, "glDrawRangeElements(end<start)");
781      return GL_FALSE;
782   }
783
784   return validate_DrawElements_common(ctx, mode, count, type, indices,
785                                       "glDrawRangeElements");
786}
787
788
789static bool
790need_xfb_remaining_prims_check(const struct gl_context *ctx)
791{
792   /* From the GLES3 specification, section 2.14.2 (Transform Feedback
793    * Primitive Capture):
794    *
795    *   The error INVALID_OPERATION is generated by DrawArrays and
796    *   DrawArraysInstanced if recording the vertices of a primitive to the
797    *   buffer objects being used for transform feedback purposes would result
798    *   in either exceeding the limits of any buffer object’s size, or in
799    *   exceeding the end position offset + size − 1, as set by
800    *   BindBufferRange.
801    *
802    * This is in contrast to the behaviour of desktop GL, where the extra
803    * primitives are silently dropped from the transform feedback buffer.
804    *
805    * This text is removed in ES 3.2, presumably because it's not really
806    * implementable with geometry and tessellation shaders.  In fact,
807    * the OES_geometry_shader spec says:
808    *
809    *    "(13) Does this extension change how transform feedback operates
810    *     compared to unextended OpenGL ES 3.0 or 3.1?
811    *
812    *     RESOLVED: Yes. Because dynamic geometry amplification in a geometry
813    *     shader can make it difficult if not impossible to predict the amount
814    *     of geometry that may be generated in advance of executing the shader,
815    *     the draw-time error for transform feedback buffer overflow conditions
816    *     is removed and replaced with the GL behavior (primitives are not
817    *     written and the corresponding counter is not updated)..."
818    */
819   return _mesa_is_gles3(ctx) && _mesa_is_xfb_active_and_unpaused(ctx) &&
820          !_mesa_has_OES_geometry_shader(ctx) &&
821          !_mesa_has_OES_tessellation_shader(ctx);
822}
823
824
825/**
826 * Figure out the number of transform feedback primitives that will be output
827 * considering the drawing mode, number of vertices, and instance count,
828 * assuming that no geometry shading is done and primitive restart is not
829 * used.
830 *
831 * This is used by driver back-ends in implementing the PRIMITIVES_GENERATED
832 * and TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN queries.  It is also used to
833 * pre-validate draw calls in GLES3 (where draw calls only succeed if there is
834 * enough room in the transform feedback buffer for the result).
835 */
836static size_t
837count_tessellated_primitives(GLenum mode, GLuint count, GLuint num_instances)
838{
839   size_t num_primitives;
840   switch (mode) {
841   case GL_POINTS:
842      num_primitives = count;
843      break;
844   case GL_LINE_STRIP:
845      num_primitives = count >= 2 ? count - 1 : 0;
846      break;
847   case GL_LINE_LOOP:
848      num_primitives = count >= 2 ? count : 0;
849      break;
850   case GL_LINES:
851      num_primitives = count / 2;
852      break;
853   case GL_TRIANGLE_STRIP:
854   case GL_TRIANGLE_FAN:
855   case GL_POLYGON:
856      num_primitives = count >= 3 ? count - 2 : 0;
857      break;
858   case GL_TRIANGLES:
859      num_primitives = count / 3;
860      break;
861   case GL_QUAD_STRIP:
862      num_primitives = count >= 4 ? ((count / 2) - 1) * 2 : 0;
863      break;
864   case GL_QUADS:
865      num_primitives = (count / 4) * 2;
866      break;
867   case GL_LINES_ADJACENCY:
868      num_primitives = count / 4;
869      break;
870   case GL_LINE_STRIP_ADJACENCY:
871      num_primitives = count >= 4 ? count - 3 : 0;
872      break;
873   case GL_TRIANGLES_ADJACENCY:
874      num_primitives = count / 6;
875      break;
876   case GL_TRIANGLE_STRIP_ADJACENCY:
877      num_primitives = count >= 6 ? (count - 4) / 2 : 0;
878      break;
879   default:
880      assert(!"Unexpected primitive type in count_tessellated_primitives");
881      num_primitives = 0;
882      break;
883   }
884   return num_primitives * num_instances;
885}
886
887
888static bool
889validate_draw_arrays(struct gl_context *ctx, const char *func,
890                     GLenum mode, GLsizei count, GLsizei numInstances)
891{
892   if (count < 0) {
893      _mesa_error(ctx, GL_INVALID_VALUE, "%s(count)", func);
894      return false;
895   }
896
897   if (!_mesa_valid_prim_mode(ctx, mode, func))
898      return false;
899
900   if (!check_valid_to_render(ctx, func))
901      return false;
902
903   if (need_xfb_remaining_prims_check(ctx)) {
904      struct gl_transform_feedback_object *xfb_obj
905         = ctx->TransformFeedback.CurrentObject;
906      size_t prim_count = count_tessellated_primitives(mode, count, numInstances);
907      if (xfb_obj->GlesRemainingPrims < prim_count) {
908         _mesa_error(ctx, GL_INVALID_OPERATION,
909                     "%s(exceeds transform feedback size)", func);
910         return false;
911      }
912      xfb_obj->GlesRemainingPrims -= prim_count;
913   }
914
915   if (count == 0)
916      return false;
917
918   return true;
919}
920
921/**
922 * Called from the tnl module to error check the function parameters and
923 * verify that we really can draw something.
924 * \return GL_TRUE if OK to render, GL_FALSE if error found
925 */
926GLboolean
927_mesa_validate_DrawArrays(struct gl_context *ctx, GLenum mode, GLsizei count)
928{
929   return validate_draw_arrays(ctx, "glDrawArrays", mode, count, 1);
930}
931
932
933GLboolean
934_mesa_validate_DrawArraysInstanced(struct gl_context *ctx, GLenum mode, GLint first,
935                                   GLsizei count, GLsizei numInstances)
936{
937   if (first < 0) {
938      _mesa_error(ctx, GL_INVALID_VALUE,
939                  "glDrawArraysInstanced(start=%d)", first);
940      return GL_FALSE;
941   }
942
943   if (numInstances <= 0) {
944      if (numInstances < 0)
945         _mesa_error(ctx, GL_INVALID_VALUE,
946                     "glDrawArraysInstanced(numInstances=%d)", numInstances);
947      return GL_FALSE;
948   }
949
950   return validate_draw_arrays(ctx, "glDrawArraysInstanced", mode, count, 1);
951}
952
953
954/**
955 * Called to error check the function parameters.
956 *
957 * Note that glMultiDrawArrays is not part of GLES, so there's limited scope
958 * for sharing code with the validation of glDrawArrays.
959 */
960bool
961_mesa_validate_MultiDrawArrays(struct gl_context *ctx, GLenum mode,
962                               const GLsizei *count, GLsizei primcount)
963{
964   int i;
965
966   if (!_mesa_valid_prim_mode(ctx, mode, "glMultiDrawArrays"))
967      return false;
968
969   if (!check_valid_to_render(ctx, "glMultiDrawArrays"))
970      return false;
971
972   if (primcount < 0) {
973      _mesa_error(ctx, GL_INVALID_VALUE, "glMultiDrawArrays(primcount=%d)",
974                  primcount);
975      return false;
976   }
977
978   for (i = 0; i < primcount; ++i) {
979      if (count[i] < 0) {
980         _mesa_error(ctx, GL_INVALID_VALUE, "glMultiDrawArrays(count[%d]=%d)",
981                     i, count[i]);
982         return false;
983      }
984   }
985
986   if (need_xfb_remaining_prims_check(ctx)) {
987      struct gl_transform_feedback_object *xfb_obj
988         = ctx->TransformFeedback.CurrentObject;
989      size_t xfb_prim_count = 0;
990
991      for (i = 0; i < primcount; ++i)
992         xfb_prim_count += count_tessellated_primitives(mode, count[i], 1);
993
994      if (xfb_obj->GlesRemainingPrims < xfb_prim_count) {
995         _mesa_error(ctx, GL_INVALID_OPERATION,
996                     "glMultiDrawArrays(exceeds transform feedback size)");
997         return false;
998      }
999      xfb_obj->GlesRemainingPrims -= xfb_prim_count;
1000   }
1001
1002   return true;
1003}
1004
1005
1006GLboolean
1007_mesa_validate_DrawElementsInstanced(struct gl_context *ctx,
1008                                     GLenum mode, GLsizei count, GLenum type,
1009                                     const GLvoid *indices, GLsizei numInstances)
1010{
1011   if (numInstances < 0) {
1012      _mesa_error(ctx, GL_INVALID_VALUE,
1013                  "glDrawElementsInstanced(numInstances=%d)", numInstances);
1014      return GL_FALSE;
1015   }
1016
1017   return validate_DrawElements_common(ctx, mode, count, type, indices,
1018                                       "glDrawElementsInstanced")
1019      && (numInstances > 0);
1020}
1021
1022
1023GLboolean
1024_mesa_validate_DrawTransformFeedback(struct gl_context *ctx,
1025                                     GLenum mode,
1026                                     struct gl_transform_feedback_object *obj,
1027                                     GLuint stream,
1028                                     GLsizei numInstances)
1029{
1030   if (!_mesa_valid_prim_mode(ctx, mode, "glDrawTransformFeedback*(mode)")) {
1031      return GL_FALSE;
1032   }
1033
1034   if (!obj) {
1035      _mesa_error(ctx, GL_INVALID_VALUE, "glDrawTransformFeedback*(name)");
1036      return GL_FALSE;
1037   }
1038
1039   /* From the GL 4.5 specification, page 429:
1040    * "An INVALID_VALUE error is generated if id is not the name of a
1041    *  transform feedback object."
1042    */
1043   if (!obj->EverBound) {
1044      _mesa_error(ctx, GL_INVALID_VALUE, "glDrawTransformFeedback*(name)");
1045      return GL_FALSE;
1046   }
1047
1048   if (stream >= ctx->Const.MaxVertexStreams) {
1049      _mesa_error(ctx, GL_INVALID_VALUE,
1050                  "glDrawTransformFeedbackStream*(index>=MaxVertexStream)");
1051      return GL_FALSE;
1052   }
1053
1054   if (!obj->EndedAnytime) {
1055      _mesa_error(ctx, GL_INVALID_OPERATION, "glDrawTransformFeedback*");
1056      return GL_FALSE;
1057   }
1058
1059   if (numInstances <= 0) {
1060      if (numInstances < 0)
1061         _mesa_error(ctx, GL_INVALID_VALUE,
1062                     "glDrawTransformFeedback*Instanced(numInstances=%d)",
1063                     numInstances);
1064      return GL_FALSE;
1065   }
1066
1067   if (!check_valid_to_render(ctx, "glDrawTransformFeedback*")) {
1068      return GL_FALSE;
1069   }
1070
1071   return GL_TRUE;
1072}
1073
1074static GLboolean
1075valid_draw_indirect(struct gl_context *ctx,
1076                    GLenum mode, const GLvoid *indirect,
1077                    GLsizei size, const char *name)
1078{
1079   const uint64_t end = (uint64_t) (uintptr_t) indirect + size;
1080
1081   /* OpenGL ES 3.1 spec. section 10.5:
1082    *
1083    *      "DrawArraysIndirect requires that all data sourced for the
1084    *      command, including the DrawArraysIndirectCommand
1085    *      structure,  be in buffer objects,  and may not be called when
1086    *      the default vertex array object is bound."
1087    */
1088   if (ctx->API != API_OPENGL_COMPAT &&
1089       ctx->Array.VAO == ctx->Array.DefaultVAO) {
1090      _mesa_error(ctx, GL_INVALID_OPERATION, "(no VAO bound)");
1091      return GL_FALSE;
1092   }
1093
1094   /* From OpenGL ES 3.1 spec. section 10.5:
1095    *     "An INVALID_OPERATION error is generated if zero is bound to
1096    *     VERTEX_ARRAY_BINDING, DRAW_INDIRECT_BUFFER or to any enabled
1097    *     vertex array."
1098    *
1099    * Here we check that for each enabled vertex array we have a vertex
1100    * buffer bound.
1101    */
1102   if (_mesa_is_gles31(ctx) &&
1103       ctx->Array.VAO->_Enabled & ~ctx->Array.VAO->VertexAttribBufferMask) {
1104      _mesa_error(ctx, GL_INVALID_OPERATION, "%s(No VBO bound)", name);
1105      return GL_FALSE;
1106   }
1107
1108   if (!_mesa_valid_prim_mode(ctx, mode, name))
1109      return GL_FALSE;
1110
1111   /* OpenGL ES 3.1 specification, section 10.5:
1112    *
1113    *      "An INVALID_OPERATION error is generated if
1114    *      transform feedback is active and not paused."
1115    *
1116    * The OES_geometry_shader spec says:
1117    *
1118    *    On p. 250 in the errors section for the DrawArraysIndirect command,
1119    *    and on p. 254 in the errors section for the DrawElementsIndirect
1120    *    command, delete the errors which state:
1121    *
1122    *    "An INVALID_OPERATION error is generated if transform feedback is
1123    *    active and not paused."
1124    *
1125    *    (thus allowing transform feedback to work with indirect draw commands).
1126    */
1127   if (_mesa_is_gles31(ctx) && !ctx->Extensions.OES_geometry_shader &&
1128       _mesa_is_xfb_active_and_unpaused(ctx)) {
1129      _mesa_error(ctx, GL_INVALID_OPERATION,
1130                  "%s(TransformFeedback is active and not paused)", name);
1131   }
1132
1133   /* From OpenGL version 4.4. section 10.5
1134    * and OpenGL ES 3.1, section 10.6:
1135    *
1136    *      "An INVALID_VALUE error is generated if indirect is not a
1137    *       multiple of the size, in basic machine units, of uint."
1138    */
1139   if ((GLsizeiptr)indirect & (sizeof(GLuint) - 1)) {
1140      _mesa_error(ctx, GL_INVALID_VALUE,
1141                  "%s(indirect is not aligned)", name);
1142      return GL_FALSE;
1143   }
1144
1145   if (!_mesa_is_bufferobj(ctx->DrawIndirectBuffer)) {
1146      _mesa_error(ctx, GL_INVALID_OPERATION,
1147                  "%s: no buffer bound to DRAW_INDIRECT_BUFFER", name);
1148      return GL_FALSE;
1149   }
1150
1151   if (_mesa_check_disallowed_mapping(ctx->DrawIndirectBuffer)) {
1152      _mesa_error(ctx, GL_INVALID_OPERATION,
1153                  "%s(DRAW_INDIRECT_BUFFER is mapped)", name);
1154      return GL_FALSE;
1155   }
1156
1157   /* From the ARB_draw_indirect specification:
1158    * "An INVALID_OPERATION error is generated if the commands source data
1159    *  beyond the end of the buffer object [...]"
1160    */
1161   if (ctx->DrawIndirectBuffer->Size < end) {
1162      _mesa_error(ctx, GL_INVALID_OPERATION,
1163                  "%s(DRAW_INDIRECT_BUFFER too small)", name);
1164      return GL_FALSE;
1165   }
1166
1167   if (!check_valid_to_render(ctx, name))
1168      return GL_FALSE;
1169
1170   return GL_TRUE;
1171}
1172
1173static inline GLboolean
1174valid_draw_indirect_elements(struct gl_context *ctx,
1175                             GLenum mode, GLenum type, const GLvoid *indirect,
1176                             GLsizeiptr size, const char *name)
1177{
1178   if (!valid_elements_type(ctx, type, name))
1179      return GL_FALSE;
1180
1181   /*
1182    * Unlike regular DrawElementsInstancedBaseVertex commands, the indices
1183    * may not come from a client array and must come from an index buffer.
1184    * If no element array buffer is bound, an INVALID_OPERATION error is
1185    * generated.
1186    */
1187   if (!_mesa_is_bufferobj(ctx->Array.VAO->IndexBufferObj)) {
1188      _mesa_error(ctx, GL_INVALID_OPERATION,
1189                  "%s(no buffer bound to GL_ELEMENT_ARRAY_BUFFER)", name);
1190      return GL_FALSE;
1191   }
1192
1193   return valid_draw_indirect(ctx, mode, indirect, size, name);
1194}
1195
1196GLboolean
1197_mesa_valid_draw_indirect_multi(struct gl_context *ctx,
1198                                GLsizei primcount, GLsizei stride,
1199                                const char *name)
1200{
1201
1202   /* From the ARB_multi_draw_indirect specification:
1203    * "INVALID_VALUE is generated by MultiDrawArraysIndirect or
1204    *  MultiDrawElementsIndirect if <primcount> is negative."
1205    *
1206    * "<primcount> must be positive, otherwise an INVALID_VALUE error will
1207    *  be generated."
1208    */
1209   if (primcount < 0) {
1210      _mesa_error(ctx, GL_INVALID_VALUE, "%s(primcount < 0)", name);
1211      return GL_FALSE;
1212   }
1213
1214
1215   /* From the ARB_multi_draw_indirect specification:
1216    * "<stride> must be a multiple of four, otherwise an INVALID_VALUE
1217    *  error is generated."
1218    */
1219   if (stride % 4) {
1220      _mesa_error(ctx, GL_INVALID_VALUE, "%s(stride %% 4)", name);
1221      return GL_FALSE;
1222   }
1223
1224   return GL_TRUE;
1225}
1226
1227GLboolean
1228_mesa_validate_DrawArraysIndirect(struct gl_context *ctx,
1229                                  GLenum mode,
1230                                  const GLvoid *indirect)
1231{
1232   const unsigned drawArraysNumParams = 4;
1233
1234   return valid_draw_indirect(ctx, mode,
1235                              indirect, drawArraysNumParams * sizeof(GLuint),
1236                              "glDrawArraysIndirect");
1237}
1238
1239GLboolean
1240_mesa_validate_DrawElementsIndirect(struct gl_context *ctx,
1241                                    GLenum mode, GLenum type,
1242                                    const GLvoid *indirect)
1243{
1244   const unsigned drawElementsNumParams = 5;
1245
1246   return valid_draw_indirect_elements(ctx, mode, type,
1247                                       indirect, drawElementsNumParams * sizeof(GLuint),
1248                                       "glDrawElementsIndirect");
1249}
1250
1251GLboolean
1252_mesa_validate_MultiDrawArraysIndirect(struct gl_context *ctx,
1253                                       GLenum mode,
1254                                       const GLvoid *indirect,
1255                                       GLsizei primcount, GLsizei stride)
1256{
1257   GLsizeiptr size = 0;
1258   const unsigned drawArraysNumParams = 4;
1259
1260   /* caller has converted stride==0 to drawArraysNumParams * sizeof(GLuint) */
1261   assert(stride != 0);
1262
1263   if (!_mesa_valid_draw_indirect_multi(ctx, primcount, stride,
1264                                        "glMultiDrawArraysIndirect"))
1265      return GL_FALSE;
1266
1267   /* number of bytes of the indirect buffer which will be read */
1268   size = primcount
1269      ? (primcount - 1) * stride + drawArraysNumParams * sizeof(GLuint)
1270      : 0;
1271
1272   if (!valid_draw_indirect(ctx, mode, indirect, size,
1273                            "glMultiDrawArraysIndirect"))
1274      return GL_FALSE;
1275
1276   return GL_TRUE;
1277}
1278
1279GLboolean
1280_mesa_validate_MultiDrawElementsIndirect(struct gl_context *ctx,
1281                                         GLenum mode, GLenum type,
1282                                         const GLvoid *indirect,
1283                                         GLsizei primcount, GLsizei stride)
1284{
1285   GLsizeiptr size = 0;
1286   const unsigned drawElementsNumParams = 5;
1287
1288   /* caller has converted stride==0 to drawElementsNumParams * sizeof(GLuint) */
1289   assert(stride != 0);
1290
1291   if (!_mesa_valid_draw_indirect_multi(ctx, primcount, stride,
1292                                        "glMultiDrawElementsIndirect"))
1293      return GL_FALSE;
1294
1295   /* number of bytes of the indirect buffer which will be read */
1296   size = primcount
1297      ? (primcount - 1) * stride + drawElementsNumParams * sizeof(GLuint)
1298      : 0;
1299
1300   if (!valid_draw_indirect_elements(ctx, mode, type,
1301                                     indirect, size,
1302                                     "glMultiDrawElementsIndirect"))
1303      return GL_FALSE;
1304
1305   return GL_TRUE;
1306}
1307
1308static GLboolean
1309valid_draw_indirect_parameters(struct gl_context *ctx,
1310                               const char *name,
1311                               GLintptr drawcount)
1312{
1313   /* From the ARB_indirect_parameters specification:
1314    * "INVALID_VALUE is generated by MultiDrawArraysIndirectCountARB or
1315    *  MultiDrawElementsIndirectCountARB if <drawcount> is not a multiple of
1316    *  four."
1317    */
1318   if (drawcount & 3) {
1319      _mesa_error(ctx, GL_INVALID_VALUE,
1320                  "%s(drawcount is not a multiple of 4)", name);
1321      return GL_FALSE;
1322   }
1323
1324   /* From the ARB_indirect_parameters specification:
1325    * "INVALID_OPERATION is generated by MultiDrawArraysIndirectCountARB or
1326    *  MultiDrawElementsIndirectCountARB if no buffer is bound to the
1327    *  PARAMETER_BUFFER_ARB binding point."
1328    */
1329   if (!_mesa_is_bufferobj(ctx->ParameterBuffer)) {
1330      _mesa_error(ctx, GL_INVALID_OPERATION,
1331                  "%s: no buffer bound to PARAMETER_BUFFER", name);
1332      return GL_FALSE;
1333   }
1334
1335   if (_mesa_check_disallowed_mapping(ctx->ParameterBuffer)) {
1336      _mesa_error(ctx, GL_INVALID_OPERATION,
1337                  "%s(PARAMETER_BUFFER is mapped)", name);
1338      return GL_FALSE;
1339   }
1340
1341   /* From the ARB_indirect_parameters specification:
1342    * "INVALID_OPERATION is generated by MultiDrawArraysIndirectCountARB or
1343    *  MultiDrawElementsIndirectCountARB if reading a <sizei> typed value
1344    *  from the buffer bound to the PARAMETER_BUFFER_ARB target at the offset
1345    *  specified by <drawcount> would result in an out-of-bounds access."
1346    */
1347   if (ctx->ParameterBuffer->Size < drawcount + sizeof(GLsizei)) {
1348      _mesa_error(ctx, GL_INVALID_OPERATION,
1349                  "%s(PARAMETER_BUFFER too small)", name);
1350      return GL_FALSE;
1351   }
1352
1353   return GL_TRUE;
1354}
1355
1356GLboolean
1357_mesa_validate_MultiDrawArraysIndirectCount(struct gl_context *ctx,
1358                                            GLenum mode,
1359                                            GLintptr indirect,
1360                                            GLintptr drawcount,
1361                                            GLsizei maxdrawcount,
1362                                            GLsizei stride)
1363{
1364   GLsizeiptr size = 0;
1365   const unsigned drawArraysNumParams = 4;
1366
1367   /* caller has converted stride==0 to drawArraysNumParams * sizeof(GLuint) */
1368   assert(stride != 0);
1369
1370   if (!_mesa_valid_draw_indirect_multi(ctx, maxdrawcount, stride,
1371                                        "glMultiDrawArraysIndirectCountARB"))
1372      return GL_FALSE;
1373
1374   /* number of bytes of the indirect buffer which will be read */
1375   size = maxdrawcount
1376      ? (maxdrawcount - 1) * stride + drawArraysNumParams * sizeof(GLuint)
1377      : 0;
1378
1379   if (!valid_draw_indirect(ctx, mode, (void *)indirect, size,
1380                            "glMultiDrawArraysIndirectCountARB"))
1381      return GL_FALSE;
1382
1383   return valid_draw_indirect_parameters(
1384         ctx, "glMultiDrawArraysIndirectCountARB", drawcount);
1385}
1386
1387GLboolean
1388_mesa_validate_MultiDrawElementsIndirectCount(struct gl_context *ctx,
1389                                              GLenum mode, GLenum type,
1390                                              GLintptr indirect,
1391                                              GLintptr drawcount,
1392                                              GLsizei maxdrawcount,
1393                                              GLsizei stride)
1394{
1395   GLsizeiptr size = 0;
1396   const unsigned drawElementsNumParams = 5;
1397
1398   /* caller has converted stride==0 to drawElementsNumParams * sizeof(GLuint) */
1399   assert(stride != 0);
1400
1401   if (!_mesa_valid_draw_indirect_multi(ctx, maxdrawcount, stride,
1402                                        "glMultiDrawElementsIndirectCountARB"))
1403      return GL_FALSE;
1404
1405   /* number of bytes of the indirect buffer which will be read */
1406   size = maxdrawcount
1407      ? (maxdrawcount - 1) * stride + drawElementsNumParams * sizeof(GLuint)
1408      : 0;
1409
1410   if (!valid_draw_indirect_elements(ctx, mode, type,
1411                                     (void *)indirect, size,
1412                                     "glMultiDrawElementsIndirectCountARB"))
1413      return GL_FALSE;
1414
1415   return valid_draw_indirect_parameters(
1416         ctx, "glMultiDrawElementsIndirectCountARB", drawcount);
1417}
1418