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