06d30bfb38b477c19a37c0d525bb282a6d691ba7
[mesa.git] / src / gallium / docs / source / context.rst
1 .. _context:
2
3 Context
4 =======
5
6 A Gallium rendering context encapsulates the state which effects 3D
7 rendering such as blend state, depth/stencil state, texture samplers,
8 etc.
9
10 Note that resource/texture allocation is not per-context but per-screen.
11
12
13 Methods
14 -------
15
16 CSO State
17 ^^^^^^^^^
18
19 All Constant State Object (CSO) state is created, bound, and destroyed,
20 with triplets of methods that all follow a specific naming scheme.
21 For example, ``create_blend_state``, ``bind_blend_state``, and
22 ``destroy_blend_state``.
23
24 CSO objects handled by the context object:
25
26 * :ref:`Blend`: ``*_blend_state``
27 * :ref:`Sampler`: Texture sampler states are bound separately for fragment,
28 vertex, geometry and compute shaders with the ``bind_sampler_states``
29 function. The ``start`` and ``num_samplers`` parameters indicate a range
30 of samplers to change. NOTE: at this time, start is always zero and
31 the CSO module will always replace all samplers at once (no sub-ranges).
32 This may change in the future.
33 * :ref:`Rasterizer`: ``*_rasterizer_state``
34 * :ref:`depth-stencil-alpha`: ``*_depth_stencil_alpha_state``
35 * :ref:`Shader`: These are create, bind and destroy methods for vertex,
36 fragment and geometry shaders.
37 * :ref:`vertexelements`: ``*_vertex_elements_state``
38
39
40 Resource Binding State
41 ^^^^^^^^^^^^^^^^^^^^^^
42
43 This state describes how resources in various flavours (textures,
44 buffers, surfaces) are bound to the driver.
45
46
47 * ``set_constant_buffer`` sets a constant buffer to be used for a given shader
48 type. index is used to indicate which buffer to set (some apis may allow
49 multiple ones to be set, and binding a specific one later, though drivers
50 are mostly restricted to the first one right now).
51
52 * ``set_framebuffer_state``
53
54 * ``set_vertex_buffers``
55
56
57 Non-CSO State
58 ^^^^^^^^^^^^^
59
60 These pieces of state are too small, variable, and/or trivial to have CSO
61 objects. They all follow simple, one-method binding calls, e.g.
62 ``set_blend_color``.
63
64 * ``set_stencil_ref`` sets the stencil front and back reference values
65 which are used as comparison values in stencil test.
66 * ``set_blend_color``
67 * ``set_sample_mask`` sets the per-context multisample sample mask. Note
68 that this takes effect even if multisampling is not explicitly enabled if
69 the frambuffer surface(s) are multisampled. Also, this mask is AND-ed
70 with the optional fragment shader sample mask output (when emitted).
71 * ``set_sample_locations`` sets the sample locations used for rasterization.
72 ```get_sample_position``` still returns the default locations. When NULL,
73 the default locations are used.
74 * ``set_min_samples`` sets the minimum number of samples that must be run.
75 * ``set_clip_state``
76 * ``set_polygon_stipple``
77 * ``set_scissor_states`` sets the bounds for the scissor test, which culls
78 pixels before blending to render targets. If the :ref:`Rasterizer` does
79 not have the scissor test enabled, then the scissor bounds never need to
80 be set since they will not be used. Note that scissor xmin and ymin are
81 inclusive, but xmax and ymax are exclusive. The inclusive ranges in x
82 and y would be [xmin..xmax-1] and [ymin..ymax-1]. The number of scissors
83 should be the same as the number of set viewports and can be up to
84 PIPE_MAX_VIEWPORTS.
85 * ``set_viewport_states``
86 * ``set_window_rectangles`` sets the window rectangles to be used for
87 rendering, as defined by GL_EXT_window_rectangles. There are two
88 modes - include and exclude, which define whether the supplied
89 rectangles are to be used for including fragments or excluding
90 them. All of the rectangles are ORed together, so in exclude mode,
91 any fragment inside any rectangle would be culled, while in include
92 mode, any fragment outside all rectangles would be culled. xmin/ymin
93 are inclusive, while xmax/ymax are exclusive (same as scissor states
94 above). Note that this only applies to draws, not clears or
95 blits. (Blits have their own way to pass the requisite rectangles
96 in.)
97 * ``set_tess_state`` configures the default tessellation parameters:
98
99 * ``default_outer_level`` is the default value for the outer tessellation
100 levels. This corresponds to GL's ``PATCH_DEFAULT_OUTER_LEVEL``.
101 * ``default_inner_level`` is the default value for the inner tessellation
102 levels. This corresponds to GL's ``PATCH_DEFAULT_INNER_LEVEL``.
103
104 * ``set_debug_callback`` sets the callback to be used for reporting
105 various debug messages, eventually reported via KHR_debug and
106 similar mechanisms.
107
108 Samplers
109 ^^^^^^^^
110
111 pipe_sampler_state objects control how textures are sampled (coordinate
112 wrap modes, interpolation modes, etc). Note that samplers are not used
113 for texture buffer objects. That is, pipe_context::bind_sampler_views()
114 will not bind a sampler if the corresponding sampler view refers to a
115 PIPE_BUFFER resource.
116
117 Sampler Views
118 ^^^^^^^^^^^^^
119
120 These are the means to bind textures to shader stages. To create one, specify
121 its format, swizzle and LOD range in sampler view template.
122
123 If texture format is different than template format, it is said the texture
124 is being cast to another format. Casting can be done only between compatible
125 formats, that is formats that have matching component order and sizes.
126
127 Swizzle fields specify the way in which fetched texel components are placed
128 in the result register. For example, ``swizzle_r`` specifies what is going to be
129 placed in first component of result register.
130
131 The ``first_level`` and ``last_level`` fields of sampler view template specify
132 the LOD range the texture is going to be constrained to. Note that these
133 values are in addition to the respective min_lod, max_lod values in the
134 pipe_sampler_state (that is if min_lod is 2.0, and first_level 3, the first mip
135 level used for sampling from the resource is effectively the fifth).
136
137 The ``first_layer`` and ``last_layer`` fields specify the layer range the
138 texture is going to be constrained to. Similar to the LOD range, this is added
139 to the array index which is used for sampling.
140
141 * ``set_sampler_views`` binds an array of sampler views to a shader stage.
142 Every binding point acquires a reference
143 to a respective sampler view and releases a reference to the previous
144 sampler view.
145
146 Sampler views outside of ``[start_slot, start_slot + num_views)`` are
147 unmodified. If ``views`` is NULL, the behavior is the same as if
148 ``views[n]`` was NULL for the entire range, ie. releasing the reference
149 for all the sampler views in the specified range.
150
151 * ``create_sampler_view`` creates a new sampler view. ``texture`` is associated
152 with the sampler view which results in sampler view holding a reference
153 to the texture. Format specified in template must be compatible
154 with texture format.
155
156 * ``sampler_view_destroy`` destroys a sampler view and releases its reference
157 to associated texture.
158
159 Hardware Atomic buffers
160 ^^^^^^^^^^^^^^^^^^^^^^^
161
162 Buffers containing hw atomics are required to support the feature
163 on some drivers.
164
165 Drivers that require this need to fill the ``set_hw_atomic_buffers`` method.
166
167 Shader Resources
168 ^^^^^^^^^^^^^^^^
169
170 Shader resources are textures or buffers that may be read or written
171 from a shader without an associated sampler. This means that they
172 have no support for floating point coordinates, address wrap modes or
173 filtering.
174
175 There are 2 types of shader resources: buffers and images.
176
177 Buffers are specified using the ``set_shader_buffers`` method.
178
179 Images are specified using the ``set_shader_images`` method. When binding
180 images, the ``level``, ``first_layer`` and ``last_layer`` pipe_image_view
181 fields specify the mipmap level and the range of layers the image will be
182 constrained to.
183
184 Surfaces
185 ^^^^^^^^
186
187 These are the means to use resources as color render targets or depthstencil
188 attachments. To create one, specify the mip level, the range of layers, and
189 the bind flags (either PIPE_BIND_DEPTH_STENCIL or PIPE_BIND_RENDER_TARGET).
190 Note that layer values are in addition to what is indicated by the geometry
191 shader output variable XXX_FIXME (that is if first_layer is 3 and geometry
192 shader indicates index 2, the 5th layer of the resource will be used). These
193 first_layer and last_layer parameters will only be used for 1d array, 2d array,
194 cube, and 3d textures otherwise they are 0.
195
196 * ``create_surface`` creates a new surface.
197
198 * ``surface_destroy`` destroys a surface and releases its reference to the
199 associated resource.
200
201 Stream output targets
202 ^^^^^^^^^^^^^^^^^^^^^
203
204 Stream output, also known as transform feedback, allows writing the primitives
205 produced by the vertex pipeline to buffers. This is done after the geometry
206 shader or vertex shader if no geometry shader is present.
207
208 The stream output targets are views into buffer resources which can be bound
209 as stream outputs and specify a memory range where it's valid to write
210 primitives. The pipe driver must implement memory protection such that any
211 primitives written outside of the specified memory range are discarded.
212
213 Two stream output targets can use the same resource at the same time, but
214 with a disjoint memory range.
215
216 Additionally, the stream output target internally maintains the offset
217 into the buffer which is incremented everytime something is written to it.
218 The internal offset is equal to how much data has already been written.
219 It can be stored in device memory and the CPU actually doesn't have to query
220 it.
221
222 The stream output target can be used in a draw command to provide
223 the vertex count. The vertex count is derived from the internal offset
224 discussed above.
225
226 * ``create_stream_output_target`` create a new target.
227
228 * ``stream_output_target_destroy`` destroys a target. Users of this should
229 use pipe_so_target_reference instead.
230
231 * ``set_stream_output_targets`` binds stream output targets. The parameter
232 offset is an array which specifies the internal offset of the buffer. The
233 internal offset is, besides writing, used for reading the data during the
234 draw_auto stage, i.e. it specifies how much data there is in the buffer
235 for the purposes of the draw_auto stage. -1 means the buffer should
236 be appended to, and everything else sets the internal offset.
237
238 NOTE: The currently-bound vertex or geometry shader must be compiled with
239 the properly-filled-in structure pipe_stream_output_info describing which
240 outputs should be written to buffers and how. The structure is part of
241 pipe_shader_state.
242
243 Clearing
244 ^^^^^^^^
245
246 Clear is one of the most difficult concepts to nail down to a single
247 interface (due to both different requirements from APIs and also driver/hw
248 specific differences).
249
250 ``clear`` initializes some or all of the surfaces currently bound to
251 the framebuffer to particular RGBA, depth, or stencil values.
252 Currently, this does not take into account color or stencil write masks (as
253 used by GL), and always clears the whole surfaces (no scissoring as used by
254 GL clear or explicit rectangles like d3d9 uses). It can, however, also clear
255 only depth or stencil in a combined depth/stencil surface.
256 If a surface includes several layers then all layers will be cleared.
257
258 ``clear_render_target`` clears a single color rendertarget with the specified
259 color value. While it is only possible to clear one surface at a time (which can
260 include several layers), this surface need not be bound to the framebuffer.
261 If render_condition_enabled is false, any current rendering condition is ignored
262 and the clear will be unconditional.
263
264 ``clear_depth_stencil`` clears a single depth, stencil or depth/stencil surface
265 with the specified depth and stencil values (for combined depth/stencil buffers,
266 it is also possible to only clear one or the other part). While it is only
267 possible to clear one surface at a time (which can include several layers),
268 this surface need not be bound to the framebuffer.
269 If render_condition_enabled is false, any current rendering condition is ignored
270 and the clear will be unconditional.
271
272 ``clear_texture`` clears a non-PIPE_BUFFER resource's specified level
273 and bounding box with a clear value provided in that resource's native
274 format.
275
276 ``clear_buffer`` clears a PIPE_BUFFER resource with the specified clear value
277 (which may be multiple bytes in length). Logically this is a memset with a
278 multi-byte element value starting at offset bytes from resource start, going
279 for size bytes. It is guaranteed that size % clear_value_size == 0.
280
281 Evaluating Depth Buffers
282 ^^^^^^^^^^^^^^^^^^^^^^^^
283
284 ``evaluate_depth_buffer`` is a hint to decompress the current depth buffer
285 assuming the current sample locations to avoid problems that could arise when
286 using programmable sample locations.
287
288 If a depth buffer is rendered with different sample location state than
289 what is current at the time of reading the depth buffer, the values may differ
290 because depth buffer compression can depend the sample locations.
291
292
293 Uploading
294 ^^^^^^^^^
295
296 For simple single-use uploads, use ``pipe_context::stream_uploader`` or
297 ``pipe_context::const_uploader``. The latter should be used for uploading
298 constants, while the former should be used for uploading everything else.
299 PIPE_USAGE_STREAM is implied in both cases, so don't use the uploaders
300 for static allocations.
301
302 Usage:
303
304 Call u_upload_alloc or u_upload_data as many times as you want. After you are
305 done, call u_upload_unmap. If the driver doesn't support persistent mappings,
306 u_upload_unmap makes sure the previously mapped memory is unmapped.
307
308 Gotchas:
309 - Always fill the memory immediately after u_upload_alloc. Any following call
310 to u_upload_alloc and u_upload_data can unmap memory returned by previous
311 u_upload_alloc.
312 - Don't interleave calls using stream_uploader and const_uploader. If you use
313 one of them, do the upload, unmap, and only then can you use the other one.
314
315
316 Drawing
317 ^^^^^^^
318
319 ``draw_vbo`` draws a specified primitive. The primitive mode and other
320 properties are described by ``pipe_draw_info``.
321
322 The ``mode``, ``start``, and ``count`` fields of ``pipe_draw_info`` specify the
323 the mode of the primitive and the vertices to be fetched, in the range between
324 ``start`` to ``start``+``count``-1, inclusive.
325
326 Every instance with instanceID in the range between ``start_instance`` and
327 ``start_instance``+``instance_count``-1, inclusive, will be drawn.
328
329 If ``index_size`` != 0, all vertex indices will be looked up from the index
330 buffer.
331
332 In indexed draw, ``min_index`` and ``max_index`` respectively provide a lower
333 and upper bound of the indices contained in the index buffer inside the range
334 between ``start`` to ``start``+``count``-1. This allows the driver to
335 determine which subset of vertices will be referenced during te draw call
336 without having to scan the index buffer. Providing a over-estimation of the
337 the true bounds, for example, a ``min_index`` and ``max_index`` of 0 and
338 0xffffffff respectively, must give exactly the same rendering, albeit with less
339 performance due to unreferenced vertex buffers being unnecessarily DMA'ed or
340 processed. Providing a underestimation of the true bounds will result in
341 undefined behavior, but should not result in program or system failure.
342
343 In case of non-indexed draw, ``min_index`` should be set to
344 ``start`` and ``max_index`` should be set to ``start``+``count``-1.
345
346 ``index_bias`` is a value added to every vertex index after lookup and before
347 fetching vertex attributes.
348
349 When drawing indexed primitives, the primitive restart index can be
350 used to draw disjoint primitive strips. For example, several separate
351 line strips can be drawn by designating a special index value as the
352 restart index. The ``primitive_restart`` flag enables/disables this
353 feature. The ``restart_index`` field specifies the restart index value.
354
355 When primitive restart is in use, array indexes are compared to the
356 restart index before adding the index_bias offset.
357
358 If a given vertex element has ``instance_divisor`` set to 0, it is said
359 it contains per-vertex data and effective vertex attribute address needs
360 to be recalculated for every index.
361
362 attribAddr = ``stride`` * index + ``src_offset``
363
364 If a given vertex element has ``instance_divisor`` set to non-zero,
365 it is said it contains per-instance data and effective vertex attribute
366 address needs to recalculated for every ``instance_divisor``-th instance.
367
368 attribAddr = ``stride`` * instanceID / ``instance_divisor`` + ``src_offset``
369
370 In the above formulas, ``src_offset`` is taken from the given vertex element
371 and ``stride`` is taken from a vertex buffer associated with the given
372 vertex element.
373
374 The calculated attribAddr is used as an offset into the vertex buffer to
375 fetch the attribute data.
376
377 The value of ``instanceID`` can be read in a vertex shader through a system
378 value register declared with INSTANCEID semantic name.
379
380
381 Queries
382 ^^^^^^^
383
384 Queries gather some statistic from the 3D pipeline over one or more
385 draws. Queries may be nested, though not all state trackers exercise this.
386
387 Queries can be created with ``create_query`` and deleted with
388 ``destroy_query``. To start a query, use ``begin_query``, and when finished,
389 use ``end_query`` to end the query.
390
391 ``create_query`` takes a query type (``PIPE_QUERY_*``), as well as an index,
392 which is the vertex stream for ``PIPE_QUERY_PRIMITIVES_GENERATED`` and
393 ``PIPE_QUERY_PRIMITIVES_EMITTED``, and allocates a query structure.
394
395 ``begin_query`` will clear/reset previous query results.
396
397 ``get_query_result`` is used to retrieve the results of a query. If
398 the ``wait`` parameter is TRUE, then the ``get_query_result`` call
399 will block until the results of the query are ready (and TRUE will be
400 returned). Otherwise, if the ``wait`` parameter is FALSE, the call
401 will not block and the return value will be TRUE if the query has
402 completed or FALSE otherwise.
403
404 ``get_query_result_resource`` is used to store the result of a query into
405 a resource without synchronizing with the CPU. This write will optionally
406 wait for the query to complete, and will optionally write whether the value
407 is available instead of the value itself.
408
409 ``set_active_query_state`` Set whether all current non-driver queries except
410 TIME_ELAPSED are active or paused.
411
412 The interface currently includes the following types of queries:
413
414 ``PIPE_QUERY_OCCLUSION_COUNTER`` counts the number of fragments which
415 are written to the framebuffer without being culled by
416 :ref:`depth-stencil-alpha` testing or shader KILL instructions.
417 The result is an unsigned 64-bit integer.
418 This query can be used with ``render_condition``.
419
420 In cases where a boolean result of an occlusion query is enough,
421 ``PIPE_QUERY_OCCLUSION_PREDICATE`` should be used. It is just like
422 ``PIPE_QUERY_OCCLUSION_COUNTER`` except that the result is a boolean
423 value of FALSE for cases where COUNTER would result in 0 and TRUE
424 for all other cases.
425 This query can be used with ``render_condition``.
426
427 In cases where a conservative approximation of an occlusion query is enough,
428 ``PIPE_QUERY_OCCLUSION_PREDICATE_CONSERVATIVE`` should be used. It behaves
429 like ``PIPE_QUERY_OCCLUSION_PREDICATE``, except that it may return TRUE in
430 additional, implementation-dependent cases.
431 This query can be used with ``render_condition``.
432
433 ``PIPE_QUERY_TIME_ELAPSED`` returns the amount of time, in nanoseconds,
434 the context takes to perform operations.
435 The result is an unsigned 64-bit integer.
436
437 ``PIPE_QUERY_TIMESTAMP`` returns a device/driver internal timestamp,
438 scaled to nanoseconds, recorded after all commands issued prior to
439 ``end_query`` have been processed.
440 This query does not require a call to ``begin_query``.
441 The result is an unsigned 64-bit integer.
442
443 ``PIPE_QUERY_TIMESTAMP_DISJOINT`` can be used to check the
444 internal timer resolution and whether the timestamp counter has become
445 unreliable due to things like throttling etc. - only if this is FALSE
446 a timestamp query (within the timestamp_disjoint query) should be trusted.
447 The result is a 64-bit integer specifying the timer resolution in Hz,
448 followed by a boolean value indicating whether the timestamp counter
449 is discontinuous or disjoint.
450
451 ``PIPE_QUERY_PRIMITIVES_GENERATED`` returns a 64-bit integer indicating
452 the number of primitives processed by the pipeline (regardless of whether
453 stream output is active or not).
454
455 ``PIPE_QUERY_PRIMITIVES_EMITTED`` returns a 64-bit integer indicating
456 the number of primitives written to stream output buffers.
457
458 ``PIPE_QUERY_SO_STATISTICS`` returns 2 64-bit integers corresponding to
459 the result of
460 ``PIPE_QUERY_PRIMITIVES_EMITTED`` and
461 the number of primitives that would have been written to stream output buffers
462 if they had infinite space available (primitives_storage_needed), in this order.
463 XXX the 2nd value is equivalent to ``PIPE_QUERY_PRIMITIVES_GENERATED`` but it is
464 unclear if it should be increased if stream output is not active.
465
466 ``PIPE_QUERY_SO_OVERFLOW_PREDICATE`` returns a boolean value indicating
467 whether a selected stream output target has overflowed as a result of the
468 commands issued between ``begin_query`` and ``end_query``.
469 This query can be used with ``render_condition``. The output stream is
470 selected by the stream number passed to ``create_query``.
471
472 ``PIPE_QUERY_SO_OVERFLOW_ANY_PREDICATE`` returns a boolean value indicating
473 whether any stream output target has overflowed as a result of the commands
474 issued between ``begin_query`` and ``end_query``. This query can be used
475 with ``render_condition``, and its result is the logical OR of multiple
476 ``PIPE_QUERY_SO_OVERFLOW_PREDICATE`` queries, one for each stream output
477 target.
478
479 ``PIPE_QUERY_GPU_FINISHED`` returns a boolean value indicating whether
480 all commands issued before ``end_query`` have completed. However, this
481 does not imply serialization.
482 This query does not require a call to ``begin_query``.
483
484 ``PIPE_QUERY_PIPELINE_STATISTICS`` returns an array of the following
485 64-bit integers:
486 Number of vertices read from vertex buffers.
487 Number of primitives read from vertex buffers.
488 Number of vertex shader threads launched.
489 Number of geometry shader threads launched.
490 Number of primitives generated by geometry shaders.
491 Number of primitives forwarded to the rasterizer.
492 Number of primitives rasterized.
493 Number of fragment shader threads launched.
494 Number of tessellation control shader threads launched.
495 Number of tessellation evaluation shader threads launched.
496 If a shader type is not supported by the device/driver,
497 the corresponding values should be set to 0.
498
499 ``PIPE_QUERY_PIPELINE_STATISTICS_SINGLE`` returns a single counter from
500 the ``PIPE_QUERY_PIPELINE_STATISTICS`` group. The specific counter must
501 be selected when calling ``create_query`` by passing one of the
502 ``PIPE_STAT_QUERY`` enums as the query's ``index``.
503
504 Gallium does not guarantee the availability of any query types; one must
505 always check the capabilities of the :ref:`Screen` first.
506
507
508 Conditional Rendering
509 ^^^^^^^^^^^^^^^^^^^^^
510
511 A drawing command can be skipped depending on the outcome of a query
512 (typically an occlusion query, or streamout overflow predicate).
513 The ``render_condition`` function specifies the query which should be checked
514 prior to rendering anything. Functions always honoring render_condition include
515 (and are limited to) draw_vbo and clear.
516 The blit, clear_render_target and clear_depth_stencil functions (but
517 not resource_copy_region, which seems inconsistent) can also optionally honor
518 the current render condition.
519
520 If ``render_condition`` is called with ``query`` = NULL, conditional
521 rendering is disabled and drawing takes place normally.
522
523 If ``render_condition`` is called with a non-null ``query`` subsequent
524 drawing commands will be predicated on the outcome of the query.
525 Commands will be skipped if ``condition`` is equal to the predicate result
526 (for non-boolean queries such as OCCLUSION_QUERY, zero counts as FALSE,
527 non-zero as TRUE).
528
529 If ``mode`` is PIPE_RENDER_COND_WAIT the driver will wait for the
530 query to complete before deciding whether to render.
531
532 If ``mode`` is PIPE_RENDER_COND_NO_WAIT and the query has not yet
533 completed, the drawing command will be executed normally. If the query
534 has completed, drawing will be predicated on the outcome of the query.
535
536 If ``mode`` is PIPE_RENDER_COND_BY_REGION_WAIT or
537 PIPE_RENDER_COND_BY_REGION_NO_WAIT rendering will be predicated as above
538 for the non-REGION modes but in the case that an occlusion query returns
539 a non-zero result, regions which were occluded may be ommitted by subsequent
540 drawing commands. This can result in better performance with some GPUs.
541 Normally, if the occlusion query returned a non-zero result subsequent
542 drawing happens normally so fragments may be generated, shaded and
543 processed even where they're known to be obscured.
544
545
546 Flushing
547 ^^^^^^^^
548
549 ``flush``
550
551 PIPE_FLUSH_END_OF_FRAME: Whether the flush marks the end of frame.
552
553 PIPE_FLUSH_DEFERRED: It is not required to flush right away, but it is required
554 to return a valid fence. If fence_finish is called with the returned fence
555 and the context is still unflushed, and the ctx parameter of fence_finish is
556 equal to the context where the fence was created, fence_finish will flush
557 the context.
558
559 PIPE_FLUSH_ASYNC: The flush is allowed to be asynchronous. Unlike
560 ``PIPE_FLUSH_DEFERRED``, the driver must still ensure that the returned fence
561 will finish in finite time. However, subsequent operations in other contexts of
562 the same screen are no longer guaranteed to happen after the flush. Drivers
563 which use this flag must implement pipe_context::fence_server_sync.
564
565 PIPE_FLUSH_HINT_FINISH: Hints to the driver that the caller will immediately
566 wait for the returned fence.
567
568 Additional flags may be set together with ``PIPE_FLUSH_DEFERRED`` for even
569 finer-grained fences. Note that as a general rule, GPU caches may not have been
570 flushed yet when these fences are signaled. Drivers are free to ignore these
571 flags and create normal fences instead. At most one of the following flags can
572 be specified:
573
574 PIPE_FLUSH_TOP_OF_PIPE: The fence should be signaled as soon as the next
575 command is ready to start executing at the top of the pipeline, before any of
576 its data is actually read (including indirect draw parameters).
577
578 PIPE_FLUSH_BOTTOM_OF_PIPE: The fence should be signaled as soon as the previous
579 command has finished executing on the GPU entirely (but data written by the
580 command may still be in caches and inaccessible to the CPU).
581
582
583 ``flush_resource``
584
585 Flush the resource cache, so that the resource can be used
586 by an external client. Possible usage:
587 - flushing a resource before presenting it on the screen
588 - flushing a resource if some other process or device wants to use it
589 This shouldn't be used to flush caches if the resource is only managed
590 by a single pipe_screen and is not shared with another process.
591 (i.e. you shouldn't use it to flush caches explicitly if you want to e.g.
592 use the resource for texturing)
593
594 Fences
595 ^^^^^^
596
597 ``pipe_fence_handle``, and related methods, are used to synchronize
598 execution between multiple parties. Examples include CPU <-> GPU synchronization,
599 renderer <-> windowing system, multiple external APIs, etc.
600
601 A ``pipe_fence_handle`` can either be 'one time use' or 're-usable'. A 'one time use'
602 fence behaves like a traditional GPU fence. Once it reaches the signaled state it
603 is forever considered to be signaled.
604
605 Once a re-usable ``pipe_fence_handle`` becomes signaled, it can be reset
606 back into an unsignaled state. The ``pipe_fence_handle`` will be reset to
607 the unsignaled state by performing a wait operation on said object, i.e.
608 ``fence_server_sync``. As a corollary to this behaviour, a re-usable
609 ``pipe_fence_handle`` can only have one waiter.
610
611 This behaviour is useful in producer <-> consumer chains. It helps avoid
612 unecessarily sharing a new ``pipe_fence_handle`` each time a new frame is
613 ready. Instead, the fences are exchanged once ahead of time, and access is synchronized
614 through GPU signaling instead of direct producer <-> consumer communication.
615
616 ``fence_server_sync`` inserts a wait command into the GPU's command stream.
617
618 ``fence_server_signal`` inserts a signal command into the GPU's command stream.
619
620 There are no guarantees that the wait/signal commands will be flushed when
621 calling ``fence_server_sync`` or ``fence_server_signal``. An explicit
622 call to ``flush`` is required to make sure the commands are emitted to the GPU.
623
624 The Gallium implementation may implicitly ``flush`` the command stream during a
625 ``fence_server_sync`` or ``fence_server_signal`` call if necessary.
626
627 Resource Busy Queries
628 ^^^^^^^^^^^^^^^^^^^^^
629
630 ``is_resource_referenced``
631
632
633
634 Blitting
635 ^^^^^^^^
636
637 These methods emulate classic blitter controls.
638
639 These methods operate directly on ``pipe_resource`` objects, and stand
640 apart from any 3D state in the context. Blitting functionality may be
641 moved to a separate abstraction at some point in the future.
642
643 ``resource_copy_region`` blits a region of a resource to a region of another
644 resource, provided that both resources have the same format, or compatible
645 formats, i.e., formats for which copying the bytes from the source resource
646 unmodified to the destination resource will achieve the same effect of a
647 textured quad blitter.. The source and destination may be the same resource,
648 but overlapping blits are not permitted.
649 This can be considered the equivalent of a CPU memcpy.
650
651 ``blit`` blits a region of a resource to a region of another resource, including
652 scaling, format conversion, and up-/downsampling, as well as a destination clip
653 rectangle (scissors) and window rectangles. It can also optionally honor the
654 current render condition (but either way the blit itself never contributes
655 anything to queries currently gathering data).
656 As opposed to manually drawing a textured quad, this lets the pipe driver choose
657 the optimal method for blitting (like using a special 2D engine), and usually
658 offers, for example, accelerated stencil-only copies even where
659 PIPE_CAP_SHADER_STENCIL_EXPORT is not available.
660
661
662 Transfers
663 ^^^^^^^^^
664
665 These methods are used to get data to/from a resource.
666
667 ``transfer_map`` creates a memory mapping and the transfer object
668 associated with it.
669 The returned pointer points to the start of the mapped range according to
670 the box region, not the beginning of the resource. If transfer_map fails,
671 the returned pointer to the buffer memory is NULL, and the pointer
672 to the transfer object remains unchanged (i.e. it can be non-NULL).
673
674 ``transfer_unmap`` remove the memory mapping for and destroy
675 the transfer object. The pointer into the resource should be considered
676 invalid and discarded.
677
678 ``texture_subdata`` and ``buffer_subdata`` perform a simplified
679 transfer for simple writes. Basically transfer_map, data write, and
680 transfer_unmap all in one.
681
682
683 The box parameter to some of these functions defines a 1D, 2D or 3D
684 region of pixels. This is self-explanatory for 1D, 2D and 3D texture
685 targets.
686
687 For PIPE_TEXTURE_1D_ARRAY and PIPE_TEXTURE_2D_ARRAY, the box::z and box::depth
688 fields refer to the array dimension of the texture.
689
690 For PIPE_TEXTURE_CUBE, the box:z and box::depth fields refer to the
691 faces of the cube map (z + depth <= 6).
692
693 For PIPE_TEXTURE_CUBE_ARRAY, the box:z and box::depth fields refer to both
694 the face and array dimension of the texture (face = z % 6, array = z / 6).
695
696
697 .. _transfer_flush_region:
698
699 transfer_flush_region
700 %%%%%%%%%%%%%%%%%%%%%
701
702 If a transfer was created with ``FLUSH_EXPLICIT``, it will not automatically
703 be flushed on write or unmap. Flushes must be requested with
704 ``transfer_flush_region``. Flush ranges are relative to the mapped range, not
705 the beginning of the resource.
706
707
708
709 .. _texture_barrier:
710
711 texture_barrier
712 %%%%%%%%%%%%%%%
713
714 This function flushes all pending writes to the currently-set surfaces and
715 invalidates all read caches of the currently-set samplers. This can be used
716 for both regular textures as well as for framebuffers read via FBFETCH.
717
718
719
720 .. _memory_barrier:
721
722 memory_barrier
723 %%%%%%%%%%%%%%%
724
725 This function flushes caches according to which of the PIPE_BARRIER_* flags
726 are set.
727
728
729
730 .. _resource_commit:
731
732 resource_commit
733 %%%%%%%%%%%%%%%
734
735 This function changes the commit state of a part of a sparse resource. Sparse
736 resources are created by setting the ``PIPE_RESOURCE_FLAG_SPARSE`` flag when
737 calling ``resource_create``. Initially, sparse resources only reserve a virtual
738 memory region that is not backed by memory (i.e., it is uncommitted). The
739 ``resource_commit`` function can be called to commit or uncommit parts (or all)
740 of a resource. The driver manages the underlying backing memory.
741
742 The contents of newly committed memory regions are undefined. Calling this
743 function to commit an already committed memory region is allowed and leaves its
744 content unchanged. Similarly, calling this function to uncommit an already
745 uncommitted memory region is allowed.
746
747 For buffers, the given box must be aligned to multiples of
748 ``PIPE_CAP_SPARSE_BUFFER_PAGE_SIZE``. As an exception to this rule, if the size
749 of the buffer is not a multiple of the page size, changing the commit state of
750 the last (partial) page requires a box that ends at the end of the buffer
751 (i.e., box->x + box->width == buffer->width0).
752
753
754
755 .. _pipe_transfer:
756
757 PIPE_TRANSFER
758 ^^^^^^^^^^^^^
759
760 These flags control the behavior of a transfer object.
761
762 ``PIPE_TRANSFER_READ``
763 Resource contents read back (or accessed directly) at transfer create time.
764
765 ``PIPE_TRANSFER_WRITE``
766 Resource contents will be written back at transfer_unmap time (or modified
767 as a result of being accessed directly).
768
769 ``PIPE_TRANSFER_MAP_DIRECTLY``
770 a transfer should directly map the resource. May return NULL if not supported.
771
772 ``PIPE_TRANSFER_DISCARD_RANGE``
773 The memory within the mapped region is discarded. Cannot be used with
774 ``PIPE_TRANSFER_READ``.
775
776 ``PIPE_TRANSFER_DISCARD_WHOLE_RESOURCE``
777 Discards all memory backing the resource. It should not be used with
778 ``PIPE_TRANSFER_READ``.
779
780 ``PIPE_TRANSFER_DONTBLOCK``
781 Fail if the resource cannot be mapped immediately.
782
783 ``PIPE_TRANSFER_UNSYNCHRONIZED``
784 Do not synchronize pending operations on the resource when mapping. The
785 interaction of any writes to the map and any operations pending on the
786 resource are undefined. Cannot be used with ``PIPE_TRANSFER_READ``.
787
788 ``PIPE_TRANSFER_FLUSH_EXPLICIT``
789 Written ranges will be notified later with :ref:`transfer_flush_region`.
790 Cannot be used with ``PIPE_TRANSFER_READ``.
791
792 ``PIPE_TRANSFER_PERSISTENT``
793 Allows the resource to be used for rendering while mapped.
794 PIPE_RESOURCE_FLAG_MAP_PERSISTENT must be set when creating
795 the resource.
796 If COHERENT is not set, memory_barrier(PIPE_BARRIER_MAPPED_BUFFER)
797 must be called to ensure the device can see what the CPU has written.
798
799 ``PIPE_TRANSFER_COHERENT``
800 If PERSISTENT is set, this ensures any writes done by the device are
801 immediately visible to the CPU and vice versa.
802 PIPE_RESOURCE_FLAG_MAP_COHERENT must be set when creating
803 the resource.
804
805 Compute kernel execution
806 ^^^^^^^^^^^^^^^^^^^^^^^^
807
808 A compute program can be defined, bound or destroyed using
809 ``create_compute_state``, ``bind_compute_state`` or
810 ``destroy_compute_state`` respectively.
811
812 Any of the subroutines contained within the compute program can be
813 executed on the device using the ``launch_grid`` method. This method
814 will execute as many instances of the program as elements in the
815 specified N-dimensional grid, hopefully in parallel.
816
817 The compute program has access to four special resources:
818
819 * ``GLOBAL`` represents a memory space shared among all the threads
820 running on the device. An arbitrary buffer created with the
821 ``PIPE_BIND_GLOBAL`` flag can be mapped into it using the
822 ``set_global_binding`` method.
823
824 * ``LOCAL`` represents a memory space shared among all the threads
825 running in the same working group. The initial contents of this
826 resource are undefined.
827
828 * ``PRIVATE`` represents a memory space local to a single thread.
829 The initial contents of this resource are undefined.
830
831 * ``INPUT`` represents a read-only memory space that can be
832 initialized at ``launch_grid`` time.
833
834 These resources use a byte-based addressing scheme, and they can be
835 accessed from the compute program by means of the LOAD/STORE TGSI
836 opcodes. Additional resources to be accessed using the same opcodes
837 may be specified by the user with the ``set_compute_resources``
838 method.
839
840 In addition, normal texture sampling is allowed from the compute
841 program: ``bind_sampler_states`` may be used to set up texture
842 samplers for the compute stage and ``set_sampler_views`` may
843 be used to bind a number of sampler views to it.
844
845 Mipmap generation
846 ^^^^^^^^^^^^^^^^^
847
848 If PIPE_CAP_GENERATE_MIPMAP is true, ``generate_mipmap`` can be used
849 to generate mipmaps for the specified texture resource.
850 It replaces texel image levels base_level+1 through
851 last_level for layers range from first_layer through last_layer.
852 It returns TRUE if mipmap generation succeeds, otherwise it
853 returns FALSE. Mipmap generation may fail when it is not supported
854 for particular texture types or formats.
855
856 Device resets
857 ^^^^^^^^^^^^^
858
859 The state tracker can query or request notifications of when the GPU
860 is reset for whatever reason (application error, driver error). When
861 a GPU reset happens, the context becomes unusable and all related state
862 should be considered lost and undefined. Despite that, context
863 notifications are single-shot, i.e. subsequent calls to
864 ``get_device_reset_status`` will return PIPE_NO_RESET.
865
866 * ``get_device_reset_status`` queries whether a device reset has happened
867 since the last call or since the last notification by callback.
868 * ``set_device_reset_callback`` sets a callback which will be called when
869 a device reset is detected. The callback is only called synchronously.
870
871 Bindless
872 ^^^^^^^^
873
874 If PIPE_CAP_BINDLESS_TEXTURE is TRUE, the following ``pipe_context`` functions
875 are used to create/delete bindless handles, and to make them resident in the
876 current context when they are going to be used by shaders.
877
878 * ``create_texture_handle`` creates a 64-bit unsigned integer texture handle
879 that is going to be directly used in shaders.
880 * ``delete_texture_handle`` deletes a 64-bit unsigned integer texture handle.
881 * ``make_texture_handle_resident`` makes a 64-bit unsigned texture handle
882 resident in the current context to be accessible by shaders for texture
883 mapping.
884 * ``create_image_handle`` creates a 64-bit unsigned integer image handle that
885 is going to be directly used in shaders.
886 * ``delete_image_handle`` deletes a 64-bit unsigned integer image handle.
887 * ``make_image_handle_resident`` makes a 64-bit unsigned integer image handle
888 resident in the current context to be accessible by shaders for image loads,
889 stores and atomic operations.
890
891 Using several contexts
892 ----------------------
893
894 Several contexts from the same screen can be used at the same time. Objects
895 created on one context cannot be used in another context, but the objects
896 created by the screen methods can be used by all contexts.
897
898 Transfers
899 ^^^^^^^^^
900 A transfer on one context is not expected to synchronize properly with
901 rendering on other contexts, thus only areas not yet used for rendering should
902 be locked.
903
904 A flush is required after transfer_unmap to expect other contexts to see the
905 uploaded data, unless:
906
907 * Using persistent mapping. Associated with coherent mapping, unmapping the
908 resource is also not required to use it in other contexts. Without coherent
909 mapping, memory_barrier(PIPE_BARRIER_MAPPED_BUFFER) should be called on the
910 context that has mapped the resource. No flush is required.
911
912 * Mapping the resource with PIPE_TRANSFER_MAP_DIRECTLY.