• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 /**
26  * \file program.c
27  * Vertex and fragment program support functions.
28  * \author Brian Paul
29  */
30 
31 
32 #include "util/glheader.h"
33 #include "main/context.h"
34 #include "main/framebuffer.h"
35 #include "main/hash.h"
36 #include "main/macros.h"
37 #include "main/shaderobj.h"
38 #include "main/state.h"
39 #include "program.h"
40 #include "prog_cache.h"
41 #include "prog_parameter.h"
42 #include "prog_instruction.h"
43 #include "util/bitscan.h"
44 #include "util/ralloc.h"
45 #include "util/u_atomic.h"
46 
47 #include "state_tracker/st_program.h"
48 #include "state_tracker/st_context.h"
49 
50 /**
51  * A pointer to this dummy program is put into the hash table when
52  * glGenPrograms is called.
53  */
54 struct gl_program _mesa_DummyProgram;
55 
56 
57 /**
58  * Init context's vertex/fragment program state
59  */
60 void
_mesa_init_program(struct gl_context * ctx)61 _mesa_init_program(struct gl_context *ctx)
62 {
63    /*
64     * If this assertion fails, we need to increase the field
65     * size for register indexes (see INST_INDEX_BITS).
66     */
67    assert(ctx->Const.Program[MESA_SHADER_VERTEX].MaxUniformComponents / 4
68           <= (1 << INST_INDEX_BITS));
69    assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxUniformComponents / 4
70           <= (1 << INST_INDEX_BITS));
71 
72    assert(ctx->Const.Program[MESA_SHADER_VERTEX].MaxTemps <= (1 << INST_INDEX_BITS));
73    assert(ctx->Const.Program[MESA_SHADER_VERTEX].MaxLocalParams <= (1 << INST_INDEX_BITS));
74    assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTemps <= (1 << INST_INDEX_BITS));
75    assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxLocalParams <= (1 << INST_INDEX_BITS));
76 
77    assert(ctx->Const.Program[MESA_SHADER_VERTEX].MaxUniformComponents <= 4 * MAX_UNIFORMS);
78    assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxUniformComponents <= 4 * MAX_UNIFORMS);
79 
80    assert(ctx->Const.Program[MESA_SHADER_VERTEX].MaxAddressOffset <= (1 << INST_INDEX_BITS));
81    assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxAddressOffset <= (1 << INST_INDEX_BITS));
82 
83    /* If this fails, increase prog_instruction::TexSrcUnit size */
84    STATIC_ASSERT(MAX_TEXTURE_UNITS <= (1 << 5));
85 
86    /* If this fails, increase prog_instruction::TexSrcTarget size */
87    STATIC_ASSERT(NUM_TEXTURE_TARGETS <= (1 << 4));
88 
89    ctx->Program.ErrorPos = -1;
90    ctx->Program.ErrorString = strdup("");
91 
92    ctx->VertexProgram._VaryingInputs = VERT_BIT_ALL;
93    ctx->VertexProgram.Enabled = GL_FALSE;
94    ctx->VertexProgram.PointSizeEnabled =
95       _mesa_is_gles2(ctx) ? GL_TRUE : GL_FALSE;
96    ctx->VertexProgram.TwoSideEnabled = GL_FALSE;
97    _mesa_reference_program(ctx, &ctx->VertexProgram.Current,
98                            ctx->Shared->DefaultVertexProgram);
99    assert(ctx->VertexProgram.Current);
100    ctx->VertexProgram.Cache = _mesa_new_program_cache();
101 
102    ctx->FragmentProgram.Enabled = GL_FALSE;
103    _mesa_reference_program(ctx, &ctx->FragmentProgram.Current,
104                            ctx->Shared->DefaultFragmentProgram);
105    assert(ctx->FragmentProgram.Current);
106    ctx->FragmentProgram.Cache = _mesa_new_program_cache();
107    _mesa_reset_vertex_processing_mode(ctx);
108 
109    /* XXX probably move this stuff */
110    ctx->ATIFragmentShader.Enabled = GL_FALSE;
111    ctx->ATIFragmentShader.Current = ctx->Shared->DefaultFragmentShader;
112    assert(ctx->ATIFragmentShader.Current);
113    ctx->ATIFragmentShader.Current->RefCount++;
114 }
115 
116 
117 /**
118  * Free a context's vertex/fragment program state
119  */
120 void
_mesa_free_program_data(struct gl_context * ctx)121 _mesa_free_program_data(struct gl_context *ctx)
122 {
123    _mesa_reference_program(ctx, &ctx->VertexProgram.Current, NULL);
124    _mesa_delete_program_cache(ctx, ctx->VertexProgram.Cache);
125    _mesa_reference_program(ctx, &ctx->FragmentProgram.Current, NULL);
126    _mesa_delete_program_cache(ctx, ctx->FragmentProgram.Cache);
127 
128    /* XXX probably move this stuff */
129    if (ctx->ATIFragmentShader.Current) {
130       ctx->ATIFragmentShader.Current->RefCount--;
131       if (ctx->ATIFragmentShader.Current->RefCount <= 0) {
132          free(ctx->ATIFragmentShader.Current);
133       }
134    }
135 
136    free((void *) ctx->Program.ErrorString);
137 }
138 
139 
140 /**
141  * Update the default program objects in the given context to reference those
142  * specified in the shared state and release those referencing the old
143  * shared state.
144  */
145 void
_mesa_update_default_objects_program(struct gl_context * ctx)146 _mesa_update_default_objects_program(struct gl_context *ctx)
147 {
148    _mesa_reference_program(ctx, &ctx->VertexProgram.Current,
149                            ctx->Shared->DefaultVertexProgram);
150    assert(ctx->VertexProgram.Current);
151 
152    _mesa_reference_program(ctx, &ctx->FragmentProgram.Current,
153                             ctx->Shared->DefaultFragmentProgram);
154    assert(ctx->FragmentProgram.Current);
155 
156    /* XXX probably move this stuff */
157    if (ctx->ATIFragmentShader.Current) {
158       ctx->ATIFragmentShader.Current->RefCount--;
159       if (ctx->ATIFragmentShader.Current->RefCount <= 0) {
160          free(ctx->ATIFragmentShader.Current);
161       }
162    }
163    ctx->ATIFragmentShader.Current = (struct ati_fragment_shader *) ctx->Shared->DefaultFragmentShader;
164    assert(ctx->ATIFragmentShader.Current);
165    ctx->ATIFragmentShader.Current->RefCount++;
166 }
167 
168 
169 /**
170  * Set the vertex/fragment program error state (position and error string).
171  * This is generally called from within the parsers.
172  */
173 void
_mesa_set_program_error(struct gl_context * ctx,GLint pos,const char * string)174 _mesa_set_program_error(struct gl_context *ctx, GLint pos, const char *string)
175 {
176    ctx->Program.ErrorPos = pos;
177    free((void *) ctx->Program.ErrorString);
178    if (!string)
179       string = "";
180    ctx->Program.ErrorString = strdup(string);
181 }
182 
183 
184 /**
185  * Initialize a new gl_program object.
186  */
187 struct gl_program *
_mesa_init_gl_program(struct gl_program * prog,gl_shader_stage stage,GLuint id,bool is_arb_asm)188 _mesa_init_gl_program(struct gl_program *prog, gl_shader_stage stage,
189                       GLuint id, bool is_arb_asm)
190 {
191    if (!prog)
192       return NULL;
193 
194    memset(prog, 0, sizeof(*prog));
195    prog->Id = id;
196    prog->Target = _mesa_shader_stage_to_program(stage);
197    prog->RefCount = 1;
198    prog->Format = GL_PROGRAM_FORMAT_ASCII_ARB;
199    prog->info.stage = stage;
200    prog->info.use_legacy_math_rules = is_arb_asm;
201 
202    /* Uniforms that lack an initializer in the shader code have an initial
203     * value of zero.  This includes sampler uniforms.
204     *
205     * Page 24 (page 30 of the PDF) of the GLSL 1.20 spec says:
206     *
207     *     "The link time initial value is either the value of the variable's
208     *     initializer, if present, or 0 if no initializer is present. Sampler
209     *     types cannot have initializers."
210     *
211     * So we only initialise ARB assembly style programs.
212     */
213    if (is_arb_asm) {
214       /* default mapping from samplers to texture units */
215       for (unsigned i = 0; i < MAX_SAMPLERS; i++)
216          prog->SamplerUnits[i] = i;
217    }
218 
219    return prog;
220 }
221 
222 struct gl_program *
_mesa_new_program(struct gl_context * ctx,gl_shader_stage stage,GLuint id,bool is_arb_asm)223 _mesa_new_program(struct gl_context *ctx, gl_shader_stage stage, GLuint id,
224                   bool is_arb_asm)
225 {
226    struct gl_program *prog;
227 
228    switch (stage) {
229    case MESA_SHADER_VERTEX:
230       prog = (struct gl_program*)rzalloc(NULL, struct gl_vertex_program);
231       break;
232    default:
233       prog = rzalloc(NULL, struct gl_program);
234       break;
235    }
236 
237    return _mesa_init_gl_program(prog, stage, id, is_arb_asm);
238 }
239 
240 /**
241  * Delete a program and remove it from the hash table, ignoring the
242  * reference count.
243  */
244 void
_mesa_delete_program(struct gl_context * ctx,struct gl_program * prog)245 _mesa_delete_program(struct gl_context *ctx, struct gl_program *prog)
246 {
247    struct st_context *st = st_context(ctx);
248    assert(prog);
249    assert(prog->RefCount==0);
250 
251    st_release_variants(st, prog);
252 
253    free(prog->serialized_nir);
254 
255    if (prog == &_mesa_DummyProgram)
256       return;
257 
258    if (prog->Parameters) {
259       _mesa_free_parameter_list(prog->Parameters);
260    }
261 
262    if (prog->nir) {
263       ralloc_free(prog->nir);
264    }
265 
266    if (prog->sh.BindlessSamplers) {
267       ralloc_free(prog->sh.BindlessSamplers);
268    }
269 
270    if (prog->sh.BindlessImages) {
271       ralloc_free(prog->sh.BindlessImages);
272    }
273 
274    if (prog->driver_cache_blob) {
275       ralloc_free(prog->driver_cache_blob);
276    }
277 
278    ralloc_free(prog);
279 }
280 
281 
282 /**
283  * Return the gl_program object for a given ID.
284  * Basically just a wrapper for _mesa_HashLookup() to avoid a lot of
285  * casts elsewhere.
286  */
287 struct gl_program *
_mesa_lookup_program(struct gl_context * ctx,GLuint id)288 _mesa_lookup_program(struct gl_context *ctx, GLuint id)
289 {
290    if (id)
291       return (struct gl_program *) _mesa_HashLookup(&ctx->Shared->Programs, id);
292    else
293       return NULL;
294 }
295 
296 
297 /**
298  * Reference counting for vertex/fragment programs
299  * This is normally only called from the _mesa_reference_program() macro
300  * when there's a real pointer change.
301  */
302 void
_mesa_reference_program_(struct gl_context * ctx,struct gl_program ** ptr,struct gl_program * prog)303 _mesa_reference_program_(struct gl_context *ctx,
304                          struct gl_program **ptr,
305                          struct gl_program *prog)
306 {
307 #ifndef NDEBUG
308    assert(ptr);
309    if (*ptr && prog) {
310       /* sanity check */
311       if ((*ptr)->Target == GL_VERTEX_PROGRAM_ARB)
312          assert(prog->Target == GL_VERTEX_PROGRAM_ARB);
313       else if ((*ptr)->Target == GL_FRAGMENT_PROGRAM_ARB)
314          assert(prog->Target == GL_FRAGMENT_PROGRAM_ARB ||
315                 prog->Target == GL_FRAGMENT_PROGRAM_NV);
316       else if ((*ptr)->Target == GL_GEOMETRY_PROGRAM_NV)
317          assert(prog->Target == GL_GEOMETRY_PROGRAM_NV);
318    }
319 #endif
320 
321    if (*ptr) {
322       struct gl_program *oldProg = *ptr;
323 
324       assert(oldProg->RefCount > 0);
325 
326       if (p_atomic_dec_zero(&oldProg->RefCount)) {
327          assert(ctx);
328          _mesa_reference_shader_program_data(&oldProg->sh.data, NULL);
329          _mesa_delete_program(ctx, oldProg);
330       }
331 
332       *ptr = NULL;
333    }
334 
335    assert(!*ptr);
336    if (prog) {
337       p_atomic_inc(&prog->RefCount);
338    }
339 
340    *ptr = prog;
341 }
342 
343 /* Gets the minimum number of shader invocations per fragment.
344  * This function is useful to determine if we need to do per
345  * sample shading or per fragment shading.
346  */
347 GLint
_mesa_get_min_invocations_per_fragment(struct gl_context * ctx,const struct gl_program * prog)348 _mesa_get_min_invocations_per_fragment(struct gl_context *ctx,
349                                        const struct gl_program *prog)
350 {
351    /* From ARB_sample_shading specification:
352     * "Using gl_SampleID in a fragment shader causes the entire shader
353     *  to be evaluated per-sample."
354     *
355     * "Using gl_SamplePosition in a fragment shader causes the entire
356     *  shader to be evaluated per-sample."
357     *
358     * "If MULTISAMPLE or SAMPLE_SHADING_ARB is disabled, sample shading
359     *  has no effect."
360     */
361    if (ctx->Multisample.Enabled) {
362       /* The ARB_gpu_shader5 specification says:
363        *
364        * "Use of the "sample" qualifier on a fragment shader input
365        *  forces per-sample shading"
366        */
367       if (prog->info.fs.uses_sample_qualifier ||
368           BITSET_TEST(prog->info.system_values_read, SYSTEM_VALUE_SAMPLE_ID) ||
369           BITSET_TEST(prog->info.system_values_read, SYSTEM_VALUE_SAMPLE_POS))
370          return MAX2(_mesa_geometric_samples(ctx->DrawBuffer), 1);
371       else if (ctx->Multisample.SampleShading)
372          return MAX2(ceilf(ctx->Multisample.MinSampleShadingValue *
373                           _mesa_geometric_samples(ctx->DrawBuffer)), 1);
374       else
375          return 1;
376    }
377    return 1;
378 }
379 
380 
381 GLbitfield
gl_external_samplers(const struct gl_program * prog)382 gl_external_samplers(const struct gl_program *prog)
383 {
384    GLbitfield external_samplers = 0;
385    GLbitfield mask = prog->SamplersUsed;
386 
387    while (mask) {
388       int idx = u_bit_scan(&mask);
389       if (prog->sh.SamplerTargets[idx] == TEXTURE_EXTERNAL_INDEX)
390          external_samplers |= (1 << idx);
391    }
392 
393    return external_samplers;
394 }
395 
compare_state_var(const void * a1,const void * a2)396 static int compare_state_var(const void *a1, const void *a2)
397 {
398    const struct gl_program_parameter *p1 =
399       (const struct gl_program_parameter *)a1;
400    const struct gl_program_parameter *p2 =
401       (const struct gl_program_parameter *)a2;
402 
403    for (unsigned i = 0; i < STATE_LENGTH; i++) {
404       if (p1->StateIndexes[i] != p2->StateIndexes[i])
405          return p1->StateIndexes[i] - p2->StateIndexes[i];
406    }
407    return 0;
408 }
409 
410 void
_mesa_add_separate_state_parameters(struct gl_program * prog,struct gl_program_parameter_list * state_params)411 _mesa_add_separate_state_parameters(struct gl_program *prog,
412                                     struct gl_program_parameter_list *state_params)
413 {
414    unsigned num_state_params = state_params->NumParameters;
415 
416    /* All state parameters should be vec4s. */
417    for (unsigned i = 0; i < num_state_params; i++) {
418       assert(state_params->Parameters[i].Type == PROGRAM_STATE_VAR);
419       assert(state_params->Parameters[i].Size == 4);
420       assert(state_params->Parameters[i].ValueOffset == i * 4);
421    }
422 
423    /* Sort state parameters to facilitate better parameter merging. */
424    qsort(state_params->Parameters, num_state_params,
425          sizeof(state_params->Parameters[0]), compare_state_var);
426    unsigned *remap = malloc(num_state_params * sizeof(unsigned));
427 
428    /* Add state parameters to the end of the parameter list. */
429    for (unsigned i = 0; i < num_state_params; i++) {
430       unsigned old_index = state_params->Parameters[i].ValueOffset / 4;
431 
432       remap[old_index] =
433          _mesa_add_parameter(prog->Parameters, PROGRAM_STATE_VAR,
434                              state_params->Parameters[i].Name,
435                              state_params->Parameters[i].Size,
436                              GL_NONE, NULL,
437                              state_params->Parameters[i].StateIndexes,
438                              state_params->Parameters[i].Padded);
439 
440       prog->Parameters->StateFlags |=
441          _mesa_program_state_flags(state_params->Parameters[i].StateIndexes);
442    }
443 
444    /* Fix up state parameter offsets in instructions. */
445    int num_instr = prog->arb.NumInstructions;
446    struct prog_instruction *instrs = prog->arb.Instructions;
447 
448    /* Fix src indices after sorting. */
449    for (unsigned i = 0; i < num_instr; i++) {
450       struct prog_instruction *inst = instrs + i;
451       unsigned num_src = _mesa_num_inst_src_regs(inst->Opcode);
452 
453       for (unsigned j = 0; j < num_src; j++) {
454          if (inst->SrcReg[j].File == PROGRAM_STATE_VAR)
455             inst->SrcReg[j].Index = remap[inst->SrcReg[j].Index];
456       }
457    }
458    free(remap);
459 }
460