1/*
2 * Mesa 3-D graphics library
3 *
4 * Copyright (C) 2010 LunarG Inc.
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 * Authors:
25 *    Chia-I Wu <olv@lunarg.com>
26 */
27
28#include "util/u_memory.h"
29#include "util/u_inlines.h"
30#include "util/u_atomic.h"
31#include "state_tracker/st_gl_api.h" /* for st_gl_api_create */
32#include "pipe/p_state.h"
33
34#include "stw_st.h"
35#include "stw_device.h"
36#include "stw_framebuffer.h"
37#include "stw_pixelformat.h"
38#include "stw_winsys.h"
39
40#ifdef GALLIUM_ZINK
41#include "kopper_interface.h"
42#endif
43
44struct stw_st_framebuffer {
45   struct st_framebuffer_iface base;
46
47   struct stw_framebuffer *fb;
48   struct st_visual stvis;
49
50   struct pipe_resource *textures[ST_ATTACHMENT_COUNT];
51   struct pipe_resource *msaa_textures[ST_ATTACHMENT_COUNT];
52   struct pipe_resource *back_texture;
53   bool needs_fake_front;
54   unsigned texture_width, texture_height;
55   unsigned texture_mask;
56};
57
58static uint32_t stwfb_ID = 0;
59
60/**
61 * Is the given mutex held by the calling thread?
62 */
63bool
64stw_own_mutex(const CRITICAL_SECTION *cs)
65{
66   // We can't compare OwningThread with our thread handle/id (see
67   // http://stackoverflow.com/a/12675635 ) but we can compare with the
68   // OwningThread member of a critical section we know we own.
69   CRITICAL_SECTION dummy;
70   InitializeCriticalSection(&dummy);
71   EnterCriticalSection(&dummy);
72   if (0)
73      _debug_printf("%p %p\n", cs->OwningThread, dummy.OwningThread);
74   bool ret = cs->OwningThread == dummy.OwningThread;
75   LeaveCriticalSection(&dummy);
76   DeleteCriticalSection(&dummy);
77   return ret;
78}
79
80static void
81stw_pipe_blit(struct pipe_context *pipe,
82              struct pipe_resource *dst,
83              struct pipe_resource *src)
84{
85   struct pipe_blit_info blit;
86
87   if (!dst || !src)
88      return;
89
90   /* From the GL spec, version 4.2, section 4.1.11 (Additional Multisample
91    *  Fragment Operations):
92    *
93    *      If a framebuffer object is not bound, after all operations have
94    *      been completed on the multisample buffer, the sample values for
95    *      each color in the multisample buffer are combined to produce a
96    *      single color value, and that value is written into the
97    *      corresponding color buffers selected by DrawBuffer or
98    *      DrawBuffers. An implementation may defer the writing of the color
99    *      buffers until a later time, but the state of the framebuffer must
100    *      behave as if the color buffers were updated as each fragment was
101    *      processed. The method of combination is not specified. If the
102    *      framebuffer contains sRGB values, then it is recommended that the
103    *      an average of sample values is computed in a linearized space, as
104    *      for blending (see section 4.1.7).
105    *
106    * In other words, to do a resolve operation in a linear space, we have
107    * to set sRGB formats if the original resources were sRGB, so don't use
108    * util_format_linear.
109    */
110
111   memset(&blit, 0, sizeof(blit));
112   blit.dst.resource = dst;
113   blit.dst.box.width = dst->width0;
114   blit.dst.box.height = dst->height0;
115   blit.dst.box.depth = 1;
116   blit.dst.format = dst->format;
117   blit.src.resource = src;
118   blit.src.box.width = src->width0;
119   blit.src.box.height = src->height0;
120   blit.src.box.depth = 1;
121   blit.src.format = src->format;
122   blit.mask = PIPE_MASK_RGBA;
123   blit.filter = PIPE_TEX_FILTER_NEAREST;
124
125   pipe->blit(pipe, &blit);
126}
127
128#ifdef GALLIUM_ZINK
129static void
130stw_st_fill_private_loader_data(struct stw_st_framebuffer *stwfb, struct kopper_loader_info *out)
131{
132   out->win32.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
133   out->win32.pNext = NULL;
134   out->win32.flags = 0;
135   out->win32.hinstance = GetModuleHandle(NULL);
136   out->win32.hwnd = stwfb->fb->hWnd;
137   out->has_alpha = true;
138}
139#endif
140/**
141 * Remove outdated textures and create the requested ones.
142 */
143static void
144stw_st_framebuffer_validate_locked(struct st_context_iface *stctx,
145                                   struct st_framebuffer_iface *stfb,
146                                   unsigned width, unsigned height,
147                                   unsigned mask)
148{
149   struct stw_st_framebuffer *stwfb = stw_st_framebuffer(stfb);
150   struct pipe_resource templ;
151   unsigned i;
152
153   memset(&templ, 0, sizeof(templ));
154   templ.target = PIPE_TEXTURE_2D;
155   templ.width0 = width;
156   templ.height0 = height;
157   templ.depth0 = 1;
158   templ.array_size = 1;
159   templ.last_level = 0;
160
161   /* As of now, the only stw_winsys_framebuffer implementation is
162    * d3d12_wgl_framebuffer and it doesn't support front buffer
163    * drawing. A fake front texture is needed to handle that scenario.
164    * For MSAA, we just need to make sure that the back buffer also
165    * exists, so we can blt to it during flush_frontbuffer. */
166   if (mask & ST_ATTACHMENT_FRONT_LEFT_MASK &&
167       stwfb->fb->winsys_framebuffer) {
168      if (stwfb->stvis.samples <= 1)
169         stwfb->needs_fake_front = true;
170      else
171         mask |= ST_ATTACHMENT_BACK_LEFT_MASK;
172   }
173
174   /* remove outdated textures */
175   if (stwfb->texture_width != width || stwfb->texture_height != height) {
176      for (i = 0; i < ST_ATTACHMENT_COUNT; i++) {
177         pipe_resource_reference(&stwfb->msaa_textures[i], NULL);
178         pipe_resource_reference(&stwfb->textures[i], NULL);
179      }
180      pipe_resource_reference(&stwfb->back_texture, NULL);
181
182      if (stwfb->fb->winsys_framebuffer) {
183         templ.nr_samples = templ.nr_storage_samples = 1;
184         templ.format = stwfb->stvis.color_format;
185         stwfb->fb->winsys_framebuffer->resize(stwfb->fb->winsys_framebuffer, stctx->pipe, &templ);
186      }
187   }
188
189   for (i = 0; i < ST_ATTACHMENT_COUNT; i++) {
190      enum pipe_format format;
191      unsigned bind;
192
193      /* the texture already exists or not requested */
194      if (stwfb->textures[i] || !(mask & (1 << i))) {
195         /* remember the texture */
196         if (stwfb->textures[i])
197            mask |= (1 << i);
198         continue;
199      }
200
201      switch (i) {
202      case ST_ATTACHMENT_FRONT_LEFT:
203      case ST_ATTACHMENT_BACK_LEFT:
204         format = stwfb->stvis.color_format;
205         bind = PIPE_BIND_DISPLAY_TARGET |
206                PIPE_BIND_SAMPLER_VIEW |
207                PIPE_BIND_RENDER_TARGET;
208
209#ifdef GALLIUM_ZINK
210         if (stw_dev->zink) {
211            /* Covers the case where we have already created a drawable that
212             * then got swapped and now we have to make a new back buffer.
213             * For Zink, we just alias the front buffer in that case.
214             */
215            if (i == ST_ATTACHMENT_BACK_LEFT && stwfb->textures[ST_ATTACHMENT_FRONT_LEFT])
216               bind &= ~PIPE_BIND_DISPLAY_TARGET;
217         }
218#endif
219
220         break;
221      case ST_ATTACHMENT_DEPTH_STENCIL:
222         format = stwfb->stvis.depth_stencil_format;
223         bind = PIPE_BIND_DEPTH_STENCIL;
224         break;
225      default:
226         format = PIPE_FORMAT_NONE;
227         break;
228      }
229
230      if (format != PIPE_FORMAT_NONE) {
231         templ.format = format;
232
233         if (bind != PIPE_BIND_DEPTH_STENCIL && stwfb->stvis.samples > 1) {
234            templ.bind = PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_RENDER_TARGET;
235            templ.nr_samples = templ.nr_storage_samples =
236               stwfb->stvis.samples;
237
238            stwfb->msaa_textures[i] =
239               stw_dev->screen->resource_create(stw_dev->screen, &templ);
240         }
241
242         templ.bind = bind;
243         templ.nr_samples = templ.nr_storage_samples = 1;
244
245#ifdef GALLIUM_ZINK
246         if (stw_dev->zink &&
247             i < ST_ATTACHMENT_DEPTH_STENCIL &&
248             stw_dev->screen->resource_create_drawable) {
249
250            struct kopper_loader_info loader_info;
251            void *data;
252
253            if (bind & PIPE_BIND_DISPLAY_TARGET) {
254               stw_st_fill_private_loader_data(stwfb, &loader_info);
255               data = &loader_info;
256            } else
257               data = stwfb->textures[ST_ATTACHMENT_FRONT_LEFT];
258
259            assert(data);
260            stwfb->textures[i] =
261               stw_dev->screen->resource_create_drawable(stw_dev->screen,
262                                                             &templ,
263                                                             data);
264         } else {
265#endif
266            if (stwfb->fb->winsys_framebuffer)
267               stwfb->textures[i] = stwfb->fb->winsys_framebuffer->get_resource(
268                  stwfb->fb->winsys_framebuffer, i);
269            else
270               stwfb->textures[i] =
271                  stw_dev->screen->resource_create(stw_dev->screen, &templ);
272#ifdef GALLIUM_ZINK
273         }
274#endif
275      }
276   }
277
278   /* When a fake front buffer is needed for drawing, we use the back buffer
279    * as it reduces the number of blits needed:
280    *
281    *   - When flushing the front buffer, we only need to swap the real buffers
282    *   - When swapping buffers, we can safely overwrite the fake front buffer
283    *     as it is now invalid anyway.
284    *
285    * A new texture is created to store the back buffer content.
286    */
287   if (stwfb->needs_fake_front) {
288      if (!stwfb->back_texture) {
289         templ.format = stwfb->stvis.color_format;
290         templ.bind = PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_RENDER_TARGET;
291         templ.nr_samples = templ.nr_storage_samples = 1;
292
293         stwfb->back_texture =
294            stw_dev->screen->resource_create(stw_dev->screen, &templ);
295
296         /* TODO Only blit if there is something currently drawn on the back buffer */
297         stw_pipe_blit(stctx->pipe,
298                       stwfb->back_texture,
299                       stwfb->textures[ST_ATTACHMENT_BACK_LEFT]);
300      }
301
302      /* Copying front texture content to fake front texture (back texture) */
303      stw_pipe_blit(stctx->pipe,
304                    stwfb->textures[ST_ATTACHMENT_BACK_LEFT],
305                    stwfb->textures[ST_ATTACHMENT_FRONT_LEFT]);
306   }
307
308   stwfb->texture_width = width;
309   stwfb->texture_height = height;
310   stwfb->texture_mask = mask;
311}
312
313static bool
314stw_st_framebuffer_validate(struct st_context_iface *stctx,
315                            struct st_framebuffer_iface *stfb,
316                            const enum st_attachment_type *statts,
317                            unsigned count,
318                            struct pipe_resource **out)
319{
320   struct stw_st_framebuffer *stwfb = stw_st_framebuffer(stfb);
321   unsigned statt_mask, i;
322
323   statt_mask = 0x0;
324   for (i = 0; i < count; i++)
325      statt_mask |= 1 << statts[i];
326
327   stw_framebuffer_lock(stwfb->fb);
328
329   if (stwfb->fb->must_resize || stwfb->needs_fake_front || (statt_mask & ~stwfb->texture_mask)) {
330      stw_st_framebuffer_validate_locked(stctx, &stwfb->base,
331            stwfb->fb->width, stwfb->fb->height, statt_mask);
332      stwfb->fb->must_resize = FALSE;
333   }
334
335   struct pipe_resource **textures =
336      stwfb->stvis.samples > 1 ? stwfb->msaa_textures
337                               : stwfb->textures;
338
339   for (i = 0; i < count; i++) {
340      struct pipe_resource *texture = NULL;
341
342      if (stwfb->needs_fake_front) {
343         if (statts[i] == ST_ATTACHMENT_FRONT_LEFT)
344            texture = textures[ST_ATTACHMENT_BACK_LEFT]; /* Fake front buffer */
345         else if (statts[i] == ST_ATTACHMENT_BACK_LEFT)
346            texture = stwfb->back_texture;
347      } else {
348         texture = textures[statts[i]];
349      }
350      pipe_resource_reference(&out[i], texture);
351   }
352
353   stw_framebuffer_unlock(stwfb->fb);
354
355   return true;
356}
357
358struct notify_before_flush_cb_args {
359   struct st_context_iface *stctx;
360   struct stw_st_framebuffer *stwfb;
361   unsigned flags;
362};
363
364static void
365notify_before_flush_cb(void* _args)
366{
367   struct notify_before_flush_cb_args *args = (struct notify_before_flush_cb_args *) _args;
368   struct st_context_iface *st = args->stctx;
369   struct pipe_context *pipe = st->pipe;
370
371   if (args->stwfb->stvis.samples > 1) {
372      /* Resolve the MSAA back buffer. */
373      stw_pipe_blit(pipe,
374                    args->stwfb->textures[ST_ATTACHMENT_BACK_LEFT],
375                    args->stwfb->msaa_textures[ST_ATTACHMENT_BACK_LEFT]);
376
377      /* FRONT_LEFT is resolved in flush_frontbuffer. */
378   } else if (args->stwfb->back_texture) {
379      /* Fake front texture is dirty ?? */
380      stw_pipe_blit(pipe,
381                    args->stwfb->textures[ST_ATTACHMENT_BACK_LEFT],
382                    args->stwfb->back_texture);
383   }
384
385   if (args->stwfb->textures[ST_ATTACHMENT_BACK_LEFT])
386      pipe->flush_resource(pipe, args->stwfb->textures[ST_ATTACHMENT_BACK_LEFT]);
387}
388
389void
390stw_st_flush(struct st_context_iface *stctx,
391             struct st_framebuffer_iface *stfb,
392             unsigned flags)
393{
394   struct stw_st_framebuffer *stwfb = stw_st_framebuffer(stfb);
395   struct notify_before_flush_cb_args args;
396   struct pipe_fence_handle **pfence = NULL;
397   struct pipe_fence_handle *fence = NULL;
398
399   args.stctx = stctx;
400   args.stwfb = stwfb;
401   args.flags = flags;
402
403   if (flags & ST_FLUSH_END_OF_FRAME && !stwfb->fb->winsys_framebuffer)
404      flags |= ST_FLUSH_WAIT;
405
406   if (flags & ST_FLUSH_WAIT)
407      pfence = &fence;
408   stctx->flush(stctx, flags, pfence, notify_before_flush_cb, &args);
409}
410
411/**
412 * Present an attachment of the framebuffer.
413 */
414static bool
415stw_st_framebuffer_present_locked(HDC hdc,
416                                  struct st_context_iface *stctx,
417                                  struct st_framebuffer_iface *stfb,
418                                  enum st_attachment_type statt)
419{
420   struct stw_st_framebuffer *stwfb = stw_st_framebuffer(stfb);
421   struct pipe_resource *resource;
422
423   assert(stw_own_mutex(&stwfb->fb->mutex));
424
425   resource = stwfb->textures[statt];
426   if (resource) {
427      stw_framebuffer_present_locked(hdc, stwfb->fb, resource);
428   }
429   else {
430      stw_framebuffer_unlock(stwfb->fb);
431   }
432
433   assert(!stw_own_mutex(&stwfb->fb->mutex));
434
435   return true;
436}
437
438static bool
439stw_st_framebuffer_flush_front(struct st_context_iface *stctx,
440                               struct st_framebuffer_iface *stfb,
441                               enum st_attachment_type statt)
442{
443   struct stw_st_framebuffer *stwfb = stw_st_framebuffer(stfb);
444   struct pipe_context *pipe = stctx->pipe;
445   bool ret;
446   HDC hDC;
447   bool need_swap_textures = false;
448
449   if (statt != ST_ATTACHMENT_FRONT_LEFT)
450      return false;
451
452   stw_framebuffer_lock(stwfb->fb);
453
454   /* Resolve the front buffer. */
455   if (stwfb->stvis.samples > 1) {
456      enum st_attachment_type blit_target = statt;
457      if (stwfb->fb->winsys_framebuffer) {
458         blit_target = ST_ATTACHMENT_BACK_LEFT;
459         need_swap_textures = true;
460      }
461
462      stw_pipe_blit(pipe, stwfb->textures[blit_target],
463                    stwfb->msaa_textures[statt]);
464   } else if (stwfb->needs_fake_front) {
465      /* fake front texture is now invalid */
466      p_atomic_inc(&stwfb->base.stamp);
467      need_swap_textures = true;
468   }
469
470   if (need_swap_textures) {
471      struct pipe_resource *ptex = stwfb->textures[ST_ATTACHMENT_FRONT_LEFT];
472      stwfb->textures[ST_ATTACHMENT_FRONT_LEFT] = stwfb->textures[ST_ATTACHMENT_BACK_LEFT];
473      stwfb->textures[ST_ATTACHMENT_BACK_LEFT] = ptex;
474   }
475
476   if (stwfb->textures[statt])
477      pipe->flush_resource(pipe, stwfb->textures[statt]);
478
479   pipe->flush(pipe, NULL, 0);
480
481   /* We must not cache HDCs anywhere, as they can be invalidated by the
482    * application, or screen resolution changes. */
483
484   hDC = GetDC(stwfb->fb->hWnd);
485
486   ret = stw_st_framebuffer_present_locked(hDC, stctx, &stwfb->base, statt);
487
488   ReleaseDC(stwfb->fb->hWnd, hDC);
489
490   return ret;
491}
492
493/**
494 * Create a framebuffer interface.
495 */
496struct st_framebuffer_iface *
497stw_st_create_framebuffer(struct stw_framebuffer *fb)
498{
499   struct stw_st_framebuffer *stwfb;
500
501   stwfb = CALLOC_STRUCT(stw_st_framebuffer);
502   if (!stwfb)
503      return NULL;
504
505   stwfb->fb = fb;
506   stwfb->stvis = fb->pfi->stvis;
507   stwfb->base.ID = p_atomic_inc_return(&stwfb_ID);
508   stwfb->base.state_manager = stw_dev->smapi;
509
510   stwfb->base.visual = &stwfb->stvis;
511   p_atomic_set(&stwfb->base.stamp, 1);
512   stwfb->base.flush_front = stw_st_framebuffer_flush_front;
513   stwfb->base.validate = stw_st_framebuffer_validate;
514
515   return &stwfb->base;
516}
517
518/**
519 * Destroy a framebuffer interface.
520 */
521void
522stw_st_destroy_framebuffer_locked(struct st_framebuffer_iface *stfb)
523{
524   struct stw_st_framebuffer *stwfb = stw_st_framebuffer(stfb);
525   int i;
526
527   for (i = 0; i < ST_ATTACHMENT_COUNT; i++) {
528      pipe_resource_reference(&stwfb->msaa_textures[i], NULL);
529      pipe_resource_reference(&stwfb->textures[i], NULL);
530   }
531   pipe_resource_reference(&stwfb->back_texture, NULL);
532
533   /* Notify the st manager that the framebuffer interface is no
534    * longer valid.
535    */
536   stw_dev->stapi->destroy_drawable(stw_dev->stapi, &stwfb->base);
537
538   FREE(stwfb);
539}
540
541/**
542 * Swap the buffers of the given framebuffer.
543 */
544bool
545stw_st_swap_framebuffer_locked(HDC hdc, struct st_context_iface *stctx,
546                               struct st_framebuffer_iface *stfb)
547{
548   struct stw_st_framebuffer *stwfb = stw_st_framebuffer(stfb);
549   unsigned front = ST_ATTACHMENT_FRONT_LEFT, back = ST_ATTACHMENT_BACK_LEFT;
550   struct pipe_resource *ptex;
551   unsigned mask;
552
553   /* swap the textures */
554   ptex = stwfb->textures[front];
555   stwfb->textures[front] = stwfb->textures[back];
556   stwfb->textures[back] = ptex;
557
558   /* swap msaa_textures */
559   ptex = stwfb->msaa_textures[front];
560   stwfb->msaa_textures[front] = stwfb->msaa_textures[back];
561   stwfb->msaa_textures[back] = ptex;
562
563
564   /* Fake front texture is now dirty */
565   if (stwfb->needs_fake_front)
566      p_atomic_inc(&stwfb->base.stamp);
567
568   /* convert to mask */
569   front = 1 << front;
570   back = 1 << back;
571
572   /* swap the bits in mask */
573   mask = stwfb->texture_mask & ~(front | back);
574   if (stwfb->texture_mask & front)
575      mask |= back;
576   if (stwfb->texture_mask & back)
577      mask |= front;
578   stwfb->texture_mask = mask;
579
580   front = ST_ATTACHMENT_FRONT_LEFT;
581   return stw_st_framebuffer_present_locked(hdc, stctx, &stwfb->base, front);
582}
583
584
585/**
586 * Return the pipe_resource that correspond to given buffer.
587 */
588struct pipe_resource *
589stw_get_framebuffer_resource(struct st_framebuffer_iface *stfb,
590                             enum st_attachment_type att)
591{
592   struct stw_st_framebuffer *stwfb = stw_st_framebuffer(stfb);
593   return stwfb->textures[att];
594}
595
596
597/**
598 * Create an st_api of the gallium frontend.
599 */
600struct st_api *
601stw_st_create_api(void)
602{
603   return st_gl_api_create();
604}
605