VirtualBox

source: vbox/trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/context.c@ 31828

Last change on this file since 31828 was 31828, checked in by vboxsync, 14 years ago

wine: basics for shared resource handling

  • Property svn:eol-style set to native
File size: 80.6 KB
Line 
1/*
2 * Context and render target management in wined3d
3 *
4 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
5 * Copyright 2009 Henri Verbeet for CodeWeavers
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 */
21/*
22 * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
23 * other than GPL or LGPL is available it will apply instead, Sun elects to use only
24 * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
25 * a choice of LGPL license versions is made available with the language indicating
26 * that LGPLv2 or any later version may be used, or where a choice of which version
27 * of the LGPL is applied is otherwise unspecified.
28 */
29
30
31#include "config.h"
32#include <stdio.h>
33#ifdef HAVE_FLOAT_H
34# include <float.h>
35#endif
36#include "wined3d_private.h"
37
38WINE_DEFAULT_DEBUG_CHANNEL(d3d);
39
40#define GLINFO_LOCATION (*gl_info)
41
42static DWORD wined3d_context_tls_idx;
43
44/* FBO helper functions */
45
46/* GL locking is done by the caller */
47void context_bind_fbo(struct wined3d_context *context, GLenum target, GLuint *fbo)
48{
49 const struct wined3d_gl_info *gl_info = context->gl_info;
50 GLuint f;
51
52 if (!fbo)
53 {
54 f = 0;
55 }
56 else
57 {
58 if (!*fbo)
59 {
60 gl_info->fbo_ops.glGenFramebuffers(1, fbo);
61 checkGLcall("glGenFramebuffers()");
62 TRACE("Created FBO %u.\n", *fbo);
63 }
64 f = *fbo;
65 }
66
67 switch (target)
68 {
69 case GL_READ_FRAMEBUFFER:
70 if (context->fbo_read_binding == f) return;
71 context->fbo_read_binding = f;
72 break;
73
74 case GL_DRAW_FRAMEBUFFER:
75 if (context->fbo_draw_binding == f) return;
76 context->fbo_draw_binding = f;
77 break;
78
79 case GL_FRAMEBUFFER:
80 if (context->fbo_read_binding == f
81 && context->fbo_draw_binding == f) return;
82 context->fbo_read_binding = f;
83 context->fbo_draw_binding = f;
84 break;
85
86 default:
87 FIXME("Unhandled target %#x.\n", target);
88 break;
89 }
90
91 gl_info->fbo_ops.glBindFramebuffer(target, f);
92 checkGLcall("glBindFramebuffer()");
93}
94
95/* GL locking is done by the caller */
96static void context_clean_fbo_attachments(const struct wined3d_gl_info *gl_info)
97{
98 unsigned int i;
99
100 for (i = 0; i < gl_info->limits.buffers; ++i)
101 {
102 gl_info->fbo_ops.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
103 checkGLcall("glFramebufferTexture2D()");
104 }
105 gl_info->fbo_ops.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
106 checkGLcall("glFramebufferTexture2D()");
107
108 gl_info->fbo_ops.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
109 checkGLcall("glFramebufferTexture2D()");
110}
111
112/* GL locking is done by the caller */
113static void context_destroy_fbo(struct wined3d_context *context, GLuint *fbo)
114{
115 const struct wined3d_gl_info *gl_info = context->gl_info;
116
117 context_bind_fbo(context, GL_FRAMEBUFFER, fbo);
118 context_clean_fbo_attachments(gl_info);
119 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
120
121 gl_info->fbo_ops.glDeleteFramebuffers(1, fbo);
122 checkGLcall("glDeleteFramebuffers()");
123}
124
125/* GL locking is done by the caller */
126static void context_apply_attachment_filter_states(IWineD3DSurfaceImpl *surface)
127{
128 IWineD3DBaseTextureImpl *texture_impl;
129
130 /* Update base texture states array */
131 if (SUCCEEDED(IWineD3DSurface_GetContainer((IWineD3DSurface *)surface,
132 &IID_IWineD3DBaseTexture, (void **)&texture_impl)))
133 {
134 IWineD3DDeviceImpl *device = surface->resource.device;
135 BOOL update_minfilter = FALSE;
136 BOOL update_magfilter = FALSE;
137
138 if (texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MINFILTER] != WINED3DTEXF_POINT
139 || texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MIPFILTER] != WINED3DTEXF_NONE)
140 {
141 texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
142 texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
143 update_minfilter = TRUE;
144 }
145
146 if (texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MAGFILTER] != WINED3DTEXF_POINT)
147 {
148 texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
149 update_magfilter = TRUE;
150 }
151
152 if (texture_impl->baseTexture.bindCount)
153 {
154 WARN("Render targets should not be bound to a sampler\n");
155 IWineD3DDeviceImpl_MarkStateDirty(device, STATE_SAMPLER(texture_impl->baseTexture.sampler));
156 }
157
158 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture_impl);
159
160 if (update_minfilter || update_magfilter)
161 {
162 GLenum target, bind_target;
163 GLint old_binding;
164
165 target = surface->texture_target;
166 if (target == GL_TEXTURE_2D)
167 {
168 bind_target = GL_TEXTURE_2D;
169 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
170 }
171 else if (target == GL_TEXTURE_RECTANGLE_ARB)
172 {
173 bind_target = GL_TEXTURE_RECTANGLE_ARB;
174 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
175 }
176 else
177 {
178 bind_target = GL_TEXTURE_CUBE_MAP_ARB;
179 glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB, &old_binding);
180 }
181
182 glBindTexture(bind_target, surface->texture_name);
183 if (update_minfilter) glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
184 if (update_magfilter) glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
185 glBindTexture(bind_target, old_binding);
186 }
187
188 checkGLcall("apply_attachment_filter_states()");
189 }
190}
191
192/* GL locking is done by the caller */
193void context_attach_depth_stencil_fbo(struct wined3d_context *context,
194 GLenum fbo_target, IWineD3DSurfaceImpl *depth_stencil, BOOL use_render_buffer)
195{
196 const struct wined3d_gl_info *gl_info = context->gl_info;
197
198 TRACE("Attach depth stencil %p\n", depth_stencil);
199
200 if (depth_stencil)
201 {
202 DWORD format_flags = depth_stencil->resource.format_desc->Flags;
203
204 if (use_render_buffer && depth_stencil->current_renderbuffer)
205 {
206 if (format_flags & WINED3DFMT_FLAG_DEPTH)
207 {
208 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_DEPTH_ATTACHMENT,
209 GL_RENDERBUFFER, depth_stencil->current_renderbuffer->id);
210 checkGLcall("glFramebufferRenderbuffer()");
211 }
212
213 if (format_flags & WINED3DFMT_FLAG_STENCIL)
214 {
215 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_STENCIL_ATTACHMENT,
216 GL_RENDERBUFFER, depth_stencil->current_renderbuffer->id);
217 checkGLcall("glFramebufferRenderbuffer()");
218 }
219 }
220 else
221 {
222 surface_prepare_texture(depth_stencil, gl_info, FALSE);
223 context_apply_attachment_filter_states(depth_stencil);
224
225 if (format_flags & WINED3DFMT_FLAG_DEPTH)
226 {
227 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT,
228 depth_stencil->texture_target, depth_stencil->texture_name,
229 depth_stencil->texture_level);
230 checkGLcall("glFramebufferTexture2D()");
231 }
232
233 if (format_flags & WINED3DFMT_FLAG_STENCIL)
234 {
235 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT,
236 depth_stencil->texture_target, depth_stencil->texture_name,
237 depth_stencil->texture_level);
238 checkGLcall("glFramebufferTexture2D()");
239 }
240 }
241
242 if (!(format_flags & WINED3DFMT_FLAG_DEPTH))
243 {
244 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
245 checkGLcall("glFramebufferTexture2D()");
246 }
247
248 if (!(format_flags & WINED3DFMT_FLAG_STENCIL))
249 {
250 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
251 checkGLcall("glFramebufferTexture2D()");
252 }
253 }
254 else
255 {
256 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
257 checkGLcall("glFramebufferTexture2D()");
258
259 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
260 checkGLcall("glFramebufferTexture2D()");
261 }
262}
263
264/* GL locking is done by the caller */
265void context_attach_surface_fbo(const struct wined3d_context *context,
266 GLenum fbo_target, DWORD idx, IWineD3DSurfaceImpl *surface)
267{
268 const struct wined3d_gl_info *gl_info = context->gl_info;
269
270 TRACE("Attach surface %p to %u\n", surface, idx);
271
272 if (surface)
273 {
274 surface_prepare_texture(surface, gl_info, FALSE);
275 context_apply_attachment_filter_states(surface);
276
277 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, surface->texture_target,
278 surface->texture_name, surface->texture_level);
279 checkGLcall("glFramebufferTexture2D()");
280 }
281 else
282 {
283 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, GL_TEXTURE_2D, 0, 0);
284 checkGLcall("glFramebufferTexture2D()");
285 }
286}
287
288/* GL locking is done by the caller */
289static void context_check_fbo_status(struct wined3d_context *context)
290{
291 const struct wined3d_gl_info *gl_info = context->gl_info;
292 GLenum status;
293
294 status = gl_info->fbo_ops.glCheckFramebufferStatus(GL_FRAMEBUFFER);
295 if (status == GL_FRAMEBUFFER_COMPLETE)
296 {
297 TRACE("FBO complete\n");
298 } else {
299 IWineD3DSurfaceImpl *attachment;
300 unsigned int i;
301 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
302
303 if (!context->current_fbo)
304 {
305 ERR("FBO 0 is incomplete, driver bug?\n");
306 return;
307 }
308
309 /* Dump the FBO attachments */
310 for (i = 0; i < gl_info->limits.buffers; ++i)
311 {
312 attachment = context->current_fbo->render_targets[i];
313 if (attachment)
314 {
315 FIXME("\tColor attachment %d: (%p) %s %ux%u\n",
316 i, attachment, debug_d3dformat(attachment->resource.format_desc->format),
317 attachment->pow2Width, attachment->pow2Height);
318 }
319 }
320 attachment = context->current_fbo->depth_stencil;
321 if (attachment)
322 {
323 FIXME("\tDepth attachment: (%p) %s %ux%u\n",
324 attachment, debug_d3dformat(attachment->resource.format_desc->format),
325 attachment->pow2Width, attachment->pow2Height);
326 }
327 }
328}
329
330static struct fbo_entry *context_create_fbo_entry(struct wined3d_context *context)
331{
332 const struct wined3d_gl_info *gl_info = context->gl_info;
333 IWineD3DDeviceImpl *device = context->swapchain->device;
334 struct fbo_entry *entry;
335
336 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
337 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, gl_info->limits.buffers * sizeof(*entry->render_targets));
338 memcpy(entry->render_targets, device->render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
339 entry->depth_stencil = (IWineD3DSurfaceImpl *)device->stencilBufferTarget;
340 entry->attached = FALSE;
341 entry->id = 0;
342
343 return entry;
344}
345
346/* GL locking is done by the caller */
347static void context_reuse_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
348{
349 const struct wined3d_gl_info *gl_info = context->gl_info;
350 IWineD3DDeviceImpl *device = context->swapchain->device;
351
352 context_bind_fbo(context, GL_FRAMEBUFFER, &entry->id);
353 context_clean_fbo_attachments(gl_info);
354
355 memcpy(entry->render_targets, device->render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
356 entry->depth_stencil = (IWineD3DSurfaceImpl *)device->stencilBufferTarget;
357 entry->attached = FALSE;
358}
359
360/* GL locking is done by the caller */
361static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
362{
363 if (entry->id)
364 {
365 TRACE("Destroy FBO %d\n", entry->id);
366 context_destroy_fbo(context, &entry->id);
367 }
368 --context->fbo_entry_count;
369 list_remove(&entry->entry);
370 HeapFree(GetProcessHeap(), 0, entry->render_targets);
371 HeapFree(GetProcessHeap(), 0, entry);
372}
373
374
375/* GL locking is done by the caller */
376static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context)
377{
378 const struct wined3d_gl_info *gl_info = context->gl_info;
379 IWineD3DDeviceImpl *device = context->swapchain->device;
380 struct fbo_entry *entry;
381
382 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
383 {
384 if (!memcmp(entry->render_targets,
385 device->render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets))
386 && entry->depth_stencil == (IWineD3DSurfaceImpl *)device->stencilBufferTarget)
387 {
388 list_remove(&entry->entry);
389 list_add_head(&context->fbo_list, &entry->entry);
390 return entry;
391 }
392 }
393
394 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
395 {
396 entry = context_create_fbo_entry(context);
397 list_add_head(&context->fbo_list, &entry->entry);
398 ++context->fbo_entry_count;
399 }
400 else
401 {
402 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
403 context_reuse_fbo_entry(context, entry);
404 list_remove(&entry->entry);
405 list_add_head(&context->fbo_list, &entry->entry);
406 }
407
408 return entry;
409}
410
411/* GL locking is done by the caller */
412static void context_apply_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
413{
414 const struct wined3d_gl_info *gl_info = context->gl_info;
415 IWineD3DDeviceImpl *device = context->swapchain->device;
416 unsigned int i;
417
418 context_bind_fbo(context, GL_FRAMEBUFFER, &entry->id);
419
420 if (!entry->attached)
421 {
422 /* Apply render targets */
423 for (i = 0; i < gl_info->limits.buffers; ++i)
424 {
425 IWineD3DSurfaceImpl *render_target = (IWineD3DSurfaceImpl *)device->render_targets[i];
426 context_attach_surface_fbo(context, GL_FRAMEBUFFER, i, render_target);
427 }
428
429 /* Apply depth targets */
430 if (device->stencilBufferTarget)
431 {
432 unsigned int w = ((IWineD3DSurfaceImpl *)device->render_targets[0])->pow2Width;
433 unsigned int h = ((IWineD3DSurfaceImpl *)device->render_targets[0])->pow2Height;
434
435 surface_set_compatible_renderbuffer(device->stencilBufferTarget, w, h);
436 }
437 context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER, (IWineD3DSurfaceImpl *)device->stencilBufferTarget, TRUE);
438
439 entry->attached = TRUE;
440 }
441 else
442 {
443 for (i = 0; i < gl_info->limits.buffers; ++i)
444 {
445 if (device->render_targets[i])
446 context_apply_attachment_filter_states((IWineD3DSurfaceImpl *)device->render_targets[i]);
447 }
448 if (device->stencilBufferTarget)
449 context_apply_attachment_filter_states((IWineD3DSurfaceImpl *)device->stencilBufferTarget);
450 }
451
452 for (i = 0; i < gl_info->limits.buffers; ++i)
453 {
454 if (device->render_targets[i])
455 device->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
456 else
457 device->draw_buffers[i] = GL_NONE;
458 }
459}
460
461/* GL locking is done by the caller */
462static void context_apply_fbo_state(struct wined3d_context *context)
463{
464 struct fbo_entry *entry, *entry2;
465
466 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
467 {
468 context_destroy_fbo_entry(context, entry);
469 }
470
471 if (context->rebind_fbo)
472 {
473 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
474 context->rebind_fbo = FALSE;
475 }
476
477 if (context->render_offscreen)
478 {
479 context->current_fbo = context_find_fbo_entry(context);
480 context_apply_fbo_entry(context, context->current_fbo);
481 } else {
482 context->current_fbo = NULL;
483 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
484 }
485
486#if defined(DEBUG) && !defined(DEBUG_misha)
487 context_check_fbo_status(context);
488#endif
489}
490
491/* Context activation is done by the caller. */
492void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
493{
494 const struct wined3d_gl_info *gl_info = context->gl_info;
495
496 if (context->free_occlusion_query_count)
497 {
498 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
499 }
500 else
501 {
502 if (gl_info->supported[ARB_OCCLUSION_QUERY])
503 {
504 ENTER_GL();
505 GL_EXTCALL(glGenQueriesARB(1, &query->id));
506 checkGLcall("glGenQueriesARB");
507 LEAVE_GL();
508
509 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
510 }
511 else
512 {
513 WARN("Occlusion queries not supported, not allocating query id.\n");
514 query->id = 0;
515 }
516 }
517
518 query->context = context;
519 list_add_head(&context->occlusion_queries, &query->entry);
520}
521
522void context_free_occlusion_query(struct wined3d_occlusion_query *query)
523{
524 struct wined3d_context *context = query->context;
525
526 list_remove(&query->entry);
527 query->context = NULL;
528
529 if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
530 {
531 UINT new_size = context->free_occlusion_query_size << 1;
532 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
533 new_size * sizeof(*context->free_occlusion_queries));
534
535 if (!new_data)
536 {
537 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
538 return;
539 }
540
541 context->free_occlusion_query_size = new_size;
542 context->free_occlusion_queries = new_data;
543 }
544
545 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
546}
547
548/* Context activation is done by the caller. */
549void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
550{
551 const struct wined3d_gl_info *gl_info = context->gl_info;
552
553 if (context->free_event_query_count)
554 {
555 query->object = context->free_event_queries[--context->free_event_query_count];
556 }
557 else
558 {
559 if (gl_info->supported[ARB_SYNC])
560 {
561 /* Using ARB_sync, not much to do here. */
562 query->object.sync = NULL;
563 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
564 }
565 else if (gl_info->supported[APPLE_FENCE])
566 {
567 ENTER_GL();
568 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
569 checkGLcall("glGenFencesAPPLE");
570 LEAVE_GL();
571
572 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
573 }
574 else if(gl_info->supported[NV_FENCE])
575 {
576 ENTER_GL();
577 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
578 checkGLcall("glGenFencesNV");
579 LEAVE_GL();
580
581 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
582 }
583 else
584 {
585 WARN("Event queries not supported, not allocating query id.\n");
586 query->object.id = 0;
587 }
588 }
589
590 query->context = context;
591 list_add_head(&context->event_queries, &query->entry);
592}
593
594void context_free_event_query(struct wined3d_event_query *query)
595{
596 struct wined3d_context *context = query->context;
597
598 list_remove(&query->entry);
599 query->context = NULL;
600
601 if (context->free_event_query_count >= context->free_event_query_size - 1)
602 {
603 UINT new_size = context->free_event_query_size << 1;
604 union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
605 new_size * sizeof(*context->free_event_queries));
606
607 if (!new_data)
608 {
609 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
610 return;
611 }
612
613 context->free_event_query_size = new_size;
614 context->free_event_queries = new_data;
615 }
616
617 context->free_event_queries[context->free_event_query_count++] = query->object;
618}
619
620void context_resource_released(IWineD3DDevice *iface, IWineD3DResource *resource, WINED3DRESOURCETYPE type)
621{
622 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
623 UINT i;
624
625 if (!This->d3d_initialized) return;
626
627 switch(type)
628 {
629 case WINED3DRTYPE_SURFACE:
630 {
631 for (i = 0; i < This->numContexts; ++i)
632 {
633 struct wined3d_context *context = This->contexts[i];
634 const struct wined3d_gl_info *gl_info = context->gl_info;
635 struct fbo_entry *entry, *entry2;
636
637 if (context->current_rt == (IWineD3DSurface *)resource) context->current_rt = NULL;
638
639 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
640 {
641 UINT j;
642
643 if (entry->depth_stencil == (IWineD3DSurfaceImpl *)resource)
644 {
645 list_remove(&entry->entry);
646 list_add_head(&context->fbo_destroy_list, &entry->entry);
647 continue;
648 }
649
650 for (j = 0; j < gl_info->limits.buffers; ++j)
651 {
652 if (entry->render_targets[j] == (IWineD3DSurfaceImpl *)resource)
653 {
654 list_remove(&entry->entry);
655 list_add_head(&context->fbo_destroy_list, &entry->entry);
656 break;
657 }
658 }
659 }
660 }
661
662 break;
663 }
664
665 default:
666 break;
667 }
668}
669
670void context_surface_update(struct wined3d_context *context, IWineD3DSurfaceImpl *surface)
671{
672 const struct wined3d_gl_info *gl_info = context->gl_info;
673 struct fbo_entry *entry = context->current_fbo;
674 unsigned int i;
675
676 if (!entry || context->rebind_fbo) return;
677
678 for (i = 0; i < gl_info->limits.buffers; ++i)
679 {
680 if (surface == entry->render_targets[i])
681 {
682 TRACE("Updated surface %p is bound as color attachment %u to the current FBO.\n", surface, i);
683 context->rebind_fbo = TRUE;
684 return;
685 }
686 }
687
688 if (surface == entry->depth_stencil)
689 {
690 TRACE("Updated surface %p is bound as depth attachment to the current FBO.\n", surface);
691 context->rebind_fbo = TRUE;
692 }
693}
694
695static BOOL context_set_pixel_format(const struct wined3d_gl_info *gl_info, HDC dc, int format)
696{
697 int current = GetPixelFormat(dc);
698
699 if (current == format) return TRUE;
700
701 if (!current)
702 {
703 if (!SetPixelFormat(dc, format, NULL))
704 {
705 ERR("Failed to set pixel format %d on device context %p, last error %#x.\n",
706 format, dc, GetLastError());
707 return FALSE;
708 }
709 return TRUE;
710 }
711
712 /* By default WGL doesn't allow pixel format adjustments but we need it
713 * here. For this reason there's a Wine specific wglSetPixelFormat()
714 * which allows us to set the pixel format multiple times. Only use it
715 * when really needed. */
716 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
717 {
718 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format, NULL)))
719 {
720 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
721 format, dc);
722 return FALSE;
723 }
724 return TRUE;
725 }
726
727 /* OpenGL doesn't allow pixel format adjustments. Print an error and
728 * continue using the old format. There's a big chance that the old
729 * format works although with a performance hit and perhaps rendering
730 * errors. */
731 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
732 format, dc, current);
733 return TRUE;
734}
735
736static void context_update_window(struct wined3d_context *context)
737{
738 TRACE("Updating context %p window from %p to %p.\n",
739 context, context->win_handle, context->swapchain->win_handle);
740
741 if (context->valid)
742 {
743 if (!ReleaseDC(context->win_handle, context->hdc))
744 {
745 ERR("Failed to release device context %p, last error %#x.\n",
746 context->hdc, GetLastError());
747 }
748 }
749 else context->valid = 1;
750
751 context->win_handle = context->swapchain->win_handle;
752
753 if (!(context->hdc = GetDC(context->win_handle)))
754 {
755 ERR("Failed to get a device context for window %p.\n", context->win_handle);
756 goto err;
757 }
758
759 if (!context_set_pixel_format(context->gl_info, context->hdc, context->pixel_format))
760 {
761 ERR("Failed to set pixel format %d on device context %p.\n",
762 context->pixel_format, context->hdc);
763 goto err;
764 }
765
766 if (!pwglMakeCurrent(context->hdc, context->glCtx))
767 {
768 ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
769 context->glCtx, context->hdc, GetLastError());
770 goto err;
771 }
772
773 return;
774
775err:
776 context->valid = 0;
777}
778
779static void context_validate(struct wined3d_context *context)
780{
781 HWND wnd = WindowFromDC(context->hdc);
782
783 if (wnd != context->win_handle)
784 {
785 WARN("DC %p belongs to window %p instead of %p.\n",
786 context->hdc, wnd, context->win_handle);
787 context->valid = 0;
788 }
789
790 if (context->win_handle != context->swapchain->win_handle)
791 context_update_window(context);
792}
793
794static void context_destroy_gl_resources(struct wined3d_context *context)
795{
796 const struct wined3d_gl_info *gl_info = context->gl_info;
797 struct wined3d_occlusion_query *occlusion_query;
798 struct wined3d_event_query *event_query;
799 struct fbo_entry *entry, *entry2;
800 HGLRC restore_ctx;
801 HDC restore_dc;
802 unsigned int i;
803
804 restore_ctx = pwglGetCurrentContext();
805 restore_dc = pwglGetCurrentDC();
806
807 context_validate(context);
808 if (context->valid && restore_ctx != context->glCtx) pwglMakeCurrent(context->hdc, context->glCtx);
809 else restore_ctx = NULL;
810
811 ENTER_GL();
812
813 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
814 {
815 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
816 GL_EXTCALL(glDeleteQueriesARB(1, &occlusion_query->id));
817 occlusion_query->context = NULL;
818 }
819
820 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
821 {
822 if (context->valid)
823 {
824 if (gl_info->supported[ARB_SYNC])
825 {
826 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
827 }
828 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
829 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
830 }
831 event_query->context = NULL;
832 }
833
834 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
835 {
836 if (!context->valid) entry->id = 0;
837 context_destroy_fbo_entry(context, entry);
838 }
839
840 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
841 {
842 if (!context->valid) entry->id = 0;
843 context_destroy_fbo_entry(context, entry);
844 }
845
846 if (context->valid)
847 {
848 if (context->src_fbo)
849 {
850 TRACE("Destroy src FBO %d\n", context->src_fbo);
851 context_destroy_fbo(context, &context->src_fbo);
852 }
853 if (context->dst_fbo)
854 {
855 TRACE("Destroy dst FBO %d\n", context->dst_fbo);
856 context_destroy_fbo(context, &context->dst_fbo);
857 }
858 if (context->dummy_arbfp_prog)
859 {
860 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
861 }
862
863 if (gl_info->supported[ARB_OCCLUSION_QUERY])
864 GL_EXTCALL(glDeleteQueriesARB(context->free_occlusion_query_count, context->free_occlusion_queries));
865
866 if (gl_info->supported[ARB_SYNC])
867 {
868 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
869 }
870 else if (gl_info->supported[APPLE_FENCE])
871 {
872 for (i = 0; i < context->free_event_query_count; ++i)
873 {
874 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
875 }
876 }
877 else if (gl_info->supported[NV_FENCE])
878 {
879 for (i = 0; i < context->free_event_query_count; ++i)
880 {
881 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
882 }
883 }
884
885 checkGLcall("context cleanup");
886 }
887
888 LEAVE_GL();
889
890 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
891 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
892
893 if (restore_ctx)
894 {
895 if (!pwglMakeCurrent(restore_dc, restore_ctx))
896 {
897 DWORD err = GetLastError();
898 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
899 restore_ctx, restore_dc, err);
900 }
901 }
902 else if (pwglGetCurrentContext() && !pwglMakeCurrent(NULL, NULL))
903 {
904 ERR("Failed to disable GL context.\n");
905 }
906
907 ReleaseDC(context->win_handle, context->hdc);
908
909 if (!pwglDeleteContext(context->glCtx))
910 {
911 DWORD err = GetLastError();
912 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
913 }
914}
915
916DWORD context_get_tls_idx(void)
917{
918 return wined3d_context_tls_idx;
919}
920
921void context_set_tls_idx(DWORD idx)
922{
923 wined3d_context_tls_idx = idx;
924}
925
926struct wined3d_context *context_get_current(void)
927{
928 return TlsGetValue(wined3d_context_tls_idx);
929}
930
931BOOL context_set_current(struct wined3d_context *ctx)
932{
933 struct wined3d_context *old = context_get_current();
934
935 if (old == ctx)
936 {
937 TRACE("Already using D3D context %p.\n", ctx);
938 return TRUE;
939 }
940
941 if (old)
942 {
943 if (old->destroyed)
944 {
945 TRACE("Switching away from destroyed context %p.\n", old);
946 context_destroy_gl_resources(old);
947 HeapFree(GetProcessHeap(), 0, old);
948 }
949 else
950 {
951 old->current = 0;
952 }
953 }
954
955 if (ctx)
956 {
957 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
958 if (!pwglMakeCurrent(ctx->hdc, ctx->glCtx))
959 {
960 DWORD err = GetLastError();
961 ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
962 ctx->glCtx, ctx->hdc, err);
963 TlsSetValue(wined3d_context_tls_idx, NULL);
964 return FALSE;
965 }
966 ctx->current = 1;
967 }
968 else if(pwglGetCurrentContext())
969 {
970 TRACE("Clearing current D3D context.\n");
971 if (!pwglMakeCurrent(NULL, NULL))
972 {
973 DWORD err = GetLastError();
974 ERR("Failed to clear current GL context, last error %#x.\n", err);
975 TlsSetValue(wined3d_context_tls_idx, NULL);
976 return FALSE;
977 }
978 }
979
980 return TlsSetValue(wined3d_context_tls_idx, ctx);
981}
982
983void context_release(struct wined3d_context *context)
984{
985 TRACE("Releasing context %p, level %u.\n", context, context->level);
986
987 if (WARN_ON(d3d))
988 {
989 if (!context->level)
990 WARN("Context %p is not active.\n", context);
991 else if (context != context_get_current())
992 WARN("Context %p is not the current context.\n", context);
993 }
994
995 if (!--context->level && context->restore_ctx)
996 {
997 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
998 if (!pwglMakeCurrent(context->restore_dc, context->restore_ctx))
999 {
1000 DWORD err = GetLastError();
1001 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
1002 context->restore_ctx, context->restore_dc, err);
1003 }
1004 context->restore_ctx = NULL;
1005 context->restore_dc = NULL;
1006 }
1007}
1008
1009static void context_enter(struct wined3d_context *context)
1010{
1011 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1012
1013 if (!context->level++)
1014 {
1015 const struct wined3d_context *current_context = context_get_current();
1016 HGLRC current_gl = pwglGetCurrentContext();
1017
1018 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1019 {
1020 TRACE("Another GL context (%p on device context %p) is already current.\n",
1021 current_gl, pwglGetCurrentDC());
1022 context->restore_ctx = current_gl;
1023 context->restore_dc = pwglGetCurrentDC();
1024 }
1025 }
1026}
1027
1028/*****************************************************************************
1029 * Context_MarkStateDirty
1030 *
1031 * Marks a state in a context dirty. Only one context, opposed to
1032 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
1033 * contexts
1034 *
1035 * Params:
1036 * context: Context to mark the state dirty in
1037 * state: State to mark dirty
1038 * StateTable: Pointer to the state table in use(for state grouping)
1039 *
1040 *****************************************************************************/
1041static void Context_MarkStateDirty(struct wined3d_context *context, DWORD state, const struct StateEntry *StateTable)
1042{
1043 DWORD rep = StateTable[state].representative;
1044 DWORD idx;
1045 BYTE shift;
1046
1047 if (isStateDirty(context, rep)) return;
1048
1049 context->dirtyArray[context->numDirtyEntries++] = rep;
1050 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1051 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1052 context->isStateDirty[idx] |= (1 << shift);
1053}
1054
1055/* This function takes care of WineD3D pixel format selection. */
1056static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc,
1057 const struct wined3d_format_desc *color_format_desc, const struct wined3d_format_desc *ds_format_desc,
1058 BOOL auxBuffers, int numSamples, BOOL findCompatible)
1059{
1060 int iPixelFormat=0;
1061 unsigned int matchtry;
1062 short redBits, greenBits, blueBits, alphaBits, colorBits;
1063 short depthBits=0, stencilBits=0;
1064
1065 struct match_type {
1066 BOOL require_aux;
1067 BOOL exact_alpha;
1068 BOOL exact_color;
1069 } matches[] = {
1070 /* First, try without alpha match buffers. MacOS supports aux buffers only
1071 * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
1072 * Then try without aux buffers - this is the most common cause for not
1073 * finding a pixel format. Also some drivers(the open source ones)
1074 * only offer 32 bit ARB pixel formats. First try without an exact alpha
1075 * match, then try without an exact alpha and color match.
1076 */
1077 { TRUE, TRUE, TRUE },
1078 { TRUE, FALSE, TRUE },
1079 { FALSE, TRUE, TRUE },
1080 { FALSE, FALSE, TRUE },
1081 { TRUE, FALSE, FALSE },
1082 { FALSE, FALSE, FALSE },
1083 };
1084
1085 int i = 0;
1086 int nCfgs = This->adapter->nCfgs;
1087
1088 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, findCompatible=%d\n",
1089 debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format),
1090 auxBuffers, numSamples, findCompatible);
1091
1092 if (!getColorBits(color_format_desc, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
1093 {
1094 ERR("Unable to get color bits for format %s (%#x)!\n",
1095 debug_d3dformat(color_format_desc->format), color_format_desc->format);
1096 return 0;
1097 }
1098
1099 getDepthStencilBits(ds_format_desc, &depthBits, &stencilBits);
1100
1101 for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
1102 for(i=0; i<nCfgs; i++) {
1103 BOOL exactDepthMatch = TRUE;
1104 WineD3D_PixelFormat *cfg = &This->adapter->cfgs[i];
1105
1106 /* For now only accept RGBA formats. Perhaps some day we will
1107 * allow floating point formats for pbuffers. */
1108 if(cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1109 continue;
1110
1111 /* In window mode we need a window drawable format and double buffering. */
1112 if(!(cfg->windowDrawable && cfg->doubleBuffer))
1113 continue;
1114
1115 /* We like to have aux buffers in backbuffer mode */
1116 if(auxBuffers && !cfg->auxBuffers && matches[matchtry].require_aux)
1117 continue;
1118
1119 if(matches[matchtry].exact_color) {
1120 if(cfg->redSize != redBits)
1121 continue;
1122 if(cfg->greenSize != greenBits)
1123 continue;
1124 if(cfg->blueSize != blueBits)
1125 continue;
1126 } else {
1127 if(cfg->redSize < redBits)
1128 continue;
1129 if(cfg->greenSize < greenBits)
1130 continue;
1131 if(cfg->blueSize < blueBits)
1132 continue;
1133 }
1134 if(matches[matchtry].exact_alpha) {
1135 if(cfg->alphaSize != alphaBits)
1136 continue;
1137 } else {
1138 if(cfg->alphaSize < alphaBits)
1139 continue;
1140 }
1141
1142 /* We try to locate a format which matches our requirements exactly. In case of
1143 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1144 if(cfg->depthSize < depthBits)
1145 continue;
1146 else if(cfg->depthSize > depthBits)
1147 exactDepthMatch = FALSE;
1148
1149 /* In all cases make sure the number of stencil bits matches our requirements
1150 * even when we don't need stencil because it could affect performance EXCEPT
1151 * on cards which don't offer depth formats without stencil like the i915 drivers
1152 * on Linux. */
1153 if(stencilBits != cfg->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfg->stencilSize))
1154 continue;
1155
1156 /* Check multisampling support */
1157 if(cfg->numSamples != numSamples)
1158 continue;
1159
1160 /* When we have passed all the checks then we have found a format which matches our
1161 * requirements. Note that we only check for a limit number of capabilities right now,
1162 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
1163 * can still differ in things like multisampling, stereo, SRGB and other flags.
1164 */
1165
1166 /* Exit the loop as we have found a format :) */
1167 if(exactDepthMatch) {
1168 iPixelFormat = cfg->iPixelFormat;
1169 break;
1170 } else if(!iPixelFormat) {
1171 /* In the end we might end up with a format which doesn't exactly match our depth
1172 * requirements. Accept the first format we found because formats with higher iPixelFormat
1173 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
1174 iPixelFormat = cfg->iPixelFormat;
1175 }
1176 }
1177 }
1178
1179 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1180 if(!iPixelFormat && !findCompatible) {
1181 ERR("Can't find a suitable iPixelFormat\n");
1182 return FALSE;
1183 } else if(!iPixelFormat) {
1184 PIXELFORMATDESCRIPTOR pfd;
1185
1186 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1187 /* PixelFormat selection */
1188 ZeroMemory(&pfd, sizeof(pfd));
1189 pfd.nSize = sizeof(pfd);
1190 pfd.nVersion = 1;
1191 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1192 pfd.iPixelType = PFD_TYPE_RGBA;
1193 pfd.cAlphaBits = alphaBits;
1194 pfd.cColorBits = colorBits;
1195 pfd.cDepthBits = depthBits;
1196 pfd.cStencilBits = stencilBits;
1197 pfd.iLayerType = PFD_MAIN_PLANE;
1198
1199 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1200 if(!iPixelFormat) {
1201 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1202 ERR("Can't find a suitable iPixelFormat\n");
1203 return FALSE;
1204 }
1205 }
1206
1207 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1208 iPixelFormat, debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format));
1209 return iPixelFormat;
1210}
1211
1212/*****************************************************************************
1213 * context_create
1214 *
1215 * Creates a new context.
1216 *
1217 * * Params:
1218 * This: Device to activate the context for
1219 * target: Surface this context will render to
1220 * win_handle: handle to the window which we are drawing to
1221 * pPresentParameters: contains the pixelformats to use for onscreen rendering
1222 *
1223 *****************************************************************************/
1224struct wined3d_context *context_create(IWineD3DSwapChainImpl *swapchain, IWineD3DSurfaceImpl *target,
1225 const struct wined3d_format_desc *ds_format_desc)
1226{
1227 IWineD3DDeviceImpl *device = swapchain->device;
1228 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1229 const struct wined3d_format_desc *color_format_desc;
1230 struct wined3d_context *ret;
1231 PIXELFORMATDESCRIPTOR pfd;
1232 BOOL auxBuffers = FALSE;
1233 int numSamples = 0;
1234 int pixel_format;
1235 unsigned int s;
1236 DWORD state;
1237 HGLRC ctx;
1238 HDC hdc;
1239
1240 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1241
1242 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1243 if (!ret)
1244 {
1245 ERR("Failed to allocate context memory.\n");
1246 return NULL;
1247 }
1248
1249 if (!(hdc = GetDC(swapchain->win_handle)))
1250 {
1251 ERR("Failed to retrieve a device context.\n");
1252 goto out;
1253 }
1254
1255 color_format_desc = target->resource.format_desc;
1256
1257 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1258 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1259 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1260 {
1261 auxBuffers = TRUE;
1262
1263 if (color_format_desc->format == WINED3DFMT_B4G4R4X4_UNORM)
1264 color_format_desc = getFormatDescEntry(WINED3DFMT_B4G4R4A4_UNORM, gl_info);
1265 else if (color_format_desc->format == WINED3DFMT_B8G8R8X8_UNORM)
1266 color_format_desc = getFormatDescEntry(WINED3DFMT_B8G8R8A8_UNORM, gl_info);
1267 }
1268
1269 /* DirectDraw supports 8bit paletted render targets and these are used by
1270 * old games like Starcraft and C&C. Most modern hardware doesn't support
1271 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1272 * conversion (ab)uses the alpha component for storing the palette index.
1273 * For this reason we require a format with 8bit alpha, so request
1274 * A8R8G8B8. */
1275 if (color_format_desc->format == WINED3DFMT_P8_UINT)
1276 color_format_desc = getFormatDescEntry(WINED3DFMT_B8G8R8A8_UNORM, gl_info);
1277
1278 /* Retrieve the depth stencil format from the present parameters.
1279 * The choice of the proper format can give a nice performance boost
1280 * in case of GPU limited programs. */
1281 if (swapchain->presentParms.EnableAutoDepthStencil)
1282 {
1283 TRACE("Auto depth stencil enabled, using format %s.\n",
1284 debug_d3dformat(swapchain->presentParms.AutoDepthStencilFormat));
1285 ds_format_desc = getFormatDescEntry(swapchain->presentParms.AutoDepthStencilFormat, gl_info);
1286 }
1287
1288 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD. */
1289 if (swapchain->presentParms.MultiSampleType && (swapchain->presentParms.SwapEffect == WINED3DSWAPEFFECT_DISCARD))
1290 {
1291 if (!gl_info->supported[ARB_MULTISAMPLE])
1292 WARN("The application is requesting multisampling without support.\n");
1293 else
1294 {
1295 TRACE("Requesting multisample type %#x.\n", swapchain->presentParms.MultiSampleType);
1296 numSamples = swapchain->presentParms.MultiSampleType;
1297 }
1298 }
1299
1300 /* Try to find a pixel format which matches our requirements. */
1301 pixel_format = WineD3D_ChoosePixelFormat(device, hdc, color_format_desc, ds_format_desc,
1302 auxBuffers, numSamples, FALSE /* findCompatible */);
1303
1304 /* Try to locate a compatible format if we weren't able to find anything. */
1305 if (!pixel_format)
1306 {
1307 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1308 pixel_format = WineD3D_ChoosePixelFormat(device, hdc, color_format_desc, ds_format_desc,
1309 auxBuffers, 0 /* numSamples */, TRUE /* findCompatible */);
1310 }
1311
1312 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1313 if (!pixel_format)
1314 {
1315 ERR("Can't find a suitable pixel format.\n");
1316 goto out;
1317 }
1318
1319 DescribePixelFormat(hdc, pixel_format, sizeof(pfd), &pfd);
1320 if (!context_set_pixel_format(gl_info, hdc, pixel_format))
1321 {
1322 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1323 goto out;
1324 }
1325
1326 ctx = pwglCreateContext(hdc);
1327 if (device->numContexts)
1328 {
1329 if (!pwglShareLists(device->contexts[0]->glCtx, ctx))
1330 {
1331 DWORD err = GetLastError();
1332 ERR("wglShareLists(%p, %p) failed, last error %#x.\n",
1333 device->contexts[0]->glCtx, ctx, err);
1334 }
1335 }
1336
1337 if(!ctx) {
1338 ERR("Failed to create a WGL context\n");
1339 goto out;
1340 }
1341
1342 if (!device_context_add(device, ret))
1343 {
1344 ERR("Failed to add the newly created context to the context list\n");
1345 if (!pwglDeleteContext(ctx))
1346 {
1347 DWORD err = GetLastError();
1348 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, err);
1349 }
1350 goto out;
1351 }
1352
1353 ret->gl_info = gl_info;
1354
1355 /* Mark all states dirty to force a proper initialization of the states
1356 * on the first use of the context. */
1357 for (state = 0; state <= STATE_HIGHEST; ++state)
1358 {
1359 if (device->StateTable[state].representative)
1360 Context_MarkStateDirty(ret, state, device->StateTable);
1361 }
1362
1363 ret->swapchain = swapchain;
1364 ret->current_rt = (IWineD3DSurface *)target;
1365 ret->tid = GetCurrentThreadId();
1366
1367 ret->render_offscreen = surface_is_offscreen((IWineD3DSurface *) target);
1368 ret->draw_buffer_dirty = TRUE;
1369 ret->valid = 1;
1370
1371 ret->glCtx = ctx;
1372 ret->win_handle = swapchain->win_handle;
1373 ret->hdc = hdc;
1374 ret->pixel_format = pixel_format;
1375
1376 if (device->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *)device))
1377 {
1378 /* Create the dirty constants array and initialize them to dirty */
1379 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
1380 sizeof(*ret->vshader_const_dirty) * device->d3d_vshader_constantF);
1381 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
1382 sizeof(*ret->pshader_const_dirty) * device->d3d_pshader_constantF);
1383 memset(ret->vshader_const_dirty, 1,
1384 sizeof(*ret->vshader_const_dirty) * device->d3d_vshader_constantF);
1385 memset(ret->pshader_const_dirty, 1,
1386 sizeof(*ret->pshader_const_dirty) * device->d3d_pshader_constantF);
1387 }
1388
1389 ret->free_occlusion_query_size = 4;
1390 ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1391 ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1392 if (!ret->free_occlusion_queries) goto out;
1393
1394 list_init(&ret->occlusion_queries);
1395
1396 ret->free_event_query_size = 4;
1397 ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1398 ret->free_event_query_size * sizeof(*ret->free_event_queries));
1399 if (!ret->free_event_queries) goto out;
1400
1401 list_init(&ret->event_queries);
1402
1403 TRACE("Successfully created new context %p\n", ret);
1404
1405 list_init(&ret->fbo_list);
1406 list_init(&ret->fbo_destroy_list);
1407
1408 context_enter(ret);
1409
1410 /* Set up the context defaults */
1411 if (!context_set_current(ret))
1412 {
1413 ERR("Cannot activate context to set up defaults\n");
1414 context_release(ret);
1415 goto out;
1416 }
1417
1418 ENTER_GL();
1419
1420 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1421
1422 TRACE("Setting up the screen\n");
1423 /* Clear the screen */
1424 glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
1425 checkGLcall("glClearColor");
1426 glClearIndex(0);
1427 glClearDepth(1);
1428 glClearStencil(0xffff);
1429
1430 checkGLcall("glClear");
1431
1432 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1433 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1434
1435 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1436 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1437
1438 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1439 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1440
1441 glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1442 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1443 glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);
1444 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1445
1446 if (gl_info->supported[APPLE_CLIENT_STORAGE])
1447 {
1448 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
1449 * and textures in DIB sections(due to the memory protection).
1450 */
1451 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1452 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1453 }
1454 if (gl_info->supported[ARB_VERTEX_BLEND])
1455 {
1456 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
1457 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
1458 * GL_VERTEX_BLEND_ARB isn't enabled too
1459 */
1460 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1461 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1462 }
1463 if (gl_info->supported[NV_TEXTURE_SHADER2])
1464 {
1465 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1466 * the previous texture where to source the offset from is always unit - 1.
1467 */
1468 for (s = 1; s < gl_info->limits.textures; ++s)
1469 {
1470 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1471 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1472 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1473 }
1474 }
1475 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1476 {
1477 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1478 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1479 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1480 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1481 * is ever assigned.
1482 *
1483 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1484 * program and the dummy program is destroyed when the context is destroyed.
1485 */
1486 const char *dummy_program =
1487 "!!ARBfp1.0\n"
1488 "MOV result.color, fragment.color.primary;\n"
1489 "END\n";
1490 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1491 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1492 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1493 }
1494
1495 for (s = 0; s < gl_info->limits.point_sprite_units; ++s)
1496 {
1497 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1498 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1499 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1500 }
1501
1502 if (gl_info->supported[ARB_PROVOKING_VERTEX])
1503 {
1504 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1505 }
1506 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1507 {
1508 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1509 }
1510
1511#ifdef VBOXWDDM
1512 GL_EXTCALL(glChromiumParameteriCR(GL_SHARE_CONTEXT_RESOURCES_CR, GL_TRUE));
1513#endif
1514
1515 LEAVE_GL();
1516
1517 device->frag_pipe->enable_extension((IWineD3DDevice *)device, TRUE);
1518
1519 TRACE("Created context %p.\n", ret);
1520
1521 return ret;
1522
1523out:
1524 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1525 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1526 HeapFree(GetProcessHeap(), 0, ret->pshader_const_dirty);
1527 HeapFree(GetProcessHeap(), 0, ret->vshader_const_dirty);
1528 HeapFree(GetProcessHeap(), 0, ret);
1529 return NULL;
1530}
1531
1532/*****************************************************************************
1533 * context_destroy
1534 *
1535 * Destroys a wined3d context
1536 *
1537 * Params:
1538 * This: Device to activate the context for
1539 * context: Context to destroy
1540 *
1541 *****************************************************************************/
1542void context_destroy(IWineD3DDeviceImpl *This, struct wined3d_context *context)
1543{
1544 BOOL destroy;
1545
1546 TRACE("Destroying ctx %p\n", context);
1547
1548 if (context->tid == GetCurrentThreadId() || !context->current)
1549 {
1550 context_destroy_gl_resources(context);
1551 TlsSetValue(wined3d_context_tls_idx, NULL);
1552 destroy = TRUE;
1553 }
1554 else
1555 {
1556 context->destroyed = 1;
1557 destroy = FALSE;
1558 }
1559
1560 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
1561 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
1562 device_context_remove(This, context);
1563 if (destroy) HeapFree(GetProcessHeap(), 0, context);
1564}
1565
1566/* GL locking is done by the caller */
1567static inline void set_blit_dimension(UINT width, UINT height) {
1568 glMatrixMode(GL_PROJECTION);
1569 checkGLcall("glMatrixMode(GL_PROJECTION)");
1570 glLoadIdentity();
1571 checkGLcall("glLoadIdentity()");
1572 glOrtho(0, width, height, 0, 0.0, -1.0);
1573 checkGLcall("glOrtho");
1574 glViewport(0, 0, width, height);
1575 checkGLcall("glViewport");
1576}
1577
1578/*****************************************************************************
1579 * SetupForBlit
1580 *
1581 * Sets up a context for DirectDraw blitting.
1582 * All texture units are disabled, texture unit 0 is set as current unit
1583 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1584 * color writing enabled for all channels
1585 * register combiners disabled, shaders disabled
1586 * world matrix is set to identity, texture matrix 0 too
1587 * projection matrix is setup for drawing screen coordinates
1588 *
1589 * Params:
1590 * This: Device to activate the context for
1591 * context: Context to setup
1592 *
1593 *****************************************************************************/
1594/* Context activation is done by the caller. */
1595static void SetupForBlit(IWineD3DDeviceImpl *This, struct wined3d_context *context)
1596{
1597 int i;
1598 const struct StateEntry *StateTable = This->StateTable;
1599 const struct wined3d_gl_info *gl_info = context->gl_info;
1600 UINT width = ((IWineD3DSurfaceImpl *)context->current_rt)->currentDesc.Width;
1601 UINT height = ((IWineD3DSurfaceImpl *)context->current_rt)->currentDesc.Height;
1602 DWORD sampler;
1603
1604 TRACE("Setting up context %p for blitting\n", context);
1605 if(context->last_was_blit) {
1606 if(context->blit_w != width || context->blit_h != height) {
1607 ENTER_GL();
1608 set_blit_dimension(width, height);
1609 LEAVE_GL();
1610 context->blit_w = width; context->blit_h = height;
1611 /* No need to dirtify here, the states are still dirtified because they weren't
1612 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1613 * be set
1614 */
1615 }
1616 TRACE("Context is already set up for blitting, nothing to do\n");
1617 return;
1618 }
1619 context->last_was_blit = TRUE;
1620
1621 /* TODO: Use a display list */
1622
1623 /* Disable shaders */
1624 ENTER_GL();
1625 This->shader_backend->shader_select(context, FALSE, FALSE);
1626 LEAVE_GL();
1627
1628 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
1629 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
1630
1631 /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1632 * helper functions in between gl calls. This function is full of Context_MarkStateDirty
1633 * which can safely be called from here, we only lock once instead locking/unlocking
1634 * after each GL call.
1635 */
1636 ENTER_GL();
1637
1638 /* Disable all textures. The caller can then bind a texture it wants to blit
1639 * from
1640 *
1641 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1642 * function texture unit. No need to care for higher samplers
1643 */
1644 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
1645 {
1646 sampler = This->rev_tex_unit_map[i];
1647 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1648 checkGLcall("glActiveTextureARB");
1649
1650 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1651 {
1652 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1653 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1654 }
1655 glDisable(GL_TEXTURE_3D);
1656 checkGLcall("glDisable GL_TEXTURE_3D");
1657 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1658 {
1659 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1660 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1661 }
1662 glDisable(GL_TEXTURE_2D);
1663 checkGLcall("glDisable GL_TEXTURE_2D");
1664
1665 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1666 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1667
1668 if (sampler != WINED3D_UNMAPPED_STAGE)
1669 {
1670 if (sampler < MAX_TEXTURES) {
1671 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1672 }
1673 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1674 }
1675 }
1676 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
1677 checkGLcall("glActiveTextureARB");
1678
1679 sampler = This->rev_tex_unit_map[0];
1680
1681 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1682 {
1683 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1684 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1685 }
1686 glDisable(GL_TEXTURE_3D);
1687 checkGLcall("glDisable GL_TEXTURE_3D");
1688 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1689 {
1690 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1691 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1692 }
1693 glDisable(GL_TEXTURE_2D);
1694 checkGLcall("glDisable GL_TEXTURE_2D");
1695
1696 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1697
1698 glMatrixMode(GL_TEXTURE);
1699 checkGLcall("glMatrixMode(GL_TEXTURE)");
1700 glLoadIdentity();
1701 checkGLcall("glLoadIdentity()");
1702
1703 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
1704 {
1705 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1706 GL_TEXTURE_LOD_BIAS_EXT,
1707 0.0f);
1708 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1709 }
1710
1711 if (sampler != WINED3D_UNMAPPED_STAGE)
1712 {
1713 if (sampler < MAX_TEXTURES) {
1714 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
1715 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1716 }
1717 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1718 }
1719
1720 /* Other misc states */
1721 glDisable(GL_ALPHA_TEST);
1722 checkGLcall("glDisable(GL_ALPHA_TEST)");
1723 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
1724 glDisable(GL_LIGHTING);
1725 checkGLcall("glDisable GL_LIGHTING");
1726 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
1727 glDisable(GL_DEPTH_TEST);
1728 checkGLcall("glDisable GL_DEPTH_TEST");
1729 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
1730 glDisableWINE(GL_FOG);
1731 checkGLcall("glDisable GL_FOG");
1732 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
1733 glDisable(GL_BLEND);
1734 checkGLcall("glDisable GL_BLEND");
1735 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1736 glDisable(GL_CULL_FACE);
1737 checkGLcall("glDisable GL_CULL_FACE");
1738 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
1739 glDisable(GL_STENCIL_TEST);
1740 checkGLcall("glDisable GL_STENCIL_TEST");
1741 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
1742 glDisable(GL_SCISSOR_TEST);
1743 checkGLcall("glDisable GL_SCISSOR_TEST");
1744 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1745 if (gl_info->supported[ARB_POINT_SPRITE])
1746 {
1747 glDisable(GL_POINT_SPRITE_ARB);
1748 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1749 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
1750 }
1751 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1752 checkGLcall("glColorMask");
1753 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE), StateTable);
1754 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1), StateTable);
1755 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2), StateTable);
1756 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3), StateTable);
1757 if (gl_info->supported[EXT_SECONDARY_COLOR])
1758 {
1759 glDisable(GL_COLOR_SUM_EXT);
1760 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
1761 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1762 }
1763
1764 /* Setup transforms */
1765 glMatrixMode(GL_MODELVIEW);
1766 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1767 glLoadIdentity();
1768 checkGLcall("glLoadIdentity()");
1769 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
1770
1771 context->last_was_rhw = TRUE;
1772 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
1773
1774 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1775 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1776 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1777 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1778 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1779 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1780 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1781
1782 set_blit_dimension(width, height);
1783
1784 LEAVE_GL();
1785
1786 context->blit_w = width; context->blit_h = height;
1787 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1788 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1789
1790
1791 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1792}
1793
1794/*****************************************************************************
1795 * findThreadContextForSwapChain
1796 *
1797 * Searches a swapchain for all contexts and picks one for the thread tid.
1798 * If none can be found the swapchain is requested to create a new context
1799 *
1800 *****************************************************************************/
1801static struct wined3d_context *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid)
1802{
1803 unsigned int i;
1804
1805 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
1806 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
1807 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
1808 }
1809
1810 }
1811
1812 /* Create a new context for the thread */
1813 return swapchain_create_context_for_thread(swapchain);
1814}
1815
1816/*****************************************************************************
1817 * FindContext
1818 *
1819 * Finds a context for the current render target and thread
1820 *
1821 * Parameters:
1822 * target: Render target to find the context for
1823 * tid: Thread to activate the context for
1824 *
1825 * Returns: The needed context
1826 *
1827 *****************************************************************************/
1828static struct wined3d_context *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target)
1829{
1830 IWineD3DSwapChain *swapchain = NULL;
1831 struct wined3d_context *current_context = context_get_current();
1832 DWORD tid = GetCurrentThreadId();
1833 struct wined3d_context *context;
1834
1835 if (current_context && current_context->destroyed) current_context = NULL;
1836
1837 if (!target)
1838 {
1839 if (current_context
1840 && current_context->current_rt
1841 && current_context->swapchain->device == This)
1842 {
1843 target = current_context->current_rt;
1844 }
1845 else
1846 {
1847 IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)This->swapchains[0];
1848 if (swapchain->backBuffer) target = swapchain->backBuffer[0];
1849 else target = swapchain->frontBuffer;
1850 }
1851 }
1852
1853 if (current_context && current_context->current_rt == target)
1854 {
1855 context_validate(current_context);
1856 return current_context;
1857 }
1858
1859 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
1860 TRACE("Rendering onscreen\n");
1861
1862 context = findThreadContextForSwapChain(swapchain, tid);
1863 IWineD3DSwapChain_Release(swapchain);
1864 }
1865 else
1866 {
1867 TRACE("Rendering offscreen\n");
1868
1869 /* Stay with the currently active context. */
1870 if (current_context && current_context->swapchain->device == This)
1871 {
1872 context = current_context;
1873 }
1874 else
1875 {
1876 /* This may happen if the app jumps straight into offscreen rendering
1877 * Start using the context of the primary swapchain. tid == 0 is no problem
1878 * for findThreadContextForSwapChain.
1879 *
1880 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1881 * is perfect to call. */
1882 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1883 }
1884 }
1885
1886 context_validate(context);
1887
1888 return context;
1889}
1890
1891/* Context activation is done by the caller. */
1892static void context_apply_draw_buffer(struct wined3d_context *context, BOOL blit)
1893{
1894 const struct wined3d_gl_info *gl_info = context->gl_info;
1895 IWineD3DSurface *rt = context->current_rt;
1896 IWineD3DDeviceImpl *device;
1897
1898 device = ((IWineD3DSurfaceImpl *)rt)->resource.device;
1899 if (!surface_is_offscreen(rt))
1900 {
1901 ENTER_GL();
1902 glDrawBuffer(surface_get_gl_buffer(rt));
1903 checkGLcall("glDrawBuffers()");
1904 LEAVE_GL();
1905 }
1906 else
1907 {
1908 ENTER_GL();
1909 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1910 {
1911 if (!blit)
1912 {
1913 if (gl_info->supported[ARB_DRAW_BUFFERS])
1914 {
1915 GL_EXTCALL(glDrawBuffersARB(gl_info->limits.buffers, device->draw_buffers));
1916 checkGLcall("glDrawBuffers()");
1917 }
1918 else
1919 {
1920 glDrawBuffer(device->draw_buffers[0]);
1921 checkGLcall("glDrawBuffer()");
1922 }
1923 } else {
1924 glDrawBuffer(GL_COLOR_ATTACHMENT0);
1925 checkGLcall("glDrawBuffer()");
1926 }
1927 }
1928 else
1929 {
1930 glDrawBuffer(device->offscreenBuffer);
1931 checkGLcall("glDrawBuffer()");
1932 }
1933 LEAVE_GL();
1934 }
1935}
1936
1937/* GL locking is done by the caller. */
1938void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
1939{
1940 glDrawBuffer(buffer);
1941 checkGLcall("glDrawBuffer()");
1942 context->draw_buffer_dirty = TRUE;
1943}
1944
1945static inline void context_set_render_offscreen(struct wined3d_context *context, const struct StateEntry *StateTable,
1946 BOOL offscreen)
1947{
1948 if (context->render_offscreen == offscreen) return;
1949
1950 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1951 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1952 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1953 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1954 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1955 context->render_offscreen = offscreen;
1956}
1957
1958static BOOL match_depth_stencil_format(const struct wined3d_format_desc *existing,
1959 const struct wined3d_format_desc *required)
1960{
1961 short existing_depth, existing_stencil, required_depth, required_stencil;
1962
1963 if(existing == required) return TRUE;
1964 if((existing->Flags & WINED3DFMT_FLAG_FLOAT) != (required->Flags & WINED3DFMT_FLAG_FLOAT)) return FALSE;
1965
1966 getDepthStencilBits(existing, &existing_depth, &existing_stencil);
1967 getDepthStencilBits(required, &required_depth, &required_stencil);
1968
1969 if(existing_depth < required_depth) return FALSE;
1970 /* If stencil bits are used the exact amount is required - otherwise wrapping
1971 * won't work correctly */
1972 if(required_stencil && required_stencil != existing_stencil) return FALSE;
1973 return TRUE;
1974}
1975/* The caller provides a context */
1976static void context_validate_onscreen_formats(IWineD3DDeviceImpl *device, struct wined3d_context *context)
1977{
1978 /* Onscreen surfaces are always in a swapchain */
1979 IWineD3DSurfaceImpl *depth_stencil = (IWineD3DSurfaceImpl *) device->stencilBufferTarget;
1980 IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *) ((IWineD3DSurfaceImpl *)context->current_rt)->container;
1981
1982 if (!depth_stencil) return;
1983 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->resource.format_desc)) return;
1984
1985 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
1986 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
1987 * format. */
1988 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
1989
1990 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
1991 IWineD3DSurface_LoadLocation(context->current_rt, SFLAG_INTEXTURE, NULL);
1992 swapchain->render_to_fbo = TRUE;
1993 context_set_render_offscreen(context, device->StateTable, TRUE);
1994}
1995
1996/* Context activation is done by the caller. */
1997static void context_apply_state(struct wined3d_context *context, IWineD3DDeviceImpl *device, enum ContextUsage usage)
1998{
1999 const struct StateEntry *state_table = device->StateTable;
2000 unsigned int i;
2001
2002 switch (usage) {
2003 case CTXUSAGE_CLEAR:
2004 case CTXUSAGE_DRAWPRIM:
2005 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
2006 if (!context->render_offscreen) context_validate_onscreen_formats(device, context);
2007 ENTER_GL();
2008 context_apply_fbo_state(context);
2009 LEAVE_GL();
2010 }
2011 if (context->draw_buffer_dirty) {
2012 context_apply_draw_buffer(context, FALSE);
2013 context->draw_buffer_dirty = FALSE;
2014 }
2015 break;
2016
2017 case CTXUSAGE_BLIT:
2018 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
2019 if (!context->render_offscreen) context_validate_onscreen_formats(device, context);
2020 if (context->render_offscreen)
2021 {
2022 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
2023 surface_internal_preload(context->current_rt, SRGB_RGB);
2024
2025 ENTER_GL();
2026 context_bind_fbo(context, GL_FRAMEBUFFER, &context->dst_fbo);
2027 context_attach_surface_fbo(context, GL_FRAMEBUFFER, 0, (IWineD3DSurfaceImpl *)context->current_rt);
2028 context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER, NULL, FALSE);
2029 LEAVE_GL();
2030 } else {
2031 ENTER_GL();
2032 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
2033 LEAVE_GL();
2034 }
2035 context->draw_buffer_dirty = TRUE;
2036 }
2037 if (context->draw_buffer_dirty) {
2038 context_apply_draw_buffer(context, TRUE);
2039 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
2040 context->draw_buffer_dirty = FALSE;
2041 }
2042 }
2043 break;
2044
2045 default:
2046 break;
2047 }
2048
2049 switch(usage) {
2050 case CTXUSAGE_RESOURCELOAD:
2051 /* This does not require any special states to be set up */
2052 break;
2053
2054 case CTXUSAGE_CLEAR:
2055 if(context->last_was_blit) {
2056 device->frag_pipe->enable_extension((IWineD3DDevice *)device, TRUE);
2057 }
2058
2059 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
2060 * blending when clearing improves the clearing performance incredibly.
2061 */
2062 ENTER_GL();
2063 glDisable(GL_BLEND);
2064 LEAVE_GL();
2065 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), state_table);
2066
2067 ENTER_GL();
2068 glEnable(GL_SCISSOR_TEST);
2069 checkGLcall("glEnable GL_SCISSOR_TEST");
2070 LEAVE_GL();
2071 context->last_was_blit = FALSE;
2072 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), state_table);
2073 Context_MarkStateDirty(context, STATE_SCISSORRECT, state_table);
2074 break;
2075
2076 case CTXUSAGE_DRAWPRIM:
2077 /* This needs all dirty states applied */
2078 if(context->last_was_blit) {
2079 device->frag_pipe->enable_extension((IWineD3DDevice *)device, TRUE);
2080 }
2081
2082 IWineD3DDeviceImpl_FindTexUnitMap(device);
2083 device_preload_textures(device);
2084 if (isStateDirty(context, STATE_VDECL))
2085 device_update_stream_info(device, context->gl_info);
2086
2087 ENTER_GL();
2088 for (i = 0; i < context->numDirtyEntries; ++i)
2089 {
2090 DWORD rep = context->dirtyArray[i];
2091 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
2092 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
2093 context->isStateDirty[idx] &= ~(1 << shift);
2094 state_table[rep].apply(rep, device->stateBlock, context);
2095 }
2096 LEAVE_GL();
2097 context->numDirtyEntries = 0; /* This makes the whole list clean */
2098 context->last_was_blit = FALSE;
2099 break;
2100
2101 case CTXUSAGE_BLIT:
2102 SetupForBlit(device, context);
2103 break;
2104
2105 default:
2106 FIXME("Unexpected context usage requested\n");
2107 }
2108}
2109
2110static void context_setup_target(IWineD3DDeviceImpl *device, struct wined3d_context *context, IWineD3DSurface *target)
2111{
2112 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
2113 const struct StateEntry *StateTable = device->StateTable;
2114
2115 if (!target) return;
2116 else if (context->current_rt == target) return;
2117 render_offscreen = surface_is_offscreen(target);
2118
2119 context_set_render_offscreen(context, StateTable, render_offscreen);
2120
2121 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
2122 * the alpha blend state changes with different render target formats. */
2123 if (!context->current_rt)
2124 {
2125 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
2126 }
2127 else
2128 {
2129 const struct wined3d_format_desc *old = ((IWineD3DSurfaceImpl *)context->current_rt)->resource.format_desc;
2130 const struct wined3d_format_desc *new = ((IWineD3DSurfaceImpl *)target)->resource.format_desc;
2131
2132 if (old->format != new->format)
2133 {
2134 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
2135 if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
2136 || !(new->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
2137 {
2138 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
2139 }
2140 }
2141
2142 /* When switching away from an offscreen render target, and we're not
2143 * using FBOs, we have to read the drawable into the texture. This is
2144 * done via PreLoad (and SFLAG_INDRAWABLE set on the surface). There
2145 * are some things that need care though. PreLoad needs a GL context,
2146 * and FindContext is called before the context is activated. It also
2147 * has to be called with the old rendertarget active, otherwise a
2148 * wrong drawable is read. */
2149 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
2150 && old_render_offscreen && context->current_rt != target)
2151 {
2152 BOOL oldInDraw = device->isInDraw;
2153
2154 /* surface_internal_preload() requires a context to load the
2155 * texture, so it will call context_acquire(). Set isInDraw to true
2156 * to signal surface_internal_preload() that it has a context. */
2157
2158 /* FIXME: This is just broken. There's no guarantee whatsoever
2159 * that the currently active context, if any, is appropriate for
2160 * reading back the render target. We should probably call
2161 * context_set_current(context) here and then rely on
2162 * context_acquire() doing the right thing. */
2163 device->isInDraw = TRUE;
2164
2165 /* Read the back buffer of the old drawable into the destination texture. */
2166 if (((IWineD3DSurfaceImpl *)context->current_rt)->texture_name_srgb)
2167 {
2168 surface_internal_preload(context->current_rt, SRGB_BOTH);
2169 }
2170 else
2171 {
2172 surface_internal_preload(context->current_rt, SRGB_RGB);
2173 }
2174
2175 IWineD3DSurface_ModifyLocation(context->current_rt, SFLAG_INDRAWABLE, FALSE);
2176
2177 device->isInDraw = oldInDraw;
2178 }
2179 }
2180
2181 context->draw_buffer_dirty = TRUE;
2182 context->current_rt = target;
2183}
2184
2185/*****************************************************************************
2186 * context_acquire
2187 *
2188 * Finds a rendering context and drawable matching the device and render
2189 * target for the current thread, activates them and puts them into the
2190 * requested state.
2191 *
2192 * Params:
2193 * This: Device to activate the context for
2194 * target: Requested render target
2195 * usage: Prepares the context for blitting, drawing or other actions
2196 *
2197 *****************************************************************************/
2198struct wined3d_context *context_acquire(IWineD3DDeviceImpl *device, IWineD3DSurface *target, enum ContextUsage usage)
2199{
2200 struct wined3d_context *current_context = context_get_current();
2201 struct wined3d_context *context;
2202
2203 TRACE("device %p, target %p, usage %#x.\n", device, target, usage);
2204
2205 context = FindContext(device, target);
2206 context_setup_target(device, context, target);
2207 context_enter(context);
2208 if (!context->valid) return context;
2209
2210 if (context != current_context)
2211 {
2212 if (!context_set_current(context)) ERR("Failed to activate the new context.\n");
2213 else device->frag_pipe->enable_extension((IWineD3DDevice *)device, !context->last_was_blit);
2214
2215 if (context->vshader_const_dirty)
2216 {
2217 memset(context->vshader_const_dirty, 1,
2218 sizeof(*context->vshader_const_dirty) * device->d3d_vshader_constantF);
2219 device->highest_dirty_vs_const = device->d3d_vshader_constantF;
2220 }
2221 if (context->pshader_const_dirty)
2222 {
2223 memset(context->pshader_const_dirty, 1,
2224 sizeof(*context->pshader_const_dirty) * device->d3d_pshader_constantF);
2225 device->highest_dirty_ps_const = device->d3d_pshader_constantF;
2226 }
2227 }
2228 else if (context->restore_ctx)
2229 {
2230 if (!pwglMakeCurrent(context->hdc, context->glCtx))
2231 {
2232 DWORD err = GetLastError();
2233 ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
2234 context->hdc, context->glCtx, err);
2235 }
2236 }
2237
2238 context_apply_state(context, device, usage);
2239
2240 return context;
2241}
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette