VirtualBox

source: vbox/trunk/src/VBox/Devices/Graphics/DevVGA-SVGA3d-ogl.cpp@ 95232

Last change on this file since 95232 was 95232, checked in by vboxsync, 2 years ago

Devices/Graphics: track constant, vertex, index buffers; clear resource view entriee when surface is deleted (doxygen fix). bugref:9830

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 310.9 KB
Line 
1/* $Id: DevVGA-SVGA3d-ogl.cpp 95232 2022-06-08 15:34:49Z vboxsync $ */
2/** @file
3 * DevVMWare - VMWare SVGA device
4 */
5
6/*
7 * Copyright (C) 2013-2022 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22/* Enable to disassemble defined shaders. (Windows host only) */
23#if defined(RT_OS_WINDOWS) && defined(DEBUG) && 0 /* Disabled as we don't have the DirectX SDK avaible atm. */
24# define DUMP_SHADER_DISASSEMBLY
25#endif
26#ifdef DEBUG_bird
27//# define RTMEM_WRAP_TO_EF_APIS
28#endif
29#define LOG_GROUP LOG_GROUP_DEV_VMSVGA
30#define GL_SILENCE_DEPRECATION /* shut up deprecated warnings on darwin (10.15 sdk) */
31#include <VBox/vmm/pdmdev.h>
32#include <VBox/version.h>
33#include <VBox/err.h>
34#include <VBox/log.h>
35#include <VBox/vmm/pgm.h>
36#include <VBox/AssertGuest.h>
37
38#include <iprt/assert.h>
39#include <iprt/semaphore.h>
40#include <iprt/uuid.h>
41#include <iprt/mem.h>
42
43#include <VBoxVideo.h> /* required by DevVGA.h */
44#include <VBoxVideo3D.h>
45
46/* should go BEFORE any other DevVGA include to make all DevVGA.h config defines be visible */
47#include "DevVGA.h"
48
49#include "DevVGA-SVGA.h"
50#include "DevVGA-SVGA3d.h"
51#include "DevVGA-SVGA3d-internal.h"
52
53#ifdef DUMP_SHADER_DISASSEMBLY
54# include <d3dx9shader.h>
55#endif
56
57#include <stdlib.h>
58#include <math.h>
59#include <float.h> /* FLT_MIN */
60
61
62/*********************************************************************************************************************************
63* Defined Constants And Macros *
64*********************************************************************************************************************************/
65#ifndef VBOX_VMSVGA3D_DEFAULT_OGL_PROFILE
66# define VBOX_VMSVGA3D_DEFAULT_OGL_PROFILE 1.0
67#endif
68
69#ifdef VMSVGA3D_DYNAMIC_LOAD
70# define OGLGETPROCADDRESS glLdrGetProcAddress
71#else
72#ifdef RT_OS_WINDOWS
73# define OGLGETPROCADDRESS MyWinGetProcAddress
74DECLINLINE(PROC) MyWinGetProcAddress(const char *pszSymbol)
75{
76 /* Khronos: [on failure] "some implementations will return other values. 1, 2, and 3 are used, as well as -1". */
77 PROC p = wglGetProcAddress(pszSymbol);
78 if (RT_VALID_PTR(p))
79 return p;
80 return 0;
81}
82#elif defined(RT_OS_DARWIN)
83# include <dlfcn.h>
84# define OGLGETPROCADDRESS MyNSGLGetProcAddress
85/** Resolves an OpenGL symbol. */
86static void *MyNSGLGetProcAddress(const char *pszSymbol)
87{
88 /* Another copy in shaderapi.c. */
89 static void *s_pvImage = NULL;
90 if (s_pvImage == NULL)
91 s_pvImage = dlopen("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", RTLD_LAZY);
92 return s_pvImage ? dlsym(s_pvImage, pszSymbol) : NULL;
93}
94
95#else
96# define OGLGETPROCADDRESS(x) glXGetProcAddress((const GLubyte *)x)
97#endif
98#endif
99
100/* Invert y-coordinate for OpenGL's bottom left origin. */
101#define D3D_TO_OGL_Y_COORD(ptrSurface, y_coordinate) (ptrSurface->paMipmapLevels[0].mipmapSize.height - (y_coordinate))
102#define D3D_TO_OGL_Y_COORD_MIPLEVEL(ptrMipLevel, y_coordinate) (ptrMipLevel->size.height - (y_coordinate))
103
104/**
105 * Macro for doing something and then checking for errors during initialization.
106 * Uses AssertLogRelMsg.
107 */
108#define VMSVGA3D_INIT_CHECKED(a_Expr) \
109 do \
110 { \
111 a_Expr; \
112 GLenum iGlError = glGetError(); \
113 AssertLogRelMsg(iGlError == GL_NO_ERROR, ("VMSVGA3d: %s -> %#x\n", #a_Expr, iGlError)); \
114 } while (0)
115
116/**
117 * Macro for doing something and then checking for errors during initialization,
118 * doing the same in the other context when enabled.
119 *
120 * This will try both profiles in dual profile builds. Caller must be in the
121 * default context.
122 *
123 * Uses AssertLogRelMsg to indicate trouble.
124 */
125#ifdef VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE
126# define VMSVGA3D_INIT_CHECKED_BOTH(a_pState, a_pContext, a_pOtherCtx, a_Expr) \
127 do \
128 { \
129 for (uint32_t i = 0; i < 64; i++) if (glGetError() == GL_NO_ERROR) break; Assert(glGetError() == GL_NO_ERROR); \
130 a_Expr; \
131 GLenum iGlError = glGetError(); \
132 if (iGlError != GL_NO_ERROR) \
133 { \
134 VMSVGA3D_SET_CURRENT_CONTEXT(a_pState, a_pOtherCtx); \
135 for (uint32_t i = 0; i < 64; i++) if (glGetError() == GL_NO_ERROR) break; Assert(glGetError() == GL_NO_ERROR); \
136 a_Expr; \
137 GLenum iGlError2 = glGetError(); \
138 AssertLogRelMsg(iGlError2 == GL_NO_ERROR, ("VMSVGA3d: %s -> %#x / %#x\n", #a_Expr, iGlError, iGlError2)); \
139 VMSVGA3D_SET_CURRENT_CONTEXT(a_pState, a_pContext); \
140 } \
141 } while (0)
142#else
143# define VMSVGA3D_INIT_CHECKED_BOTH(a_pState, a_pContext, a_pOtherCtx, a_Expr) VMSVGA3D_INIT_CHECKED(a_Expr)
144#endif
145
146
147/*********************************************************************************************************************************
148* Global Variables *
149*********************************************************************************************************************************/
150/* Define the default light parameters as specified by MSDN. */
151/** @todo move out; fetched from Wine */
152const SVGA3dLightData vmsvga3d_default_light =
153{
154 SVGA3D_LIGHTTYPE_DIRECTIONAL, /* type */
155 false, /* inWorldSpace */
156 { 1.0f, 1.0f, 1.0f, 0.0f }, /* diffuse r,g,b,a */
157 { 0.0f, 0.0f, 0.0f, 0.0f }, /* specular r,g,b,a */
158 { 0.0f, 0.0f, 0.0f, 0.0f }, /* ambient r,g,b,a, */
159 { 0.0f, 0.0f, 0.0f }, /* position x,y,z */
160 { 0.0f, 0.0f, 1.0f }, /* direction x,y,z */
161 0.0f, /* range */
162 0.0f, /* falloff */
163 0.0f, 0.0f, 0.0f, /* attenuation 0,1,2 */
164 0.0f, /* theta */
165 0.0f /* phi */
166};
167
168
169/*********************************************************************************************************************************
170* Internal Functions *
171*********************************************************************************************************************************/
172static int vmsvga3dContextDestroyOgl(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t cid);
173static DECLCALLBACK(int) vmsvga3dBackContextDestroy(PVGASTATECC pThisCC, uint32_t cid);
174static void vmsvgaColor2GLFloatArray(uint32_t color, GLfloat *pRed, GLfloat *pGreen, GLfloat *pBlue, GLfloat *pAlpha);
175static DECLCALLBACK(int) vmsvga3dBackSetLightData(PVGASTATECC pThisCC, uint32_t cid, uint32_t index, SVGA3dLightData *pData);
176static DECLCALLBACK(int) vmsvga3dBackSetClipPlane(PVGASTATECC pThisCC, uint32_t cid, uint32_t index, float plane[4]);
177static DECLCALLBACK(int) vmsvga3dBackShaderDestroy(PVGASTATECC pThisCC, uint32_t cid, uint32_t shid, SVGA3dShaderType type);
178static DECLCALLBACK(int) vmsvga3dBackOcclusionQueryDelete(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext);
179static DECLCALLBACK(int) vmsvga3dBackCreateTexture(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t idAssociatedContext, PVMSVGA3DSURFACE pSurface);
180
181/* Generated by VBoxDef2LazyLoad from the VBoxSVGA3D.def and VBoxSVGA3DObjC.def files. */
182extern "C" int ExplicitlyLoadVBoxSVGA3D(bool fResolveAllImports, PRTERRINFO pErrInfo);
183
184
185/**
186 * Checks if the given OpenGL extension is supported.
187 *
188 * @returns true if supported, false if not.
189 * @param pState The VMSVGA3d state.
190 * @param rsMinGLVersion The OpenGL version that introduced this feature
191 * into the core.
192 * @param pszWantedExtension The name of the OpenGL extension we want padded
193 * with one space at each end.
194 * @remarks Init time only.
195 */
196static bool vmsvga3dCheckGLExtension(PVMSVGA3DSTATE pState, float rsMinGLVersion, const char *pszWantedExtension)
197{
198 RT_NOREF(rsMinGLVersion);
199 /* check padding. */
200 Assert(pszWantedExtension[0] == ' ');
201 Assert(pszWantedExtension[1] != ' ');
202 Assert(strchr(&pszWantedExtension[1], ' ') + 1 == strchr(pszWantedExtension, '\0'));
203
204 /* Look it up. */
205 bool fRet = false;
206 if (strstr(pState->pszExtensions, pszWantedExtension))
207 fRet = true;
208
209 /* Temporarily. Later start if (rsMinGLVersion != 0.0 && fActualGLVersion >= rsMinGLVersion) return true; */
210#ifdef RT_OS_DARWIN
211 AssertMsg( rsMinGLVersion == 0.0
212 || fRet == (pState->rsGLVersion >= rsMinGLVersion)
213 || VBOX_VMSVGA3D_DEFAULT_OGL_PROFILE == 2.1,
214 ("%s actual:%d min:%d fRet=%d\n",
215 pszWantedExtension, (int)(pState->rsGLVersion * 10), (int)(rsMinGLVersion * 10), fRet));
216#else
217 AssertMsg(rsMinGLVersion == 0.0 || fRet == (pState->rsGLVersion >= rsMinGLVersion),
218 ("%s actual:%d min:%d fRet=%d\n",
219 pszWantedExtension, (int)(pState->rsGLVersion * 10), (int)(rsMinGLVersion * 10), fRet));
220#endif
221 return fRet;
222}
223
224
225/**
226 * Outputs GL_EXTENSIONS list to the release log.
227 */
228static void vmsvga3dLogRelExtensions(const char *pszPrefix, const char *pszExtensions)
229{
230 /* OpenGL 3.0 interface (glGetString(GL_EXTENSIONS) return NULL). */
231 bool fBuffered = RTLogRelSetBuffering(true);
232
233 /*
234 * Determin the column widths first.
235 */
236 size_t acchWidths[4] = { 1, 1, 1, 1 };
237 uint32_t i;
238 const char *psz = pszExtensions;
239 for (i = 0; ; i++)
240 {
241 while (*psz == ' ')
242 psz++;
243 if (!*psz)
244 break;
245
246 const char *pszEnd = strchr(psz, ' ');
247 AssertBreak(pszEnd);
248 size_t cch = pszEnd - psz;
249
250 uint32_t iColumn = i % RT_ELEMENTS(acchWidths);
251 if (acchWidths[iColumn] < cch)
252 acchWidths[iColumn] = cch;
253
254 psz = pszEnd;
255 }
256
257 /*
258 * Output it.
259 */
260 LogRel(("VMSVGA3d: %sOpenGL extensions (%d):", pszPrefix, i));
261 psz = pszExtensions;
262 for (i = 0; ; i++)
263 {
264 while (*psz == ' ')
265 psz++;
266 if (!*psz)
267 break;
268
269 const char *pszEnd = strchr(psz, ' ');
270 AssertBreak(pszEnd);
271 size_t cch = pszEnd - psz;
272
273 uint32_t iColumn = i % RT_ELEMENTS(acchWidths);
274 if (iColumn == 0)
275 LogRel(("\nVMSVGA3d: %-*.*s", acchWidths[iColumn], cch, psz));
276 else if (iColumn != RT_ELEMENTS(acchWidths) - 1)
277 LogRel((" %-*.*s", acchWidths[iColumn], cch, psz));
278 else
279 LogRel((" %.*s", cch, psz));
280
281 psz = pszEnd;
282 }
283
284 RTLogRelSetBuffering(fBuffered);
285 LogRel(("\n"));
286}
287
288/**
289 * Gathers the GL_EXTENSIONS list, storing it as a space padded list at
290 * @a ppszExtensions.
291 *
292 * @returns VINF_SUCCESS or VERR_NO_STR_MEMORY
293 * @param ppszExtensions Pointer to the string pointer. Free with RTStrFree.
294 * @param fGLProfileVersion The OpenGL profile version.
295 */
296static int vmsvga3dGatherExtensions(char **ppszExtensions, float fGLProfileVersion)
297{
298 int rc;
299 *ppszExtensions = NULL;
300
301 /*
302 * Try the old glGetString interface first.
303 */
304 const char *pszExtensions = (const char *)glGetString(GL_EXTENSIONS);
305 if (pszExtensions)
306 {
307 rc = RTStrAAppendExN(ppszExtensions, 3, " ", (size_t)1, pszExtensions, RTSTR_MAX, " ", (size_t)1);
308 AssertLogRelRCReturn(rc, rc);
309 }
310 else
311 {
312 /*
313 * The new interface where each extension string is retrieved separately.
314 * Note! Cannot use VMSVGA3D_INIT_CHECKED_GL_GET_INTEGER_VALUE here because
315 * the above GL_EXTENSIONS error lingers on darwin. sucks.
316 */
317#ifndef GL_NUM_EXTENSIONS
318# define GL_NUM_EXTENSIONS 0x821D
319#endif
320 GLint cExtensions = 1024;
321 glGetIntegerv(GL_NUM_EXTENSIONS, &cExtensions);
322 Assert(cExtensions != 1024);
323
324 PFNGLGETSTRINGIPROC pfnGlGetStringi = (PFNGLGETSTRINGIPROC)OGLGETPROCADDRESS("glGetStringi");
325 AssertLogRelReturn(pfnGlGetStringi, VERR_NOT_SUPPORTED);
326
327 rc = RTStrAAppend(ppszExtensions, " ");
328 for (GLint i = 0; RT_SUCCESS(rc) && i < cExtensions; i++)
329 {
330 const char *pszExt = (const char *)pfnGlGetStringi(GL_EXTENSIONS, i);
331 if (pszExt)
332 rc = RTStrAAppendExN(ppszExtensions, 2, pfnGlGetStringi(GL_EXTENSIONS, i), RTSTR_MAX, " ", (size_t)1);
333 }
334 AssertRCReturn(rc, rc);
335 }
336
337#if 1
338 /*
339 * Add extensions promoted into the core OpenGL profile.
340 */
341 static const struct
342 {
343 float fGLVersion;
344 const char *pszzExtensions;
345 } s_aPromotedExtensions[] =
346 {
347 {
348 1.1f,
349 " GL_EXT_vertex_array \0"
350 " GL_EXT_polygon_offset \0"
351 " GL_EXT_blend_logic_op \0"
352 " GL_EXT_texture \0"
353 " GL_EXT_copy_texture \0"
354 " GL_EXT_subtexture \0"
355 " GL_EXT_texture_object \0"
356 " GL_ARB_framebuffer_object \0"
357 " GL_ARB_map_buffer_range \0"
358 " GL_ARB_vertex_array_object \0"
359 "\0"
360 },
361 {
362 1.2f,
363 " EXT_texture3D \0"
364 " EXT_bgra \0"
365 " EXT_packed_pixels \0"
366 " EXT_rescale_normal \0"
367 " EXT_separate_specular_color \0"
368 " SGIS_texture_edge_clamp \0"
369 " SGIS_texture_lod \0"
370 " EXT_draw_range_elements \0"
371 "\0"
372 },
373 {
374 1.3f,
375 " GL_ARB_texture_compression \0"
376 " GL_ARB_texture_cube_map \0"
377 " GL_ARB_multisample \0"
378 " GL_ARB_multitexture \0"
379 " GL_ARB_texture_env_add \0"
380 " GL_ARB_texture_env_combine \0"
381 " GL_ARB_texture_env_dot3 \0"
382 " GL_ARB_texture_border_clamp \0"
383 " GL_ARB_transpose_matrix \0"
384 "\0"
385 },
386 {
387 1.5f,
388 " GL_SGIS_generate_mipmap \0"
389 /*" GL_NV_blend_equare \0"*/
390 " GL_ARB_depth_texture \0"
391 " GL_ARB_shadow \0"
392 " GL_EXT_fog_coord \0"
393 " GL_EXT_multi_draw_arrays \0"
394 " GL_ARB_point_parameters \0"
395 " GL_EXT_secondary_color \0"
396 " GL_EXT_blend_func_separate \0"
397 " GL_EXT_stencil_wrap \0"
398 " GL_ARB_texture_env_crossbar \0"
399 " GL_EXT_texture_lod_bias \0"
400 " GL_ARB_texture_mirrored_repeat \0"
401 " GL_ARB_window_pos \0"
402 "\0"
403 },
404 {
405 1.6f,
406 " GL_ARB_vertex_buffer_object \0"
407 " GL_ARB_occlusion_query \0"
408 " GL_EXT_shadow_funcs \0"
409 },
410 {
411 2.0f,
412 " GL_ARB_shader_objects \0" /*??*/
413 " GL_ARB_vertex_shader \0" /*??*/
414 " GL_ARB_fragment_shader \0" /*??*/
415 " GL_ARB_shading_language_100 \0" /*??*/
416 " GL_ARB_draw_buffers \0"
417 " GL_ARB_texture_non_power_of_two \0"
418 " GL_ARB_point_sprite \0"
419 " GL_ATI_separate_stencil \0"
420 " GL_EXT_stencil_two_side \0"
421 "\0"
422 },
423 {
424 2.1f,
425 " GL_ARB_pixel_buffer_object \0"
426 " GL_EXT_texture_sRGB \0"
427 "\0"
428 },
429 {
430 3.0f,
431 " GL_ARB_framebuffer_object \0"
432 " GL_ARB_map_buffer_range \0"
433 " GL_ARB_vertex_array_object \0"
434 "\0"
435 },
436 {
437 3.1f,
438 " GL_ARB_copy_buffer \0"
439 " GL_ARB_uniform_buffer_object \0"
440 "\0"
441 },
442 {
443 3.2f,
444 " GL_ARB_vertex_array_bgra \0"
445 " GL_ARB_draw_elements_base_vertex \0"
446 " GL_ARB_fragment_coord_conventions \0"
447 " GL_ARB_provoking_vertex \0"
448 " GL_ARB_seamless_cube_map \0"
449 " GL_ARB_texture_multisample \0"
450 " GL_ARB_depth_clamp \0"
451 " GL_ARB_sync \0"
452 " GL_ARB_geometry_shader4 \0" /*??*/
453 "\0"
454 },
455 {
456 3.3f,
457 " GL_ARB_blend_func_extended \0"
458 " GL_ARB_sampler_objects \0"
459 " GL_ARB_explicit_attrib_location \0"
460 " GL_ARB_occlusion_query2 \0"
461 " GL_ARB_shader_bit_encoding \0"
462 " GL_ARB_texture_rgb10_a2ui \0"
463 " GL_ARB_texture_swizzle \0"
464 " GL_ARB_timer_query \0"
465 " GL_ARB_vertex_type_2_10_10_10_rev \0"
466 "\0"
467 },
468 {
469 4.0f,
470 " GL_ARB_texture_query_lod \0"
471 " GL_ARB_draw_indirect \0"
472 " GL_ARB_gpu_shader5 \0"
473 " GL_ARB_gpu_shader_fp64 \0"
474 " GL_ARB_shader_subroutine \0"
475 " GL_ARB_tessellation_shader \0"
476 " GL_ARB_texture_buffer_object_rgb32 \0"
477 " GL_ARB_texture_cube_map_array \0"
478 " GL_ARB_texture_gather \0"
479 " GL_ARB_transform_feedback2 \0"
480 " GL_ARB_transform_feedback3 \0"
481 "\0"
482 },
483 {
484 4.1f,
485 " GL_ARB_ES2_compatibility \0"
486 " GL_ARB_get_program_binary \0"
487 " GL_ARB_separate_shader_objects \0"
488 " GL_ARB_shader_precision \0"
489 " GL_ARB_vertex_attrib_64bit \0"
490 " GL_ARB_viewport_array \0"
491 "\0"
492 }
493 };
494
495 uint32_t cPromoted = 0;
496 for (uint32_t i = 0; i < RT_ELEMENTS(s_aPromotedExtensions) && s_aPromotedExtensions[i].fGLVersion <= fGLProfileVersion; i++)
497 {
498 const char *pszExt = s_aPromotedExtensions[i].pszzExtensions;
499 while (*pszExt)
500 {
501# ifdef VBOX_STRICT
502 size_t cchExt = strlen(pszExt);
503 Assert(cchExt > 3);
504 Assert(pszExt[0] == ' ');
505 Assert(pszExt[1] != ' ');
506 Assert(pszExt[cchExt - 2] != ' ');
507 Assert(pszExt[cchExt - 1] == ' ');
508# endif
509
510 if (strstr(*ppszExtensions, pszExt) == NULL)
511 {
512 if (cPromoted++ == 0)
513 {
514 rc = RTStrAAppend(ppszExtensions, " <promoted-extensions:> <promoted-extensions:> <promoted-extensions:> ");
515 AssertRCReturn(rc, rc);
516 }
517
518 rc = RTStrAAppend(ppszExtensions, pszExt);
519 AssertRCReturn(rc, rc);
520 }
521
522 pszExt = strchr(pszExt, '\0') + 1;
523 }
524 }
525#endif
526
527 return VINF_SUCCESS;
528}
529
530/** Check whether this is an Intel GL driver.
531 *
532 * @returns true if this seems to be some Intel graphics.
533 */
534static bool vmsvga3dIsVendorIntel(void)
535{
536 return RTStrNICmp((char *)glGetString(GL_VENDOR), "Intel", 5) == 0;
537}
538
539/**
540 * @interface_method_impl{VBOXVMSVGASHADERIF,pfnSwitchInitProfile}
541 */
542static DECLCALLBACK(void) vmsvga3dShaderIfSwitchInitProfile(PVBOXVMSVGASHADERIF pThis, bool fOtherProfile)
543{
544#ifdef VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE
545 PVMSVGA3DSTATE pState = RT_FROM_MEMBER(pThis, VMSVGA3DSTATE, ShaderIf);
546 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pState->papContexts[fOtherProfile ? 2 : 1]);
547#else
548 NOREF(pThis);
549 NOREF(fOtherProfile);
550#endif
551}
552
553
554/**
555 * @interface_method_impl{VBOXVMSVGASHADERIF,pfnGetNextExtension}
556 */
557static DECLCALLBACK(bool) vmsvga3dShaderIfGetNextExtension(PVBOXVMSVGASHADERIF pThis, void **ppvEnumCtx,
558 char *pszBuf, size_t cbBuf, bool fOtherProfile)
559{
560 PVMSVGA3DSTATE pState = RT_FROM_MEMBER(pThis, VMSVGA3DSTATE, ShaderIf);
561 const char *pszCur = *ppvEnumCtx ? (const char *)*ppvEnumCtx
562 : fOtherProfile ? pState->pszOtherExtensions : pState->pszExtensions;
563 while (*pszCur == ' ')
564 pszCur++;
565 if (!*pszCur)
566 return false;
567
568 const char *pszEnd = strchr(pszCur, ' ');
569 AssertReturn(pszEnd, false);
570 size_t cch = pszEnd - pszCur;
571 if (cch < cbBuf)
572 {
573 memcpy(pszBuf, pszCur, cch);
574 pszBuf[cch] = '\0';
575 }
576 else if (cbBuf > 0)
577 {
578 memcpy(pszBuf, "<overflow>", RT_MIN(sizeof("<overflow>"), cbBuf));
579 pszBuf[cbBuf - 1] = '\0';
580 }
581
582 *ppvEnumCtx = (void *)pszEnd;
583 return true;
584}
585
586
587/**
588 * Initializes the VMSVGA3D state during VGA device construction.
589 *
590 * Failure are generally not fatal, 3D support will just be disabled.
591 *
592 * @returns VBox status code.
593 * @param pDevIns The device instance.
594 * @param pThis The shared VGA/VMSVGA state where svga.p3dState will be
595 * modified.
596 * @param pThisCC The VGA/VMSVGA state for ring-3.
597 */
598static DECLCALLBACK(int) vmsvga3dBackInit(PPDMDEVINS pDevIns, PVGASTATE pThis, PVGASTATECC pThisCC)
599{
600 int rc;
601 RT_NOREF(pDevIns, pThis);
602
603 AssertCompile(GL_TRUE == 1);
604 AssertCompile(GL_FALSE == 0);
605
606#ifdef VMSVGA3D_DYNAMIC_LOAD
607 rc = glLdrInit(pDevIns);
608 if (RT_FAILURE(rc))
609 {
610 LogRel(("VMSVGA3d: Error loading OpenGL library and resolving necessary functions: %Rrc\n", rc));
611 return rc;
612 }
613#endif
614
615 /*
616 * Load and resolve imports from the external shared libraries.
617 */
618 RTERRINFOSTATIC ErrInfo;
619 rc = ExplicitlyLoadVBoxSVGA3D(true /*fResolveAllImports*/, RTErrInfoInitStatic(&ErrInfo));
620 if (RT_FAILURE(rc))
621 {
622 LogRel(("VMSVGA3d: Error loading VBoxSVGA3D and resolving necessary functions: %Rrc - %s\n", rc, ErrInfo.Core.pszMsg));
623 return rc;
624 }
625#ifdef RT_OS_DARWIN
626 rc = ExplicitlyLoadVBoxSVGA3DObjC(true /*fResolveAllImports*/, RTErrInfoInitStatic(&ErrInfo));
627 if (RT_FAILURE(rc))
628 {
629 LogRel(("VMSVGA3d: Error loading VBoxSVGA3DObjC and resolving necessary functions: %Rrc - %s\n", rc, ErrInfo.Core.pszMsg));
630 return rc;
631 }
632#endif
633
634 /*
635 * Allocate the state.
636 */
637 pThisCC->svga.p3dState = (PVMSVGA3DSTATE)RTMemAllocZ(sizeof(VMSVGA3DSTATE));
638 AssertReturn(pThisCC->svga.p3dState, VERR_NO_MEMORY);
639
640#ifdef RT_OS_WINDOWS
641 /* Create event semaphore and async IO thread. */
642 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
643 rc = RTSemEventCreate(&pState->WndRequestSem);
644 if (RT_SUCCESS(rc))
645 {
646 rc = RTThreadCreate(&pState->pWindowThread, vmsvga3dWindowThread, pState->WndRequestSem, 0, RTTHREADTYPE_GUI, 0,
647 "VMSVGA3DWND");
648 if (RT_SUCCESS(rc))
649 return VINF_SUCCESS;
650
651 /* bail out. */
652 LogRel(("VMSVGA3d: RTThreadCreate failed: %Rrc\n", rc));
653 RTSemEventDestroy(pState->WndRequestSem);
654 }
655 else
656 LogRel(("VMSVGA3d: RTSemEventCreate failed: %Rrc\n", rc));
657 RTMemFree(pThisCC->svga.p3dState);
658 pThisCC->svga.p3dState = NULL;
659 return rc;
660#else
661 return VINF_SUCCESS;
662#endif
663}
664
665static int vmsvga3dLoadGLFunctions(PVMSVGA3DSTATE pState)
666{
667 /* A strict approach to get a proc address as recommended by Khronos:
668 * - "If the function is a core OpenGL function, then we need to check the OpenGL version".
669 * - "If the function is an extension, we need to check to see if the extension is supported."
670 */
671
672/* Get a function address, return VERR_NOT_IMPLEMENTED on failure. */
673#define GLGETPROC_(ProcType, ProcName, NameSuffix) do { \
674 pState->ext.ProcName = (ProcType)OGLGETPROCADDRESS(#ProcName NameSuffix); \
675 AssertLogRelMsgReturn(pState->ext.ProcName, (#ProcName NameSuffix " missing"), VERR_NOT_IMPLEMENTED); \
676} while(0)
677
678/* Get an optional function address. LogRel on failure. */
679#define GLGETPROCOPT_(ProcType, ProcName, NameSuffix) do { \
680 pState->ext.ProcName = (ProcType)OGLGETPROCADDRESS(#ProcName NameSuffix); \
681 if (!pState->ext.ProcName) \
682 { \
683 LogRel(("VMSVGA3d: missing optional %s\n", #ProcName NameSuffix)); \
684 AssertFailed(); \
685 } \
686} while(0)
687
688 /* OpenGL 2.0 or earlier core. Do not bother with extensions. */
689 GLGETPROC_(PFNGLGENQUERIESPROC , glGenQueries, "");
690 GLGETPROC_(PFNGLDELETEQUERIESPROC , glDeleteQueries, "");
691 GLGETPROC_(PFNGLBEGINQUERYPROC , glBeginQuery, "");
692 GLGETPROC_(PFNGLENDQUERYPROC , glEndQuery, "");
693 GLGETPROC_(PFNGLGETQUERYOBJECTUIVPROC , glGetQueryObjectuiv, "");
694 GLGETPROC_(PFNGLTEXIMAGE3DPROC , glTexImage3D, "");
695 GLGETPROC_(PFNGLTEXSUBIMAGE3DPROC , glTexSubImage3D, "");
696 GLGETPROC_(PFNGLGETCOMPRESSEDTEXIMAGEPROC , glGetCompressedTexImage, "");
697 GLGETPROC_(PFNGLCOMPRESSEDTEXIMAGE2DPROC , glCompressedTexImage2D, "");
698 GLGETPROC_(PFNGLCOMPRESSEDTEXIMAGE3DPROC , glCompressedTexImage3D, "");
699 GLGETPROC_(PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC , glCompressedTexSubImage2D, "");
700 GLGETPROC_(PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC , glCompressedTexSubImage3D, "");
701 GLGETPROC_(PFNGLPOINTPARAMETERFPROC , glPointParameterf, "");
702 GLGETPROC_(PFNGLBLENDEQUATIONSEPARATEPROC , glBlendEquationSeparate, "");
703 GLGETPROC_(PFNGLBLENDFUNCSEPARATEPROC , glBlendFuncSeparate, "");
704 GLGETPROC_(PFNGLSTENCILOPSEPARATEPROC , glStencilOpSeparate, "");
705 GLGETPROC_(PFNGLSTENCILFUNCSEPARATEPROC , glStencilFuncSeparate, "");
706 GLGETPROC_(PFNGLBINDBUFFERPROC , glBindBuffer, "");
707 GLGETPROC_(PFNGLDELETEBUFFERSPROC , glDeleteBuffers, "");
708 GLGETPROC_(PFNGLGENBUFFERSPROC , glGenBuffers, "");
709 GLGETPROC_(PFNGLBUFFERDATAPROC , glBufferData, "");
710 GLGETPROC_(PFNGLMAPBUFFERPROC , glMapBuffer, "");
711 GLGETPROC_(PFNGLUNMAPBUFFERPROC , glUnmapBuffer, "");
712 GLGETPROC_(PFNGLENABLEVERTEXATTRIBARRAYPROC , glEnableVertexAttribArray, "");
713 GLGETPROC_(PFNGLDISABLEVERTEXATTRIBARRAYPROC , glDisableVertexAttribArray, "");
714 GLGETPROC_(PFNGLVERTEXATTRIBPOINTERPROC , glVertexAttribPointer, "");
715 GLGETPROC_(PFNGLACTIVETEXTUREPROC , glActiveTexture, "");
716 /* glGetProgramivARB determines implementation limits for the program
717 * target (GL_FRAGMENT_PROGRAM_ARB, GL_VERTEX_PROGRAM_ARB).
718 * It differs from glGetProgramiv, which returns a parameter from a program object.
719 */
720 GLGETPROC_(PFNGLGETPROGRAMIVARBPROC , glGetProgramivARB, "");
721 GLGETPROC_(PFNGLFOGCOORDPOINTERPROC , glFogCoordPointer, "");
722#if VBOX_VMSVGA3D_GL_HACK_LEVEL < 0x102
723 GLGETPROC_(PFNGLBLENDCOLORPROC , glBlendColor, "");
724 GLGETPROC_(PFNGLBLENDEQUATIONPROC , glBlendEquation, "");
725#endif
726#if VBOX_VMSVGA3D_GL_HACK_LEVEL < 0x103
727 GLGETPROC_(PFNGLCLIENTACTIVETEXTUREPROC , glClientActiveTexture, "");
728#endif
729 GLGETPROC_(PFNGLDRAWBUFFERSPROC , glDrawBuffers, "");
730 GLGETPROC_(PFNGLCREATESHADERPROC , glCreateShader, "");
731 GLGETPROC_(PFNGLSHADERSOURCEPROC , glShaderSource, "");
732 GLGETPROC_(PFNGLCOMPILESHADERPROC , glCompileShader, "");
733 GLGETPROC_(PFNGLGETSHADERIVPROC , glGetShaderiv, "");
734 GLGETPROC_(PFNGLGETSHADERINFOLOGPROC , glGetShaderInfoLog, "");
735 GLGETPROC_(PFNGLCREATEPROGRAMPROC , glCreateProgram, "");
736 GLGETPROC_(PFNGLATTACHSHADERPROC , glAttachShader, "");
737 GLGETPROC_(PFNGLLINKPROGRAMPROC , glLinkProgram, "");
738 GLGETPROC_(PFNGLGETPROGRAMIVPROC , glGetProgramiv, "");
739 GLGETPROC_(PFNGLGETPROGRAMINFOLOGPROC , glGetProgramInfoLog, "");
740 GLGETPROC_(PFNGLUSEPROGRAMPROC , glUseProgram, "");
741 GLGETPROC_(PFNGLGETUNIFORMLOCATIONPROC , glGetUniformLocation, "");
742 GLGETPROC_(PFNGLUNIFORM1IPROC , glUniform1i, "");
743 GLGETPROC_(PFNGLUNIFORM4FVPROC , glUniform4fv, "");
744 GLGETPROC_(PFNGLDETACHSHADERPROC , glDetachShader, "");
745 GLGETPROC_(PFNGLDELETESHADERPROC , glDeleteShader, "");
746 GLGETPROC_(PFNGLDELETEPROGRAMPROC , glDeleteProgram, "");
747
748 GLGETPROC_(PFNGLVERTEXATTRIB4FVPROC , glVertexAttrib4fv, "");
749 GLGETPROC_(PFNGLVERTEXATTRIB4UBVPROC , glVertexAttrib4ubv, "");
750 GLGETPROC_(PFNGLVERTEXATTRIB4NUBVPROC , glVertexAttrib4Nubv, "");
751 GLGETPROC_(PFNGLVERTEXATTRIB4SVPROC , glVertexAttrib4sv, "");
752 GLGETPROC_(PFNGLVERTEXATTRIB4NSVPROC , glVertexAttrib4Nsv, "");
753 GLGETPROC_(PFNGLVERTEXATTRIB4NUSVPROC , glVertexAttrib4Nusv, "");
754
755 /* OpenGL 3.0 core, GL_ARB_instanced_arrays. Same functions names in the ARB and core specs. */
756 if ( pState->rsGLVersion >= 3.0f
757 || vmsvga3dCheckGLExtension(pState, 0.0f, " GL_ARB_framebuffer_object "))
758 {
759 GLGETPROC_(PFNGLISRENDERBUFFERPROC , glIsRenderbuffer, "");
760 GLGETPROC_(PFNGLBINDRENDERBUFFERPROC , glBindRenderbuffer, "");
761 GLGETPROC_(PFNGLDELETERENDERBUFFERSPROC , glDeleteRenderbuffers, "");
762 GLGETPROC_(PFNGLGENRENDERBUFFERSPROC , glGenRenderbuffers, "");
763 GLGETPROC_(PFNGLRENDERBUFFERSTORAGEPROC , glRenderbufferStorage, "");
764 GLGETPROC_(PFNGLGETRENDERBUFFERPARAMETERIVPROC , glGetRenderbufferParameteriv, "");
765 GLGETPROC_(PFNGLISFRAMEBUFFERPROC , glIsFramebuffer, "");
766 GLGETPROC_(PFNGLBINDFRAMEBUFFERPROC , glBindFramebuffer, "");
767 GLGETPROC_(PFNGLDELETEFRAMEBUFFERSPROC , glDeleteFramebuffers, "");
768 GLGETPROC_(PFNGLGENFRAMEBUFFERSPROC , glGenFramebuffers, "");
769 GLGETPROC_(PFNGLCHECKFRAMEBUFFERSTATUSPROC , glCheckFramebufferStatus, "");
770 GLGETPROC_(PFNGLFRAMEBUFFERTEXTURE1DPROC , glFramebufferTexture1D, "");
771 GLGETPROC_(PFNGLFRAMEBUFFERTEXTURE2DPROC , glFramebufferTexture2D, "");
772 GLGETPROC_(PFNGLFRAMEBUFFERTEXTURE3DPROC , glFramebufferTexture3D, "");
773 GLGETPROC_(PFNGLFRAMEBUFFERRENDERBUFFERPROC , glFramebufferRenderbuffer, "");
774 GLGETPROC_(PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC , glGetFramebufferAttachmentParameteriv, "");
775 GLGETPROC_(PFNGLGENERATEMIPMAPPROC , glGenerateMipmap, "");
776 GLGETPROC_(PFNGLBLITFRAMEBUFFERPROC , glBlitFramebuffer, "");
777 GLGETPROC_(PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC , glRenderbufferStorageMultisample, "");
778 GLGETPROC_(PFNGLFRAMEBUFFERTEXTURELAYERPROC , glFramebufferTextureLayer, "");
779 }
780
781 /* OpenGL 3.1 core, GL_ARB_draw_instanced, GL_EXT_draw_instanced. */
782 if (pState->rsGLVersion >= 3.1f)
783 {
784 GLGETPROC_(PFNGLDRAWARRAYSINSTANCEDPROC , glDrawArraysInstanced, "");
785 GLGETPROC_(PFNGLDRAWELEMENTSINSTANCEDPROC , glDrawElementsInstanced, "");
786 }
787 else if (vmsvga3dCheckGLExtension(pState, 0.0f, " GL_ARB_draw_instanced "))
788 {
789 GLGETPROC_(PFNGLDRAWARRAYSINSTANCEDPROC , glDrawArraysInstanced, "ARB");
790 GLGETPROC_(PFNGLDRAWELEMENTSINSTANCEDPROC , glDrawElementsInstanced, "ARB");
791 }
792 else if (vmsvga3dCheckGLExtension(pState, 0.0f, " GL_EXT_draw_instanced "))
793 {
794 GLGETPROC_(PFNGLDRAWARRAYSINSTANCEDPROC , glDrawArraysInstanced, "EXT");
795 GLGETPROC_(PFNGLDRAWELEMENTSINSTANCEDPROC , glDrawElementsInstanced, "EXT");
796 }
797
798 /* OpenGL 3.2 core, GL_ARB_draw_elements_base_vertex. Same functions names in the ARB and core specs. */
799 if ( pState->rsGLVersion >= 3.2f
800 || vmsvga3dCheckGLExtension(pState, 0.0f, " GL_ARB_draw_elements_base_vertex "))
801 {
802 GLGETPROC_(PFNGLDRAWELEMENTSBASEVERTEXPROC , glDrawElementsBaseVertex, "");
803 GLGETPROC_(PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC , glDrawElementsInstancedBaseVertex, "");
804 }
805
806 /* Optional. OpenGL 3.2 core, GL_ARB_provoking_vertex. Same functions names in the ARB and core specs. */
807 if ( pState->rsGLVersion >= 3.2f
808 || vmsvga3dCheckGLExtension(pState, 0.0f, " GL_ARB_provoking_vertex "))
809 {
810 GLGETPROCOPT_(PFNGLPROVOKINGVERTEXPROC , glProvokingVertex, "");
811 }
812
813 /* OpenGL 3.3 core, GL_ARB_instanced_arrays. */
814 if (pState->rsGLVersion >= 3.3f)
815 {
816 GLGETPROC_(PFNGLVERTEXATTRIBDIVISORPROC , glVertexAttribDivisor, "");
817 }
818 else if (vmsvga3dCheckGLExtension(pState, 0.0f, " GL_ARB_instanced_arrays "))
819 {
820 GLGETPROC_(PFNGLVERTEXATTRIBDIVISORARBPROC , glVertexAttribDivisor, "ARB");
821 }
822
823#undef GLGETPROCOPT_
824#undef GLGETPROC_
825
826 return VINF_SUCCESS;
827}
828
829
830DECLINLINE(GLenum) vmsvga3dCubemapFaceFromIndex(uint32_t iFace)
831{
832 GLint Face;
833 switch (iFace)
834 {
835 case 0: Face = GL_TEXTURE_CUBE_MAP_POSITIVE_X; break;
836 case 1: Face = GL_TEXTURE_CUBE_MAP_NEGATIVE_X; break;
837 case 2: Face = GL_TEXTURE_CUBE_MAP_POSITIVE_Y; break;
838 case 3: Face = GL_TEXTURE_CUBE_MAP_NEGATIVE_Y; break;
839 case 4: Face = GL_TEXTURE_CUBE_MAP_POSITIVE_Z; break;
840 default:
841 case 5: Face = GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; break;
842 }
843 return Face;
844}
845
846
847/* We must delay window creation until the PowerOn phase. Init is too early and will cause failures. */
848static DECLCALLBACK(int) vmsvga3dBackPowerOn(PPDMDEVINS pDevIns, PVGASTATE pThis, PVGASTATECC pThisCC)
849{
850 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
851 AssertReturn(pThisCC->svga.p3dState, VERR_NO_MEMORY);
852 PVMSVGA3DCONTEXT pContext;
853#ifdef VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE
854 PVMSVGA3DCONTEXT pOtherCtx;
855#endif
856 int rc;
857 RT_NOREF(pDevIns, pThis);
858
859 if (pState->rsGLVersion != 0.0)
860 return VINF_SUCCESS; /* already initialized (load state) */
861
862 /*
863 * OpenGL function calls aren't possible without a valid current context, so create a fake one here.
864 */
865 rc = vmsvga3dContextDefineOgl(pThisCC, 1, VMSVGA3D_DEF_CTX_F_INIT);
866 AssertRCReturn(rc, rc);
867
868 pContext = pState->papContexts[1];
869 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
870
871#ifdef VMSVGA3D_DYNAMIC_LOAD
872 /* Context is set and it is possible now to resolve extension functions. */
873 rc = glLdrGetExtFunctions(pDevIns);
874 if (RT_FAILURE(rc))
875 {
876 LogRel(("VMSVGA3d: Error resolving extension functions: %Rrc\n", rc));
877 return rc;
878 }
879#endif
880
881 LogRel(("VMSVGA3d: OpenGL version: %s\n"
882 "VMSVGA3d: OpenGL Vendor: %s\n"
883 "VMSVGA3d: OpenGL Renderer: %s\n"
884 "VMSVGA3d: OpenGL shader language version: %s\n",
885 glGetString(GL_VERSION), glGetString(GL_VENDOR), glGetString(GL_RENDERER),
886 glGetString(GL_SHADING_LANGUAGE_VERSION)));
887
888 rc = vmsvga3dGatherExtensions(&pState->pszExtensions, VBOX_VMSVGA3D_DEFAULT_OGL_PROFILE);
889 AssertRCReturn(rc, rc);
890 vmsvga3dLogRelExtensions("", pState->pszExtensions);
891
892 pState->rsGLVersion = atof((const char *)glGetString(GL_VERSION));
893
894
895#ifdef VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE
896 /*
897 * Get the extension list for the alternative profile so we can better
898 * figure out the shader model and stuff.
899 */
900 rc = vmsvga3dContextDefineOgl(pThisCC, 2, VMSVGA3D_DEF_CTX_F_INIT | VMSVGA3D_DEF_CTX_F_OTHER_PROFILE);
901 AssertLogRelRCReturn(rc, rc);
902 pContext = pState->papContexts[1]; /* Array may have been reallocated. */
903
904 pOtherCtx = pState->papContexts[2];
905 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pOtherCtx);
906
907 LogRel(("VMSVGA3d: Alternative OpenGL version: %s\n"
908 "VMSVGA3d: Alternative OpenGL Vendor: %s\n"
909 "VMSVGA3d: Alternative OpenGL Renderer: %s\n"
910 "VMSVGA3d: Alternative OpenGL shader language version: %s\n",
911 glGetString(GL_VERSION), glGetString(GL_VENDOR), glGetString(GL_RENDERER),
912 glGetString(GL_SHADING_LANGUAGE_VERSION)));
913
914 rc = vmsvga3dGatherExtensions(&pState->pszOtherExtensions, VBOX_VMSVGA3D_OTHER_OGL_PROFILE);
915 AssertRCReturn(rc, rc);
916 vmsvga3dLogRelExtensions("Alternative ", pState->pszOtherExtensions);
917
918 pState->rsOtherGLVersion = atof((const char *)glGetString(GL_VERSION));
919
920 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
921#else
922 pState->pszOtherExtensions = (char *)"";
923 pState->rsOtherGLVersion = pState->rsGLVersion;
924#endif
925
926 /*
927 * Resolve GL function pointers and store them in pState->ext.
928 */
929 rc = vmsvga3dLoadGLFunctions(pState);
930 if (RT_FAILURE(rc))
931 {
932 LogRel(("VMSVGA3d: missing required OpenGL function or extension; aborting\n"));
933 return rc;
934 }
935
936 /*
937 * Initialize the capabilities with sensible defaults.
938 */
939 pState->caps.maxActiveLights = 1;
940 pState->caps.maxTextures = 1;
941 pState->caps.maxClipDistances = 4;
942 pState->caps.maxColorAttachments = 1;
943 pState->caps.maxRectangleTextureSize = 2048;
944 pState->caps.maxTextureAnisotropy = 1;
945 pState->caps.maxVertexShaderInstructions = 1024;
946 pState->caps.maxFragmentShaderInstructions = 1024;
947 pState->caps.vertexShaderVersion = SVGA3DVSVERSION_NONE;
948 pState->caps.fragmentShaderVersion = SVGA3DPSVERSION_NONE;
949 pState->caps.flPointSize[0] = 1;
950 pState->caps.flPointSize[1] = 1;
951
952 /*
953 * Query capabilities
954 */
955 pState->caps.fS3TCSupported = vmsvga3dCheckGLExtension(pState, 0.0f, " GL_EXT_texture_compression_s3tc ");
956 pState->caps.fTextureFilterAnisotropicSupported = vmsvga3dCheckGLExtension(pState, 0.0f, " GL_EXT_texture_filter_anisotropic ");
957
958 VMSVGA3D_INIT_CHECKED_BOTH(pState, pContext, pOtherCtx, glGetIntegerv(GL_MAX_LIGHTS, &pState->caps.maxActiveLights));
959 VMSVGA3D_INIT_CHECKED_BOTH(pState, pContext, pOtherCtx, glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &pState->caps.maxTextures));
960#ifdef VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE /* The alternative profile has a higher number here (ati/darwin). */
961 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pOtherCtx);
962 VMSVGA3D_INIT_CHECKED_BOTH(pState, pOtherCtx, pContext, glGetIntegerv(GL_MAX_CLIP_DISTANCES, &pState->caps.maxClipDistances));
963 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
964#else
965 VMSVGA3D_INIT_CHECKED(glGetIntegerv(GL_MAX_CLIP_DISTANCES, &pState->caps.maxClipDistances));
966#endif
967 VMSVGA3D_INIT_CHECKED(glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &pState->caps.maxColorAttachments));
968 VMSVGA3D_INIT_CHECKED(glGetIntegerv(GL_MAX_RECTANGLE_TEXTURE_SIZE, &pState->caps.maxRectangleTextureSize));
969 if (pState->caps.fTextureFilterAnisotropicSupported)
970 VMSVGA3D_INIT_CHECKED(glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &pState->caps.maxTextureAnisotropy));
971 VMSVGA3D_INIT_CHECKED_BOTH(pState, pContext, pOtherCtx, glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, pState->caps.flPointSize));
972
973 VMSVGA3D_INIT_CHECKED_BOTH(pState, pContext, pOtherCtx,
974 pState->ext.glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB,
975 &pState->caps.maxFragmentShaderTemps));
976 VMSVGA3D_INIT_CHECKED_BOTH(pState, pContext, pOtherCtx,
977 pState->ext.glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB,
978 &pState->caps.maxFragmentShaderInstructions));
979 VMSVGA3D_INIT_CHECKED_BOTH(pState, pContext, pOtherCtx,
980 pState->ext.glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB,
981 &pState->caps.maxVertexShaderTemps));
982 VMSVGA3D_INIT_CHECKED_BOTH(pState, pContext, pOtherCtx,
983 pState->ext.glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB,
984 &pState->caps.maxVertexShaderInstructions));
985
986 /* http://http://www.opengl.org/wiki/Detecting_the_Shader_Model
987 * ARB Assembly Language
988 * These are done through testing the presence of extensions. You should test them in this order:
989 * GL_NV_gpu_program4: SM 4.0 or better.
990 * GL_NV_vertex_program3: SM 3.0 or better.
991 * GL_ARB_fragment_program: SM 2.0 or better.
992 * ATI does not support higher than SM 2.0 functionality in assembly shaders.
993 *
994 */
995 /** @todo distinguish between vertex and pixel shaders??? */
996#ifdef VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE /* The alternative profile has a higher number here (ati/darwin). */
997 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pOtherCtx);
998 const char *pszShadingLanguageVersion = (const char *)glGetString(GL_SHADING_LANGUAGE_VERSION);
999 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
1000#else
1001 const char *pszShadingLanguageVersion = (const char *)glGetString(GL_SHADING_LANGUAGE_VERSION);
1002#endif
1003 float v = pszShadingLanguageVersion ? atof(pszShadingLanguageVersion) : 0.0f;
1004 if ( vmsvga3dCheckGLExtension(pState, 0.0f, " GL_NV_gpu_program4 ")
1005 || strstr(pState->pszOtherExtensions, " GL_NV_gpu_program4 "))
1006 {
1007 pState->caps.vertexShaderVersion = SVGA3DVSVERSION_40;
1008 pState->caps.fragmentShaderVersion = SVGA3DPSVERSION_40;
1009 }
1010 else
1011 if ( vmsvga3dCheckGLExtension(pState, 0.0f, " GL_NV_vertex_program3 ")
1012 || strstr(pState->pszOtherExtensions, " GL_NV_vertex_program3 ")
1013 || vmsvga3dCheckGLExtension(pState, 0.0f, " GL_ARB_shader_texture_lod ") /* Wine claims this suggests SM 3.0 support */
1014 || strstr(pState->pszOtherExtensions, " GL_ARB_shader_texture_lod ")
1015 )
1016 {
1017 pState->caps.vertexShaderVersion = SVGA3DVSVERSION_30;
1018 pState->caps.fragmentShaderVersion = SVGA3DPSVERSION_30;
1019 }
1020 else
1021 if ( vmsvga3dCheckGLExtension(pState, 0.0f, " GL_ARB_fragment_program ")
1022 || strstr(pState->pszOtherExtensions, " GL_ARB_fragment_program "))
1023 {
1024 pState->caps.vertexShaderVersion = SVGA3DVSVERSION_20;
1025 pState->caps.fragmentShaderVersion = SVGA3DPSVERSION_20;
1026 }
1027 else
1028 {
1029 LogRel(("VMSVGA3D: WARNING: unknown support for assembly shaders!!\n"));
1030 pState->caps.vertexShaderVersion = SVGA3DVSVERSION_11;
1031 pState->caps.fragmentShaderVersion = SVGA3DPSVERSION_11;
1032 }
1033
1034 /* Now check the shading language version, in case it indicates a higher supported version. */
1035 if (v >= 3.30f)
1036 {
1037 pState->caps.vertexShaderVersion = RT_MAX(pState->caps.vertexShaderVersion, SVGA3DVSVERSION_40);
1038 pState->caps.fragmentShaderVersion = RT_MAX(pState->caps.fragmentShaderVersion, SVGA3DPSVERSION_40);
1039 }
1040 else
1041 if (v >= 1.20f)
1042 {
1043 pState->caps.vertexShaderVersion = RT_MAX(pState->caps.vertexShaderVersion, SVGA3DVSVERSION_20);
1044 pState->caps.fragmentShaderVersion = RT_MAX(pState->caps.fragmentShaderVersion, SVGA3DPSVERSION_20);
1045 }
1046
1047 if ( !vmsvga3dCheckGLExtension(pState, 0.0f, " GL_ARB_vertex_array_bgra ")
1048 && !vmsvga3dCheckGLExtension(pState, 0.0f, " GL_EXT_vertex_array_bgra "))
1049 {
1050 LogRel(("VMSVGA3D: WARNING: Missing required extension GL_ARB_vertex_array_bgra (d3dcolor)!!!\n"));
1051 }
1052
1053 /*
1054 * Tweak capabilities.
1055 */
1056 /* Intel Windows drivers return 31, while the guest expects 32 at least. */
1057 if ( pState->caps.maxVertexShaderTemps < 32
1058 && vmsvga3dIsVendorIntel())
1059 pState->caps.maxVertexShaderTemps = 32;
1060
1061#if 0
1062 SVGA3D_DEVCAP_MAX_FIXED_VERTEXBLEND = 11,
1063 SVGA3D_DEVCAP_QUERY_TYPES = 15,
1064 SVGA3D_DEVCAP_TEXTURE_GRADIENT_SAMPLING = 16,
1065 SVGA3D_DEVCAP_MAX_POINT_SIZE = 17,
1066 SVGA3D_DEVCAP_MAX_SHADER_TEXTURES = 18,
1067 SVGA3D_DEVCAP_MAX_VOLUME_EXTENT = 21,
1068 SVGA3D_DEVCAP_MAX_TEXTURE_REPEAT = 22,
1069 SVGA3D_DEVCAP_MAX_TEXTURE_ASPECT_RATIO = 23,
1070 SVGA3D_DEVCAP_MAX_TEXTURE_ANISOTROPY = 24,
1071 SVGA3D_DEVCAP_MAX_PRIMITIVE_COUNT = 25,
1072 SVGA3D_DEVCAP_MAX_VERTEX_INDEX = 26,
1073 SVGA3D_DEVCAP_MAX_FRAGMENT_SHADER_INSTRUCTIONS = 28,
1074 SVGA3D_DEVCAP_MAX_VERTEX_SHADER_TEMPS = 29,
1075 SVGA3D_DEVCAP_MAX_FRAGMENT_SHADER_TEMPS = 30,
1076 SVGA3D_DEVCAP_TEXTURE_OPS = 31,
1077 SVGA3D_DEVCAP_SURFACEFMT_X8R8G8B8 = 32,
1078 SVGA3D_DEVCAP_SURFACEFMT_A8R8G8B8 = 33,
1079 SVGA3D_DEVCAP_SURFACEFMT_A2R10G10B10 = 34,
1080 SVGA3D_DEVCAP_SURFACEFMT_X1R5G5B5 = 35,
1081 SVGA3D_DEVCAP_SURFACEFMT_A1R5G5B5 = 36,
1082 SVGA3D_DEVCAP_SURFACEFMT_A4R4G4B4 = 37,
1083 SVGA3D_DEVCAP_SURFACEFMT_R5G6B5 = 38,
1084 SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE16 = 39,
1085 SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE8_ALPHA8 = 40,
1086 SVGA3D_DEVCAP_SURFACEFMT_ALPHA8 = 41,
1087 SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE8 = 42,
1088 SVGA3D_DEVCAP_SURFACEFMT_Z_D16 = 43,
1089 SVGA3D_DEVCAP_SURFACEFMT_Z_D24S8 = 44,
1090 SVGA3D_DEVCAP_SURFACEFMT_Z_D24X8 = 45,
1091 SVGA3D_DEVCAP_SURFACEFMT_DXT1 = 46,
1092 SVGA3D_DEVCAP_SURFACEFMT_DXT2 = 47,
1093 SVGA3D_DEVCAP_SURFACEFMT_DXT3 = 48,
1094 SVGA3D_DEVCAP_SURFACEFMT_DXT4 = 49,
1095 SVGA3D_DEVCAP_SURFACEFMT_DXT5 = 50,
1096 SVGA3D_DEVCAP_SURFACEFMT_BUMPX8L8V8U8 = 51,
1097 SVGA3D_DEVCAP_SURFACEFMT_A2W10V10U10 = 52,
1098 SVGA3D_DEVCAP_SURFACEFMT_BUMPU8V8 = 53,
1099 SVGA3D_DEVCAP_SURFACEFMT_Q8W8V8U8 = 54,
1100 SVGA3D_DEVCAP_SURFACEFMT_CxV8U8 = 55,
1101 SVGA3D_DEVCAP_SURFACEFMT_R_S10E5 = 56,
1102 SVGA3D_DEVCAP_SURFACEFMT_R_S23E8 = 57,
1103 SVGA3D_DEVCAP_SURFACEFMT_RG_S10E5 = 58,
1104 SVGA3D_DEVCAP_SURFACEFMT_RG_S23E8 = 59,
1105 SVGA3D_DEVCAP_SURFACEFMT_ARGB_S10E5 = 60,
1106 SVGA3D_DEVCAP_SURFACEFMT_ARGB_S23E8 = 61,
1107 SVGA3D_DEVCAP_MAX_VERTEX_SHADER_TEXTURES = 63,
1108 SVGA3D_DEVCAP_SURFACEFMT_V16U16 = 65,
1109 SVGA3D_DEVCAP_SURFACEFMT_G16R16 = 66,
1110 SVGA3D_DEVCAP_SURFACEFMT_A16B16G16R16 = 67,
1111 SVGA3D_DEVCAP_SURFACEFMT_UYVY = 68,
1112 SVGA3D_DEVCAP_SURFACEFMT_YUY2 = 69,
1113 SVGA3D_DEVCAP_MULTISAMPLE_NONMASKABLESAMPLES = 70,
1114 SVGA3D_DEVCAP_MULTISAMPLE_MASKABLESAMPLES = 71,
1115 SVGA3D_DEVCAP_ALPHATOCOVERAGE = 72,
1116 SVGA3D_DEVCAP_SUPERSAMPLE = 73,
1117 SVGA3D_DEVCAP_AUTOGENMIPMAPS = 74,
1118 SVGA3D_DEVCAP_SURFACEFMT_NV12 = 75,
1119 SVGA3D_DEVCAP_SURFACEFMT_AYUV = 76,
1120 SVGA3D_DEVCAP_SURFACEFMT_Z_DF16 = 79,
1121 SVGA3D_DEVCAP_SURFACEFMT_Z_DF24 = 80,
1122 SVGA3D_DEVCAP_SURFACEFMT_Z_D24S8_INT = 81,
1123 SVGA3D_DEVCAP_SURFACEFMT_ATI1 = 82,
1124 SVGA3D_DEVCAP_SURFACEFMT_ATI2 = 83,
1125#endif
1126
1127 LogRel(("VMSVGA3d: Capabilities:\n"));
1128 LogRel(("VMSVGA3d: maxActiveLights=%-2d maxTextures=%-2d\n",
1129 pState->caps.maxActiveLights, pState->caps.maxTextures));
1130 LogRel(("VMSVGA3d: maxClipDistances=%-2d maxColorAttachments=%-2d maxClipDistances=%d\n",
1131 pState->caps.maxClipDistances, pState->caps.maxColorAttachments, pState->caps.maxClipDistances));
1132 LogRel(("VMSVGA3d: maxColorAttachments=%-2d maxTextureAnisotropy=%-2d maxRectangleTextureSize=%d\n",
1133 pState->caps.maxColorAttachments, pState->caps.maxTextureAnisotropy, pState->caps.maxRectangleTextureSize));
1134 LogRel(("VMSVGA3d: maxVertexShaderTemps=%-2d maxVertexShaderInstructions=%d maxFragmentShaderInstructions=%d\n",
1135 pState->caps.maxVertexShaderTemps, pState->caps.maxVertexShaderInstructions, pState->caps.maxFragmentShaderInstructions));
1136 LogRel(("VMSVGA3d: maxFragmentShaderTemps=%d flPointSize={%d.%02u, %d.%02u}\n",
1137 pState->caps.maxFragmentShaderTemps,
1138 (int)pState->caps.flPointSize[0], (int)(pState->caps.flPointSize[0] * 100) % 100,
1139 (int)pState->caps.flPointSize[1], (int)(pState->caps.flPointSize[1] * 100) % 100));
1140 LogRel(("VMSVGA3d: fragmentShaderVersion=%-2d vertexShaderVersion=%-2d\n",
1141 pState->caps.fragmentShaderVersion, pState->caps.vertexShaderVersion));
1142 LogRel(("VMSVGA3d: fS3TCSupported=%-2d fTextureFilterAnisotropicSupported=%d\n",
1143 pState->caps.fS3TCSupported, pState->caps.fTextureFilterAnisotropicSupported));
1144
1145
1146 /* Initialize the shader library. */
1147 pState->ShaderIf.pfnSwitchInitProfile = vmsvga3dShaderIfSwitchInitProfile;
1148 pState->ShaderIf.pfnGetNextExtension = vmsvga3dShaderIfGetNextExtension;
1149 rc = ShaderInitLib(&pState->ShaderIf);
1150 AssertRC(rc);
1151
1152 /* Cleanup */
1153 rc = vmsvga3dBackContextDestroy(pThisCC, 1);
1154 AssertRC(rc);
1155#ifdef VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE
1156 rc = vmsvga3dBackContextDestroy(pThisCC, 2);
1157 AssertRC(rc);
1158#endif
1159
1160 if ( pState->rsGLVersion < 3.0
1161 && pState->rsOtherGLVersion < 3.0 /* darwin: legacy profile hack */)
1162 {
1163 LogRel(("VMSVGA3d: unsupported OpenGL version; minimum is 3.0\n"));
1164 return VERR_NOT_IMPLEMENTED;
1165 }
1166
1167 return VINF_SUCCESS;
1168}
1169
1170static DECLCALLBACK(int) vmsvga3dBackReset(PVGASTATECC pThisCC)
1171{
1172 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
1173 AssertReturn(pThisCC->svga.p3dState, VERR_NO_MEMORY);
1174
1175 /* Destroy all leftover surfaces. */
1176 for (uint32_t i = 0; i < pState->cSurfaces; i++)
1177 {
1178 if (pState->papSurfaces[i]->id != SVGA3D_INVALID_ID)
1179 vmsvga3dSurfaceDestroy(pThisCC, pState->papSurfaces[i]->id);
1180 }
1181
1182 /* Destroy all leftover contexts. */
1183 for (uint32_t i = 0; i < pState->cContexts; i++)
1184 {
1185 if (pState->papContexts[i]->id != SVGA3D_INVALID_ID)
1186 vmsvga3dBackContextDestroy(pThisCC, pState->papContexts[i]->id);
1187 }
1188
1189 if (pState->SharedCtx.id == VMSVGA3D_SHARED_CTX_ID)
1190 vmsvga3dContextDestroyOgl(pThisCC, &pState->SharedCtx, VMSVGA3D_SHARED_CTX_ID);
1191
1192 return VINF_SUCCESS;
1193}
1194
1195static DECLCALLBACK(int) vmsvga3dBackTerminate(PVGASTATECC pThisCC)
1196{
1197 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
1198 AssertReturn(pState, VERR_WRONG_ORDER);
1199 int rc;
1200
1201 rc = vmsvga3dBackReset(pThisCC);
1202 AssertRCReturn(rc, rc);
1203
1204 /* Terminate the shader library. */
1205 rc = ShaderDestroyLib();
1206 AssertRC(rc);
1207
1208#ifdef RT_OS_WINDOWS
1209 /* Terminate the window creation thread. */
1210 rc = vmsvga3dSendThreadMessage(pState->pWindowThread, pState->WndRequestSem, WM_VMSVGA3D_EXIT, 0, 0);
1211 AssertRCReturn(rc, rc);
1212
1213 RTSemEventDestroy(pState->WndRequestSem);
1214#elif defined(RT_OS_DARWIN)
1215
1216#elif defined(RT_OS_LINUX)
1217 /* signal to the thread that it is supposed to exit */
1218 pState->bTerminate = true;
1219 /* wait for it to terminate */
1220 rc = RTThreadWait(pState->pWindowThread, 10000, NULL);
1221 AssertRC(rc);
1222 XCloseDisplay(pState->display);
1223#endif
1224
1225 RTStrFree(pState->pszExtensions);
1226 pState->pszExtensions = NULL;
1227#ifdef VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE
1228 RTStrFree(pState->pszOtherExtensions);
1229#endif
1230 pState->pszOtherExtensions = NULL;
1231
1232 /* Free all leftover surface states. */
1233 for (uint32_t i = 0; i < pState->cSurfaces; i++)
1234 {
1235 AssertPtr(pState->papSurfaces[i]);
1236 RTMemFree(pState->papSurfaces[i]);
1237 pState->papSurfaces[i] = NULL;
1238 }
1239
1240 /* Destroy all leftover contexts. */
1241 for (uint32_t i = 0; i < pState->cContexts; i++)
1242 {
1243 AssertPtr(pState->papContexts[i]);
1244 RTMemFree(pState->papContexts[i]);
1245 pState->papContexts[i] = NULL;
1246 }
1247
1248 if (pState->papSurfaces)
1249 {
1250 RTMemFree(pState->papSurfaces);
1251 pState->papSurfaces = NULL;
1252 }
1253
1254 if (pState->papContexts)
1255 {
1256 RTMemFree(pState->papContexts);
1257 pState->papContexts = NULL;
1258 }
1259
1260 pThisCC->svga.p3dState = NULL;
1261 RTMemFree(pState);
1262 return VINF_SUCCESS;
1263}
1264
1265
1266static DECLCALLBACK(void) vmsvga3dBackUpdateHostScreenViewport(PVGASTATECC pThisCC, uint32_t idScreen, VMSVGAVIEWPORT const *pOldViewport)
1267{
1268 /** @todo Move the visible framebuffer content here, don't wait for the guest to
1269 * redraw it. */
1270
1271#ifdef RT_OS_DARWIN
1272 RT_NOREF(pOldViewport);
1273 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
1274 if ( pState
1275 && idScreen == 0
1276 && pState->SharedCtx.id == VMSVGA3D_SHARED_CTX_ID)
1277 {
1278 vmsvga3dCocoaViewUpdateViewport(pState->SharedCtx.cocoaView);
1279 }
1280#else
1281 RT_NOREF(pThisCC, idScreen, pOldViewport);
1282#endif
1283}
1284
1285
1286/**
1287 * Worker for vmsvga3dBackQueryCaps that figures out supported operations for a
1288 * given surface format capability.
1289 *
1290 * @returns Supported/indented operations (SVGA3DFORMAT_OP_XXX).
1291 * @param idx3dCaps The SVGA3D_CAPS_XXX value of the surface format.
1292 *
1293 * @remarks See fromat_cap_table in svga_format.c (mesa/gallium) for a reference
1294 * of implicit guest expectations:
1295 * http://cgit.freedesktop.org/mesa/mesa/tree/src/gallium/drivers/svga/svga_format.c
1296 */
1297static uint32_t vmsvga3dGetSurfaceFormatSupport(uint32_t idx3dCaps)
1298{
1299 uint32_t result = 0;
1300
1301 /** @todo missing:
1302 *
1303 * SVGA3DFORMAT_OP_PIXELSIZE
1304 */
1305
1306 switch (idx3dCaps)
1307 {
1308 case SVGA3D_DEVCAP_SURFACEFMT_X8R8G8B8:
1309 case SVGA3D_DEVCAP_SURFACEFMT_X1R5G5B5:
1310 case SVGA3D_DEVCAP_SURFACEFMT_R5G6B5:
1311 result |= SVGA3DFORMAT_OP_MEMBEROFGROUP_ARGB
1312 | SVGA3DFORMAT_OP_CONVERT_TO_ARGB
1313 | SVGA3DFORMAT_OP_DISPLAYMODE /* Should not be set for alpha formats. */
1314 | SVGA3DFORMAT_OP_3DACCELERATION; /* implies OP_DISPLAYMODE */
1315 break;
1316
1317 case SVGA3D_DEVCAP_SURFACEFMT_A8R8G8B8:
1318 case SVGA3D_DEVCAP_SURFACEFMT_A2R10G10B10:
1319 case SVGA3D_DEVCAP_SURFACEFMT_A1R5G5B5:
1320 case SVGA3D_DEVCAP_SURFACEFMT_A4R4G4B4:
1321 result |= SVGA3DFORMAT_OP_MEMBEROFGROUP_ARGB
1322 | SVGA3DFORMAT_OP_CONVERT_TO_ARGB
1323 | SVGA3DFORMAT_OP_SAME_FORMAT_UP_TO_ALPHA_RENDERTARGET;
1324 break;
1325 }
1326
1327 /** @todo check hardware caps! */
1328 switch (idx3dCaps)
1329 {
1330 case SVGA3D_DEVCAP_SURFACEFMT_X8R8G8B8:
1331 case SVGA3D_DEVCAP_SURFACEFMT_A8R8G8B8:
1332 case SVGA3D_DEVCAP_SURFACEFMT_A2R10G10B10:
1333 case SVGA3D_DEVCAP_SURFACEFMT_X1R5G5B5:
1334 case SVGA3D_DEVCAP_SURFACEFMT_A1R5G5B5:
1335 case SVGA3D_DEVCAP_SURFACEFMT_A4R4G4B4:
1336 case SVGA3D_DEVCAP_SURFACEFMT_R5G6B5:
1337 case SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE16:
1338 case SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE8_ALPHA8:
1339 case SVGA3D_DEVCAP_SURFACEFMT_ALPHA8:
1340 case SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE8:
1341 result |= SVGA3DFORMAT_OP_TEXTURE
1342 | SVGA3DFORMAT_OP_OFFSCREEN_RENDERTARGET
1343 | SVGA3DFORMAT_OP_OFFSCREENPLAIN
1344 | SVGA3DFORMAT_OP_SAME_FORMAT_RENDERTARGET
1345 | SVGA3DFORMAT_OP_VOLUMETEXTURE
1346 | SVGA3DFORMAT_OP_CUBETEXTURE
1347 | SVGA3DFORMAT_OP_SRGBREAD
1348 | SVGA3DFORMAT_OP_SRGBWRITE;
1349 break;
1350
1351 case SVGA3D_DEVCAP_SURFACEFMT_Z_D16:
1352 case SVGA3D_DEVCAP_SURFACEFMT_Z_D24S8:
1353 case SVGA3D_DEVCAP_SURFACEFMT_Z_D24X8:
1354 case SVGA3D_DEVCAP_SURFACEFMT_Z_DF16:
1355 case SVGA3D_DEVCAP_SURFACEFMT_Z_DF24:
1356 case SVGA3D_DEVCAP_SURFACEFMT_Z_D24S8_INT:
1357 result |= SVGA3DFORMAT_OP_ZSTENCIL
1358 | SVGA3DFORMAT_OP_ZSTENCIL_WITH_ARBITRARY_COLOR_DEPTH
1359 | SVGA3DFORMAT_OP_TEXTURE /* Necessary for Ubuntu Unity */;
1360 break;
1361
1362 case SVGA3D_DEVCAP_SURFACEFMT_DXT1:
1363 case SVGA3D_DEVCAP_SURFACEFMT_DXT2:
1364 case SVGA3D_DEVCAP_SURFACEFMT_DXT3:
1365 case SVGA3D_DEVCAP_SURFACEFMT_DXT4:
1366 case SVGA3D_DEVCAP_SURFACEFMT_DXT5:
1367 result |= SVGA3DFORMAT_OP_TEXTURE
1368 | SVGA3DFORMAT_OP_VOLUMETEXTURE
1369 | SVGA3DFORMAT_OP_CUBETEXTURE
1370 | SVGA3DFORMAT_OP_SRGBREAD;
1371 break;
1372
1373 case SVGA3D_DEVCAP_SURFACEFMT_BUMPX8L8V8U8:
1374 case SVGA3D_DEVCAP_SURFACEFMT_A2W10V10U10:
1375 case SVGA3D_DEVCAP_SURFACEFMT_BUMPU8V8:
1376 case SVGA3D_DEVCAP_SURFACEFMT_Q8W8V8U8:
1377 case SVGA3D_DEVCAP_SURFACEFMT_CxV8U8:
1378 break;
1379
1380 case SVGA3D_DEVCAP_SURFACEFMT_R_S10E5:
1381 case SVGA3D_DEVCAP_SURFACEFMT_R_S23E8:
1382 case SVGA3D_DEVCAP_SURFACEFMT_RG_S10E5:
1383 case SVGA3D_DEVCAP_SURFACEFMT_RG_S23E8:
1384 case SVGA3D_DEVCAP_SURFACEFMT_ARGB_S10E5:
1385 case SVGA3D_DEVCAP_SURFACEFMT_ARGB_S23E8:
1386 result |= SVGA3DFORMAT_OP_TEXTURE
1387 | SVGA3DFORMAT_OP_VOLUMETEXTURE
1388 | SVGA3DFORMAT_OP_CUBETEXTURE
1389 | SVGA3DFORMAT_OP_OFFSCREEN_RENDERTARGET;
1390 break;
1391
1392 case SVGA3D_DEVCAP_SURFACEFMT_V16U16:
1393 case SVGA3D_DEVCAP_SURFACEFMT_G16R16:
1394 case SVGA3D_DEVCAP_SURFACEFMT_A16B16G16R16:
1395 result |= SVGA3DFORMAT_OP_TEXTURE
1396 | SVGA3DFORMAT_OP_VOLUMETEXTURE
1397 | SVGA3DFORMAT_OP_CUBETEXTURE
1398 | SVGA3DFORMAT_OP_OFFSCREEN_RENDERTARGET;
1399 break;
1400
1401 case SVGA3D_DEVCAP_SURFACEFMT_UYVY:
1402 case SVGA3D_DEVCAP_SURFACEFMT_YUY2:
1403 result |= SVGA3DFORMAT_OP_OFFSCREENPLAIN
1404 | SVGA3DFORMAT_OP_CONVERT_TO_ARGB
1405 | SVGA3DFORMAT_OP_TEXTURE;
1406 break;
1407
1408 case SVGA3D_DEVCAP_SURFACEFMT_NV12:
1409 case SVGA3D_DEVCAP_DEAD10: /* SVGA3D_DEVCAP_SURFACEFMT_AYUV */
1410 break;
1411 }
1412 Log(("CAPS: %s =\n%s\n", vmsvga3dGetCapString(idx3dCaps), vmsvga3dGet3dFormatString(result)));
1413
1414 return result;
1415}
1416
1417#if 0 /* unused */
1418static uint32_t vmsvga3dGetDepthFormatSupport(PVMSVGA3DSTATE pState3D, uint32_t idx3dCaps)
1419{
1420 RT_NOREF(pState3D, idx3dCaps);
1421
1422 /** @todo test this somehow */
1423 uint32_t result = SVGA3DFORMAT_OP_ZSTENCIL | SVGA3DFORMAT_OP_ZSTENCIL_WITH_ARBITRARY_COLOR_DEPTH;
1424
1425 Log(("CAPS: %s =\n%s\n", vmsvga3dGetCapString(idx3dCaps), vmsvga3dGet3dFormatString(result)));
1426 return result;
1427}
1428#endif
1429
1430
1431static DECLCALLBACK(int) vmsvga3dBackQueryCaps(PVGASTATECC pThisCC, SVGA3dDevCapIndex idx3dCaps, uint32_t *pu32Val)
1432{
1433 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
1434 AssertReturn(pState, VERR_NO_MEMORY);
1435 int rc = VINF_SUCCESS;
1436
1437 *pu32Val = 0;
1438
1439 /*
1440 * The capabilities access by current (2015-03-01) linux sources (gallium,
1441 * vmwgfx, xorg-video-vmware) are annotated, caps without xref annotations
1442 * aren't access.
1443 */
1444
1445 switch (idx3dCaps)
1446 {
1447 /* Linux: vmwgfx_fifo.c in kmod; only used with SVGA_CAP_GBOBJECTS. */
1448 case SVGA3D_DEVCAP_3D:
1449 *pu32Val = 1; /* boolean? */
1450 break;
1451
1452 case SVGA3D_DEVCAP_MAX_LIGHTS:
1453 *pu32Val = pState->caps.maxActiveLights;
1454 break;
1455
1456 case SVGA3D_DEVCAP_MAX_TEXTURES:
1457 *pu32Val = pState->caps.maxTextures;
1458 break;
1459
1460 case SVGA3D_DEVCAP_MAX_CLIP_PLANES:
1461 *pu32Val = pState->caps.maxClipDistances;
1462 break;
1463
1464 /* Linux: svga_screen.c in gallium; 3.0 or later required. */
1465 case SVGA3D_DEVCAP_VERTEX_SHADER_VERSION:
1466 *pu32Val = pState->caps.vertexShaderVersion;
1467 break;
1468
1469 case SVGA3D_DEVCAP_VERTEX_SHADER:
1470 /* boolean? */
1471 *pu32Val = (pState->caps.vertexShaderVersion != SVGA3DVSVERSION_NONE);
1472 break;
1473
1474 /* Linux: svga_screen.c in gallium; 3.0 or later required. */
1475 case SVGA3D_DEVCAP_FRAGMENT_SHADER_VERSION:
1476 *pu32Val = pState->caps.fragmentShaderVersion;
1477 break;
1478
1479 case SVGA3D_DEVCAP_FRAGMENT_SHADER:
1480 /* boolean? */
1481 *pu32Val = (pState->caps.fragmentShaderVersion != SVGA3DPSVERSION_NONE);
1482 break;
1483
1484 case SVGA3D_DEVCAP_S23E8_TEXTURES:
1485 case SVGA3D_DEVCAP_S10E5_TEXTURES:
1486 /* Must be obsolete by now; surface format caps specify the same thing. */
1487 rc = VERR_INVALID_PARAMETER;
1488 break;
1489
1490 case SVGA3D_DEVCAP_MAX_FIXED_VERTEXBLEND:
1491 break;
1492
1493 /*
1494 * 2. The BUFFER_FORMAT capabilities are deprecated, and they always
1495 * return TRUE. Even on physical hardware that does not support
1496 * these formats natively, the SVGA3D device will provide an emulation
1497 * which should be invisible to the guest OS.
1498 */
1499 case SVGA3D_DEVCAP_D16_BUFFER_FORMAT:
1500 case SVGA3D_DEVCAP_D24S8_BUFFER_FORMAT:
1501 case SVGA3D_DEVCAP_D24X8_BUFFER_FORMAT:
1502 *pu32Val = 1;
1503 break;
1504
1505 case SVGA3D_DEVCAP_QUERY_TYPES:
1506 break;
1507
1508 case SVGA3D_DEVCAP_TEXTURE_GRADIENT_SAMPLING:
1509 break;
1510
1511 /* Linux: svga_screen.c in gallium; capped at 80.0, default 1.0. */
1512 case SVGA3D_DEVCAP_MAX_POINT_SIZE:
1513 AssertCompile(sizeof(uint32_t) == sizeof(float));
1514 *(float *)pu32Val = pState->caps.flPointSize[1];
1515 break;
1516
1517 case SVGA3D_DEVCAP_MAX_SHADER_TEXTURES:
1518 /** @todo ?? */
1519 rc = VERR_INVALID_PARAMETER;
1520 break;
1521
1522 /* Linux: svga_screen.c in gallium (for PIPE_CAP_MAX_TEXTURE_2D_LEVELS); have default if missing. */
1523 case SVGA3D_DEVCAP_MAX_TEXTURE_WIDTH:
1524 case SVGA3D_DEVCAP_MAX_TEXTURE_HEIGHT:
1525 *pu32Val = pState->caps.maxRectangleTextureSize;
1526 break;
1527
1528 /* Linux: svga_screen.c in gallium (for PIPE_CAP_MAX_TEXTURE_3D_LEVELS); have default if missing. */
1529 case SVGA3D_DEVCAP_MAX_VOLUME_EXTENT:
1530 //*pu32Val = pCaps->MaxVolumeExtent;
1531 *pu32Val = 256;
1532 break;
1533
1534 case SVGA3D_DEVCAP_MAX_TEXTURE_REPEAT:
1535 *pu32Val = 32768; /* hardcoded in Wine */
1536 break;
1537
1538 case SVGA3D_DEVCAP_MAX_TEXTURE_ASPECT_RATIO:
1539 //*pu32Val = pCaps->MaxTextureAspectRatio;
1540 break;
1541
1542 /* Linux: svga_screen.c in gallium (for PIPE_CAPF_MAX_TEXTURE_ANISOTROPY); defaults to 4.0. */
1543 case SVGA3D_DEVCAP_MAX_TEXTURE_ANISOTROPY:
1544 *pu32Val = pState->caps.maxTextureAnisotropy;
1545 break;
1546
1547 case SVGA3D_DEVCAP_MAX_PRIMITIVE_COUNT:
1548 case SVGA3D_DEVCAP_MAX_VERTEX_INDEX:
1549 *pu32Val = 0xFFFFF; /* hardcoded in Wine */
1550 break;
1551
1552 /* Linux: svga_screen.c in gallium (for PIPE_SHADER_VERTEX/PIPE_SHADER_CAP_MAX_INSTRUCTIONS); defaults to 512. */
1553 case SVGA3D_DEVCAP_MAX_VERTEX_SHADER_INSTRUCTIONS:
1554 *pu32Val = pState->caps.maxVertexShaderInstructions;
1555 break;
1556
1557 case SVGA3D_DEVCAP_MAX_FRAGMENT_SHADER_INSTRUCTIONS:
1558 *pu32Val = pState->caps.maxFragmentShaderInstructions;
1559 break;
1560
1561 /* Linux: svga_screen.c in gallium (for PIPE_SHADER_VERTEX/PIPE_SHADER_CAP_MAX_TEMPS); defaults to 32. */
1562 case SVGA3D_DEVCAP_MAX_VERTEX_SHADER_TEMPS:
1563 *pu32Val = pState->caps.maxVertexShaderTemps;
1564 break;
1565
1566 /* Linux: svga_screen.c in gallium (for PIPE_SHADER_FRAGMENT/PIPE_SHADER_CAP_MAX_TEMPS); defaults to 32. */
1567 case SVGA3D_DEVCAP_MAX_FRAGMENT_SHADER_TEMPS:
1568 *pu32Val = pState->caps.maxFragmentShaderTemps;
1569 break;
1570
1571 case SVGA3D_DEVCAP_TEXTURE_OPS:
1572 break;
1573
1574 case SVGA3D_DEVCAP_DEAD4: /* SVGA3D_DEVCAP_MULTISAMPLE_NONMASKABLESAMPLES */
1575 break;
1576
1577 case SVGA3D_DEVCAP_DEAD5: /* SVGA3D_DEVCAP_MULTISAMPLE_MASKABLESAMPLES */
1578 break;
1579
1580 case SVGA3D_DEVCAP_DEAD7: /* SVGA3D_DEVCAP_ALPHATOCOVERAGE */
1581 break;
1582
1583 case SVGA3D_DEVCAP_DEAD6: /* SVGA3D_DEVCAP_SUPERSAMPLE */
1584 break;
1585
1586 case SVGA3D_DEVCAP_AUTOGENMIPMAPS:
1587 //*pu32Val = !!(pCaps->Caps2 & D3DCAPS2_CANAUTOGENMIPMAP);
1588 break;
1589
1590 case SVGA3D_DEVCAP_MAX_VERTEX_SHADER_TEXTURES:
1591 break;
1592
1593 case SVGA3D_DEVCAP_MAX_RENDER_TARGETS: /** @todo same thing? */
1594 case SVGA3D_DEVCAP_MAX_SIMULTANEOUS_RENDER_TARGETS:
1595 *pu32Val = pState->caps.maxColorAttachments;
1596 break;
1597
1598 /*
1599 * This is the maximum number of SVGA context IDs that the guest
1600 * can define using SVGA_3D_CMD_CONTEXT_DEFINE.
1601 */
1602 case SVGA3D_DEVCAP_MAX_CONTEXT_IDS:
1603 *pu32Val = SVGA3D_MAX_CONTEXT_IDS;
1604 break;
1605
1606 /*
1607 * This is the maximum number of SVGA surface IDs that the guest
1608 * can define using SVGA_3D_CMD_SURFACE_DEFINE*.
1609 */
1610 case SVGA3D_DEVCAP_MAX_SURFACE_IDS:
1611 *pu32Val = SVGA3D_MAX_SURFACE_IDS;
1612 break;
1613
1614#if 0 /* Appeared more recently, not yet implemented. */
1615 /* Linux: svga_screen.c in gallium; defaults to FALSE. */
1616 case SVGA3D_DEVCAP_LINE_AA:
1617 break;
1618 /* Linux: svga_screen.c in gallium; defaults to FALSE. */
1619 case SVGA3D_DEVCAP_LINE_STIPPLE:
1620 break;
1621 /* Linux: svga_screen.c in gallium; defaults to 1.0. */
1622 case SVGA3D_DEVCAP_MAX_LINE_WIDTH:
1623 break;
1624 /* Linux: svga_screen.c in gallium; defaults to 1.0. */
1625 case SVGA3D_DEVCAP_MAX_AA_LINE_WIDTH:
1626 break;
1627#endif
1628
1629 /*
1630 * Supported surface formats.
1631 * Linux: svga_format.c in gallium, format_cap_table defines implicit expectations.
1632 */
1633 case SVGA3D_DEVCAP_SURFACEFMT_X8R8G8B8:
1634 case SVGA3D_DEVCAP_SURFACEFMT_A8R8G8B8:
1635 case SVGA3D_DEVCAP_SURFACEFMT_A2R10G10B10:
1636 case SVGA3D_DEVCAP_SURFACEFMT_X1R5G5B5:
1637 case SVGA3D_DEVCAP_SURFACEFMT_A1R5G5B5:
1638 case SVGA3D_DEVCAP_SURFACEFMT_A4R4G4B4:
1639 case SVGA3D_DEVCAP_SURFACEFMT_R5G6B5:
1640 case SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE16:
1641 case SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE8_ALPHA8:
1642 case SVGA3D_DEVCAP_SURFACEFMT_ALPHA8:
1643 case SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE8:
1644 case SVGA3D_DEVCAP_SURFACEFMT_Z_D16:
1645 case SVGA3D_DEVCAP_SURFACEFMT_Z_D24S8:
1646 case SVGA3D_DEVCAP_SURFACEFMT_Z_D24X8:
1647 case SVGA3D_DEVCAP_SURFACEFMT_Z_DF16:
1648 case SVGA3D_DEVCAP_SURFACEFMT_Z_DF24:
1649 case SVGA3D_DEVCAP_SURFACEFMT_Z_D24S8_INT:
1650 case SVGA3D_DEVCAP_SURFACEFMT_DXT1:
1651 *pu32Val = vmsvga3dGetSurfaceFormatSupport(idx3dCaps);
1652 break;
1653
1654 case SVGA3D_DEVCAP_SURFACEFMT_DXT2:
1655 case SVGA3D_DEVCAP_SURFACEFMT_DXT3:
1656 case SVGA3D_DEVCAP_SURFACEFMT_DXT4:
1657 case SVGA3D_DEVCAP_SURFACEFMT_DXT5:
1658 case SVGA3D_DEVCAP_SURFACEFMT_BUMPX8L8V8U8:
1659 case SVGA3D_DEVCAP_SURFACEFMT_A2W10V10U10:
1660 case SVGA3D_DEVCAP_SURFACEFMT_BUMPU8V8:
1661 case SVGA3D_DEVCAP_SURFACEFMT_Q8W8V8U8:
1662 case SVGA3D_DEVCAP_SURFACEFMT_CxV8U8:
1663 case SVGA3D_DEVCAP_SURFACEFMT_R_S10E5:
1664 case SVGA3D_DEVCAP_SURFACEFMT_R_S23E8:
1665 case SVGA3D_DEVCAP_SURFACEFMT_RG_S10E5:
1666 case SVGA3D_DEVCAP_SURFACEFMT_RG_S23E8:
1667 case SVGA3D_DEVCAP_SURFACEFMT_ARGB_S10E5:
1668 case SVGA3D_DEVCAP_SURFACEFMT_ARGB_S23E8:
1669 case SVGA3D_DEVCAP_SURFACEFMT_V16U16:
1670 case SVGA3D_DEVCAP_SURFACEFMT_G16R16:
1671 case SVGA3D_DEVCAP_SURFACEFMT_A16B16G16R16:
1672 case SVGA3D_DEVCAP_SURFACEFMT_UYVY:
1673 case SVGA3D_DEVCAP_SURFACEFMT_YUY2:
1674 case SVGA3D_DEVCAP_SURFACEFMT_NV12:
1675 case SVGA3D_DEVCAP_DEAD10: /* SVGA3D_DEVCAP_SURFACEFMT_AYUV */
1676 *pu32Val = vmsvga3dGetSurfaceFormatSupport(idx3dCaps);
1677 break;
1678
1679 /* Linux: Not referenced in current sources. */
1680 case SVGA3D_DEVCAP_SURFACEFMT_ATI1:
1681 case SVGA3D_DEVCAP_SURFACEFMT_ATI2:
1682 Log(("CAPS: Unknown CAP %s\n", vmsvga3dGetCapString(idx3dCaps)));
1683 rc = VERR_INVALID_PARAMETER;
1684 *pu32Val = 0;
1685 break;
1686
1687 default:
1688 Log(("CAPS: Unexpected CAP %d\n", idx3dCaps));
1689 rc = VERR_INVALID_PARAMETER;
1690 break;
1691 }
1692
1693 Log(("CAPS: %s - %x\n", vmsvga3dGetCapString(idx3dCaps), *pu32Val));
1694 return rc;
1695}
1696
1697/**
1698 * Convert SVGA format value to its OpenGL equivalent
1699 *
1700 * @remarks Clues to be had in format_texture_info table (wined3d/utils.c) with
1701 * help from wined3dformat_from_d3dformat().
1702 */
1703void vmsvga3dSurfaceFormat2OGL(PVMSVGA3DSURFACE pSurface, SVGA3dSurfaceFormat format)
1704{
1705#if 0
1706#define AssertTestFmt(f) AssertMsgFailed(("Test me - " #f "\n"))
1707#else
1708#define AssertTestFmt(f) do {} while(0)
1709#endif
1710 /* Init cbBlockGL for non-emulated formats. */
1711 pSurface->cbBlockGL = pSurface->cbBlock;
1712
1713 switch (format)
1714 {
1715 case SVGA3D_X8R8G8B8: /* D3DFMT_X8R8G8B8 - WINED3DFMT_B8G8R8X8_UNORM */
1716 pSurface->internalFormatGL = GL_RGB8;
1717 pSurface->formatGL = GL_BGRA;
1718 pSurface->typeGL = GL_UNSIGNED_INT_8_8_8_8_REV;
1719 break;
1720 case SVGA3D_A8R8G8B8: /* D3DFMT_A8R8G8B8 - WINED3DFMT_B8G8R8A8_UNORM */
1721 pSurface->internalFormatGL = GL_RGBA8;
1722 pSurface->formatGL = GL_BGRA;
1723 pSurface->typeGL = GL_UNSIGNED_INT_8_8_8_8_REV;
1724 break;
1725 case SVGA3D_R5G6B5: /* D3DFMT_R5G6B5 - WINED3DFMT_B5G6R5_UNORM */
1726 pSurface->internalFormatGL = GL_RGB5;
1727 pSurface->formatGL = GL_RGB;
1728 pSurface->typeGL = GL_UNSIGNED_SHORT_5_6_5;
1729 AssertTestFmt(SVGA3D_R5G6B5);
1730 break;
1731 case SVGA3D_X1R5G5B5: /* D3DFMT_X1R5G5B5 - WINED3DFMT_B5G5R5X1_UNORM */
1732 pSurface->internalFormatGL = GL_RGB5;
1733 pSurface->formatGL = GL_BGRA;
1734 pSurface->typeGL = GL_UNSIGNED_SHORT_1_5_5_5_REV;
1735 AssertTestFmt(SVGA3D_X1R5G5B5);
1736 break;
1737 case SVGA3D_A1R5G5B5: /* D3DFMT_A1R5G5B5 - WINED3DFMT_B5G5R5A1_UNORM */
1738 pSurface->internalFormatGL = GL_RGB5_A1;
1739 pSurface->formatGL = GL_BGRA;
1740 pSurface->typeGL = GL_UNSIGNED_SHORT_1_5_5_5_REV;
1741 AssertTestFmt(SVGA3D_A1R5G5B5);
1742 break;
1743 case SVGA3D_A4R4G4B4: /* D3DFMT_A4R4G4B4 - WINED3DFMT_B4G4R4A4_UNORM */
1744 pSurface->internalFormatGL = GL_RGBA4;
1745 pSurface->formatGL = GL_BGRA;
1746 pSurface->typeGL = GL_UNSIGNED_SHORT_4_4_4_4_REV;
1747 AssertTestFmt(SVGA3D_A4R4G4B4);
1748 break;
1749
1750 case SVGA3D_R8G8B8A8_UNORM:
1751 pSurface->internalFormatGL = GL_RGBA8;
1752 pSurface->formatGL = GL_RGBA;
1753 pSurface->typeGL = GL_UNSIGNED_INT_8_8_8_8_REV;
1754 break;
1755
1756 case SVGA3D_Z_D32: /* D3DFMT_D32 - WINED3DFMT_D32_UNORM */
1757 pSurface->internalFormatGL = GL_DEPTH_COMPONENT32;
1758 pSurface->formatGL = GL_DEPTH_COMPONENT;
1759 pSurface->typeGL = GL_UNSIGNED_INT;
1760 break;
1761 case SVGA3D_Z_D16: /* D3DFMT_D16 - WINED3DFMT_D16_UNORM */
1762 pSurface->internalFormatGL = GL_DEPTH_COMPONENT16; /** @todo Wine suggests GL_DEPTH_COMPONENT24. */
1763 pSurface->formatGL = GL_DEPTH_COMPONENT;
1764 pSurface->typeGL = GL_UNSIGNED_SHORT;
1765 AssertTestFmt(SVGA3D_Z_D16);
1766 break;
1767 case SVGA3D_Z_D24S8: /* D3DFMT_D24S8 - WINED3DFMT_D24_UNORM_S8_UINT */
1768 pSurface->internalFormatGL = GL_DEPTH24_STENCIL8;
1769 pSurface->formatGL = GL_DEPTH_STENCIL;
1770 pSurface->typeGL = GL_UNSIGNED_INT_24_8;
1771 break;
1772 case SVGA3D_Z_D15S1: /* D3DFMT_D15S1 - WINED3DFMT_S1_UINT_D15_UNORM */
1773 pSurface->internalFormatGL = GL_DEPTH_COMPONENT16; /** @todo ??? */
1774 pSurface->formatGL = GL_DEPTH_STENCIL;
1775 pSurface->typeGL = GL_UNSIGNED_SHORT;
1776 /** @todo Wine sources hints at no hw support for this, so test this one! */
1777 AssertTestFmt(SVGA3D_Z_D15S1);
1778 break;
1779 case SVGA3D_Z_D24X8: /* D3DFMT_D24X8 - WINED3DFMT_X8D24_UNORM */
1780 pSurface->internalFormatGL = GL_DEPTH_COMPONENT24;
1781 pSurface->formatGL = GL_DEPTH_COMPONENT;
1782 pSurface->typeGL = GL_UNSIGNED_INT;
1783 AssertTestFmt(SVGA3D_Z_D24X8);
1784 break;
1785
1786 /* Advanced D3D9 depth formats. */
1787 case SVGA3D_Z_DF16: /* D3DFMT_DF16? - not supported */
1788 pSurface->internalFormatGL = GL_DEPTH_COMPONENT16;
1789 pSurface->formatGL = GL_DEPTH_COMPONENT;
1790 pSurface->typeGL = GL_HALF_FLOAT;
1791 break;
1792
1793 case SVGA3D_Z_DF24: /* D3DFMT_DF24? - not supported */
1794 pSurface->internalFormatGL = GL_DEPTH_COMPONENT24;
1795 pSurface->formatGL = GL_DEPTH_COMPONENT;
1796 pSurface->typeGL = GL_FLOAT; /* ??? */
1797 break;
1798
1799 case SVGA3D_Z_D24S8_INT: /* D3DFMT_D24S8 */
1800 pSurface->internalFormatGL = GL_DEPTH24_STENCIL8;
1801 pSurface->formatGL = GL_DEPTH_STENCIL;
1802 pSurface->typeGL = GL_UNSIGNED_INT_24_8;
1803 break;
1804
1805 case SVGA3D_DXT1: /* D3DFMT_DXT1 - WINED3DFMT_DXT1 */
1806 pSurface->internalFormatGL = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
1807 pSurface->formatGL = GL_RGBA; /* not used */
1808 pSurface->typeGL = GL_UNSIGNED_BYTE; /* not used */
1809 break;
1810
1811 case SVGA3D_DXT2: /* D3DFMT_DXT2 */
1812 /* "DXT2 and DXT3 are the same from an API perspective." */
1813 RT_FALL_THRU();
1814 case SVGA3D_DXT3: /* D3DFMT_DXT3 - WINED3DFMT_DXT3 */
1815 pSurface->internalFormatGL = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
1816 pSurface->formatGL = GL_RGBA; /* not used */
1817 pSurface->typeGL = GL_UNSIGNED_BYTE; /* not used */
1818 break;
1819
1820 case SVGA3D_DXT4: /* D3DFMT_DXT4 */
1821 /* "DXT4 and DXT5 are the same from an API perspective." */
1822 RT_FALL_THRU();
1823 case SVGA3D_DXT5: /* D3DFMT_DXT5 - WINED3DFMT_DXT5 */
1824 pSurface->internalFormatGL = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
1825 pSurface->formatGL = GL_RGBA; /* not used */
1826 pSurface->typeGL = GL_UNSIGNED_BYTE; /* not used */
1827 break;
1828
1829 case SVGA3D_LUMINANCE8: /* D3DFMT_? - ? */
1830 pSurface->internalFormatGL = GL_LUMINANCE8_EXT;
1831 pSurface->formatGL = GL_LUMINANCE;
1832 pSurface->typeGL = GL_UNSIGNED_BYTE;
1833 break;
1834
1835 case SVGA3D_LUMINANCE16: /* D3DFMT_? - ? */
1836 pSurface->internalFormatGL = GL_LUMINANCE16_EXT;
1837 pSurface->formatGL = GL_LUMINANCE;
1838 pSurface->typeGL = GL_UNSIGNED_SHORT;
1839 break;
1840
1841 case SVGA3D_LUMINANCE4_ALPHA4: /* D3DFMT_? - ? */
1842 pSurface->internalFormatGL = GL_LUMINANCE4_ALPHA4_EXT;
1843 pSurface->formatGL = GL_LUMINANCE_ALPHA;
1844 pSurface->typeGL = GL_UNSIGNED_BYTE;
1845 break;
1846
1847 case SVGA3D_LUMINANCE8_ALPHA8: /* D3DFMT_? - ? */
1848 pSurface->internalFormatGL = GL_LUMINANCE8_ALPHA8_EXT;
1849 pSurface->formatGL = GL_LUMINANCE_ALPHA;
1850 pSurface->typeGL = GL_UNSIGNED_BYTE; /* unsigned_short causes issues even though this type should be 16-bit */
1851 break;
1852
1853 case SVGA3D_ALPHA8: /* D3DFMT_A8? - WINED3DFMT_A8_UNORM? */
1854 pSurface->internalFormatGL = GL_ALPHA8_EXT;
1855 pSurface->formatGL = GL_ALPHA;
1856 pSurface->typeGL = GL_UNSIGNED_BYTE;
1857 break;
1858
1859#if 0
1860
1861 /* Bump-map formats */
1862 case SVGA3D_BUMPU8V8:
1863 return D3DFMT_V8U8;
1864 case SVGA3D_BUMPL6V5U5:
1865 return D3DFMT_L6V5U5;
1866 case SVGA3D_BUMPX8L8V8U8:
1867 return D3DFMT_X8L8V8U8;
1868 case SVGA3D_FORMAT_DEAD1:
1869 /* No corresponding D3D9 equivalent. */
1870 AssertFailedReturn(D3DFMT_UNKNOWN);
1871 /* signed bump-map formats */
1872 case SVGA3D_V8U8:
1873 return D3DFMT_V8U8;
1874 case SVGA3D_Q8W8V8U8:
1875 return D3DFMT_Q8W8V8U8;
1876 case SVGA3D_CxV8U8:
1877 return D3DFMT_CxV8U8;
1878 /* mixed bump-map formats */
1879 case SVGA3D_X8L8V8U8:
1880 return D3DFMT_X8L8V8U8;
1881 case SVGA3D_A2W10V10U10:
1882 return D3DFMT_A2W10V10U10;
1883#endif
1884
1885 case SVGA3D_ARGB_S10E5: /* 16-bit floating-point ARGB */ /* D3DFMT_A16B16G16R16F - WINED3DFMT_R16G16B16A16_FLOAT */
1886 pSurface->internalFormatGL = GL_RGBA16F;
1887 pSurface->formatGL = GL_RGBA;
1888#if 0 /* bird: wine uses half float, sounds correct to me... */
1889 pSurface->typeGL = GL_FLOAT;
1890#else
1891 pSurface->typeGL = GL_HALF_FLOAT;
1892 AssertTestFmt(SVGA3D_ARGB_S10E5);
1893#endif
1894 break;
1895
1896 case SVGA3D_ARGB_S23E8: /* 32-bit floating-point ARGB */ /* D3DFMT_A32B32G32R32F - WINED3DFMT_R32G32B32A32_FLOAT */
1897 pSurface->internalFormatGL = GL_RGBA32F;
1898 pSurface->formatGL = GL_RGBA;
1899 pSurface->typeGL = GL_FLOAT; /* ?? - same as wine, so probably correct */
1900 break;
1901
1902 case SVGA3D_A2R10G10B10: /* D3DFMT_A2R10G10B10 - WINED3DFMT_B10G10R10A2_UNORM */
1903 pSurface->internalFormatGL = GL_RGB10_A2; /* ?? - same as wine, so probably correct */
1904#if 0 /* bird: Wine uses GL_BGRA instead of GL_RGBA. */
1905 pSurface->formatGL = GL_RGBA;
1906#else
1907 pSurface->formatGL = GL_BGRA;
1908#endif
1909 pSurface->typeGL = GL_UNSIGNED_INT;
1910 AssertTestFmt(SVGA3D_A2R10G10B10);
1911 break;
1912
1913
1914 /* Single- and dual-component floating point formats */
1915 case SVGA3D_R_S10E5: /* D3DFMT_R16F - WINED3DFMT_R16_FLOAT */
1916 pSurface->internalFormatGL = GL_R16F;
1917 pSurface->formatGL = GL_RED;
1918#if 0 /* bird: wine uses half float, sounds correct to me... */
1919 pSurface->typeGL = GL_FLOAT;
1920#else
1921 pSurface->typeGL = GL_HALF_FLOAT;
1922 AssertTestFmt(SVGA3D_R_S10E5);
1923#endif
1924 break;
1925 case SVGA3D_R_S23E8: /* D3DFMT_R32F - WINED3DFMT_R32_FLOAT */
1926 pSurface->internalFormatGL = GL_R32F;
1927 pSurface->formatGL = GL_RED;
1928 pSurface->typeGL = GL_FLOAT;
1929 break;
1930 case SVGA3D_RG_S10E5: /* D3DFMT_G16R16F - WINED3DFMT_R16G16_FLOAT */
1931 pSurface->internalFormatGL = GL_RG16F;
1932 pSurface->formatGL = GL_RG;
1933#if 0 /* bird: wine uses half float, sounds correct to me... */
1934 pSurface->typeGL = GL_FLOAT;
1935#else
1936 pSurface->typeGL = GL_HALF_FLOAT;
1937 AssertTestFmt(SVGA3D_RG_S10E5);
1938#endif
1939 break;
1940 case SVGA3D_RG_S23E8: /* D3DFMT_G32R32F - WINED3DFMT_R32G32_FLOAT */
1941 pSurface->internalFormatGL = GL_RG32F;
1942 pSurface->formatGL = GL_RG;
1943 pSurface->typeGL = GL_FLOAT;
1944 break;
1945
1946 /*
1947 * Any surface can be used as a buffer object, but SVGA3D_BUFFER is
1948 * the most efficient format to use when creating new surfaces
1949 * expressly for index or vertex data.
1950 */
1951 case SVGA3D_BUFFER:
1952 pSurface->internalFormatGL = -1;
1953 pSurface->formatGL = -1;
1954 pSurface->typeGL = -1;
1955 break;
1956
1957#if 0
1958 return D3DFMT_UNKNOWN;
1959
1960 case SVGA3D_V16U16:
1961 return D3DFMT_V16U16;
1962#endif
1963
1964 case SVGA3D_G16R16: /* D3DFMT_G16R16 - WINED3DFMT_R16G16_UNORM */
1965 pSurface->internalFormatGL = GL_RG16;
1966 pSurface->formatGL = GL_RG;
1967#if 0 /* bird: Wine uses GL_UNSIGNED_SHORT here. */
1968 pSurface->typeGL = GL_UNSIGNED_INT;
1969#else
1970 pSurface->typeGL = GL_UNSIGNED_SHORT;
1971 AssertTestFmt(SVGA3D_G16R16);
1972#endif
1973 break;
1974
1975 case SVGA3D_A16B16G16R16: /* D3DFMT_A16B16G16R16 - WINED3DFMT_R16G16B16A16_UNORM */
1976 pSurface->internalFormatGL = GL_RGBA16;
1977 pSurface->formatGL = GL_RGBA;
1978#if 0 /* bird: Wine uses GL_UNSIGNED_SHORT here. */
1979 pSurface->typeGL = GL_UNSIGNED_INT; /* ??? */
1980#else
1981 pSurface->typeGL = GL_UNSIGNED_SHORT;
1982 AssertTestFmt(SVGA3D_A16B16G16R16);
1983#endif
1984 break;
1985
1986 case SVGA3D_R8G8B8A8_SNORM:
1987 pSurface->internalFormatGL = GL_RGB8;
1988 pSurface->formatGL = GL_BGRA;
1989 pSurface->typeGL = GL_UNSIGNED_INT_8_8_8_8_REV;
1990 AssertTestFmt(SVGA3D_R8G8B8A8_SNORM);
1991 break;
1992 case SVGA3D_R16G16_UNORM:
1993 pSurface->internalFormatGL = GL_RG16;
1994 pSurface->formatGL = GL_RG;
1995 pSurface->typeGL = GL_UNSIGNED_SHORT;
1996 AssertTestFmt(SVGA3D_R16G16_UNORM);
1997 break;
1998
1999 /* Packed Video formats */
2000 case SVGA3D_UYVY:
2001 case SVGA3D_YUY2:
2002 /* Use a BRGA texture to hold the data and convert it to an actual BGRA. */
2003 pSurface->fEmulated = true;
2004 pSurface->internalFormatGL = GL_RGBA8;
2005 pSurface->formatGL = GL_BGRA;
2006 pSurface->typeGL = GL_UNSIGNED_INT_8_8_8_8_REV;
2007 pSurface->cbBlockGL = 4 * pSurface->cxBlock * pSurface->cyBlock;
2008 break;
2009
2010#if 0
2011 /* Planar video formats */
2012 case SVGA3D_NV12:
2013 return (D3DFORMAT)MAKEFOURCC('N', 'V', '1', '2');
2014
2015 /* Video format with alpha */
2016 case SVGA3D_FORMAT_DEAD2: /* Old SVGA3D_AYUV */
2017
2018 case SVGA3D_ATI1:
2019 case SVGA3D_ATI2:
2020 /* Unknown; only in DX10 & 11 */
2021 break;
2022#endif
2023 default:
2024 AssertMsgFailed(("Unsupported format %d\n", format));
2025 break;
2026 }
2027#undef AssertTestFmt
2028}
2029
2030
2031#if 0
2032/**
2033 * Convert SVGA multi sample count value to its D3D equivalent
2034 */
2035D3DMULTISAMPLE_TYPE vmsvga3dMultipeSampleCount2D3D(uint32_t multisampleCount)
2036{
2037 AssertCompile(D3DMULTISAMPLE_2_SAMPLES == 2);
2038 AssertCompile(D3DMULTISAMPLE_16_SAMPLES == 16);
2039
2040 if (multisampleCount > 16)
2041 return D3DMULTISAMPLE_NONE;
2042
2043 /** @todo exact same mapping as d3d? */
2044 return (D3DMULTISAMPLE_TYPE)multisampleCount;
2045}
2046#endif
2047
2048/**
2049 * Destroy backend specific surface bits (part of SVGA_3D_CMD_SURFACE_DESTROY).
2050 *
2051 * @param pThisCC The device state.
2052 * @param fClearCOTableEntry Not relevant for this backend.
2053 * @param pSurface The surface being destroyed.
2054 */
2055static DECLCALLBACK(void) vmsvga3dBackSurfaceDestroy(PVGASTATECC pThisCC, bool fClearCOTableEntry, PVMSVGA3DSURFACE pSurface)
2056{
2057 RT_NOREF(fClearCOTableEntry);
2058
2059 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
2060 AssertReturnVoid(pState);
2061
2062 PVMSVGA3DCONTEXT pContext = &pState->SharedCtx;
2063 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
2064
2065 switch (pSurface->enmOGLResType)
2066 {
2067 case VMSVGA3D_OGLRESTYPE_BUFFER:
2068 Assert(pSurface->oglId.buffer != OPENGL_INVALID_ID);
2069 pState->ext.glDeleteBuffers(1, &pSurface->oglId.buffer);
2070 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2071 break;
2072
2073 case VMSVGA3D_OGLRESTYPE_TEXTURE:
2074 Assert(pSurface->oglId.texture != OPENGL_INVALID_ID);
2075 glDeleteTextures(1, &pSurface->oglId.texture);
2076 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2077 if (pSurface->fEmulated)
2078 {
2079 if (pSurface->idEmulated)
2080 {
2081 glDeleteTextures(1, &pSurface->idEmulated);
2082 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2083 }
2084 }
2085 else
2086 {
2087 Assert(!pSurface->idEmulated);
2088 }
2089 break;
2090
2091 case VMSVGA3D_OGLRESTYPE_RENDERBUFFER:
2092 Assert(pSurface->oglId.renderbuffer != OPENGL_INVALID_ID);
2093 pState->ext.glDeleteRenderbuffers(1, &pSurface->oglId.renderbuffer);
2094 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2095 break;
2096
2097 default:
2098 AssertMsg(!VMSVGA3DSURFACE_HAS_HW_SURFACE(pSurface),
2099 ("hint=%#x, type=%d\n",
2100 (pSurface->f.s.surface1Flags & VMSVGA3D_SURFACE_HINT_SWITCH_MASK), pSurface->enmOGLResType));
2101 break;
2102 }
2103}
2104
2105
2106static DECLCALLBACK(void) vmsvga3dBackSurfaceInvalidateImage(PVGASTATECC pThisCC, PVMSVGA3DSURFACE pSurface, uint32_t uFace, uint32_t uMipmap)
2107{
2108 RT_NOREF(pThisCC, pSurface, uFace, uMipmap);
2109}
2110
2111
2112static DECLCALLBACK(int) vmsvga3dBackSurfaceCopy(PVGASTATECC pThisCC, SVGA3dSurfaceImageId dest, SVGA3dSurfaceImageId src,
2113 uint32_t cCopyBoxes, SVGA3dCopyBox *pBox)
2114{
2115 int rc;
2116
2117 LogFunc(("Copy %d boxes from sid=%u face=%u mipmap=%u to sid=%u face=%u mipmap=%u\n",
2118 cCopyBoxes, src.sid, src.face, src.mipmap, dest.sid, dest.face, dest.mipmap));
2119
2120 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
2121 AssertReturn(pState, VERR_INVALID_STATE);
2122
2123 PVMSVGA3DSURFACE pSurfaceSrc;
2124 rc = vmsvga3dSurfaceFromSid(pState, src.sid, &pSurfaceSrc);
2125 AssertRCReturn(rc, rc);
2126
2127 PVMSVGA3DSURFACE pSurfaceDst;
2128 rc = vmsvga3dSurfaceFromSid(pState, dest.sid, &pSurfaceDst);
2129 AssertRCReturn(rc, rc);
2130
2131 if (!VMSVGA3DSURFACE_HAS_HW_SURFACE(pSurfaceSrc))
2132 {
2133 /* The source surface is still in memory. */
2134 PVMSVGA3DMIPMAPLEVEL pMipmapLevelSrc;
2135 rc = vmsvga3dMipmapLevel(pSurfaceSrc, src.face, src.mipmap, &pMipmapLevelSrc);
2136 AssertRCReturn(rc, rc);
2137
2138 PVMSVGA3DMIPMAPLEVEL pMipmapLevelDst;
2139 rc = vmsvga3dMipmapLevel(pSurfaceDst, dest.face, dest.mipmap, &pMipmapLevelDst);
2140 AssertRCReturn(rc, rc);
2141
2142 /* The copy operation is performed on the shared context. */
2143 PVMSVGA3DCONTEXT pContext = &pState->SharedCtx;
2144 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
2145
2146 /* Use glTexSubImage to upload the data to the destination texture.
2147 * The latter must be an OpenGL texture.
2148 */
2149 if (!VMSVGA3DSURFACE_HAS_HW_SURFACE(pSurfaceDst))
2150 {
2151 LogFunc(("dest sid=%u type=0x%x format=%d -> create texture\n", dest.sid, pSurfaceDst->f.s.surface1Flags, pSurfaceDst->format));
2152 rc = vmsvga3dBackCreateTexture(pThisCC, pContext, pContext->id, pSurfaceDst);
2153 AssertRCReturn(rc, rc);
2154 }
2155
2156 GLenum target;
2157 if (pSurfaceDst->targetGL == GL_TEXTURE_CUBE_MAP)
2158 target = vmsvga3dCubemapFaceFromIndex(dest.face);
2159 else
2160 {
2161 AssertMsg(pSurfaceDst->targetGL == GL_TEXTURE_2D, ("Test %#x\n", pSurfaceDst->targetGL));
2162 target = pSurfaceDst->targetGL;
2163 }
2164
2165 /* Save the unpacking parameters and set what we need here. */
2166 VMSVGAPACKPARAMS SavedParams;
2167 vmsvga3dOglSetUnpackParams(pState, pContext,
2168 pMipmapLevelSrc->mipmapSize.width,
2169 target == GL_TEXTURE_3D ? pMipmapLevelSrc->mipmapSize.height : 0,
2170 &SavedParams);
2171
2172 glBindTexture(pSurfaceDst->targetGL, pSurfaceDst->oglId.texture);
2173 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2174
2175 for (uint32_t i = 0; i < cCopyBoxes; ++i)
2176 {
2177 SVGA3dCopyBox clipBox = pBox[i];
2178 vmsvgaR3ClipCopyBox(&pMipmapLevelSrc->mipmapSize, &pMipmapLevelDst->mipmapSize, &clipBox);
2179 if ( !clipBox.w
2180 || !clipBox.h
2181 || !clipBox.d)
2182 {
2183 LogFunc(("Skipped empty box.\n"));
2184 continue;
2185 }
2186
2187 LogFunc(("copy box %d,%d,%d %dx%d to %d,%d,%d\n",
2188 clipBox.srcx, clipBox.srcy, clipBox.srcz, clipBox.w, clipBox.h, clipBox.x, clipBox.y, clipBox.z));
2189
2190 uint32_t const u32BlockX = clipBox.srcx / pSurfaceSrc->cxBlock;
2191 uint32_t const u32BlockY = clipBox.srcy / pSurfaceSrc->cyBlock;
2192 uint32_t const u32BlockZ = clipBox.srcz;
2193 Assert(u32BlockX * pSurfaceSrc->cxBlock == clipBox.srcx);
2194 Assert(u32BlockY * pSurfaceSrc->cyBlock == clipBox.srcy);
2195
2196 uint8_t const *pSrcBits = (uint8_t *)pMipmapLevelSrc->pSurfaceData
2197 + pMipmapLevelSrc->cbSurfacePlane * u32BlockZ
2198 + pMipmapLevelSrc->cbSurfacePitch * u32BlockY
2199 + pSurfaceSrc->cbBlock * u32BlockX;
2200
2201 if (target == GL_TEXTURE_3D)
2202 {
2203 if ( pSurfaceDst->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
2204 || pSurfaceDst->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
2205 || pSurfaceDst->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
2206 {
2207 uint32_t const cBlocksX = (clipBox.w + pSurfaceSrc->cxBlock - 1) / pSurfaceSrc->cxBlock;
2208 uint32_t const cBlocksY = (clipBox.h + pSurfaceSrc->cyBlock - 1) / pSurfaceSrc->cyBlock;
2209 uint32_t const imageSize = cBlocksX * cBlocksY * clipBox.d * pSurfaceSrc->cbBlock;
2210 pState->ext.glCompressedTexSubImage3D(target, dest.mipmap,
2211 clipBox.x, clipBox.y, clipBox.z,
2212 clipBox.w, clipBox.h, clipBox.d,
2213 pSurfaceSrc->internalFormatGL, (GLsizei)imageSize, pSrcBits);
2214 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2215 }
2216 else
2217 {
2218 pState->ext.glTexSubImage3D(target, dest.mipmap,
2219 clipBox.x, clipBox.y, clipBox.z,
2220 clipBox.w, clipBox.h, clipBox.d,
2221 pSurfaceSrc->formatGL, pSurfaceSrc->typeGL, pSrcBits);
2222 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2223 }
2224 }
2225 else
2226 {
2227 if ( pSurfaceDst->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
2228 || pSurfaceDst->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
2229 || pSurfaceDst->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
2230 {
2231 uint32_t const cBlocksX = (clipBox.w + pSurfaceSrc->cxBlock - 1) / pSurfaceSrc->cxBlock;
2232 uint32_t const cBlocksY = (clipBox.h + pSurfaceSrc->cyBlock - 1) / pSurfaceSrc->cyBlock;
2233 uint32_t const imageSize = cBlocksX * cBlocksY * pSurfaceSrc->cbBlock;
2234 pState->ext.glCompressedTexSubImage2D(target, dest.mipmap,
2235 clipBox.x, clipBox.y, clipBox.w, clipBox.h,
2236 pSurfaceSrc->internalFormatGL, (GLsizei)imageSize, pSrcBits);
2237 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2238 }
2239 else
2240 {
2241 glTexSubImage2D(target, dest.mipmap,
2242 clipBox.x, clipBox.y, clipBox.w, clipBox.h,
2243 pSurfaceSrc->formatGL, pSurfaceSrc->typeGL, pSrcBits);
2244 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2245 }
2246 }
2247 }
2248
2249 glBindTexture(pSurfaceDst->targetGL, 0);
2250 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2251
2252 vmsvga3dOglRestoreUnpackParams(pState, pContext, &SavedParams);
2253
2254 return VINF_SUCCESS;
2255 }
2256
2257 PVGASTATE pThis = PDMDEVINS_2_DATA(pThisCC->pDevIns, PVGASTATE);
2258 for (uint32_t i = 0; i < cCopyBoxes; i++)
2259 {
2260 SVGA3dBox destBox, srcBox;
2261
2262 srcBox.x = pBox[i].srcx;
2263 srcBox.y = pBox[i].srcy;
2264 srcBox.z = pBox[i].srcz;
2265 srcBox.w = pBox[i].w;
2266 srcBox.h = pBox[i].h;
2267 srcBox.d = pBox[i].d;
2268
2269 destBox.x = pBox[i].x;
2270 destBox.y = pBox[i].y;
2271 destBox.z = pBox[i].z;
2272 destBox.w = pBox[i].w;
2273 destBox.h = pBox[i].h;
2274 destBox.d = pBox[i].d;
2275
2276 /* No stretching is required, therefore use SVGA3D_STRETCH_BLT_POINT which translated to GL_NEAREST. */
2277 rc = vmsvga3dSurfaceStretchBlt(pThis, pThisCC, &dest, &destBox, &src, &srcBox, SVGA3D_STRETCH_BLT_POINT);
2278 AssertRCReturn(rc, rc);
2279 }
2280 return VINF_SUCCESS;
2281}
2282
2283
2284/**
2285 * Saves texture unpacking parameters and loads the specified ones.
2286 *
2287 * @param pState The VMSVGA3D state structure.
2288 * @param pContext The active context.
2289 * @param cxRow The number of pixels in a row. 0 for the entire width.
2290 * @param cyImage The height of the image in pixels. 0 for the entire height.
2291 * @param pSave Where to save stuff.
2292 */
2293void vmsvga3dOglSetUnpackParams(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext, GLint cxRow, GLint cyImage,
2294 PVMSVGAPACKPARAMS pSave)
2295{
2296 RT_NOREF(pState);
2297
2298 /*
2299 * Save (ignore errors, setting the defaults we want and avoids restore).
2300 */
2301 pSave->iAlignment = 1;
2302 VMSVGA3D_ASSERT_GL_CALL(glGetIntegerv(GL_UNPACK_ALIGNMENT, &pSave->iAlignment), pState, pContext);
2303 pSave->cxRow = 0;
2304 VMSVGA3D_ASSERT_GL_CALL(glGetIntegerv(GL_UNPACK_ROW_LENGTH, &pSave->cxRow), pState, pContext);
2305 pSave->cyImage = 0;
2306 VMSVGA3D_ASSERT_GL_CALL(glGetIntegerv(GL_UNPACK_IMAGE_HEIGHT, &pSave->cyImage), pState, pContext);
2307
2308#ifdef VMSVGA3D_PARANOID_TEXTURE_PACKING
2309 pSave->fSwapBytes = GL_FALSE;
2310 glGetBooleanv(GL_UNPACK_SWAP_BYTES, &pSave->fSwapBytes);
2311 Assert(pSave->fSwapBytes == GL_FALSE);
2312
2313 pSave->fLsbFirst = GL_FALSE;
2314 glGetBooleanv(GL_UNPACK_LSB_FIRST, &pSave->fLsbFirst);
2315 Assert(pSave->fLsbFirst == GL_FALSE);
2316
2317 pSave->cSkipRows = 0;
2318 glGetIntegerv(GL_UNPACK_SKIP_ROWS, &pSave->cSkipRows);
2319 Assert(pSave->cSkipRows == 0);
2320
2321 pSave->cSkipPixels = 0;
2322 glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &pSave->cSkipPixels);
2323 Assert(pSave->cSkipPixels == 0);
2324
2325 pSave->cSkipImages = 0;
2326 glGetIntegerv(GL_UNPACK_SKIP_IMAGES, &pSave->cSkipImages);
2327 Assert(pSave->cSkipImages == 0);
2328
2329 VMSVGA3D_CLEAR_GL_ERRORS();
2330#endif
2331
2332 /*
2333 * Setup unpack.
2334 *
2335 * Note! We use 1 as alignment here because we currently don't do any
2336 * aligning of line pitches anywhere.
2337 */
2338 pSave->fChanged = 0;
2339 if (pSave->iAlignment != 1)
2340 {
2341 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_ALIGNMENT, 1), pState, pContext);
2342 pSave->fChanged |= VMSVGAPACKPARAMS_ALIGNMENT;
2343 }
2344 if (pSave->cxRow != cxRow)
2345 {
2346 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, cxRow), pState, pContext);
2347 pSave->fChanged |= VMSVGAPACKPARAMS_ROW_LENGTH;
2348 }
2349 if (pSave->cyImage != cyImage)
2350 {
2351 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, cyImage), pState, pContext);
2352 pSave->fChanged |= VMSVGAPACKPARAMS_IMAGE_HEIGHT;
2353 }
2354#ifdef VMSVGA3D_PARANOID_TEXTURE_PACKING
2355 if (pSave->fSwapBytes != 0)
2356 {
2357 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE), pState, pContext);
2358 pSave->fChanged |= VMSVGAPACKPARAMS_SWAP_BYTES;
2359 }
2360 if (pSave->fLsbFirst != 0)
2361 {
2362 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE), pState, pContext);
2363 pSave->fChanged |= VMSVGAPACKPARAMS_LSB_FIRST;
2364 }
2365 if (pSave->cSkipRows != 0)
2366 {
2367 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SKIP_ROWS, 0), pState, pContext);
2368 pSave->fChanged |= VMSVGAPACKPARAMS_SKIP_ROWS;
2369 }
2370 if (pSave->cSkipPixels != 0)
2371 {
2372 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0), pState, pContext);
2373 pSave->fChanged |= VMSVGAPACKPARAMS_SKIP_PIXELS;
2374 }
2375 if (pSave->cSkipImages != 0)
2376 {
2377 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SKIP_IMAGES, 0), pState, pContext);
2378 pSave->fChanged |= VMSVGAPACKPARAMS_SKIP_IMAGES;
2379 }
2380#endif
2381}
2382
2383
2384/**
2385 * Restores texture unpacking parameters.
2386 *
2387 * @param pState The VMSVGA3D state structure.
2388 * @param pContext The active context.
2389 * @param pSave Where stuff was saved.
2390 */
2391void vmsvga3dOglRestoreUnpackParams(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext,
2392 PCVMSVGAPACKPARAMS pSave)
2393{
2394 RT_NOREF(pState);
2395
2396 if (pSave->fChanged & VMSVGAPACKPARAMS_ALIGNMENT)
2397 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_ALIGNMENT, pSave->iAlignment), pState, pContext);
2398 if (pSave->fChanged & VMSVGAPACKPARAMS_ROW_LENGTH)
2399 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, pSave->cxRow), pState, pContext);
2400 if (pSave->fChanged & VMSVGAPACKPARAMS_IMAGE_HEIGHT)
2401 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, pSave->cyImage), pState, pContext);
2402#ifdef VMSVGA3D_PARANOID_TEXTURE_PACKING
2403 if (pSave->fChanged & VMSVGAPACKPARAMS_SWAP_BYTES)
2404 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SWAP_BYTES, pSave->fSwapBytes), pState, pContext);
2405 if (pSave->fChanged & VMSVGAPACKPARAMS_LSB_FIRST)
2406 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_LSB_FIRST, pSave->fLsbFirst), pState, pContext);
2407 if (pSave->fChanged & VMSVGAPACKPARAMS_SKIP_ROWS)
2408 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SKIP_ROWS, pSave->cSkipRows), pState, pContext);
2409 if (pSave->fChanged & VMSVGAPACKPARAMS_SKIP_PIXELS)
2410 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SKIP_PIXELS, pSave->cSkipPixels), pState, pContext);
2411 if (pSave->fChanged & VMSVGAPACKPARAMS_SKIP_IMAGES)
2412 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SKIP_IMAGES, pSave->cSkipImages), pState, pContext);
2413#endif
2414}
2415
2416/**
2417 * Create D3D/OpenGL texture object for the specified surface.
2418 *
2419 * Surfaces are created when needed.
2420 *
2421 * @param pThisCC The device context.
2422 * @param pContext The context.
2423 * @param idAssociatedContext Probably the same as pContext->id.
2424 * @param pSurface The surface to create the texture for.
2425 */
2426static DECLCALLBACK(int) vmsvga3dBackCreateTexture(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t idAssociatedContext,
2427 PVMSVGA3DSURFACE pSurface)
2428{
2429 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
2430
2431 RT_NOREF(idAssociatedContext);
2432
2433 LogFunc(("sid=%u\n", pSurface->id));
2434
2435 uint32_t const numMipLevels = pSurface->cLevels;
2436
2437 /* Fugure out what kind of texture we are creating. */
2438 GLenum binding;
2439 GLenum target;
2440 if (pSurface->f.s.surface1Flags & SVGA3D_SURFACE_CUBEMAP)
2441 {
2442 Assert(pSurface->cFaces == 6);
2443
2444 binding = GL_TEXTURE_BINDING_CUBE_MAP;
2445 target = GL_TEXTURE_CUBE_MAP;
2446 }
2447 else
2448 {
2449 if (pSurface->paMipmapLevels[0].mipmapSize.depth > 1)
2450 {
2451 binding = GL_TEXTURE_BINDING_3D;
2452 target = GL_TEXTURE_3D;
2453 }
2454 else
2455 {
2456 Assert(pSurface->cFaces == 1);
2457
2458 binding = GL_TEXTURE_BINDING_2D;
2459 target = GL_TEXTURE_2D;
2460 }
2461 }
2462
2463 /* All textures are created in the SharedCtx. */
2464 uint32_t idPrevCtx = pState->idActiveContext;
2465 pContext = &pState->SharedCtx;
2466 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
2467
2468 glGenTextures(1, &pSurface->oglId.texture);
2469 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2470 if (pSurface->fEmulated)
2471 {
2472 glGenTextures(1, &pSurface->idEmulated);
2473 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2474 }
2475 pSurface->enmOGLResType = VMSVGA3D_OGLRESTYPE_TEXTURE;
2476
2477 GLint activeTexture = 0;
2478 glGetIntegerv(binding, &activeTexture);
2479 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2480
2481 /* Must bind texture to the current context in order to change it. */
2482 glBindTexture(target, pSurface->oglId.texture);
2483 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2484
2485 /* Set the unpacking parameters. */
2486 VMSVGAPACKPARAMS SavedParams;
2487 vmsvga3dOglSetUnpackParams(pState, pContext, 0, 0, &SavedParams);
2488
2489 /** @todo Set the mip map generation filter settings. */
2490
2491 /* Set the mipmap base and max level parameters. */
2492 glTexParameteri(target, GL_TEXTURE_BASE_LEVEL, 0);
2493 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2494 glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, pSurface->cLevels - 1);
2495 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2496
2497 if (pSurface->fDirty)
2498 LogFunc(("sync dirty texture\n"));
2499
2500 /* Always allocate and initialize all mipmap levels; non-initialized mipmap levels used as render targets cause failures. */
2501 if (target == GL_TEXTURE_3D)
2502 {
2503 for (uint32_t i = 0; i < numMipLevels; ++i)
2504 {
2505 /* Allocate and initialize texture memory. Passing the zero filled pSurfaceData avoids
2506 * exposing random host memory to the guest and helps a with the fedora 21 surface
2507 * corruption issues (launchpad, background, search field, login).
2508 */
2509 PVMSVGA3DMIPMAPLEVEL pMipLevel = &pSurface->paMipmapLevels[i];
2510
2511 LogFunc(("sync dirty 3D texture mipmap level %d (pitch %x) (dirty %d)\n",
2512 i, pMipLevel->cbSurfacePitch, pMipLevel->fDirty));
2513
2514 if ( pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
2515 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
2516 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
2517 {
2518 pState->ext.glCompressedTexImage3D(GL_TEXTURE_3D,
2519 i,
2520 pSurface->internalFormatGL,
2521 pMipLevel->mipmapSize.width,
2522 pMipLevel->mipmapSize.height,
2523 pMipLevel->mipmapSize.depth,
2524 0,
2525 pMipLevel->cbSurface,
2526 pMipLevel->pSurfaceData);
2527 }
2528 else
2529 {
2530 pState->ext.glTexImage3D(GL_TEXTURE_3D,
2531 i,
2532 pSurface->internalFormatGL,
2533 pMipLevel->mipmapSize.width,
2534 pMipLevel->mipmapSize.height,
2535 pMipLevel->mipmapSize.depth,
2536 0, /* border */
2537 pSurface->formatGL,
2538 pSurface->typeGL,
2539 pMipLevel->pSurfaceData);
2540 }
2541 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2542
2543 pMipLevel->fDirty = false;
2544 }
2545 }
2546 else if (target == GL_TEXTURE_CUBE_MAP)
2547 {
2548 for (uint32_t iFace = 0; iFace < 6; ++iFace)
2549 {
2550 GLenum const Face = vmsvga3dCubemapFaceFromIndex(iFace);
2551
2552 for (uint32_t i = 0; i < numMipLevels; ++i)
2553 {
2554 PVMSVGA3DMIPMAPLEVEL pMipLevel = &pSurface->paMipmapLevels[iFace * numMipLevels + i];
2555 Assert(pMipLevel->mipmapSize.width == pMipLevel->mipmapSize.height);
2556 Assert(pMipLevel->mipmapSize.depth == 1);
2557
2558 LogFunc(("sync cube texture face %d mipmap level %d (dirty %d)\n",
2559 iFace, i, pMipLevel->fDirty));
2560
2561 if ( pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
2562 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
2563 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
2564 {
2565 pState->ext.glCompressedTexImage2D(Face,
2566 i,
2567 pSurface->internalFormatGL,
2568 pMipLevel->mipmapSize.width,
2569 pMipLevel->mipmapSize.height,
2570 0,
2571 pMipLevel->cbSurface,
2572 pMipLevel->pSurfaceData);
2573 }
2574 else
2575 {
2576 glTexImage2D(Face,
2577 i,
2578 pSurface->internalFormatGL,
2579 pMipLevel->mipmapSize.width,
2580 pMipLevel->mipmapSize.height,
2581 0,
2582 pSurface->formatGL,
2583 pSurface->typeGL,
2584 pMipLevel->pSurfaceData);
2585 }
2586 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2587
2588 pMipLevel->fDirty = false;
2589 }
2590 }
2591 }
2592 else if (target == GL_TEXTURE_2D)
2593 {
2594 for (uint32_t i = 0; i < numMipLevels; ++i)
2595 {
2596 /* Allocate and initialize texture memory. Passing the zero filled pSurfaceData avoids
2597 * exposing random host memory to the guest and helps a with the fedora 21 surface
2598 * corruption issues (launchpad, background, search field, login).
2599 */
2600 PVMSVGA3DMIPMAPLEVEL pMipLevel = &pSurface->paMipmapLevels[i];
2601 Assert(pMipLevel->mipmapSize.depth == 1);
2602
2603 LogFunc(("sync dirty texture mipmap level %d (pitch %x) (dirty %d)\n",
2604 i, pMipLevel->cbSurfacePitch, pMipLevel->fDirty));
2605
2606 if ( pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
2607 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
2608 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
2609 {
2610 pState->ext.glCompressedTexImage2D(GL_TEXTURE_2D,
2611 i,
2612 pSurface->internalFormatGL,
2613 pMipLevel->mipmapSize.width,
2614 pMipLevel->mipmapSize.height,
2615 0,
2616 pMipLevel->cbSurface,
2617 pMipLevel->pSurfaceData);
2618 }
2619 else
2620 {
2621 glTexImage2D(GL_TEXTURE_2D,
2622 i,
2623 pSurface->internalFormatGL,
2624 pMipLevel->mipmapSize.width,
2625 pMipLevel->mipmapSize.height,
2626 0,
2627 pSurface->formatGL,
2628 pSurface->typeGL,
2629 NULL);
2630 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2631
2632 if (pSurface->fEmulated)
2633 {
2634 /* Bind the emulated texture and init it. */
2635 glBindTexture(GL_TEXTURE_2D, pSurface->idEmulated);
2636 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2637
2638 glTexImage2D(GL_TEXTURE_2D,
2639 i,
2640 pSurface->internalFormatGL,
2641 pMipLevel->mipmapSize.width,
2642 pMipLevel->mipmapSize.height,
2643 0,
2644 pSurface->formatGL,
2645 pSurface->typeGL,
2646 NULL);
2647 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2648 }
2649
2650 /* Fetch texture data: either to the actual or to the emulated texture.
2651 * The pSurfaceData buffer may be smaller than the entire texture
2652 * for emulated formats, in which case only part of the texture is synched.
2653 */
2654 uint32_t cBlocksX = pMipLevel->mipmapSize.width / pSurface->cxBlock;
2655 uint32_t cBlocksY = pMipLevel->mipmapSize.height / pSurface->cyBlock;
2656 glTexSubImage2D(GL_TEXTURE_2D,
2657 i,
2658 0,
2659 0,
2660 cBlocksX,
2661 cBlocksY,
2662 pSurface->formatGL,
2663 pSurface->typeGL,
2664 pMipLevel->pSurfaceData);
2665 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2666
2667 if (pSurface->fEmulated)
2668 {
2669 /* Update the actual texture using the format converter. */
2670 FormatConvUpdateTexture(pState, pContext, pSurface, i);
2671
2672 /* Rebind the actual texture. */
2673 glBindTexture(GL_TEXTURE_2D, pSurface->oglId.texture);
2674 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2675 }
2676 }
2677 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2678
2679 pMipLevel->fDirty = false;
2680 }
2681 }
2682
2683 pSurface->fDirty = false;
2684
2685 /* Restore unpacking parameters. */
2686 vmsvga3dOglRestoreUnpackParams(pState, pContext, &SavedParams);
2687
2688 /* Restore the old active texture. */
2689 glBindTexture(target, activeTexture);
2690 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2691
2692 pSurface->f.s.surface1Flags |= SVGA3D_SURFACE_HINT_TEXTURE;
2693 pSurface->targetGL = target;
2694 pSurface->bindingGL = binding;
2695
2696 if (idPrevCtx < pState->cContexts && pState->papContexts[idPrevCtx]->id == idPrevCtx)
2697 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pState->papContexts[idPrevCtx]);
2698 return VINF_SUCCESS;
2699}
2700
2701
2702/**
2703 * Backend worker for implementing SVGA_3D_CMD_SURFACE_STRETCHBLT.
2704 *
2705 * @returns VBox status code.
2706 * @param pThis The VGA device instance.
2707 * @param pState The VMSVGA3d state.
2708 * @param pDstSurface The destination host surface.
2709 * @param uDstFace The destination face (valid).
2710 * @param uDstMipmap The destination mipmap level (valid).
2711 * @param pDstBox The destination box.
2712 * @param pSrcSurface The source host surface.
2713 * @param uSrcFace The destination face (valid).
2714 * @param uSrcMipmap The source mimap level (valid).
2715 * @param pSrcBox The source box.
2716 * @param enmMode The strecht blt mode .
2717 * @param pContext The VMSVGA3d context (already current for OGL).
2718 */
2719static DECLCALLBACK(int) vmsvga3dBackSurfaceStretchBlt(PVGASTATE pThis, PVMSVGA3DSTATE pState,
2720 PVMSVGA3DSURFACE pDstSurface, uint32_t uDstFace, uint32_t uDstMipmap, SVGA3dBox const *pDstBox,
2721 PVMSVGA3DSURFACE pSrcSurface, uint32_t uSrcFace, uint32_t uSrcMipmap, SVGA3dBox const *pSrcBox,
2722 SVGA3dStretchBltMode enmMode, PVMSVGA3DCONTEXT pContext)
2723{
2724 RT_NOREF(pThis);
2725
2726 AssertReturn( RT_BOOL(pSrcSurface->f.s.surface1Flags & SVGA3D_SURFACE_HINT_DEPTHSTENCIL)
2727 == RT_BOOL(pDstSurface->f.s.surface1Flags & SVGA3D_SURFACE_HINT_DEPTHSTENCIL), VERR_NOT_IMPLEMENTED);
2728
2729 GLenum glAttachment = GL_COLOR_ATTACHMENT0;
2730 GLbitfield glMask = GL_COLOR_BUFFER_BIT;
2731 if (pDstSurface->f.s.surface1Flags & SVGA3D_SURFACE_HINT_DEPTHSTENCIL)
2732 {
2733 /** @todo Need GL_DEPTH_STENCIL_ATTACHMENT for depth/stencil formats? */
2734 glAttachment = GL_DEPTH_ATTACHMENT;
2735 glMask = GL_DEPTH_BUFFER_BIT;
2736 }
2737
2738 /* Activate the read and draw framebuffer objects. */
2739 pState->ext.glBindFramebuffer(GL_READ_FRAMEBUFFER, pContext->idReadFramebuffer);
2740 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2741 pState->ext.glBindFramebuffer(GL_DRAW_FRAMEBUFFER, pContext->idDrawFramebuffer);
2742 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2743
2744 /* Bind the source and destination objects to the right place. */
2745 GLenum textarget;
2746 if (pSrcSurface->targetGL == GL_TEXTURE_CUBE_MAP)
2747 textarget = vmsvga3dCubemapFaceFromIndex(uSrcFace);
2748 else
2749 {
2750 /// @todo later AssertMsg(pSrcSurface->targetGL == GL_TEXTURE_2D, ("%#x\n", pSrcSurface->targetGL));
2751 textarget = GL_TEXTURE_2D;
2752 }
2753 pState->ext.glFramebufferTexture2D(GL_READ_FRAMEBUFFER, glAttachment, textarget,
2754 pSrcSurface->oglId.texture, uSrcMipmap);
2755 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2756
2757 if (pDstSurface->targetGL == GL_TEXTURE_CUBE_MAP)
2758 textarget = vmsvga3dCubemapFaceFromIndex(uDstFace);
2759 else
2760 {
2761 /// @todo later AssertMsg(pDstSurface->targetGL == GL_TEXTURE_2D, ("%#x\n", pDstSurface->targetGL));
2762 textarget = GL_TEXTURE_2D;
2763 }
2764 pState->ext.glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, glAttachment, textarget,
2765 pDstSurface->oglId.texture, uDstMipmap);
2766 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2767
2768 Log(("src conv. (%d,%d)(%d,%d); dest conv (%d,%d)(%d,%d)\n",
2769 pSrcBox->x, D3D_TO_OGL_Y_COORD(pSrcSurface, pSrcBox->y + pSrcBox->h),
2770 pSrcBox->x + pSrcBox->w, D3D_TO_OGL_Y_COORD(pSrcSurface, pSrcBox->y),
2771 pDstBox->x, D3D_TO_OGL_Y_COORD(pDstSurface, pDstBox->y + pDstBox->h),
2772 pDstBox->x + pDstBox->w, D3D_TO_OGL_Y_COORD(pDstSurface, pDstBox->y)));
2773
2774 pState->ext.glBlitFramebuffer(pSrcBox->x,
2775 pSrcBox->y,
2776 pSrcBox->x + pSrcBox->w, /* exclusive. */
2777 pSrcBox->y + pSrcBox->h,
2778 pDstBox->x,
2779 pDstBox->y,
2780 pDstBox->x + pDstBox->w, /* exclusive. */
2781 pDstBox->y + pDstBox->h,
2782 glMask,
2783 (enmMode == SVGA3D_STRETCH_BLT_POINT) ? GL_NEAREST : GL_LINEAR);
2784 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2785
2786 /* Reset the frame buffer association */
2787 pState->ext.glBindFramebuffer(GL_FRAMEBUFFER, pContext->idFramebuffer);
2788 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2789
2790 return VINF_SUCCESS;
2791}
2792
2793/**
2794 * Save texture packing parameters and loads those appropriate for the given
2795 * surface.
2796 *
2797 * @param pState The VMSVGA3D state structure.
2798 * @param pContext The active context.
2799 * @param pSurface The surface.
2800 * @param pSave Where to save stuff.
2801 */
2802void vmsvga3dOglSetPackParams(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext, PVMSVGA3DSURFACE pSurface,
2803 PVMSVGAPACKPARAMS pSave)
2804{
2805 RT_NOREF(pState);
2806 /*
2807 * Save (ignore errors, setting the defaults we want and avoids restore).
2808 */
2809 pSave->iAlignment = 1;
2810 VMSVGA3D_ASSERT_GL_CALL(glGetIntegerv(GL_PACK_ALIGNMENT, &pSave->iAlignment), pState, pContext);
2811 pSave->cxRow = 0;
2812 VMSVGA3D_ASSERT_GL_CALL(glGetIntegerv(GL_PACK_ROW_LENGTH, &pSave->cxRow), pState, pContext);
2813
2814#ifdef VMSVGA3D_PARANOID_TEXTURE_PACKING
2815 pSave->cyImage = 0;
2816 glGetIntegerv(GL_PACK_IMAGE_HEIGHT, &pSave->cyImage);
2817 Assert(pSave->cyImage == 0);
2818
2819 pSave->fSwapBytes = GL_FALSE;
2820 glGetBooleanv(GL_PACK_SWAP_BYTES, &pSave->fSwapBytes);
2821 Assert(pSave->fSwapBytes == GL_FALSE);
2822
2823 pSave->fLsbFirst = GL_FALSE;
2824 glGetBooleanv(GL_PACK_LSB_FIRST, &pSave->fLsbFirst);
2825 Assert(pSave->fLsbFirst == GL_FALSE);
2826
2827 pSave->cSkipRows = 0;
2828 glGetIntegerv(GL_PACK_SKIP_ROWS, &pSave->cSkipRows);
2829 Assert(pSave->cSkipRows == 0);
2830
2831 pSave->cSkipPixels = 0;
2832 glGetIntegerv(GL_PACK_SKIP_PIXELS, &pSave->cSkipPixels);
2833 Assert(pSave->cSkipPixels == 0);
2834
2835 pSave->cSkipImages = 0;
2836 glGetIntegerv(GL_PACK_SKIP_IMAGES, &pSave->cSkipImages);
2837 Assert(pSave->cSkipImages == 0);
2838
2839 VMSVGA3D_CLEAR_GL_ERRORS();
2840#endif
2841
2842 /*
2843 * Setup unpack.
2844 *
2845 * Note! We use 1 as alignment here because we currently don't do any
2846 * aligning of line pitches anywhere.
2847 */
2848 NOREF(pSurface);
2849 if (pSave->iAlignment != 1)
2850 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_ALIGNMENT, 1), pState, pContext);
2851 if (pSave->cxRow != 0)
2852 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_ROW_LENGTH, 0), pState, pContext);
2853#ifdef VMSVGA3D_PARANOID_TEXTURE_PACKING
2854 if (pSave->cyImage != 0)
2855 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_IMAGE_HEIGHT, 0), pState, pContext);
2856 if (pSave->fSwapBytes != 0)
2857 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SWAP_BYTES, GL_FALSE), pState, pContext);
2858 if (pSave->fLsbFirst != 0)
2859 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_LSB_FIRST, GL_FALSE), pState, pContext);
2860 if (pSave->cSkipRows != 0)
2861 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SKIP_ROWS, 0), pState, pContext);
2862 if (pSave->cSkipPixels != 0)
2863 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SKIP_PIXELS, 0), pState, pContext);
2864 if (pSave->cSkipImages != 0)
2865 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SKIP_IMAGES, 0), pState, pContext);
2866#endif
2867}
2868
2869
2870/**
2871 * Restores texture packing parameters.
2872 *
2873 * @param pState The VMSVGA3D state structure.
2874 * @param pContext The active context.
2875 * @param pSurface The surface.
2876 * @param pSave Where stuff was saved.
2877 */
2878void vmsvga3dOglRestorePackParams(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext, PVMSVGA3DSURFACE pSurface,
2879 PCVMSVGAPACKPARAMS pSave)
2880{
2881 RT_NOREF(pState, pSurface);
2882 if (pSave->iAlignment != 1)
2883 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_ALIGNMENT, pSave->iAlignment), pState, pContext);
2884 if (pSave->cxRow != 0)
2885 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_ROW_LENGTH, pSave->cxRow), pState, pContext);
2886#ifdef VMSVGA3D_PARANOID_TEXTURE_PACKING
2887 if (pSave->cyImage != 0)
2888 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_IMAGE_HEIGHT, pSave->cyImage), pState, pContext);
2889 if (pSave->fSwapBytes != 0)
2890 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SWAP_BYTES, pSave->fSwapBytes), pState, pContext);
2891 if (pSave->fLsbFirst != 0)
2892 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_LSB_FIRST, pSave->fLsbFirst), pState, pContext);
2893 if (pSave->cSkipRows != 0)
2894 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SKIP_ROWS, pSave->cSkipRows), pState, pContext);
2895 if (pSave->cSkipPixels != 0)
2896 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SKIP_PIXELS, pSave->cSkipPixels), pState, pContext);
2897 if (pSave->cSkipImages != 0)
2898 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SKIP_IMAGES, pSave->cSkipImages), pState, pContext);
2899#endif
2900}
2901
2902
2903/**
2904 * Backend worker for implementing SVGA_3D_CMD_SURFACE_DMA that copies one box.
2905 *
2906 * @returns Failure status code or @a rc.
2907 * @param pThis The shared VGA/VMSVGA instance data.
2908 * @param pThisCC The VGA/VMSVGA state for ring-3.
2909 * @param pState The VMSVGA3d state.
2910 * @param pSurface The host surface.
2911 * @param pMipLevel Mipmap level. The caller knows it already.
2912 * @param uHostFace The host face (valid).
2913 * @param uHostMipmap The host mipmap level (valid).
2914 * @param GuestPtr The guest pointer.
2915 * @param cbGuestPitch The guest pitch.
2916 * @param transfer The transfer direction.
2917 * @param pBox The box to copy (clipped, valid, except for guest's srcx, srcy, srcz).
2918 * @param pContext The context (for OpenGL).
2919 * @param rc The current rc for all boxes.
2920 * @param iBox The current box number (for Direct 3D).
2921 */
2922static DECLCALLBACK(int) vmsvga3dBackSurfaceDMACopyBox(PVGASTATE pThis, PVGASTATECC pThisCC, PVMSVGA3DSTATE pState, PVMSVGA3DSURFACE pSurface,
2923 PVMSVGA3DMIPMAPLEVEL pMipLevel, uint32_t uHostFace, uint32_t uHostMipmap,
2924 SVGAGuestPtr GuestPtr, uint32_t cbGuestPitch, SVGA3dTransferType transfer,
2925 SVGA3dCopyBox const *pBox, PVMSVGA3DCONTEXT pContext, int rc, int iBox)
2926{
2927 RT_NOREF(iBox);
2928
2929 switch (pSurface->enmOGLResType)
2930 {
2931 case VMSVGA3D_OGLRESTYPE_TEXTURE:
2932 {
2933 uint32_t cbSurfacePitch;
2934 uint8_t *pDoubleBuffer;
2935 uint64_t offHst;
2936
2937 uint32_t const u32HostBlockX = pBox->x / pSurface->cxBlock;
2938 uint32_t const u32HostBlockY = pBox->y / pSurface->cyBlock;
2939 uint32_t const u32HostZ = pBox->z;
2940 Assert(u32HostBlockX * pSurface->cxBlock == pBox->x);
2941 Assert(u32HostBlockY * pSurface->cyBlock == pBox->y);
2942
2943 uint32_t const u32GuestBlockX = pBox->srcx / pSurface->cxBlock;
2944 uint32_t const u32GuestBlockY = pBox->srcy / pSurface->cyBlock;
2945 uint32_t const u32GuestZ = pBox->srcz / pSurface->cyBlock;
2946 Assert(u32GuestBlockX * pSurface->cxBlock == pBox->srcx);
2947 Assert(u32GuestBlockY * pSurface->cyBlock == pBox->srcy);
2948
2949 uint32_t const cBlocksX = (pBox->w + pSurface->cxBlock - 1) / pSurface->cxBlock;
2950 uint32_t const cBlocksY = (pBox->h + pSurface->cyBlock - 1) / pSurface->cyBlock;
2951 AssertMsgReturn(cBlocksX && cBlocksY, ("Empty box %dx%d\n", pBox->w, pBox->h), VERR_INTERNAL_ERROR);
2952
2953 GLenum texImageTarget;
2954 if (pSurface->targetGL == GL_TEXTURE_3D)
2955 {
2956 texImageTarget = GL_TEXTURE_3D;
2957 }
2958 else if (pSurface->targetGL == GL_TEXTURE_CUBE_MAP)
2959 {
2960 texImageTarget = vmsvga3dCubemapFaceFromIndex(uHostFace);
2961 }
2962 else
2963 {
2964 AssertMsg(pSurface->targetGL == GL_TEXTURE_2D, ("%#x\n", pSurface->targetGL));
2965 texImageTarget = GL_TEXTURE_2D;
2966 }
2967
2968 /* The buffer must be large enough to hold entire texture in the OpenGL format. */
2969 pDoubleBuffer = (uint8_t *)RTMemAlloc(pSurface->cbBlockGL * pMipLevel->cBlocks);
2970 AssertReturn(pDoubleBuffer, VERR_NO_MEMORY);
2971
2972 if (transfer == SVGA3D_READ_HOST_VRAM)
2973 {
2974 /* Read the entire texture to the double buffer. */
2975 GLint activeTexture;
2976
2977 /* Must bind texture to the current context in order to read it. */
2978 glGetIntegerv(pSurface->bindingGL, &activeTexture);
2979 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2980
2981 glBindTexture(pSurface->targetGL, GLTextureId(pSurface));
2982 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2983
2984 if (pSurface->fEmulated)
2985 {
2986 FormatConvReadTexture(pState, pContext, pSurface, uHostMipmap);
2987 }
2988
2989 /* Set row length and alignment of the input data. */
2990 VMSVGAPACKPARAMS SavedParams;
2991 vmsvga3dOglSetPackParams(pState, pContext, pSurface, &SavedParams);
2992
2993 if ( pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
2994 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
2995 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
2996 {
2997 pState->ext.glGetCompressedTexImage(texImageTarget, uHostMipmap, pDoubleBuffer);
2998 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2999 }
3000 else
3001 {
3002 glGetTexImage(texImageTarget, uHostMipmap, pSurface->formatGL, pSurface->typeGL, pDoubleBuffer);
3003 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
3004 }
3005
3006 vmsvga3dOglRestorePackParams(pState, pContext, pSurface, &SavedParams);
3007
3008 /* Restore the old active texture. */
3009 glBindTexture(pSurface->targetGL, activeTexture);
3010 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
3011
3012 offHst = u32HostBlockX * pSurface->cbBlock + u32HostBlockY * pMipLevel->cbSurfacePitch + u32HostZ * pMipLevel->cbSurfacePlane;
3013 cbSurfacePitch = pMipLevel->cbSurfacePitch;
3014 }
3015 else
3016 {
3017 /* The buffer will contain only the copied rectangle. */
3018 offHst = 0;
3019 cbSurfacePitch = cBlocksX * pSurface->cbBlock;
3020 }
3021
3022 uint64_t offGst = u32GuestBlockX * pSurface->cbBlock + u32GuestBlockY * cbGuestPitch + u32GuestZ * cbGuestPitch * pMipLevel->mipmapSize.height;
3023
3024 for (uint32_t iPlane = 0; iPlane < pBox->d; ++iPlane)
3025 {
3026 AssertBreak(offHst < UINT32_MAX);
3027 AssertBreak(offGst < UINT32_MAX);
3028
3029 rc = vmsvgaR3GmrTransfer(pThis,
3030 pThisCC,
3031 transfer,
3032 pDoubleBuffer,
3033 pMipLevel->cbSurface,
3034 (uint32_t)offHst,
3035 cbSurfacePitch,
3036 GuestPtr,
3037 (uint32_t)offGst,
3038 cbGuestPitch,
3039 cBlocksX * pSurface->cbBlock,
3040 cBlocksY);
3041 AssertRC(rc);
3042
3043 offHst += pMipLevel->cbSurfacePlane;
3044 offGst += pMipLevel->mipmapSize.height * cbGuestPitch;
3045 }
3046
3047 /* Update the opengl surface data. */
3048 if (transfer == SVGA3D_WRITE_HOST_VRAM)
3049 {
3050 GLint activeTexture = 0;
3051 glGetIntegerv(pSurface->bindingGL, &activeTexture);
3052 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
3053
3054 /* Must bind texture to the current context in order to change it. */
3055 glBindTexture(pSurface->targetGL, GLTextureId(pSurface));
3056 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
3057
3058 LogFunc(("copy texture mipmap level %d (pitch %x)\n", uHostMipmap, pMipLevel->cbSurfacePitch));
3059
3060 /* Set row length and alignment of the input data. */
3061 /* We do not need to set ROW_LENGTH to w here, because the image in pDoubleBuffer is tightly packed. */
3062 VMSVGAPACKPARAMS SavedParams;
3063 vmsvga3dOglSetUnpackParams(pState, pContext, 0, 0, &SavedParams);
3064
3065 if (texImageTarget == GL_TEXTURE_3D)
3066 {
3067 if ( pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
3068 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
3069 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
3070 {
3071 pState->ext.glCompressedTexSubImage3D(texImageTarget,
3072 uHostMipmap,
3073 pBox->x,
3074 pBox->y,
3075 pBox->z,
3076 pBox->w,
3077 pBox->h,
3078 pBox->d,
3079 pSurface->internalFormatGL,
3080 cbSurfacePitch * cBlocksY * pBox->d,
3081 pDoubleBuffer);
3082 }
3083 else
3084 {
3085 pState->ext.glTexSubImage3D(texImageTarget,
3086 uHostMipmap,
3087 u32HostBlockX,
3088 u32HostBlockY,
3089 pBox->z,
3090 cBlocksX,
3091 cBlocksY,
3092 pBox->d,
3093 pSurface->formatGL,
3094 pSurface->typeGL,
3095 pDoubleBuffer);
3096 }
3097 }
3098 else
3099 {
3100 if ( pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
3101 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
3102 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
3103 {
3104 pState->ext.glCompressedTexSubImage2D(texImageTarget,
3105 uHostMipmap,
3106 pBox->x,
3107 pBox->y,
3108 pBox->w,
3109 pBox->h,
3110 pSurface->internalFormatGL,
3111 cbSurfacePitch * cBlocksY,
3112 pDoubleBuffer);
3113 }
3114 else
3115 {
3116 glTexSubImage2D(texImageTarget,
3117 uHostMipmap,
3118 u32HostBlockX,
3119 u32HostBlockY,
3120 cBlocksX,
3121 cBlocksY,
3122 pSurface->formatGL,
3123 pSurface->typeGL,
3124 pDoubleBuffer);
3125 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
3126
3127 if (pSurface->fEmulated)
3128 {
3129 /* Convert the texture to the actual texture if necessary */
3130 FormatConvUpdateTexture(pState, pContext, pSurface, uHostMipmap);
3131 }
3132 }
3133 }
3134 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
3135
3136 /* Restore old values. */
3137 vmsvga3dOglRestoreUnpackParams(pState, pContext, &SavedParams);
3138
3139 /* Restore the old active texture. */
3140 glBindTexture(pSurface->targetGL, activeTexture);
3141 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
3142 }
3143
3144 Log4(("first line:\n%.*Rhxd\n", cBlocksX * pSurface->cbBlock, pDoubleBuffer));
3145
3146 /* Free the double buffer. */
3147 RTMemFree(pDoubleBuffer);
3148 break;
3149 }
3150
3151 case VMSVGA3D_OGLRESTYPE_BUFFER:
3152 {
3153 /* Buffers are uncompressed. */
3154 AssertReturn(pSurface->cxBlock == 1 && pSurface->cyBlock == 1, VERR_INTERNAL_ERROR);
3155
3156 /* Caller already clipped pBox and buffers are 1-dimensional. */
3157 Assert(pBox->y == 0 && pBox->h == 1 && pBox->z == 0 && pBox->d == 1);
3158
3159 VMSVGA3D_CLEAR_GL_ERRORS();
3160 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, pSurface->oglId.buffer);
3161 if (VMSVGA3D_GL_IS_SUCCESS(pContext))
3162 {
3163 GLenum enmGlTransfer = (transfer == SVGA3D_READ_HOST_VRAM) ? GL_READ_ONLY : GL_WRITE_ONLY;
3164 uint8_t *pbData = (uint8_t *)pState->ext.glMapBuffer(GL_ARRAY_BUFFER, enmGlTransfer);
3165 if (RT_LIKELY(pbData != NULL))
3166 {
3167#if defined(VBOX_STRICT) && defined(RT_OS_DARWIN)
3168 GLint cbStrictBufSize;
3169 glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &cbStrictBufSize);
3170 Assert(VMSVGA3D_GL_IS_SUCCESS(pContext));
3171 AssertMsg(cbStrictBufSize >= (int32_t)pMipLevel->cbSurface,
3172 ("cbStrictBufSize=%#x cbSurface=%#x pContext->id=%#x\n", (uint32_t)cbStrictBufSize, pMipLevel->cbSurface, pContext->id));
3173#endif
3174 Log(("Lock %s memory for rectangle (%d,%d)(%d,%d)\n",
3175 (pSurface->f.s.surface1Flags & VMSVGA3D_SURFACE_HINT_SWITCH_MASK) == SVGA3D_SURFACE_HINT_VERTEXBUFFER ? "vertex" :
3176 (pSurface->f.s.surface1Flags & VMSVGA3D_SURFACE_HINT_SWITCH_MASK) == SVGA3D_SURFACE_HINT_INDEXBUFFER ? "index" : "buffer",
3177 pBox->x, pBox->y, pBox->x + pBox->w, pBox->y + pBox->h));
3178
3179 /* The caller already copied the data to the pMipLevel->pSurfaceData buffer, see VMSVGA3DSURFACE_NEEDS_DATA. */
3180 uint32_t const offHst = pBox->x * pSurface->cbBlock;
3181 uint32_t const cbWidth = pBox->w * pSurface->cbBlock;
3182
3183 memcpy(pbData + offHst, (uint8_t *)pMipLevel->pSurfaceData + offHst, cbWidth);
3184
3185 Log4(("Buffer updated at [0x%x;0x%x):\n%.*Rhxd\n", offHst, offHst + cbWidth, cbWidth, (uint8_t *)pbData + offHst));
3186
3187 pState->ext.glUnmapBuffer(GL_ARRAY_BUFFER);
3188 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3189 }
3190 else
3191 VMSVGA3D_GL_GET_AND_COMPLAIN(pState, pContext, ("glMapBuffer(GL_ARRAY_BUFFER, %#x) -> NULL\n", enmGlTransfer));
3192 }
3193 else
3194 VMSVGA3D_GL_COMPLAIN(pState, pContext, ("glBindBuffer(GL_ARRAY_BUFFER, %#x)\n", pSurface->oglId.buffer));
3195 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, 0);
3196 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3197 break;
3198 }
3199
3200 default:
3201 AssertFailed();
3202 break;
3203 }
3204
3205 return rc;
3206}
3207
3208static DECLCALLBACK(int) vmsvga3dBackGenerateMipmaps(PVGASTATECC pThisCC, uint32_t sid, SVGA3dTextureFilter filter)
3209{
3210 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3211 PVMSVGA3DSURFACE pSurface;
3212 int rc = VINF_SUCCESS;
3213 PVMSVGA3DCONTEXT pContext;
3214 uint32_t cid;
3215 GLint activeTexture = 0;
3216
3217 AssertReturn(pState, VERR_NO_MEMORY);
3218
3219 rc = vmsvga3dSurfaceFromSid(pState, sid, &pSurface);
3220 AssertRCReturn(rc, rc);
3221
3222 Assert(filter != SVGA3D_TEX_FILTER_FLATCUBIC);
3223 Assert(filter != SVGA3D_TEX_FILTER_GAUSSIANCUBIC);
3224 pSurface->autogenFilter = filter;
3225
3226 LogFunc(("sid=%u filter=%d\n", sid, filter));
3227
3228 cid = SVGA3D_INVALID_ID;
3229 pContext = &pState->SharedCtx;
3230 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
3231
3232 if (pSurface->oglId.texture == OPENGL_INVALID_ID)
3233 {
3234 /* Unknown surface type; turn it into a texture. */
3235 LogFunc(("unknown src surface id=%x type=%d format=%d -> create texture\n", sid, pSurface->f.s.surface1Flags, pSurface->format));
3236 rc = vmsvga3dBackCreateTexture(pThisCC, pContext, cid, pSurface);
3237 AssertRCReturn(rc, rc);
3238 }
3239 else
3240 {
3241 /** @todo new filter */
3242 AssertFailed();
3243 }
3244
3245 glGetIntegerv(pSurface->bindingGL, &activeTexture);
3246 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3247
3248 /* Must bind texture to the current context in order to change it. */
3249 glBindTexture(pSurface->targetGL, pSurface->oglId.texture);
3250 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3251
3252 /* Generate the mip maps. */
3253 pState->ext.glGenerateMipmap(pSurface->targetGL);
3254 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3255
3256 /* Restore the old texture. */
3257 glBindTexture(pSurface->targetGL, activeTexture);
3258 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3259
3260 return VINF_SUCCESS;
3261}
3262
3263
3264#ifdef RT_OS_LINUX
3265/**
3266 * X11 event handling thread.
3267 *
3268 * @returns VINF_SUCCESS (ignored)
3269 * @param hThreadSelf thread handle
3270 * @param pvUser pointer to pState structure
3271 */
3272DECLCALLBACK(int) vmsvga3dXEventThread(RTTHREAD hThreadSelf, void *pvUser)
3273{
3274 RT_NOREF(hThreadSelf);
3275 PVMSVGA3DSTATE pState = (PVMSVGA3DSTATE)pvUser;
3276 while (!pState->bTerminate)
3277 {
3278 while (XPending(pState->display) > 0)
3279 {
3280 XEvent event;
3281 XNextEvent(pState->display, &event);
3282
3283 switch (event.type)
3284 {
3285 default:
3286 break;
3287 }
3288 }
3289 /* sleep for 16ms to not burn too many cycles */
3290 RTThreadSleep(16);
3291 }
3292 return VINF_SUCCESS;
3293}
3294#endif // RT_OS_LINUX
3295
3296
3297/**
3298 * Create a new 3d context
3299 *
3300 * @returns VBox status code.
3301 * @param pThisCC The VGA/VMSVGA state for ring-3.
3302 * @param cid Context id
3303 * @param fFlags VMSVGA3D_DEF_CTX_F_XXX.
3304 */
3305int vmsvga3dContextDefineOgl(PVGASTATECC pThisCC, uint32_t cid, uint32_t fFlags)
3306{
3307 int rc;
3308 PVMSVGA3DCONTEXT pContext;
3309 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3310
3311 AssertReturn(pState, VERR_NO_MEMORY);
3312 AssertReturn( cid < SVGA3D_MAX_CONTEXT_IDS
3313 || (cid == VMSVGA3D_SHARED_CTX_ID && (fFlags & VMSVGA3D_DEF_CTX_F_SHARED_CTX)), VERR_INVALID_PARAMETER);
3314#if !defined(VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE) || !(defined(RT_OS_DARWIN))
3315 AssertReturn(!(fFlags & VMSVGA3D_DEF_CTX_F_OTHER_PROFILE), VERR_INTERNAL_ERROR_3);
3316#endif
3317
3318 Log(("vmsvga3dContextDefine id %x\n", cid));
3319
3320 if (cid == VMSVGA3D_SHARED_CTX_ID)
3321 pContext = &pState->SharedCtx;
3322 else
3323 {
3324 if (cid >= pState->cContexts)
3325 {
3326 /* Grow the array. */
3327 uint32_t cNew = RT_ALIGN(cid + 15, 16);
3328 void *pvNew = RTMemRealloc(pState->papContexts, sizeof(pState->papContexts[0]) * cNew);
3329 AssertReturn(pvNew, VERR_NO_MEMORY);
3330 pState->papContexts = (PVMSVGA3DCONTEXT *)pvNew;
3331 while (pState->cContexts < cNew)
3332 {
3333 pContext = (PVMSVGA3DCONTEXT)RTMemAllocZ(sizeof(*pContext));
3334 AssertReturn(pContext, VERR_NO_MEMORY);
3335 pContext->id = SVGA3D_INVALID_ID;
3336 pState->papContexts[pState->cContexts++] = pContext;
3337 }
3338 }
3339 /* If one already exists with this id, then destroy it now. */
3340 if (pState->papContexts[cid]->id != SVGA3D_INVALID_ID)
3341 vmsvga3dBackContextDestroy(pThisCC, cid);
3342
3343 pContext = pState->papContexts[cid];
3344 }
3345
3346 /*
3347 * Find or create the shared context if needed (necessary for sharing e.g. textures between contexts).
3348 */
3349 PVMSVGA3DCONTEXT pSharedCtx = NULL;
3350 if (!(fFlags & (VMSVGA3D_DEF_CTX_F_INIT | VMSVGA3D_DEF_CTX_F_SHARED_CTX)))
3351 {
3352 pSharedCtx = &pState->SharedCtx;
3353 if (pSharedCtx->id != VMSVGA3D_SHARED_CTX_ID)
3354 {
3355 rc = vmsvga3dContextDefineOgl(pThisCC, VMSVGA3D_SHARED_CTX_ID, VMSVGA3D_DEF_CTX_F_SHARED_CTX);
3356 AssertLogRelRCReturn(rc, rc);
3357
3358 /* Create resources which use the shared context. */
3359 vmsvga3dOnSharedContextDefine(pState);
3360 }
3361 }
3362
3363 /*
3364 * Initialize the context.
3365 */
3366 memset(pContext, 0, sizeof(*pContext));
3367 pContext->id = cid;
3368 for (uint32_t i = 0; i < RT_ELEMENTS(pContext->aSidActiveTextures); i++)
3369 pContext->aSidActiveTextures[i] = SVGA3D_INVALID_ID;
3370
3371 pContext->state.shidVertex = SVGA3D_INVALID_ID;
3372 pContext->state.shidPixel = SVGA3D_INVALID_ID;
3373 pContext->idFramebuffer = OPENGL_INVALID_ID;
3374 pContext->idReadFramebuffer = OPENGL_INVALID_ID;
3375 pContext->idDrawFramebuffer = OPENGL_INVALID_ID;
3376
3377 rc = ShaderContextCreate(&pContext->pShaderContext);
3378 AssertRCReturn(rc, rc);
3379
3380 for (uint32_t i = 0; i < RT_ELEMENTS(pContext->state.aRenderTargets); i++)
3381 pContext->state.aRenderTargets[i] = SVGA3D_INVALID_ID;
3382
3383#ifdef RT_OS_WINDOWS
3384 /* Create a context window with minimal 4x4 size. We will never use the swapchain
3385 * to present the rendered image. Rendered images from the guest will be copied to
3386 * the VMSVGA SCREEN object, which can be either an offscreen render target or
3387 * system memory in the guest VRAM.
3388 */
3389 rc = vmsvga3dContextWindowCreate(pState->hInstance, pState->pWindowThread, pState->WndRequestSem, &pContext->hwnd);
3390 AssertRCReturn(rc, rc);
3391
3392 pContext->hdc = GetDC(pContext->hwnd);
3393 AssertMsgReturn(pContext->hdc, ("GetDC %x failed with %d\n", pContext->hwnd, GetLastError()), VERR_INTERNAL_ERROR);
3394
3395 PIXELFORMATDESCRIPTOR pfd = {
3396 sizeof(PIXELFORMATDESCRIPTOR), /* size of this pfd */
3397 1, /* version number */
3398 PFD_DRAW_TO_WINDOW | /* support window */
3399 PFD_SUPPORT_OPENGL, /* support OpenGL */
3400 PFD_TYPE_RGBA, /* RGBA type */
3401 24, /* 24-bit color depth */
3402 0, 0, 0, 0, 0, 0, /* color bits ignored */
3403 8, /* alpha buffer */
3404 0, /* shift bit ignored */
3405 0, /* no accumulation buffer */
3406 0, 0, 0, 0, /* accum bits ignored */
3407 16, /* set depth buffer */
3408 16, /* set stencil buffer */
3409 0, /* no auxiliary buffer */
3410 PFD_MAIN_PLANE, /* main layer */
3411 0, /* reserved */
3412 0, 0, 0 /* layer masks ignored */
3413 };
3414 int pixelFormat;
3415 BOOL ret;
3416
3417 pixelFormat = ChoosePixelFormat(pContext->hdc, &pfd);
3418 /** @todo is this really necessary?? */
3419 pixelFormat = ChoosePixelFormat(pContext->hdc, &pfd);
3420 AssertMsgReturn(pixelFormat != 0, ("ChoosePixelFormat failed with %d\n", GetLastError()), VERR_INTERNAL_ERROR);
3421
3422 ret = SetPixelFormat(pContext->hdc, pixelFormat, &pfd);
3423 AssertMsgReturn(ret == TRUE, ("SetPixelFormat failed with %d\n", GetLastError()), VERR_INTERNAL_ERROR);
3424
3425 pContext->hglrc = wglCreateContext(pContext->hdc);
3426 AssertMsgReturn(pContext->hglrc, ("wglCreateContext %x failed with %d\n", pContext->hdc, GetLastError()), VERR_INTERNAL_ERROR);
3427
3428 if (pSharedCtx)
3429 {
3430 ret = wglShareLists(pSharedCtx->hglrc, pContext->hglrc);
3431 AssertMsg(ret == TRUE, ("wglShareLists(%p, %p) failed with %d\n", pSharedCtx->hglrc, pContext->hglrc, GetLastError()));
3432 }
3433
3434#elif defined(RT_OS_DARWIN)
3435 pContext->fOtherProfile = RT_BOOL(fFlags & VMSVGA3D_DEF_CTX_F_OTHER_PROFILE);
3436
3437 NativeNSOpenGLContextRef pShareContext = pSharedCtx ? pSharedCtx->cocoaContext : NULL;
3438 vmsvga3dCocoaCreateViewAndContext(&pContext->cocoaView, &pContext->cocoaContext,
3439 NULL,
3440 4, 4,
3441 pShareContext, pContext->fOtherProfile);
3442
3443#else
3444 if (pState->display == NULL)
3445 {
3446 /* get an X display and make sure we have glX 1.3 */
3447 pState->display = XOpenDisplay(0);
3448 AssertLogRelMsgReturn(pState->display, ("XOpenDisplay failed"), VERR_INTERNAL_ERROR);
3449 int glxMajor, glxMinor;
3450 Bool ret = glXQueryVersion(pState->display, &glxMajor, &glxMinor);
3451 AssertLogRelMsgReturn(ret && glxMajor == 1 && glxMinor >= 3, ("glX >=1.3 not present"), VERR_INTERNAL_ERROR);
3452 /* start our X event handling thread */
3453 rc = RTThreadCreate(&pState->pWindowThread, vmsvga3dXEventThread, pState, 0, RTTHREADTYPE_GUI, RTTHREADFLAGS_WAITABLE, "VMSVGA3DXEVENT");
3454 AssertLogRelMsgReturn(RT_SUCCESS(rc), ("Async IO Thread creation for 3d window handling failed rc=%Rrc\n", rc), rc);
3455 }
3456
3457 Window defaultRootWindow = XDefaultRootWindow(pState->display);
3458 /* Create a small 4x4 window required for GL context. */
3459 int attrib[] =
3460 {
3461 GLX_RGBA,
3462 GLX_RED_SIZE, 1,
3463 GLX_GREEN_SIZE, 1,
3464 GLX_BLUE_SIZE, 1,
3465 //GLX_ALPHA_SIZE, 1, this flips the bbos screen
3466 GLX_DOUBLEBUFFER,
3467 None
3468 };
3469 XVisualInfo *vi = glXChooseVisual(pState->display, DefaultScreen(pState->display), attrib);
3470 AssertLogRelMsgReturn(vi, ("glXChooseVisual failed"), VERR_INTERNAL_ERROR);
3471 XSetWindowAttributes swa;
3472 swa.colormap = XCreateColormap(pState->display, defaultRootWindow, vi->visual, AllocNone);
3473 AssertLogRelMsgReturn(swa.colormap, ("XCreateColormap failed"), VERR_INTERNAL_ERROR);
3474 swa.border_pixel = 0;
3475 swa.background_pixel = 0;
3476 swa.event_mask = StructureNotifyMask;
3477 unsigned long flags = CWBorderPixel | CWBackPixel | CWColormap | CWEventMask;
3478 pContext->window = XCreateWindow(pState->display, defaultRootWindow,
3479 0, 0, 4, 4,
3480 0, vi->depth, InputOutput,
3481 vi->visual, flags, &swa);
3482 AssertLogRelMsgReturn(pContext->window, ("XCreateWindow failed"), VERR_INTERNAL_ERROR);
3483
3484 /* The window is hidden by default and never mapped, because we only render offscreen and never present to it. */
3485
3486 GLXContext shareContext = pSharedCtx ? pSharedCtx->glxContext : NULL;
3487 pContext->glxContext = glXCreateContext(pState->display, vi, shareContext, GL_TRUE);
3488 XFree(vi);
3489 AssertLogRelMsgReturn(pContext->glxContext, ("glXCreateContext failed"), VERR_INTERNAL_ERROR);
3490#endif
3491
3492 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
3493
3494 /* NULL during the first PowerOn call. */
3495 if (pState->ext.glGenFramebuffers)
3496 {
3497 /* Create a framebuffer object for this context. */
3498 pState->ext.glGenFramebuffers(1, &pContext->idFramebuffer);
3499 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3500
3501 /* Bind the object to the framebuffer target. */
3502 pState->ext.glBindFramebuffer(GL_FRAMEBUFFER, pContext->idFramebuffer);
3503 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3504
3505 /* Create read and draw framebuffer objects for this context. */
3506 pState->ext.glGenFramebuffers(1, &pContext->idReadFramebuffer);
3507 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3508
3509 pState->ext.glGenFramebuffers(1, &pContext->idDrawFramebuffer);
3510 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3511
3512 }
3513#if 0
3514 /** @todo move to shader lib!!! */
3515 /* Clear the screen */
3516 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
3517
3518 glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
3519 glClearIndex(0);
3520 glClearDepth(1);
3521 glClearStencil(0xffff);
3522 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
3523 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
3524 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
3525 if (pState->ext.glProvokingVertex)
3526 pState->ext.glProvokingVertex(GL_FIRST_VERTEX_CONVENTION);
3527 /** @todo move to shader lib!!! */
3528#endif
3529 return VINF_SUCCESS;
3530}
3531
3532#if defined(RT_OS_LINUX)
3533/*
3534 * HW accelerated graphics output.
3535 */
3536
3537/**
3538 * VMSVGA3d screen data.
3539 *
3540 * Allocated on the heap and pointed to by VMSVGASCREENOBJECT::pHwScreen.
3541 */
3542typedef struct VMSVGAHWSCREEN
3543{
3544 /* OpenGL context, which is used for the screen updates. */
3545 GLXContext glxctx;
3546
3547 /* The overlay window. */
3548 Window xwindow;
3549
3550 /* The RGBA texture which hold the screen content. */
3551 GLuint idScreenTexture;
3552
3553 /* Read and draw framebuffer objects for copying a surface to the screen texture. */
3554 GLuint idReadFramebuffer;
3555 GLuint idDrawFramebuffer;
3556} VMSVGAHWSCREEN;
3557
3558/* Send a notification to the UI. */
3559#if 0 /* Unused */
3560static int vmsvga3dDrvNotifyHwScreen(PVGASTATECC pThisCC, VBOX3D_NOTIFY_TYPE enmNotification,
3561 uint32_t idScreen, Pixmap pixmap, void *pvData, size_t cbData)
3562{
3563 uint8_t au8Buffer[128];
3564 AssertLogRelMsgReturn(cbData <= sizeof(au8Buffer) - sizeof(VBOX3DNOTIFY),
3565 ("cbData %zu", cbData),
3566 VERR_INVALID_PARAMETER);
3567
3568 VBOX3DNOTIFY *p = (VBOX3DNOTIFY *)&au8Buffer[0];
3569 p->enmNotification = enmNotification;
3570 p->iDisplay = idScreen;
3571 p->u32Reserved = 0;
3572 p->cbData = cbData + sizeof(uint64_t);
3573 /* au8Data consists of a 64 bit pixmap handle followed by notification specific data. */
3574 AssertCompile(sizeof(pixmap) <= sizeof(uint64_t));
3575 *(uint64_t *)&p->au8Data[0] = (uint64_t)pixmap;
3576 memcpy(&p->au8Data[sizeof(uint64_t)], pvData, cbData);
3577
3578 int rc = pThisCC->pDrv->pfn3DNotifyProcess(pThisCC->pDrv, p);
3579 return rc;
3580}
3581#endif /* Unused */
3582
3583static void vmsvga3dDrvNotifyHwOverlay(PVGASTATECC pThisCC, VBOX3D_NOTIFY_TYPE enmNotification, uint32_t idScreen)
3584{
3585 uint8_t au8Buffer[128];
3586 VBOX3DNOTIFY *p = (VBOX3DNOTIFY *)&au8Buffer[0];
3587 p->enmNotification = enmNotification;
3588 p->iDisplay = idScreen;
3589 p->u32Reserved = 0;
3590 p->cbData = sizeof(uint64_t);
3591 *(uint64_t *)&p->au8Data[0] = 0;
3592
3593 pThisCC->pDrv->pfn3DNotifyProcess(pThisCC->pDrv, p);
3594}
3595
3596/* Get X Window handle of the UI Framebuffer window. */
3597static int vmsvga3dDrvQueryWindow(PVGASTATECC pThisCC, uint32_t idScreen, Window *pWindow)
3598{
3599 uint8_t au8Buffer[128];
3600 VBOX3DNOTIFY *p = (VBOX3DNOTIFY *)&au8Buffer[0];
3601 p->enmNotification = VBOX3D_NOTIFY_TYPE_HW_OVERLAY_GET_ID;
3602 p->iDisplay = idScreen;
3603 p->u32Reserved = 0;
3604 p->cbData = sizeof(uint64_t);
3605 *(uint64_t *)&p->au8Data[0] = 0;
3606
3607 int rc = pThisCC->pDrv->pfn3DNotifyProcess(pThisCC->pDrv, p);
3608 if (RT_SUCCESS(rc))
3609 {
3610 *pWindow = (Window)*(uint64_t *)&p->au8Data[0];
3611 }
3612 return rc;
3613}
3614
3615static int ctxErrorHandler(Display *dpy, XErrorEvent *ev)
3616{
3617 RT_NOREF(dpy);
3618 LogRel4(("VMSVGA: XError %d\n", (int)ev->error_code));
3619 return 0;
3620}
3621
3622/* Create an overlay X window for the HW accelerated screen. */
3623static int vmsvga3dHwScreenCreate(PVMSVGA3DSTATE pState, Window parentWindow, unsigned int cWidth, unsigned int cHeight, VMSVGAHWSCREEN *p)
3624{
3625 int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctxErrorHandler);
3626
3627 int rc = VINF_SUCCESS;
3628
3629 XWindowAttributes parentAttr;
3630 if (XGetWindowAttributes(pState->display, parentWindow, &parentAttr) == 0)
3631 return VERR_INVALID_PARAMETER;
3632
3633 int const idxParentScreen = XScreenNumberOfScreen(parentAttr.screen);
3634
3635 /*
3636 * Create a new GL context, which will be used for copying to the screen.
3637 */
3638
3639 /* FBConfig attributes for the overlay window. */
3640 static int const aConfigAttribList[] =
3641 {
3642 GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, // Must support GLX windows
3643 GLX_DOUBLEBUFFER, False, // Double buffering had a much lower performance.
3644 GLX_RED_SIZE, 8, // True color RGB with 8 bits per channel.
3645 GLX_GREEN_SIZE, 8,
3646 GLX_BLUE_SIZE, 8,
3647 GLX_ALPHA_SIZE, 8,
3648 GLX_STENCIL_SIZE, 0, // No stencil buffer
3649 GLX_DEPTH_SIZE, 0, // No depth buffer
3650 None
3651 };
3652
3653 /* Find a suitable FB config. */
3654 int cConfigs = 0;
3655 GLXFBConfig *paConfigs = glXChooseFBConfig(pState->display, idxParentScreen, aConfigAttribList, &cConfigs);
3656 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: paConfigs %p cConfigs %d\n", (void *)paConfigs, cConfigs));
3657 if (paConfigs)
3658 {
3659 XVisualInfo *vi = NULL;
3660 int i = 0;
3661 for (; i < cConfigs; ++i)
3662 {
3663 /* Use XFree to free the data returned in the previous iteration of this loop. */
3664 if (vi)
3665 XFree(vi);
3666
3667 vi = glXGetVisualFromFBConfig(pState->display, paConfigs[i]);
3668 if (!vi)
3669 continue;
3670
3671 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: %p vid %lu screen %d depth %d r %lu g %lu b %lu clrmap %d bitsperrgb %d\n",
3672 (void *)vi->visual, vi->visualid, vi->screen, vi->depth,
3673 vi->red_mask, vi->green_mask, vi->blue_mask, vi->colormap_size, vi->bits_per_rgb));
3674
3675 /* Same screen as the parent window. */
3676 if (vi->screen != idxParentScreen)
3677 continue;
3678
3679 /* Search for 32 bits per pixel. */
3680 if (vi->depth != 32)
3681 continue;
3682
3683 /* 8 bits per color component is enough. */
3684 if (vi->bits_per_rgb != 8)
3685 continue;
3686
3687 /* Render to pixmap. */
3688 int value = 0;
3689 glXGetFBConfigAttrib(pState->display, paConfigs[i], GLX_DRAWABLE_TYPE, &value);
3690 if (!(value & GLX_WINDOW_BIT))
3691 continue;
3692
3693 /* This FB config can be used. */
3694 break;
3695 }
3696
3697 if (i < cConfigs)
3698 {
3699 /* Found a suitable config with index i. */
3700
3701 /* Create an overlay window. */
3702 XSetWindowAttributes swa;
3703 RT_ZERO(swa);
3704
3705 swa.colormap = XCreateColormap(pState->display, parentWindow, vi->visual, AllocNone);
3706 AssertLogRelMsg(swa.colormap, ("XCreateColormap failed"));
3707 swa.border_pixel = 0;
3708 swa.background_pixel = 0;
3709 swa.event_mask = StructureNotifyMask;
3710 swa.override_redirect = 1;
3711 unsigned long const swaAttrs = CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect;
3712 p->xwindow = XCreateWindow(pState->display, parentWindow,
3713 0, 0, cWidth, cHeight, 0, vi->depth, InputOutput,
3714 vi->visual, swaAttrs, &swa);
3715 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: p->xwindow %ld\n", p->xwindow));
3716 if (p->xwindow)
3717 {
3718
3719 p->glxctx = glXCreateContext(pState->display, vi, pState->SharedCtx.glxContext, GL_TRUE);
3720 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: p->glxctx %p\n", (void *)p->glxctx));
3721 if (p->glxctx)
3722 {
3723 XMapWindow(pState->display, p->xwindow);
3724 }
3725 else
3726 {
3727 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: glXCreateContext failed\n"));
3728 rc = VERR_NOT_SUPPORTED;
3729 }
3730 }
3731 else
3732 {
3733 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: XCreateWindow failed\n"));
3734 rc = VERR_NOT_SUPPORTED;
3735 }
3736
3737 XSync(pState->display, False);
3738 }
3739 else
3740 {
3741 /* A suitable config is not found. */
3742 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: no FBConfig\n"));
3743 rc = VERR_NOT_SUPPORTED;
3744 }
3745
3746 if (vi)
3747 XFree(vi);
3748
3749 /* "Use XFree to free the memory returned by glXChooseFBConfig." */
3750 XFree(paConfigs);
3751 }
3752 else
3753 {
3754 /* glXChooseFBConfig failed. */
3755 rc = VERR_NOT_SUPPORTED;
3756 }
3757
3758 XSetErrorHandler(oldHandler);
3759 return rc;
3760}
3761
3762/* Destroy a HW accelerated screen. */
3763static void vmsvga3dHwScreenDestroy(PVMSVGA3DSTATE pState, VMSVGAHWSCREEN *p)
3764{
3765 if (p)
3766 {
3767 LogRel4(("VMSVGA: vmsvga3dHwScreenDestroy: p->xwindow %ld, ctx %p\n", p->xwindow, (void *)p->glxctx));
3768 if (p->glxctx)
3769 {
3770 /* GLX context is changed here, so other code has to set the appropriate context again. */
3771 VMSVGA3D_CLEAR_CURRENT_CONTEXT(pState);
3772
3773 glXMakeCurrent(pState->display, p->xwindow, p->glxctx);
3774
3775 /* Clean up OpenGL. */
3776 if (p->idReadFramebuffer != OPENGL_INVALID_ID)
3777 pState->ext.glDeleteFramebuffers(1, &p->idReadFramebuffer);
3778 if (p->idDrawFramebuffer != OPENGL_INVALID_ID)
3779 pState->ext.glDeleteFramebuffers(1, &p->idDrawFramebuffer);
3780 if (p->idScreenTexture != OPENGL_INVALID_ID)
3781 glDeleteTextures(1, &p->idScreenTexture);
3782
3783 glXMakeCurrent(pState->display, None, NULL);
3784
3785 glXDestroyContext(pState->display, p->glxctx);
3786 }
3787
3788 if (p->xwindow)
3789 XDestroyWindow(pState->display, p->xwindow);
3790
3791 RT_ZERO(*p);
3792 }
3793}
3794
3795#define GLCHECK() \
3796 do { \
3797 int glErr = glGetError(); \
3798 if (glErr != GL_NO_ERROR) LogRel4(("VMSVGA: GL error 0x%x @%d\n", glErr, __LINE__)); \
3799 } while(0)
3800
3801static DECLCALLBACK(int) vmsvga3dBackDefineScreen(PVGASTATE pThis, PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen)
3802{
3803 LogRel4(("VMSVGA: vmsvga3dBackDefineScreen: screen %u\n", pScreen->idScreen));
3804
3805 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3806 AssertReturn(pState, VERR_NOT_SUPPORTED);
3807
3808 if (!pThis->svga.f3DOverlayEnabled)
3809 return VERR_NOT_SUPPORTED;
3810
3811 Assert(pScreen->pHwScreen == NULL);
3812
3813 VMSVGAHWSCREEN *p = (VMSVGAHWSCREEN *)RTMemAllocZ(sizeof(VMSVGAHWSCREEN));
3814 AssertPtrReturn(p, VERR_NO_MEMORY);
3815
3816 /* Query the parent window ID from the UI framebuffer.
3817 * If it is there then
3818 * the device will create a texture for the screen content and an overlay window to present the screen content.
3819 * otherwise
3820 * the device will use the guest VRAM system memory for the screen content.
3821 */
3822 Window parentWindow;
3823 int rc = vmsvga3dDrvQueryWindow(pThisCC, pScreen->idScreen, &parentWindow);
3824 if (RT_SUCCESS(rc))
3825 {
3826 /* Create the hardware accelerated screen. */
3827 rc = vmsvga3dHwScreenCreate(pState, parentWindow, pScreen->cWidth, pScreen->cHeight, p);
3828 if (RT_SUCCESS(rc))
3829 {
3830 /*
3831 * Setup the OpenGL context of the screen. The context will be used to draw on the screen.
3832 */
3833
3834 /* GLX context is changed here, so other code has to set the appropriate context again. */
3835 VMSVGA3D_CLEAR_CURRENT_CONTEXT(pState);
3836
3837 Bool const fSuccess = glXMakeCurrent(pState->display, p->xwindow, p->glxctx);
3838 if (fSuccess)
3839 {
3840 /* Set GL state. */
3841 glClearColor(0, 0, 0, 1);
3842 glEnable(GL_TEXTURE_2D);
3843 glDisable(GL_DEPTH_TEST);
3844 glDisable(GL_CULL_FACE);
3845
3846 /* The RGBA texture which hold the screen content. */
3847 glGenTextures(1, &p->idScreenTexture); GLCHECK();
3848 glBindTexture(GL_TEXTURE_2D, p->idScreenTexture); GLCHECK();
3849 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); GLCHECK();
3850 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); GLCHECK();
3851 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, pScreen->cWidth, pScreen->cHeight, 0,
3852 GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, NULL); GLCHECK();
3853
3854 /* Create read and draw framebuffer objects for this screen. */
3855 pState->ext.glGenFramebuffers(1, &p->idReadFramebuffer); GLCHECK();
3856 pState->ext.glGenFramebuffers(1, &p->idDrawFramebuffer); GLCHECK();
3857
3858 /* Work in screen coordinates. */
3859 glMatrixMode(GL_MODELVIEW);
3860 glLoadIdentity();
3861 glOrtho(0, pScreen->cWidth, 0, pScreen->cHeight, -1, 1);
3862 glMatrixMode(GL_PROJECTION);
3863 glLoadIdentity();
3864
3865 /* Clear the texture. */
3866 pState->ext.glBindFramebuffer(GL_DRAW_FRAMEBUFFER, p->idDrawFramebuffer); GLCHECK();
3867 pState->ext.glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
3868 p->idScreenTexture, 0); GLCHECK();
3869
3870 glClear(GL_COLOR_BUFFER_BIT);
3871
3872 pState->ext.glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); GLCHECK();
3873
3874 glXMakeCurrent(pState->display, None, NULL);
3875
3876 XSync(pState->display, False);
3877
3878 vmsvga3dDrvNotifyHwOverlay(pThisCC, VBOX3D_NOTIFY_TYPE_HW_OVERLAY_CREATED, pScreen->idScreen);
3879 }
3880 else
3881 {
3882 LogRel4(("VMSVGA: vmsvga3dBackDefineScreen: failed to set current context\n"));
3883 rc = VERR_NOT_SUPPORTED;
3884 }
3885 }
3886 }
3887 else
3888 {
3889 LogRel4(("VMSVGA: vmsvga3dBackDefineScreen: no framebuffer\n"));
3890 }
3891
3892 if (RT_SUCCESS(rc))
3893 {
3894 LogRel(("VMSVGA: Using HW accelerated screen %u\n", pScreen->idScreen));
3895 pScreen->pHwScreen = p;
3896 }
3897 else
3898 {
3899 LogRel4(("VMSVGA: vmsvga3dBackDefineScreen: %Rrc\n", rc));
3900 vmsvga3dHwScreenDestroy(pState, p);
3901 RTMemFree(p);
3902 }
3903
3904 return rc;
3905}
3906
3907static DECLCALLBACK(int) vmsvga3dBackDestroyScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen)
3908{
3909 LogRel4(("VMSVGA: vmsvga3dBackDestroyScreen: screen %u\n", pScreen->idScreen));
3910
3911 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3912 AssertReturn(pState, VERR_NOT_SUPPORTED);
3913
3914 int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctxErrorHandler);
3915
3916 VMSVGAHWSCREEN *p = pScreen->pHwScreen;
3917 if (p)
3918 {
3919 pScreen->pHwScreen = NULL;
3920
3921 vmsvga3dDrvNotifyHwOverlay(pThisCC, VBOX3D_NOTIFY_TYPE_HW_OVERLAY_DESTROYED, pScreen->idScreen);
3922
3923 vmsvga3dHwScreenDestroy(pState, p);
3924 RTMemFree(p);
3925 }
3926
3927 XSetErrorHandler(oldHandler);
3928
3929 return VINF_SUCCESS;
3930}
3931
3932/* Blit a surface to the GLX pixmap. */
3933static DECLCALLBACK(int) vmsvga3dBackSurfaceBlitToScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen,
3934 SVGASignedRect destRect, SVGA3dSurfaceImageId srcImage,
3935 SVGASignedRect srcRect, uint32_t cRects, SVGASignedRect *paRects)
3936{
3937 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3938 AssertReturn(pState, VERR_NOT_SUPPORTED);
3939
3940 VMSVGAHWSCREEN *p = pScreen->pHwScreen;
3941 AssertReturn(p, VERR_NOT_SUPPORTED);
3942
3943 PVMSVGA3DSURFACE pSurface;
3944 int rc = vmsvga3dSurfaceFromSid(pState, srcImage.sid, &pSurface);
3945 AssertRCReturn(rc, rc);
3946
3947 if (!VMSVGA3DSURFACE_HAS_HW_SURFACE(pSurface))
3948 {
3949 LogFunc(("src sid=%u flags=0x%x format=%d -> create texture\n", srcImage.sid, pSurface->f.s.surface1Flags, pSurface->format));
3950 rc = vmsvga3dBackCreateTexture(pThisCC, &pState->SharedCtx, VMSVGA3D_SHARED_CTX_ID, pSurface);
3951 AssertRCReturn(rc, rc);
3952 }
3953
3954 AssertReturn(pSurface->enmOGLResType == VMSVGA3D_OGLRESTYPE_TEXTURE, VERR_NOT_SUPPORTED);
3955
3956 PVMSVGA3DMIPMAPLEVEL pMipLevel;
3957 rc = vmsvga3dMipmapLevel(pSurface, srcImage.face, srcImage.mipmap, &pMipLevel);
3958 AssertRCReturn(rc, rc);
3959
3960 /** @todo Implement. */
3961 RT_NOREF(cRects, paRects);
3962
3963 /* GLX context is changed here, so other code has to set appropriate context again. */
3964 VMSVGA3D_CLEAR_CURRENT_CONTEXT(pState);
3965
3966 int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctxErrorHandler);
3967
3968 Bool fSuccess = glXMakeCurrent(pState->display, p->xwindow, p->glxctx);
3969 if (fSuccess)
3970 {
3971 /* Activate the read and draw framebuffer objects. */
3972 pState->ext.glBindFramebuffer(GL_READ_FRAMEBUFFER, p->idReadFramebuffer); GLCHECK();
3973 pState->ext.glBindFramebuffer(GL_DRAW_FRAMEBUFFER, p->idDrawFramebuffer); GLCHECK();
3974
3975 /* Bind the source and destination objects to the right place. */
3976 pState->ext.glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
3977 pSurface->oglId.texture, 0); GLCHECK();
3978 pState->ext.glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
3979 p->idScreenTexture, 0); GLCHECK();
3980
3981 pState->ext.glBlitFramebuffer(srcRect.left,
3982 srcRect.top,
3983 srcRect.right,
3984 srcRect.bottom,
3985 destRect.left,
3986 destRect.top,
3987 destRect.right,
3988 destRect.bottom,
3989 GL_COLOR_BUFFER_BIT,
3990 GL_NEAREST); GLCHECK();
3991
3992 /* Reset the frame buffer association */
3993 pState->ext.glBindFramebuffer(GL_FRAMEBUFFER, 0); GLCHECK();
3994
3995 /* Update the overlay window. */
3996 glClear(GL_COLOR_BUFFER_BIT);
3997
3998 glBindTexture(GL_TEXTURE_2D, p->idScreenTexture); GLCHECK();
3999
4000 GLint const w = pScreen->cWidth;
4001 GLint const h = pScreen->cHeight;
4002
4003 glBegin(GL_QUADS);
4004 glTexCoord2f(0.0f, 0.0f); glVertex2i(0, h);
4005 glTexCoord2f(0.0f, 1.0f); glVertex2i(0, 0);
4006 glTexCoord2f(1.0f, 1.0f); glVertex2i(w, 0);
4007 glTexCoord2f(1.0f, 0.0f); glVertex2i(w, h);
4008 glEnd(); GLCHECK();
4009
4010 glBindTexture(GL_TEXTURE_2D, 0); GLCHECK();
4011
4012 glXMakeCurrent(pState->display, None, NULL);
4013 }
4014 else
4015 {
4016 LogRel4(("VMSVGA: vmsvga3dBackSurfaceBlitToScreen: screen %u, glXMakeCurrent for pixmap failed\n", pScreen->idScreen));
4017 }
4018
4019 XSetErrorHandler(oldHandler);
4020
4021 return VINF_SUCCESS;
4022}
4023
4024#else /* !RT_OS_LINUX */
4025
4026static DECLCALLBACK(int) vmsvga3dBackDefineScreen(PVGASTATE pThis, PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen)
4027{
4028 RT_NOREF(pThis, pThisCC, pScreen);
4029 return VERR_NOT_IMPLEMENTED;
4030}
4031
4032static DECLCALLBACK(int) vmsvga3dBackDestroyScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen)
4033{
4034 RT_NOREF(pThisCC, pScreen);
4035 return VERR_NOT_IMPLEMENTED;
4036}
4037
4038static DECLCALLBACK(int) vmsvga3dBackSurfaceBlitToScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen,
4039 SVGASignedRect destRect, SVGA3dSurfaceImageId srcImage,
4040 SVGASignedRect srcRect, uint32_t cRects, SVGASignedRect *paRects)
4041{
4042 RT_NOREF(pThisCC, pScreen, destRect, srcImage, srcRect, cRects, paRects);
4043 return VERR_NOT_IMPLEMENTED;
4044}
4045#endif
4046
4047/**
4048 * Create a new 3d context
4049 *
4050 * @returns VBox status code.
4051 * @param pThisCC The VGA/VMSVGA state for ring-3.
4052 * @param cid Context id
4053 */
4054static DECLCALLBACK(int) vmsvga3dBackContextDefine(PVGASTATECC pThisCC, uint32_t cid)
4055{
4056 return vmsvga3dContextDefineOgl(pThisCC, cid, 0/*fFlags*/);
4057}
4058
4059/**
4060 * Destroys a 3d context.
4061 *
4062 * @returns VBox status code.
4063 * @param pThisCC The VGA/VMSVGA state for ring-3.
4064 * @param pContext The context to destroy.
4065 * @param cid Context id
4066 */
4067static int vmsvga3dContextDestroyOgl(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t cid)
4068{
4069 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4070 AssertReturn(pState, VERR_NO_MEMORY);
4071 AssertReturn(pContext, VERR_INVALID_PARAMETER);
4072 AssertReturn(pContext->id == cid, VERR_INVALID_PARAMETER);
4073 Log(("vmsvga3dContextDestroyOgl id %x\n", cid));
4074
4075 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
4076
4077 if (pContext->id == VMSVGA3D_SHARED_CTX_ID)
4078 {
4079 /* Delete resources which use the shared context. */
4080 vmsvga3dOnSharedContextDestroy(pState);
4081 }
4082
4083 /* Destroy all leftover pixel shaders. */
4084 for (uint32_t i = 0; i < pContext->cPixelShaders; i++)
4085 {
4086 if (pContext->paPixelShader[i].id != SVGA3D_INVALID_ID)
4087 vmsvga3dBackShaderDestroy(pThisCC, pContext->paPixelShader[i].cid, pContext->paPixelShader[i].id, pContext->paPixelShader[i].type);
4088 }
4089 if (pContext->paPixelShader)
4090 RTMemFree(pContext->paPixelShader);
4091
4092 /* Destroy all leftover vertex shaders. */
4093 for (uint32_t i = 0; i < pContext->cVertexShaders; i++)
4094 {
4095 if (pContext->paVertexShader[i].id != SVGA3D_INVALID_ID)
4096 vmsvga3dBackShaderDestroy(pThisCC, pContext->paVertexShader[i].cid, pContext->paVertexShader[i].id, pContext->paVertexShader[i].type);
4097 }
4098 if (pContext->paVertexShader)
4099 RTMemFree(pContext->paVertexShader);
4100
4101 if (pContext->state.paVertexShaderConst)
4102 RTMemFree(pContext->state.paVertexShaderConst);
4103 if (pContext->state.paPixelShaderConst)
4104 RTMemFree(pContext->state.paPixelShaderConst);
4105
4106 if (pContext->pShaderContext)
4107 {
4108 int rc = ShaderContextDestroy(pContext->pShaderContext);
4109 AssertRC(rc);
4110 }
4111
4112 if (pContext->idFramebuffer != OPENGL_INVALID_ID)
4113 {
4114 /* Unbind the object from the framebuffer target. */
4115 pState->ext.glBindFramebuffer(GL_FRAMEBUFFER, 0 /* back buffer */);
4116 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4117 pState->ext.glDeleteFramebuffers(1, &pContext->idFramebuffer);
4118 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4119
4120 if (pContext->idReadFramebuffer != OPENGL_INVALID_ID)
4121 {
4122 pState->ext.glDeleteFramebuffers(1, &pContext->idReadFramebuffer);
4123 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4124 }
4125 if (pContext->idDrawFramebuffer != OPENGL_INVALID_ID)
4126 {
4127 pState->ext.glDeleteFramebuffers(1, &pContext->idDrawFramebuffer);
4128 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4129 }
4130 }
4131
4132 vmsvga3dBackOcclusionQueryDelete(pThisCC, pContext);
4133
4134#ifdef RT_OS_WINDOWS
4135 wglMakeCurrent(pContext->hdc, NULL);
4136 wglDeleteContext(pContext->hglrc);
4137 ReleaseDC(pContext->hwnd, pContext->hdc);
4138
4139 /* Destroy the window we've created. */
4140 int rc = vmsvga3dSendThreadMessage(pState->pWindowThread, pState->WndRequestSem, WM_VMSVGA3D_DESTROYWINDOW, (WPARAM)pContext->hwnd, 0);
4141 AssertRC(rc);
4142#elif defined(RT_OS_DARWIN)
4143 vmsvga3dCocoaDestroyViewAndContext(pContext->cocoaView, pContext->cocoaContext);
4144#elif defined(RT_OS_LINUX)
4145 glXMakeCurrent(pState->display, None, NULL);
4146 glXDestroyContext(pState->display, pContext->glxContext);
4147 XDestroyWindow(pState->display, pContext->window);
4148#endif
4149
4150 memset(pContext, 0, sizeof(*pContext));
4151 pContext->id = SVGA3D_INVALID_ID;
4152
4153 VMSVGA3D_CLEAR_CURRENT_CONTEXT(pState);
4154 return VINF_SUCCESS;
4155}
4156
4157/**
4158 * Destroy an existing 3d context
4159 *
4160 * @returns VBox status code.
4161 * @param pThisCC The VGA/VMSVGA state for ring-3.
4162 * @param cid Context id
4163 */
4164static DECLCALLBACK(int) vmsvga3dBackContextDestroy(PVGASTATECC pThisCC, uint32_t cid)
4165{
4166 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4167 AssertReturn(pState, VERR_WRONG_ORDER);
4168
4169 /*
4170 * Resolve the context and hand it to the common worker function.
4171 */
4172 if ( cid < pState->cContexts
4173 && pState->papContexts[cid]->id == cid)
4174 return vmsvga3dContextDestroyOgl(pThisCC, pState->papContexts[cid], cid);
4175
4176 AssertReturn(cid < SVGA3D_MAX_CONTEXT_IDS, VERR_INVALID_PARAMETER);
4177 return VINF_SUCCESS;
4178}
4179
4180/**
4181 * Worker for vmsvga3dBackChangeMode that resizes a context.
4182 *
4183 * @param pState The VMSVGA3d state.
4184 * @param pContext The context.
4185 */
4186static void vmsvga3dChangeModeOneContext(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext)
4187{
4188 RT_NOREF(pState, pContext);
4189 /* Do nothing. The window is not used for presenting. */
4190}
4191
4192/* Handle resize */
4193static DECLCALLBACK(int) vmsvga3dBackChangeMode(PVGASTATECC pThisCC)
4194{
4195 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4196 AssertReturn(pState, VERR_NO_MEMORY);
4197
4198 /* Resize the shared context too. */
4199 if (pState->SharedCtx.id == VMSVGA3D_SHARED_CTX_ID)
4200 vmsvga3dChangeModeOneContext(pState, &pState->SharedCtx);
4201
4202 /* Resize all active contexts. */
4203 for (uint32_t i = 0; i < pState->cContexts; i++)
4204 {
4205 PVMSVGA3DCONTEXT pContext = pState->papContexts[i];
4206 if (pContext->id != SVGA3D_INVALID_ID)
4207 vmsvga3dChangeModeOneContext(pState, pContext);
4208 }
4209
4210 return VINF_SUCCESS;
4211}
4212
4213
4214static DECLCALLBACK(int) vmsvga3dBackSetTransform(PVGASTATECC pThisCC, uint32_t cid, SVGA3dTransformType type, float matrix[16])
4215{
4216 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4217 AssertReturn(pState, VERR_NO_MEMORY);
4218 bool fModelViewChanged = false;
4219
4220 Log(("vmsvga3dSetTransform cid=%u %s\n", cid, vmsvgaTransformToString(type)));
4221
4222 ASSERT_GUEST_RETURN((unsigned)type < SVGA3D_TRANSFORM_MAX, VERR_INVALID_PARAMETER);
4223
4224 PVMSVGA3DCONTEXT pContext;
4225 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
4226 AssertRCReturn(rc, rc);
4227
4228 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
4229
4230 /* Save this matrix for vm state save/restore. */
4231 pContext->state.aTransformState[type].fValid = true;
4232 memcpy(pContext->state.aTransformState[type].matrix, matrix, sizeof(pContext->state.aTransformState[type].matrix));
4233 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_TRANSFORM;
4234
4235 Log(("Matrix [%d %d %d %d]\n", (int)(matrix[0] * 10.0), (int)(matrix[1] * 10.0), (int)(matrix[2] * 10.0), (int)(matrix[3] * 10.0)));
4236 Log((" [%d %d %d %d]\n", (int)(matrix[4] * 10.0), (int)(matrix[5] * 10.0), (int)(matrix[6] * 10.0), (int)(matrix[7] * 10.0)));
4237 Log((" [%d %d %d %d]\n", (int)(matrix[8] * 10.0), (int)(matrix[9] * 10.0), (int)(matrix[10] * 10.0), (int)(matrix[11] * 10.0)));
4238 Log((" [%d %d %d %d]\n", (int)(matrix[12] * 10.0), (int)(matrix[13] * 10.0), (int)(matrix[14] * 10.0), (int)(matrix[15] * 10.0)));
4239
4240 switch (type)
4241 {
4242 case SVGA3D_TRANSFORM_VIEW:
4243 /* View * World = Model View */
4244 glMatrixMode(GL_MODELVIEW);
4245 glLoadMatrixf(matrix);
4246 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_WORLD].fValid)
4247 glMultMatrixf(pContext->state.aTransformState[SVGA3D_TRANSFORM_WORLD].matrix);
4248 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4249 fModelViewChanged = true;
4250 break;
4251
4252 case SVGA3D_TRANSFORM_PROJECTION:
4253 {
4254 rc = ShaderTransformProjection(pContext->state.RectViewPort.w, pContext->state.RectViewPort.h, matrix, false /* fPretransformed */);
4255 AssertRCReturn(rc, rc);
4256 break;
4257 }
4258
4259 case SVGA3D_TRANSFORM_TEXTURE0:
4260 glMatrixMode(GL_TEXTURE);
4261 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4262 glLoadMatrixf(matrix);
4263 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4264 break;
4265
4266 case SVGA3D_TRANSFORM_TEXTURE1:
4267 case SVGA3D_TRANSFORM_TEXTURE2:
4268 case SVGA3D_TRANSFORM_TEXTURE3:
4269 case SVGA3D_TRANSFORM_TEXTURE4:
4270 case SVGA3D_TRANSFORM_TEXTURE5:
4271 case SVGA3D_TRANSFORM_TEXTURE6:
4272 case SVGA3D_TRANSFORM_TEXTURE7:
4273 Log(("vmsvga3dSetTransform: unsupported SVGA3D_TRANSFORM_TEXTUREx transform!!\n"));
4274 return VERR_INVALID_PARAMETER;
4275
4276 case SVGA3D_TRANSFORM_WORLD:
4277 /* View * World = Model View */
4278 glMatrixMode(GL_MODELVIEW);
4279 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].fValid)
4280 glLoadMatrixf(pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].matrix);
4281 else
4282 glLoadIdentity();
4283 glMultMatrixf(matrix);
4284 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4285 fModelViewChanged = true;
4286 break;
4287
4288 case SVGA3D_TRANSFORM_WORLD1:
4289 case SVGA3D_TRANSFORM_WORLD2:
4290 case SVGA3D_TRANSFORM_WORLD3:
4291 Log(("vmsvga3dSetTransform: unsupported SVGA3D_TRANSFORM_WORLDx transform!!\n"));
4292 return VERR_INVALID_PARAMETER;
4293
4294 default:
4295 Log(("vmsvga3dSetTransform: unknown type!!\n"));
4296 return VERR_INVALID_PARAMETER;
4297 }
4298
4299 /* Apparently we need to reset the light and clip data after modifying the modelview matrix. */
4300 if (fModelViewChanged)
4301 {
4302 /* Reprogram the clip planes. */
4303 for (uint32_t j = 0; j < RT_ELEMENTS(pContext->state.aClipPlane); j++)
4304 {
4305 if (pContext->state.aClipPlane[j].fValid == true)
4306 vmsvga3dBackSetClipPlane(pThisCC, cid, j, pContext->state.aClipPlane[j].plane);
4307 }
4308
4309 /* Reprogram the light data. */
4310 for (uint32_t j = 0; j < RT_ELEMENTS(pContext->state.aLightData); j++)
4311 {
4312 if (pContext->state.aLightData[j].fValidData == true)
4313 vmsvga3dBackSetLightData(pThisCC, cid, j, &pContext->state.aLightData[j].data);
4314 }
4315 }
4316
4317 return VINF_SUCCESS;
4318}
4319
4320static DECLCALLBACK(int) vmsvga3dBackSetZRange(PVGASTATECC pThisCC, uint32_t cid, SVGA3dZRange zRange)
4321{
4322 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4323 AssertReturn(pState, VERR_NO_MEMORY);
4324
4325 Log(("vmsvga3dSetZRange cid=%u min=%d max=%d\n", cid, (uint32_t)(zRange.min * 100.0), (uint32_t)(zRange.max * 100.0)));
4326
4327 PVMSVGA3DCONTEXT pContext;
4328 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
4329 AssertRCReturn(rc, rc);
4330
4331 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
4332
4333 pContext->state.zRange = zRange;
4334 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_ZRANGE;
4335
4336 if (zRange.min < -1.0)
4337 zRange.min = -1.0;
4338 if (zRange.max > 1.0)
4339 zRange.max = 1.0;
4340
4341 glDepthRange((GLdouble)zRange.min, (GLdouble)zRange.max);
4342 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4343 return VINF_SUCCESS;
4344}
4345
4346/**
4347 * Convert SVGA blend op value to its OpenGL equivalent
4348 */
4349static GLenum vmsvga3dBlendOp2GL(uint32_t blendOp)
4350{
4351 switch (blendOp)
4352 {
4353 case SVGA3D_BLENDOP_ZERO:
4354 return GL_ZERO;
4355 case SVGA3D_BLENDOP_ONE:
4356 return GL_ONE;
4357 case SVGA3D_BLENDOP_SRCCOLOR:
4358 return GL_SRC_COLOR;
4359 case SVGA3D_BLENDOP_INVSRCCOLOR:
4360 return GL_ONE_MINUS_SRC_COLOR;
4361 case SVGA3D_BLENDOP_SRCALPHA:
4362 return GL_SRC_ALPHA;
4363 case SVGA3D_BLENDOP_INVSRCALPHA:
4364 return GL_ONE_MINUS_SRC_ALPHA;
4365 case SVGA3D_BLENDOP_DESTALPHA:
4366 return GL_DST_ALPHA;
4367 case SVGA3D_BLENDOP_INVDESTALPHA:
4368 return GL_ONE_MINUS_DST_ALPHA;
4369 case SVGA3D_BLENDOP_DESTCOLOR:
4370 return GL_DST_COLOR;
4371 case SVGA3D_BLENDOP_INVDESTCOLOR:
4372 return GL_ONE_MINUS_DST_COLOR;
4373 case SVGA3D_BLENDOP_SRCALPHASAT:
4374 return GL_SRC_ALPHA_SATURATE;
4375 case SVGA3D_BLENDOP_BLENDFACTOR:
4376 return GL_CONSTANT_COLOR;
4377 case SVGA3D_BLENDOP_INVBLENDFACTOR:
4378 return GL_ONE_MINUS_CONSTANT_COLOR;
4379 default:
4380 AssertFailed();
4381 return GL_ONE;
4382 }
4383}
4384
4385static GLenum vmsvga3dBlendEquation2GL(uint32_t blendEq)
4386{
4387 switch (blendEq)
4388 {
4389 case SVGA3D_BLENDEQ_ADD:
4390 return GL_FUNC_ADD;
4391 case SVGA3D_BLENDEQ_SUBTRACT:
4392 return GL_FUNC_SUBTRACT;
4393 case SVGA3D_BLENDEQ_REVSUBTRACT:
4394 return GL_FUNC_REVERSE_SUBTRACT;
4395 case SVGA3D_BLENDEQ_MINIMUM:
4396 return GL_MIN;
4397 case SVGA3D_BLENDEQ_MAXIMUM:
4398 return GL_MAX;
4399 default:
4400 /* SVGA3D_BLENDEQ_INVALID means that the render state has not been set, therefore use default. */
4401 AssertMsg(blendEq == SVGA3D_BLENDEQ_INVALID, ("blendEq=%d (%#x)\n", blendEq, blendEq));
4402 return GL_FUNC_ADD;
4403 }
4404}
4405
4406static GLenum vmsvgaCmpFunc2GL(uint32_t cmpFunc)
4407{
4408 switch (cmpFunc)
4409 {
4410 case SVGA3D_CMP_NEVER:
4411 return GL_NEVER;
4412 case SVGA3D_CMP_LESS:
4413 return GL_LESS;
4414 case SVGA3D_CMP_EQUAL:
4415 return GL_EQUAL;
4416 case SVGA3D_CMP_LESSEQUAL:
4417 return GL_LEQUAL;
4418 case SVGA3D_CMP_GREATER:
4419 return GL_GREATER;
4420 case SVGA3D_CMP_NOTEQUAL:
4421 return GL_NOTEQUAL;
4422 case SVGA3D_CMP_GREATEREQUAL:
4423 return GL_GEQUAL;
4424 case SVGA3D_CMP_ALWAYS:
4425 return GL_ALWAYS;
4426 default:
4427 Assert(cmpFunc == SVGA3D_CMP_INVALID);
4428 return GL_LESS;
4429 }
4430}
4431
4432static GLenum vmsvgaStencipOp2GL(uint32_t stencilOp)
4433{
4434 switch (stencilOp)
4435 {
4436 case SVGA3D_STENCILOP_KEEP:
4437 return GL_KEEP;
4438 case SVGA3D_STENCILOP_ZERO:
4439 return GL_ZERO;
4440 case SVGA3D_STENCILOP_REPLACE:
4441 return GL_REPLACE;
4442 case SVGA3D_STENCILOP_INCRSAT:
4443 return GL_INCR_WRAP;
4444 case SVGA3D_STENCILOP_DECRSAT:
4445 return GL_DECR_WRAP;
4446 case SVGA3D_STENCILOP_INVERT:
4447 return GL_INVERT;
4448 case SVGA3D_STENCILOP_INCR:
4449 return GL_INCR;
4450 case SVGA3D_STENCILOP_DECR:
4451 return GL_DECR;
4452 default:
4453 Assert(stencilOp == SVGA3D_STENCILOP_INVALID);
4454 return GL_KEEP;
4455 }
4456}
4457
4458static DECLCALLBACK(int) vmsvga3dBackSetRenderState(PVGASTATECC pThisCC, uint32_t cid, uint32_t cRenderStates, SVGA3dRenderState *pRenderState)
4459{
4460 uint32_t val = UINT32_MAX; /* Shut up MSC. */
4461 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4462 AssertReturn(pState, VERR_NO_MEMORY);
4463
4464 Log(("vmsvga3dSetRenderState cid=%u cRenderStates=%d\n", cid, cRenderStates));
4465
4466 PVMSVGA3DCONTEXT pContext;
4467 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
4468 AssertRCReturn(rc, rc);
4469
4470 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
4471
4472 for (unsigned i = 0; i < cRenderStates; i++)
4473 {
4474 GLenum enableCap = ~(GLenum)0;
4475 Log(("vmsvga3dSetRenderState: cid=%u state=%s (%d) val=%x\n", cid, vmsvga3dGetRenderStateName(pRenderState[i].state), pRenderState[i].state, pRenderState[i].uintValue));
4476 /* Save the render state for vm state saving. */
4477 ASSERT_GUEST_RETURN((unsigned)pRenderState[i].state < SVGA3D_RS_MAX, VERR_INVALID_PARAMETER);
4478 pContext->state.aRenderState[pRenderState[i].state] = pRenderState[i];
4479
4480 switch (pRenderState[i].state)
4481 {
4482 case SVGA3D_RS_ZENABLE: /* SVGA3dBool */
4483 enableCap = GL_DEPTH_TEST;
4484 val = pRenderState[i].uintValue;
4485 break;
4486
4487 case SVGA3D_RS_ZWRITEENABLE: /* SVGA3dBool */
4488 glDepthMask(!!pRenderState[i].uintValue);
4489 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4490 break;
4491
4492 case SVGA3D_RS_ALPHATESTENABLE: /* SVGA3dBool */
4493 enableCap = GL_ALPHA_TEST;
4494 val = pRenderState[i].uintValue;
4495 break;
4496
4497 case SVGA3D_RS_DITHERENABLE: /* SVGA3dBool */
4498 enableCap = GL_DITHER;
4499 val = pRenderState[i].uintValue;
4500 break;
4501
4502 case SVGA3D_RS_FOGENABLE: /* SVGA3dBool */
4503 enableCap = GL_FOG;
4504 val = pRenderState[i].uintValue;
4505 break;
4506
4507 case SVGA3D_RS_SPECULARENABLE: /* SVGA3dBool */
4508 Log(("vmsvga3dSetRenderState: WARNING: not applicable.\n"));
4509 break;
4510
4511 case SVGA3D_RS_LIGHTINGENABLE: /* SVGA3dBool */
4512 enableCap = GL_LIGHTING;
4513 val = pRenderState[i].uintValue;
4514 break;
4515
4516 case SVGA3D_RS_NORMALIZENORMALS: /* SVGA3dBool */
4517 /* not applicable */
4518 Log(("vmsvga3dSetRenderState: WARNING: not applicable.\n"));
4519 break;
4520
4521 case SVGA3D_RS_POINTSPRITEENABLE: /* SVGA3dBool */
4522 enableCap = GL_POINT_SPRITE_ARB;
4523 val = pRenderState[i].uintValue;
4524 break;
4525
4526 case SVGA3D_RS_POINTSIZE: /* float */
4527 /** @todo we need to apply scaling for point sizes below the min or above the max; see Wine) */
4528 if (pRenderState[i].floatValue < pState->caps.flPointSize[0])
4529 pRenderState[i].floatValue = pState->caps.flPointSize[0];
4530 if (pRenderState[i].floatValue > pState->caps.flPointSize[1])
4531 pRenderState[i].floatValue = pState->caps.flPointSize[1];
4532
4533 glPointSize(pRenderState[i].floatValue);
4534 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4535 Log(("SVGA3D_RS_POINTSIZE: %d\n", (uint32_t) (pRenderState[i].floatValue * 100.0)));
4536 break;
4537
4538 case SVGA3D_RS_POINTSIZEMIN: /* float */
4539 pState->ext.glPointParameterf(GL_POINT_SIZE_MIN, pRenderState[i].floatValue);
4540 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4541 Log(("SVGA3D_RS_POINTSIZEMIN: %d\n", (uint32_t) (pRenderState[i].floatValue * 100.0)));
4542 break;
4543
4544 case SVGA3D_RS_POINTSIZEMAX: /* float */
4545 pState->ext.glPointParameterf(GL_POINT_SIZE_MAX, pRenderState[i].floatValue);
4546 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4547 Log(("SVGA3D_RS_POINTSIZEMAX: %d\n", (uint32_t) (pRenderState[i].floatValue * 100.0)));
4548 break;
4549
4550 case SVGA3D_RS_POINTSCALEENABLE: /* SVGA3dBool */
4551 case SVGA3D_RS_POINTSCALE_A: /* float */
4552 case SVGA3D_RS_POINTSCALE_B: /* float */
4553 case SVGA3D_RS_POINTSCALE_C: /* float */
4554 Log(("vmsvga3dSetRenderState: WARNING: not applicable.\n"));
4555 break;
4556
4557 case SVGA3D_RS_AMBIENT: /* SVGA3dColor */
4558 {
4559 GLfloat color[4]; /* red, green, blue, alpha */
4560
4561 vmsvgaColor2GLFloatArray(pRenderState[i].uintValue, &color[0], &color[1], &color[2], &color[3]);
4562
4563 glLightModelfv(GL_LIGHT_MODEL_AMBIENT, color);
4564 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4565 break;
4566 }
4567
4568 case SVGA3D_RS_CLIPPLANEENABLE: /* SVGA3dClipPlanes */
4569 {
4570 for (uint32_t j = 0; j < SVGA3D_NUM_CLIPPLANES; j++)
4571 {
4572 if (pRenderState[i].uintValue & RT_BIT(j))
4573 glEnable(GL_CLIP_PLANE0 + j);
4574 else
4575 glDisable(GL_CLIP_PLANE0 + j);
4576 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4577 }
4578 break;
4579 }
4580
4581 case SVGA3D_RS_FOGCOLOR: /* SVGA3dColor */
4582 {
4583 GLfloat color[4]; /* red, green, blue, alpha */
4584
4585 vmsvgaColor2GLFloatArray(pRenderState[i].uintValue, &color[0], &color[1], &color[2], &color[3]);
4586
4587 glFogfv(GL_FOG_COLOR, color);
4588 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4589 break;
4590 }
4591
4592 case SVGA3D_RS_FOGSTART: /* float */
4593 glFogf(GL_FOG_START, pRenderState[i].floatValue);
4594 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4595 break;
4596
4597 case SVGA3D_RS_FOGEND: /* float */
4598 glFogf(GL_FOG_END, pRenderState[i].floatValue);
4599 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4600 break;
4601
4602 case SVGA3D_RS_FOGDENSITY: /* float */
4603 glFogf(GL_FOG_DENSITY, pRenderState[i].floatValue);
4604 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4605 break;
4606
4607 case SVGA3D_RS_RANGEFOGENABLE: /* SVGA3dBool */
4608 glFogi(GL_FOG_COORD_SRC, (pRenderState[i].uintValue) ? GL_FOG_COORD : GL_FRAGMENT_DEPTH);
4609 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4610 break;
4611
4612 case SVGA3D_RS_FOGMODE: /* SVGA3dFogMode */
4613 {
4614 SVGA3dFogMode mode;
4615 mode.uintValue = pRenderState[i].uintValue;
4616
4617 enableCap = GL_FOG_MODE;
4618 switch (mode.function)
4619 {
4620 case SVGA3D_FOGFUNC_EXP:
4621 val = GL_EXP;
4622 break;
4623 case SVGA3D_FOGFUNC_EXP2:
4624 val = GL_EXP2;
4625 break;
4626 case SVGA3D_FOGFUNC_LINEAR:
4627 val = GL_LINEAR;
4628 break;
4629 default:
4630 AssertMsgFailedReturn(("Unexpected fog function %d\n", mode.function), VERR_INTERNAL_ERROR);
4631 break;
4632 }
4633
4634 /** @todo how to switch between vertex and pixel fog modes??? */
4635 Assert(mode.type == SVGA3D_FOGTYPE_PIXEL);
4636#if 0
4637 /* The fog type determines the render state. */
4638 switch (mode.type)
4639 {
4640 case SVGA3D_FOGTYPE_VERTEX:
4641 renderState = D3DRS_FOGVERTEXMODE;
4642 break;
4643 case SVGA3D_FOGTYPE_PIXEL:
4644 renderState = D3DRS_FOGTABLEMODE;
4645 break;
4646 default:
4647 AssertMsgFailedReturn(("Unexpected fog type %d\n", mode.type), VERR_INTERNAL_ERROR);
4648 break;
4649 }
4650#endif
4651
4652 /* Set the fog base to depth or range. */
4653 switch (mode.base)
4654 {
4655 case SVGA3D_FOGBASE_DEPTHBASED:
4656 glFogi(GL_FOG_COORD_SRC, GL_FRAGMENT_DEPTH);
4657 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4658 break;
4659 case SVGA3D_FOGBASE_RANGEBASED:
4660 glFogi(GL_FOG_COORD_SRC, GL_FOG_COORD);
4661 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4662 break;
4663 default:
4664 /* ignore */
4665 AssertMsgFailed(("Unexpected fog base %d\n", mode.base));
4666 break;
4667 }
4668 break;
4669 }
4670
4671 case SVGA3D_RS_FILLMODE: /* SVGA3dFillMode */
4672 {
4673 SVGA3dFillMode mode;
4674
4675 mode.uintValue = pRenderState[i].uintValue;
4676
4677 switch (mode.mode)
4678 {
4679 case SVGA3D_FILLMODE_POINT:
4680 val = GL_POINT;
4681 break;
4682 case SVGA3D_FILLMODE_LINE:
4683 val = GL_LINE;
4684 break;
4685 case SVGA3D_FILLMODE_FILL:
4686 val = GL_FILL;
4687 break;
4688 default:
4689 AssertMsgFailedReturn(("Unexpected fill mode %d\n", mode.mode), VERR_INTERNAL_ERROR);
4690 break;
4691 }
4692 /* Only front and back faces. Also recent Mesa guest drivers initialize the 'face' to zero. */
4693 ASSERT_GUEST(mode.face == SVGA3D_FACE_FRONT_BACK || mode.face == SVGA3D_FACE_INVALID);
4694 glPolygonMode(GL_FRONT_AND_BACK, val);
4695 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4696 break;
4697 }
4698
4699 case SVGA3D_RS_SHADEMODE: /* SVGA3dShadeMode */
4700 switch (pRenderState[i].uintValue)
4701 {
4702 case SVGA3D_SHADEMODE_FLAT:
4703 val = GL_FLAT;
4704 break;
4705
4706 case SVGA3D_SHADEMODE_SMOOTH:
4707 val = GL_SMOOTH;
4708 break;
4709
4710 default:
4711 AssertMsgFailedReturn(("Unexpected shade mode %d\n", pRenderState[i].uintValue), VERR_INTERNAL_ERROR);
4712 break;
4713 }
4714
4715 glShadeModel(val);
4716 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4717 break;
4718
4719 case SVGA3D_RS_LINEPATTERN: /* SVGA3dLinePattern */
4720 /* No longer supported by d3d; mesagl comments suggest not all backends support it */
4721 /** @todo */
4722 Log(("WARNING: SVGA3D_RS_LINEPATTERN %x not supported!!\n", pRenderState[i].uintValue));
4723 /*
4724 renderState = D3DRS_LINEPATTERN;
4725 val = pRenderState[i].uintValue;
4726 */
4727 break;
4728
4729 case SVGA3D_RS_ANTIALIASEDLINEENABLE: /* SVGA3dBool */
4730 enableCap = GL_LINE_SMOOTH;
4731 val = pRenderState[i].uintValue;
4732 break;
4733
4734 case SVGA3D_RS_LINEWIDTH: /* float */
4735 glLineWidth(pRenderState[i].floatValue);
4736 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4737 break;
4738
4739 case SVGA3D_RS_SEPARATEALPHABLENDENABLE: /* SVGA3dBool */
4740 {
4741 /* Refresh the blending state based on the new enable setting.
4742 * This will take existing states and set them using either glBlend* or glBlend*Separate.
4743 */
4744 static SVGA3dRenderStateName const saRefreshState[] =
4745 {
4746 SVGA3D_RS_SRCBLEND,
4747 SVGA3D_RS_BLENDEQUATION
4748 };
4749 SVGA3dRenderState renderstate[RT_ELEMENTS(saRefreshState)];
4750 for (uint32_t j = 0; j < RT_ELEMENTS(saRefreshState); ++j)
4751 {
4752 renderstate[j].state = saRefreshState[j];
4753 renderstate[j].uintValue = pContext->state.aRenderState[saRefreshState[j]].uintValue;
4754 }
4755
4756 rc = vmsvga3dBackSetRenderState(pThisCC, cid, 2, renderstate);
4757 AssertRCReturn(rc, rc);
4758
4759 if (pContext->state.aRenderState[SVGA3D_RS_BLENDENABLE].uintValue != 0)
4760 continue; /* Ignore if blend is enabled */
4761 /* Apply SVGA3D_RS_SEPARATEALPHABLENDENABLE as SVGA3D_RS_BLENDENABLE */
4762 } RT_FALL_THRU();
4763
4764 case SVGA3D_RS_BLENDENABLE: /* SVGA3dBool */
4765 enableCap = GL_BLEND;
4766 val = pRenderState[i].uintValue;
4767 break;
4768
4769 case SVGA3D_RS_SRCBLENDALPHA: /* SVGA3dBlendOp */
4770 case SVGA3D_RS_DSTBLENDALPHA: /* SVGA3dBlendOp */
4771 case SVGA3D_RS_SRCBLEND: /* SVGA3dBlendOp */
4772 case SVGA3D_RS_DSTBLEND: /* SVGA3dBlendOp */
4773 {
4774 GLint srcRGB, srcAlpha, dstRGB, dstAlpha;
4775 GLint blendop = vmsvga3dBlendOp2GL(pRenderState[i].uintValue);
4776
4777 glGetIntegerv(GL_BLEND_SRC_RGB, &srcRGB);
4778 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4779 glGetIntegerv(GL_BLEND_DST_RGB, &dstRGB);
4780 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4781 glGetIntegerv(GL_BLEND_DST_ALPHA, &dstAlpha);
4782 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4783 glGetIntegerv(GL_BLEND_SRC_ALPHA, &srcAlpha);
4784 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4785
4786 switch (pRenderState[i].state)
4787 {
4788 case SVGA3D_RS_SRCBLEND:
4789 srcRGB = blendop;
4790 break;
4791 case SVGA3D_RS_DSTBLEND:
4792 dstRGB = blendop;
4793 break;
4794 case SVGA3D_RS_SRCBLENDALPHA:
4795 srcAlpha = blendop;
4796 break;
4797 case SVGA3D_RS_DSTBLENDALPHA:
4798 dstAlpha = blendop;
4799 break;
4800 default:
4801 /* not possible; shut up gcc */
4802 AssertFailed();
4803 break;
4804 }
4805
4806 if (pContext->state.aRenderState[SVGA3D_RS_SEPARATEALPHABLENDENABLE].uintValue != 0)
4807 pState->ext.glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
4808 else
4809 glBlendFunc(srcRGB, dstRGB);
4810 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4811 break;
4812 }
4813
4814 case SVGA3D_RS_BLENDEQUATIONALPHA: /* SVGA3dBlendEquation */
4815 case SVGA3D_RS_BLENDEQUATION: /* SVGA3dBlendEquation */
4816 if (pContext->state.aRenderState[SVGA3D_RS_SEPARATEALPHABLENDENABLE].uintValue != 0)
4817 {
4818 GLenum const modeRGB = vmsvga3dBlendEquation2GL(pContext->state.aRenderState[SVGA3D_RS_BLENDEQUATION].uintValue);
4819 GLenum const modeAlpha = vmsvga3dBlendEquation2GL(pContext->state.aRenderState[SVGA3D_RS_BLENDEQUATIONALPHA].uintValue);
4820 pState->ext.glBlendEquationSeparate(modeRGB, modeAlpha);
4821 }
4822 else
4823 {
4824#if VBOX_VMSVGA3D_GL_HACK_LEVEL >= 0x102
4825 glBlendEquation(vmsvga3dBlendEquation2GL(pRenderState[i].uintValue));
4826#else
4827 pState->ext.glBlendEquation(vmsvga3dBlendEquation2GL(pRenderState[i].uintValue));
4828#endif
4829 }
4830 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4831 break;
4832
4833 case SVGA3D_RS_BLENDCOLOR: /* SVGA3dColor */
4834 {
4835 GLfloat red, green, blue, alpha;
4836
4837 vmsvgaColor2GLFloatArray(pRenderState[i].uintValue, &red, &green, &blue, &alpha);
4838
4839#if VBOX_VMSVGA3D_GL_HACK_LEVEL >= 0x102
4840 glBlendColor(red, green, blue, alpha);
4841#else
4842 pState->ext.glBlendColor(red, green, blue, alpha);
4843#endif
4844 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4845 break;
4846 }
4847
4848 case SVGA3D_RS_CULLMODE: /* SVGA3dFace */
4849 {
4850 GLenum mode = GL_BACK; /* default for OpenGL */
4851
4852 switch (pRenderState[i].uintValue)
4853 {
4854 case SVGA3D_FACE_NONE:
4855 break;
4856 case SVGA3D_FACE_FRONT:
4857 mode = GL_FRONT;
4858 break;
4859 case SVGA3D_FACE_BACK:
4860 mode = GL_BACK;
4861 break;
4862 case SVGA3D_FACE_FRONT_BACK:
4863 mode = GL_FRONT_AND_BACK;
4864 break;
4865 default:
4866 AssertMsgFailedReturn(("Unexpected cull mode %d\n", pRenderState[i].uintValue), VERR_INTERNAL_ERROR);
4867 break;
4868 }
4869 enableCap = GL_CULL_FACE;
4870 if (pRenderState[i].uintValue != SVGA3D_FACE_NONE)
4871 {
4872 glCullFace(mode);
4873 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4874 val = 1;
4875 }
4876 else
4877 val = 0;
4878 break;
4879 }
4880
4881 case SVGA3D_RS_ZFUNC: /* SVGA3dCmpFunc */
4882 glDepthFunc(vmsvgaCmpFunc2GL(pRenderState[i].uintValue));
4883 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4884 break;
4885
4886 case SVGA3D_RS_ALPHAFUNC: /* SVGA3dCmpFunc */
4887 {
4888 GLclampf ref;
4889
4890 glGetFloatv(GL_ALPHA_TEST_REF, &ref);
4891 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4892 glAlphaFunc(vmsvgaCmpFunc2GL(pRenderState[i].uintValue), ref);
4893 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4894 break;
4895 }
4896
4897 case SVGA3D_RS_ALPHAREF: /* float (0.0 .. 1.0) */
4898 {
4899 GLint func;
4900
4901 glGetIntegerv(GL_ALPHA_TEST_FUNC, &func);
4902 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4903 glAlphaFunc(func, pRenderState[i].floatValue);
4904 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4905 break;
4906 }
4907
4908 case SVGA3D_RS_STENCILENABLE2SIDED: /* SVGA3dBool */
4909 {
4910 /* Refresh the stencil state based on the new enable setting.
4911 * This will take existing states and set them using either glStencil or glStencil*Separate.
4912 */
4913 static SVGA3dRenderStateName const saRefreshState[] =
4914 {
4915 SVGA3D_RS_STENCILFUNC,
4916 SVGA3D_RS_STENCILFAIL,
4917 SVGA3D_RS_CCWSTENCILFUNC,
4918 SVGA3D_RS_CCWSTENCILFAIL
4919 };
4920 SVGA3dRenderState renderstate[RT_ELEMENTS(saRefreshState)];
4921 for (uint32_t j = 0; j < RT_ELEMENTS(saRefreshState); ++j)
4922 {
4923 renderstate[j].state = saRefreshState[j];
4924 renderstate[j].uintValue = pContext->state.aRenderState[saRefreshState[j]].uintValue;
4925 }
4926
4927 rc = vmsvga3dBackSetRenderState(pThisCC, cid, RT_ELEMENTS(renderstate), renderstate);
4928 AssertRCReturn(rc, rc);
4929
4930 if (pContext->state.aRenderState[SVGA3D_RS_STENCILENABLE].uintValue != 0)
4931 continue; /* Ignore if stencil is enabled */
4932 /* Apply SVGA3D_RS_STENCILENABLE2SIDED as SVGA3D_RS_STENCILENABLE. */
4933 } RT_FALL_THRU();
4934
4935 case SVGA3D_RS_STENCILENABLE: /* SVGA3dBool */
4936 enableCap = GL_STENCIL_TEST;
4937 val = pRenderState[i].uintValue;
4938 break;
4939
4940 case SVGA3D_RS_STENCILFUNC: /* SVGA3dCmpFunc */
4941 case SVGA3D_RS_STENCILREF: /* uint32_t */
4942 case SVGA3D_RS_STENCILMASK: /* uint32_t */
4943 {
4944 GLint func, ref;
4945 GLuint mask;
4946
4947 /* Query current values to have all parameters for glStencilFunc[Separate]. */
4948 glGetIntegerv(GL_STENCIL_FUNC, &func);
4949 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4950 glGetIntegerv(GL_STENCIL_VALUE_MASK, (GLint *)&mask);
4951 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4952 glGetIntegerv(GL_STENCIL_REF, &ref);
4953 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4954
4955 /* Update the changed value. */
4956 switch (pRenderState[i].state)
4957 {
4958 case SVGA3D_RS_STENCILFUNC: /* SVGA3dCmpFunc */
4959 func = vmsvgaCmpFunc2GL(pRenderState[i].uintValue);
4960 break;
4961
4962 case SVGA3D_RS_STENCILREF: /* uint32_t */
4963 ref = pRenderState[i].uintValue;
4964 break;
4965
4966 case SVGA3D_RS_STENCILMASK: /* uint32_t */
4967 mask = pRenderState[i].uintValue;
4968 break;
4969
4970 default:
4971 /* not possible; shut up gcc */
4972 AssertFailed();
4973 break;
4974 }
4975
4976 if (pContext->state.aRenderState[SVGA3D_RS_STENCILENABLE2SIDED].uintValue != 0)
4977 {
4978 pState->ext.glStencilFuncSeparate(GL_FRONT, func, ref, mask);
4979 }
4980 else
4981 {
4982 glStencilFunc(func, ref, mask);
4983 }
4984 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4985 break;
4986 }
4987
4988 case SVGA3D_RS_STENCILWRITEMASK: /* uint32_t */
4989 glStencilMask(pRenderState[i].uintValue);
4990 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4991 break;
4992
4993 case SVGA3D_RS_STENCILFAIL: /* SVGA3dStencilOp */
4994 case SVGA3D_RS_STENCILZFAIL: /* SVGA3dStencilOp */
4995 case SVGA3D_RS_STENCILPASS: /* SVGA3dStencilOp */
4996 {
4997 GLint sfail, dpfail, dppass;
4998 GLenum const stencilop = vmsvgaStencipOp2GL(pRenderState[i].uintValue);
4999
5000 glGetIntegerv(GL_STENCIL_FAIL, &sfail);
5001 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5002 glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, &dpfail);
5003 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5004 glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, &dppass);
5005 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5006
5007 switch (pRenderState[i].state)
5008 {
5009 case SVGA3D_RS_STENCILFAIL: /* SVGA3dStencilOp */
5010 sfail = stencilop;
5011 break;
5012 case SVGA3D_RS_STENCILZFAIL: /* SVGA3dStencilOp */
5013 dpfail = stencilop;
5014 break;
5015 case SVGA3D_RS_STENCILPASS: /* SVGA3dStencilOp */
5016 dppass = stencilop;
5017 break;
5018 default:
5019 /* not possible; shut up gcc */
5020 AssertFailed();
5021 break;
5022 }
5023 if (pContext->state.aRenderState[SVGA3D_RS_STENCILENABLE2SIDED].uintValue != 0)
5024 {
5025 pState->ext.glStencilOpSeparate(GL_FRONT, sfail, dpfail, dppass);
5026 }
5027 else
5028 {
5029 glStencilOp(sfail, dpfail, dppass);
5030 }
5031 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5032 break;
5033 }
5034
5035 case SVGA3D_RS_CCWSTENCILFUNC: /* SVGA3dCmpFunc */
5036 {
5037 GLint ref;
5038 GLuint mask;
5039 GLint const func = vmsvgaCmpFunc2GL(pRenderState[i].uintValue);
5040
5041 /* GL_STENCIL_VALUE_MASK and GL_STENCIL_REF are the same for both GL_FRONT and GL_BACK. */
5042 glGetIntegerv(GL_STENCIL_VALUE_MASK, (GLint *)&mask);
5043 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5044 glGetIntegerv(GL_STENCIL_REF, &ref);
5045 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5046
5047 pState->ext.glStencilFuncSeparate(GL_BACK, func, ref, mask);
5048 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5049 break;
5050 }
5051
5052 case SVGA3D_RS_CCWSTENCILFAIL: /* SVGA3dStencilOp */
5053 case SVGA3D_RS_CCWSTENCILZFAIL: /* SVGA3dStencilOp */
5054 case SVGA3D_RS_CCWSTENCILPASS: /* SVGA3dStencilOp */
5055 {
5056 GLint sfail, dpfail, dppass;
5057 GLenum const stencilop = vmsvgaStencipOp2GL(pRenderState[i].uintValue);
5058
5059 glGetIntegerv(GL_STENCIL_BACK_FAIL, &sfail);
5060 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5061 glGetIntegerv(GL_STENCIL_BACK_PASS_DEPTH_FAIL, &dpfail);
5062 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5063 glGetIntegerv(GL_STENCIL_BACK_PASS_DEPTH_PASS, &dppass);
5064 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5065
5066 switch (pRenderState[i].state)
5067 {
5068 case SVGA3D_RS_CCWSTENCILFAIL: /* SVGA3dStencilOp */
5069 sfail = stencilop;
5070 break;
5071 case SVGA3D_RS_CCWSTENCILZFAIL: /* SVGA3dStencilOp */
5072 dpfail = stencilop;
5073 break;
5074 case SVGA3D_RS_CCWSTENCILPASS: /* SVGA3dStencilOp */
5075 dppass = stencilop;
5076 break;
5077 default:
5078 /* not possible; shut up gcc */
5079 AssertFailed();
5080 break;
5081 }
5082 pState->ext.glStencilOpSeparate(GL_BACK, sfail, dpfail, dppass);
5083 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5084 break;
5085 }
5086
5087 case SVGA3D_RS_ZBIAS: /* float */
5088 /** @todo unknown meaning; depth bias is not identical
5089 renderState = D3DRS_DEPTHBIAS;
5090 val = pRenderState[i].uintValue;
5091 */
5092 Log(("vmsvga3dSetRenderState: WARNING unsupported SVGA3D_RS_ZBIAS\n"));
5093 break;
5094
5095 case SVGA3D_RS_DEPTHBIAS: /* float */
5096 {
5097 GLfloat factor;
5098
5099 /** @todo not sure if the d3d & ogl definitions are identical. */
5100
5101 /* Do not change the factor part. */
5102 glGetFloatv(GL_POLYGON_OFFSET_FACTOR, &factor);
5103 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5104
5105 glPolygonOffset(factor, pRenderState[i].floatValue);
5106 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5107 break;
5108 }
5109
5110 case SVGA3D_RS_SLOPESCALEDEPTHBIAS: /* float */
5111 {
5112 GLfloat units;
5113
5114 /** @todo not sure if the d3d & ogl definitions are identical. */
5115
5116 /* Do not change the factor part. */
5117 glGetFloatv(GL_POLYGON_OFFSET_UNITS, &units);
5118 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5119
5120 glPolygonOffset(pRenderState[i].floatValue, units);
5121 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5122 break;
5123 }
5124
5125 case SVGA3D_RS_COLORWRITEENABLE: /* SVGA3dColorMask */
5126 {
5127 GLboolean red, green, blue, alpha;
5128 SVGA3dColorMask mask;
5129
5130 mask.uintValue = pRenderState[i].uintValue;
5131
5132 red = mask.red;
5133 green = mask.green;
5134 blue = mask.blue;
5135 alpha = mask.alpha;
5136
5137 glColorMask(red, green, blue, alpha);
5138 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5139 break;
5140 }
5141
5142 case SVGA3D_RS_COLORWRITEENABLE1: /* SVGA3dColorMask to D3DCOLORWRITEENABLE_* */
5143 case SVGA3D_RS_COLORWRITEENABLE2: /* SVGA3dColorMask to D3DCOLORWRITEENABLE_* */
5144 case SVGA3D_RS_COLORWRITEENABLE3: /* SVGA3dColorMask to D3DCOLORWRITEENABLE_* */
5145 Log(("vmsvga3dSetRenderState: WARNING SVGA3D_RS_COLORWRITEENABLEx not supported!!\n"));
5146 break;
5147
5148 case SVGA3D_RS_SCISSORTESTENABLE: /* SVGA3dBool */
5149 enableCap = GL_SCISSOR_TEST;
5150 val = pRenderState[i].uintValue;
5151 break;
5152
5153#if 0
5154 case SVGA3D_RS_DIFFUSEMATERIALSOURCE: /* SVGA3dVertexMaterial */
5155 AssertCompile(D3DMCS_COLOR2 == SVGA3D_VERTEXMATERIAL_SPECULAR);
5156 renderState = D3DRS_DIFFUSEMATERIALSOURCE;
5157 val = pRenderState[i].uintValue;
5158 break;
5159
5160 case SVGA3D_RS_SPECULARMATERIALSOURCE: /* SVGA3dVertexMaterial */
5161 renderState = D3DRS_SPECULARMATERIALSOURCE;
5162 val = pRenderState[i].uintValue;
5163 break;
5164
5165 case SVGA3D_RS_AMBIENTMATERIALSOURCE: /* SVGA3dVertexMaterial */
5166 renderState = D3DRS_AMBIENTMATERIALSOURCE;
5167 val = pRenderState[i].uintValue;
5168 break;
5169
5170 case SVGA3D_RS_EMISSIVEMATERIALSOURCE: /* SVGA3dVertexMaterial */
5171 renderState = D3DRS_EMISSIVEMATERIALSOURCE;
5172 val = pRenderState[i].uintValue;
5173 break;
5174#endif
5175
5176 case SVGA3D_RS_WRAP3: /* SVGA3dWrapFlags */
5177 case SVGA3D_RS_WRAP4: /* SVGA3dWrapFlags */
5178 case SVGA3D_RS_WRAP5: /* SVGA3dWrapFlags */
5179 case SVGA3D_RS_WRAP6: /* SVGA3dWrapFlags */
5180 case SVGA3D_RS_WRAP7: /* SVGA3dWrapFlags */
5181 case SVGA3D_RS_WRAP8: /* SVGA3dWrapFlags */
5182 case SVGA3D_RS_WRAP9: /* SVGA3dWrapFlags */
5183 case SVGA3D_RS_WRAP10: /* SVGA3dWrapFlags */
5184 case SVGA3D_RS_WRAP11: /* SVGA3dWrapFlags */
5185 case SVGA3D_RS_WRAP12: /* SVGA3dWrapFlags */
5186 case SVGA3D_RS_WRAP13: /* SVGA3dWrapFlags */
5187 case SVGA3D_RS_WRAP14: /* SVGA3dWrapFlags */
5188 case SVGA3D_RS_WRAP15: /* SVGA3dWrapFlags */
5189 Log(("vmsvga3dSetRenderState: WARNING unsupported SVGA3D_WRAPx (x >= 3)\n"));
5190 break;
5191
5192 case SVGA3D_RS_LASTPIXEL: /* SVGA3dBool */
5193 case SVGA3D_RS_TWEENFACTOR: /* float */
5194 case SVGA3D_RS_INDEXEDVERTEXBLENDENABLE: /* SVGA3dBool */
5195 case SVGA3D_RS_VERTEXBLEND: /* SVGA3dVertexBlendFlags */
5196 Log(("vmsvga3dSetRenderState: WARNING not applicable!!\n"));
5197 break;
5198
5199 case SVGA3D_RS_MULTISAMPLEANTIALIAS: /* SVGA3dBool */
5200 enableCap = GL_MULTISAMPLE;
5201 val = pRenderState[i].uintValue;
5202 break;
5203
5204 case SVGA3D_RS_MULTISAMPLEMASK: /* uint32_t */
5205 Log(("vmsvga3dSetRenderState: WARNING not applicable??!!\n"));
5206 break;
5207
5208 case SVGA3D_RS_COORDINATETYPE: /* SVGA3dCoordinateType */
5209 Assert(pRenderState[i].uintValue == SVGA3D_COORDINATE_LEFTHANDED);
5210 /** @todo setup a view matrix to scale the world space by -1 in the z-direction for right handed coordinates. */
5211 /*
5212 renderState = D3DRS_COORDINATETYPE;
5213 val = pRenderState[i].uintValue;
5214 */
5215 break;
5216
5217 case SVGA3D_RS_FRONTWINDING: /* SVGA3dFrontWinding */
5218 Assert(pRenderState[i].uintValue == SVGA3D_FRONTWINDING_CW);
5219 /* Invert the selected mode because of y-inversion (?) */
5220 glFrontFace((pRenderState[i].uintValue != SVGA3D_FRONTWINDING_CW) ? GL_CW : GL_CCW);
5221 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5222 break;
5223
5224 case SVGA3D_RS_OUTPUTGAMMA: /* float */
5225 //AssertFailed();
5226 /*
5227 D3DRS_SRGBWRITEENABLE ??
5228 renderState = D3DRS_OUTPUTGAMMA;
5229 val = pRenderState[i].uintValue;
5230 */
5231 break;
5232
5233#if 0
5234
5235 case SVGA3D_RS_VERTEXMATERIALENABLE: /* SVGA3dBool */
5236 //AssertFailed();
5237 renderState = D3DRS_INDEXEDVERTEXBLENDENABLE; /* correct?? */
5238 val = pRenderState[i].uintValue;
5239 break;
5240
5241 case SVGA3D_RS_TEXTUREFACTOR: /* SVGA3dColor */
5242 renderState = D3DRS_TEXTUREFACTOR;
5243 val = pRenderState[i].uintValue;
5244 break;
5245
5246 case SVGA3D_RS_LOCALVIEWER: /* SVGA3dBool */
5247 renderState = D3DRS_LOCALVIEWER;
5248 val = pRenderState[i].uintValue;
5249 break;
5250
5251 case SVGA3D_RS_ZVISIBLE: /* SVGA3dBool */
5252 AssertFailed();
5253 /*
5254 renderState = D3DRS_ZVISIBLE;
5255 val = pRenderState[i].uintValue;
5256 */
5257 break;
5258
5259 case SVGA3D_RS_CLIPPING: /* SVGA3dBool */
5260 renderState = D3DRS_CLIPPING;
5261 val = pRenderState[i].uintValue;
5262 break;
5263
5264 case SVGA3D_RS_WRAP0: /* SVGA3dWrapFlags */
5265 glTexParameter GL_TEXTURE_WRAP_S
5266 Assert(SVGA3D_WRAPCOORD_3 == D3DWRAPCOORD_3);
5267 renderState = D3DRS_WRAP0;
5268 val = pRenderState[i].uintValue;
5269 break;
5270
5271 case SVGA3D_RS_WRAP1: /* SVGA3dWrapFlags */
5272 glTexParameter GL_TEXTURE_WRAP_T
5273 renderState = D3DRS_WRAP1;
5274 val = pRenderState[i].uintValue;
5275 break;
5276
5277 case SVGA3D_RS_WRAP2: /* SVGA3dWrapFlags */
5278 glTexParameter GL_TEXTURE_WRAP_R
5279 renderState = D3DRS_WRAP2;
5280 val = pRenderState[i].uintValue;
5281 break;
5282
5283
5284 case SVGA3D_RS_SEPARATEALPHABLENDENABLE: /* SVGA3dBool */
5285 renderState = D3DRS_SEPARATEALPHABLENDENABLE;
5286 val = pRenderState[i].uintValue;
5287 break;
5288
5289
5290 case SVGA3D_RS_BLENDEQUATIONALPHA: /* SVGA3dBlendEquation */
5291 renderState = D3DRS_BLENDOPALPHA;
5292 val = pRenderState[i].uintValue;
5293 break;
5294
5295 case SVGA3D_RS_TRANSPARENCYANTIALIAS: /* SVGA3dTransparencyAntialiasType */
5296 AssertFailed();
5297 /*
5298 renderState = D3DRS_TRANSPARENCYANTIALIAS;
5299 val = pRenderState[i].uintValue;
5300 */
5301 break;
5302
5303#endif
5304 default:
5305 AssertFailed();
5306 break;
5307 }
5308
5309 if (enableCap != ~(GLenum)0)
5310 {
5311 if (val)
5312 glEnable(enableCap);
5313 else
5314 glDisable(enableCap);
5315 }
5316 }
5317
5318 return VINF_SUCCESS;
5319}
5320
5321static DECLCALLBACK(int) vmsvga3dBackSetRenderTarget(PVGASTATECC pThisCC, uint32_t cid, SVGA3dRenderTargetType type, SVGA3dSurfaceImageId target)
5322{
5323 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
5324
5325 AssertReturn(pState, VERR_NO_MEMORY);
5326 AssertReturn((unsigned)type < SVGA3D_RT_MAX, VERR_INVALID_PARAMETER);
5327
5328 LogFunc(("cid=%u type=%x sid=%u\n", cid, type, target.sid));
5329
5330 PVMSVGA3DCONTEXT pContext;
5331 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
5332 AssertRCReturn(rc, rc);
5333
5334 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5335
5336 /* Save for vm state save/restore. */
5337 pContext->state.aRenderTargets[type] = target.sid;
5338
5339 if (target.sid == SVGA3D_INVALID_ID)
5340 {
5341 /* Disable render target. */
5342 switch (type)
5343 {
5344 case SVGA3D_RT_DEPTH:
5345 case SVGA3D_RT_STENCIL:
5346 pState->ext.glFramebufferRenderbuffer(GL_FRAMEBUFFER, (type == SVGA3D_RT_DEPTH) ? GL_DEPTH_ATTACHMENT : GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0);
5347 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5348 break;
5349
5350 case SVGA3D_RT_COLOR0:
5351 case SVGA3D_RT_COLOR1:
5352 case SVGA3D_RT_COLOR2:
5353 case SVGA3D_RT_COLOR3:
5354 case SVGA3D_RT_COLOR4:
5355 case SVGA3D_RT_COLOR5:
5356 case SVGA3D_RT_COLOR6:
5357 case SVGA3D_RT_COLOR7:
5358 pState->ext.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + type - SVGA3D_RT_COLOR0, 0, 0, 0);
5359 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5360 break;
5361
5362 default:
5363 AssertFailedReturn(VERR_INVALID_PARAMETER);
5364 }
5365 return VINF_SUCCESS;
5366 }
5367
5368 PVMSVGA3DSURFACE pRenderTarget;
5369 rc = vmsvga3dSurfaceFromSid(pState, target.sid, &pRenderTarget);
5370 AssertRCReturn(rc, rc);
5371
5372 switch (type)
5373 {
5374 case SVGA3D_RT_DEPTH:
5375 case SVGA3D_RT_STENCIL:
5376#if 1
5377 /* A texture surface can be used as a render target to fill it and later on used as a texture. */
5378 if (pRenderTarget->oglId.texture == OPENGL_INVALID_ID)
5379 {
5380 LogFunc(("create depth texture to be used as render target; surface id=%x type=%d format=%d -> create texture\n",
5381 target.sid, pRenderTarget->f.s.surface1Flags, pRenderTarget->format));
5382 rc = vmsvga3dBackCreateTexture(pThisCC, pContext, cid, pRenderTarget);
5383 AssertRCReturn(rc, rc);
5384 }
5385
5386 AssertReturn(pRenderTarget->oglId.texture != OPENGL_INVALID_ID, VERR_INVALID_PARAMETER);
5387 Assert(!pRenderTarget->fDirty);
5388
5389 pRenderTarget->f.s.surface1Flags |= SVGA3D_SURFACE_HINT_DEPTHSTENCIL;
5390
5391 pState->ext.glFramebufferTexture2D(GL_FRAMEBUFFER,
5392 (type == SVGA3D_RT_DEPTH) ? GL_DEPTH_ATTACHMENT : GL_STENCIL_ATTACHMENT,
5393 GL_TEXTURE_2D, pRenderTarget->oglId.texture, target.mipmap);
5394 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5395#else
5396 AssertReturn(target.mipmap == 0, VERR_INVALID_PARAMETER);
5397 if (pRenderTarget->oglId.texture == OPENGL_INVALID_ID)
5398 {
5399 Log(("vmsvga3dSetRenderTarget: create renderbuffer to be used as render target; surface id=%x type=%d format=%d\n", target.sid, pRenderTarget->f.s.surface1Flags, pRenderTarget->internalFormatGL));
5400 pContext = &pState->SharedCtx;
5401 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5402
5403 pState->ext.glGenRenderbuffers(1, &pRenderTarget->oglId.renderbuffer);
5404 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5405 pSurface->enmOGLResType = VMSVGA3D_OGLRESTYPE_RENDERBUFFER;
5406
5407 pState->ext.glBindRenderbuffer(GL_RENDERBUFFER, pRenderTarget->oglId.renderbuffer);
5408 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5409
5410 pState->ext.glRenderbufferStorage(GL_RENDERBUFFER,
5411 pRenderTarget->internalFormatGL,
5412 pRenderTarget->paMipmapLevels[0].mipmapSize.width,
5413 pRenderTarget->paMipmapLevels[0].mipmapSize.height);
5414 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5415
5416 pState->ext.glBindRenderbuffer(GL_RENDERBUFFER, OPENGL_INVALID_ID);
5417 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5418
5419 pContext = pState->papContexts[cid];
5420 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5421 }
5422
5423 pState->ext.glBindRenderbuffer(GL_RENDERBUFFER, pRenderTarget->oglId.renderbuffer);
5424 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5425 Assert(!pRenderTarget->fDirty);
5426 AssertReturn(pRenderTarget->oglId.texture != OPENGL_INVALID_ID, VERR_INVALID_PARAMETER);
5427
5428 pRenderTarget->f.s.surface1Flags |= SVGA3D_SURFACE_HINT_DEPTHSTENCIL;
5429
5430 pState->ext.glFramebufferRenderbuffer(GL_FRAMEBUFFER,
5431 (type == SVGA3D_RT_DEPTH) ? GL_DEPTH_ATTACHMENT : GL_STENCIL_ATTACHMENT,
5432 GL_RENDERBUFFER, pRenderTarget->oglId.renderbuffer);
5433 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5434#endif
5435 break;
5436
5437 case SVGA3D_RT_COLOR0:
5438 case SVGA3D_RT_COLOR1:
5439 case SVGA3D_RT_COLOR2:
5440 case SVGA3D_RT_COLOR3:
5441 case SVGA3D_RT_COLOR4:
5442 case SVGA3D_RT_COLOR5:
5443 case SVGA3D_RT_COLOR6:
5444 case SVGA3D_RT_COLOR7:
5445 {
5446 /* A texture surface can be used as a render target to fill it and later on used as a texture. */
5447 if (pRenderTarget->oglId.texture == OPENGL_INVALID_ID)
5448 {
5449 Log(("vmsvga3dSetRenderTarget: create texture to be used as render target; surface id=%x type=%d format=%d -> create texture\n", target.sid, pRenderTarget->f.s.surface1Flags, pRenderTarget->format));
5450 rc = vmsvga3dBackCreateTexture(pThisCC, pContext, cid, pRenderTarget);
5451 AssertRCReturn(rc, rc);
5452 }
5453
5454 AssertReturn(pRenderTarget->oglId.texture != OPENGL_INVALID_ID, VERR_INVALID_PARAMETER);
5455 Assert(!pRenderTarget->fDirty);
5456
5457 pRenderTarget->f.s.surface1Flags |= SVGA3D_SURFACE_HINT_RENDERTARGET;
5458
5459 GLenum textarget;
5460 if (pRenderTarget->f.s.surface1Flags & SVGA3D_SURFACE_CUBEMAP)
5461 textarget = vmsvga3dCubemapFaceFromIndex(target.face);
5462 else
5463 textarget = GL_TEXTURE_2D;
5464 pState->ext.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + type - SVGA3D_RT_COLOR0,
5465 textarget, pRenderTarget->oglId.texture, target.mipmap);
5466 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5467
5468#ifdef DEBUG
5469 GLenum status = pState->ext.glCheckFramebufferStatus(GL_FRAMEBUFFER);
5470 if (status != GL_FRAMEBUFFER_COMPLETE)
5471 Log(("vmsvga3dSetRenderTarget: WARNING: glCheckFramebufferStatus returned %x\n", status));
5472#endif
5473 /** @todo use glDrawBuffers too? */
5474 break;
5475 }
5476
5477 default:
5478 AssertFailedReturn(VERR_INVALID_PARAMETER);
5479 }
5480
5481 return VINF_SUCCESS;
5482}
5483
5484#if 0
5485/**
5486 * Convert SVGA texture combiner value to its D3D equivalent
5487 */
5488static DWORD vmsvga3dTextureCombiner2D3D(uint32_t value)
5489{
5490 switch (value)
5491 {
5492 case SVGA3D_TC_DISABLE:
5493 return D3DTOP_DISABLE;
5494 case SVGA3D_TC_SELECTARG1:
5495 return D3DTOP_SELECTARG1;
5496 case SVGA3D_TC_SELECTARG2:
5497 return D3DTOP_SELECTARG2;
5498 case SVGA3D_TC_MODULATE:
5499 return D3DTOP_MODULATE;
5500 case SVGA3D_TC_ADD:
5501 return D3DTOP_ADD;
5502 case SVGA3D_TC_ADDSIGNED:
5503 return D3DTOP_ADDSIGNED;
5504 case SVGA3D_TC_SUBTRACT:
5505 return D3DTOP_SUBTRACT;
5506 case SVGA3D_TC_BLENDTEXTUREALPHA:
5507 return D3DTOP_BLENDTEXTUREALPHA;
5508 case SVGA3D_TC_BLENDDIFFUSEALPHA:
5509 return D3DTOP_BLENDDIFFUSEALPHA;
5510 case SVGA3D_TC_BLENDCURRENTALPHA:
5511 return D3DTOP_BLENDCURRENTALPHA;
5512 case SVGA3D_TC_BLENDFACTORALPHA:
5513 return D3DTOP_BLENDFACTORALPHA;
5514 case SVGA3D_TC_MODULATE2X:
5515 return D3DTOP_MODULATE2X;
5516 case SVGA3D_TC_MODULATE4X:
5517 return D3DTOP_MODULATE4X;
5518 case SVGA3D_TC_DSDT:
5519 AssertFailed(); /** @todo ??? */
5520 return D3DTOP_DISABLE;
5521 case SVGA3D_TC_DOTPRODUCT3:
5522 return D3DTOP_DOTPRODUCT3;
5523 case SVGA3D_TC_BLENDTEXTUREALPHAPM:
5524 return D3DTOP_BLENDTEXTUREALPHAPM;
5525 case SVGA3D_TC_ADDSIGNED2X:
5526 return D3DTOP_ADDSIGNED2X;
5527 case SVGA3D_TC_ADDSMOOTH:
5528 return D3DTOP_ADDSMOOTH;
5529 case SVGA3D_TC_PREMODULATE:
5530 return D3DTOP_PREMODULATE;
5531 case SVGA3D_TC_MODULATEALPHA_ADDCOLOR:
5532 return D3DTOP_MODULATEALPHA_ADDCOLOR;
5533 case SVGA3D_TC_MODULATECOLOR_ADDALPHA:
5534 return D3DTOP_MODULATECOLOR_ADDALPHA;
5535 case SVGA3D_TC_MODULATEINVALPHA_ADDCOLOR:
5536 return D3DTOP_MODULATEINVALPHA_ADDCOLOR;
5537 case SVGA3D_TC_MODULATEINVCOLOR_ADDALPHA:
5538 return D3DTOP_MODULATEINVCOLOR_ADDALPHA;
5539 case SVGA3D_TC_BUMPENVMAPLUMINANCE:
5540 return D3DTOP_BUMPENVMAPLUMINANCE;
5541 case SVGA3D_TC_MULTIPLYADD:
5542 return D3DTOP_MULTIPLYADD;
5543 case SVGA3D_TC_LERP:
5544 return D3DTOP_LERP;
5545 default:
5546 AssertFailed();
5547 return D3DTOP_DISABLE;
5548 }
5549}
5550
5551/**
5552 * Convert SVGA texture arg data value to its D3D equivalent
5553 */
5554static DWORD vmsvga3dTextureArgData2D3D(uint32_t value)
5555{
5556 switch (value)
5557 {
5558 case SVGA3D_TA_CONSTANT:
5559 return D3DTA_CONSTANT;
5560 case SVGA3D_TA_PREVIOUS:
5561 return D3DTA_CURRENT; /* current = previous */
5562 case SVGA3D_TA_DIFFUSE:
5563 return D3DTA_DIFFUSE;
5564 case SVGA3D_TA_TEXTURE:
5565 return D3DTA_TEXTURE;
5566 case SVGA3D_TA_SPECULAR:
5567 return D3DTA_SPECULAR;
5568 default:
5569 AssertFailed();
5570 return 0;
5571 }
5572}
5573
5574/**
5575 * Convert SVGA texture transform flag value to its D3D equivalent
5576 */
5577static DWORD vmsvga3dTextTransformFlags2D3D(uint32_t value)
5578{
5579 switch (value)
5580 {
5581 case SVGA3D_TEX_TRANSFORM_OFF:
5582 return D3DTTFF_DISABLE;
5583 case SVGA3D_TEX_TRANSFORM_S:
5584 return D3DTTFF_COUNT1; /** @todo correct? */
5585 case SVGA3D_TEX_TRANSFORM_T:
5586 return D3DTTFF_COUNT2; /** @todo correct? */
5587 case SVGA3D_TEX_TRANSFORM_R:
5588 return D3DTTFF_COUNT3; /** @todo correct? */
5589 case SVGA3D_TEX_TRANSFORM_Q:
5590 return D3DTTFF_COUNT4; /** @todo correct? */
5591 case SVGA3D_TEX_PROJECTED:
5592 return D3DTTFF_PROJECTED;
5593 default:
5594 AssertFailed();
5595 return 0;
5596 }
5597}
5598#endif
5599
5600static GLenum vmsvga3dTextureAddress2OGL(SVGA3dTextureAddress value)
5601{
5602 switch (value)
5603 {
5604 case SVGA3D_TEX_ADDRESS_WRAP:
5605 return GL_REPEAT;
5606 case SVGA3D_TEX_ADDRESS_MIRROR:
5607 return GL_MIRRORED_REPEAT;
5608 case SVGA3D_TEX_ADDRESS_CLAMP:
5609 return GL_CLAMP_TO_EDGE;
5610 case SVGA3D_TEX_ADDRESS_BORDER:
5611 return GL_CLAMP_TO_BORDER;
5612 case SVGA3D_TEX_ADDRESS_MIRRORONCE:
5613 AssertFailed();
5614 return GL_CLAMP_TO_EDGE_SGIS; /** @todo correct? */
5615
5616 case SVGA3D_TEX_ADDRESS_EDGE:
5617 case SVGA3D_TEX_ADDRESS_INVALID:
5618 default:
5619 AssertFailed();
5620 return GL_REPEAT; /* default */
5621 }
5622}
5623
5624static GLenum vmsvga3dTextureFilter2OGL(SVGA3dTextureFilter value)
5625{
5626 switch (value)
5627 {
5628 case SVGA3D_TEX_FILTER_NONE:
5629 case SVGA3D_TEX_FILTER_LINEAR:
5630 case SVGA3D_TEX_FILTER_ANISOTROPIC: /* Anisotropic filtering is controlled by SVGA3D_TS_TEXTURE_ANISOTROPIC_LEVEL */
5631 return GL_LINEAR;
5632 case SVGA3D_TEX_FILTER_NEAREST:
5633 return GL_NEAREST;
5634 case SVGA3D_TEX_FILTER_FLATCUBIC: // Deprecated, not implemented
5635 case SVGA3D_TEX_FILTER_GAUSSIANCUBIC: // Deprecated, not implemented
5636 case SVGA3D_TEX_FILTER_PYRAMIDALQUAD: // Not currently implemented
5637 case SVGA3D_TEX_FILTER_GAUSSIANQUAD: // Not currently implemented
5638 default:
5639 AssertFailed();
5640 return GL_LINEAR; /* default */
5641 }
5642}
5643
5644uint32_t vmsvga3dSVGA3dColor2RGBA(SVGA3dColor value)
5645{
5646 /* flip the red and blue bytes */
5647 uint8_t blue = value & 0xff;
5648 uint8_t red = (value >> 16) & 0xff;
5649 return (value & 0xff00ff00) | red | (blue << 16);
5650}
5651
5652static DECLCALLBACK(int) vmsvga3dBackSetTextureState(PVGASTATECC pThisCC, uint32_t cid, uint32_t cTextureStates, SVGA3dTextureState *pTextureState)
5653{
5654 GLenum val = ~(GLenum)0; /* Shut up MSC. */
5655 GLenum currentStage = ~(GLenum)0;
5656 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
5657 AssertReturn(pState, VERR_NO_MEMORY);
5658
5659 Log(("vmsvga3dSetTextureState %x cTextureState=%d\n", cid, cTextureStates));
5660
5661 PVMSVGA3DCONTEXT pContext;
5662 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
5663 AssertRCReturn(rc, rc);
5664
5665 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5666
5667 /* Which texture is active for the current stage. Needed to use right OpenGL target when setting parameters. */
5668 PVMSVGA3DSURFACE pCurrentTextureSurface = NULL;
5669
5670 for (uint32_t i = 0; i < cTextureStates; ++i)
5671 {
5672 GLenum textureType = ~(GLenum)0;
5673#if 0
5674 GLenum samplerType = ~(GLenum)0;
5675#endif
5676
5677 LogFunc(("cid=%u stage=%d type=%s (%x) val=%x\n",
5678 cid, pTextureState[i].stage, vmsvga3dTextureStateToString(pTextureState[i].name), pTextureState[i].name, pTextureState[i].value));
5679
5680 /* Record the texture state for vm state saving. */
5681 if ( pTextureState[i].stage < RT_ELEMENTS(pContext->state.aTextureStates)
5682 && (unsigned)pTextureState[i].name < RT_ELEMENTS(pContext->state.aTextureStates[0]))
5683 {
5684 pContext->state.aTextureStates[pTextureState[i].stage][pTextureState[i].name] = pTextureState[i];
5685 }
5686
5687 /* Activate the right texture unit for subsequent texture state changes. */
5688 if (pTextureState[i].stage != currentStage || i == 0)
5689 {
5690 /** @todo Is this the appropriate limit for all kinds of textures? It is the
5691 * size of aSidActiveTextures and for binding/unbinding we cannot exceed it. */
5692 if (pTextureState[i].stage < RT_ELEMENTS(pContext->state.aTextureStates))
5693 {
5694 pState->ext.glActiveTexture(GL_TEXTURE0 + pTextureState[i].stage);
5695 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5696 currentStage = pTextureState[i].stage;
5697 }
5698 else
5699 {
5700 AssertMsgFailed(("pTextureState[%d].stage=%#x name=%#x\n", i, pTextureState[i].stage, pTextureState[i].name));
5701 continue;
5702 }
5703
5704 if (pContext->aSidActiveTextures[currentStage] != SVGA3D_INVALID_ID)
5705 {
5706 rc = vmsvga3dSurfaceFromSid(pState, pContext->aSidActiveTextures[currentStage], &pCurrentTextureSurface);
5707 AssertRCReturn(rc, rc);
5708 }
5709 else
5710 pCurrentTextureSurface = NULL; /* Make sure that no stale pointer is used. */
5711 }
5712
5713 switch (pTextureState[i].name)
5714 {
5715 case SVGA3D_TS_BUMPENVMAT00: /* float */
5716 case SVGA3D_TS_BUMPENVMAT01: /* float */
5717 case SVGA3D_TS_BUMPENVMAT10: /* float */
5718 case SVGA3D_TS_BUMPENVMAT11: /* float */
5719 case SVGA3D_TS_BUMPENVLSCALE: /* float */
5720 case SVGA3D_TS_BUMPENVLOFFSET: /* float */
5721 Log(("vmsvga3dSetTextureState: bump mapping texture options not supported!!\n"));
5722 break;
5723
5724 case SVGA3D_TS_COLOROP: /* SVGA3dTextureCombiner */
5725 case SVGA3D_TS_COLORARG0: /* SVGA3dTextureArgData */
5726 case SVGA3D_TS_COLORARG1: /* SVGA3dTextureArgData */
5727 case SVGA3D_TS_COLORARG2: /* SVGA3dTextureArgData */
5728 case SVGA3D_TS_ALPHAOP: /* SVGA3dTextureCombiner */
5729 case SVGA3D_TS_ALPHAARG0: /* SVGA3dTextureArgData */
5730 case SVGA3D_TS_ALPHAARG1: /* SVGA3dTextureArgData */
5731 case SVGA3D_TS_ALPHAARG2: /* SVGA3dTextureArgData */
5732 /** @todo not used by MesaGL */
5733 Log(("vmsvga3dSetTextureState: colorop/alphaop not yet supported!!\n"));
5734 break;
5735#if 0
5736
5737 case SVGA3D_TS_TEXCOORDINDEX: /* uint32_t */
5738 textureType = D3DTSS_TEXCOORDINDEX;
5739 val = pTextureState[i].value;
5740 break;
5741
5742 case SVGA3D_TS_TEXTURETRANSFORMFLAGS: /* SVGA3dTexTransformFlags */
5743 textureType = D3DTSS_TEXTURETRANSFORMFLAGS;
5744 val = vmsvga3dTextTransformFlags2D3D(pTextureState[i].value);
5745 break;
5746#endif
5747
5748 case SVGA3D_TS_BIND_TEXTURE: /* SVGA3dSurfaceId */
5749 {
5750 uint32_t const sid = pTextureState[i].value;
5751
5752 Log(("SVGA3D_TS_BIND_TEXTURE: stage %d, texture sid=%u replacing sid=%u\n",
5753 currentStage, sid, pContext->aSidActiveTextures[currentStage]));
5754
5755 /* Only if texture actually changed. */ /// @todo needs testing.
5756 if (pContext->aSidActiveTextures[currentStage] != sid)
5757 {
5758 if (pCurrentTextureSurface)
5759 {
5760 /* Unselect the currently associated texture. */
5761 glBindTexture(pCurrentTextureSurface->targetGL, 0);
5762 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5763
5764 if (currentStage < 8)
5765 {
5766 /* Necessary for the fixed pipeline. */
5767 glDisable(pCurrentTextureSurface->targetGL);
5768 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5769 }
5770
5771 pCurrentTextureSurface = NULL;
5772 }
5773
5774 if (sid == SVGA3D_INVALID_ID)
5775 {
5776 Assert(pCurrentTextureSurface == NULL);
5777 }
5778 else
5779 {
5780 PVMSVGA3DSURFACE pSurface;
5781 rc = vmsvga3dSurfaceFromSid(pState, sid, &pSurface);
5782 AssertRCReturn(rc, rc);
5783
5784 Log(("SVGA3D_TS_BIND_TEXTURE: stage %d, texture sid=%u (%d,%d) replacing sid=%u\n",
5785 currentStage, sid, pSurface->paMipmapLevels[0].mipmapSize.width,
5786 pSurface->paMipmapLevels[0].mipmapSize.height, pContext->aSidActiveTextures[currentStage]));
5787
5788 if (pSurface->oglId.texture == OPENGL_INVALID_ID)
5789 {
5790 Log(("CreateTexture (%d,%d) levels=%d\n",
5791 pSurface->paMipmapLevels[0].mipmapSize.width, pSurface->paMipmapLevels[0].mipmapSize.height, pSurface->cLevels));
5792 rc = vmsvga3dBackCreateTexture(pThisCC, pContext, cid, pSurface);
5793 AssertRCReturn(rc, rc);
5794 }
5795
5796 glBindTexture(pSurface->targetGL, pSurface->oglId.texture);
5797 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5798
5799 if (currentStage < 8)
5800 {
5801 /* Necessary for the fixed pipeline. */
5802 glEnable(pSurface->targetGL);
5803 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5804 }
5805
5806 /* Remember the currently active texture. */
5807 pCurrentTextureSurface = pSurface;
5808
5809 /* Recreate the texture state as glBindTexture resets them all (sigh). */
5810 for (uint32_t iStage = 0; iStage < RT_ELEMENTS(pContext->state.aTextureStates); iStage++)
5811 {
5812 for (uint32_t j = 0; j < RT_ELEMENTS(pContext->state.aTextureStates[0]); j++)
5813 {
5814 SVGA3dTextureState *pTextureStateIter = &pContext->state.aTextureStates[iStage][j];
5815
5816 if ( pTextureStateIter->name != SVGA3D_TS_INVALID
5817 && pTextureStateIter->name != SVGA3D_TS_BIND_TEXTURE)
5818 vmsvga3dBackSetTextureState(pThisCC, pContext->id, 1, pTextureStateIter);
5819 }
5820 }
5821 }
5822
5823 pContext->aSidActiveTextures[currentStage] = sid;
5824 }
5825
5826 /* Finished; continue with the next one. */
5827 continue;
5828 }
5829
5830 case SVGA3D_TS_ADDRESSW: /* SVGA3dTextureAddress */
5831 textureType = GL_TEXTURE_WRAP_R; /* R = W */
5832 val = vmsvga3dTextureAddress2OGL((SVGA3dTextureAddress)pTextureState[i].value);
5833 break;
5834
5835 case SVGA3D_TS_ADDRESSU: /* SVGA3dTextureAddress */
5836 textureType = GL_TEXTURE_WRAP_S; /* S = U */
5837 val = vmsvga3dTextureAddress2OGL((SVGA3dTextureAddress)pTextureState[i].value);
5838 break;
5839
5840 case SVGA3D_TS_ADDRESSV: /* SVGA3dTextureAddress */
5841 textureType = GL_TEXTURE_WRAP_T; /* T = V */
5842 val = vmsvga3dTextureAddress2OGL((SVGA3dTextureAddress)pTextureState[i].value);
5843 break;
5844
5845 case SVGA3D_TS_MIPFILTER: /* SVGA3dTextureFilter */
5846 case SVGA3D_TS_MINFILTER: /* SVGA3dTextureFilter */
5847 {
5848 uint32_t mipFilter = pContext->state.aTextureStates[currentStage][SVGA3D_TS_MIPFILTER].value;
5849 uint32_t minFilter = pContext->state.aTextureStates[currentStage][SVGA3D_TS_MINFILTER].value;
5850
5851 /* If SVGA3D_TS_MIPFILTER is set to NONE, then use SVGA3D_TS_MIPFILTER, otherwise SVGA3D_TS_MIPFILTER enables mipmap minification. */
5852 textureType = GL_TEXTURE_MIN_FILTER;
5853 if (mipFilter != SVGA3D_TEX_FILTER_NONE)
5854 {
5855 if (minFilter == SVGA3D_TEX_FILTER_NEAREST)
5856 {
5857 if (mipFilter == SVGA3D_TEX_FILTER_LINEAR)
5858 val = GL_NEAREST_MIPMAP_LINEAR;
5859 else
5860 val = GL_NEAREST_MIPMAP_NEAREST;
5861 }
5862 else
5863 {
5864 if (mipFilter == SVGA3D_TEX_FILTER_LINEAR)
5865 val = GL_LINEAR_MIPMAP_LINEAR;
5866 else
5867 val = GL_LINEAR_MIPMAP_NEAREST;
5868 }
5869 }
5870 else
5871 val = vmsvga3dTextureFilter2OGL((SVGA3dTextureFilter)minFilter);
5872 break;
5873 }
5874
5875 case SVGA3D_TS_MAGFILTER: /* SVGA3dTextureFilter */
5876 textureType = GL_TEXTURE_MAG_FILTER;
5877 val = vmsvga3dTextureFilter2OGL((SVGA3dTextureFilter)pTextureState[i].value);
5878 Assert(val == GL_NEAREST || val == GL_LINEAR);
5879 break;
5880
5881 case SVGA3D_TS_BORDERCOLOR: /* SVGA3dColor */
5882 {
5883 GLfloat color[4]; /* red, green, blue, alpha */
5884 vmsvgaColor2GLFloatArray(pTextureState[i].value, &color[0], &color[1], &color[2], &color[3]);
5885
5886 GLenum targetGL;
5887 if (pCurrentTextureSurface)
5888 targetGL = pCurrentTextureSurface->targetGL;
5889 else
5890 {
5891 /* No texture bound, assume 2D. */
5892 targetGL = GL_TEXTURE_2D;
5893 }
5894
5895 glTexParameterfv(targetGL, GL_TEXTURE_BORDER_COLOR, color); /* Identical; default 0.0 identical too */
5896 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5897 break;
5898 }
5899
5900 case SVGA3D_TS_TEXTURE_LOD_BIAS: /* float */
5901 {
5902 GLenum targetGL;
5903 if (pCurrentTextureSurface)
5904 targetGL = pCurrentTextureSurface->targetGL;
5905 else
5906 {
5907 /* No texture bound, assume 2D. */
5908 targetGL = GL_TEXTURE_2D;
5909 }
5910
5911 glTexParameterf(targetGL, GL_TEXTURE_LOD_BIAS, pTextureState[i].floatValue); /* Identical; default 0.0 identical too */
5912 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5913 break;
5914 }
5915
5916 case SVGA3D_TS_TEXTURE_MIPMAP_LEVEL: /* uint32_t */
5917 textureType = GL_TEXTURE_BASE_LEVEL;
5918 val = pTextureState[i].value;
5919 break;
5920
5921 case SVGA3D_TS_TEXTURE_ANISOTROPIC_LEVEL: /* uint32_t */
5922 if (pState->caps.fTextureFilterAnisotropicSupported)
5923 {
5924 textureType = GL_TEXTURE_MAX_ANISOTROPY_EXT;
5925 val = RT_MIN((GLint)pTextureState[i].value, pState->caps.maxTextureAnisotropy);
5926 } /* otherwise ignore. */
5927 break;
5928
5929#if 0
5930 case SVGA3D_TS_GAMMA: /* float */
5931 samplerType = D3DSAMP_SRGBTEXTURE;
5932 /* Boolean in D3D */
5933 if (pTextureState[i].floatValue == 1.0f)
5934 val = FALSE;
5935 else
5936 val = TRUE;
5937 break;
5938#endif
5939 /* Internal commands, that don't map directly to the SetTextureStageState API. */
5940 case SVGA3D_TS_TEXCOORDGEN: /* SVGA3dTextureCoordGen */
5941 AssertFailed();
5942 break;
5943
5944 default:
5945 //AssertFailed();
5946 break;
5947 }
5948
5949 if (textureType != ~(GLenum)0)
5950 {
5951 GLenum targetGL;
5952 if (pCurrentTextureSurface)
5953 targetGL = pCurrentTextureSurface->targetGL;
5954 else
5955 {
5956 /* No texture bound, assume 2D. */
5957 targetGL = GL_TEXTURE_2D;
5958 }
5959
5960 switch (pTextureState[i].name)
5961 {
5962 case SVGA3D_TS_MINFILTER:
5963 case SVGA3D_TS_MAGFILTER:
5964 {
5965 if (pState->caps.fTextureFilterAnisotropicSupported)
5966 {
5967 uint32_t const anisotropyLevel = (SVGA3dTextureFilter)pTextureState[i].value == SVGA3D_TEX_FILTER_ANISOTROPIC
5968 ? RT_MAX(1, pContext->state.aTextureStates[currentStage][SVGA3D_TS_TEXTURE_ANISOTROPIC_LEVEL].value)
5969 : 1;
5970 glTexParameteri(targetGL, GL_TEXTURE_MAX_ANISOTROPY_EXT, RT_MIN((GLint)anisotropyLevel, pState->caps.maxTextureAnisotropy));
5971 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5972 }
5973 } break;
5974
5975 default: break;
5976 }
5977
5978 glTexParameteri(targetGL, textureType, val);
5979 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5980 }
5981 }
5982
5983 return VINF_SUCCESS;
5984}
5985
5986static DECLCALLBACK(int) vmsvga3dBackSetMaterial(PVGASTATECC pThisCC, uint32_t cid, SVGA3dFace face, SVGA3dMaterial *pMaterial)
5987{
5988 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
5989 AssertReturn(pState, VERR_NO_MEMORY);
5990
5991 LogFunc(("cid=%u face %d\n", cid, face));
5992
5993 PVMSVGA3DCONTEXT pContext;
5994 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
5995 AssertRCReturn(rc, rc);
5996
5997 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5998
5999 GLenum oglFace;
6000 switch (face)
6001 {
6002 case SVGA3D_FACE_NONE:
6003 case SVGA3D_FACE_FRONT:
6004 oglFace = GL_FRONT;
6005 break;
6006
6007 case SVGA3D_FACE_BACK:
6008 oglFace = GL_BACK;
6009 break;
6010
6011 case SVGA3D_FACE_FRONT_BACK:
6012 oglFace = GL_FRONT_AND_BACK;
6013 break;
6014
6015 default:
6016 AssertFailedReturn(VERR_INVALID_PARAMETER);
6017 }
6018
6019 /* Save for vm state save/restore. */
6020 pContext->state.aMaterial[face].fValid = true;
6021 pContext->state.aMaterial[face].material = *pMaterial;
6022 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_MATERIAL;
6023
6024 glMaterialfv(oglFace, GL_DIFFUSE, pMaterial->diffuse);
6025 glMaterialfv(oglFace, GL_AMBIENT, pMaterial->ambient);
6026 glMaterialfv(oglFace, GL_SPECULAR, pMaterial->specular);
6027 glMaterialfv(oglFace, GL_EMISSION, pMaterial->emissive);
6028 glMaterialfv(oglFace, GL_SHININESS, &pMaterial->shininess);
6029 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6030
6031 return VINF_SUCCESS;
6032}
6033
6034/** @todo Move into separate library as we are using logic from Wine here. */
6035static DECLCALLBACK(int) vmsvga3dBackSetLightData(PVGASTATECC pThisCC, uint32_t cid, uint32_t index, SVGA3dLightData *pData)
6036{
6037 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6038 AssertReturn(pState, VERR_NO_MEMORY);
6039
6040 LogFunc(("vmsvga3dSetLightData cid=%u index=%d type=%d\n", cid, index, pData->type));
6041 ASSERT_GUEST_RETURN(index < SVGA3D_MAX_LIGHTS, VERR_INVALID_PARAMETER);
6042
6043 PVMSVGA3DCONTEXT pContext;
6044 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6045 AssertRCReturn(rc, rc);
6046
6047 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6048
6049 /* Store for vm state save/restore */
6050 pContext->state.aLightData[index].fValidData = true;
6051 pContext->state.aLightData[index].data = *pData;
6052
6053 if ( pData->attenuation0 < 0.0f
6054 || pData->attenuation1 < 0.0f
6055 || pData->attenuation2 < 0.0f)
6056 {
6057 Log(("vmsvga3dSetLightData: invalid negative attenuation values!!\n"));
6058 return VINF_SUCCESS; /* ignore; could crash the GL driver */
6059 }
6060
6061 /* Light settings are affected by the model view in OpenGL, the View transform in direct3d */
6062 glMatrixMode(GL_MODELVIEW);
6063 glPushMatrix();
6064 glLoadMatrixf(pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].matrix);
6065
6066 glLightfv(GL_LIGHT0 + index, GL_DIFFUSE, pData->diffuse);
6067 glLightfv(GL_LIGHT0 + index, GL_SPECULAR, pData->specular);
6068 glLightfv(GL_LIGHT0 + index, GL_AMBIENT, pData->ambient);
6069
6070 float QuadAttenuation;
6071 if (pData->range * pData->range >= FLT_MIN)
6072 QuadAttenuation = 1.4f / (pData->range * pData->range);
6073 else
6074 QuadAttenuation = 0.0f;
6075
6076 switch (pData->type)
6077 {
6078 case SVGA3D_LIGHTTYPE_POINT:
6079 {
6080 GLfloat position[4];
6081
6082 position[0] = pData->position[0];
6083 position[1] = pData->position[1];
6084 position[2] = pData->position[2];
6085 position[3] = 1.0f;
6086
6087 glLightfv(GL_LIGHT0 + index, GL_POSITION, position);
6088 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6089
6090 glLightf(GL_LIGHT0 + index, GL_SPOT_CUTOFF, 180.0f);
6091 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6092
6093 /* Attenuation - Are these right? guessing... */
6094 glLightf(GL_LIGHT0 + index, GL_CONSTANT_ATTENUATION, pData->attenuation0);
6095 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6096
6097 glLightf(GL_LIGHT0 + index, GL_LINEAR_ATTENUATION, pData->attenuation1);
6098 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6099
6100 glLightf(GL_LIGHT0 + index, GL_QUADRATIC_ATTENUATION, (QuadAttenuation < pData->attenuation2) ? pData->attenuation2 : QuadAttenuation);
6101 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6102
6103 /** @todo range */
6104 break;
6105 }
6106
6107 case SVGA3D_LIGHTTYPE_SPOT1:
6108 {
6109 GLfloat exponent;
6110 GLfloat position[4];
6111 const GLfloat pi = 4.0f * atanf(1.0f);
6112
6113 position[0] = pData->position[0];
6114 position[1] = pData->position[1];
6115 position[2] = pData->position[2];
6116 position[3] = 1.0f;
6117
6118 glLightfv(GL_LIGHT0 + index, GL_POSITION, position);
6119 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6120
6121 position[0] = pData->direction[0];
6122 position[1] = pData->direction[1];
6123 position[2] = pData->direction[2];
6124 position[3] = 1.0f;
6125
6126 glLightfv(GL_LIGHT0 + index, GL_SPOT_DIRECTION, position);
6127 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6128
6129 /*
6130 * opengl-ish and d3d-ish spot lights use too different models for the
6131 * light "intensity" as a function of the angle towards the main light direction,
6132 * so we only can approximate very roughly.
6133 * however spot lights are rather rarely used in games (if ever used at all).
6134 * furthermore if still used, probably nobody pays attention to such details.
6135 */
6136 if (pData->falloff == 0)
6137 {
6138 /* Falloff = 0 is easy, because d3d's and opengl's spot light equations have the
6139 * falloff resp. exponent parameter as an exponent, so the spot light lighting
6140 * will always be 1.0 for both of them, and we don't have to care for the
6141 * rest of the rather complex calculation
6142 */
6143 exponent = 0.0f;
6144 }
6145 else
6146 {
6147 float rho = pData->theta + (pData->phi - pData->theta) / (2 * pData->falloff);
6148 if (rho < 0.0001f)
6149 rho = 0.0001f;
6150 exponent = -0.3f/log(cos(rho/2));
6151 }
6152 if (exponent > 128.0f)
6153 exponent = 128.0f;
6154
6155 glLightf(GL_LIGHT0 + index, GL_SPOT_EXPONENT, exponent);
6156 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6157
6158 glLightf(GL_LIGHT0 + index, GL_SPOT_CUTOFF, pData->phi * 90.0 / pi);
6159 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6160
6161 /* Attenuation - Are these right? guessing... */
6162 glLightf(GL_LIGHT0 + index, GL_CONSTANT_ATTENUATION, pData->attenuation0);
6163 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6164
6165 glLightf(GL_LIGHT0 + index, GL_LINEAR_ATTENUATION, pData->attenuation1);
6166 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6167
6168 glLightf(GL_LIGHT0 + index, GL_QUADRATIC_ATTENUATION, (QuadAttenuation < pData->attenuation2) ? pData->attenuation2 : QuadAttenuation);
6169 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6170
6171 /** @todo range */
6172 break;
6173 }
6174
6175 case SVGA3D_LIGHTTYPE_DIRECTIONAL:
6176 {
6177 GLfloat position[4];
6178
6179 position[0] = -pData->direction[0];
6180 position[1] = -pData->direction[1];
6181 position[2] = -pData->direction[2];
6182 position[3] = 0.0f;
6183
6184 glLightfv(GL_LIGHT0 + index, GL_POSITION, position); /* Note gl uses w position of 0 for direction! */
6185 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6186
6187 glLightf(GL_LIGHT0 + index, GL_SPOT_CUTOFF, 180.0f);
6188 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6189
6190 glLightf(GL_LIGHT0 + index, GL_SPOT_EXPONENT, 0.0f);
6191 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6192 break;
6193 }
6194
6195 case SVGA3D_LIGHTTYPE_SPOT2:
6196 default:
6197 Log(("Unsupported light type!!\n"));
6198 rc = VERR_INVALID_PARAMETER;
6199 break;
6200 }
6201
6202 /* Restore the modelview matrix */
6203 glPopMatrix();
6204
6205 return rc;
6206}
6207
6208static DECLCALLBACK(int) vmsvga3dBackSetLightEnabled(PVGASTATECC pThisCC, uint32_t cid, uint32_t index, uint32_t enabled)
6209{
6210 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6211 AssertReturn(pState, VERR_NO_MEMORY);
6212
6213 LogFunc(("cid=%u %d -> %d\n", cid, index, enabled));
6214
6215 PVMSVGA3DCONTEXT pContext;
6216 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6217 AssertRCReturn(rc, rc);
6218
6219 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6220
6221 /* Store for vm state save/restore */
6222 if (index < SVGA3D_MAX_LIGHTS)
6223 pContext->state.aLightData[index].fEnabled = !!enabled;
6224 else
6225 AssertFailed();
6226
6227 if (enabled)
6228 {
6229 if (index < SVGA3D_MAX_LIGHTS)
6230 {
6231 /* Load the default settings if none have been set yet. */
6232 if (!pContext->state.aLightData[index].fValidData)
6233 vmsvga3dBackSetLightData(pThisCC, cid, index, (SVGA3dLightData *)&vmsvga3d_default_light);
6234 }
6235 glEnable(GL_LIGHT0 + index);
6236 }
6237 else
6238 glDisable(GL_LIGHT0 + index);
6239
6240 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6241 return VINF_SUCCESS;
6242}
6243
6244static DECLCALLBACK(int) vmsvga3dBackSetViewPort(PVGASTATECC pThisCC, uint32_t cid, SVGA3dRect *pRect)
6245{
6246 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6247 AssertReturn(pState, VERR_NO_MEMORY);
6248
6249 Log(("vmsvga3dSetViewPort cid=%u (%d,%d)(%d,%d)\n", cid, pRect->x, pRect->y, pRect->w, pRect->h));
6250
6251 PVMSVGA3DCONTEXT pContext;
6252 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6253 AssertRCReturn(rc, rc);
6254
6255 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6256
6257 /* Save for vm state save/restore. */
6258 pContext->state.RectViewPort = *pRect;
6259 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_VIEWPORT;
6260
6261 /** @todo y-inversion for partial viewport coordinates? */
6262 glViewport(pRect->x, pRect->y, pRect->w, pRect->h);
6263 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6264
6265 /* Reset the projection matrix as that relies on the viewport setting. */
6266 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_PROJECTION].fValid == true)
6267 vmsvga3dBackSetTransform(pThisCC, cid, SVGA3D_TRANSFORM_PROJECTION,
6268 pContext->state.aTransformState[SVGA3D_TRANSFORM_PROJECTION].matrix);
6269 else
6270 {
6271 float matrix[16];
6272
6273 /* identity matrix if no matrix set. */
6274 memset(matrix, 0, sizeof(matrix));
6275 matrix[0] = 1.0;
6276 matrix[5] = 1.0;
6277 matrix[10] = 1.0;
6278 matrix[15] = 1.0;
6279 vmsvga3dBackSetTransform(pThisCC, cid, SVGA3D_TRANSFORM_PROJECTION, matrix);
6280 }
6281
6282 return VINF_SUCCESS;
6283}
6284
6285static DECLCALLBACK(int) vmsvga3dBackSetClipPlane(PVGASTATECC pThisCC, uint32_t cid, uint32_t index, float plane[4])
6286{
6287 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6288 AssertReturn(pState, VERR_NO_MEMORY);
6289 double oglPlane[4];
6290
6291 Log(("vmsvga3dSetClipPlane cid=%u %d (%d,%d)(%d,%d)\n", cid, index, (unsigned)(plane[0] * 100.0), (unsigned)(plane[1] * 100.0), (unsigned)(plane[2] * 100.0), (unsigned)(plane[3] * 100.0)));
6292 AssertReturn(index < SVGA3D_NUM_CLIPPLANES, VERR_INVALID_PARAMETER);
6293
6294 PVMSVGA3DCONTEXT pContext;
6295 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6296 AssertRCReturn(rc, rc);
6297
6298 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6299
6300 /* Store for vm state save/restore. */
6301 pContext->state.aClipPlane[index].fValid = true;
6302 memcpy(pContext->state.aClipPlane[index].plane, plane, sizeof(pContext->state.aClipPlane[index].plane));
6303
6304 /** @todo clip plane affected by model view in OpenGL & view in D3D + vertex shader -> not transformed (see Wine; state.c clipplane) */
6305 oglPlane[0] = (double)plane[0];
6306 oglPlane[1] = (double)plane[1];
6307 oglPlane[2] = (double)plane[2];
6308 oglPlane[3] = (double)plane[3];
6309
6310 glClipPlane(GL_CLIP_PLANE0 + index, oglPlane);
6311 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6312
6313 return VINF_SUCCESS;
6314}
6315
6316static DECLCALLBACK(int) vmsvga3dBackSetScissorRect(PVGASTATECC pThisCC, uint32_t cid, SVGA3dRect *pRect)
6317{
6318 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6319 AssertReturn(pState, VERR_NO_MEMORY);
6320
6321 Log(("vmsvga3dSetScissorRect cid=%u (%d,%d)(%d,%d)\n", cid, pRect->x, pRect->y, pRect->w, pRect->h));
6322
6323 PVMSVGA3DCONTEXT pContext;
6324 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6325 AssertRCReturn(rc, rc);
6326
6327 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6328
6329 /* Store for vm state save/restore. */
6330 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_SCISSORRECT;
6331 pContext->state.RectScissor = *pRect;
6332
6333 glScissor(pRect->x, pRect->y, pRect->w, pRect->h);
6334 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6335
6336 return VINF_SUCCESS;
6337}
6338
6339static void vmsvgaColor2GLFloatArray(uint32_t color, GLfloat *pRed, GLfloat *pGreen, GLfloat *pBlue, GLfloat *pAlpha)
6340{
6341 /* Convert byte color components to float (0-1.0) */
6342 *pAlpha = (GLfloat)(color >> 24) / 255.0;
6343 *pRed = (GLfloat)((color >> 16) & 0xff) / 255.0;
6344 *pGreen = (GLfloat)((color >> 8) & 0xff) / 255.0;
6345 *pBlue = (GLfloat)(color & 0xff) / 255.0;
6346}
6347
6348static DECLCALLBACK(int) vmsvga3dBackCommandClear(PVGASTATECC pThisCC, uint32_t cid, SVGA3dClearFlag clearFlag, uint32_t color, float depth, uint32_t stencil,
6349 uint32_t cRects, SVGA3dRect *pRect)
6350{
6351 GLbitfield mask = 0;
6352 GLbitfield restoreMask = 0;
6353 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6354 AssertReturn(pState, VERR_NO_MEMORY);
6355 GLboolean fDepthWriteEnabled = GL_FALSE;
6356 GLboolean afColorWriteEnabled[4] = { GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE };
6357
6358 Log(("vmsvga3dCommandClear cid=%u clearFlag=%x color=%x depth=%d stencil=%x cRects=%d\n", cid, clearFlag, color, (uint32_t)(depth * 100.0), stencil, cRects));
6359
6360 PVMSVGA3DCONTEXT pContext;
6361 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6362 AssertRCReturn(rc, rc);
6363
6364 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6365
6366 if (clearFlag & SVGA3D_CLEAR_COLOR)
6367 {
6368 GLfloat red, green, blue, alpha;
6369 vmsvgaColor2GLFloatArray(color, &red, &green, &blue, &alpha);
6370
6371 /* Set the color clear value. */
6372 glClearColor(red, green, blue, alpha);
6373 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6374
6375 mask |= GL_COLOR_BUFFER_BIT;
6376
6377 /* glClear will not clear the color buffer if writing is disabled. */
6378 glGetBooleanv(GL_COLOR_WRITEMASK, afColorWriteEnabled);
6379 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6380 if ( afColorWriteEnabled[0] == GL_FALSE
6381 || afColorWriteEnabled[1] == GL_FALSE
6382 || afColorWriteEnabled[2] == GL_FALSE
6383 || afColorWriteEnabled[3] == GL_FALSE)
6384 {
6385 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
6386 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6387
6388 restoreMask |= GL_COLOR_BUFFER_BIT;
6389 }
6390
6391 }
6392
6393 if (clearFlag & SVGA3D_CLEAR_STENCIL)
6394 {
6395 /** @todo possibly the same problem as with glDepthMask */
6396 glClearStencil(stencil);
6397 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6398
6399 mask |= GL_STENCIL_BUFFER_BIT;
6400 }
6401
6402 if (clearFlag & SVGA3D_CLEAR_DEPTH)
6403 {
6404 glClearDepth((GLdouble)depth);
6405 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6406
6407 mask |= GL_DEPTH_BUFFER_BIT;
6408
6409 /* glClear will not clear the depth buffer if writing is disabled. */
6410 glGetBooleanv(GL_DEPTH_WRITEMASK, &fDepthWriteEnabled);
6411 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6412 if (fDepthWriteEnabled == GL_FALSE)
6413 {
6414 glDepthMask(GL_TRUE);
6415 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6416
6417 restoreMask |= GL_DEPTH_BUFFER_BIT;
6418 }
6419 }
6420
6421 /* Save the current scissor test bit and scissor box. */
6422 glPushAttrib(GL_SCISSOR_BIT);
6423 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6424
6425 if (cRects)
6426 {
6427 glEnable(GL_SCISSOR_TEST);
6428 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6429
6430 for (uint32_t i = 0; i < cRects; ++i)
6431 {
6432 LogFunc(("rect [%d] %d,%d %dx%d)\n", i, pRect[i].x, pRect[i].y, pRect[i].w, pRect[i].h));
6433 glScissor(pRect[i].x, pRect[i].y, pRect[i].w, pRect[i].h);
6434 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6435
6436 glClear(mask);
6437 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6438 }
6439 }
6440 else
6441 {
6442 glDisable(GL_SCISSOR_TEST);
6443 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6444
6445 glClear(mask);
6446 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6447 }
6448
6449 /* Restore the old scissor test bit and box */
6450 glPopAttrib();
6451 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6452
6453 /* Restore the write states. */
6454 if (restoreMask & GL_COLOR_BUFFER_BIT)
6455 {
6456 glColorMask(afColorWriteEnabled[0],
6457 afColorWriteEnabled[1],
6458 afColorWriteEnabled[2],
6459 afColorWriteEnabled[3]);
6460 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6461 }
6462
6463 if (restoreMask & GL_DEPTH_BUFFER_BIT)
6464 {
6465 glDepthMask(fDepthWriteEnabled);
6466 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6467 }
6468
6469 return VINF_SUCCESS;
6470}
6471
6472/* Convert VMWare vertex declaration to its OpenGL equivalent. */
6473int vmsvga3dVertexDecl2OGL(SVGA3dVertexArrayIdentity &identity, GLint &size, GLenum &type, GLboolean &normalized, uint32_t &cbAttrib)
6474{
6475 normalized = GL_FALSE;
6476 switch (identity.type)
6477 {
6478 case SVGA3D_DECLTYPE_FLOAT1:
6479 size = 1;
6480 type = GL_FLOAT;
6481 cbAttrib = sizeof(float);
6482 break;
6483 case SVGA3D_DECLTYPE_FLOAT2:
6484 size = 2;
6485 type = GL_FLOAT;
6486 cbAttrib = 2 * sizeof(float);
6487 break;
6488 case SVGA3D_DECLTYPE_FLOAT3:
6489 size = 3;
6490 type = GL_FLOAT;
6491 cbAttrib = 3 * sizeof(float);
6492 break;
6493 case SVGA3D_DECLTYPE_FLOAT4:
6494 size = 4;
6495 type = GL_FLOAT;
6496 cbAttrib = 4 * sizeof(float);
6497 break;
6498
6499 case SVGA3D_DECLTYPE_D3DCOLOR:
6500 size = GL_BGRA; /* @note requires GL_ARB_vertex_array_bgra */
6501 type = GL_UNSIGNED_BYTE;
6502 normalized = GL_TRUE; /* glVertexAttribPointer fails otherwise */
6503 cbAttrib = sizeof(uint32_t);
6504 break;
6505
6506 case SVGA3D_DECLTYPE_UBYTE4N:
6507 normalized = GL_TRUE;
6508 RT_FALL_THRU();
6509 case SVGA3D_DECLTYPE_UBYTE4:
6510 size = 4;
6511 type = GL_UNSIGNED_BYTE;
6512 cbAttrib = sizeof(uint32_t);
6513 break;
6514
6515 case SVGA3D_DECLTYPE_SHORT2N:
6516 normalized = GL_TRUE;
6517 RT_FALL_THRU();
6518 case SVGA3D_DECLTYPE_SHORT2:
6519 size = 2;
6520 type = GL_SHORT;
6521 cbAttrib = 2 * sizeof(uint16_t);
6522 break;
6523
6524 case SVGA3D_DECLTYPE_SHORT4N:
6525 normalized = GL_TRUE;
6526 RT_FALL_THRU();
6527 case SVGA3D_DECLTYPE_SHORT4:
6528 size = 4;
6529 type = GL_SHORT;
6530 cbAttrib = 4 * sizeof(uint16_t);
6531 break;
6532
6533 case SVGA3D_DECLTYPE_USHORT4N:
6534 normalized = GL_TRUE;
6535 size = 4;
6536 type = GL_UNSIGNED_SHORT;
6537 cbAttrib = 4 * sizeof(uint16_t);
6538 break;
6539
6540 case SVGA3D_DECLTYPE_USHORT2N:
6541 normalized = GL_TRUE;
6542 size = 2;
6543 type = GL_UNSIGNED_SHORT;
6544 cbAttrib = 2 * sizeof(uint16_t);
6545 break;
6546
6547 case SVGA3D_DECLTYPE_UDEC3:
6548 size = 3;
6549 type = GL_UNSIGNED_INT_2_10_10_10_REV; /** @todo correct? */
6550 cbAttrib = sizeof(uint32_t);
6551 break;
6552
6553 case SVGA3D_DECLTYPE_DEC3N:
6554 normalized = true;
6555 size = 3;
6556 type = GL_INT_2_10_10_10_REV; /** @todo correct? */
6557 cbAttrib = sizeof(uint32_t);
6558 break;
6559
6560 case SVGA3D_DECLTYPE_FLOAT16_2:
6561 size = 2;
6562 type = GL_HALF_FLOAT;
6563 cbAttrib = 2 * sizeof(uint16_t);
6564 break;
6565 case SVGA3D_DECLTYPE_FLOAT16_4:
6566 size = 4;
6567 type = GL_HALF_FLOAT;
6568 cbAttrib = 4 * sizeof(uint16_t);
6569 break;
6570 default:
6571 AssertFailedReturn(VERR_INVALID_PARAMETER);
6572 }
6573
6574 //pVertexElement->Method = identity.method;
6575 //pVertexElement->Usage = identity.usage;
6576
6577 return VINF_SUCCESS;
6578}
6579
6580static float vmsvga3dFloat16To32(uint16_t f16)
6581{
6582 /* From Wiki */
6583#ifndef INFINITY
6584 static uint32_t const sBitsINFINITY = UINT32_C(0x7f800000);
6585 #define INFINITY (*(float const *)&sBitsINFINITY)
6586#endif
6587#ifndef NAN
6588 static uint32_t const sBitsNAN = UINT32_C(0x7fc00000);
6589 #define NAN (*(float const *)&sBitsNAN)
6590#endif
6591
6592 uint16_t const s = (f16 >> UINT16_C(15)) & UINT16_C(0x1);
6593 uint16_t const e = (f16 >> UINT16_C(10)) & UINT16_C(0x1f);
6594 uint16_t const m = (f16 ) & UINT16_C(0x3ff);
6595
6596 float result = s ? 1.0f : -1.0f;
6597 if (e == 0)
6598 {
6599 if (m == 0)
6600 result *= 0.0f; /* zero, -0 */
6601 else
6602 result *= (float)m / 1024.0f / 16384.0f; /* subnormal numbers: sign * 2^-14 * 0.m */
6603 }
6604 else if (e == 0x1f)
6605 {
6606 if (m == 0)
6607 result *= INFINITY; /* +-infinity */
6608 else
6609 result = NAN; /* NAN */
6610 }
6611 else
6612 {
6613 result *= powf(2.0f, (float)e - 15.0f) * (1.0f + (float)m / 1024.0f); /* sign * 2^(e-15) * 1.m */
6614 }
6615
6616 return result;
6617}
6618
6619/* Set a vertex attribute according to VMSVGA vertex declaration. */
6620static int vmsvga3dSetVertexAttrib(PVMSVGA3DSTATE pState, GLuint index, SVGA3dVertexArrayIdentity const *pIdentity, GLvoid const *pv)
6621{
6622 switch (pIdentity->type)
6623 {
6624 case SVGA3D_DECLTYPE_FLOAT1:
6625 {
6626 /* "One-component float expanded to (float, 0, 0, 1)." */
6627 GLfloat const *p = (GLfloat *)pv;
6628 GLfloat const v[4] = { p[0], 0.0f, 0.0f, 1.0f };
6629 pState->ext.glVertexAttrib4fv(index, v);
6630 break;
6631 }
6632 case SVGA3D_DECLTYPE_FLOAT2:
6633 {
6634 /* "Two-component float expanded to (float, float, 0, 1)." */
6635 GLfloat const *p = (GLfloat *)pv;
6636 GLfloat const v[4] = { p[0], p[1], 0.0f, 1.0f };
6637 pState->ext.glVertexAttrib4fv(index, v);
6638 break;
6639 }
6640 case SVGA3D_DECLTYPE_FLOAT3:
6641 {
6642 /* "Three-component float expanded to (float, float, float, 1)." */
6643 GLfloat const *p = (GLfloat *)pv;
6644 GLfloat const v[4] = { p[0], p[1], p[2], 1.0f };
6645 pState->ext.glVertexAttrib4fv(index, v);
6646 break;
6647 }
6648 case SVGA3D_DECLTYPE_FLOAT4:
6649 pState->ext.glVertexAttrib4fv(index, (GLfloat const *)pv);
6650 break;
6651 case SVGA3D_DECLTYPE_D3DCOLOR:
6652 /** @todo Need to swap bytes? */
6653 pState->ext.glVertexAttrib4Nubv(index, (GLubyte const *)pv);
6654 break;
6655 case SVGA3D_DECLTYPE_UBYTE4:
6656 pState->ext.glVertexAttrib4ubv(index, (GLubyte const *)pv);
6657 break;
6658 case SVGA3D_DECLTYPE_SHORT2:
6659 {
6660 /* "Two-component, signed short expanded to (value, value, 0, 1)." */
6661 GLshort const *p = (GLshort const *)pv;
6662 GLshort const v[4] = { p[0], p[1], 0, 1 };
6663 pState->ext.glVertexAttrib4sv(index, v);
6664 break;
6665 }
6666 case SVGA3D_DECLTYPE_SHORT4:
6667 pState->ext.glVertexAttrib4sv(index, (GLshort const *)pv);
6668 break;
6669 case SVGA3D_DECLTYPE_UBYTE4N:
6670 pState->ext.glVertexAttrib4Nubv(index, (GLubyte const *)pv);
6671 break;
6672 case SVGA3D_DECLTYPE_SHORT2N:
6673 {
6674 /* "Normalized, two-component, signed short, expanded to (first short/32767.0, second short/32767.0, 0, 1)." */
6675 GLshort const *p = (GLshort const *)pv;
6676 GLshort const v[4] = { p[0], p[1], 0, 1 };
6677 pState->ext.glVertexAttrib4Nsv(index, v);
6678 break;
6679 }
6680 case SVGA3D_DECLTYPE_SHORT4N:
6681 pState->ext.glVertexAttrib4Nsv(index, (GLshort const *)pv);
6682 break;
6683 case SVGA3D_DECLTYPE_USHORT2N:
6684 {
6685 GLushort const *p = (GLushort const *)pv;
6686 GLushort const v[4] = { p[0], p[1], 0, 1 };
6687 pState->ext.glVertexAttrib4Nusv(index, v);
6688 break;
6689 }
6690 case SVGA3D_DECLTYPE_USHORT4N:
6691 pState->ext.glVertexAttrib4Nusv(index, (GLushort const *)pv);
6692 break;
6693 case SVGA3D_DECLTYPE_UDEC3:
6694 {
6695 /** @todo Test */
6696 /* "Three-component, unsigned, 10 10 10 format expanded to (value, value, value, 1)." */
6697 uint32_t const u32 = *(uint32_t *)pv;
6698 GLfloat const v[4] = { (float)(u32 & 0x3ff), (float)((u32 >> 10) & 0x3ff), (float)((u32 >> 20) & 0x3ff), 1.0f };
6699 pState->ext.glVertexAttrib4fv(index, v);
6700 break;
6701 }
6702 case SVGA3D_DECLTYPE_DEC3N:
6703 {
6704 /** @todo Test */
6705 /* "Three-component, signed, 10 10 10 format normalized and expanded to (v[0]/511.0, v[1]/511.0, v[2]/511.0, 1)." */
6706 uint32_t const u32 = *(uint32_t *)pv;
6707 GLfloat const v[4] = { (u32 & 0x3ff) / 511.0f, ((u32 >> 10) & 0x3ff) / 511.0f, ((u32 >> 20) & 0x3ff) / 511.0f, 1.0f };
6708 pState->ext.glVertexAttrib4fv(index, v);
6709 break;
6710 }
6711 case SVGA3D_DECLTYPE_FLOAT16_2:
6712 {
6713 /** @todo Test */
6714 /* "Two-component, 16-bit, floating point expanded to (value, value, 0, 1)." */
6715 uint16_t const *p = (uint16_t *)pv;
6716 GLfloat const v[4] = { vmsvga3dFloat16To32(p[0]), vmsvga3dFloat16To32(p[1]), 0.0f, 1.0f };
6717 pState->ext.glVertexAttrib4fv(index, v);
6718 break;
6719 }
6720 case SVGA3D_DECLTYPE_FLOAT16_4:
6721 {
6722 /** @todo Test */
6723 uint16_t const *p = (uint16_t *)pv;
6724 GLfloat const v[4] = { vmsvga3dFloat16To32(p[0]), vmsvga3dFloat16To32(p[1]),
6725 vmsvga3dFloat16To32(p[2]), vmsvga3dFloat16To32(p[3]) };
6726 pState->ext.glVertexAttrib4fv(index, v);
6727 break;
6728 }
6729 default:
6730 AssertFailedReturn(VERR_INVALID_PARAMETER);
6731 }
6732
6733 return VINF_SUCCESS;
6734}
6735
6736/* Convert VMWare primitive type to its OpenGL equivalent. */
6737/* Calculate the vertex count based on the primitive type and nr of primitives. */
6738int vmsvga3dPrimitiveType2OGL(SVGA3dPrimitiveType PrimitiveType, GLenum *pMode, uint32_t cPrimitiveCount, uint32_t *pcVertices)
6739{
6740 switch (PrimitiveType)
6741 {
6742 case SVGA3D_PRIMITIVE_TRIANGLELIST:
6743 *pMode = GL_TRIANGLES;
6744 *pcVertices = cPrimitiveCount * 3;
6745 break;
6746 case SVGA3D_PRIMITIVE_POINTLIST:
6747 *pMode = GL_POINTS;
6748 *pcVertices = cPrimitiveCount;
6749 break;
6750 case SVGA3D_PRIMITIVE_LINELIST:
6751 *pMode = GL_LINES;
6752 *pcVertices = cPrimitiveCount * 2;
6753 break;
6754 case SVGA3D_PRIMITIVE_LINESTRIP:
6755 *pMode = GL_LINE_STRIP;
6756 *pcVertices = cPrimitiveCount + 1;
6757 break;
6758 case SVGA3D_PRIMITIVE_TRIANGLESTRIP:
6759 *pMode = GL_TRIANGLE_STRIP;
6760 *pcVertices = cPrimitiveCount + 2;
6761 break;
6762 case SVGA3D_PRIMITIVE_TRIANGLEFAN:
6763 *pMode = GL_TRIANGLE_FAN;
6764 *pcVertices = cPrimitiveCount + 2;
6765 break;
6766 default:
6767 return VERR_INVALID_PARAMETER;
6768 }
6769 return VINF_SUCCESS;
6770}
6771
6772static int vmsvga3dResetTransformMatrices(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext)
6773{
6774 int rc;
6775
6776 /* Reset the view matrix (also takes the world matrix into account). */
6777 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].fValid == true)
6778 rc = vmsvga3dBackSetTransform(pThisCC, pContext->id, SVGA3D_TRANSFORM_VIEW,
6779 pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].matrix);
6780 else
6781 {
6782 float matrix[16];
6783
6784 /* identity matrix if no matrix set. */
6785 memset(matrix, 0, sizeof(matrix));
6786 matrix[0] = 1.0;
6787 matrix[5] = 1.0;
6788 matrix[10] = 1.0;
6789 matrix[15] = 1.0;
6790 rc = vmsvga3dBackSetTransform(pThisCC, pContext->id, SVGA3D_TRANSFORM_VIEW, matrix);
6791 }
6792
6793 /* Reset the projection matrix. */
6794 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_PROJECTION].fValid == true)
6795 {
6796 rc = vmsvga3dBackSetTransform(pThisCC, pContext->id, SVGA3D_TRANSFORM_PROJECTION, pContext->state.aTransformState[SVGA3D_TRANSFORM_PROJECTION].matrix);
6797 }
6798 else
6799 {
6800 float matrix[16];
6801
6802 /* identity matrix if no matrix set. */
6803 memset(matrix, 0, sizeof(matrix));
6804 matrix[0] = 1.0;
6805 matrix[5] = 1.0;
6806 matrix[10] = 1.0;
6807 matrix[15] = 1.0;
6808 rc = vmsvga3dBackSetTransform(pThisCC, pContext->id, SVGA3D_TRANSFORM_PROJECTION, matrix);
6809 }
6810 AssertRC(rc);
6811 return rc;
6812}
6813
6814static int vmsvga3dDrawPrimitivesProcessVertexDecls(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext,
6815 uint32_t iVertexDeclBase, uint32_t numVertexDecls,
6816 SVGA3dVertexDecl *pVertexDecl,
6817 SVGA3dVertexDivisor const *paVertexDivisors)
6818{
6819 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6820 unsigned const sidVertex = pVertexDecl[0].array.surfaceId;
6821
6822 PVMSVGA3DSURFACE pVertexSurface;
6823 int rc = vmsvga3dSurfaceFromSid(pState, sidVertex, &pVertexSurface);
6824 AssertRCReturn(rc, rc);
6825
6826 Log(("vmsvga3dDrawPrimitives: vertex surface sid=%u\n", sidVertex));
6827
6828 /* Create and/or bind the vertex buffer. */
6829 if (pVertexSurface->oglId.buffer == OPENGL_INVALID_ID)
6830 {
6831 Log(("vmsvga3dDrawPrimitives: create vertex buffer fDirty=%d size=%x bytes\n", pVertexSurface->fDirty, pVertexSurface->paMipmapLevels[0].cbSurface));
6832 PVMSVGA3DCONTEXT pSavedCtx = pContext;
6833 pContext = &pState->SharedCtx;
6834 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6835
6836 pState->ext.glGenBuffers(1, &pVertexSurface->oglId.buffer);
6837 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6838 pVertexSurface->enmOGLResType = VMSVGA3D_OGLRESTYPE_BUFFER;
6839
6840 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, pVertexSurface->oglId.buffer);
6841 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6842
6843 Assert(pVertexSurface->fDirty);
6844 /** @todo rethink usage dynamic/static */
6845 pState->ext.glBufferData(GL_ARRAY_BUFFER, pVertexSurface->paMipmapLevels[0].cbSurface, pVertexSurface->paMipmapLevels[0].pSurfaceData, GL_DYNAMIC_DRAW);
6846 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6847
6848 pVertexSurface->paMipmapLevels[0].fDirty = false;
6849 pVertexSurface->fDirty = false;
6850
6851 pVertexSurface->f.s.surface1Flags |= SVGA3D_SURFACE_HINT_VERTEXBUFFER;
6852
6853 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, OPENGL_INVALID_ID);
6854 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6855
6856 pContext = pSavedCtx;
6857 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6858 }
6859
6860 Assert(pVertexSurface->fDirty == false);
6861 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, pVertexSurface->oglId.buffer);
6862 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6863
6864 /* Setup the vertex declarations. */
6865 for (unsigned iVertex = 0; iVertex < numVertexDecls; iVertex++)
6866 {
6867 GLint size;
6868 GLenum type;
6869 GLboolean normalized;
6870 uint32_t cbAttrib;
6871 GLuint index = iVertexDeclBase + iVertex;
6872
6873 Log(("vmsvga3dDrawPrimitives: array index %d type=%s (%d) method=%s (%d) usage=%s (%d) usageIndex=%d stride=%d offset=%d\n", index, vmsvgaDeclType2String(pVertexDecl[iVertex].identity.type), pVertexDecl[iVertex].identity.type, vmsvgaDeclMethod2String(pVertexDecl[iVertex].identity.method), pVertexDecl[iVertex].identity.method, vmsvgaDeclUsage2String(pVertexDecl[iVertex].identity.usage), pVertexDecl[iVertex].identity.usage, pVertexDecl[iVertex].identity.usageIndex, pVertexDecl[iVertex].array.stride, pVertexDecl[iVertex].array.offset));
6874
6875 rc = vmsvga3dVertexDecl2OGL(pVertexDecl[iVertex].identity, size, type, normalized, cbAttrib);
6876 AssertRCReturn(rc, rc);
6877
6878 ASSERT_GUEST_RETURN( pVertexSurface->paMipmapLevels[0].cbSurface >= pVertexDecl[iVertex].array.offset
6879 && pVertexSurface->paMipmapLevels[0].cbSurface - pVertexDecl[iVertex].array.offset >= cbAttrib,
6880 VERR_INVALID_PARAMETER);
6881 RT_UNTRUSTED_VALIDATED_FENCE();
6882
6883 if (pContext->state.shidVertex != SVGA_ID_INVALID)
6884 {
6885 /* Use numbered vertex arrays (or attributes) when shaders are active. */
6886 if (pVertexDecl[iVertex].array.stride)
6887 {
6888 pState->ext.glEnableVertexAttribArray(index);
6889 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6890 pState->ext.glVertexAttribPointer(index, size, type, normalized, pVertexDecl[iVertex].array.stride,
6891 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6892 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6893
6894 GLuint divisor = paVertexDivisors && paVertexDivisors[index].instanceData ? 1 : 0;
6895 pState->ext.glVertexAttribDivisor(index, divisor);
6896 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6897
6898 /** @todo case SVGA3D_DECLUSAGE_COLOR: color component order not identical!! test GL_BGRA!! */
6899 }
6900 else
6901 {
6902 /*
6903 * D3D and OpenGL have a different meaning of value zero for the vertex array stride:
6904 * - D3D (VMSVGA): "use a zero stride to tell the runtime not to increment the vertex buffer offset."
6905 * - OpenGL: "If stride is 0, the generic vertex attributes are understood to be tightly packed in the array."
6906 * VMSVGA uses the D3D semantics.
6907 *
6908 * Use glVertexAttrib in order to tell OpenGL to reuse the zero stride attributes for each vertex.
6909 */
6910 pState->ext.glDisableVertexAttribArray(index);
6911 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6912
6913 const GLvoid *v = (uint8_t *)pVertexSurface->paMipmapLevels[0].pSurfaceData + pVertexDecl[iVertex].array.offset;
6914 vmsvga3dSetVertexAttrib(pState, index, &pVertexDecl[iVertex].identity, v);
6915 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6916 }
6917 }
6918 else
6919 {
6920 if (pVertexDecl[iVertex].array.stride == 0)
6921 {
6922 /* Zero stride means that the attribute pointer must not be increased.
6923 * See comment about stride in vmsvga3dDrawPrimitives.
6924 */
6925 LogRelMax(8, ("VMSVGA: Warning: zero stride array in fixed function pipeline\n"));
6926 AssertFailed();
6927 }
6928
6929 /* Use the predefined selection of vertex streams for the fixed pipeline. */
6930 switch (pVertexDecl[iVertex].identity.usage)
6931 {
6932 case SVGA3D_DECLUSAGE_POSITIONT:
6933 case SVGA3D_DECLUSAGE_POSITION:
6934 {
6935 glEnableClientState(GL_VERTEX_ARRAY);
6936 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6937 glVertexPointer(size, type, pVertexDecl[iVertex].array.stride,
6938 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6939 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6940 break;
6941 }
6942 case SVGA3D_DECLUSAGE_BLENDWEIGHT:
6943 AssertFailed();
6944 break;
6945 case SVGA3D_DECLUSAGE_BLENDINDICES:
6946 AssertFailed();
6947 break;
6948 case SVGA3D_DECLUSAGE_NORMAL:
6949 glEnableClientState(GL_NORMAL_ARRAY);
6950 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6951 glNormalPointer(type, pVertexDecl[iVertex].array.stride,
6952 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6953 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6954 break;
6955 case SVGA3D_DECLUSAGE_PSIZE:
6956 AssertFailed();
6957 break;
6958 case SVGA3D_DECLUSAGE_TEXCOORD:
6959 /* Specify the affected texture unit. */
6960#if VBOX_VMSVGA3D_GL_HACK_LEVEL >= 0x103
6961 glClientActiveTexture(GL_TEXTURE0 + pVertexDecl[iVertex].identity.usageIndex);
6962#else
6963 pState->ext.glClientActiveTexture(GL_TEXTURE0 + pVertexDecl[iVertex].identity.usageIndex);
6964#endif
6965 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
6966 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6967 glTexCoordPointer(size, type, pVertexDecl[iVertex].array.stride,
6968 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6969 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6970 break;
6971 case SVGA3D_DECLUSAGE_TANGENT:
6972 AssertFailed();
6973 break;
6974 case SVGA3D_DECLUSAGE_BINORMAL:
6975 AssertFailed();
6976 break;
6977 case SVGA3D_DECLUSAGE_TESSFACTOR:
6978 AssertFailed();
6979 break;
6980 case SVGA3D_DECLUSAGE_COLOR: /** @todo color component order not identical!! test GL_BGRA!! */
6981 glEnableClientState(GL_COLOR_ARRAY);
6982 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6983 glColorPointer(size, type, pVertexDecl[iVertex].array.stride,
6984 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6985 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6986 break;
6987 case SVGA3D_DECLUSAGE_FOG:
6988 glEnableClientState(GL_FOG_COORD_ARRAY);
6989 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6990 pState->ext.glFogCoordPointer(type, pVertexDecl[iVertex].array.stride,
6991 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6992 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6993 break;
6994 case SVGA3D_DECLUSAGE_DEPTH:
6995 AssertFailed();
6996 break;
6997 case SVGA3D_DECLUSAGE_SAMPLE:
6998 AssertFailed();
6999 break;
7000 case SVGA3D_DECLUSAGE_MAX: AssertFailed(); break; /* shut up gcc */
7001 }
7002 }
7003
7004#ifdef LOG_ENABLED
7005 if (pVertexDecl[iVertex].array.stride == 0)
7006 Log(("vmsvga3dDrawPrimitives: stride == 0! Can be valid\n"));
7007#endif
7008 }
7009
7010 return VINF_SUCCESS;
7011}
7012
7013static int vmsvga3dDrawPrimitivesCleanupVertexDecls(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t iVertexDeclBase,
7014 uint32_t numVertexDecls, SVGA3dVertexDecl *pVertexDecl)
7015{
7016 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7017
7018 /* Clean up the vertex declarations. */
7019 for (unsigned iVertex = 0; iVertex < numVertexDecls; iVertex++)
7020 {
7021 if (pVertexDecl[iVertex].identity.usage == SVGA3D_DECLUSAGE_POSITIONT)
7022 {
7023 /* Reset the transformation matrices in case of a switch back from pretransformed mode. */
7024 Log(("vmsvga3dDrawPrimitivesCleanupVertexDecls: reset world and projection matrices after transformation reset (pre-transformed -> transformed)\n"));
7025 vmsvga3dResetTransformMatrices(pThisCC, pContext);
7026 }
7027
7028 if (pContext->state.shidVertex != SVGA_ID_INVALID)
7029 {
7030 /* Use numbered vertex arrays when shaders are active. */
7031 pState->ext.glVertexAttribDivisor(iVertexDeclBase + iVertex, 0);
7032 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7033 pState->ext.glDisableVertexAttribArray(iVertexDeclBase + iVertex);
7034 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7035 }
7036 else
7037 {
7038 /* Use the predefined selection of vertex streams for the fixed pipeline. */
7039 switch (pVertexDecl[iVertex].identity.usage)
7040 {
7041 case SVGA3D_DECLUSAGE_POSITION:
7042 case SVGA3D_DECLUSAGE_POSITIONT:
7043 glDisableClientState(GL_VERTEX_ARRAY);
7044 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7045 break;
7046 case SVGA3D_DECLUSAGE_BLENDWEIGHT:
7047 break;
7048 case SVGA3D_DECLUSAGE_BLENDINDICES:
7049 break;
7050 case SVGA3D_DECLUSAGE_NORMAL:
7051 glDisableClientState(GL_NORMAL_ARRAY);
7052 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7053 break;
7054 case SVGA3D_DECLUSAGE_PSIZE:
7055 break;
7056 case SVGA3D_DECLUSAGE_TEXCOORD:
7057 /* Specify the affected texture unit. */
7058#if VBOX_VMSVGA3D_GL_HACK_LEVEL >= 0x103
7059 glClientActiveTexture(GL_TEXTURE0 + pVertexDecl[iVertex].identity.usageIndex);
7060#else
7061 pState->ext.glClientActiveTexture(GL_TEXTURE0 + pVertexDecl[iVertex].identity.usageIndex);
7062#endif
7063 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
7064 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7065 break;
7066 case SVGA3D_DECLUSAGE_TANGENT:
7067 break;
7068 case SVGA3D_DECLUSAGE_BINORMAL:
7069 break;
7070 case SVGA3D_DECLUSAGE_TESSFACTOR:
7071 break;
7072 case SVGA3D_DECLUSAGE_COLOR: /** @todo color component order not identical!! */
7073 glDisableClientState(GL_COLOR_ARRAY);
7074 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7075 break;
7076 case SVGA3D_DECLUSAGE_FOG:
7077 glDisableClientState(GL_FOG_COORD_ARRAY);
7078 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7079 break;
7080 case SVGA3D_DECLUSAGE_DEPTH:
7081 break;
7082 case SVGA3D_DECLUSAGE_SAMPLE:
7083 break;
7084 case SVGA3D_DECLUSAGE_MAX: AssertFailed(); break; /* shut up gcc */
7085 }
7086 }
7087 }
7088 /* Unbind the vertex buffer after usage. */
7089 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, 0);
7090 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7091 return VINF_SUCCESS;
7092}
7093
7094static DECLCALLBACK(int) vmsvga3dBackDrawPrimitives(PVGASTATECC pThisCC, uint32_t cid, uint32_t numVertexDecls, SVGA3dVertexDecl *pVertexDecl,
7095 uint32_t numRanges, SVGA3dPrimitiveRange *pRange, uint32_t cVertexDivisor,
7096 SVGA3dVertexDivisor *pVertexDivisor)
7097{
7098 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7099 AssertReturn(pState, VERR_INTERNAL_ERROR);
7100 uint32_t iCurrentVertex;
7101
7102 Log(("vmsvga3dDrawPrimitives cid=%u numVertexDecls=%d numRanges=%d, cVertexDivisor=%d\n", cid, numVertexDecls, numRanges, cVertexDivisor));
7103
7104 /* Caller already check these, but it cannot hurt to check again... */
7105 AssertReturn(numVertexDecls && numVertexDecls <= SVGA3D_MAX_VERTEX_ARRAYS, VERR_INVALID_PARAMETER);
7106 AssertReturn(numRanges && numRanges <= SVGA3D_MAX_DRAW_PRIMITIVE_RANGES, VERR_INVALID_PARAMETER);
7107 AssertReturn(!cVertexDivisor || cVertexDivisor == numVertexDecls, VERR_INVALID_PARAMETER);
7108
7109 if (!cVertexDivisor)
7110 pVertexDivisor = NULL; /* Be sure. */
7111
7112 PVMSVGA3DCONTEXT pContext;
7113 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
7114 AssertRCReturn(rc, rc);
7115
7116 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7117
7118 /* Check for pretransformed vertex declarations. */
7119 for (unsigned iVertex = 0; iVertex < numVertexDecls; iVertex++)
7120 {
7121 switch (pVertexDecl[iVertex].identity.usage)
7122 {
7123 case SVGA3D_DECLUSAGE_POSITIONT:
7124 Log(("ShaderSetPositionTransformed: (%d,%d)\n", pContext->state.RectViewPort.w, pContext->state.RectViewPort.h));
7125 RT_FALL_THRU();
7126 case SVGA3D_DECLUSAGE_POSITION:
7127 ShaderSetPositionTransformed(pContext->pShaderContext, pContext->state.RectViewPort.w,
7128 pContext->state.RectViewPort.h,
7129 pVertexDecl[iVertex].identity.usage == SVGA3D_DECLUSAGE_POSITIONT);
7130 break;
7131 default: /* Shut up MSC. */ break;
7132 }
7133 }
7134
7135 /* Flush any shader changes; after (!) checking the vertex declarations to deal with pre-transformed vertices. */
7136 if (pContext->pShaderContext)
7137 {
7138 uint32_t rtHeight = 0;
7139
7140 if (pContext->state.aRenderTargets[SVGA3D_RT_COLOR0] != SVGA_ID_INVALID)
7141 {
7142 PVMSVGA3DSURFACE pRenderTarget;
7143 rc = vmsvga3dSurfaceFromSid(pState, pContext->state.aRenderTargets[SVGA3D_RT_COLOR0], &pRenderTarget);
7144 AssertRCReturn(rc, rc);
7145
7146 rtHeight = pRenderTarget->paMipmapLevels[0].mipmapSize.height;
7147 }
7148
7149 ShaderUpdateState(pContext->pShaderContext, rtHeight);
7150 }
7151
7152 /* Try to figure out if instancing is used.
7153 * Support simple instancing case with one set of indexed data and one set per-instance data.
7154 */
7155 uint32_t cInstances = 0;
7156 for (uint32_t iVertexDivisor = 0; iVertexDivisor < cVertexDivisor; ++iVertexDivisor)
7157 {
7158 if (pVertexDivisor[iVertexDivisor].indexedData)
7159 {
7160 if (cInstances == 0)
7161 cInstances = pVertexDivisor[iVertexDivisor].count;
7162 else
7163 Assert(cInstances == pVertexDivisor[iVertexDivisor].count);
7164 }
7165 else if (pVertexDivisor[iVertexDivisor].instanceData)
7166 {
7167 Assert(pVertexDivisor[iVertexDivisor].count == 1);
7168 }
7169 }
7170
7171 /* Process all vertex declarations. Each vertex buffer is represented by one stream. */
7172 iCurrentVertex = 0;
7173 while (iCurrentVertex < numVertexDecls)
7174 {
7175 uint32_t sidVertex = SVGA_ID_INVALID;
7176 uint32_t iVertex;
7177
7178 for (iVertex = iCurrentVertex; iVertex < numVertexDecls; iVertex++)
7179 {
7180 if ( sidVertex != SVGA_ID_INVALID
7181 && pVertexDecl[iVertex].array.surfaceId != sidVertex
7182 )
7183 break;
7184 sidVertex = pVertexDecl[iVertex].array.surfaceId;
7185 }
7186
7187 rc = vmsvga3dDrawPrimitivesProcessVertexDecls(pThisCC, pContext, iCurrentVertex, iVertex - iCurrentVertex,
7188 &pVertexDecl[iCurrentVertex], pVertexDivisor);
7189 AssertRCReturn(rc, rc);
7190
7191 iCurrentVertex = iVertex;
7192 }
7193
7194 /* Now draw the primitives. */
7195 for (unsigned iPrimitive = 0; iPrimitive < numRanges; iPrimitive++)
7196 {
7197 GLenum modeDraw;
7198 unsigned const sidIndex = pRange[iPrimitive].indexArray.surfaceId;
7199 PVMSVGA3DSURFACE pIndexSurface = NULL;
7200 unsigned cVertices;
7201
7202 Log(("Primitive %d: type %s\n", iPrimitive, vmsvga3dPrimitiveType2String(pRange[iPrimitive].primType)));
7203 rc = vmsvga3dPrimitiveType2OGL(pRange[iPrimitive].primType, &modeDraw, pRange[iPrimitive].primitiveCount, &cVertices);
7204 if (RT_FAILURE(rc))
7205 {
7206 AssertRC(rc);
7207 goto internal_error;
7208 }
7209
7210 if (sidIndex != SVGA3D_INVALID_ID)
7211 {
7212 AssertMsg(pRange[iPrimitive].indexWidth == sizeof(uint32_t) || pRange[iPrimitive].indexWidth == sizeof(uint16_t), ("Unsupported primitive width %d\n", pRange[iPrimitive].indexWidth));
7213
7214 rc = vmsvga3dSurfaceFromSid(pState, sidIndex, &pIndexSurface);
7215 if (RT_FAILURE(rc))
7216 {
7217 AssertRC(rc);
7218 goto internal_error;
7219 }
7220
7221 Log(("vmsvga3dDrawPrimitives: index surface sid=%u\n", sidIndex));
7222
7223 if (pIndexSurface->oglId.buffer == OPENGL_INVALID_ID)
7224 {
7225 Log(("vmsvga3dDrawPrimitives: create index buffer fDirty=%d size=%x bytes\n", pIndexSurface->fDirty, pIndexSurface->paMipmapLevels[0].cbSurface));
7226 pContext = &pState->SharedCtx;
7227 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7228
7229 pState->ext.glGenBuffers(1, &pIndexSurface->oglId.buffer);
7230 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7231 pIndexSurface->enmOGLResType = VMSVGA3D_OGLRESTYPE_BUFFER;
7232
7233 pState->ext.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pIndexSurface->oglId.buffer);
7234 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7235
7236 Assert(pIndexSurface->fDirty);
7237
7238 /** @todo rethink usage dynamic/static */
7239 pState->ext.glBufferData(GL_ELEMENT_ARRAY_BUFFER, pIndexSurface->paMipmapLevels[0].cbSurface, pIndexSurface->paMipmapLevels[0].pSurfaceData, GL_DYNAMIC_DRAW);
7240 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7241
7242 pIndexSurface->paMipmapLevels[0].fDirty = false;
7243 pIndexSurface->fDirty = false;
7244
7245 pIndexSurface->f.s.surface1Flags |= SVGA3D_SURFACE_HINT_INDEXBUFFER;
7246
7247 pState->ext.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, OPENGL_INVALID_ID);
7248 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7249
7250 pContext = pState->papContexts[cid];
7251 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7252 }
7253 Assert(pIndexSurface->fDirty == false);
7254
7255 pState->ext.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pIndexSurface->oglId.buffer);
7256 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7257 }
7258
7259 if (!pIndexSurface)
7260 {
7261 /* Render without an index buffer */
7262 Log(("DrawPrimitive %d cPrimitives=%d cVertices=%d index index bias=%d cInstances=%d\n", modeDraw, pRange[iPrimitive].primitiveCount, cVertices, pRange[iPrimitive].indexBias, cInstances));
7263 if (cInstances == 0)
7264 {
7265 glDrawArrays(modeDraw, pRange[iPrimitive].indexBias, cVertices);
7266 }
7267 else
7268 {
7269 pState->ext.glDrawArraysInstanced(modeDraw, pRange[iPrimitive].indexBias, cVertices, cInstances);
7270 }
7271 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7272 }
7273 else
7274 {
7275 Assert(pRange[iPrimitive].indexWidth == pRange[iPrimitive].indexArray.stride);
7276
7277 GLenum indexType;
7278 switch (pRange[iPrimitive].indexWidth)
7279 {
7280 case 1: indexType = GL_UNSIGNED_BYTE; break;
7281 case 2: indexType = GL_UNSIGNED_SHORT; break;
7282 default: AssertMsgFailed(("indexWidth %d\n", pRange[iPrimitive].indexWidth));
7283 RT_FALL_THROUGH();
7284 case 4: indexType = GL_UNSIGNED_INT; break;
7285 }
7286
7287 Log(("DrawIndexedPrimitive %d cPrimitives=%d cVertices=%d hint.first=%d hint.last=%d index offset=%d primitivecount=%d index width=%d index bias=%d cInstances=%d\n", modeDraw, pRange[iPrimitive].primitiveCount, cVertices, pVertexDecl[0].rangeHint.first, pVertexDecl[0].rangeHint.last, pRange[iPrimitive].indexArray.offset, pRange[iPrimitive].primitiveCount, pRange[iPrimitive].indexWidth, pRange[iPrimitive].indexBias, cInstances));
7288 if (cInstances == 0)
7289 {
7290 /* Render with an index buffer */
7291 if (pRange[iPrimitive].indexBias == 0)
7292 glDrawElements(modeDraw,
7293 cVertices,
7294 indexType,
7295 (GLvoid *)(uintptr_t)pRange[iPrimitive].indexArray.offset); /* byte offset in indices buffer */
7296 else
7297 pState->ext.glDrawElementsBaseVertex(modeDraw,
7298 cVertices,
7299 indexType,
7300 (GLvoid *)(uintptr_t)pRange[iPrimitive].indexArray.offset, /* byte offset in indices buffer */
7301 pRange[iPrimitive].indexBias); /* basevertex */
7302 }
7303 else
7304 {
7305 /* Render with an index buffer */
7306 if (pRange[iPrimitive].indexBias == 0)
7307 pState->ext.glDrawElementsInstanced(modeDraw,
7308 cVertices,
7309 indexType,
7310 (GLvoid *)(uintptr_t)pRange[iPrimitive].indexArray.offset, /* byte offset in indices buffer */
7311 cInstances);
7312 else
7313 pState->ext.glDrawElementsInstancedBaseVertex(modeDraw,
7314 cVertices,
7315 indexType,
7316 (GLvoid *)(uintptr_t)pRange[iPrimitive].indexArray.offset, /* byte offset in indices buffer */
7317 cInstances,
7318 pRange[iPrimitive].indexBias); /* basevertex */
7319 }
7320 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7321
7322 /* Unbind the index buffer after usage. */
7323 pState->ext.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
7324 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7325 }
7326 }
7327
7328internal_error:
7329
7330 /* Deactivate the vertex declarations. */
7331 iCurrentVertex = 0;
7332 while (iCurrentVertex < numVertexDecls)
7333 {
7334 uint32_t sidVertex = SVGA_ID_INVALID;
7335 uint32_t iVertex;
7336
7337 for (iVertex = iCurrentVertex; iVertex < numVertexDecls; iVertex++)
7338 {
7339 if ( sidVertex != SVGA_ID_INVALID
7340 && pVertexDecl[iVertex].array.surfaceId != sidVertex
7341 )
7342 break;
7343 sidVertex = pVertexDecl[iVertex].array.surfaceId;
7344 }
7345
7346 rc = vmsvga3dDrawPrimitivesCleanupVertexDecls(pThisCC, pContext, iCurrentVertex,
7347 iVertex - iCurrentVertex, &pVertexDecl[iCurrentVertex]);
7348 AssertRCReturn(rc, rc);
7349
7350 iCurrentVertex = iVertex;
7351 }
7352
7353#ifdef DEBUG
7354 /* Check whether 'activeTexture' on texture unit 'i' matches what we expect. */
7355 for (uint32_t i = 0; i < RT_ELEMENTS(pContext->aSidActiveTextures); ++i)
7356 {
7357 if (pContext->aSidActiveTextures[i] != SVGA3D_INVALID_ID)
7358 {
7359 PVMSVGA3DSURFACE pTexture;
7360 int rc2 = vmsvga3dSurfaceFromSid(pState, pContext->aSidActiveTextures[i], &pTexture);
7361 AssertContinue(RT_SUCCESS(rc2));
7362
7363 GLint activeTextureUnit = 0;
7364 glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTextureUnit);
7365 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7366
7367 pState->ext.glActiveTexture(GL_TEXTURE0 + i);
7368 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7369
7370 GLint activeTexture = 0;
7371 glGetIntegerv(pTexture->bindingGL, &activeTexture);
7372 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7373
7374 pState->ext.glActiveTexture(activeTextureUnit);
7375 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7376
7377 AssertMsg(pTexture->oglId.texture == (GLuint)activeTexture,
7378 ("%d vs %d unit %d (active unit %d) sid=%u\n", pTexture->oglId.texture, activeTexture, i,
7379 activeTextureUnit - GL_TEXTURE0, pContext->aSidActiveTextures[i]));
7380 }
7381 }
7382#endif
7383
7384#if 0
7385 /* Dump render target to a bitmap. */
7386 if (pContext->state.aRenderTargets[SVGA3D_RT_COLOR0] != SVGA3D_INVALID_ID)
7387 {
7388 vmsvga3dUpdateHeapBuffersForSurfaces(pThisCC, pContext->state.aRenderTargets[SVGA3D_RT_COLOR0]);
7389 PVMSVGA3DSURFACE pSurface;
7390 int rc2 = vmsvga3dSurfaceFromSid(pState, pContext->state.aRenderTargets[SVGA3D_RT_COLOR0], &pSurface);
7391 if (RT_SUCCESS(rc2))
7392 vmsvga3dInfoSurfaceToBitmap(NULL, pSurface, "bmpgl", "rt", "-post");
7393# if 0
7394 /* Stage 0 texture. */
7395 if (pContext->aSidActiveTextures[0] != SVGA3D_INVALID_ID)
7396 {
7397 vmsvga3dUpdateHeapBuffersForSurfaces(pThisCC, pContext->aSidActiveTextures[0]);
7398 rc2 = vmsvga3dSurfaceFromSid(pState, pContext->aSidActiveTextures[0], &pSurface);
7399 if (RT_SUCCESS(rc2))
7400 vmsvga3dInfoSurfaceToBitmap(NULL, pSurface, "bmpgl", "rt", "-post-tx");
7401 }
7402# endif
7403 }
7404#endif
7405
7406 return rc;
7407}
7408
7409
7410static DECLCALLBACK(int) vmsvga3dBackShaderDefine(PVGASTATECC pThisCC, uint32_t cid, uint32_t shid, SVGA3dShaderType type, uint32_t cbData, uint32_t *pShaderData)
7411{
7412 PVMSVGA3DSHADER pShader;
7413 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7414 AssertReturn(pState, VERR_NO_MEMORY);
7415
7416 Log(("vmsvga3dShaderDefine cid=%u shid=%d type=%s cbData=0x%x\n", cid, shid, (type == SVGA3D_SHADERTYPE_VS) ? "VERTEX" : "PIXEL", cbData));
7417
7418 PVMSVGA3DCONTEXT pContext;
7419 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
7420 AssertRCReturn(rc, rc);
7421
7422 AssertReturn(shid < SVGA3D_MAX_SHADER_IDS, VERR_INVALID_PARAMETER);
7423
7424 rc = vmsvga3dShaderParse(type, cbData, pShaderData);
7425 if (RT_FAILURE(rc))
7426 {
7427 AssertRC(rc);
7428 vmsvga3dShaderLogRel("Failed to parse", type, cbData, pShaderData);
7429 return rc;
7430 }
7431
7432 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7433
7434 if (type == SVGA3D_SHADERTYPE_VS)
7435 {
7436 if (shid >= pContext->cVertexShaders)
7437 {
7438 void *pvNew = RTMemRealloc(pContext->paVertexShader, sizeof(VMSVGA3DSHADER) * (shid + 1));
7439 AssertReturn(pvNew, VERR_NO_MEMORY);
7440 pContext->paVertexShader = (PVMSVGA3DSHADER)pvNew;
7441 memset(&pContext->paVertexShader[pContext->cVertexShaders], 0, sizeof(VMSVGA3DSHADER) * (shid + 1 - pContext->cVertexShaders));
7442 for (uint32_t i = pContext->cVertexShaders; i < shid + 1; i++)
7443 pContext->paVertexShader[i].id = SVGA3D_INVALID_ID;
7444 pContext->cVertexShaders = shid + 1;
7445 }
7446 /* If one already exists with this id, then destroy it now. */
7447 if (pContext->paVertexShader[shid].id != SVGA3D_INVALID_ID)
7448 vmsvga3dBackShaderDestroy(pThisCC, cid, shid, pContext->paVertexShader[shid].type);
7449
7450 pShader = &pContext->paVertexShader[shid];
7451 }
7452 else
7453 {
7454 Assert(type == SVGA3D_SHADERTYPE_PS);
7455 if (shid >= pContext->cPixelShaders)
7456 {
7457 void *pvNew = RTMemRealloc(pContext->paPixelShader, sizeof(VMSVGA3DSHADER) * (shid + 1));
7458 AssertReturn(pvNew, VERR_NO_MEMORY);
7459 pContext->paPixelShader = (PVMSVGA3DSHADER)pvNew;
7460 memset(&pContext->paPixelShader[pContext->cPixelShaders], 0, sizeof(VMSVGA3DSHADER) * (shid + 1 - pContext->cPixelShaders));
7461 for (uint32_t i = pContext->cPixelShaders; i < shid + 1; i++)
7462 pContext->paPixelShader[i].id = SVGA3D_INVALID_ID;
7463 pContext->cPixelShaders = shid + 1;
7464 }
7465 /* If one already exists with this id, then destroy it now. */
7466 if (pContext->paPixelShader[shid].id != SVGA3D_INVALID_ID)
7467 vmsvga3dBackShaderDestroy(pThisCC, cid, shid, pContext->paPixelShader[shid].type);
7468
7469 pShader = &pContext->paPixelShader[shid];
7470 }
7471
7472 memset(pShader, 0, sizeof(*pShader));
7473 pShader->id = shid;
7474 pShader->cid = cid;
7475 pShader->type = type;
7476 pShader->cbData = cbData;
7477 pShader->pShaderProgram = RTMemAllocZ(cbData);
7478 AssertReturn(pShader->pShaderProgram, VERR_NO_MEMORY);
7479 memcpy(pShader->pShaderProgram, pShaderData, cbData);
7480
7481#ifdef DUMP_SHADER_DISASSEMBLY
7482 LPD3DXBUFFER pDisassembly;
7483 HRESULT hr = D3DXDisassembleShader((const DWORD *)pShaderData, FALSE, NULL, &pDisassembly);
7484 if (hr == D3D_OK)
7485 {
7486 Log(("Shader disassembly:\n%s\n", pDisassembly->GetBufferPointer()));
7487 pDisassembly->Release();
7488 }
7489#endif
7490
7491 switch (type)
7492 {
7493 case SVGA3D_SHADERTYPE_VS:
7494 rc = ShaderCreateVertexShader(pContext->pShaderContext, (const uint32_t *)pShaderData, cbData, &pShader->u.pVertexShader);
7495 AssertRC(rc);
7496 break;
7497
7498 case SVGA3D_SHADERTYPE_PS:
7499 rc = ShaderCreatePixelShader(pContext->pShaderContext, (const uint32_t *)pShaderData, cbData, &pShader->u.pPixelShader);
7500 AssertRC(rc);
7501 break;
7502
7503 default:
7504 AssertFailedReturn(VERR_INVALID_PARAMETER);
7505 }
7506 if (rc != VINF_SUCCESS)
7507 {
7508 vmsvga3dShaderLogRel("Failed to create", type, cbData, pShaderData);
7509
7510 RTMemFree(pShader->pShaderProgram);
7511 memset(pShader, 0, sizeof(*pShader));
7512 pShader->id = SVGA3D_INVALID_ID;
7513 }
7514
7515 return rc;
7516}
7517
7518static DECLCALLBACK(int) vmsvga3dBackShaderDestroy(PVGASTATECC pThisCC, uint32_t cid, uint32_t shid, SVGA3dShaderType type)
7519{
7520 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7521 AssertReturn(pState, VERR_NO_MEMORY);
7522 PVMSVGA3DSHADER pShader = NULL;
7523
7524 Log(("vmsvga3dShaderDestroy cid=%u shid=%d type=%s\n", cid, shid, (type == SVGA3D_SHADERTYPE_VS) ? "VERTEX" : "PIXEL"));
7525
7526 PVMSVGA3DCONTEXT pContext;
7527 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
7528 AssertRCReturn(rc, rc);
7529
7530 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7531
7532 if (type == SVGA3D_SHADERTYPE_VS)
7533 {
7534 if ( shid < pContext->cVertexShaders
7535 && pContext->paVertexShader[shid].id == shid)
7536 {
7537 pShader = &pContext->paVertexShader[shid];
7538 if (pContext->state.shidVertex == shid)
7539 {
7540 rc = ShaderSetVertexShader(pContext->pShaderContext, NULL);
7541 AssertRC(rc);
7542 }
7543
7544 rc = ShaderDestroyVertexShader(pContext->pShaderContext, pShader->u.pVertexShader);
7545 AssertRC(rc);
7546 }
7547 }
7548 else
7549 {
7550 Assert(type == SVGA3D_SHADERTYPE_PS);
7551 if ( shid < pContext->cPixelShaders
7552 && pContext->paPixelShader[shid].id == shid)
7553 {
7554 pShader = &pContext->paPixelShader[shid];
7555 if (pContext->state.shidPixel == shid)
7556 {
7557 ShaderSetPixelShader(pContext->pShaderContext, NULL);
7558 AssertRC(rc);
7559 }
7560
7561 rc = ShaderDestroyPixelShader(pContext->pShaderContext, pShader->u.pPixelShader);
7562 AssertRC(rc);
7563 }
7564 }
7565
7566 if (pShader)
7567 {
7568 if (pShader->pShaderProgram)
7569 RTMemFree(pShader->pShaderProgram);
7570 memset(pShader, 0, sizeof(*pShader));
7571 pShader->id = SVGA3D_INVALID_ID;
7572 }
7573 else
7574 AssertFailedReturn(VERR_INVALID_PARAMETER);
7575
7576 return VINF_SUCCESS;
7577}
7578
7579static DECLCALLBACK(int) vmsvga3dBackShaderSet(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t cid, SVGA3dShaderType type, uint32_t shid)
7580{
7581 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7582 AssertReturn(pState, VERR_NO_MEMORY);
7583 int rc;
7584
7585 Log(("vmsvga3dShaderSet cid=%u type=%s shid=%d\n", cid, (type == SVGA3D_SHADERTYPE_VS) ? "VERTEX" : "PIXEL", shid));
7586
7587 if (!pContext)
7588 {
7589 rc = vmsvga3dContextFromCid(pState, cid, &pContext);
7590 AssertRCReturn(rc, rc);
7591 }
7592
7593 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7594
7595 if (type == SVGA3D_SHADERTYPE_VS)
7596 {
7597 /* Save for vm state save/restore. */
7598 pContext->state.shidVertex = shid;
7599 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_VERTEXSHADER;
7600
7601 if ( shid < pContext->cVertexShaders
7602 && pContext->paVertexShader[shid].id == shid)
7603 {
7604 PVMSVGA3DSHADER pShader = &pContext->paVertexShader[shid];
7605 Assert(type == pShader->type);
7606
7607 rc = ShaderSetVertexShader(pContext->pShaderContext, pShader->u.pVertexShader);
7608 AssertRCReturn(rc, rc);
7609 }
7610 else
7611 if (shid == SVGA_ID_INVALID)
7612 {
7613 /* Unselect shader. */
7614 rc = ShaderSetVertexShader(pContext->pShaderContext, NULL);
7615 AssertRCReturn(rc, rc);
7616 }
7617 else
7618 AssertFailedReturn(VERR_INVALID_PARAMETER);
7619 }
7620 else
7621 {
7622 /* Save for vm state save/restore. */
7623 pContext->state.shidPixel = shid;
7624 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_PIXELSHADER;
7625
7626 Assert(type == SVGA3D_SHADERTYPE_PS);
7627 if ( shid < pContext->cPixelShaders
7628 && pContext->paPixelShader[shid].id == shid)
7629 {
7630 PVMSVGA3DSHADER pShader = &pContext->paPixelShader[shid];
7631 Assert(type == pShader->type);
7632
7633 rc = ShaderSetPixelShader(pContext->pShaderContext, pShader->u.pPixelShader);
7634 AssertRCReturn(rc, rc);
7635 }
7636 else
7637 if (shid == SVGA_ID_INVALID)
7638 {
7639 /* Unselect shader. */
7640 rc = ShaderSetPixelShader(pContext->pShaderContext, NULL);
7641 AssertRCReturn(rc, rc);
7642 }
7643 else
7644 AssertFailedReturn(VERR_INVALID_PARAMETER);
7645 }
7646
7647 return VINF_SUCCESS;
7648}
7649
7650static DECLCALLBACK(int) vmsvga3dBackShaderSetConst(PVGASTATECC pThisCC, uint32_t cid, uint32_t reg, SVGA3dShaderType type, SVGA3dShaderConstType ctype, uint32_t cRegisters, uint32_t *pValues)
7651{
7652 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7653 AssertReturn(pState, VERR_NO_MEMORY);
7654
7655 Log(("vmsvga3dShaderSetConst cid=%u reg=%x type=%s cregs=%d ctype=%x\n", cid, reg, (type == SVGA3D_SHADERTYPE_VS) ? "VERTEX" : "PIXEL", cRegisters, ctype));
7656
7657 PVMSVGA3DCONTEXT pContext;
7658 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
7659 AssertRCReturn(rc, rc);
7660
7661 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7662
7663 for (uint32_t i = 0; i < cRegisters; i++)
7664 {
7665#ifdef LOG_ENABLED
7666 switch (ctype)
7667 {
7668 case SVGA3D_CONST_TYPE_FLOAT:
7669 {
7670 float *pValuesF = (float *)pValues;
7671 Log(("ConstantF %d: value=" FLOAT_FMT_STR ", " FLOAT_FMT_STR ", " FLOAT_FMT_STR ", " FLOAT_FMT_STR "\n",
7672 reg + i, FLOAT_FMT_ARGS(pValuesF[i*4 + 0]), FLOAT_FMT_ARGS(pValuesF[i*4 + 1]), FLOAT_FMT_ARGS(pValuesF[i*4 + 2]), FLOAT_FMT_ARGS(pValuesF[i*4 + 3])));
7673 break;
7674 }
7675
7676 case SVGA3D_CONST_TYPE_INT:
7677 Log(("ConstantI %d: value=%d, %d, %d, %d\n", reg + i, pValues[i*4 + 0], pValues[i*4 + 1], pValues[i*4 + 2], pValues[i*4 + 3]));
7678 break;
7679
7680 case SVGA3D_CONST_TYPE_BOOL:
7681 Log(("ConstantB %d: value=%d, %d, %d, %d\n", reg + i, pValues[i*4 + 0], pValues[i*4 + 1], pValues[i*4 + 2], pValues[i*4 + 3]));
7682 break;
7683
7684 default:
7685 AssertFailedReturn(VERR_INVALID_PARAMETER);
7686 }
7687#endif
7688 vmsvga3dSaveShaderConst(pContext, reg + i, type, ctype, pValues[i*4 + 0], pValues[i*4 + 1], pValues[i*4 + 2], pValues[i*4 + 3]);
7689 }
7690
7691 switch (type)
7692 {
7693 case SVGA3D_SHADERTYPE_VS:
7694 switch (ctype)
7695 {
7696 case SVGA3D_CONST_TYPE_FLOAT:
7697 rc = ShaderSetVertexShaderConstantF(pContext->pShaderContext, reg, (const float *)pValues, cRegisters);
7698 break;
7699
7700 case SVGA3D_CONST_TYPE_INT:
7701 rc = ShaderSetVertexShaderConstantI(pContext->pShaderContext, reg, (const int32_t *)pValues, cRegisters);
7702 break;
7703
7704 case SVGA3D_CONST_TYPE_BOOL:
7705 rc = ShaderSetVertexShaderConstantB(pContext->pShaderContext, reg, (const uint8_t *)pValues, cRegisters);
7706 break;
7707
7708 default:
7709 AssertFailedReturn(VERR_INVALID_PARAMETER);
7710 }
7711 AssertRCReturn(rc, rc);
7712 break;
7713
7714 case SVGA3D_SHADERTYPE_PS:
7715 switch (ctype)
7716 {
7717 case SVGA3D_CONST_TYPE_FLOAT:
7718 rc = ShaderSetPixelShaderConstantF(pContext->pShaderContext, reg, (const float *)pValues, cRegisters);
7719 break;
7720
7721 case SVGA3D_CONST_TYPE_INT:
7722 rc = ShaderSetPixelShaderConstantI(pContext->pShaderContext, reg, (const int32_t *)pValues, cRegisters);
7723 break;
7724
7725 case SVGA3D_CONST_TYPE_BOOL:
7726 rc = ShaderSetPixelShaderConstantB(pContext->pShaderContext, reg, (const uint8_t *)pValues, cRegisters);
7727 break;
7728
7729 default:
7730 AssertFailedReturn(VERR_INVALID_PARAMETER);
7731 }
7732 AssertRCReturn(rc, rc);
7733 break;
7734
7735 default:
7736 AssertFailedReturn(VERR_INVALID_PARAMETER);
7737 }
7738
7739 return VINF_SUCCESS;
7740}
7741
7742static DECLCALLBACK(int) vmsvga3dBackOcclusionQueryCreate(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext)
7743{
7744 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7745 AssertReturn(pState->ext.glGenQueries, VERR_NOT_SUPPORTED);
7746 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7747
7748 GLuint idQuery = 0;
7749 pState->ext.glGenQueries(1, &idQuery);
7750 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7751 AssertReturn(idQuery, VERR_INTERNAL_ERROR);
7752 pContext->occlusion.idQuery = idQuery;
7753 return VINF_SUCCESS;
7754}
7755
7756static DECLCALLBACK(int) vmsvga3dBackOcclusionQueryDelete(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext)
7757{
7758 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7759 AssertReturn(pState->ext.glDeleteQueries, VERR_NOT_SUPPORTED);
7760 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7761
7762 if (pContext->occlusion.idQuery)
7763 {
7764 pState->ext.glDeleteQueries(1, &pContext->occlusion.idQuery);
7765 }
7766 return VINF_SUCCESS;
7767}
7768
7769static DECLCALLBACK(int) vmsvga3dBackOcclusionQueryBegin(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext)
7770{
7771 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7772 AssertReturn(pState->ext.glBeginQuery, VERR_NOT_SUPPORTED);
7773 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7774
7775 pState->ext.glBeginQuery(GL_ANY_SAMPLES_PASSED, pContext->occlusion.idQuery);
7776 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7777 return VINF_SUCCESS;
7778}
7779
7780static DECLCALLBACK(int) vmsvga3dBackOcclusionQueryEnd(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext)
7781{
7782 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7783 AssertReturn(pState->ext.glEndQuery, VERR_NOT_SUPPORTED);
7784 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7785
7786 pState->ext.glEndQuery(GL_ANY_SAMPLES_PASSED);
7787 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7788 return VINF_SUCCESS;
7789}
7790
7791static DECLCALLBACK(int) vmsvga3dBackOcclusionQueryGetData(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t *pu32Pixels)
7792{
7793 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7794 AssertReturn(pState->ext.glGetQueryObjectuiv, VERR_NOT_SUPPORTED);
7795 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7796
7797 GLuint pixels = 0;
7798 pState->ext.glGetQueryObjectuiv(pContext->occlusion.idQuery, GL_QUERY_RESULT, &pixels);
7799 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7800
7801 *pu32Pixels = (uint32_t)pixels;
7802 return VINF_SUCCESS;
7803}
7804
7805/**
7806 * Worker for vmsvga3dUpdateHeapBuffersForSurfaces.
7807 *
7808 * This will allocate heap buffers if necessary, thus increasing the memory
7809 * usage of the process.
7810 *
7811 * @todo Would be interesting to share this code with the saved state code.
7812 *
7813 * @returns VBox status code.
7814 * @param pThisCC The VGA/VMSVGA context.
7815 * @param pSurface The surface to refresh the heap buffers for.
7816 */
7817static DECLCALLBACK(int) vmsvga3dBackSurfaceUpdateHeapBuffers(PVGASTATECC pThisCC, PVMSVGA3DSURFACE pSurface)
7818{
7819 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7820 AssertReturn(pState, VERR_INVALID_STATE);
7821
7822 /*
7823 * Currently we've got trouble retreving bit for DEPTHSTENCIL
7824 * surfaces both for OpenGL and D3D, so skip these here (don't
7825 * wast memory on them).
7826 */
7827 uint32_t const fSwitchFlags = pSurface->f.s.surface1Flags & VMSVGA3D_SURFACE_HINT_SWITCH_MASK;
7828 if ( fSwitchFlags != SVGA3D_SURFACE_HINT_DEPTHSTENCIL
7829 && fSwitchFlags != (SVGA3D_SURFACE_HINT_DEPTHSTENCIL | SVGA3D_SURFACE_HINT_TEXTURE))
7830 {
7831 /*
7832 * Change OpenGL context to the one the surface is associated with.
7833 */
7834 PVMSVGA3DCONTEXT pContext = &pState->SharedCtx;
7835 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7836
7837 /*
7838 * Work thru each mipmap level for each face.
7839 */
7840 for (uint32_t iFace = 0; iFace < pSurface->cFaces; iFace++)
7841 {
7842 PVMSVGA3DMIPMAPLEVEL pMipmapLevel = &pSurface->paMipmapLevels[iFace * pSurface->cLevels];
7843 for (uint32_t i = 0; i < pSurface->cLevels; i++, pMipmapLevel++)
7844 {
7845 if (VMSVGA3DSURFACE_HAS_HW_SURFACE(pSurface))
7846 {
7847 Assert(pMipmapLevel->cbSurface);
7848 Assert(pMipmapLevel->cbSurface == pMipmapLevel->cbSurfacePlane * pMipmapLevel->mipmapSize.depth);
7849
7850 /*
7851 * Make sure we've got surface memory buffer.
7852 */
7853 uint8_t *pbDst = (uint8_t *)pMipmapLevel->pSurfaceData;
7854 if (!pbDst)
7855 {
7856 pMipmapLevel->pSurfaceData = pbDst = (uint8_t *)RTMemAllocZ(pMipmapLevel->cbSurface);
7857 AssertReturn(pbDst, VERR_NO_MEMORY);
7858 }
7859
7860 /*
7861 * OpenGL specifics.
7862 */
7863 switch (pSurface->enmOGLResType)
7864 {
7865 case VMSVGA3D_OGLRESTYPE_TEXTURE:
7866 {
7867 GLint activeTexture;
7868 glGetIntegerv(GL_TEXTURE_BINDING_2D, &activeTexture);
7869 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7870
7871 glBindTexture(GL_TEXTURE_2D, pSurface->oglId.texture);
7872 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7873
7874 /* Set row length and alignment of the output data. */
7875 VMSVGAPACKPARAMS SavedParams;
7876 vmsvga3dOglSetPackParams(pState, pContext, pSurface, &SavedParams);
7877
7878 glGetTexImage(GL_TEXTURE_2D,
7879 i,
7880 pSurface->formatGL,
7881 pSurface->typeGL,
7882 pbDst);
7883 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7884
7885 vmsvga3dOglRestorePackParams(pState, pContext, pSurface, &SavedParams);
7886
7887 /* Restore the old active texture. */
7888 glBindTexture(GL_TEXTURE_2D, activeTexture);
7889 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7890 break;
7891 }
7892
7893 case VMSVGA3D_OGLRESTYPE_BUFFER:
7894 {
7895 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, pSurface->oglId.buffer);
7896 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7897
7898 void *pvSrc = pState->ext.glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY);
7899 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7900 if (RT_VALID_PTR(pvSrc))
7901 memcpy(pbDst, pvSrc, pMipmapLevel->cbSurface);
7902 else
7903 AssertPtr(pvSrc);
7904
7905 pState->ext.glUnmapBuffer(GL_ARRAY_BUFFER);
7906 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7907
7908 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, 0);
7909 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7910 break;
7911 }
7912
7913 default:
7914 AssertMsgFailed(("%#x\n", fSwitchFlags));
7915 }
7916 }
7917 /* else: There is no data in hardware yet, so whatever we got is already current. */
7918 }
7919 }
7920 }
7921
7922 return VINF_SUCCESS;
7923}
7924
7925static DECLCALLBACK(int) vmsvga3dBackQueryInterface(PVGASTATECC pThisCC, char const *pszInterfaceName, void *pvInterfaceFuncs, size_t cbInterfaceFuncs)
7926{
7927 RT_NOREF(pThisCC);
7928
7929 int rc = VINF_SUCCESS;
7930 if (RTStrCmp(pszInterfaceName, VMSVGA3D_BACKEND_INTERFACE_NAME_3D) == 0)
7931 {
7932 if (cbInterfaceFuncs == sizeof(VMSVGA3DBACKENDFUNCS3D))
7933 {
7934 if (pvInterfaceFuncs)
7935 {
7936 VMSVGA3DBACKENDFUNCS3D *p = (VMSVGA3DBACKENDFUNCS3D *)pvInterfaceFuncs;
7937 p->pfnInit = vmsvga3dBackInit;
7938 p->pfnPowerOn = vmsvga3dBackPowerOn;
7939 p->pfnTerminate = vmsvga3dBackTerminate;
7940 p->pfnReset = vmsvga3dBackReset;
7941 p->pfnQueryCaps = vmsvga3dBackQueryCaps;
7942 p->pfnChangeMode = vmsvga3dBackChangeMode;
7943 p->pfnCreateTexture = vmsvga3dBackCreateTexture;
7944 p->pfnSurfaceDestroy = vmsvga3dBackSurfaceDestroy;
7945 p->pfnSurfaceInvalidateImage = vmsvga3dBackSurfaceInvalidateImage;
7946 p->pfnSurfaceCopy = vmsvga3dBackSurfaceCopy;
7947 p->pfnSurfaceDMACopyBox = vmsvga3dBackSurfaceDMACopyBox;
7948 p->pfnSurfaceStretchBlt = vmsvga3dBackSurfaceStretchBlt;
7949 p->pfnUpdateHostScreenViewport = vmsvga3dBackUpdateHostScreenViewport;
7950 p->pfnDefineScreen = vmsvga3dBackDefineScreen;
7951 p->pfnDestroyScreen = vmsvga3dBackDestroyScreen;
7952 p->pfnSurfaceBlitToScreen = vmsvga3dBackSurfaceBlitToScreen;
7953 p->pfnSurfaceUpdateHeapBuffers = vmsvga3dBackSurfaceUpdateHeapBuffers;
7954 }
7955 }
7956 else
7957 {
7958 AssertFailed();
7959 rc = VERR_INVALID_PARAMETER;
7960 }
7961 }
7962 else if (RTStrCmp(pszInterfaceName, VMSVGA3D_BACKEND_INTERFACE_NAME_VGPU9) == 0)
7963 {
7964 if (cbInterfaceFuncs == sizeof(VMSVGA3DBACKENDFUNCSVGPU9))
7965 {
7966 if (pvInterfaceFuncs)
7967 {
7968 VMSVGA3DBACKENDFUNCSVGPU9 *p = (VMSVGA3DBACKENDFUNCSVGPU9 *)pvInterfaceFuncs;
7969 p->pfnContextDefine = vmsvga3dBackContextDefine;
7970 p->pfnContextDestroy = vmsvga3dBackContextDestroy;
7971 p->pfnSetTransform = vmsvga3dBackSetTransform;
7972 p->pfnSetZRange = vmsvga3dBackSetZRange;
7973 p->pfnSetRenderState = vmsvga3dBackSetRenderState;
7974 p->pfnSetRenderTarget = vmsvga3dBackSetRenderTarget;
7975 p->pfnSetTextureState = vmsvga3dBackSetTextureState;
7976 p->pfnSetMaterial = vmsvga3dBackSetMaterial;
7977 p->pfnSetLightData = vmsvga3dBackSetLightData;
7978 p->pfnSetLightEnabled = vmsvga3dBackSetLightEnabled;
7979 p->pfnSetViewPort = vmsvga3dBackSetViewPort;
7980 p->pfnSetClipPlane = vmsvga3dBackSetClipPlane;
7981 p->pfnCommandClear = vmsvga3dBackCommandClear;
7982 p->pfnDrawPrimitives = vmsvga3dBackDrawPrimitives;
7983 p->pfnSetScissorRect = vmsvga3dBackSetScissorRect;
7984 p->pfnGenerateMipmaps = vmsvga3dBackGenerateMipmaps;
7985 p->pfnShaderDefine = vmsvga3dBackShaderDefine;
7986 p->pfnShaderDestroy = vmsvga3dBackShaderDestroy;
7987 p->pfnShaderSet = vmsvga3dBackShaderSet;
7988 p->pfnShaderSetConst = vmsvga3dBackShaderSetConst;
7989 p->pfnOcclusionQueryCreate = vmsvga3dBackOcclusionQueryCreate;
7990 p->pfnOcclusionQueryDelete = vmsvga3dBackOcclusionQueryDelete;
7991 p->pfnOcclusionQueryBegin = vmsvga3dBackOcclusionQueryBegin;
7992 p->pfnOcclusionQueryEnd = vmsvga3dBackOcclusionQueryEnd;
7993 p->pfnOcclusionQueryGetData = vmsvga3dBackOcclusionQueryGetData;
7994 }
7995 }
7996 else
7997 {
7998 AssertFailed();
7999 rc = VERR_INVALID_PARAMETER;
8000 }
8001 }
8002 else
8003 rc = VERR_NOT_IMPLEMENTED;
8004 return rc;
8005}
8006
8007
8008extern VMSVGA3DBACKENDDESC const g_BackendLegacy =
8009{
8010 "LEGACY",
8011 vmsvga3dBackQueryInterface
8012};
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