VirtualBox

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

Last change on this file since 95231 was 95231, checked in by vboxsync, 3 years ago

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

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 310.8 KB
Line 
1/* $Id: DevVGA-SVGA3d-ogl.cpp 95231 2022-06-08 15:26:23Z 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 pSurface The surface being destroyed.
2053 */
2054static DECLCALLBACK(void) vmsvga3dBackSurfaceDestroy(PVGASTATECC pThisCC, bool fClearCOTableEntry, PVMSVGA3DSURFACE pSurface)
2055{
2056 RT_NOREF(fClearCOTableEntry);
2057
2058 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
2059 AssertReturnVoid(pState);
2060
2061 PVMSVGA3DCONTEXT pContext = &pState->SharedCtx;
2062 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
2063
2064 switch (pSurface->enmOGLResType)
2065 {
2066 case VMSVGA3D_OGLRESTYPE_BUFFER:
2067 Assert(pSurface->oglId.buffer != OPENGL_INVALID_ID);
2068 pState->ext.glDeleteBuffers(1, &pSurface->oglId.buffer);
2069 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2070 break;
2071
2072 case VMSVGA3D_OGLRESTYPE_TEXTURE:
2073 Assert(pSurface->oglId.texture != OPENGL_INVALID_ID);
2074 glDeleteTextures(1, &pSurface->oglId.texture);
2075 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2076 if (pSurface->fEmulated)
2077 {
2078 if (pSurface->idEmulated)
2079 {
2080 glDeleteTextures(1, &pSurface->idEmulated);
2081 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2082 }
2083 }
2084 else
2085 {
2086 Assert(!pSurface->idEmulated);
2087 }
2088 break;
2089
2090 case VMSVGA3D_OGLRESTYPE_RENDERBUFFER:
2091 Assert(pSurface->oglId.renderbuffer != OPENGL_INVALID_ID);
2092 pState->ext.glDeleteRenderbuffers(1, &pSurface->oglId.renderbuffer);
2093 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2094 break;
2095
2096 default:
2097 AssertMsg(!VMSVGA3DSURFACE_HAS_HW_SURFACE(pSurface),
2098 ("hint=%#x, type=%d\n",
2099 (pSurface->f.s.surface1Flags & VMSVGA3D_SURFACE_HINT_SWITCH_MASK), pSurface->enmOGLResType));
2100 break;
2101 }
2102}
2103
2104
2105static DECLCALLBACK(void) vmsvga3dBackSurfaceInvalidateImage(PVGASTATECC pThisCC, PVMSVGA3DSURFACE pSurface, uint32_t uFace, uint32_t uMipmap)
2106{
2107 RT_NOREF(pThisCC, pSurface, uFace, uMipmap);
2108}
2109
2110
2111static DECLCALLBACK(int) vmsvga3dBackSurfaceCopy(PVGASTATECC pThisCC, SVGA3dSurfaceImageId dest, SVGA3dSurfaceImageId src,
2112 uint32_t cCopyBoxes, SVGA3dCopyBox *pBox)
2113{
2114 int rc;
2115
2116 LogFunc(("Copy %d boxes from sid=%u face=%u mipmap=%u to sid=%u face=%u mipmap=%u\n",
2117 cCopyBoxes, src.sid, src.face, src.mipmap, dest.sid, dest.face, dest.mipmap));
2118
2119 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
2120 AssertReturn(pState, VERR_INVALID_STATE);
2121
2122 PVMSVGA3DSURFACE pSurfaceSrc;
2123 rc = vmsvga3dSurfaceFromSid(pState, src.sid, &pSurfaceSrc);
2124 AssertRCReturn(rc, rc);
2125
2126 PVMSVGA3DSURFACE pSurfaceDst;
2127 rc = vmsvga3dSurfaceFromSid(pState, dest.sid, &pSurfaceDst);
2128 AssertRCReturn(rc, rc);
2129
2130 if (!VMSVGA3DSURFACE_HAS_HW_SURFACE(pSurfaceSrc))
2131 {
2132 /* The source surface is still in memory. */
2133 PVMSVGA3DMIPMAPLEVEL pMipmapLevelSrc;
2134 rc = vmsvga3dMipmapLevel(pSurfaceSrc, src.face, src.mipmap, &pMipmapLevelSrc);
2135 AssertRCReturn(rc, rc);
2136
2137 PVMSVGA3DMIPMAPLEVEL pMipmapLevelDst;
2138 rc = vmsvga3dMipmapLevel(pSurfaceDst, dest.face, dest.mipmap, &pMipmapLevelDst);
2139 AssertRCReturn(rc, rc);
2140
2141 /* The copy operation is performed on the shared context. */
2142 PVMSVGA3DCONTEXT pContext = &pState->SharedCtx;
2143 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
2144
2145 /* Use glTexSubImage to upload the data to the destination texture.
2146 * The latter must be an OpenGL texture.
2147 */
2148 if (!VMSVGA3DSURFACE_HAS_HW_SURFACE(pSurfaceDst))
2149 {
2150 LogFunc(("dest sid=%u type=0x%x format=%d -> create texture\n", dest.sid, pSurfaceDst->f.s.surface1Flags, pSurfaceDst->format));
2151 rc = vmsvga3dBackCreateTexture(pThisCC, pContext, pContext->id, pSurfaceDst);
2152 AssertRCReturn(rc, rc);
2153 }
2154
2155 GLenum target;
2156 if (pSurfaceDst->targetGL == GL_TEXTURE_CUBE_MAP)
2157 target = vmsvga3dCubemapFaceFromIndex(dest.face);
2158 else
2159 {
2160 AssertMsg(pSurfaceDst->targetGL == GL_TEXTURE_2D, ("Test %#x\n", pSurfaceDst->targetGL));
2161 target = pSurfaceDst->targetGL;
2162 }
2163
2164 /* Save the unpacking parameters and set what we need here. */
2165 VMSVGAPACKPARAMS SavedParams;
2166 vmsvga3dOglSetUnpackParams(pState, pContext,
2167 pMipmapLevelSrc->mipmapSize.width,
2168 target == GL_TEXTURE_3D ? pMipmapLevelSrc->mipmapSize.height : 0,
2169 &SavedParams);
2170
2171 glBindTexture(pSurfaceDst->targetGL, pSurfaceDst->oglId.texture);
2172 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2173
2174 for (uint32_t i = 0; i < cCopyBoxes; ++i)
2175 {
2176 SVGA3dCopyBox clipBox = pBox[i];
2177 vmsvgaR3ClipCopyBox(&pMipmapLevelSrc->mipmapSize, &pMipmapLevelDst->mipmapSize, &clipBox);
2178 if ( !clipBox.w
2179 || !clipBox.h
2180 || !clipBox.d)
2181 {
2182 LogFunc(("Skipped empty box.\n"));
2183 continue;
2184 }
2185
2186 LogFunc(("copy box %d,%d,%d %dx%d to %d,%d,%d\n",
2187 clipBox.srcx, clipBox.srcy, clipBox.srcz, clipBox.w, clipBox.h, clipBox.x, clipBox.y, clipBox.z));
2188
2189 uint32_t const u32BlockX = clipBox.srcx / pSurfaceSrc->cxBlock;
2190 uint32_t const u32BlockY = clipBox.srcy / pSurfaceSrc->cyBlock;
2191 uint32_t const u32BlockZ = clipBox.srcz;
2192 Assert(u32BlockX * pSurfaceSrc->cxBlock == clipBox.srcx);
2193 Assert(u32BlockY * pSurfaceSrc->cyBlock == clipBox.srcy);
2194
2195 uint8_t const *pSrcBits = (uint8_t *)pMipmapLevelSrc->pSurfaceData
2196 + pMipmapLevelSrc->cbSurfacePlane * u32BlockZ
2197 + pMipmapLevelSrc->cbSurfacePitch * u32BlockY
2198 + pSurfaceSrc->cbBlock * u32BlockX;
2199
2200 if (target == GL_TEXTURE_3D)
2201 {
2202 if ( pSurfaceDst->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
2203 || pSurfaceDst->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
2204 || pSurfaceDst->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
2205 {
2206 uint32_t const cBlocksX = (clipBox.w + pSurfaceSrc->cxBlock - 1) / pSurfaceSrc->cxBlock;
2207 uint32_t const cBlocksY = (clipBox.h + pSurfaceSrc->cyBlock - 1) / pSurfaceSrc->cyBlock;
2208 uint32_t const imageSize = cBlocksX * cBlocksY * clipBox.d * pSurfaceSrc->cbBlock;
2209 pState->ext.glCompressedTexSubImage3D(target, dest.mipmap,
2210 clipBox.x, clipBox.y, clipBox.z,
2211 clipBox.w, clipBox.h, clipBox.d,
2212 pSurfaceSrc->internalFormatGL, (GLsizei)imageSize, pSrcBits);
2213 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2214 }
2215 else
2216 {
2217 pState->ext.glTexSubImage3D(target, dest.mipmap,
2218 clipBox.x, clipBox.y, clipBox.z,
2219 clipBox.w, clipBox.h, clipBox.d,
2220 pSurfaceSrc->formatGL, pSurfaceSrc->typeGL, pSrcBits);
2221 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2222 }
2223 }
2224 else
2225 {
2226 if ( pSurfaceDst->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
2227 || pSurfaceDst->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
2228 || pSurfaceDst->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
2229 {
2230 uint32_t const cBlocksX = (clipBox.w + pSurfaceSrc->cxBlock - 1) / pSurfaceSrc->cxBlock;
2231 uint32_t const cBlocksY = (clipBox.h + pSurfaceSrc->cyBlock - 1) / pSurfaceSrc->cyBlock;
2232 uint32_t const imageSize = cBlocksX * cBlocksY * pSurfaceSrc->cbBlock;
2233 pState->ext.glCompressedTexSubImage2D(target, dest.mipmap,
2234 clipBox.x, clipBox.y, clipBox.w, clipBox.h,
2235 pSurfaceSrc->internalFormatGL, (GLsizei)imageSize, pSrcBits);
2236 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2237 }
2238 else
2239 {
2240 glTexSubImage2D(target, dest.mipmap,
2241 clipBox.x, clipBox.y, clipBox.w, clipBox.h,
2242 pSurfaceSrc->formatGL, pSurfaceSrc->typeGL, pSrcBits);
2243 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2244 }
2245 }
2246 }
2247
2248 glBindTexture(pSurfaceDst->targetGL, 0);
2249 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2250
2251 vmsvga3dOglRestoreUnpackParams(pState, pContext, &SavedParams);
2252
2253 return VINF_SUCCESS;
2254 }
2255
2256 PVGASTATE pThis = PDMDEVINS_2_DATA(pThisCC->pDevIns, PVGASTATE);
2257 for (uint32_t i = 0; i < cCopyBoxes; i++)
2258 {
2259 SVGA3dBox destBox, srcBox;
2260
2261 srcBox.x = pBox[i].srcx;
2262 srcBox.y = pBox[i].srcy;
2263 srcBox.z = pBox[i].srcz;
2264 srcBox.w = pBox[i].w;
2265 srcBox.h = pBox[i].h;
2266 srcBox.d = pBox[i].d;
2267
2268 destBox.x = pBox[i].x;
2269 destBox.y = pBox[i].y;
2270 destBox.z = pBox[i].z;
2271 destBox.w = pBox[i].w;
2272 destBox.h = pBox[i].h;
2273 destBox.d = pBox[i].d;
2274
2275 /* No stretching is required, therefore use SVGA3D_STRETCH_BLT_POINT which translated to GL_NEAREST. */
2276 rc = vmsvga3dSurfaceStretchBlt(pThis, pThisCC, &dest, &destBox, &src, &srcBox, SVGA3D_STRETCH_BLT_POINT);
2277 AssertRCReturn(rc, rc);
2278 }
2279 return VINF_SUCCESS;
2280}
2281
2282
2283/**
2284 * Saves texture unpacking parameters and loads the specified ones.
2285 *
2286 * @param pState The VMSVGA3D state structure.
2287 * @param pContext The active context.
2288 * @param cxRow The number of pixels in a row. 0 for the entire width.
2289 * @param cyImage The height of the image in pixels. 0 for the entire height.
2290 * @param pSave Where to save stuff.
2291 */
2292void vmsvga3dOglSetUnpackParams(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext, GLint cxRow, GLint cyImage,
2293 PVMSVGAPACKPARAMS pSave)
2294{
2295 RT_NOREF(pState);
2296
2297 /*
2298 * Save (ignore errors, setting the defaults we want and avoids restore).
2299 */
2300 pSave->iAlignment = 1;
2301 VMSVGA3D_ASSERT_GL_CALL(glGetIntegerv(GL_UNPACK_ALIGNMENT, &pSave->iAlignment), pState, pContext);
2302 pSave->cxRow = 0;
2303 VMSVGA3D_ASSERT_GL_CALL(glGetIntegerv(GL_UNPACK_ROW_LENGTH, &pSave->cxRow), pState, pContext);
2304 pSave->cyImage = 0;
2305 VMSVGA3D_ASSERT_GL_CALL(glGetIntegerv(GL_UNPACK_IMAGE_HEIGHT, &pSave->cyImage), pState, pContext);
2306
2307#ifdef VMSVGA3D_PARANOID_TEXTURE_PACKING
2308 pSave->fSwapBytes = GL_FALSE;
2309 glGetBooleanv(GL_UNPACK_SWAP_BYTES, &pSave->fSwapBytes);
2310 Assert(pSave->fSwapBytes == GL_FALSE);
2311
2312 pSave->fLsbFirst = GL_FALSE;
2313 glGetBooleanv(GL_UNPACK_LSB_FIRST, &pSave->fLsbFirst);
2314 Assert(pSave->fLsbFirst == GL_FALSE);
2315
2316 pSave->cSkipRows = 0;
2317 glGetIntegerv(GL_UNPACK_SKIP_ROWS, &pSave->cSkipRows);
2318 Assert(pSave->cSkipRows == 0);
2319
2320 pSave->cSkipPixels = 0;
2321 glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &pSave->cSkipPixels);
2322 Assert(pSave->cSkipPixels == 0);
2323
2324 pSave->cSkipImages = 0;
2325 glGetIntegerv(GL_UNPACK_SKIP_IMAGES, &pSave->cSkipImages);
2326 Assert(pSave->cSkipImages == 0);
2327
2328 VMSVGA3D_CLEAR_GL_ERRORS();
2329#endif
2330
2331 /*
2332 * Setup unpack.
2333 *
2334 * Note! We use 1 as alignment here because we currently don't do any
2335 * aligning of line pitches anywhere.
2336 */
2337 pSave->fChanged = 0;
2338 if (pSave->iAlignment != 1)
2339 {
2340 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_ALIGNMENT, 1), pState, pContext);
2341 pSave->fChanged |= VMSVGAPACKPARAMS_ALIGNMENT;
2342 }
2343 if (pSave->cxRow != cxRow)
2344 {
2345 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, cxRow), pState, pContext);
2346 pSave->fChanged |= VMSVGAPACKPARAMS_ROW_LENGTH;
2347 }
2348 if (pSave->cyImage != cyImage)
2349 {
2350 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, cyImage), pState, pContext);
2351 pSave->fChanged |= VMSVGAPACKPARAMS_IMAGE_HEIGHT;
2352 }
2353#ifdef VMSVGA3D_PARANOID_TEXTURE_PACKING
2354 if (pSave->fSwapBytes != 0)
2355 {
2356 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE), pState, pContext);
2357 pSave->fChanged |= VMSVGAPACKPARAMS_SWAP_BYTES;
2358 }
2359 if (pSave->fLsbFirst != 0)
2360 {
2361 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE), pState, pContext);
2362 pSave->fChanged |= VMSVGAPACKPARAMS_LSB_FIRST;
2363 }
2364 if (pSave->cSkipRows != 0)
2365 {
2366 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SKIP_ROWS, 0), pState, pContext);
2367 pSave->fChanged |= VMSVGAPACKPARAMS_SKIP_ROWS;
2368 }
2369 if (pSave->cSkipPixels != 0)
2370 {
2371 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0), pState, pContext);
2372 pSave->fChanged |= VMSVGAPACKPARAMS_SKIP_PIXELS;
2373 }
2374 if (pSave->cSkipImages != 0)
2375 {
2376 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SKIP_IMAGES, 0), pState, pContext);
2377 pSave->fChanged |= VMSVGAPACKPARAMS_SKIP_IMAGES;
2378 }
2379#endif
2380}
2381
2382
2383/**
2384 * Restores texture unpacking parameters.
2385 *
2386 * @param pState The VMSVGA3D state structure.
2387 * @param pContext The active context.
2388 * @param pSave Where stuff was saved.
2389 */
2390void vmsvga3dOglRestoreUnpackParams(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext,
2391 PCVMSVGAPACKPARAMS pSave)
2392{
2393 RT_NOREF(pState);
2394
2395 if (pSave->fChanged & VMSVGAPACKPARAMS_ALIGNMENT)
2396 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_ALIGNMENT, pSave->iAlignment), pState, pContext);
2397 if (pSave->fChanged & VMSVGAPACKPARAMS_ROW_LENGTH)
2398 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, pSave->cxRow), pState, pContext);
2399 if (pSave->fChanged & VMSVGAPACKPARAMS_IMAGE_HEIGHT)
2400 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, pSave->cyImage), pState, pContext);
2401#ifdef VMSVGA3D_PARANOID_TEXTURE_PACKING
2402 if (pSave->fChanged & VMSVGAPACKPARAMS_SWAP_BYTES)
2403 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SWAP_BYTES, pSave->fSwapBytes), pState, pContext);
2404 if (pSave->fChanged & VMSVGAPACKPARAMS_LSB_FIRST)
2405 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_LSB_FIRST, pSave->fLsbFirst), pState, pContext);
2406 if (pSave->fChanged & VMSVGAPACKPARAMS_SKIP_ROWS)
2407 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SKIP_ROWS, pSave->cSkipRows), pState, pContext);
2408 if (pSave->fChanged & VMSVGAPACKPARAMS_SKIP_PIXELS)
2409 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SKIP_PIXELS, pSave->cSkipPixels), pState, pContext);
2410 if (pSave->fChanged & VMSVGAPACKPARAMS_SKIP_IMAGES)
2411 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_UNPACK_SKIP_IMAGES, pSave->cSkipImages), pState, pContext);
2412#endif
2413}
2414
2415/**
2416 * Create D3D/OpenGL texture object for the specified surface.
2417 *
2418 * Surfaces are created when needed.
2419 *
2420 * @param pThisCC The device context.
2421 * @param pContext The context.
2422 * @param idAssociatedContext Probably the same as pContext->id.
2423 * @param pSurface The surface to create the texture for.
2424 */
2425static DECLCALLBACK(int) vmsvga3dBackCreateTexture(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t idAssociatedContext,
2426 PVMSVGA3DSURFACE pSurface)
2427{
2428 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
2429
2430 RT_NOREF(idAssociatedContext);
2431
2432 LogFunc(("sid=%u\n", pSurface->id));
2433
2434 uint32_t const numMipLevels = pSurface->cLevels;
2435
2436 /* Fugure out what kind of texture we are creating. */
2437 GLenum binding;
2438 GLenum target;
2439 if (pSurface->f.s.surface1Flags & SVGA3D_SURFACE_CUBEMAP)
2440 {
2441 Assert(pSurface->cFaces == 6);
2442
2443 binding = GL_TEXTURE_BINDING_CUBE_MAP;
2444 target = GL_TEXTURE_CUBE_MAP;
2445 }
2446 else
2447 {
2448 if (pSurface->paMipmapLevels[0].mipmapSize.depth > 1)
2449 {
2450 binding = GL_TEXTURE_BINDING_3D;
2451 target = GL_TEXTURE_3D;
2452 }
2453 else
2454 {
2455 Assert(pSurface->cFaces == 1);
2456
2457 binding = GL_TEXTURE_BINDING_2D;
2458 target = GL_TEXTURE_2D;
2459 }
2460 }
2461
2462 /* All textures are created in the SharedCtx. */
2463 uint32_t idPrevCtx = pState->idActiveContext;
2464 pContext = &pState->SharedCtx;
2465 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
2466
2467 glGenTextures(1, &pSurface->oglId.texture);
2468 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2469 if (pSurface->fEmulated)
2470 {
2471 glGenTextures(1, &pSurface->idEmulated);
2472 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2473 }
2474 pSurface->enmOGLResType = VMSVGA3D_OGLRESTYPE_TEXTURE;
2475
2476 GLint activeTexture = 0;
2477 glGetIntegerv(binding, &activeTexture);
2478 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2479
2480 /* Must bind texture to the current context in order to change it. */
2481 glBindTexture(target, pSurface->oglId.texture);
2482 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2483
2484 /* Set the unpacking parameters. */
2485 VMSVGAPACKPARAMS SavedParams;
2486 vmsvga3dOglSetUnpackParams(pState, pContext, 0, 0, &SavedParams);
2487
2488 /** @todo Set the mip map generation filter settings. */
2489
2490 /* Set the mipmap base and max level parameters. */
2491 glTexParameteri(target, GL_TEXTURE_BASE_LEVEL, 0);
2492 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2493 glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, pSurface->cLevels - 1);
2494 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2495
2496 if (pSurface->fDirty)
2497 LogFunc(("sync dirty texture\n"));
2498
2499 /* Always allocate and initialize all mipmap levels; non-initialized mipmap levels used as render targets cause failures. */
2500 if (target == GL_TEXTURE_3D)
2501 {
2502 for (uint32_t i = 0; i < numMipLevels; ++i)
2503 {
2504 /* Allocate and initialize texture memory. Passing the zero filled pSurfaceData avoids
2505 * exposing random host memory to the guest and helps a with the fedora 21 surface
2506 * corruption issues (launchpad, background, search field, login).
2507 */
2508 PVMSVGA3DMIPMAPLEVEL pMipLevel = &pSurface->paMipmapLevels[i];
2509
2510 LogFunc(("sync dirty 3D texture mipmap level %d (pitch %x) (dirty %d)\n",
2511 i, pMipLevel->cbSurfacePitch, pMipLevel->fDirty));
2512
2513 if ( pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
2514 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
2515 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
2516 {
2517 pState->ext.glCompressedTexImage3D(GL_TEXTURE_3D,
2518 i,
2519 pSurface->internalFormatGL,
2520 pMipLevel->mipmapSize.width,
2521 pMipLevel->mipmapSize.height,
2522 pMipLevel->mipmapSize.depth,
2523 0,
2524 pMipLevel->cbSurface,
2525 pMipLevel->pSurfaceData);
2526 }
2527 else
2528 {
2529 pState->ext.glTexImage3D(GL_TEXTURE_3D,
2530 i,
2531 pSurface->internalFormatGL,
2532 pMipLevel->mipmapSize.width,
2533 pMipLevel->mipmapSize.height,
2534 pMipLevel->mipmapSize.depth,
2535 0, /* border */
2536 pSurface->formatGL,
2537 pSurface->typeGL,
2538 pMipLevel->pSurfaceData);
2539 }
2540 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2541
2542 pMipLevel->fDirty = false;
2543 }
2544 }
2545 else if (target == GL_TEXTURE_CUBE_MAP)
2546 {
2547 for (uint32_t iFace = 0; iFace < 6; ++iFace)
2548 {
2549 GLenum const Face = vmsvga3dCubemapFaceFromIndex(iFace);
2550
2551 for (uint32_t i = 0; i < numMipLevels; ++i)
2552 {
2553 PVMSVGA3DMIPMAPLEVEL pMipLevel = &pSurface->paMipmapLevels[iFace * numMipLevels + i];
2554 Assert(pMipLevel->mipmapSize.width == pMipLevel->mipmapSize.height);
2555 Assert(pMipLevel->mipmapSize.depth == 1);
2556
2557 LogFunc(("sync cube texture face %d mipmap level %d (dirty %d)\n",
2558 iFace, i, pMipLevel->fDirty));
2559
2560 if ( pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
2561 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
2562 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
2563 {
2564 pState->ext.glCompressedTexImage2D(Face,
2565 i,
2566 pSurface->internalFormatGL,
2567 pMipLevel->mipmapSize.width,
2568 pMipLevel->mipmapSize.height,
2569 0,
2570 pMipLevel->cbSurface,
2571 pMipLevel->pSurfaceData);
2572 }
2573 else
2574 {
2575 glTexImage2D(Face,
2576 i,
2577 pSurface->internalFormatGL,
2578 pMipLevel->mipmapSize.width,
2579 pMipLevel->mipmapSize.height,
2580 0,
2581 pSurface->formatGL,
2582 pSurface->typeGL,
2583 pMipLevel->pSurfaceData);
2584 }
2585 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2586
2587 pMipLevel->fDirty = false;
2588 }
2589 }
2590 }
2591 else if (target == GL_TEXTURE_2D)
2592 {
2593 for (uint32_t i = 0; i < numMipLevels; ++i)
2594 {
2595 /* Allocate and initialize texture memory. Passing the zero filled pSurfaceData avoids
2596 * exposing random host memory to the guest and helps a with the fedora 21 surface
2597 * corruption issues (launchpad, background, search field, login).
2598 */
2599 PVMSVGA3DMIPMAPLEVEL pMipLevel = &pSurface->paMipmapLevels[i];
2600 Assert(pMipLevel->mipmapSize.depth == 1);
2601
2602 LogFunc(("sync dirty texture mipmap level %d (pitch %x) (dirty %d)\n",
2603 i, pMipLevel->cbSurfacePitch, pMipLevel->fDirty));
2604
2605 if ( pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
2606 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
2607 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
2608 {
2609 pState->ext.glCompressedTexImage2D(GL_TEXTURE_2D,
2610 i,
2611 pSurface->internalFormatGL,
2612 pMipLevel->mipmapSize.width,
2613 pMipLevel->mipmapSize.height,
2614 0,
2615 pMipLevel->cbSurface,
2616 pMipLevel->pSurfaceData);
2617 }
2618 else
2619 {
2620 glTexImage2D(GL_TEXTURE_2D,
2621 i,
2622 pSurface->internalFormatGL,
2623 pMipLevel->mipmapSize.width,
2624 pMipLevel->mipmapSize.height,
2625 0,
2626 pSurface->formatGL,
2627 pSurface->typeGL,
2628 NULL);
2629 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2630
2631 if (pSurface->fEmulated)
2632 {
2633 /* Bind the emulated texture and init it. */
2634 glBindTexture(GL_TEXTURE_2D, pSurface->idEmulated);
2635 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2636
2637 glTexImage2D(GL_TEXTURE_2D,
2638 i,
2639 pSurface->internalFormatGL,
2640 pMipLevel->mipmapSize.width,
2641 pMipLevel->mipmapSize.height,
2642 0,
2643 pSurface->formatGL,
2644 pSurface->typeGL,
2645 NULL);
2646 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2647 }
2648
2649 /* Fetch texture data: either to the actual or to the emulated texture.
2650 * The pSurfaceData buffer may be smaller than the entire texture
2651 * for emulated formats, in which case only part of the texture is synched.
2652 */
2653 uint32_t cBlocksX = pMipLevel->mipmapSize.width / pSurface->cxBlock;
2654 uint32_t cBlocksY = pMipLevel->mipmapSize.height / pSurface->cyBlock;
2655 glTexSubImage2D(GL_TEXTURE_2D,
2656 i,
2657 0,
2658 0,
2659 cBlocksX,
2660 cBlocksY,
2661 pSurface->formatGL,
2662 pSurface->typeGL,
2663 pMipLevel->pSurfaceData);
2664 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2665
2666 if (pSurface->fEmulated)
2667 {
2668 /* Update the actual texture using the format converter. */
2669 FormatConvUpdateTexture(pState, pContext, pSurface, i);
2670
2671 /* Rebind the actual texture. */
2672 glBindTexture(GL_TEXTURE_2D, pSurface->oglId.texture);
2673 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2674 }
2675 }
2676 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2677
2678 pMipLevel->fDirty = false;
2679 }
2680 }
2681
2682 pSurface->fDirty = false;
2683
2684 /* Restore unpacking parameters. */
2685 vmsvga3dOglRestoreUnpackParams(pState, pContext, &SavedParams);
2686
2687 /* Restore the old active texture. */
2688 glBindTexture(target, activeTexture);
2689 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2690
2691 pSurface->f.s.surface1Flags |= SVGA3D_SURFACE_HINT_TEXTURE;
2692 pSurface->targetGL = target;
2693 pSurface->bindingGL = binding;
2694
2695 if (idPrevCtx < pState->cContexts && pState->papContexts[idPrevCtx]->id == idPrevCtx)
2696 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pState->papContexts[idPrevCtx]);
2697 return VINF_SUCCESS;
2698}
2699
2700
2701/**
2702 * Backend worker for implementing SVGA_3D_CMD_SURFACE_STRETCHBLT.
2703 *
2704 * @returns VBox status code.
2705 * @param pThis The VGA device instance.
2706 * @param pState The VMSVGA3d state.
2707 * @param pDstSurface The destination host surface.
2708 * @param uDstFace The destination face (valid).
2709 * @param uDstMipmap The destination mipmap level (valid).
2710 * @param pDstBox The destination box.
2711 * @param pSrcSurface The source host surface.
2712 * @param uSrcFace The destination face (valid).
2713 * @param uSrcMipmap The source mimap level (valid).
2714 * @param pSrcBox The source box.
2715 * @param enmMode The strecht blt mode .
2716 * @param pContext The VMSVGA3d context (already current for OGL).
2717 */
2718static DECLCALLBACK(int) vmsvga3dBackSurfaceStretchBlt(PVGASTATE pThis, PVMSVGA3DSTATE pState,
2719 PVMSVGA3DSURFACE pDstSurface, uint32_t uDstFace, uint32_t uDstMipmap, SVGA3dBox const *pDstBox,
2720 PVMSVGA3DSURFACE pSrcSurface, uint32_t uSrcFace, uint32_t uSrcMipmap, SVGA3dBox const *pSrcBox,
2721 SVGA3dStretchBltMode enmMode, PVMSVGA3DCONTEXT pContext)
2722{
2723 RT_NOREF(pThis);
2724
2725 AssertReturn( RT_BOOL(pSrcSurface->f.s.surface1Flags & SVGA3D_SURFACE_HINT_DEPTHSTENCIL)
2726 == RT_BOOL(pDstSurface->f.s.surface1Flags & SVGA3D_SURFACE_HINT_DEPTHSTENCIL), VERR_NOT_IMPLEMENTED);
2727
2728 GLenum glAttachment = GL_COLOR_ATTACHMENT0;
2729 GLbitfield glMask = GL_COLOR_BUFFER_BIT;
2730 if (pDstSurface->f.s.surface1Flags & SVGA3D_SURFACE_HINT_DEPTHSTENCIL)
2731 {
2732 /** @todo Need GL_DEPTH_STENCIL_ATTACHMENT for depth/stencil formats? */
2733 glAttachment = GL_DEPTH_ATTACHMENT;
2734 glMask = GL_DEPTH_BUFFER_BIT;
2735 }
2736
2737 /* Activate the read and draw framebuffer objects. */
2738 pState->ext.glBindFramebuffer(GL_READ_FRAMEBUFFER, pContext->idReadFramebuffer);
2739 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2740 pState->ext.glBindFramebuffer(GL_DRAW_FRAMEBUFFER, pContext->idDrawFramebuffer);
2741 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2742
2743 /* Bind the source and destination objects to the right place. */
2744 GLenum textarget;
2745 if (pSrcSurface->targetGL == GL_TEXTURE_CUBE_MAP)
2746 textarget = vmsvga3dCubemapFaceFromIndex(uSrcFace);
2747 else
2748 {
2749 /// @todo later AssertMsg(pSrcSurface->targetGL == GL_TEXTURE_2D, ("%#x\n", pSrcSurface->targetGL));
2750 textarget = GL_TEXTURE_2D;
2751 }
2752 pState->ext.glFramebufferTexture2D(GL_READ_FRAMEBUFFER, glAttachment, textarget,
2753 pSrcSurface->oglId.texture, uSrcMipmap);
2754 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2755
2756 if (pDstSurface->targetGL == GL_TEXTURE_CUBE_MAP)
2757 textarget = vmsvga3dCubemapFaceFromIndex(uDstFace);
2758 else
2759 {
2760 /// @todo later AssertMsg(pDstSurface->targetGL == GL_TEXTURE_2D, ("%#x\n", pDstSurface->targetGL));
2761 textarget = GL_TEXTURE_2D;
2762 }
2763 pState->ext.glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, glAttachment, textarget,
2764 pDstSurface->oglId.texture, uDstMipmap);
2765 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2766
2767 Log(("src conv. (%d,%d)(%d,%d); dest conv (%d,%d)(%d,%d)\n",
2768 pSrcBox->x, D3D_TO_OGL_Y_COORD(pSrcSurface, pSrcBox->y + pSrcBox->h),
2769 pSrcBox->x + pSrcBox->w, D3D_TO_OGL_Y_COORD(pSrcSurface, pSrcBox->y),
2770 pDstBox->x, D3D_TO_OGL_Y_COORD(pDstSurface, pDstBox->y + pDstBox->h),
2771 pDstBox->x + pDstBox->w, D3D_TO_OGL_Y_COORD(pDstSurface, pDstBox->y)));
2772
2773 pState->ext.glBlitFramebuffer(pSrcBox->x,
2774 pSrcBox->y,
2775 pSrcBox->x + pSrcBox->w, /* exclusive. */
2776 pSrcBox->y + pSrcBox->h,
2777 pDstBox->x,
2778 pDstBox->y,
2779 pDstBox->x + pDstBox->w, /* exclusive. */
2780 pDstBox->y + pDstBox->h,
2781 glMask,
2782 (enmMode == SVGA3D_STRETCH_BLT_POINT) ? GL_NEAREST : GL_LINEAR);
2783 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2784
2785 /* Reset the frame buffer association */
2786 pState->ext.glBindFramebuffer(GL_FRAMEBUFFER, pContext->idFramebuffer);
2787 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
2788
2789 return VINF_SUCCESS;
2790}
2791
2792/**
2793 * Save texture packing parameters and loads those appropriate for the given
2794 * surface.
2795 *
2796 * @param pState The VMSVGA3D state structure.
2797 * @param pContext The active context.
2798 * @param pSurface The surface.
2799 * @param pSave Where to save stuff.
2800 */
2801void vmsvga3dOglSetPackParams(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext, PVMSVGA3DSURFACE pSurface,
2802 PVMSVGAPACKPARAMS pSave)
2803{
2804 RT_NOREF(pState);
2805 /*
2806 * Save (ignore errors, setting the defaults we want and avoids restore).
2807 */
2808 pSave->iAlignment = 1;
2809 VMSVGA3D_ASSERT_GL_CALL(glGetIntegerv(GL_PACK_ALIGNMENT, &pSave->iAlignment), pState, pContext);
2810 pSave->cxRow = 0;
2811 VMSVGA3D_ASSERT_GL_CALL(glGetIntegerv(GL_PACK_ROW_LENGTH, &pSave->cxRow), pState, pContext);
2812
2813#ifdef VMSVGA3D_PARANOID_TEXTURE_PACKING
2814 pSave->cyImage = 0;
2815 glGetIntegerv(GL_PACK_IMAGE_HEIGHT, &pSave->cyImage);
2816 Assert(pSave->cyImage == 0);
2817
2818 pSave->fSwapBytes = GL_FALSE;
2819 glGetBooleanv(GL_PACK_SWAP_BYTES, &pSave->fSwapBytes);
2820 Assert(pSave->fSwapBytes == GL_FALSE);
2821
2822 pSave->fLsbFirst = GL_FALSE;
2823 glGetBooleanv(GL_PACK_LSB_FIRST, &pSave->fLsbFirst);
2824 Assert(pSave->fLsbFirst == GL_FALSE);
2825
2826 pSave->cSkipRows = 0;
2827 glGetIntegerv(GL_PACK_SKIP_ROWS, &pSave->cSkipRows);
2828 Assert(pSave->cSkipRows == 0);
2829
2830 pSave->cSkipPixels = 0;
2831 glGetIntegerv(GL_PACK_SKIP_PIXELS, &pSave->cSkipPixels);
2832 Assert(pSave->cSkipPixels == 0);
2833
2834 pSave->cSkipImages = 0;
2835 glGetIntegerv(GL_PACK_SKIP_IMAGES, &pSave->cSkipImages);
2836 Assert(pSave->cSkipImages == 0);
2837
2838 VMSVGA3D_CLEAR_GL_ERRORS();
2839#endif
2840
2841 /*
2842 * Setup unpack.
2843 *
2844 * Note! We use 1 as alignment here because we currently don't do any
2845 * aligning of line pitches anywhere.
2846 */
2847 NOREF(pSurface);
2848 if (pSave->iAlignment != 1)
2849 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_ALIGNMENT, 1), pState, pContext);
2850 if (pSave->cxRow != 0)
2851 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_ROW_LENGTH, 0), pState, pContext);
2852#ifdef VMSVGA3D_PARANOID_TEXTURE_PACKING
2853 if (pSave->cyImage != 0)
2854 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_IMAGE_HEIGHT, 0), pState, pContext);
2855 if (pSave->fSwapBytes != 0)
2856 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SWAP_BYTES, GL_FALSE), pState, pContext);
2857 if (pSave->fLsbFirst != 0)
2858 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_LSB_FIRST, GL_FALSE), pState, pContext);
2859 if (pSave->cSkipRows != 0)
2860 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SKIP_ROWS, 0), pState, pContext);
2861 if (pSave->cSkipPixels != 0)
2862 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SKIP_PIXELS, 0), pState, pContext);
2863 if (pSave->cSkipImages != 0)
2864 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SKIP_IMAGES, 0), pState, pContext);
2865#endif
2866}
2867
2868
2869/**
2870 * Restores texture packing parameters.
2871 *
2872 * @param pState The VMSVGA3D state structure.
2873 * @param pContext The active context.
2874 * @param pSurface The surface.
2875 * @param pSave Where stuff was saved.
2876 */
2877void vmsvga3dOglRestorePackParams(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext, PVMSVGA3DSURFACE pSurface,
2878 PCVMSVGAPACKPARAMS pSave)
2879{
2880 RT_NOREF(pState, pSurface);
2881 if (pSave->iAlignment != 1)
2882 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_ALIGNMENT, pSave->iAlignment), pState, pContext);
2883 if (pSave->cxRow != 0)
2884 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_ROW_LENGTH, pSave->cxRow), pState, pContext);
2885#ifdef VMSVGA3D_PARANOID_TEXTURE_PACKING
2886 if (pSave->cyImage != 0)
2887 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_IMAGE_HEIGHT, pSave->cyImage), pState, pContext);
2888 if (pSave->fSwapBytes != 0)
2889 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SWAP_BYTES, pSave->fSwapBytes), pState, pContext);
2890 if (pSave->fLsbFirst != 0)
2891 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_LSB_FIRST, pSave->fLsbFirst), pState, pContext);
2892 if (pSave->cSkipRows != 0)
2893 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SKIP_ROWS, pSave->cSkipRows), pState, pContext);
2894 if (pSave->cSkipPixels != 0)
2895 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SKIP_PIXELS, pSave->cSkipPixels), pState, pContext);
2896 if (pSave->cSkipImages != 0)
2897 VMSVGA3D_ASSERT_GL_CALL(glPixelStorei(GL_PACK_SKIP_IMAGES, pSave->cSkipImages), pState, pContext);
2898#endif
2899}
2900
2901
2902/**
2903 * Backend worker for implementing SVGA_3D_CMD_SURFACE_DMA that copies one box.
2904 *
2905 * @returns Failure status code or @a rc.
2906 * @param pThis The shared VGA/VMSVGA instance data.
2907 * @param pThisCC The VGA/VMSVGA state for ring-3.
2908 * @param pState The VMSVGA3d state.
2909 * @param pSurface The host surface.
2910 * @param pMipLevel Mipmap level. The caller knows it already.
2911 * @param uHostFace The host face (valid).
2912 * @param uHostMipmap The host mipmap level (valid).
2913 * @param GuestPtr The guest pointer.
2914 * @param cbGuestPitch The guest pitch.
2915 * @param transfer The transfer direction.
2916 * @param pBox The box to copy (clipped, valid, except for guest's srcx, srcy, srcz).
2917 * @param pContext The context (for OpenGL).
2918 * @param rc The current rc for all boxes.
2919 * @param iBox The current box number (for Direct 3D).
2920 */
2921static DECLCALLBACK(int) vmsvga3dBackSurfaceDMACopyBox(PVGASTATE pThis, PVGASTATECC pThisCC, PVMSVGA3DSTATE pState, PVMSVGA3DSURFACE pSurface,
2922 PVMSVGA3DMIPMAPLEVEL pMipLevel, uint32_t uHostFace, uint32_t uHostMipmap,
2923 SVGAGuestPtr GuestPtr, uint32_t cbGuestPitch, SVGA3dTransferType transfer,
2924 SVGA3dCopyBox const *pBox, PVMSVGA3DCONTEXT pContext, int rc, int iBox)
2925{
2926 RT_NOREF(iBox);
2927
2928 switch (pSurface->enmOGLResType)
2929 {
2930 case VMSVGA3D_OGLRESTYPE_TEXTURE:
2931 {
2932 uint32_t cbSurfacePitch;
2933 uint8_t *pDoubleBuffer;
2934 uint64_t offHst;
2935
2936 uint32_t const u32HostBlockX = pBox->x / pSurface->cxBlock;
2937 uint32_t const u32HostBlockY = pBox->y / pSurface->cyBlock;
2938 uint32_t const u32HostZ = pBox->z;
2939 Assert(u32HostBlockX * pSurface->cxBlock == pBox->x);
2940 Assert(u32HostBlockY * pSurface->cyBlock == pBox->y);
2941
2942 uint32_t const u32GuestBlockX = pBox->srcx / pSurface->cxBlock;
2943 uint32_t const u32GuestBlockY = pBox->srcy / pSurface->cyBlock;
2944 uint32_t const u32GuestZ = pBox->srcz / pSurface->cyBlock;
2945 Assert(u32GuestBlockX * pSurface->cxBlock == pBox->srcx);
2946 Assert(u32GuestBlockY * pSurface->cyBlock == pBox->srcy);
2947
2948 uint32_t const cBlocksX = (pBox->w + pSurface->cxBlock - 1) / pSurface->cxBlock;
2949 uint32_t const cBlocksY = (pBox->h + pSurface->cyBlock - 1) / pSurface->cyBlock;
2950 AssertMsgReturn(cBlocksX && cBlocksY, ("Empty box %dx%d\n", pBox->w, pBox->h), VERR_INTERNAL_ERROR);
2951
2952 GLenum texImageTarget;
2953 if (pSurface->targetGL == GL_TEXTURE_3D)
2954 {
2955 texImageTarget = GL_TEXTURE_3D;
2956 }
2957 else if (pSurface->targetGL == GL_TEXTURE_CUBE_MAP)
2958 {
2959 texImageTarget = vmsvga3dCubemapFaceFromIndex(uHostFace);
2960 }
2961 else
2962 {
2963 AssertMsg(pSurface->targetGL == GL_TEXTURE_2D, ("%#x\n", pSurface->targetGL));
2964 texImageTarget = GL_TEXTURE_2D;
2965 }
2966
2967 /* The buffer must be large enough to hold entire texture in the OpenGL format. */
2968 pDoubleBuffer = (uint8_t *)RTMemAlloc(pSurface->cbBlockGL * pMipLevel->cBlocks);
2969 AssertReturn(pDoubleBuffer, VERR_NO_MEMORY);
2970
2971 if (transfer == SVGA3D_READ_HOST_VRAM)
2972 {
2973 /* Read the entire texture to the double buffer. */
2974 GLint activeTexture;
2975
2976 /* Must bind texture to the current context in order to read it. */
2977 glGetIntegerv(pSurface->bindingGL, &activeTexture);
2978 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2979
2980 glBindTexture(pSurface->targetGL, GLTextureId(pSurface));
2981 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2982
2983 if (pSurface->fEmulated)
2984 {
2985 FormatConvReadTexture(pState, pContext, pSurface, uHostMipmap);
2986 }
2987
2988 /* Set row length and alignment of the input data. */
2989 VMSVGAPACKPARAMS SavedParams;
2990 vmsvga3dOglSetPackParams(pState, pContext, pSurface, &SavedParams);
2991
2992 if ( pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
2993 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
2994 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
2995 {
2996 pState->ext.glGetCompressedTexImage(texImageTarget, uHostMipmap, pDoubleBuffer);
2997 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
2998 }
2999 else
3000 {
3001 glGetTexImage(texImageTarget, uHostMipmap, pSurface->formatGL, pSurface->typeGL, pDoubleBuffer);
3002 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
3003 }
3004
3005 vmsvga3dOglRestorePackParams(pState, pContext, pSurface, &SavedParams);
3006
3007 /* Restore the old active texture. */
3008 glBindTexture(pSurface->targetGL, activeTexture);
3009 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
3010
3011 offHst = u32HostBlockX * pSurface->cbBlock + u32HostBlockY * pMipLevel->cbSurfacePitch + u32HostZ * pMipLevel->cbSurfacePlane;
3012 cbSurfacePitch = pMipLevel->cbSurfacePitch;
3013 }
3014 else
3015 {
3016 /* The buffer will contain only the copied rectangle. */
3017 offHst = 0;
3018 cbSurfacePitch = cBlocksX * pSurface->cbBlock;
3019 }
3020
3021 uint64_t offGst = u32GuestBlockX * pSurface->cbBlock + u32GuestBlockY * cbGuestPitch + u32GuestZ * cbGuestPitch * pMipLevel->mipmapSize.height;
3022
3023 for (uint32_t iPlane = 0; iPlane < pBox->d; ++iPlane)
3024 {
3025 AssertBreak(offHst < UINT32_MAX);
3026 AssertBreak(offGst < UINT32_MAX);
3027
3028 rc = vmsvgaR3GmrTransfer(pThis,
3029 pThisCC,
3030 transfer,
3031 pDoubleBuffer,
3032 pMipLevel->cbSurface,
3033 (uint32_t)offHst,
3034 cbSurfacePitch,
3035 GuestPtr,
3036 (uint32_t)offGst,
3037 cbGuestPitch,
3038 cBlocksX * pSurface->cbBlock,
3039 cBlocksY);
3040 AssertRC(rc);
3041
3042 offHst += pMipLevel->cbSurfacePlane;
3043 offGst += pMipLevel->mipmapSize.height * cbGuestPitch;
3044 }
3045
3046 /* Update the opengl surface data. */
3047 if (transfer == SVGA3D_WRITE_HOST_VRAM)
3048 {
3049 GLint activeTexture = 0;
3050 glGetIntegerv(pSurface->bindingGL, &activeTexture);
3051 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
3052
3053 /* Must bind texture to the current context in order to change it. */
3054 glBindTexture(pSurface->targetGL, GLTextureId(pSurface));
3055 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
3056
3057 LogFunc(("copy texture mipmap level %d (pitch %x)\n", uHostMipmap, pMipLevel->cbSurfacePitch));
3058
3059 /* Set row length and alignment of the input data. */
3060 /* We do not need to set ROW_LENGTH to w here, because the image in pDoubleBuffer is tightly packed. */
3061 VMSVGAPACKPARAMS SavedParams;
3062 vmsvga3dOglSetUnpackParams(pState, pContext, 0, 0, &SavedParams);
3063
3064 if (texImageTarget == GL_TEXTURE_3D)
3065 {
3066 if ( pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
3067 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
3068 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
3069 {
3070 pState->ext.glCompressedTexSubImage3D(texImageTarget,
3071 uHostMipmap,
3072 pBox->x,
3073 pBox->y,
3074 pBox->z,
3075 pBox->w,
3076 pBox->h,
3077 pBox->d,
3078 pSurface->internalFormatGL,
3079 cbSurfacePitch * cBlocksY * pBox->d,
3080 pDoubleBuffer);
3081 }
3082 else
3083 {
3084 pState->ext.glTexSubImage3D(texImageTarget,
3085 uHostMipmap,
3086 u32HostBlockX,
3087 u32HostBlockY,
3088 pBox->z,
3089 cBlocksX,
3090 cBlocksY,
3091 pBox->d,
3092 pSurface->formatGL,
3093 pSurface->typeGL,
3094 pDoubleBuffer);
3095 }
3096 }
3097 else
3098 {
3099 if ( pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
3100 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
3101 || pSurface->internalFormatGL == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
3102 {
3103 pState->ext.glCompressedTexSubImage2D(texImageTarget,
3104 uHostMipmap,
3105 pBox->x,
3106 pBox->y,
3107 pBox->w,
3108 pBox->h,
3109 pSurface->internalFormatGL,
3110 cbSurfacePitch * cBlocksY,
3111 pDoubleBuffer);
3112 }
3113 else
3114 {
3115 glTexSubImage2D(texImageTarget,
3116 uHostMipmap,
3117 u32HostBlockX,
3118 u32HostBlockY,
3119 cBlocksX,
3120 cBlocksY,
3121 pSurface->formatGL,
3122 pSurface->typeGL,
3123 pDoubleBuffer);
3124 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
3125
3126 if (pSurface->fEmulated)
3127 {
3128 /* Convert the texture to the actual texture if necessary */
3129 FormatConvUpdateTexture(pState, pContext, pSurface, uHostMipmap);
3130 }
3131 }
3132 }
3133 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
3134
3135 /* Restore old values. */
3136 vmsvga3dOglRestoreUnpackParams(pState, pContext, &SavedParams);
3137
3138 /* Restore the old active texture. */
3139 glBindTexture(pSurface->targetGL, activeTexture);
3140 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
3141 }
3142
3143 Log4(("first line:\n%.*Rhxd\n", cBlocksX * pSurface->cbBlock, pDoubleBuffer));
3144
3145 /* Free the double buffer. */
3146 RTMemFree(pDoubleBuffer);
3147 break;
3148 }
3149
3150 case VMSVGA3D_OGLRESTYPE_BUFFER:
3151 {
3152 /* Buffers are uncompressed. */
3153 AssertReturn(pSurface->cxBlock == 1 && pSurface->cyBlock == 1, VERR_INTERNAL_ERROR);
3154
3155 /* Caller already clipped pBox and buffers are 1-dimensional. */
3156 Assert(pBox->y == 0 && pBox->h == 1 && pBox->z == 0 && pBox->d == 1);
3157
3158 VMSVGA3D_CLEAR_GL_ERRORS();
3159 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, pSurface->oglId.buffer);
3160 if (VMSVGA3D_GL_IS_SUCCESS(pContext))
3161 {
3162 GLenum enmGlTransfer = (transfer == SVGA3D_READ_HOST_VRAM) ? GL_READ_ONLY : GL_WRITE_ONLY;
3163 uint8_t *pbData = (uint8_t *)pState->ext.glMapBuffer(GL_ARRAY_BUFFER, enmGlTransfer);
3164 if (RT_LIKELY(pbData != NULL))
3165 {
3166#if defined(VBOX_STRICT) && defined(RT_OS_DARWIN)
3167 GLint cbStrictBufSize;
3168 glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &cbStrictBufSize);
3169 Assert(VMSVGA3D_GL_IS_SUCCESS(pContext));
3170 AssertMsg(cbStrictBufSize >= (int32_t)pMipLevel->cbSurface,
3171 ("cbStrictBufSize=%#x cbSurface=%#x pContext->id=%#x\n", (uint32_t)cbStrictBufSize, pMipLevel->cbSurface, pContext->id));
3172#endif
3173 Log(("Lock %s memory for rectangle (%d,%d)(%d,%d)\n",
3174 (pSurface->f.s.surface1Flags & VMSVGA3D_SURFACE_HINT_SWITCH_MASK) == SVGA3D_SURFACE_HINT_VERTEXBUFFER ? "vertex" :
3175 (pSurface->f.s.surface1Flags & VMSVGA3D_SURFACE_HINT_SWITCH_MASK) == SVGA3D_SURFACE_HINT_INDEXBUFFER ? "index" : "buffer",
3176 pBox->x, pBox->y, pBox->x + pBox->w, pBox->y + pBox->h));
3177
3178 /* The caller already copied the data to the pMipLevel->pSurfaceData buffer, see VMSVGA3DSURFACE_NEEDS_DATA. */
3179 uint32_t const offHst = pBox->x * pSurface->cbBlock;
3180 uint32_t const cbWidth = pBox->w * pSurface->cbBlock;
3181
3182 memcpy(pbData + offHst, (uint8_t *)pMipLevel->pSurfaceData + offHst, cbWidth);
3183
3184 Log4(("Buffer updated at [0x%x;0x%x):\n%.*Rhxd\n", offHst, offHst + cbWidth, cbWidth, (uint8_t *)pbData + offHst));
3185
3186 pState->ext.glUnmapBuffer(GL_ARRAY_BUFFER);
3187 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3188 }
3189 else
3190 VMSVGA3D_GL_GET_AND_COMPLAIN(pState, pContext, ("glMapBuffer(GL_ARRAY_BUFFER, %#x) -> NULL\n", enmGlTransfer));
3191 }
3192 else
3193 VMSVGA3D_GL_COMPLAIN(pState, pContext, ("glBindBuffer(GL_ARRAY_BUFFER, %#x)\n", pSurface->oglId.buffer));
3194 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, 0);
3195 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3196 break;
3197 }
3198
3199 default:
3200 AssertFailed();
3201 break;
3202 }
3203
3204 return rc;
3205}
3206
3207static DECLCALLBACK(int) vmsvga3dBackGenerateMipmaps(PVGASTATECC pThisCC, uint32_t sid, SVGA3dTextureFilter filter)
3208{
3209 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3210 PVMSVGA3DSURFACE pSurface;
3211 int rc = VINF_SUCCESS;
3212 PVMSVGA3DCONTEXT pContext;
3213 uint32_t cid;
3214 GLint activeTexture = 0;
3215
3216 AssertReturn(pState, VERR_NO_MEMORY);
3217
3218 rc = vmsvga3dSurfaceFromSid(pState, sid, &pSurface);
3219 AssertRCReturn(rc, rc);
3220
3221 Assert(filter != SVGA3D_TEX_FILTER_FLATCUBIC);
3222 Assert(filter != SVGA3D_TEX_FILTER_GAUSSIANCUBIC);
3223 pSurface->autogenFilter = filter;
3224
3225 LogFunc(("sid=%u filter=%d\n", sid, filter));
3226
3227 cid = SVGA3D_INVALID_ID;
3228 pContext = &pState->SharedCtx;
3229 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
3230
3231 if (pSurface->oglId.texture == OPENGL_INVALID_ID)
3232 {
3233 /* Unknown surface type; turn it into a texture. */
3234 LogFunc(("unknown src surface id=%x type=%d format=%d -> create texture\n", sid, pSurface->f.s.surface1Flags, pSurface->format));
3235 rc = vmsvga3dBackCreateTexture(pThisCC, pContext, cid, pSurface);
3236 AssertRCReturn(rc, rc);
3237 }
3238 else
3239 {
3240 /** @todo new filter */
3241 AssertFailed();
3242 }
3243
3244 glGetIntegerv(pSurface->bindingGL, &activeTexture);
3245 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3246
3247 /* Must bind texture to the current context in order to change it. */
3248 glBindTexture(pSurface->targetGL, pSurface->oglId.texture);
3249 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3250
3251 /* Generate the mip maps. */
3252 pState->ext.glGenerateMipmap(pSurface->targetGL);
3253 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3254
3255 /* Restore the old texture. */
3256 glBindTexture(pSurface->targetGL, activeTexture);
3257 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3258
3259 return VINF_SUCCESS;
3260}
3261
3262
3263#ifdef RT_OS_LINUX
3264/**
3265 * X11 event handling thread.
3266 *
3267 * @returns VINF_SUCCESS (ignored)
3268 * @param hThreadSelf thread handle
3269 * @param pvUser pointer to pState structure
3270 */
3271DECLCALLBACK(int) vmsvga3dXEventThread(RTTHREAD hThreadSelf, void *pvUser)
3272{
3273 RT_NOREF(hThreadSelf);
3274 PVMSVGA3DSTATE pState = (PVMSVGA3DSTATE)pvUser;
3275 while (!pState->bTerminate)
3276 {
3277 while (XPending(pState->display) > 0)
3278 {
3279 XEvent event;
3280 XNextEvent(pState->display, &event);
3281
3282 switch (event.type)
3283 {
3284 default:
3285 break;
3286 }
3287 }
3288 /* sleep for 16ms to not burn too many cycles */
3289 RTThreadSleep(16);
3290 }
3291 return VINF_SUCCESS;
3292}
3293#endif // RT_OS_LINUX
3294
3295
3296/**
3297 * Create a new 3d context
3298 *
3299 * @returns VBox status code.
3300 * @param pThisCC The VGA/VMSVGA state for ring-3.
3301 * @param cid Context id
3302 * @param fFlags VMSVGA3D_DEF_CTX_F_XXX.
3303 */
3304int vmsvga3dContextDefineOgl(PVGASTATECC pThisCC, uint32_t cid, uint32_t fFlags)
3305{
3306 int rc;
3307 PVMSVGA3DCONTEXT pContext;
3308 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3309
3310 AssertReturn(pState, VERR_NO_MEMORY);
3311 AssertReturn( cid < SVGA3D_MAX_CONTEXT_IDS
3312 || (cid == VMSVGA3D_SHARED_CTX_ID && (fFlags & VMSVGA3D_DEF_CTX_F_SHARED_CTX)), VERR_INVALID_PARAMETER);
3313#if !defined(VBOX_VMSVGA3D_DUAL_OPENGL_PROFILE) || !(defined(RT_OS_DARWIN))
3314 AssertReturn(!(fFlags & VMSVGA3D_DEF_CTX_F_OTHER_PROFILE), VERR_INTERNAL_ERROR_3);
3315#endif
3316
3317 Log(("vmsvga3dContextDefine id %x\n", cid));
3318
3319 if (cid == VMSVGA3D_SHARED_CTX_ID)
3320 pContext = &pState->SharedCtx;
3321 else
3322 {
3323 if (cid >= pState->cContexts)
3324 {
3325 /* Grow the array. */
3326 uint32_t cNew = RT_ALIGN(cid + 15, 16);
3327 void *pvNew = RTMemRealloc(pState->papContexts, sizeof(pState->papContexts[0]) * cNew);
3328 AssertReturn(pvNew, VERR_NO_MEMORY);
3329 pState->papContexts = (PVMSVGA3DCONTEXT *)pvNew;
3330 while (pState->cContexts < cNew)
3331 {
3332 pContext = (PVMSVGA3DCONTEXT)RTMemAllocZ(sizeof(*pContext));
3333 AssertReturn(pContext, VERR_NO_MEMORY);
3334 pContext->id = SVGA3D_INVALID_ID;
3335 pState->papContexts[pState->cContexts++] = pContext;
3336 }
3337 }
3338 /* If one already exists with this id, then destroy it now. */
3339 if (pState->papContexts[cid]->id != SVGA3D_INVALID_ID)
3340 vmsvga3dBackContextDestroy(pThisCC, cid);
3341
3342 pContext = pState->papContexts[cid];
3343 }
3344
3345 /*
3346 * Find or create the shared context if needed (necessary for sharing e.g. textures between contexts).
3347 */
3348 PVMSVGA3DCONTEXT pSharedCtx = NULL;
3349 if (!(fFlags & (VMSVGA3D_DEF_CTX_F_INIT | VMSVGA3D_DEF_CTX_F_SHARED_CTX)))
3350 {
3351 pSharedCtx = &pState->SharedCtx;
3352 if (pSharedCtx->id != VMSVGA3D_SHARED_CTX_ID)
3353 {
3354 rc = vmsvga3dContextDefineOgl(pThisCC, VMSVGA3D_SHARED_CTX_ID, VMSVGA3D_DEF_CTX_F_SHARED_CTX);
3355 AssertLogRelRCReturn(rc, rc);
3356
3357 /* Create resources which use the shared context. */
3358 vmsvga3dOnSharedContextDefine(pState);
3359 }
3360 }
3361
3362 /*
3363 * Initialize the context.
3364 */
3365 memset(pContext, 0, sizeof(*pContext));
3366 pContext->id = cid;
3367 for (uint32_t i = 0; i < RT_ELEMENTS(pContext->aSidActiveTextures); i++)
3368 pContext->aSidActiveTextures[i] = SVGA3D_INVALID_ID;
3369
3370 pContext->state.shidVertex = SVGA3D_INVALID_ID;
3371 pContext->state.shidPixel = SVGA3D_INVALID_ID;
3372 pContext->idFramebuffer = OPENGL_INVALID_ID;
3373 pContext->idReadFramebuffer = OPENGL_INVALID_ID;
3374 pContext->idDrawFramebuffer = OPENGL_INVALID_ID;
3375
3376 rc = ShaderContextCreate(&pContext->pShaderContext);
3377 AssertRCReturn(rc, rc);
3378
3379 for (uint32_t i = 0; i < RT_ELEMENTS(pContext->state.aRenderTargets); i++)
3380 pContext->state.aRenderTargets[i] = SVGA3D_INVALID_ID;
3381
3382#ifdef RT_OS_WINDOWS
3383 /* Create a context window with minimal 4x4 size. We will never use the swapchain
3384 * to present the rendered image. Rendered images from the guest will be copied to
3385 * the VMSVGA SCREEN object, which can be either an offscreen render target or
3386 * system memory in the guest VRAM.
3387 */
3388 rc = vmsvga3dContextWindowCreate(pState->hInstance, pState->pWindowThread, pState->WndRequestSem, &pContext->hwnd);
3389 AssertRCReturn(rc, rc);
3390
3391 pContext->hdc = GetDC(pContext->hwnd);
3392 AssertMsgReturn(pContext->hdc, ("GetDC %x failed with %d\n", pContext->hwnd, GetLastError()), VERR_INTERNAL_ERROR);
3393
3394 PIXELFORMATDESCRIPTOR pfd = {
3395 sizeof(PIXELFORMATDESCRIPTOR), /* size of this pfd */
3396 1, /* version number */
3397 PFD_DRAW_TO_WINDOW | /* support window */
3398 PFD_SUPPORT_OPENGL, /* support OpenGL */
3399 PFD_TYPE_RGBA, /* RGBA type */
3400 24, /* 24-bit color depth */
3401 0, 0, 0, 0, 0, 0, /* color bits ignored */
3402 8, /* alpha buffer */
3403 0, /* shift bit ignored */
3404 0, /* no accumulation buffer */
3405 0, 0, 0, 0, /* accum bits ignored */
3406 16, /* set depth buffer */
3407 16, /* set stencil buffer */
3408 0, /* no auxiliary buffer */
3409 PFD_MAIN_PLANE, /* main layer */
3410 0, /* reserved */
3411 0, 0, 0 /* layer masks ignored */
3412 };
3413 int pixelFormat;
3414 BOOL ret;
3415
3416 pixelFormat = ChoosePixelFormat(pContext->hdc, &pfd);
3417 /** @todo is this really necessary?? */
3418 pixelFormat = ChoosePixelFormat(pContext->hdc, &pfd);
3419 AssertMsgReturn(pixelFormat != 0, ("ChoosePixelFormat failed with %d\n", GetLastError()), VERR_INTERNAL_ERROR);
3420
3421 ret = SetPixelFormat(pContext->hdc, pixelFormat, &pfd);
3422 AssertMsgReturn(ret == TRUE, ("SetPixelFormat failed with %d\n", GetLastError()), VERR_INTERNAL_ERROR);
3423
3424 pContext->hglrc = wglCreateContext(pContext->hdc);
3425 AssertMsgReturn(pContext->hglrc, ("wglCreateContext %x failed with %d\n", pContext->hdc, GetLastError()), VERR_INTERNAL_ERROR);
3426
3427 if (pSharedCtx)
3428 {
3429 ret = wglShareLists(pSharedCtx->hglrc, pContext->hglrc);
3430 AssertMsg(ret == TRUE, ("wglShareLists(%p, %p) failed with %d\n", pSharedCtx->hglrc, pContext->hglrc, GetLastError()));
3431 }
3432
3433#elif defined(RT_OS_DARWIN)
3434 pContext->fOtherProfile = RT_BOOL(fFlags & VMSVGA3D_DEF_CTX_F_OTHER_PROFILE);
3435
3436 NativeNSOpenGLContextRef pShareContext = pSharedCtx ? pSharedCtx->cocoaContext : NULL;
3437 vmsvga3dCocoaCreateViewAndContext(&pContext->cocoaView, &pContext->cocoaContext,
3438 NULL,
3439 4, 4,
3440 pShareContext, pContext->fOtherProfile);
3441
3442#else
3443 if (pState->display == NULL)
3444 {
3445 /* get an X display and make sure we have glX 1.3 */
3446 pState->display = XOpenDisplay(0);
3447 AssertLogRelMsgReturn(pState->display, ("XOpenDisplay failed"), VERR_INTERNAL_ERROR);
3448 int glxMajor, glxMinor;
3449 Bool ret = glXQueryVersion(pState->display, &glxMajor, &glxMinor);
3450 AssertLogRelMsgReturn(ret && glxMajor == 1 && glxMinor >= 3, ("glX >=1.3 not present"), VERR_INTERNAL_ERROR);
3451 /* start our X event handling thread */
3452 rc = RTThreadCreate(&pState->pWindowThread, vmsvga3dXEventThread, pState, 0, RTTHREADTYPE_GUI, RTTHREADFLAGS_WAITABLE, "VMSVGA3DXEVENT");
3453 AssertLogRelMsgReturn(RT_SUCCESS(rc), ("Async IO Thread creation for 3d window handling failed rc=%Rrc\n", rc), rc);
3454 }
3455
3456 Window defaultRootWindow = XDefaultRootWindow(pState->display);
3457 /* Create a small 4x4 window required for GL context. */
3458 int attrib[] =
3459 {
3460 GLX_RGBA,
3461 GLX_RED_SIZE, 1,
3462 GLX_GREEN_SIZE, 1,
3463 GLX_BLUE_SIZE, 1,
3464 //GLX_ALPHA_SIZE, 1, this flips the bbos screen
3465 GLX_DOUBLEBUFFER,
3466 None
3467 };
3468 XVisualInfo *vi = glXChooseVisual(pState->display, DefaultScreen(pState->display), attrib);
3469 AssertLogRelMsgReturn(vi, ("glXChooseVisual failed"), VERR_INTERNAL_ERROR);
3470 XSetWindowAttributes swa;
3471 swa.colormap = XCreateColormap(pState->display, defaultRootWindow, vi->visual, AllocNone);
3472 AssertLogRelMsgReturn(swa.colormap, ("XCreateColormap failed"), VERR_INTERNAL_ERROR);
3473 swa.border_pixel = 0;
3474 swa.background_pixel = 0;
3475 swa.event_mask = StructureNotifyMask;
3476 unsigned long flags = CWBorderPixel | CWBackPixel | CWColormap | CWEventMask;
3477 pContext->window = XCreateWindow(pState->display, defaultRootWindow,
3478 0, 0, 4, 4,
3479 0, vi->depth, InputOutput,
3480 vi->visual, flags, &swa);
3481 AssertLogRelMsgReturn(pContext->window, ("XCreateWindow failed"), VERR_INTERNAL_ERROR);
3482
3483 /* The window is hidden by default and never mapped, because we only render offscreen and never present to it. */
3484
3485 GLXContext shareContext = pSharedCtx ? pSharedCtx->glxContext : NULL;
3486 pContext->glxContext = glXCreateContext(pState->display, vi, shareContext, GL_TRUE);
3487 XFree(vi);
3488 AssertLogRelMsgReturn(pContext->glxContext, ("glXCreateContext failed"), VERR_INTERNAL_ERROR);
3489#endif
3490
3491 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
3492
3493 /* NULL during the first PowerOn call. */
3494 if (pState->ext.glGenFramebuffers)
3495 {
3496 /* Create a framebuffer object for this context. */
3497 pState->ext.glGenFramebuffers(1, &pContext->idFramebuffer);
3498 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3499
3500 /* Bind the object to the framebuffer target. */
3501 pState->ext.glBindFramebuffer(GL_FRAMEBUFFER, pContext->idFramebuffer);
3502 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3503
3504 /* Create read and draw framebuffer objects for this context. */
3505 pState->ext.glGenFramebuffers(1, &pContext->idReadFramebuffer);
3506 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3507
3508 pState->ext.glGenFramebuffers(1, &pContext->idDrawFramebuffer);
3509 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
3510
3511 }
3512#if 0
3513 /** @todo move to shader lib!!! */
3514 /* Clear the screen */
3515 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
3516
3517 glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
3518 glClearIndex(0);
3519 glClearDepth(1);
3520 glClearStencil(0xffff);
3521 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
3522 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
3523 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
3524 if (pState->ext.glProvokingVertex)
3525 pState->ext.glProvokingVertex(GL_FIRST_VERTEX_CONVENTION);
3526 /** @todo move to shader lib!!! */
3527#endif
3528 return VINF_SUCCESS;
3529}
3530
3531#if defined(RT_OS_LINUX)
3532/*
3533 * HW accelerated graphics output.
3534 */
3535
3536/**
3537 * VMSVGA3d screen data.
3538 *
3539 * Allocated on the heap and pointed to by VMSVGASCREENOBJECT::pHwScreen.
3540 */
3541typedef struct VMSVGAHWSCREEN
3542{
3543 /* OpenGL context, which is used for the screen updates. */
3544 GLXContext glxctx;
3545
3546 /* The overlay window. */
3547 Window xwindow;
3548
3549 /* The RGBA texture which hold the screen content. */
3550 GLuint idScreenTexture;
3551
3552 /* Read and draw framebuffer objects for copying a surface to the screen texture. */
3553 GLuint idReadFramebuffer;
3554 GLuint idDrawFramebuffer;
3555} VMSVGAHWSCREEN;
3556
3557/* Send a notification to the UI. */
3558#if 0 /* Unused */
3559static int vmsvga3dDrvNotifyHwScreen(PVGASTATECC pThisCC, VBOX3D_NOTIFY_TYPE enmNotification,
3560 uint32_t idScreen, Pixmap pixmap, void *pvData, size_t cbData)
3561{
3562 uint8_t au8Buffer[128];
3563 AssertLogRelMsgReturn(cbData <= sizeof(au8Buffer) - sizeof(VBOX3DNOTIFY),
3564 ("cbData %zu", cbData),
3565 VERR_INVALID_PARAMETER);
3566
3567 VBOX3DNOTIFY *p = (VBOX3DNOTIFY *)&au8Buffer[0];
3568 p->enmNotification = enmNotification;
3569 p->iDisplay = idScreen;
3570 p->u32Reserved = 0;
3571 p->cbData = cbData + sizeof(uint64_t);
3572 /* au8Data consists of a 64 bit pixmap handle followed by notification specific data. */
3573 AssertCompile(sizeof(pixmap) <= sizeof(uint64_t));
3574 *(uint64_t *)&p->au8Data[0] = (uint64_t)pixmap;
3575 memcpy(&p->au8Data[sizeof(uint64_t)], pvData, cbData);
3576
3577 int rc = pThisCC->pDrv->pfn3DNotifyProcess(pThisCC->pDrv, p);
3578 return rc;
3579}
3580#endif /* Unused */
3581
3582static void vmsvga3dDrvNotifyHwOverlay(PVGASTATECC pThisCC, VBOX3D_NOTIFY_TYPE enmNotification, uint32_t idScreen)
3583{
3584 uint8_t au8Buffer[128];
3585 VBOX3DNOTIFY *p = (VBOX3DNOTIFY *)&au8Buffer[0];
3586 p->enmNotification = enmNotification;
3587 p->iDisplay = idScreen;
3588 p->u32Reserved = 0;
3589 p->cbData = sizeof(uint64_t);
3590 *(uint64_t *)&p->au8Data[0] = 0;
3591
3592 pThisCC->pDrv->pfn3DNotifyProcess(pThisCC->pDrv, p);
3593}
3594
3595/* Get X Window handle of the UI Framebuffer window. */
3596static int vmsvga3dDrvQueryWindow(PVGASTATECC pThisCC, uint32_t idScreen, Window *pWindow)
3597{
3598 uint8_t au8Buffer[128];
3599 VBOX3DNOTIFY *p = (VBOX3DNOTIFY *)&au8Buffer[0];
3600 p->enmNotification = VBOX3D_NOTIFY_TYPE_HW_OVERLAY_GET_ID;
3601 p->iDisplay = idScreen;
3602 p->u32Reserved = 0;
3603 p->cbData = sizeof(uint64_t);
3604 *(uint64_t *)&p->au8Data[0] = 0;
3605
3606 int rc = pThisCC->pDrv->pfn3DNotifyProcess(pThisCC->pDrv, p);
3607 if (RT_SUCCESS(rc))
3608 {
3609 *pWindow = (Window)*(uint64_t *)&p->au8Data[0];
3610 }
3611 return rc;
3612}
3613
3614static int ctxErrorHandler(Display *dpy, XErrorEvent *ev)
3615{
3616 RT_NOREF(dpy);
3617 LogRel4(("VMSVGA: XError %d\n", (int)ev->error_code));
3618 return 0;
3619}
3620
3621/* Create an overlay X window for the HW accelerated screen. */
3622static int vmsvga3dHwScreenCreate(PVMSVGA3DSTATE pState, Window parentWindow, unsigned int cWidth, unsigned int cHeight, VMSVGAHWSCREEN *p)
3623{
3624 int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctxErrorHandler);
3625
3626 int rc = VINF_SUCCESS;
3627
3628 XWindowAttributes parentAttr;
3629 if (XGetWindowAttributes(pState->display, parentWindow, &parentAttr) == 0)
3630 return VERR_INVALID_PARAMETER;
3631
3632 int const idxParentScreen = XScreenNumberOfScreen(parentAttr.screen);
3633
3634 /*
3635 * Create a new GL context, which will be used for copying to the screen.
3636 */
3637
3638 /* FBConfig attributes for the overlay window. */
3639 static int const aConfigAttribList[] =
3640 {
3641 GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, // Must support GLX windows
3642 GLX_DOUBLEBUFFER, False, // Double buffering had a much lower performance.
3643 GLX_RED_SIZE, 8, // True color RGB with 8 bits per channel.
3644 GLX_GREEN_SIZE, 8,
3645 GLX_BLUE_SIZE, 8,
3646 GLX_ALPHA_SIZE, 8,
3647 GLX_STENCIL_SIZE, 0, // No stencil buffer
3648 GLX_DEPTH_SIZE, 0, // No depth buffer
3649 None
3650 };
3651
3652 /* Find a suitable FB config. */
3653 int cConfigs = 0;
3654 GLXFBConfig *paConfigs = glXChooseFBConfig(pState->display, idxParentScreen, aConfigAttribList, &cConfigs);
3655 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: paConfigs %p cConfigs %d\n", (void *)paConfigs, cConfigs));
3656 if (paConfigs)
3657 {
3658 XVisualInfo *vi = NULL;
3659 int i = 0;
3660 for (; i < cConfigs; ++i)
3661 {
3662 /* Use XFree to free the data returned in the previous iteration of this loop. */
3663 if (vi)
3664 XFree(vi);
3665
3666 vi = glXGetVisualFromFBConfig(pState->display, paConfigs[i]);
3667 if (!vi)
3668 continue;
3669
3670 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: %p vid %lu screen %d depth %d r %lu g %lu b %lu clrmap %d bitsperrgb %d\n",
3671 (void *)vi->visual, vi->visualid, vi->screen, vi->depth,
3672 vi->red_mask, vi->green_mask, vi->blue_mask, vi->colormap_size, vi->bits_per_rgb));
3673
3674 /* Same screen as the parent window. */
3675 if (vi->screen != idxParentScreen)
3676 continue;
3677
3678 /* Search for 32 bits per pixel. */
3679 if (vi->depth != 32)
3680 continue;
3681
3682 /* 8 bits per color component is enough. */
3683 if (vi->bits_per_rgb != 8)
3684 continue;
3685
3686 /* Render to pixmap. */
3687 int value = 0;
3688 glXGetFBConfigAttrib(pState->display, paConfigs[i], GLX_DRAWABLE_TYPE, &value);
3689 if (!(value & GLX_WINDOW_BIT))
3690 continue;
3691
3692 /* This FB config can be used. */
3693 break;
3694 }
3695
3696 if (i < cConfigs)
3697 {
3698 /* Found a suitable config with index i. */
3699
3700 /* Create an overlay window. */
3701 XSetWindowAttributes swa;
3702 RT_ZERO(swa);
3703
3704 swa.colormap = XCreateColormap(pState->display, parentWindow, vi->visual, AllocNone);
3705 AssertLogRelMsg(swa.colormap, ("XCreateColormap failed"));
3706 swa.border_pixel = 0;
3707 swa.background_pixel = 0;
3708 swa.event_mask = StructureNotifyMask;
3709 swa.override_redirect = 1;
3710 unsigned long const swaAttrs = CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect;
3711 p->xwindow = XCreateWindow(pState->display, parentWindow,
3712 0, 0, cWidth, cHeight, 0, vi->depth, InputOutput,
3713 vi->visual, swaAttrs, &swa);
3714 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: p->xwindow %ld\n", p->xwindow));
3715 if (p->xwindow)
3716 {
3717
3718 p->glxctx = glXCreateContext(pState->display, vi, pState->SharedCtx.glxContext, GL_TRUE);
3719 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: p->glxctx %p\n", (void *)p->glxctx));
3720 if (p->glxctx)
3721 {
3722 XMapWindow(pState->display, p->xwindow);
3723 }
3724 else
3725 {
3726 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: glXCreateContext failed\n"));
3727 rc = VERR_NOT_SUPPORTED;
3728 }
3729 }
3730 else
3731 {
3732 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: XCreateWindow failed\n"));
3733 rc = VERR_NOT_SUPPORTED;
3734 }
3735
3736 XSync(pState->display, False);
3737 }
3738 else
3739 {
3740 /* A suitable config is not found. */
3741 LogRel4(("VMSVGA: vmsvga3dHwScreenCreate: no FBConfig\n"));
3742 rc = VERR_NOT_SUPPORTED;
3743 }
3744
3745 if (vi)
3746 XFree(vi);
3747
3748 /* "Use XFree to free the memory returned by glXChooseFBConfig." */
3749 XFree(paConfigs);
3750 }
3751 else
3752 {
3753 /* glXChooseFBConfig failed. */
3754 rc = VERR_NOT_SUPPORTED;
3755 }
3756
3757 XSetErrorHandler(oldHandler);
3758 return rc;
3759}
3760
3761/* Destroy a HW accelerated screen. */
3762static void vmsvga3dHwScreenDestroy(PVMSVGA3DSTATE pState, VMSVGAHWSCREEN *p)
3763{
3764 if (p)
3765 {
3766 LogRel4(("VMSVGA: vmsvga3dHwScreenDestroy: p->xwindow %ld, ctx %p\n", p->xwindow, (void *)p->glxctx));
3767 if (p->glxctx)
3768 {
3769 /* GLX context is changed here, so other code has to set the appropriate context again. */
3770 VMSVGA3D_CLEAR_CURRENT_CONTEXT(pState);
3771
3772 glXMakeCurrent(pState->display, p->xwindow, p->glxctx);
3773
3774 /* Clean up OpenGL. */
3775 if (p->idReadFramebuffer != OPENGL_INVALID_ID)
3776 pState->ext.glDeleteFramebuffers(1, &p->idReadFramebuffer);
3777 if (p->idDrawFramebuffer != OPENGL_INVALID_ID)
3778 pState->ext.glDeleteFramebuffers(1, &p->idDrawFramebuffer);
3779 if (p->idScreenTexture != OPENGL_INVALID_ID)
3780 glDeleteTextures(1, &p->idScreenTexture);
3781
3782 glXMakeCurrent(pState->display, None, NULL);
3783
3784 glXDestroyContext(pState->display, p->glxctx);
3785 }
3786
3787 if (p->xwindow)
3788 XDestroyWindow(pState->display, p->xwindow);
3789
3790 RT_ZERO(*p);
3791 }
3792}
3793
3794#define GLCHECK() \
3795 do { \
3796 int glErr = glGetError(); \
3797 if (glErr != GL_NO_ERROR) LogRel4(("VMSVGA: GL error 0x%x @%d\n", glErr, __LINE__)); \
3798 } while(0)
3799
3800static DECLCALLBACK(int) vmsvga3dBackDefineScreen(PVGASTATE pThis, PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen)
3801{
3802 LogRel4(("VMSVGA: vmsvga3dBackDefineScreen: screen %u\n", pScreen->idScreen));
3803
3804 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3805 AssertReturn(pState, VERR_NOT_SUPPORTED);
3806
3807 if (!pThis->svga.f3DOverlayEnabled)
3808 return VERR_NOT_SUPPORTED;
3809
3810 Assert(pScreen->pHwScreen == NULL);
3811
3812 VMSVGAHWSCREEN *p = (VMSVGAHWSCREEN *)RTMemAllocZ(sizeof(VMSVGAHWSCREEN));
3813 AssertPtrReturn(p, VERR_NO_MEMORY);
3814
3815 /* Query the parent window ID from the UI framebuffer.
3816 * If it is there then
3817 * the device will create a texture for the screen content and an overlay window to present the screen content.
3818 * otherwise
3819 * the device will use the guest VRAM system memory for the screen content.
3820 */
3821 Window parentWindow;
3822 int rc = vmsvga3dDrvQueryWindow(pThisCC, pScreen->idScreen, &parentWindow);
3823 if (RT_SUCCESS(rc))
3824 {
3825 /* Create the hardware accelerated screen. */
3826 rc = vmsvga3dHwScreenCreate(pState, parentWindow, pScreen->cWidth, pScreen->cHeight, p);
3827 if (RT_SUCCESS(rc))
3828 {
3829 /*
3830 * Setup the OpenGL context of the screen. The context will be used to draw on the screen.
3831 */
3832
3833 /* GLX context is changed here, so other code has to set the appropriate context again. */
3834 VMSVGA3D_CLEAR_CURRENT_CONTEXT(pState);
3835
3836 Bool const fSuccess = glXMakeCurrent(pState->display, p->xwindow, p->glxctx);
3837 if (fSuccess)
3838 {
3839 /* Set GL state. */
3840 glClearColor(0, 0, 0, 1);
3841 glEnable(GL_TEXTURE_2D);
3842 glDisable(GL_DEPTH_TEST);
3843 glDisable(GL_CULL_FACE);
3844
3845 /* The RGBA texture which hold the screen content. */
3846 glGenTextures(1, &p->idScreenTexture); GLCHECK();
3847 glBindTexture(GL_TEXTURE_2D, p->idScreenTexture); GLCHECK();
3848 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); GLCHECK();
3849 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); GLCHECK();
3850 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, pScreen->cWidth, pScreen->cHeight, 0,
3851 GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, NULL); GLCHECK();
3852
3853 /* Create read and draw framebuffer objects for this screen. */
3854 pState->ext.glGenFramebuffers(1, &p->idReadFramebuffer); GLCHECK();
3855 pState->ext.glGenFramebuffers(1, &p->idDrawFramebuffer); GLCHECK();
3856
3857 /* Work in screen coordinates. */
3858 glMatrixMode(GL_MODELVIEW);
3859 glLoadIdentity();
3860 glOrtho(0, pScreen->cWidth, 0, pScreen->cHeight, -1, 1);
3861 glMatrixMode(GL_PROJECTION);
3862 glLoadIdentity();
3863
3864 /* Clear the texture. */
3865 pState->ext.glBindFramebuffer(GL_DRAW_FRAMEBUFFER, p->idDrawFramebuffer); GLCHECK();
3866 pState->ext.glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
3867 p->idScreenTexture, 0); GLCHECK();
3868
3869 glClear(GL_COLOR_BUFFER_BIT);
3870
3871 pState->ext.glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); GLCHECK();
3872
3873 glXMakeCurrent(pState->display, None, NULL);
3874
3875 XSync(pState->display, False);
3876
3877 vmsvga3dDrvNotifyHwOverlay(pThisCC, VBOX3D_NOTIFY_TYPE_HW_OVERLAY_CREATED, pScreen->idScreen);
3878 }
3879 else
3880 {
3881 LogRel4(("VMSVGA: vmsvga3dBackDefineScreen: failed to set current context\n"));
3882 rc = VERR_NOT_SUPPORTED;
3883 }
3884 }
3885 }
3886 else
3887 {
3888 LogRel4(("VMSVGA: vmsvga3dBackDefineScreen: no framebuffer\n"));
3889 }
3890
3891 if (RT_SUCCESS(rc))
3892 {
3893 LogRel(("VMSVGA: Using HW accelerated screen %u\n", pScreen->idScreen));
3894 pScreen->pHwScreen = p;
3895 }
3896 else
3897 {
3898 LogRel4(("VMSVGA: vmsvga3dBackDefineScreen: %Rrc\n", rc));
3899 vmsvga3dHwScreenDestroy(pState, p);
3900 RTMemFree(p);
3901 }
3902
3903 return rc;
3904}
3905
3906static DECLCALLBACK(int) vmsvga3dBackDestroyScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen)
3907{
3908 LogRel4(("VMSVGA: vmsvga3dBackDestroyScreen: screen %u\n", pScreen->idScreen));
3909
3910 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3911 AssertReturn(pState, VERR_NOT_SUPPORTED);
3912
3913 int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctxErrorHandler);
3914
3915 VMSVGAHWSCREEN *p = pScreen->pHwScreen;
3916 if (p)
3917 {
3918 pScreen->pHwScreen = NULL;
3919
3920 vmsvga3dDrvNotifyHwOverlay(pThisCC, VBOX3D_NOTIFY_TYPE_HW_OVERLAY_DESTROYED, pScreen->idScreen);
3921
3922 vmsvga3dHwScreenDestroy(pState, p);
3923 RTMemFree(p);
3924 }
3925
3926 XSetErrorHandler(oldHandler);
3927
3928 return VINF_SUCCESS;
3929}
3930
3931/* Blit a surface to the GLX pixmap. */
3932static DECLCALLBACK(int) vmsvga3dBackSurfaceBlitToScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen,
3933 SVGASignedRect destRect, SVGA3dSurfaceImageId srcImage,
3934 SVGASignedRect srcRect, uint32_t cRects, SVGASignedRect *paRects)
3935{
3936 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
3937 AssertReturn(pState, VERR_NOT_SUPPORTED);
3938
3939 VMSVGAHWSCREEN *p = pScreen->pHwScreen;
3940 AssertReturn(p, VERR_NOT_SUPPORTED);
3941
3942 PVMSVGA3DSURFACE pSurface;
3943 int rc = vmsvga3dSurfaceFromSid(pState, srcImage.sid, &pSurface);
3944 AssertRCReturn(rc, rc);
3945
3946 if (!VMSVGA3DSURFACE_HAS_HW_SURFACE(pSurface))
3947 {
3948 LogFunc(("src sid=%u flags=0x%x format=%d -> create texture\n", srcImage.sid, pSurface->f.s.surface1Flags, pSurface->format));
3949 rc = vmsvga3dBackCreateTexture(pThisCC, &pState->SharedCtx, VMSVGA3D_SHARED_CTX_ID, pSurface);
3950 AssertRCReturn(rc, rc);
3951 }
3952
3953 AssertReturn(pSurface->enmOGLResType == VMSVGA3D_OGLRESTYPE_TEXTURE, VERR_NOT_SUPPORTED);
3954
3955 PVMSVGA3DMIPMAPLEVEL pMipLevel;
3956 rc = vmsvga3dMipmapLevel(pSurface, srcImage.face, srcImage.mipmap, &pMipLevel);
3957 AssertRCReturn(rc, rc);
3958
3959 /** @todo Implement. */
3960 RT_NOREF(cRects, paRects);
3961
3962 /* GLX context is changed here, so other code has to set appropriate context again. */
3963 VMSVGA3D_CLEAR_CURRENT_CONTEXT(pState);
3964
3965 int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctxErrorHandler);
3966
3967 Bool fSuccess = glXMakeCurrent(pState->display, p->xwindow, p->glxctx);
3968 if (fSuccess)
3969 {
3970 /* Activate the read and draw framebuffer objects. */
3971 pState->ext.glBindFramebuffer(GL_READ_FRAMEBUFFER, p->idReadFramebuffer); GLCHECK();
3972 pState->ext.glBindFramebuffer(GL_DRAW_FRAMEBUFFER, p->idDrawFramebuffer); GLCHECK();
3973
3974 /* Bind the source and destination objects to the right place. */
3975 pState->ext.glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
3976 pSurface->oglId.texture, 0); GLCHECK();
3977 pState->ext.glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
3978 p->idScreenTexture, 0); GLCHECK();
3979
3980 pState->ext.glBlitFramebuffer(srcRect.left,
3981 srcRect.top,
3982 srcRect.right,
3983 srcRect.bottom,
3984 destRect.left,
3985 destRect.top,
3986 destRect.right,
3987 destRect.bottom,
3988 GL_COLOR_BUFFER_BIT,
3989 GL_NEAREST); GLCHECK();
3990
3991 /* Reset the frame buffer association */
3992 pState->ext.glBindFramebuffer(GL_FRAMEBUFFER, 0); GLCHECK();
3993
3994 /* Update the overlay window. */
3995 glClear(GL_COLOR_BUFFER_BIT);
3996
3997 glBindTexture(GL_TEXTURE_2D, p->idScreenTexture); GLCHECK();
3998
3999 GLint const w = pScreen->cWidth;
4000 GLint const h = pScreen->cHeight;
4001
4002 glBegin(GL_QUADS);
4003 glTexCoord2f(0.0f, 0.0f); glVertex2i(0, h);
4004 glTexCoord2f(0.0f, 1.0f); glVertex2i(0, 0);
4005 glTexCoord2f(1.0f, 1.0f); glVertex2i(w, 0);
4006 glTexCoord2f(1.0f, 0.0f); glVertex2i(w, h);
4007 glEnd(); GLCHECK();
4008
4009 glBindTexture(GL_TEXTURE_2D, 0); GLCHECK();
4010
4011 glXMakeCurrent(pState->display, None, NULL);
4012 }
4013 else
4014 {
4015 LogRel4(("VMSVGA: vmsvga3dBackSurfaceBlitToScreen: screen %u, glXMakeCurrent for pixmap failed\n", pScreen->idScreen));
4016 }
4017
4018 XSetErrorHandler(oldHandler);
4019
4020 return VINF_SUCCESS;
4021}
4022
4023#else /* !RT_OS_LINUX */
4024
4025static DECLCALLBACK(int) vmsvga3dBackDefineScreen(PVGASTATE pThis, PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen)
4026{
4027 RT_NOREF(pThis, pThisCC, pScreen);
4028 return VERR_NOT_IMPLEMENTED;
4029}
4030
4031static DECLCALLBACK(int) vmsvga3dBackDestroyScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen)
4032{
4033 RT_NOREF(pThisCC, pScreen);
4034 return VERR_NOT_IMPLEMENTED;
4035}
4036
4037static DECLCALLBACK(int) vmsvga3dBackSurfaceBlitToScreen(PVGASTATECC pThisCC, VMSVGASCREENOBJECT *pScreen,
4038 SVGASignedRect destRect, SVGA3dSurfaceImageId srcImage,
4039 SVGASignedRect srcRect, uint32_t cRects, SVGASignedRect *paRects)
4040{
4041 RT_NOREF(pThisCC, pScreen, destRect, srcImage, srcRect, cRects, paRects);
4042 return VERR_NOT_IMPLEMENTED;
4043}
4044#endif
4045
4046/**
4047 * Create a new 3d context
4048 *
4049 * @returns VBox status code.
4050 * @param pThisCC The VGA/VMSVGA state for ring-3.
4051 * @param cid Context id
4052 */
4053static DECLCALLBACK(int) vmsvga3dBackContextDefine(PVGASTATECC pThisCC, uint32_t cid)
4054{
4055 return vmsvga3dContextDefineOgl(pThisCC, cid, 0/*fFlags*/);
4056}
4057
4058/**
4059 * Destroys a 3d context.
4060 *
4061 * @returns VBox status code.
4062 * @param pThisCC The VGA/VMSVGA state for ring-3.
4063 * @param pContext The context to destroy.
4064 * @param cid Context id
4065 */
4066static int vmsvga3dContextDestroyOgl(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t cid)
4067{
4068 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4069 AssertReturn(pState, VERR_NO_MEMORY);
4070 AssertReturn(pContext, VERR_INVALID_PARAMETER);
4071 AssertReturn(pContext->id == cid, VERR_INVALID_PARAMETER);
4072 Log(("vmsvga3dContextDestroyOgl id %x\n", cid));
4073
4074 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
4075
4076 if (pContext->id == VMSVGA3D_SHARED_CTX_ID)
4077 {
4078 /* Delete resources which use the shared context. */
4079 vmsvga3dOnSharedContextDestroy(pState);
4080 }
4081
4082 /* Destroy all leftover pixel shaders. */
4083 for (uint32_t i = 0; i < pContext->cPixelShaders; i++)
4084 {
4085 if (pContext->paPixelShader[i].id != SVGA3D_INVALID_ID)
4086 vmsvga3dBackShaderDestroy(pThisCC, pContext->paPixelShader[i].cid, pContext->paPixelShader[i].id, pContext->paPixelShader[i].type);
4087 }
4088 if (pContext->paPixelShader)
4089 RTMemFree(pContext->paPixelShader);
4090
4091 /* Destroy all leftover vertex shaders. */
4092 for (uint32_t i = 0; i < pContext->cVertexShaders; i++)
4093 {
4094 if (pContext->paVertexShader[i].id != SVGA3D_INVALID_ID)
4095 vmsvga3dBackShaderDestroy(pThisCC, pContext->paVertexShader[i].cid, pContext->paVertexShader[i].id, pContext->paVertexShader[i].type);
4096 }
4097 if (pContext->paVertexShader)
4098 RTMemFree(pContext->paVertexShader);
4099
4100 if (pContext->state.paVertexShaderConst)
4101 RTMemFree(pContext->state.paVertexShaderConst);
4102 if (pContext->state.paPixelShaderConst)
4103 RTMemFree(pContext->state.paPixelShaderConst);
4104
4105 if (pContext->pShaderContext)
4106 {
4107 int rc = ShaderContextDestroy(pContext->pShaderContext);
4108 AssertRC(rc);
4109 }
4110
4111 if (pContext->idFramebuffer != OPENGL_INVALID_ID)
4112 {
4113 /* Unbind the object from the framebuffer target. */
4114 pState->ext.glBindFramebuffer(GL_FRAMEBUFFER, 0 /* back buffer */);
4115 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4116 pState->ext.glDeleteFramebuffers(1, &pContext->idFramebuffer);
4117 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4118
4119 if (pContext->idReadFramebuffer != OPENGL_INVALID_ID)
4120 {
4121 pState->ext.glDeleteFramebuffers(1, &pContext->idReadFramebuffer);
4122 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4123 }
4124 if (pContext->idDrawFramebuffer != OPENGL_INVALID_ID)
4125 {
4126 pState->ext.glDeleteFramebuffers(1, &pContext->idDrawFramebuffer);
4127 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4128 }
4129 }
4130
4131 vmsvga3dBackOcclusionQueryDelete(pThisCC, pContext);
4132
4133#ifdef RT_OS_WINDOWS
4134 wglMakeCurrent(pContext->hdc, NULL);
4135 wglDeleteContext(pContext->hglrc);
4136 ReleaseDC(pContext->hwnd, pContext->hdc);
4137
4138 /* Destroy the window we've created. */
4139 int rc = vmsvga3dSendThreadMessage(pState->pWindowThread, pState->WndRequestSem, WM_VMSVGA3D_DESTROYWINDOW, (WPARAM)pContext->hwnd, 0);
4140 AssertRC(rc);
4141#elif defined(RT_OS_DARWIN)
4142 vmsvga3dCocoaDestroyViewAndContext(pContext->cocoaView, pContext->cocoaContext);
4143#elif defined(RT_OS_LINUX)
4144 glXMakeCurrent(pState->display, None, NULL);
4145 glXDestroyContext(pState->display, pContext->glxContext);
4146 XDestroyWindow(pState->display, pContext->window);
4147#endif
4148
4149 memset(pContext, 0, sizeof(*pContext));
4150 pContext->id = SVGA3D_INVALID_ID;
4151
4152 VMSVGA3D_CLEAR_CURRENT_CONTEXT(pState);
4153 return VINF_SUCCESS;
4154}
4155
4156/**
4157 * Destroy an existing 3d context
4158 *
4159 * @returns VBox status code.
4160 * @param pThisCC The VGA/VMSVGA state for ring-3.
4161 * @param cid Context id
4162 */
4163static DECLCALLBACK(int) vmsvga3dBackContextDestroy(PVGASTATECC pThisCC, uint32_t cid)
4164{
4165 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4166 AssertReturn(pState, VERR_WRONG_ORDER);
4167
4168 /*
4169 * Resolve the context and hand it to the common worker function.
4170 */
4171 if ( cid < pState->cContexts
4172 && pState->papContexts[cid]->id == cid)
4173 return vmsvga3dContextDestroyOgl(pThisCC, pState->papContexts[cid], cid);
4174
4175 AssertReturn(cid < SVGA3D_MAX_CONTEXT_IDS, VERR_INVALID_PARAMETER);
4176 return VINF_SUCCESS;
4177}
4178
4179/**
4180 * Worker for vmsvga3dBackChangeMode that resizes a context.
4181 *
4182 * @param pState The VMSVGA3d state.
4183 * @param pContext The context.
4184 */
4185static void vmsvga3dChangeModeOneContext(PVMSVGA3DSTATE pState, PVMSVGA3DCONTEXT pContext)
4186{
4187 RT_NOREF(pState, pContext);
4188 /* Do nothing. The window is not used for presenting. */
4189}
4190
4191/* Handle resize */
4192static DECLCALLBACK(int) vmsvga3dBackChangeMode(PVGASTATECC pThisCC)
4193{
4194 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4195 AssertReturn(pState, VERR_NO_MEMORY);
4196
4197 /* Resize the shared context too. */
4198 if (pState->SharedCtx.id == VMSVGA3D_SHARED_CTX_ID)
4199 vmsvga3dChangeModeOneContext(pState, &pState->SharedCtx);
4200
4201 /* Resize all active contexts. */
4202 for (uint32_t i = 0; i < pState->cContexts; i++)
4203 {
4204 PVMSVGA3DCONTEXT pContext = pState->papContexts[i];
4205 if (pContext->id != SVGA3D_INVALID_ID)
4206 vmsvga3dChangeModeOneContext(pState, pContext);
4207 }
4208
4209 return VINF_SUCCESS;
4210}
4211
4212
4213static DECLCALLBACK(int) vmsvga3dBackSetTransform(PVGASTATECC pThisCC, uint32_t cid, SVGA3dTransformType type, float matrix[16])
4214{
4215 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4216 AssertReturn(pState, VERR_NO_MEMORY);
4217 bool fModelViewChanged = false;
4218
4219 Log(("vmsvga3dSetTransform cid=%u %s\n", cid, vmsvgaTransformToString(type)));
4220
4221 ASSERT_GUEST_RETURN((unsigned)type < SVGA3D_TRANSFORM_MAX, VERR_INVALID_PARAMETER);
4222
4223 PVMSVGA3DCONTEXT pContext;
4224 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
4225 AssertRCReturn(rc, rc);
4226
4227 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
4228
4229 /* Save this matrix for vm state save/restore. */
4230 pContext->state.aTransformState[type].fValid = true;
4231 memcpy(pContext->state.aTransformState[type].matrix, matrix, sizeof(pContext->state.aTransformState[type].matrix));
4232 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_TRANSFORM;
4233
4234 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)));
4235 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)));
4236 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)));
4237 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)));
4238
4239 switch (type)
4240 {
4241 case SVGA3D_TRANSFORM_VIEW:
4242 /* View * World = Model View */
4243 glMatrixMode(GL_MODELVIEW);
4244 glLoadMatrixf(matrix);
4245 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_WORLD].fValid)
4246 glMultMatrixf(pContext->state.aTransformState[SVGA3D_TRANSFORM_WORLD].matrix);
4247 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4248 fModelViewChanged = true;
4249 break;
4250
4251 case SVGA3D_TRANSFORM_PROJECTION:
4252 {
4253 rc = ShaderTransformProjection(pContext->state.RectViewPort.w, pContext->state.RectViewPort.h, matrix, false /* fPretransformed */);
4254 AssertRCReturn(rc, rc);
4255 break;
4256 }
4257
4258 case SVGA3D_TRANSFORM_TEXTURE0:
4259 glMatrixMode(GL_TEXTURE);
4260 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4261 glLoadMatrixf(matrix);
4262 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4263 break;
4264
4265 case SVGA3D_TRANSFORM_TEXTURE1:
4266 case SVGA3D_TRANSFORM_TEXTURE2:
4267 case SVGA3D_TRANSFORM_TEXTURE3:
4268 case SVGA3D_TRANSFORM_TEXTURE4:
4269 case SVGA3D_TRANSFORM_TEXTURE5:
4270 case SVGA3D_TRANSFORM_TEXTURE6:
4271 case SVGA3D_TRANSFORM_TEXTURE7:
4272 Log(("vmsvga3dSetTransform: unsupported SVGA3D_TRANSFORM_TEXTUREx transform!!\n"));
4273 return VERR_INVALID_PARAMETER;
4274
4275 case SVGA3D_TRANSFORM_WORLD:
4276 /* View * World = Model View */
4277 glMatrixMode(GL_MODELVIEW);
4278 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].fValid)
4279 glLoadMatrixf(pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].matrix);
4280 else
4281 glLoadIdentity();
4282 glMultMatrixf(matrix);
4283 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4284 fModelViewChanged = true;
4285 break;
4286
4287 case SVGA3D_TRANSFORM_WORLD1:
4288 case SVGA3D_TRANSFORM_WORLD2:
4289 case SVGA3D_TRANSFORM_WORLD3:
4290 Log(("vmsvga3dSetTransform: unsupported SVGA3D_TRANSFORM_WORLDx transform!!\n"));
4291 return VERR_INVALID_PARAMETER;
4292
4293 default:
4294 Log(("vmsvga3dSetTransform: unknown type!!\n"));
4295 return VERR_INVALID_PARAMETER;
4296 }
4297
4298 /* Apparently we need to reset the light and clip data after modifying the modelview matrix. */
4299 if (fModelViewChanged)
4300 {
4301 /* Reprogram the clip planes. */
4302 for (uint32_t j = 0; j < RT_ELEMENTS(pContext->state.aClipPlane); j++)
4303 {
4304 if (pContext->state.aClipPlane[j].fValid == true)
4305 vmsvga3dBackSetClipPlane(pThisCC, cid, j, pContext->state.aClipPlane[j].plane);
4306 }
4307
4308 /* Reprogram the light data. */
4309 for (uint32_t j = 0; j < RT_ELEMENTS(pContext->state.aLightData); j++)
4310 {
4311 if (pContext->state.aLightData[j].fValidData == true)
4312 vmsvga3dBackSetLightData(pThisCC, cid, j, &pContext->state.aLightData[j].data);
4313 }
4314 }
4315
4316 return VINF_SUCCESS;
4317}
4318
4319static DECLCALLBACK(int) vmsvga3dBackSetZRange(PVGASTATECC pThisCC, uint32_t cid, SVGA3dZRange zRange)
4320{
4321 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4322 AssertReturn(pState, VERR_NO_MEMORY);
4323
4324 Log(("vmsvga3dSetZRange cid=%u min=%d max=%d\n", cid, (uint32_t)(zRange.min * 100.0), (uint32_t)(zRange.max * 100.0)));
4325
4326 PVMSVGA3DCONTEXT pContext;
4327 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
4328 AssertRCReturn(rc, rc);
4329
4330 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
4331
4332 pContext->state.zRange = zRange;
4333 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_ZRANGE;
4334
4335 if (zRange.min < -1.0)
4336 zRange.min = -1.0;
4337 if (zRange.max > 1.0)
4338 zRange.max = 1.0;
4339
4340 glDepthRange((GLdouble)zRange.min, (GLdouble)zRange.max);
4341 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4342 return VINF_SUCCESS;
4343}
4344
4345/**
4346 * Convert SVGA blend op value to its OpenGL equivalent
4347 */
4348static GLenum vmsvga3dBlendOp2GL(uint32_t blendOp)
4349{
4350 switch (blendOp)
4351 {
4352 case SVGA3D_BLENDOP_ZERO:
4353 return GL_ZERO;
4354 case SVGA3D_BLENDOP_ONE:
4355 return GL_ONE;
4356 case SVGA3D_BLENDOP_SRCCOLOR:
4357 return GL_SRC_COLOR;
4358 case SVGA3D_BLENDOP_INVSRCCOLOR:
4359 return GL_ONE_MINUS_SRC_COLOR;
4360 case SVGA3D_BLENDOP_SRCALPHA:
4361 return GL_SRC_ALPHA;
4362 case SVGA3D_BLENDOP_INVSRCALPHA:
4363 return GL_ONE_MINUS_SRC_ALPHA;
4364 case SVGA3D_BLENDOP_DESTALPHA:
4365 return GL_DST_ALPHA;
4366 case SVGA3D_BLENDOP_INVDESTALPHA:
4367 return GL_ONE_MINUS_DST_ALPHA;
4368 case SVGA3D_BLENDOP_DESTCOLOR:
4369 return GL_DST_COLOR;
4370 case SVGA3D_BLENDOP_INVDESTCOLOR:
4371 return GL_ONE_MINUS_DST_COLOR;
4372 case SVGA3D_BLENDOP_SRCALPHASAT:
4373 return GL_SRC_ALPHA_SATURATE;
4374 case SVGA3D_BLENDOP_BLENDFACTOR:
4375 return GL_CONSTANT_COLOR;
4376 case SVGA3D_BLENDOP_INVBLENDFACTOR:
4377 return GL_ONE_MINUS_CONSTANT_COLOR;
4378 default:
4379 AssertFailed();
4380 return GL_ONE;
4381 }
4382}
4383
4384static GLenum vmsvga3dBlendEquation2GL(uint32_t blendEq)
4385{
4386 switch (blendEq)
4387 {
4388 case SVGA3D_BLENDEQ_ADD:
4389 return GL_FUNC_ADD;
4390 case SVGA3D_BLENDEQ_SUBTRACT:
4391 return GL_FUNC_SUBTRACT;
4392 case SVGA3D_BLENDEQ_REVSUBTRACT:
4393 return GL_FUNC_REVERSE_SUBTRACT;
4394 case SVGA3D_BLENDEQ_MINIMUM:
4395 return GL_MIN;
4396 case SVGA3D_BLENDEQ_MAXIMUM:
4397 return GL_MAX;
4398 default:
4399 /* SVGA3D_BLENDEQ_INVALID means that the render state has not been set, therefore use default. */
4400 AssertMsg(blendEq == SVGA3D_BLENDEQ_INVALID, ("blendEq=%d (%#x)\n", blendEq, blendEq));
4401 return GL_FUNC_ADD;
4402 }
4403}
4404
4405static GLenum vmsvgaCmpFunc2GL(uint32_t cmpFunc)
4406{
4407 switch (cmpFunc)
4408 {
4409 case SVGA3D_CMP_NEVER:
4410 return GL_NEVER;
4411 case SVGA3D_CMP_LESS:
4412 return GL_LESS;
4413 case SVGA3D_CMP_EQUAL:
4414 return GL_EQUAL;
4415 case SVGA3D_CMP_LESSEQUAL:
4416 return GL_LEQUAL;
4417 case SVGA3D_CMP_GREATER:
4418 return GL_GREATER;
4419 case SVGA3D_CMP_NOTEQUAL:
4420 return GL_NOTEQUAL;
4421 case SVGA3D_CMP_GREATEREQUAL:
4422 return GL_GEQUAL;
4423 case SVGA3D_CMP_ALWAYS:
4424 return GL_ALWAYS;
4425 default:
4426 Assert(cmpFunc == SVGA3D_CMP_INVALID);
4427 return GL_LESS;
4428 }
4429}
4430
4431static GLenum vmsvgaStencipOp2GL(uint32_t stencilOp)
4432{
4433 switch (stencilOp)
4434 {
4435 case SVGA3D_STENCILOP_KEEP:
4436 return GL_KEEP;
4437 case SVGA3D_STENCILOP_ZERO:
4438 return GL_ZERO;
4439 case SVGA3D_STENCILOP_REPLACE:
4440 return GL_REPLACE;
4441 case SVGA3D_STENCILOP_INCRSAT:
4442 return GL_INCR_WRAP;
4443 case SVGA3D_STENCILOP_DECRSAT:
4444 return GL_DECR_WRAP;
4445 case SVGA3D_STENCILOP_INVERT:
4446 return GL_INVERT;
4447 case SVGA3D_STENCILOP_INCR:
4448 return GL_INCR;
4449 case SVGA3D_STENCILOP_DECR:
4450 return GL_DECR;
4451 default:
4452 Assert(stencilOp == SVGA3D_STENCILOP_INVALID);
4453 return GL_KEEP;
4454 }
4455}
4456
4457static DECLCALLBACK(int) vmsvga3dBackSetRenderState(PVGASTATECC pThisCC, uint32_t cid, uint32_t cRenderStates, SVGA3dRenderState *pRenderState)
4458{
4459 uint32_t val = UINT32_MAX; /* Shut up MSC. */
4460 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
4461 AssertReturn(pState, VERR_NO_MEMORY);
4462
4463 Log(("vmsvga3dSetRenderState cid=%u cRenderStates=%d\n", cid, cRenderStates));
4464
4465 PVMSVGA3DCONTEXT pContext;
4466 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
4467 AssertRCReturn(rc, rc);
4468
4469 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
4470
4471 for (unsigned i = 0; i < cRenderStates; i++)
4472 {
4473 GLenum enableCap = ~(GLenum)0;
4474 Log(("vmsvga3dSetRenderState: cid=%u state=%s (%d) val=%x\n", cid, vmsvga3dGetRenderStateName(pRenderState[i].state), pRenderState[i].state, pRenderState[i].uintValue));
4475 /* Save the render state for vm state saving. */
4476 ASSERT_GUEST_RETURN((unsigned)pRenderState[i].state < SVGA3D_RS_MAX, VERR_INVALID_PARAMETER);
4477 pContext->state.aRenderState[pRenderState[i].state] = pRenderState[i];
4478
4479 switch (pRenderState[i].state)
4480 {
4481 case SVGA3D_RS_ZENABLE: /* SVGA3dBool */
4482 enableCap = GL_DEPTH_TEST;
4483 val = pRenderState[i].uintValue;
4484 break;
4485
4486 case SVGA3D_RS_ZWRITEENABLE: /* SVGA3dBool */
4487 glDepthMask(!!pRenderState[i].uintValue);
4488 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4489 break;
4490
4491 case SVGA3D_RS_ALPHATESTENABLE: /* SVGA3dBool */
4492 enableCap = GL_ALPHA_TEST;
4493 val = pRenderState[i].uintValue;
4494 break;
4495
4496 case SVGA3D_RS_DITHERENABLE: /* SVGA3dBool */
4497 enableCap = GL_DITHER;
4498 val = pRenderState[i].uintValue;
4499 break;
4500
4501 case SVGA3D_RS_FOGENABLE: /* SVGA3dBool */
4502 enableCap = GL_FOG;
4503 val = pRenderState[i].uintValue;
4504 break;
4505
4506 case SVGA3D_RS_SPECULARENABLE: /* SVGA3dBool */
4507 Log(("vmsvga3dSetRenderState: WARNING: not applicable.\n"));
4508 break;
4509
4510 case SVGA3D_RS_LIGHTINGENABLE: /* SVGA3dBool */
4511 enableCap = GL_LIGHTING;
4512 val = pRenderState[i].uintValue;
4513 break;
4514
4515 case SVGA3D_RS_NORMALIZENORMALS: /* SVGA3dBool */
4516 /* not applicable */
4517 Log(("vmsvga3dSetRenderState: WARNING: not applicable.\n"));
4518 break;
4519
4520 case SVGA3D_RS_POINTSPRITEENABLE: /* SVGA3dBool */
4521 enableCap = GL_POINT_SPRITE_ARB;
4522 val = pRenderState[i].uintValue;
4523 break;
4524
4525 case SVGA3D_RS_POINTSIZE: /* float */
4526 /** @todo we need to apply scaling for point sizes below the min or above the max; see Wine) */
4527 if (pRenderState[i].floatValue < pState->caps.flPointSize[0])
4528 pRenderState[i].floatValue = pState->caps.flPointSize[0];
4529 if (pRenderState[i].floatValue > pState->caps.flPointSize[1])
4530 pRenderState[i].floatValue = pState->caps.flPointSize[1];
4531
4532 glPointSize(pRenderState[i].floatValue);
4533 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4534 Log(("SVGA3D_RS_POINTSIZE: %d\n", (uint32_t) (pRenderState[i].floatValue * 100.0)));
4535 break;
4536
4537 case SVGA3D_RS_POINTSIZEMIN: /* float */
4538 pState->ext.glPointParameterf(GL_POINT_SIZE_MIN, pRenderState[i].floatValue);
4539 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4540 Log(("SVGA3D_RS_POINTSIZEMIN: %d\n", (uint32_t) (pRenderState[i].floatValue * 100.0)));
4541 break;
4542
4543 case SVGA3D_RS_POINTSIZEMAX: /* float */
4544 pState->ext.glPointParameterf(GL_POINT_SIZE_MAX, pRenderState[i].floatValue);
4545 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4546 Log(("SVGA3D_RS_POINTSIZEMAX: %d\n", (uint32_t) (pRenderState[i].floatValue * 100.0)));
4547 break;
4548
4549 case SVGA3D_RS_POINTSCALEENABLE: /* SVGA3dBool */
4550 case SVGA3D_RS_POINTSCALE_A: /* float */
4551 case SVGA3D_RS_POINTSCALE_B: /* float */
4552 case SVGA3D_RS_POINTSCALE_C: /* float */
4553 Log(("vmsvga3dSetRenderState: WARNING: not applicable.\n"));
4554 break;
4555
4556 case SVGA3D_RS_AMBIENT: /* SVGA3dColor */
4557 {
4558 GLfloat color[4]; /* red, green, blue, alpha */
4559
4560 vmsvgaColor2GLFloatArray(pRenderState[i].uintValue, &color[0], &color[1], &color[2], &color[3]);
4561
4562 glLightModelfv(GL_LIGHT_MODEL_AMBIENT, color);
4563 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4564 break;
4565 }
4566
4567 case SVGA3D_RS_CLIPPLANEENABLE: /* SVGA3dClipPlanes */
4568 {
4569 for (uint32_t j = 0; j < SVGA3D_NUM_CLIPPLANES; j++)
4570 {
4571 if (pRenderState[i].uintValue & RT_BIT(j))
4572 glEnable(GL_CLIP_PLANE0 + j);
4573 else
4574 glDisable(GL_CLIP_PLANE0 + j);
4575 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4576 }
4577 break;
4578 }
4579
4580 case SVGA3D_RS_FOGCOLOR: /* SVGA3dColor */
4581 {
4582 GLfloat color[4]; /* red, green, blue, alpha */
4583
4584 vmsvgaColor2GLFloatArray(pRenderState[i].uintValue, &color[0], &color[1], &color[2], &color[3]);
4585
4586 glFogfv(GL_FOG_COLOR, color);
4587 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4588 break;
4589 }
4590
4591 case SVGA3D_RS_FOGSTART: /* float */
4592 glFogf(GL_FOG_START, pRenderState[i].floatValue);
4593 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4594 break;
4595
4596 case SVGA3D_RS_FOGEND: /* float */
4597 glFogf(GL_FOG_END, pRenderState[i].floatValue);
4598 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4599 break;
4600
4601 case SVGA3D_RS_FOGDENSITY: /* float */
4602 glFogf(GL_FOG_DENSITY, pRenderState[i].floatValue);
4603 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4604 break;
4605
4606 case SVGA3D_RS_RANGEFOGENABLE: /* SVGA3dBool */
4607 glFogi(GL_FOG_COORD_SRC, (pRenderState[i].uintValue) ? GL_FOG_COORD : GL_FRAGMENT_DEPTH);
4608 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4609 break;
4610
4611 case SVGA3D_RS_FOGMODE: /* SVGA3dFogMode */
4612 {
4613 SVGA3dFogMode mode;
4614 mode.uintValue = pRenderState[i].uintValue;
4615
4616 enableCap = GL_FOG_MODE;
4617 switch (mode.function)
4618 {
4619 case SVGA3D_FOGFUNC_EXP:
4620 val = GL_EXP;
4621 break;
4622 case SVGA3D_FOGFUNC_EXP2:
4623 val = GL_EXP2;
4624 break;
4625 case SVGA3D_FOGFUNC_LINEAR:
4626 val = GL_LINEAR;
4627 break;
4628 default:
4629 AssertMsgFailedReturn(("Unexpected fog function %d\n", mode.function), VERR_INTERNAL_ERROR);
4630 break;
4631 }
4632
4633 /** @todo how to switch between vertex and pixel fog modes??? */
4634 Assert(mode.type == SVGA3D_FOGTYPE_PIXEL);
4635#if 0
4636 /* The fog type determines the render state. */
4637 switch (mode.type)
4638 {
4639 case SVGA3D_FOGTYPE_VERTEX:
4640 renderState = D3DRS_FOGVERTEXMODE;
4641 break;
4642 case SVGA3D_FOGTYPE_PIXEL:
4643 renderState = D3DRS_FOGTABLEMODE;
4644 break;
4645 default:
4646 AssertMsgFailedReturn(("Unexpected fog type %d\n", mode.type), VERR_INTERNAL_ERROR);
4647 break;
4648 }
4649#endif
4650
4651 /* Set the fog base to depth or range. */
4652 switch (mode.base)
4653 {
4654 case SVGA3D_FOGBASE_DEPTHBASED:
4655 glFogi(GL_FOG_COORD_SRC, GL_FRAGMENT_DEPTH);
4656 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4657 break;
4658 case SVGA3D_FOGBASE_RANGEBASED:
4659 glFogi(GL_FOG_COORD_SRC, GL_FOG_COORD);
4660 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4661 break;
4662 default:
4663 /* ignore */
4664 AssertMsgFailed(("Unexpected fog base %d\n", mode.base));
4665 break;
4666 }
4667 break;
4668 }
4669
4670 case SVGA3D_RS_FILLMODE: /* SVGA3dFillMode */
4671 {
4672 SVGA3dFillMode mode;
4673
4674 mode.uintValue = pRenderState[i].uintValue;
4675
4676 switch (mode.mode)
4677 {
4678 case SVGA3D_FILLMODE_POINT:
4679 val = GL_POINT;
4680 break;
4681 case SVGA3D_FILLMODE_LINE:
4682 val = GL_LINE;
4683 break;
4684 case SVGA3D_FILLMODE_FILL:
4685 val = GL_FILL;
4686 break;
4687 default:
4688 AssertMsgFailedReturn(("Unexpected fill mode %d\n", mode.mode), VERR_INTERNAL_ERROR);
4689 break;
4690 }
4691 /* Only front and back faces. Also recent Mesa guest drivers initialize the 'face' to zero. */
4692 ASSERT_GUEST(mode.face == SVGA3D_FACE_FRONT_BACK || mode.face == SVGA3D_FACE_INVALID);
4693 glPolygonMode(GL_FRONT_AND_BACK, val);
4694 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4695 break;
4696 }
4697
4698 case SVGA3D_RS_SHADEMODE: /* SVGA3dShadeMode */
4699 switch (pRenderState[i].uintValue)
4700 {
4701 case SVGA3D_SHADEMODE_FLAT:
4702 val = GL_FLAT;
4703 break;
4704
4705 case SVGA3D_SHADEMODE_SMOOTH:
4706 val = GL_SMOOTH;
4707 break;
4708
4709 default:
4710 AssertMsgFailedReturn(("Unexpected shade mode %d\n", pRenderState[i].uintValue), VERR_INTERNAL_ERROR);
4711 break;
4712 }
4713
4714 glShadeModel(val);
4715 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4716 break;
4717
4718 case SVGA3D_RS_LINEPATTERN: /* SVGA3dLinePattern */
4719 /* No longer supported by d3d; mesagl comments suggest not all backends support it */
4720 /** @todo */
4721 Log(("WARNING: SVGA3D_RS_LINEPATTERN %x not supported!!\n", pRenderState[i].uintValue));
4722 /*
4723 renderState = D3DRS_LINEPATTERN;
4724 val = pRenderState[i].uintValue;
4725 */
4726 break;
4727
4728 case SVGA3D_RS_ANTIALIASEDLINEENABLE: /* SVGA3dBool */
4729 enableCap = GL_LINE_SMOOTH;
4730 val = pRenderState[i].uintValue;
4731 break;
4732
4733 case SVGA3D_RS_LINEWIDTH: /* float */
4734 glLineWidth(pRenderState[i].floatValue);
4735 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4736 break;
4737
4738 case SVGA3D_RS_SEPARATEALPHABLENDENABLE: /* SVGA3dBool */
4739 {
4740 /* Refresh the blending state based on the new enable setting.
4741 * This will take existing states and set them using either glBlend* or glBlend*Separate.
4742 */
4743 static SVGA3dRenderStateName const saRefreshState[] =
4744 {
4745 SVGA3D_RS_SRCBLEND,
4746 SVGA3D_RS_BLENDEQUATION
4747 };
4748 SVGA3dRenderState renderstate[RT_ELEMENTS(saRefreshState)];
4749 for (uint32_t j = 0; j < RT_ELEMENTS(saRefreshState); ++j)
4750 {
4751 renderstate[j].state = saRefreshState[j];
4752 renderstate[j].uintValue = pContext->state.aRenderState[saRefreshState[j]].uintValue;
4753 }
4754
4755 rc = vmsvga3dBackSetRenderState(pThisCC, cid, 2, renderstate);
4756 AssertRCReturn(rc, rc);
4757
4758 if (pContext->state.aRenderState[SVGA3D_RS_BLENDENABLE].uintValue != 0)
4759 continue; /* Ignore if blend is enabled */
4760 /* Apply SVGA3D_RS_SEPARATEALPHABLENDENABLE as SVGA3D_RS_BLENDENABLE */
4761 } RT_FALL_THRU();
4762
4763 case SVGA3D_RS_BLENDENABLE: /* SVGA3dBool */
4764 enableCap = GL_BLEND;
4765 val = pRenderState[i].uintValue;
4766 break;
4767
4768 case SVGA3D_RS_SRCBLENDALPHA: /* SVGA3dBlendOp */
4769 case SVGA3D_RS_DSTBLENDALPHA: /* SVGA3dBlendOp */
4770 case SVGA3D_RS_SRCBLEND: /* SVGA3dBlendOp */
4771 case SVGA3D_RS_DSTBLEND: /* SVGA3dBlendOp */
4772 {
4773 GLint srcRGB, srcAlpha, dstRGB, dstAlpha;
4774 GLint blendop = vmsvga3dBlendOp2GL(pRenderState[i].uintValue);
4775
4776 glGetIntegerv(GL_BLEND_SRC_RGB, &srcRGB);
4777 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4778 glGetIntegerv(GL_BLEND_DST_RGB, &dstRGB);
4779 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4780 glGetIntegerv(GL_BLEND_DST_ALPHA, &dstAlpha);
4781 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4782 glGetIntegerv(GL_BLEND_SRC_ALPHA, &srcAlpha);
4783 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4784
4785 switch (pRenderState[i].state)
4786 {
4787 case SVGA3D_RS_SRCBLEND:
4788 srcRGB = blendop;
4789 break;
4790 case SVGA3D_RS_DSTBLEND:
4791 dstRGB = blendop;
4792 break;
4793 case SVGA3D_RS_SRCBLENDALPHA:
4794 srcAlpha = blendop;
4795 break;
4796 case SVGA3D_RS_DSTBLENDALPHA:
4797 dstAlpha = blendop;
4798 break;
4799 default:
4800 /* not possible; shut up gcc */
4801 AssertFailed();
4802 break;
4803 }
4804
4805 if (pContext->state.aRenderState[SVGA3D_RS_SEPARATEALPHABLENDENABLE].uintValue != 0)
4806 pState->ext.glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
4807 else
4808 glBlendFunc(srcRGB, dstRGB);
4809 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4810 break;
4811 }
4812
4813 case SVGA3D_RS_BLENDEQUATIONALPHA: /* SVGA3dBlendEquation */
4814 case SVGA3D_RS_BLENDEQUATION: /* SVGA3dBlendEquation */
4815 if (pContext->state.aRenderState[SVGA3D_RS_SEPARATEALPHABLENDENABLE].uintValue != 0)
4816 {
4817 GLenum const modeRGB = vmsvga3dBlendEquation2GL(pContext->state.aRenderState[SVGA3D_RS_BLENDEQUATION].uintValue);
4818 GLenum const modeAlpha = vmsvga3dBlendEquation2GL(pContext->state.aRenderState[SVGA3D_RS_BLENDEQUATIONALPHA].uintValue);
4819 pState->ext.glBlendEquationSeparate(modeRGB, modeAlpha);
4820 }
4821 else
4822 {
4823#if VBOX_VMSVGA3D_GL_HACK_LEVEL >= 0x102
4824 glBlendEquation(vmsvga3dBlendEquation2GL(pRenderState[i].uintValue));
4825#else
4826 pState->ext.glBlendEquation(vmsvga3dBlendEquation2GL(pRenderState[i].uintValue));
4827#endif
4828 }
4829 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4830 break;
4831
4832 case SVGA3D_RS_BLENDCOLOR: /* SVGA3dColor */
4833 {
4834 GLfloat red, green, blue, alpha;
4835
4836 vmsvgaColor2GLFloatArray(pRenderState[i].uintValue, &red, &green, &blue, &alpha);
4837
4838#if VBOX_VMSVGA3D_GL_HACK_LEVEL >= 0x102
4839 glBlendColor(red, green, blue, alpha);
4840#else
4841 pState->ext.glBlendColor(red, green, blue, alpha);
4842#endif
4843 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4844 break;
4845 }
4846
4847 case SVGA3D_RS_CULLMODE: /* SVGA3dFace */
4848 {
4849 GLenum mode = GL_BACK; /* default for OpenGL */
4850
4851 switch (pRenderState[i].uintValue)
4852 {
4853 case SVGA3D_FACE_NONE:
4854 break;
4855 case SVGA3D_FACE_FRONT:
4856 mode = GL_FRONT;
4857 break;
4858 case SVGA3D_FACE_BACK:
4859 mode = GL_BACK;
4860 break;
4861 case SVGA3D_FACE_FRONT_BACK:
4862 mode = GL_FRONT_AND_BACK;
4863 break;
4864 default:
4865 AssertMsgFailedReturn(("Unexpected cull mode %d\n", pRenderState[i].uintValue), VERR_INTERNAL_ERROR);
4866 break;
4867 }
4868 enableCap = GL_CULL_FACE;
4869 if (pRenderState[i].uintValue != SVGA3D_FACE_NONE)
4870 {
4871 glCullFace(mode);
4872 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4873 val = 1;
4874 }
4875 else
4876 val = 0;
4877 break;
4878 }
4879
4880 case SVGA3D_RS_ZFUNC: /* SVGA3dCmpFunc */
4881 glDepthFunc(vmsvgaCmpFunc2GL(pRenderState[i].uintValue));
4882 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4883 break;
4884
4885 case SVGA3D_RS_ALPHAFUNC: /* SVGA3dCmpFunc */
4886 {
4887 GLclampf ref;
4888
4889 glGetFloatv(GL_ALPHA_TEST_REF, &ref);
4890 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4891 glAlphaFunc(vmsvgaCmpFunc2GL(pRenderState[i].uintValue), ref);
4892 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4893 break;
4894 }
4895
4896 case SVGA3D_RS_ALPHAREF: /* float (0.0 .. 1.0) */
4897 {
4898 GLint func;
4899
4900 glGetIntegerv(GL_ALPHA_TEST_FUNC, &func);
4901 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4902 glAlphaFunc(func, pRenderState[i].floatValue);
4903 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4904 break;
4905 }
4906
4907 case SVGA3D_RS_STENCILENABLE2SIDED: /* SVGA3dBool */
4908 {
4909 /* Refresh the stencil state based on the new enable setting.
4910 * This will take existing states and set them using either glStencil or glStencil*Separate.
4911 */
4912 static SVGA3dRenderStateName const saRefreshState[] =
4913 {
4914 SVGA3D_RS_STENCILFUNC,
4915 SVGA3D_RS_STENCILFAIL,
4916 SVGA3D_RS_CCWSTENCILFUNC,
4917 SVGA3D_RS_CCWSTENCILFAIL
4918 };
4919 SVGA3dRenderState renderstate[RT_ELEMENTS(saRefreshState)];
4920 for (uint32_t j = 0; j < RT_ELEMENTS(saRefreshState); ++j)
4921 {
4922 renderstate[j].state = saRefreshState[j];
4923 renderstate[j].uintValue = pContext->state.aRenderState[saRefreshState[j]].uintValue;
4924 }
4925
4926 rc = vmsvga3dBackSetRenderState(pThisCC, cid, RT_ELEMENTS(renderstate), renderstate);
4927 AssertRCReturn(rc, rc);
4928
4929 if (pContext->state.aRenderState[SVGA3D_RS_STENCILENABLE].uintValue != 0)
4930 continue; /* Ignore if stencil is enabled */
4931 /* Apply SVGA3D_RS_STENCILENABLE2SIDED as SVGA3D_RS_STENCILENABLE. */
4932 } RT_FALL_THRU();
4933
4934 case SVGA3D_RS_STENCILENABLE: /* SVGA3dBool */
4935 enableCap = GL_STENCIL_TEST;
4936 val = pRenderState[i].uintValue;
4937 break;
4938
4939 case SVGA3D_RS_STENCILFUNC: /* SVGA3dCmpFunc */
4940 case SVGA3D_RS_STENCILREF: /* uint32_t */
4941 case SVGA3D_RS_STENCILMASK: /* uint32_t */
4942 {
4943 GLint func, ref;
4944 GLuint mask;
4945
4946 /* Query current values to have all parameters for glStencilFunc[Separate]. */
4947 glGetIntegerv(GL_STENCIL_FUNC, &func);
4948 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4949 glGetIntegerv(GL_STENCIL_VALUE_MASK, (GLint *)&mask);
4950 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4951 glGetIntegerv(GL_STENCIL_REF, &ref);
4952 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4953
4954 /* Update the changed value. */
4955 switch (pRenderState[i].state)
4956 {
4957 case SVGA3D_RS_STENCILFUNC: /* SVGA3dCmpFunc */
4958 func = vmsvgaCmpFunc2GL(pRenderState[i].uintValue);
4959 break;
4960
4961 case SVGA3D_RS_STENCILREF: /* uint32_t */
4962 ref = pRenderState[i].uintValue;
4963 break;
4964
4965 case SVGA3D_RS_STENCILMASK: /* uint32_t */
4966 mask = pRenderState[i].uintValue;
4967 break;
4968
4969 default:
4970 /* not possible; shut up gcc */
4971 AssertFailed();
4972 break;
4973 }
4974
4975 if (pContext->state.aRenderState[SVGA3D_RS_STENCILENABLE2SIDED].uintValue != 0)
4976 {
4977 pState->ext.glStencilFuncSeparate(GL_FRONT, func, ref, mask);
4978 }
4979 else
4980 {
4981 glStencilFunc(func, ref, mask);
4982 }
4983 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4984 break;
4985 }
4986
4987 case SVGA3D_RS_STENCILWRITEMASK: /* uint32_t */
4988 glStencilMask(pRenderState[i].uintValue);
4989 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
4990 break;
4991
4992 case SVGA3D_RS_STENCILFAIL: /* SVGA3dStencilOp */
4993 case SVGA3D_RS_STENCILZFAIL: /* SVGA3dStencilOp */
4994 case SVGA3D_RS_STENCILPASS: /* SVGA3dStencilOp */
4995 {
4996 GLint sfail, dpfail, dppass;
4997 GLenum const stencilop = vmsvgaStencipOp2GL(pRenderState[i].uintValue);
4998
4999 glGetIntegerv(GL_STENCIL_FAIL, &sfail);
5000 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5001 glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, &dpfail);
5002 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5003 glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, &dppass);
5004 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5005
5006 switch (pRenderState[i].state)
5007 {
5008 case SVGA3D_RS_STENCILFAIL: /* SVGA3dStencilOp */
5009 sfail = stencilop;
5010 break;
5011 case SVGA3D_RS_STENCILZFAIL: /* SVGA3dStencilOp */
5012 dpfail = stencilop;
5013 break;
5014 case SVGA3D_RS_STENCILPASS: /* SVGA3dStencilOp */
5015 dppass = stencilop;
5016 break;
5017 default:
5018 /* not possible; shut up gcc */
5019 AssertFailed();
5020 break;
5021 }
5022 if (pContext->state.aRenderState[SVGA3D_RS_STENCILENABLE2SIDED].uintValue != 0)
5023 {
5024 pState->ext.glStencilOpSeparate(GL_FRONT, sfail, dpfail, dppass);
5025 }
5026 else
5027 {
5028 glStencilOp(sfail, dpfail, dppass);
5029 }
5030 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5031 break;
5032 }
5033
5034 case SVGA3D_RS_CCWSTENCILFUNC: /* SVGA3dCmpFunc */
5035 {
5036 GLint ref;
5037 GLuint mask;
5038 GLint const func = vmsvgaCmpFunc2GL(pRenderState[i].uintValue);
5039
5040 /* GL_STENCIL_VALUE_MASK and GL_STENCIL_REF are the same for both GL_FRONT and GL_BACK. */
5041 glGetIntegerv(GL_STENCIL_VALUE_MASK, (GLint *)&mask);
5042 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5043 glGetIntegerv(GL_STENCIL_REF, &ref);
5044 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5045
5046 pState->ext.glStencilFuncSeparate(GL_BACK, func, ref, mask);
5047 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5048 break;
5049 }
5050
5051 case SVGA3D_RS_CCWSTENCILFAIL: /* SVGA3dStencilOp */
5052 case SVGA3D_RS_CCWSTENCILZFAIL: /* SVGA3dStencilOp */
5053 case SVGA3D_RS_CCWSTENCILPASS: /* SVGA3dStencilOp */
5054 {
5055 GLint sfail, dpfail, dppass;
5056 GLenum const stencilop = vmsvgaStencipOp2GL(pRenderState[i].uintValue);
5057
5058 glGetIntegerv(GL_STENCIL_BACK_FAIL, &sfail);
5059 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5060 glGetIntegerv(GL_STENCIL_BACK_PASS_DEPTH_FAIL, &dpfail);
5061 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5062 glGetIntegerv(GL_STENCIL_BACK_PASS_DEPTH_PASS, &dppass);
5063 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5064
5065 switch (pRenderState[i].state)
5066 {
5067 case SVGA3D_RS_CCWSTENCILFAIL: /* SVGA3dStencilOp */
5068 sfail = stencilop;
5069 break;
5070 case SVGA3D_RS_CCWSTENCILZFAIL: /* SVGA3dStencilOp */
5071 dpfail = stencilop;
5072 break;
5073 case SVGA3D_RS_CCWSTENCILPASS: /* SVGA3dStencilOp */
5074 dppass = stencilop;
5075 break;
5076 default:
5077 /* not possible; shut up gcc */
5078 AssertFailed();
5079 break;
5080 }
5081 pState->ext.glStencilOpSeparate(GL_BACK, sfail, dpfail, dppass);
5082 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5083 break;
5084 }
5085
5086 case SVGA3D_RS_ZBIAS: /* float */
5087 /** @todo unknown meaning; depth bias is not identical
5088 renderState = D3DRS_DEPTHBIAS;
5089 val = pRenderState[i].uintValue;
5090 */
5091 Log(("vmsvga3dSetRenderState: WARNING unsupported SVGA3D_RS_ZBIAS\n"));
5092 break;
5093
5094 case SVGA3D_RS_DEPTHBIAS: /* float */
5095 {
5096 GLfloat factor;
5097
5098 /** @todo not sure if the d3d & ogl definitions are identical. */
5099
5100 /* Do not change the factor part. */
5101 glGetFloatv(GL_POLYGON_OFFSET_FACTOR, &factor);
5102 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5103
5104 glPolygonOffset(factor, pRenderState[i].floatValue);
5105 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5106 break;
5107 }
5108
5109 case SVGA3D_RS_SLOPESCALEDEPTHBIAS: /* float */
5110 {
5111 GLfloat units;
5112
5113 /** @todo not sure if the d3d & ogl definitions are identical. */
5114
5115 /* Do not change the factor part. */
5116 glGetFloatv(GL_POLYGON_OFFSET_UNITS, &units);
5117 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5118
5119 glPolygonOffset(pRenderState[i].floatValue, units);
5120 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5121 break;
5122 }
5123
5124 case SVGA3D_RS_COLORWRITEENABLE: /* SVGA3dColorMask */
5125 {
5126 GLboolean red, green, blue, alpha;
5127 SVGA3dColorMask mask;
5128
5129 mask.uintValue = pRenderState[i].uintValue;
5130
5131 red = mask.red;
5132 green = mask.green;
5133 blue = mask.blue;
5134 alpha = mask.alpha;
5135
5136 glColorMask(red, green, blue, alpha);
5137 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5138 break;
5139 }
5140
5141 case SVGA3D_RS_COLORWRITEENABLE1: /* SVGA3dColorMask to D3DCOLORWRITEENABLE_* */
5142 case SVGA3D_RS_COLORWRITEENABLE2: /* SVGA3dColorMask to D3DCOLORWRITEENABLE_* */
5143 case SVGA3D_RS_COLORWRITEENABLE3: /* SVGA3dColorMask to D3DCOLORWRITEENABLE_* */
5144 Log(("vmsvga3dSetRenderState: WARNING SVGA3D_RS_COLORWRITEENABLEx not supported!!\n"));
5145 break;
5146
5147 case SVGA3D_RS_SCISSORTESTENABLE: /* SVGA3dBool */
5148 enableCap = GL_SCISSOR_TEST;
5149 val = pRenderState[i].uintValue;
5150 break;
5151
5152#if 0
5153 case SVGA3D_RS_DIFFUSEMATERIALSOURCE: /* SVGA3dVertexMaterial */
5154 AssertCompile(D3DMCS_COLOR2 == SVGA3D_VERTEXMATERIAL_SPECULAR);
5155 renderState = D3DRS_DIFFUSEMATERIALSOURCE;
5156 val = pRenderState[i].uintValue;
5157 break;
5158
5159 case SVGA3D_RS_SPECULARMATERIALSOURCE: /* SVGA3dVertexMaterial */
5160 renderState = D3DRS_SPECULARMATERIALSOURCE;
5161 val = pRenderState[i].uintValue;
5162 break;
5163
5164 case SVGA3D_RS_AMBIENTMATERIALSOURCE: /* SVGA3dVertexMaterial */
5165 renderState = D3DRS_AMBIENTMATERIALSOURCE;
5166 val = pRenderState[i].uintValue;
5167 break;
5168
5169 case SVGA3D_RS_EMISSIVEMATERIALSOURCE: /* SVGA3dVertexMaterial */
5170 renderState = D3DRS_EMISSIVEMATERIALSOURCE;
5171 val = pRenderState[i].uintValue;
5172 break;
5173#endif
5174
5175 case SVGA3D_RS_WRAP3: /* SVGA3dWrapFlags */
5176 case SVGA3D_RS_WRAP4: /* SVGA3dWrapFlags */
5177 case SVGA3D_RS_WRAP5: /* SVGA3dWrapFlags */
5178 case SVGA3D_RS_WRAP6: /* SVGA3dWrapFlags */
5179 case SVGA3D_RS_WRAP7: /* SVGA3dWrapFlags */
5180 case SVGA3D_RS_WRAP8: /* SVGA3dWrapFlags */
5181 case SVGA3D_RS_WRAP9: /* SVGA3dWrapFlags */
5182 case SVGA3D_RS_WRAP10: /* SVGA3dWrapFlags */
5183 case SVGA3D_RS_WRAP11: /* SVGA3dWrapFlags */
5184 case SVGA3D_RS_WRAP12: /* SVGA3dWrapFlags */
5185 case SVGA3D_RS_WRAP13: /* SVGA3dWrapFlags */
5186 case SVGA3D_RS_WRAP14: /* SVGA3dWrapFlags */
5187 case SVGA3D_RS_WRAP15: /* SVGA3dWrapFlags */
5188 Log(("vmsvga3dSetRenderState: WARNING unsupported SVGA3D_WRAPx (x >= 3)\n"));
5189 break;
5190
5191 case SVGA3D_RS_LASTPIXEL: /* SVGA3dBool */
5192 case SVGA3D_RS_TWEENFACTOR: /* float */
5193 case SVGA3D_RS_INDEXEDVERTEXBLENDENABLE: /* SVGA3dBool */
5194 case SVGA3D_RS_VERTEXBLEND: /* SVGA3dVertexBlendFlags */
5195 Log(("vmsvga3dSetRenderState: WARNING not applicable!!\n"));
5196 break;
5197
5198 case SVGA3D_RS_MULTISAMPLEANTIALIAS: /* SVGA3dBool */
5199 enableCap = GL_MULTISAMPLE;
5200 val = pRenderState[i].uintValue;
5201 break;
5202
5203 case SVGA3D_RS_MULTISAMPLEMASK: /* uint32_t */
5204 Log(("vmsvga3dSetRenderState: WARNING not applicable??!!\n"));
5205 break;
5206
5207 case SVGA3D_RS_COORDINATETYPE: /* SVGA3dCoordinateType */
5208 Assert(pRenderState[i].uintValue == SVGA3D_COORDINATE_LEFTHANDED);
5209 /** @todo setup a view matrix to scale the world space by -1 in the z-direction for right handed coordinates. */
5210 /*
5211 renderState = D3DRS_COORDINATETYPE;
5212 val = pRenderState[i].uintValue;
5213 */
5214 break;
5215
5216 case SVGA3D_RS_FRONTWINDING: /* SVGA3dFrontWinding */
5217 Assert(pRenderState[i].uintValue == SVGA3D_FRONTWINDING_CW);
5218 /* Invert the selected mode because of y-inversion (?) */
5219 glFrontFace((pRenderState[i].uintValue != SVGA3D_FRONTWINDING_CW) ? GL_CW : GL_CCW);
5220 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5221 break;
5222
5223 case SVGA3D_RS_OUTPUTGAMMA: /* float */
5224 //AssertFailed();
5225 /*
5226 D3DRS_SRGBWRITEENABLE ??
5227 renderState = D3DRS_OUTPUTGAMMA;
5228 val = pRenderState[i].uintValue;
5229 */
5230 break;
5231
5232#if 0
5233
5234 case SVGA3D_RS_VERTEXMATERIALENABLE: /* SVGA3dBool */
5235 //AssertFailed();
5236 renderState = D3DRS_INDEXEDVERTEXBLENDENABLE; /* correct?? */
5237 val = pRenderState[i].uintValue;
5238 break;
5239
5240 case SVGA3D_RS_TEXTUREFACTOR: /* SVGA3dColor */
5241 renderState = D3DRS_TEXTUREFACTOR;
5242 val = pRenderState[i].uintValue;
5243 break;
5244
5245 case SVGA3D_RS_LOCALVIEWER: /* SVGA3dBool */
5246 renderState = D3DRS_LOCALVIEWER;
5247 val = pRenderState[i].uintValue;
5248 break;
5249
5250 case SVGA3D_RS_ZVISIBLE: /* SVGA3dBool */
5251 AssertFailed();
5252 /*
5253 renderState = D3DRS_ZVISIBLE;
5254 val = pRenderState[i].uintValue;
5255 */
5256 break;
5257
5258 case SVGA3D_RS_CLIPPING: /* SVGA3dBool */
5259 renderState = D3DRS_CLIPPING;
5260 val = pRenderState[i].uintValue;
5261 break;
5262
5263 case SVGA3D_RS_WRAP0: /* SVGA3dWrapFlags */
5264 glTexParameter GL_TEXTURE_WRAP_S
5265 Assert(SVGA3D_WRAPCOORD_3 == D3DWRAPCOORD_3);
5266 renderState = D3DRS_WRAP0;
5267 val = pRenderState[i].uintValue;
5268 break;
5269
5270 case SVGA3D_RS_WRAP1: /* SVGA3dWrapFlags */
5271 glTexParameter GL_TEXTURE_WRAP_T
5272 renderState = D3DRS_WRAP1;
5273 val = pRenderState[i].uintValue;
5274 break;
5275
5276 case SVGA3D_RS_WRAP2: /* SVGA3dWrapFlags */
5277 glTexParameter GL_TEXTURE_WRAP_R
5278 renderState = D3DRS_WRAP2;
5279 val = pRenderState[i].uintValue;
5280 break;
5281
5282
5283 case SVGA3D_RS_SEPARATEALPHABLENDENABLE: /* SVGA3dBool */
5284 renderState = D3DRS_SEPARATEALPHABLENDENABLE;
5285 val = pRenderState[i].uintValue;
5286 break;
5287
5288
5289 case SVGA3D_RS_BLENDEQUATIONALPHA: /* SVGA3dBlendEquation */
5290 renderState = D3DRS_BLENDOPALPHA;
5291 val = pRenderState[i].uintValue;
5292 break;
5293
5294 case SVGA3D_RS_TRANSPARENCYANTIALIAS: /* SVGA3dTransparencyAntialiasType */
5295 AssertFailed();
5296 /*
5297 renderState = D3DRS_TRANSPARENCYANTIALIAS;
5298 val = pRenderState[i].uintValue;
5299 */
5300 break;
5301
5302#endif
5303 default:
5304 AssertFailed();
5305 break;
5306 }
5307
5308 if (enableCap != ~(GLenum)0)
5309 {
5310 if (val)
5311 glEnable(enableCap);
5312 else
5313 glDisable(enableCap);
5314 }
5315 }
5316
5317 return VINF_SUCCESS;
5318}
5319
5320static DECLCALLBACK(int) vmsvga3dBackSetRenderTarget(PVGASTATECC pThisCC, uint32_t cid, SVGA3dRenderTargetType type, SVGA3dSurfaceImageId target)
5321{
5322 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
5323
5324 AssertReturn(pState, VERR_NO_MEMORY);
5325 AssertReturn((unsigned)type < SVGA3D_RT_MAX, VERR_INVALID_PARAMETER);
5326
5327 LogFunc(("cid=%u type=%x sid=%u\n", cid, type, target.sid));
5328
5329 PVMSVGA3DCONTEXT pContext;
5330 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
5331 AssertRCReturn(rc, rc);
5332
5333 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5334
5335 /* Save for vm state save/restore. */
5336 pContext->state.aRenderTargets[type] = target.sid;
5337
5338 if (target.sid == SVGA3D_INVALID_ID)
5339 {
5340 /* Disable render target. */
5341 switch (type)
5342 {
5343 case SVGA3D_RT_DEPTH:
5344 case SVGA3D_RT_STENCIL:
5345 pState->ext.glFramebufferRenderbuffer(GL_FRAMEBUFFER, (type == SVGA3D_RT_DEPTH) ? GL_DEPTH_ATTACHMENT : GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0);
5346 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5347 break;
5348
5349 case SVGA3D_RT_COLOR0:
5350 case SVGA3D_RT_COLOR1:
5351 case SVGA3D_RT_COLOR2:
5352 case SVGA3D_RT_COLOR3:
5353 case SVGA3D_RT_COLOR4:
5354 case SVGA3D_RT_COLOR5:
5355 case SVGA3D_RT_COLOR6:
5356 case SVGA3D_RT_COLOR7:
5357 pState->ext.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + type - SVGA3D_RT_COLOR0, 0, 0, 0);
5358 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5359 break;
5360
5361 default:
5362 AssertFailedReturn(VERR_INVALID_PARAMETER);
5363 }
5364 return VINF_SUCCESS;
5365 }
5366
5367 PVMSVGA3DSURFACE pRenderTarget;
5368 rc = vmsvga3dSurfaceFromSid(pState, target.sid, &pRenderTarget);
5369 AssertRCReturn(rc, rc);
5370
5371 switch (type)
5372 {
5373 case SVGA3D_RT_DEPTH:
5374 case SVGA3D_RT_STENCIL:
5375#if 1
5376 /* A texture surface can be used as a render target to fill it and later on used as a texture. */
5377 if (pRenderTarget->oglId.texture == OPENGL_INVALID_ID)
5378 {
5379 LogFunc(("create depth texture to be used as render target; surface id=%x type=%d format=%d -> create texture\n",
5380 target.sid, pRenderTarget->f.s.surface1Flags, pRenderTarget->format));
5381 rc = vmsvga3dBackCreateTexture(pThisCC, pContext, cid, pRenderTarget);
5382 AssertRCReturn(rc, rc);
5383 }
5384
5385 AssertReturn(pRenderTarget->oglId.texture != OPENGL_INVALID_ID, VERR_INVALID_PARAMETER);
5386 Assert(!pRenderTarget->fDirty);
5387
5388 pRenderTarget->f.s.surface1Flags |= SVGA3D_SURFACE_HINT_DEPTHSTENCIL;
5389
5390 pState->ext.glFramebufferTexture2D(GL_FRAMEBUFFER,
5391 (type == SVGA3D_RT_DEPTH) ? GL_DEPTH_ATTACHMENT : GL_STENCIL_ATTACHMENT,
5392 GL_TEXTURE_2D, pRenderTarget->oglId.texture, target.mipmap);
5393 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5394#else
5395 AssertReturn(target.mipmap == 0, VERR_INVALID_PARAMETER);
5396 if (pRenderTarget->oglId.texture == OPENGL_INVALID_ID)
5397 {
5398 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));
5399 pContext = &pState->SharedCtx;
5400 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5401
5402 pState->ext.glGenRenderbuffers(1, &pRenderTarget->oglId.renderbuffer);
5403 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5404 pSurface->enmOGLResType = VMSVGA3D_OGLRESTYPE_RENDERBUFFER;
5405
5406 pState->ext.glBindRenderbuffer(GL_RENDERBUFFER, pRenderTarget->oglId.renderbuffer);
5407 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5408
5409 pState->ext.glRenderbufferStorage(GL_RENDERBUFFER,
5410 pRenderTarget->internalFormatGL,
5411 pRenderTarget->paMipmapLevels[0].mipmapSize.width,
5412 pRenderTarget->paMipmapLevels[0].mipmapSize.height);
5413 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5414
5415 pState->ext.glBindRenderbuffer(GL_RENDERBUFFER, OPENGL_INVALID_ID);
5416 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5417
5418 pContext = pState->papContexts[cid];
5419 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5420 }
5421
5422 pState->ext.glBindRenderbuffer(GL_RENDERBUFFER, pRenderTarget->oglId.renderbuffer);
5423 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5424 Assert(!pRenderTarget->fDirty);
5425 AssertReturn(pRenderTarget->oglId.texture != OPENGL_INVALID_ID, VERR_INVALID_PARAMETER);
5426
5427 pRenderTarget->f.s.surface1Flags |= SVGA3D_SURFACE_HINT_DEPTHSTENCIL;
5428
5429 pState->ext.glFramebufferRenderbuffer(GL_FRAMEBUFFER,
5430 (type == SVGA3D_RT_DEPTH) ? GL_DEPTH_ATTACHMENT : GL_STENCIL_ATTACHMENT,
5431 GL_RENDERBUFFER, pRenderTarget->oglId.renderbuffer);
5432 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5433#endif
5434 break;
5435
5436 case SVGA3D_RT_COLOR0:
5437 case SVGA3D_RT_COLOR1:
5438 case SVGA3D_RT_COLOR2:
5439 case SVGA3D_RT_COLOR3:
5440 case SVGA3D_RT_COLOR4:
5441 case SVGA3D_RT_COLOR5:
5442 case SVGA3D_RT_COLOR6:
5443 case SVGA3D_RT_COLOR7:
5444 {
5445 /* A texture surface can be used as a render target to fill it and later on used as a texture. */
5446 if (pRenderTarget->oglId.texture == OPENGL_INVALID_ID)
5447 {
5448 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));
5449 rc = vmsvga3dBackCreateTexture(pThisCC, pContext, cid, pRenderTarget);
5450 AssertRCReturn(rc, rc);
5451 }
5452
5453 AssertReturn(pRenderTarget->oglId.texture != OPENGL_INVALID_ID, VERR_INVALID_PARAMETER);
5454 Assert(!pRenderTarget->fDirty);
5455
5456 pRenderTarget->f.s.surface1Flags |= SVGA3D_SURFACE_HINT_RENDERTARGET;
5457
5458 GLenum textarget;
5459 if (pRenderTarget->f.s.surface1Flags & SVGA3D_SURFACE_CUBEMAP)
5460 textarget = vmsvga3dCubemapFaceFromIndex(target.face);
5461 else
5462 textarget = GL_TEXTURE_2D;
5463 pState->ext.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + type - SVGA3D_RT_COLOR0,
5464 textarget, pRenderTarget->oglId.texture, target.mipmap);
5465 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5466
5467#ifdef DEBUG
5468 GLenum status = pState->ext.glCheckFramebufferStatus(GL_FRAMEBUFFER);
5469 if (status != GL_FRAMEBUFFER_COMPLETE)
5470 Log(("vmsvga3dSetRenderTarget: WARNING: glCheckFramebufferStatus returned %x\n", status));
5471#endif
5472 /** @todo use glDrawBuffers too? */
5473 break;
5474 }
5475
5476 default:
5477 AssertFailedReturn(VERR_INVALID_PARAMETER);
5478 }
5479
5480 return VINF_SUCCESS;
5481}
5482
5483#if 0
5484/**
5485 * Convert SVGA texture combiner value to its D3D equivalent
5486 */
5487static DWORD vmsvga3dTextureCombiner2D3D(uint32_t value)
5488{
5489 switch (value)
5490 {
5491 case SVGA3D_TC_DISABLE:
5492 return D3DTOP_DISABLE;
5493 case SVGA3D_TC_SELECTARG1:
5494 return D3DTOP_SELECTARG1;
5495 case SVGA3D_TC_SELECTARG2:
5496 return D3DTOP_SELECTARG2;
5497 case SVGA3D_TC_MODULATE:
5498 return D3DTOP_MODULATE;
5499 case SVGA3D_TC_ADD:
5500 return D3DTOP_ADD;
5501 case SVGA3D_TC_ADDSIGNED:
5502 return D3DTOP_ADDSIGNED;
5503 case SVGA3D_TC_SUBTRACT:
5504 return D3DTOP_SUBTRACT;
5505 case SVGA3D_TC_BLENDTEXTUREALPHA:
5506 return D3DTOP_BLENDTEXTUREALPHA;
5507 case SVGA3D_TC_BLENDDIFFUSEALPHA:
5508 return D3DTOP_BLENDDIFFUSEALPHA;
5509 case SVGA3D_TC_BLENDCURRENTALPHA:
5510 return D3DTOP_BLENDCURRENTALPHA;
5511 case SVGA3D_TC_BLENDFACTORALPHA:
5512 return D3DTOP_BLENDFACTORALPHA;
5513 case SVGA3D_TC_MODULATE2X:
5514 return D3DTOP_MODULATE2X;
5515 case SVGA3D_TC_MODULATE4X:
5516 return D3DTOP_MODULATE4X;
5517 case SVGA3D_TC_DSDT:
5518 AssertFailed(); /** @todo ??? */
5519 return D3DTOP_DISABLE;
5520 case SVGA3D_TC_DOTPRODUCT3:
5521 return D3DTOP_DOTPRODUCT3;
5522 case SVGA3D_TC_BLENDTEXTUREALPHAPM:
5523 return D3DTOP_BLENDTEXTUREALPHAPM;
5524 case SVGA3D_TC_ADDSIGNED2X:
5525 return D3DTOP_ADDSIGNED2X;
5526 case SVGA3D_TC_ADDSMOOTH:
5527 return D3DTOP_ADDSMOOTH;
5528 case SVGA3D_TC_PREMODULATE:
5529 return D3DTOP_PREMODULATE;
5530 case SVGA3D_TC_MODULATEALPHA_ADDCOLOR:
5531 return D3DTOP_MODULATEALPHA_ADDCOLOR;
5532 case SVGA3D_TC_MODULATECOLOR_ADDALPHA:
5533 return D3DTOP_MODULATECOLOR_ADDALPHA;
5534 case SVGA3D_TC_MODULATEINVALPHA_ADDCOLOR:
5535 return D3DTOP_MODULATEINVALPHA_ADDCOLOR;
5536 case SVGA3D_TC_MODULATEINVCOLOR_ADDALPHA:
5537 return D3DTOP_MODULATEINVCOLOR_ADDALPHA;
5538 case SVGA3D_TC_BUMPENVMAPLUMINANCE:
5539 return D3DTOP_BUMPENVMAPLUMINANCE;
5540 case SVGA3D_TC_MULTIPLYADD:
5541 return D3DTOP_MULTIPLYADD;
5542 case SVGA3D_TC_LERP:
5543 return D3DTOP_LERP;
5544 default:
5545 AssertFailed();
5546 return D3DTOP_DISABLE;
5547 }
5548}
5549
5550/**
5551 * Convert SVGA texture arg data value to its D3D equivalent
5552 */
5553static DWORD vmsvga3dTextureArgData2D3D(uint32_t value)
5554{
5555 switch (value)
5556 {
5557 case SVGA3D_TA_CONSTANT:
5558 return D3DTA_CONSTANT;
5559 case SVGA3D_TA_PREVIOUS:
5560 return D3DTA_CURRENT; /* current = previous */
5561 case SVGA3D_TA_DIFFUSE:
5562 return D3DTA_DIFFUSE;
5563 case SVGA3D_TA_TEXTURE:
5564 return D3DTA_TEXTURE;
5565 case SVGA3D_TA_SPECULAR:
5566 return D3DTA_SPECULAR;
5567 default:
5568 AssertFailed();
5569 return 0;
5570 }
5571}
5572
5573/**
5574 * Convert SVGA texture transform flag value to its D3D equivalent
5575 */
5576static DWORD vmsvga3dTextTransformFlags2D3D(uint32_t value)
5577{
5578 switch (value)
5579 {
5580 case SVGA3D_TEX_TRANSFORM_OFF:
5581 return D3DTTFF_DISABLE;
5582 case SVGA3D_TEX_TRANSFORM_S:
5583 return D3DTTFF_COUNT1; /** @todo correct? */
5584 case SVGA3D_TEX_TRANSFORM_T:
5585 return D3DTTFF_COUNT2; /** @todo correct? */
5586 case SVGA3D_TEX_TRANSFORM_R:
5587 return D3DTTFF_COUNT3; /** @todo correct? */
5588 case SVGA3D_TEX_TRANSFORM_Q:
5589 return D3DTTFF_COUNT4; /** @todo correct? */
5590 case SVGA3D_TEX_PROJECTED:
5591 return D3DTTFF_PROJECTED;
5592 default:
5593 AssertFailed();
5594 return 0;
5595 }
5596}
5597#endif
5598
5599static GLenum vmsvga3dTextureAddress2OGL(SVGA3dTextureAddress value)
5600{
5601 switch (value)
5602 {
5603 case SVGA3D_TEX_ADDRESS_WRAP:
5604 return GL_REPEAT;
5605 case SVGA3D_TEX_ADDRESS_MIRROR:
5606 return GL_MIRRORED_REPEAT;
5607 case SVGA3D_TEX_ADDRESS_CLAMP:
5608 return GL_CLAMP_TO_EDGE;
5609 case SVGA3D_TEX_ADDRESS_BORDER:
5610 return GL_CLAMP_TO_BORDER;
5611 case SVGA3D_TEX_ADDRESS_MIRRORONCE:
5612 AssertFailed();
5613 return GL_CLAMP_TO_EDGE_SGIS; /** @todo correct? */
5614
5615 case SVGA3D_TEX_ADDRESS_EDGE:
5616 case SVGA3D_TEX_ADDRESS_INVALID:
5617 default:
5618 AssertFailed();
5619 return GL_REPEAT; /* default */
5620 }
5621}
5622
5623static GLenum vmsvga3dTextureFilter2OGL(SVGA3dTextureFilter value)
5624{
5625 switch (value)
5626 {
5627 case SVGA3D_TEX_FILTER_NONE:
5628 case SVGA3D_TEX_FILTER_LINEAR:
5629 case SVGA3D_TEX_FILTER_ANISOTROPIC: /* Anisotropic filtering is controlled by SVGA3D_TS_TEXTURE_ANISOTROPIC_LEVEL */
5630 return GL_LINEAR;
5631 case SVGA3D_TEX_FILTER_NEAREST:
5632 return GL_NEAREST;
5633 case SVGA3D_TEX_FILTER_FLATCUBIC: // Deprecated, not implemented
5634 case SVGA3D_TEX_FILTER_GAUSSIANCUBIC: // Deprecated, not implemented
5635 case SVGA3D_TEX_FILTER_PYRAMIDALQUAD: // Not currently implemented
5636 case SVGA3D_TEX_FILTER_GAUSSIANQUAD: // Not currently implemented
5637 default:
5638 AssertFailed();
5639 return GL_LINEAR; /* default */
5640 }
5641}
5642
5643uint32_t vmsvga3dSVGA3dColor2RGBA(SVGA3dColor value)
5644{
5645 /* flip the red and blue bytes */
5646 uint8_t blue = value & 0xff;
5647 uint8_t red = (value >> 16) & 0xff;
5648 return (value & 0xff00ff00) | red | (blue << 16);
5649}
5650
5651static DECLCALLBACK(int) vmsvga3dBackSetTextureState(PVGASTATECC pThisCC, uint32_t cid, uint32_t cTextureStates, SVGA3dTextureState *pTextureState)
5652{
5653 GLenum val = ~(GLenum)0; /* Shut up MSC. */
5654 GLenum currentStage = ~(GLenum)0;
5655 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
5656 AssertReturn(pState, VERR_NO_MEMORY);
5657
5658 Log(("vmsvga3dSetTextureState %x cTextureState=%d\n", cid, cTextureStates));
5659
5660 PVMSVGA3DCONTEXT pContext;
5661 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
5662 AssertRCReturn(rc, rc);
5663
5664 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5665
5666 /* Which texture is active for the current stage. Needed to use right OpenGL target when setting parameters. */
5667 PVMSVGA3DSURFACE pCurrentTextureSurface = NULL;
5668
5669 for (uint32_t i = 0; i < cTextureStates; ++i)
5670 {
5671 GLenum textureType = ~(GLenum)0;
5672#if 0
5673 GLenum samplerType = ~(GLenum)0;
5674#endif
5675
5676 LogFunc(("cid=%u stage=%d type=%s (%x) val=%x\n",
5677 cid, pTextureState[i].stage, vmsvga3dTextureStateToString(pTextureState[i].name), pTextureState[i].name, pTextureState[i].value));
5678
5679 /* Record the texture state for vm state saving. */
5680 if ( pTextureState[i].stage < RT_ELEMENTS(pContext->state.aTextureStates)
5681 && (unsigned)pTextureState[i].name < RT_ELEMENTS(pContext->state.aTextureStates[0]))
5682 {
5683 pContext->state.aTextureStates[pTextureState[i].stage][pTextureState[i].name] = pTextureState[i];
5684 }
5685
5686 /* Activate the right texture unit for subsequent texture state changes. */
5687 if (pTextureState[i].stage != currentStage || i == 0)
5688 {
5689 /** @todo Is this the appropriate limit for all kinds of textures? It is the
5690 * size of aSidActiveTextures and for binding/unbinding we cannot exceed it. */
5691 if (pTextureState[i].stage < RT_ELEMENTS(pContext->state.aTextureStates))
5692 {
5693 pState->ext.glActiveTexture(GL_TEXTURE0 + pTextureState[i].stage);
5694 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5695 currentStage = pTextureState[i].stage;
5696 }
5697 else
5698 {
5699 AssertMsgFailed(("pTextureState[%d].stage=%#x name=%#x\n", i, pTextureState[i].stage, pTextureState[i].name));
5700 continue;
5701 }
5702
5703 if (pContext->aSidActiveTextures[currentStage] != SVGA3D_INVALID_ID)
5704 {
5705 rc = vmsvga3dSurfaceFromSid(pState, pContext->aSidActiveTextures[currentStage], &pCurrentTextureSurface);
5706 AssertRCReturn(rc, rc);
5707 }
5708 else
5709 pCurrentTextureSurface = NULL; /* Make sure that no stale pointer is used. */
5710 }
5711
5712 switch (pTextureState[i].name)
5713 {
5714 case SVGA3D_TS_BUMPENVMAT00: /* float */
5715 case SVGA3D_TS_BUMPENVMAT01: /* float */
5716 case SVGA3D_TS_BUMPENVMAT10: /* float */
5717 case SVGA3D_TS_BUMPENVMAT11: /* float */
5718 case SVGA3D_TS_BUMPENVLSCALE: /* float */
5719 case SVGA3D_TS_BUMPENVLOFFSET: /* float */
5720 Log(("vmsvga3dSetTextureState: bump mapping texture options not supported!!\n"));
5721 break;
5722
5723 case SVGA3D_TS_COLOROP: /* SVGA3dTextureCombiner */
5724 case SVGA3D_TS_COLORARG0: /* SVGA3dTextureArgData */
5725 case SVGA3D_TS_COLORARG1: /* SVGA3dTextureArgData */
5726 case SVGA3D_TS_COLORARG2: /* SVGA3dTextureArgData */
5727 case SVGA3D_TS_ALPHAOP: /* SVGA3dTextureCombiner */
5728 case SVGA3D_TS_ALPHAARG0: /* SVGA3dTextureArgData */
5729 case SVGA3D_TS_ALPHAARG1: /* SVGA3dTextureArgData */
5730 case SVGA3D_TS_ALPHAARG2: /* SVGA3dTextureArgData */
5731 /** @todo not used by MesaGL */
5732 Log(("vmsvga3dSetTextureState: colorop/alphaop not yet supported!!\n"));
5733 break;
5734#if 0
5735
5736 case SVGA3D_TS_TEXCOORDINDEX: /* uint32_t */
5737 textureType = D3DTSS_TEXCOORDINDEX;
5738 val = pTextureState[i].value;
5739 break;
5740
5741 case SVGA3D_TS_TEXTURETRANSFORMFLAGS: /* SVGA3dTexTransformFlags */
5742 textureType = D3DTSS_TEXTURETRANSFORMFLAGS;
5743 val = vmsvga3dTextTransformFlags2D3D(pTextureState[i].value);
5744 break;
5745#endif
5746
5747 case SVGA3D_TS_BIND_TEXTURE: /* SVGA3dSurfaceId */
5748 {
5749 uint32_t const sid = pTextureState[i].value;
5750
5751 Log(("SVGA3D_TS_BIND_TEXTURE: stage %d, texture sid=%u replacing sid=%u\n",
5752 currentStage, sid, pContext->aSidActiveTextures[currentStage]));
5753
5754 /* Only if texture actually changed. */ /// @todo needs testing.
5755 if (pContext->aSidActiveTextures[currentStage] != sid)
5756 {
5757 if (pCurrentTextureSurface)
5758 {
5759 /* Unselect the currently associated texture. */
5760 glBindTexture(pCurrentTextureSurface->targetGL, 0);
5761 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5762
5763 if (currentStage < 8)
5764 {
5765 /* Necessary for the fixed pipeline. */
5766 glDisable(pCurrentTextureSurface->targetGL);
5767 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5768 }
5769
5770 pCurrentTextureSurface = NULL;
5771 }
5772
5773 if (sid == SVGA3D_INVALID_ID)
5774 {
5775 Assert(pCurrentTextureSurface == NULL);
5776 }
5777 else
5778 {
5779 PVMSVGA3DSURFACE pSurface;
5780 rc = vmsvga3dSurfaceFromSid(pState, sid, &pSurface);
5781 AssertRCReturn(rc, rc);
5782
5783 Log(("SVGA3D_TS_BIND_TEXTURE: stage %d, texture sid=%u (%d,%d) replacing sid=%u\n",
5784 currentStage, sid, pSurface->paMipmapLevels[0].mipmapSize.width,
5785 pSurface->paMipmapLevels[0].mipmapSize.height, pContext->aSidActiveTextures[currentStage]));
5786
5787 if (pSurface->oglId.texture == OPENGL_INVALID_ID)
5788 {
5789 Log(("CreateTexture (%d,%d) levels=%d\n",
5790 pSurface->paMipmapLevels[0].mipmapSize.width, pSurface->paMipmapLevels[0].mipmapSize.height, pSurface->cLevels));
5791 rc = vmsvga3dBackCreateTexture(pThisCC, pContext, cid, pSurface);
5792 AssertRCReturn(rc, rc);
5793 }
5794
5795 glBindTexture(pSurface->targetGL, pSurface->oglId.texture);
5796 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5797
5798 if (currentStage < 8)
5799 {
5800 /* Necessary for the fixed pipeline. */
5801 glEnable(pSurface->targetGL);
5802 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5803 }
5804
5805 /* Remember the currently active texture. */
5806 pCurrentTextureSurface = pSurface;
5807
5808 /* Recreate the texture state as glBindTexture resets them all (sigh). */
5809 for (uint32_t iStage = 0; iStage < RT_ELEMENTS(pContext->state.aTextureStates); iStage++)
5810 {
5811 for (uint32_t j = 0; j < RT_ELEMENTS(pContext->state.aTextureStates[0]); j++)
5812 {
5813 SVGA3dTextureState *pTextureStateIter = &pContext->state.aTextureStates[iStage][j];
5814
5815 if ( pTextureStateIter->name != SVGA3D_TS_INVALID
5816 && pTextureStateIter->name != SVGA3D_TS_BIND_TEXTURE)
5817 vmsvga3dBackSetTextureState(pThisCC, pContext->id, 1, pTextureStateIter);
5818 }
5819 }
5820 }
5821
5822 pContext->aSidActiveTextures[currentStage] = sid;
5823 }
5824
5825 /* Finished; continue with the next one. */
5826 continue;
5827 }
5828
5829 case SVGA3D_TS_ADDRESSW: /* SVGA3dTextureAddress */
5830 textureType = GL_TEXTURE_WRAP_R; /* R = W */
5831 val = vmsvga3dTextureAddress2OGL((SVGA3dTextureAddress)pTextureState[i].value);
5832 break;
5833
5834 case SVGA3D_TS_ADDRESSU: /* SVGA3dTextureAddress */
5835 textureType = GL_TEXTURE_WRAP_S; /* S = U */
5836 val = vmsvga3dTextureAddress2OGL((SVGA3dTextureAddress)pTextureState[i].value);
5837 break;
5838
5839 case SVGA3D_TS_ADDRESSV: /* SVGA3dTextureAddress */
5840 textureType = GL_TEXTURE_WRAP_T; /* T = V */
5841 val = vmsvga3dTextureAddress2OGL((SVGA3dTextureAddress)pTextureState[i].value);
5842 break;
5843
5844 case SVGA3D_TS_MIPFILTER: /* SVGA3dTextureFilter */
5845 case SVGA3D_TS_MINFILTER: /* SVGA3dTextureFilter */
5846 {
5847 uint32_t mipFilter = pContext->state.aTextureStates[currentStage][SVGA3D_TS_MIPFILTER].value;
5848 uint32_t minFilter = pContext->state.aTextureStates[currentStage][SVGA3D_TS_MINFILTER].value;
5849
5850 /* If SVGA3D_TS_MIPFILTER is set to NONE, then use SVGA3D_TS_MIPFILTER, otherwise SVGA3D_TS_MIPFILTER enables mipmap minification. */
5851 textureType = GL_TEXTURE_MIN_FILTER;
5852 if (mipFilter != SVGA3D_TEX_FILTER_NONE)
5853 {
5854 if (minFilter == SVGA3D_TEX_FILTER_NEAREST)
5855 {
5856 if (mipFilter == SVGA3D_TEX_FILTER_LINEAR)
5857 val = GL_NEAREST_MIPMAP_LINEAR;
5858 else
5859 val = GL_NEAREST_MIPMAP_NEAREST;
5860 }
5861 else
5862 {
5863 if (mipFilter == SVGA3D_TEX_FILTER_LINEAR)
5864 val = GL_LINEAR_MIPMAP_LINEAR;
5865 else
5866 val = GL_LINEAR_MIPMAP_NEAREST;
5867 }
5868 }
5869 else
5870 val = vmsvga3dTextureFilter2OGL((SVGA3dTextureFilter)minFilter);
5871 break;
5872 }
5873
5874 case SVGA3D_TS_MAGFILTER: /* SVGA3dTextureFilter */
5875 textureType = GL_TEXTURE_MAG_FILTER;
5876 val = vmsvga3dTextureFilter2OGL((SVGA3dTextureFilter)pTextureState[i].value);
5877 Assert(val == GL_NEAREST || val == GL_LINEAR);
5878 break;
5879
5880 case SVGA3D_TS_BORDERCOLOR: /* SVGA3dColor */
5881 {
5882 GLfloat color[4]; /* red, green, blue, alpha */
5883 vmsvgaColor2GLFloatArray(pTextureState[i].value, &color[0], &color[1], &color[2], &color[3]);
5884
5885 GLenum targetGL;
5886 if (pCurrentTextureSurface)
5887 targetGL = pCurrentTextureSurface->targetGL;
5888 else
5889 {
5890 /* No texture bound, assume 2D. */
5891 targetGL = GL_TEXTURE_2D;
5892 }
5893
5894 glTexParameterfv(targetGL, GL_TEXTURE_BORDER_COLOR, color); /* Identical; default 0.0 identical too */
5895 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5896 break;
5897 }
5898
5899 case SVGA3D_TS_TEXTURE_LOD_BIAS: /* float */
5900 {
5901 GLenum targetGL;
5902 if (pCurrentTextureSurface)
5903 targetGL = pCurrentTextureSurface->targetGL;
5904 else
5905 {
5906 /* No texture bound, assume 2D. */
5907 targetGL = GL_TEXTURE_2D;
5908 }
5909
5910 glTexParameterf(targetGL, GL_TEXTURE_LOD_BIAS, pTextureState[i].floatValue); /* Identical; default 0.0 identical too */
5911 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5912 break;
5913 }
5914
5915 case SVGA3D_TS_TEXTURE_MIPMAP_LEVEL: /* uint32_t */
5916 textureType = GL_TEXTURE_BASE_LEVEL;
5917 val = pTextureState[i].value;
5918 break;
5919
5920 case SVGA3D_TS_TEXTURE_ANISOTROPIC_LEVEL: /* uint32_t */
5921 if (pState->caps.fTextureFilterAnisotropicSupported)
5922 {
5923 textureType = GL_TEXTURE_MAX_ANISOTROPY_EXT;
5924 val = RT_MIN((GLint)pTextureState[i].value, pState->caps.maxTextureAnisotropy);
5925 } /* otherwise ignore. */
5926 break;
5927
5928#if 0
5929 case SVGA3D_TS_GAMMA: /* float */
5930 samplerType = D3DSAMP_SRGBTEXTURE;
5931 /* Boolean in D3D */
5932 if (pTextureState[i].floatValue == 1.0f)
5933 val = FALSE;
5934 else
5935 val = TRUE;
5936 break;
5937#endif
5938 /* Internal commands, that don't map directly to the SetTextureStageState API. */
5939 case SVGA3D_TS_TEXCOORDGEN: /* SVGA3dTextureCoordGen */
5940 AssertFailed();
5941 break;
5942
5943 default:
5944 //AssertFailed();
5945 break;
5946 }
5947
5948 if (textureType != ~(GLenum)0)
5949 {
5950 GLenum targetGL;
5951 if (pCurrentTextureSurface)
5952 targetGL = pCurrentTextureSurface->targetGL;
5953 else
5954 {
5955 /* No texture bound, assume 2D. */
5956 targetGL = GL_TEXTURE_2D;
5957 }
5958
5959 switch (pTextureState[i].name)
5960 {
5961 case SVGA3D_TS_MINFILTER:
5962 case SVGA3D_TS_MAGFILTER:
5963 {
5964 if (pState->caps.fTextureFilterAnisotropicSupported)
5965 {
5966 uint32_t const anisotropyLevel = (SVGA3dTextureFilter)pTextureState[i].value == SVGA3D_TEX_FILTER_ANISOTROPIC
5967 ? RT_MAX(1, pContext->state.aTextureStates[currentStage][SVGA3D_TS_TEXTURE_ANISOTROPIC_LEVEL].value)
5968 : 1;
5969 glTexParameteri(targetGL, GL_TEXTURE_MAX_ANISOTROPY_EXT, RT_MIN((GLint)anisotropyLevel, pState->caps.maxTextureAnisotropy));
5970 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5971 }
5972 } break;
5973
5974 default: break;
5975 }
5976
5977 glTexParameteri(targetGL, textureType, val);
5978 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
5979 }
5980 }
5981
5982 return VINF_SUCCESS;
5983}
5984
5985static DECLCALLBACK(int) vmsvga3dBackSetMaterial(PVGASTATECC pThisCC, uint32_t cid, SVGA3dFace face, SVGA3dMaterial *pMaterial)
5986{
5987 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
5988 AssertReturn(pState, VERR_NO_MEMORY);
5989
5990 LogFunc(("cid=%u face %d\n", cid, face));
5991
5992 PVMSVGA3DCONTEXT pContext;
5993 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
5994 AssertRCReturn(rc, rc);
5995
5996 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
5997
5998 GLenum oglFace;
5999 switch (face)
6000 {
6001 case SVGA3D_FACE_NONE:
6002 case SVGA3D_FACE_FRONT:
6003 oglFace = GL_FRONT;
6004 break;
6005
6006 case SVGA3D_FACE_BACK:
6007 oglFace = GL_BACK;
6008 break;
6009
6010 case SVGA3D_FACE_FRONT_BACK:
6011 oglFace = GL_FRONT_AND_BACK;
6012 break;
6013
6014 default:
6015 AssertFailedReturn(VERR_INVALID_PARAMETER);
6016 }
6017
6018 /* Save for vm state save/restore. */
6019 pContext->state.aMaterial[face].fValid = true;
6020 pContext->state.aMaterial[face].material = *pMaterial;
6021 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_MATERIAL;
6022
6023 glMaterialfv(oglFace, GL_DIFFUSE, pMaterial->diffuse);
6024 glMaterialfv(oglFace, GL_AMBIENT, pMaterial->ambient);
6025 glMaterialfv(oglFace, GL_SPECULAR, pMaterial->specular);
6026 glMaterialfv(oglFace, GL_EMISSION, pMaterial->emissive);
6027 glMaterialfv(oglFace, GL_SHININESS, &pMaterial->shininess);
6028 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6029
6030 return VINF_SUCCESS;
6031}
6032
6033/** @todo Move into separate library as we are using logic from Wine here. */
6034static DECLCALLBACK(int) vmsvga3dBackSetLightData(PVGASTATECC pThisCC, uint32_t cid, uint32_t index, SVGA3dLightData *pData)
6035{
6036 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6037 AssertReturn(pState, VERR_NO_MEMORY);
6038
6039 LogFunc(("vmsvga3dSetLightData cid=%u index=%d type=%d\n", cid, index, pData->type));
6040 ASSERT_GUEST_RETURN(index < SVGA3D_MAX_LIGHTS, VERR_INVALID_PARAMETER);
6041
6042 PVMSVGA3DCONTEXT pContext;
6043 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6044 AssertRCReturn(rc, rc);
6045
6046 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6047
6048 /* Store for vm state save/restore */
6049 pContext->state.aLightData[index].fValidData = true;
6050 pContext->state.aLightData[index].data = *pData;
6051
6052 if ( pData->attenuation0 < 0.0f
6053 || pData->attenuation1 < 0.0f
6054 || pData->attenuation2 < 0.0f)
6055 {
6056 Log(("vmsvga3dSetLightData: invalid negative attenuation values!!\n"));
6057 return VINF_SUCCESS; /* ignore; could crash the GL driver */
6058 }
6059
6060 /* Light settings are affected by the model view in OpenGL, the View transform in direct3d */
6061 glMatrixMode(GL_MODELVIEW);
6062 glPushMatrix();
6063 glLoadMatrixf(pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].matrix);
6064
6065 glLightfv(GL_LIGHT0 + index, GL_DIFFUSE, pData->diffuse);
6066 glLightfv(GL_LIGHT0 + index, GL_SPECULAR, pData->specular);
6067 glLightfv(GL_LIGHT0 + index, GL_AMBIENT, pData->ambient);
6068
6069 float QuadAttenuation;
6070 if (pData->range * pData->range >= FLT_MIN)
6071 QuadAttenuation = 1.4f / (pData->range * pData->range);
6072 else
6073 QuadAttenuation = 0.0f;
6074
6075 switch (pData->type)
6076 {
6077 case SVGA3D_LIGHTTYPE_POINT:
6078 {
6079 GLfloat position[4];
6080
6081 position[0] = pData->position[0];
6082 position[1] = pData->position[1];
6083 position[2] = pData->position[2];
6084 position[3] = 1.0f;
6085
6086 glLightfv(GL_LIGHT0 + index, GL_POSITION, position);
6087 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6088
6089 glLightf(GL_LIGHT0 + index, GL_SPOT_CUTOFF, 180.0f);
6090 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6091
6092 /* Attenuation - Are these right? guessing... */
6093 glLightf(GL_LIGHT0 + index, GL_CONSTANT_ATTENUATION, pData->attenuation0);
6094 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6095
6096 glLightf(GL_LIGHT0 + index, GL_LINEAR_ATTENUATION, pData->attenuation1);
6097 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6098
6099 glLightf(GL_LIGHT0 + index, GL_QUADRATIC_ATTENUATION, (QuadAttenuation < pData->attenuation2) ? pData->attenuation2 : QuadAttenuation);
6100 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6101
6102 /** @todo range */
6103 break;
6104 }
6105
6106 case SVGA3D_LIGHTTYPE_SPOT1:
6107 {
6108 GLfloat exponent;
6109 GLfloat position[4];
6110 const GLfloat pi = 4.0f * atanf(1.0f);
6111
6112 position[0] = pData->position[0];
6113 position[1] = pData->position[1];
6114 position[2] = pData->position[2];
6115 position[3] = 1.0f;
6116
6117 glLightfv(GL_LIGHT0 + index, GL_POSITION, position);
6118 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6119
6120 position[0] = pData->direction[0];
6121 position[1] = pData->direction[1];
6122 position[2] = pData->direction[2];
6123 position[3] = 1.0f;
6124
6125 glLightfv(GL_LIGHT0 + index, GL_SPOT_DIRECTION, position);
6126 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6127
6128 /*
6129 * opengl-ish and d3d-ish spot lights use too different models for the
6130 * light "intensity" as a function of the angle towards the main light direction,
6131 * so we only can approximate very roughly.
6132 * however spot lights are rather rarely used in games (if ever used at all).
6133 * furthermore if still used, probably nobody pays attention to such details.
6134 */
6135 if (pData->falloff == 0)
6136 {
6137 /* Falloff = 0 is easy, because d3d's and opengl's spot light equations have the
6138 * falloff resp. exponent parameter as an exponent, so the spot light lighting
6139 * will always be 1.0 for both of them, and we don't have to care for the
6140 * rest of the rather complex calculation
6141 */
6142 exponent = 0.0f;
6143 }
6144 else
6145 {
6146 float rho = pData->theta + (pData->phi - pData->theta) / (2 * pData->falloff);
6147 if (rho < 0.0001f)
6148 rho = 0.0001f;
6149 exponent = -0.3f/log(cos(rho/2));
6150 }
6151 if (exponent > 128.0f)
6152 exponent = 128.0f;
6153
6154 glLightf(GL_LIGHT0 + index, GL_SPOT_EXPONENT, exponent);
6155 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6156
6157 glLightf(GL_LIGHT0 + index, GL_SPOT_CUTOFF, pData->phi * 90.0 / pi);
6158 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6159
6160 /* Attenuation - Are these right? guessing... */
6161 glLightf(GL_LIGHT0 + index, GL_CONSTANT_ATTENUATION, pData->attenuation0);
6162 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6163
6164 glLightf(GL_LIGHT0 + index, GL_LINEAR_ATTENUATION, pData->attenuation1);
6165 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6166
6167 glLightf(GL_LIGHT0 + index, GL_QUADRATIC_ATTENUATION, (QuadAttenuation < pData->attenuation2) ? pData->attenuation2 : QuadAttenuation);
6168 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6169
6170 /** @todo range */
6171 break;
6172 }
6173
6174 case SVGA3D_LIGHTTYPE_DIRECTIONAL:
6175 {
6176 GLfloat position[4];
6177
6178 position[0] = -pData->direction[0];
6179 position[1] = -pData->direction[1];
6180 position[2] = -pData->direction[2];
6181 position[3] = 0.0f;
6182
6183 glLightfv(GL_LIGHT0 + index, GL_POSITION, position); /* Note gl uses w position of 0 for direction! */
6184 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6185
6186 glLightf(GL_LIGHT0 + index, GL_SPOT_CUTOFF, 180.0f);
6187 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6188
6189 glLightf(GL_LIGHT0 + index, GL_SPOT_EXPONENT, 0.0f);
6190 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6191 break;
6192 }
6193
6194 case SVGA3D_LIGHTTYPE_SPOT2:
6195 default:
6196 Log(("Unsupported light type!!\n"));
6197 rc = VERR_INVALID_PARAMETER;
6198 break;
6199 }
6200
6201 /* Restore the modelview matrix */
6202 glPopMatrix();
6203
6204 return rc;
6205}
6206
6207static DECLCALLBACK(int) vmsvga3dBackSetLightEnabled(PVGASTATECC pThisCC, uint32_t cid, uint32_t index, uint32_t enabled)
6208{
6209 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6210 AssertReturn(pState, VERR_NO_MEMORY);
6211
6212 LogFunc(("cid=%u %d -> %d\n", cid, index, enabled));
6213
6214 PVMSVGA3DCONTEXT pContext;
6215 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6216 AssertRCReturn(rc, rc);
6217
6218 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6219
6220 /* Store for vm state save/restore */
6221 if (index < SVGA3D_MAX_LIGHTS)
6222 pContext->state.aLightData[index].fEnabled = !!enabled;
6223 else
6224 AssertFailed();
6225
6226 if (enabled)
6227 {
6228 if (index < SVGA3D_MAX_LIGHTS)
6229 {
6230 /* Load the default settings if none have been set yet. */
6231 if (!pContext->state.aLightData[index].fValidData)
6232 vmsvga3dBackSetLightData(pThisCC, cid, index, (SVGA3dLightData *)&vmsvga3d_default_light);
6233 }
6234 glEnable(GL_LIGHT0 + index);
6235 }
6236 else
6237 glDisable(GL_LIGHT0 + index);
6238
6239 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6240 return VINF_SUCCESS;
6241}
6242
6243static DECLCALLBACK(int) vmsvga3dBackSetViewPort(PVGASTATECC pThisCC, uint32_t cid, SVGA3dRect *pRect)
6244{
6245 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6246 AssertReturn(pState, VERR_NO_MEMORY);
6247
6248 Log(("vmsvga3dSetViewPort cid=%u (%d,%d)(%d,%d)\n", cid, pRect->x, pRect->y, pRect->w, pRect->h));
6249
6250 PVMSVGA3DCONTEXT pContext;
6251 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6252 AssertRCReturn(rc, rc);
6253
6254 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6255
6256 /* Save for vm state save/restore. */
6257 pContext->state.RectViewPort = *pRect;
6258 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_VIEWPORT;
6259
6260 /** @todo y-inversion for partial viewport coordinates? */
6261 glViewport(pRect->x, pRect->y, pRect->w, pRect->h);
6262 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6263
6264 /* Reset the projection matrix as that relies on the viewport setting. */
6265 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_PROJECTION].fValid == true)
6266 vmsvga3dBackSetTransform(pThisCC, cid, SVGA3D_TRANSFORM_PROJECTION,
6267 pContext->state.aTransformState[SVGA3D_TRANSFORM_PROJECTION].matrix);
6268 else
6269 {
6270 float matrix[16];
6271
6272 /* identity matrix if no matrix set. */
6273 memset(matrix, 0, sizeof(matrix));
6274 matrix[0] = 1.0;
6275 matrix[5] = 1.0;
6276 matrix[10] = 1.0;
6277 matrix[15] = 1.0;
6278 vmsvga3dBackSetTransform(pThisCC, cid, SVGA3D_TRANSFORM_PROJECTION, matrix);
6279 }
6280
6281 return VINF_SUCCESS;
6282}
6283
6284static DECLCALLBACK(int) vmsvga3dBackSetClipPlane(PVGASTATECC pThisCC, uint32_t cid, uint32_t index, float plane[4])
6285{
6286 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6287 AssertReturn(pState, VERR_NO_MEMORY);
6288 double oglPlane[4];
6289
6290 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)));
6291 AssertReturn(index < SVGA3D_NUM_CLIPPLANES, VERR_INVALID_PARAMETER);
6292
6293 PVMSVGA3DCONTEXT pContext;
6294 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6295 AssertRCReturn(rc, rc);
6296
6297 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6298
6299 /* Store for vm state save/restore. */
6300 pContext->state.aClipPlane[index].fValid = true;
6301 memcpy(pContext->state.aClipPlane[index].plane, plane, sizeof(pContext->state.aClipPlane[index].plane));
6302
6303 /** @todo clip plane affected by model view in OpenGL & view in D3D + vertex shader -> not transformed (see Wine; state.c clipplane) */
6304 oglPlane[0] = (double)plane[0];
6305 oglPlane[1] = (double)plane[1];
6306 oglPlane[2] = (double)plane[2];
6307 oglPlane[3] = (double)plane[3];
6308
6309 glClipPlane(GL_CLIP_PLANE0 + index, oglPlane);
6310 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6311
6312 return VINF_SUCCESS;
6313}
6314
6315static DECLCALLBACK(int) vmsvga3dBackSetScissorRect(PVGASTATECC pThisCC, uint32_t cid, SVGA3dRect *pRect)
6316{
6317 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6318 AssertReturn(pState, VERR_NO_MEMORY);
6319
6320 Log(("vmsvga3dSetScissorRect cid=%u (%d,%d)(%d,%d)\n", cid, pRect->x, pRect->y, pRect->w, pRect->h));
6321
6322 PVMSVGA3DCONTEXT pContext;
6323 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6324 AssertRCReturn(rc, rc);
6325
6326 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6327
6328 /* Store for vm state save/restore. */
6329 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_SCISSORRECT;
6330 pContext->state.RectScissor = *pRect;
6331
6332 glScissor(pRect->x, pRect->y, pRect->w, pRect->h);
6333 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6334
6335 return VINF_SUCCESS;
6336}
6337
6338static void vmsvgaColor2GLFloatArray(uint32_t color, GLfloat *pRed, GLfloat *pGreen, GLfloat *pBlue, GLfloat *pAlpha)
6339{
6340 /* Convert byte color components to float (0-1.0) */
6341 *pAlpha = (GLfloat)(color >> 24) / 255.0;
6342 *pRed = (GLfloat)((color >> 16) & 0xff) / 255.0;
6343 *pGreen = (GLfloat)((color >> 8) & 0xff) / 255.0;
6344 *pBlue = (GLfloat)(color & 0xff) / 255.0;
6345}
6346
6347static DECLCALLBACK(int) vmsvga3dBackCommandClear(PVGASTATECC pThisCC, uint32_t cid, SVGA3dClearFlag clearFlag, uint32_t color, float depth, uint32_t stencil,
6348 uint32_t cRects, SVGA3dRect *pRect)
6349{
6350 GLbitfield mask = 0;
6351 GLbitfield restoreMask = 0;
6352 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6353 AssertReturn(pState, VERR_NO_MEMORY);
6354 GLboolean fDepthWriteEnabled = GL_FALSE;
6355 GLboolean afColorWriteEnabled[4] = { GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE };
6356
6357 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));
6358
6359 PVMSVGA3DCONTEXT pContext;
6360 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
6361 AssertRCReturn(rc, rc);
6362
6363 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6364
6365 if (clearFlag & SVGA3D_CLEAR_COLOR)
6366 {
6367 GLfloat red, green, blue, alpha;
6368 vmsvgaColor2GLFloatArray(color, &red, &green, &blue, &alpha);
6369
6370 /* Set the color clear value. */
6371 glClearColor(red, green, blue, alpha);
6372 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6373
6374 mask |= GL_COLOR_BUFFER_BIT;
6375
6376 /* glClear will not clear the color buffer if writing is disabled. */
6377 glGetBooleanv(GL_COLOR_WRITEMASK, afColorWriteEnabled);
6378 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6379 if ( afColorWriteEnabled[0] == GL_FALSE
6380 || afColorWriteEnabled[1] == GL_FALSE
6381 || afColorWriteEnabled[2] == GL_FALSE
6382 || afColorWriteEnabled[3] == GL_FALSE)
6383 {
6384 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
6385 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6386
6387 restoreMask |= GL_COLOR_BUFFER_BIT;
6388 }
6389
6390 }
6391
6392 if (clearFlag & SVGA3D_CLEAR_STENCIL)
6393 {
6394 /** @todo possibly the same problem as with glDepthMask */
6395 glClearStencil(stencil);
6396 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6397
6398 mask |= GL_STENCIL_BUFFER_BIT;
6399 }
6400
6401 if (clearFlag & SVGA3D_CLEAR_DEPTH)
6402 {
6403 glClearDepth((GLdouble)depth);
6404 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6405
6406 mask |= GL_DEPTH_BUFFER_BIT;
6407
6408 /* glClear will not clear the depth buffer if writing is disabled. */
6409 glGetBooleanv(GL_DEPTH_WRITEMASK, &fDepthWriteEnabled);
6410 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6411 if (fDepthWriteEnabled == GL_FALSE)
6412 {
6413 glDepthMask(GL_TRUE);
6414 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6415
6416 restoreMask |= GL_DEPTH_BUFFER_BIT;
6417 }
6418 }
6419
6420 /* Save the current scissor test bit and scissor box. */
6421 glPushAttrib(GL_SCISSOR_BIT);
6422 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6423
6424 if (cRects)
6425 {
6426 glEnable(GL_SCISSOR_TEST);
6427 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6428
6429 for (uint32_t i = 0; i < cRects; ++i)
6430 {
6431 LogFunc(("rect [%d] %d,%d %dx%d)\n", i, pRect[i].x, pRect[i].y, pRect[i].w, pRect[i].h));
6432 glScissor(pRect[i].x, pRect[i].y, pRect[i].w, pRect[i].h);
6433 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6434
6435 glClear(mask);
6436 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6437 }
6438 }
6439 else
6440 {
6441 glDisable(GL_SCISSOR_TEST);
6442 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6443
6444 glClear(mask);
6445 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6446 }
6447
6448 /* Restore the old scissor test bit and box */
6449 glPopAttrib();
6450 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6451
6452 /* Restore the write states. */
6453 if (restoreMask & GL_COLOR_BUFFER_BIT)
6454 {
6455 glColorMask(afColorWriteEnabled[0],
6456 afColorWriteEnabled[1],
6457 afColorWriteEnabled[2],
6458 afColorWriteEnabled[3]);
6459 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6460 }
6461
6462 if (restoreMask & GL_DEPTH_BUFFER_BIT)
6463 {
6464 glDepthMask(fDepthWriteEnabled);
6465 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6466 }
6467
6468 return VINF_SUCCESS;
6469}
6470
6471/* Convert VMWare vertex declaration to its OpenGL equivalent. */
6472int vmsvga3dVertexDecl2OGL(SVGA3dVertexArrayIdentity &identity, GLint &size, GLenum &type, GLboolean &normalized, uint32_t &cbAttrib)
6473{
6474 normalized = GL_FALSE;
6475 switch (identity.type)
6476 {
6477 case SVGA3D_DECLTYPE_FLOAT1:
6478 size = 1;
6479 type = GL_FLOAT;
6480 cbAttrib = sizeof(float);
6481 break;
6482 case SVGA3D_DECLTYPE_FLOAT2:
6483 size = 2;
6484 type = GL_FLOAT;
6485 cbAttrib = 2 * sizeof(float);
6486 break;
6487 case SVGA3D_DECLTYPE_FLOAT3:
6488 size = 3;
6489 type = GL_FLOAT;
6490 cbAttrib = 3 * sizeof(float);
6491 break;
6492 case SVGA3D_DECLTYPE_FLOAT4:
6493 size = 4;
6494 type = GL_FLOAT;
6495 cbAttrib = 4 * sizeof(float);
6496 break;
6497
6498 case SVGA3D_DECLTYPE_D3DCOLOR:
6499 size = GL_BGRA; /* @note requires GL_ARB_vertex_array_bgra */
6500 type = GL_UNSIGNED_BYTE;
6501 normalized = GL_TRUE; /* glVertexAttribPointer fails otherwise */
6502 cbAttrib = sizeof(uint32_t);
6503 break;
6504
6505 case SVGA3D_DECLTYPE_UBYTE4N:
6506 normalized = GL_TRUE;
6507 RT_FALL_THRU();
6508 case SVGA3D_DECLTYPE_UBYTE4:
6509 size = 4;
6510 type = GL_UNSIGNED_BYTE;
6511 cbAttrib = sizeof(uint32_t);
6512 break;
6513
6514 case SVGA3D_DECLTYPE_SHORT2N:
6515 normalized = GL_TRUE;
6516 RT_FALL_THRU();
6517 case SVGA3D_DECLTYPE_SHORT2:
6518 size = 2;
6519 type = GL_SHORT;
6520 cbAttrib = 2 * sizeof(uint16_t);
6521 break;
6522
6523 case SVGA3D_DECLTYPE_SHORT4N:
6524 normalized = GL_TRUE;
6525 RT_FALL_THRU();
6526 case SVGA3D_DECLTYPE_SHORT4:
6527 size = 4;
6528 type = GL_SHORT;
6529 cbAttrib = 4 * sizeof(uint16_t);
6530 break;
6531
6532 case SVGA3D_DECLTYPE_USHORT4N:
6533 normalized = GL_TRUE;
6534 size = 4;
6535 type = GL_UNSIGNED_SHORT;
6536 cbAttrib = 4 * sizeof(uint16_t);
6537 break;
6538
6539 case SVGA3D_DECLTYPE_USHORT2N:
6540 normalized = GL_TRUE;
6541 size = 2;
6542 type = GL_UNSIGNED_SHORT;
6543 cbAttrib = 2 * sizeof(uint16_t);
6544 break;
6545
6546 case SVGA3D_DECLTYPE_UDEC3:
6547 size = 3;
6548 type = GL_UNSIGNED_INT_2_10_10_10_REV; /** @todo correct? */
6549 cbAttrib = sizeof(uint32_t);
6550 break;
6551
6552 case SVGA3D_DECLTYPE_DEC3N:
6553 normalized = true;
6554 size = 3;
6555 type = GL_INT_2_10_10_10_REV; /** @todo correct? */
6556 cbAttrib = sizeof(uint32_t);
6557 break;
6558
6559 case SVGA3D_DECLTYPE_FLOAT16_2:
6560 size = 2;
6561 type = GL_HALF_FLOAT;
6562 cbAttrib = 2 * sizeof(uint16_t);
6563 break;
6564 case SVGA3D_DECLTYPE_FLOAT16_4:
6565 size = 4;
6566 type = GL_HALF_FLOAT;
6567 cbAttrib = 4 * sizeof(uint16_t);
6568 break;
6569 default:
6570 AssertFailedReturn(VERR_INVALID_PARAMETER);
6571 }
6572
6573 //pVertexElement->Method = identity.method;
6574 //pVertexElement->Usage = identity.usage;
6575
6576 return VINF_SUCCESS;
6577}
6578
6579static float vmsvga3dFloat16To32(uint16_t f16)
6580{
6581 /* From Wiki */
6582#ifndef INFINITY
6583 static uint32_t const sBitsINFINITY = UINT32_C(0x7f800000);
6584 #define INFINITY (*(float const *)&sBitsINFINITY)
6585#endif
6586#ifndef NAN
6587 static uint32_t const sBitsNAN = UINT32_C(0x7fc00000);
6588 #define NAN (*(float const *)&sBitsNAN)
6589#endif
6590
6591 uint16_t const s = (f16 >> UINT16_C(15)) & UINT16_C(0x1);
6592 uint16_t const e = (f16 >> UINT16_C(10)) & UINT16_C(0x1f);
6593 uint16_t const m = (f16 ) & UINT16_C(0x3ff);
6594
6595 float result = s ? 1.0f : -1.0f;
6596 if (e == 0)
6597 {
6598 if (m == 0)
6599 result *= 0.0f; /* zero, -0 */
6600 else
6601 result *= (float)m / 1024.0f / 16384.0f; /* subnormal numbers: sign * 2^-14 * 0.m */
6602 }
6603 else if (e == 0x1f)
6604 {
6605 if (m == 0)
6606 result *= INFINITY; /* +-infinity */
6607 else
6608 result = NAN; /* NAN */
6609 }
6610 else
6611 {
6612 result *= powf(2.0f, (float)e - 15.0f) * (1.0f + (float)m / 1024.0f); /* sign * 2^(e-15) * 1.m */
6613 }
6614
6615 return result;
6616}
6617
6618/* Set a vertex attribute according to VMSVGA vertex declaration. */
6619static int vmsvga3dSetVertexAttrib(PVMSVGA3DSTATE pState, GLuint index, SVGA3dVertexArrayIdentity const *pIdentity, GLvoid const *pv)
6620{
6621 switch (pIdentity->type)
6622 {
6623 case SVGA3D_DECLTYPE_FLOAT1:
6624 {
6625 /* "One-component float expanded to (float, 0, 0, 1)." */
6626 GLfloat const *p = (GLfloat *)pv;
6627 GLfloat const v[4] = { p[0], 0.0f, 0.0f, 1.0f };
6628 pState->ext.glVertexAttrib4fv(index, v);
6629 break;
6630 }
6631 case SVGA3D_DECLTYPE_FLOAT2:
6632 {
6633 /* "Two-component float expanded to (float, float, 0, 1)." */
6634 GLfloat const *p = (GLfloat *)pv;
6635 GLfloat const v[4] = { p[0], p[1], 0.0f, 1.0f };
6636 pState->ext.glVertexAttrib4fv(index, v);
6637 break;
6638 }
6639 case SVGA3D_DECLTYPE_FLOAT3:
6640 {
6641 /* "Three-component float expanded to (float, float, float, 1)." */
6642 GLfloat const *p = (GLfloat *)pv;
6643 GLfloat const v[4] = { p[0], p[1], p[2], 1.0f };
6644 pState->ext.glVertexAttrib4fv(index, v);
6645 break;
6646 }
6647 case SVGA3D_DECLTYPE_FLOAT4:
6648 pState->ext.glVertexAttrib4fv(index, (GLfloat const *)pv);
6649 break;
6650 case SVGA3D_DECLTYPE_D3DCOLOR:
6651 /** @todo Need to swap bytes? */
6652 pState->ext.glVertexAttrib4Nubv(index, (GLubyte const *)pv);
6653 break;
6654 case SVGA3D_DECLTYPE_UBYTE4:
6655 pState->ext.glVertexAttrib4ubv(index, (GLubyte const *)pv);
6656 break;
6657 case SVGA3D_DECLTYPE_SHORT2:
6658 {
6659 /* "Two-component, signed short expanded to (value, value, 0, 1)." */
6660 GLshort const *p = (GLshort const *)pv;
6661 GLshort const v[4] = { p[0], p[1], 0, 1 };
6662 pState->ext.glVertexAttrib4sv(index, v);
6663 break;
6664 }
6665 case SVGA3D_DECLTYPE_SHORT4:
6666 pState->ext.glVertexAttrib4sv(index, (GLshort const *)pv);
6667 break;
6668 case SVGA3D_DECLTYPE_UBYTE4N:
6669 pState->ext.glVertexAttrib4Nubv(index, (GLubyte const *)pv);
6670 break;
6671 case SVGA3D_DECLTYPE_SHORT2N:
6672 {
6673 /* "Normalized, two-component, signed short, expanded to (first short/32767.0, second short/32767.0, 0, 1)." */
6674 GLshort const *p = (GLshort const *)pv;
6675 GLshort const v[4] = { p[0], p[1], 0, 1 };
6676 pState->ext.glVertexAttrib4Nsv(index, v);
6677 break;
6678 }
6679 case SVGA3D_DECLTYPE_SHORT4N:
6680 pState->ext.glVertexAttrib4Nsv(index, (GLshort const *)pv);
6681 break;
6682 case SVGA3D_DECLTYPE_USHORT2N:
6683 {
6684 GLushort const *p = (GLushort const *)pv;
6685 GLushort const v[4] = { p[0], p[1], 0, 1 };
6686 pState->ext.glVertexAttrib4Nusv(index, v);
6687 break;
6688 }
6689 case SVGA3D_DECLTYPE_USHORT4N:
6690 pState->ext.glVertexAttrib4Nusv(index, (GLushort const *)pv);
6691 break;
6692 case SVGA3D_DECLTYPE_UDEC3:
6693 {
6694 /** @todo Test */
6695 /* "Three-component, unsigned, 10 10 10 format expanded to (value, value, value, 1)." */
6696 uint32_t const u32 = *(uint32_t *)pv;
6697 GLfloat const v[4] = { (float)(u32 & 0x3ff), (float)((u32 >> 10) & 0x3ff), (float)((u32 >> 20) & 0x3ff), 1.0f };
6698 pState->ext.glVertexAttrib4fv(index, v);
6699 break;
6700 }
6701 case SVGA3D_DECLTYPE_DEC3N:
6702 {
6703 /** @todo Test */
6704 /* "Three-component, signed, 10 10 10 format normalized and expanded to (v[0]/511.0, v[1]/511.0, v[2]/511.0, 1)." */
6705 uint32_t const u32 = *(uint32_t *)pv;
6706 GLfloat const v[4] = { (u32 & 0x3ff) / 511.0f, ((u32 >> 10) & 0x3ff) / 511.0f, ((u32 >> 20) & 0x3ff) / 511.0f, 1.0f };
6707 pState->ext.glVertexAttrib4fv(index, v);
6708 break;
6709 }
6710 case SVGA3D_DECLTYPE_FLOAT16_2:
6711 {
6712 /** @todo Test */
6713 /* "Two-component, 16-bit, floating point expanded to (value, value, 0, 1)." */
6714 uint16_t const *p = (uint16_t *)pv;
6715 GLfloat const v[4] = { vmsvga3dFloat16To32(p[0]), vmsvga3dFloat16To32(p[1]), 0.0f, 1.0f };
6716 pState->ext.glVertexAttrib4fv(index, v);
6717 break;
6718 }
6719 case SVGA3D_DECLTYPE_FLOAT16_4:
6720 {
6721 /** @todo Test */
6722 uint16_t const *p = (uint16_t *)pv;
6723 GLfloat const v[4] = { vmsvga3dFloat16To32(p[0]), vmsvga3dFloat16To32(p[1]),
6724 vmsvga3dFloat16To32(p[2]), vmsvga3dFloat16To32(p[3]) };
6725 pState->ext.glVertexAttrib4fv(index, v);
6726 break;
6727 }
6728 default:
6729 AssertFailedReturn(VERR_INVALID_PARAMETER);
6730 }
6731
6732 return VINF_SUCCESS;
6733}
6734
6735/* Convert VMWare primitive type to its OpenGL equivalent. */
6736/* Calculate the vertex count based on the primitive type and nr of primitives. */
6737int vmsvga3dPrimitiveType2OGL(SVGA3dPrimitiveType PrimitiveType, GLenum *pMode, uint32_t cPrimitiveCount, uint32_t *pcVertices)
6738{
6739 switch (PrimitiveType)
6740 {
6741 case SVGA3D_PRIMITIVE_TRIANGLELIST:
6742 *pMode = GL_TRIANGLES;
6743 *pcVertices = cPrimitiveCount * 3;
6744 break;
6745 case SVGA3D_PRIMITIVE_POINTLIST:
6746 *pMode = GL_POINTS;
6747 *pcVertices = cPrimitiveCount;
6748 break;
6749 case SVGA3D_PRIMITIVE_LINELIST:
6750 *pMode = GL_LINES;
6751 *pcVertices = cPrimitiveCount * 2;
6752 break;
6753 case SVGA3D_PRIMITIVE_LINESTRIP:
6754 *pMode = GL_LINE_STRIP;
6755 *pcVertices = cPrimitiveCount + 1;
6756 break;
6757 case SVGA3D_PRIMITIVE_TRIANGLESTRIP:
6758 *pMode = GL_TRIANGLE_STRIP;
6759 *pcVertices = cPrimitiveCount + 2;
6760 break;
6761 case SVGA3D_PRIMITIVE_TRIANGLEFAN:
6762 *pMode = GL_TRIANGLE_FAN;
6763 *pcVertices = cPrimitiveCount + 2;
6764 break;
6765 default:
6766 return VERR_INVALID_PARAMETER;
6767 }
6768 return VINF_SUCCESS;
6769}
6770
6771static int vmsvga3dResetTransformMatrices(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext)
6772{
6773 int rc;
6774
6775 /* Reset the view matrix (also takes the world matrix into account). */
6776 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].fValid == true)
6777 rc = vmsvga3dBackSetTransform(pThisCC, pContext->id, SVGA3D_TRANSFORM_VIEW,
6778 pContext->state.aTransformState[SVGA3D_TRANSFORM_VIEW].matrix);
6779 else
6780 {
6781 float matrix[16];
6782
6783 /* identity matrix if no matrix set. */
6784 memset(matrix, 0, sizeof(matrix));
6785 matrix[0] = 1.0;
6786 matrix[5] = 1.0;
6787 matrix[10] = 1.0;
6788 matrix[15] = 1.0;
6789 rc = vmsvga3dBackSetTransform(pThisCC, pContext->id, SVGA3D_TRANSFORM_VIEW, matrix);
6790 }
6791
6792 /* Reset the projection matrix. */
6793 if (pContext->state.aTransformState[SVGA3D_TRANSFORM_PROJECTION].fValid == true)
6794 {
6795 rc = vmsvga3dBackSetTransform(pThisCC, pContext->id, SVGA3D_TRANSFORM_PROJECTION, pContext->state.aTransformState[SVGA3D_TRANSFORM_PROJECTION].matrix);
6796 }
6797 else
6798 {
6799 float matrix[16];
6800
6801 /* identity matrix if no matrix set. */
6802 memset(matrix, 0, sizeof(matrix));
6803 matrix[0] = 1.0;
6804 matrix[5] = 1.0;
6805 matrix[10] = 1.0;
6806 matrix[15] = 1.0;
6807 rc = vmsvga3dBackSetTransform(pThisCC, pContext->id, SVGA3D_TRANSFORM_PROJECTION, matrix);
6808 }
6809 AssertRC(rc);
6810 return rc;
6811}
6812
6813static int vmsvga3dDrawPrimitivesProcessVertexDecls(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext,
6814 uint32_t iVertexDeclBase, uint32_t numVertexDecls,
6815 SVGA3dVertexDecl *pVertexDecl,
6816 SVGA3dVertexDivisor const *paVertexDivisors)
6817{
6818 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
6819 unsigned const sidVertex = pVertexDecl[0].array.surfaceId;
6820
6821 PVMSVGA3DSURFACE pVertexSurface;
6822 int rc = vmsvga3dSurfaceFromSid(pState, sidVertex, &pVertexSurface);
6823 AssertRCReturn(rc, rc);
6824
6825 Log(("vmsvga3dDrawPrimitives: vertex surface sid=%u\n", sidVertex));
6826
6827 /* Create and/or bind the vertex buffer. */
6828 if (pVertexSurface->oglId.buffer == OPENGL_INVALID_ID)
6829 {
6830 Log(("vmsvga3dDrawPrimitives: create vertex buffer fDirty=%d size=%x bytes\n", pVertexSurface->fDirty, pVertexSurface->paMipmapLevels[0].cbSurface));
6831 PVMSVGA3DCONTEXT pSavedCtx = pContext;
6832 pContext = &pState->SharedCtx;
6833 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6834
6835 pState->ext.glGenBuffers(1, &pVertexSurface->oglId.buffer);
6836 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6837 pVertexSurface->enmOGLResType = VMSVGA3D_OGLRESTYPE_BUFFER;
6838
6839 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, pVertexSurface->oglId.buffer);
6840 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6841
6842 Assert(pVertexSurface->fDirty);
6843 /** @todo rethink usage dynamic/static */
6844 pState->ext.glBufferData(GL_ARRAY_BUFFER, pVertexSurface->paMipmapLevels[0].cbSurface, pVertexSurface->paMipmapLevels[0].pSurfaceData, GL_DYNAMIC_DRAW);
6845 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6846
6847 pVertexSurface->paMipmapLevels[0].fDirty = false;
6848 pVertexSurface->fDirty = false;
6849
6850 pVertexSurface->f.s.surface1Flags |= SVGA3D_SURFACE_HINT_VERTEXBUFFER;
6851
6852 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, OPENGL_INVALID_ID);
6853 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6854
6855 pContext = pSavedCtx;
6856 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
6857 }
6858
6859 Assert(pVertexSurface->fDirty == false);
6860 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, pVertexSurface->oglId.buffer);
6861 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6862
6863 /* Setup the vertex declarations. */
6864 for (unsigned iVertex = 0; iVertex < numVertexDecls; iVertex++)
6865 {
6866 GLint size;
6867 GLenum type;
6868 GLboolean normalized;
6869 uint32_t cbAttrib;
6870 GLuint index = iVertexDeclBase + iVertex;
6871
6872 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));
6873
6874 rc = vmsvga3dVertexDecl2OGL(pVertexDecl[iVertex].identity, size, type, normalized, cbAttrib);
6875 AssertRCReturn(rc, rc);
6876
6877 ASSERT_GUEST_RETURN( pVertexSurface->paMipmapLevels[0].cbSurface >= pVertexDecl[iVertex].array.offset
6878 && pVertexSurface->paMipmapLevels[0].cbSurface - pVertexDecl[iVertex].array.offset >= cbAttrib,
6879 VERR_INVALID_PARAMETER);
6880 RT_UNTRUSTED_VALIDATED_FENCE();
6881
6882 if (pContext->state.shidVertex != SVGA_ID_INVALID)
6883 {
6884 /* Use numbered vertex arrays (or attributes) when shaders are active. */
6885 if (pVertexDecl[iVertex].array.stride)
6886 {
6887 pState->ext.glEnableVertexAttribArray(index);
6888 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6889 pState->ext.glVertexAttribPointer(index, size, type, normalized, pVertexDecl[iVertex].array.stride,
6890 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6891 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6892
6893 GLuint divisor = paVertexDivisors && paVertexDivisors[index].instanceData ? 1 : 0;
6894 pState->ext.glVertexAttribDivisor(index, divisor);
6895 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6896
6897 /** @todo case SVGA3D_DECLUSAGE_COLOR: color component order not identical!! test GL_BGRA!! */
6898 }
6899 else
6900 {
6901 /*
6902 * D3D and OpenGL have a different meaning of value zero for the vertex array stride:
6903 * - D3D (VMSVGA): "use a zero stride to tell the runtime not to increment the vertex buffer offset."
6904 * - OpenGL: "If stride is 0, the generic vertex attributes are understood to be tightly packed in the array."
6905 * VMSVGA uses the D3D semantics.
6906 *
6907 * Use glVertexAttrib in order to tell OpenGL to reuse the zero stride attributes for each vertex.
6908 */
6909 pState->ext.glDisableVertexAttribArray(index);
6910 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6911
6912 const GLvoid *v = (uint8_t *)pVertexSurface->paMipmapLevels[0].pSurfaceData + pVertexDecl[iVertex].array.offset;
6913 vmsvga3dSetVertexAttrib(pState, index, &pVertexDecl[iVertex].identity, v);
6914 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
6915 }
6916 }
6917 else
6918 {
6919 if (pVertexDecl[iVertex].array.stride == 0)
6920 {
6921 /* Zero stride means that the attribute pointer must not be increased.
6922 * See comment about stride in vmsvga3dDrawPrimitives.
6923 */
6924 LogRelMax(8, ("VMSVGA: Warning: zero stride array in fixed function pipeline\n"));
6925 AssertFailed();
6926 }
6927
6928 /* Use the predefined selection of vertex streams for the fixed pipeline. */
6929 switch (pVertexDecl[iVertex].identity.usage)
6930 {
6931 case SVGA3D_DECLUSAGE_POSITIONT:
6932 case SVGA3D_DECLUSAGE_POSITION:
6933 {
6934 glEnableClientState(GL_VERTEX_ARRAY);
6935 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6936 glVertexPointer(size, type, pVertexDecl[iVertex].array.stride,
6937 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6938 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6939 break;
6940 }
6941 case SVGA3D_DECLUSAGE_BLENDWEIGHT:
6942 AssertFailed();
6943 break;
6944 case SVGA3D_DECLUSAGE_BLENDINDICES:
6945 AssertFailed();
6946 break;
6947 case SVGA3D_DECLUSAGE_NORMAL:
6948 glEnableClientState(GL_NORMAL_ARRAY);
6949 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6950 glNormalPointer(type, pVertexDecl[iVertex].array.stride,
6951 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6952 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6953 break;
6954 case SVGA3D_DECLUSAGE_PSIZE:
6955 AssertFailed();
6956 break;
6957 case SVGA3D_DECLUSAGE_TEXCOORD:
6958 /* Specify the affected texture unit. */
6959#if VBOX_VMSVGA3D_GL_HACK_LEVEL >= 0x103
6960 glClientActiveTexture(GL_TEXTURE0 + pVertexDecl[iVertex].identity.usageIndex);
6961#else
6962 pState->ext.glClientActiveTexture(GL_TEXTURE0 + pVertexDecl[iVertex].identity.usageIndex);
6963#endif
6964 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
6965 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6966 glTexCoordPointer(size, type, pVertexDecl[iVertex].array.stride,
6967 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6968 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6969 break;
6970 case SVGA3D_DECLUSAGE_TANGENT:
6971 AssertFailed();
6972 break;
6973 case SVGA3D_DECLUSAGE_BINORMAL:
6974 AssertFailed();
6975 break;
6976 case SVGA3D_DECLUSAGE_TESSFACTOR:
6977 AssertFailed();
6978 break;
6979 case SVGA3D_DECLUSAGE_COLOR: /** @todo color component order not identical!! test GL_BGRA!! */
6980 glEnableClientState(GL_COLOR_ARRAY);
6981 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6982 glColorPointer(size, type, pVertexDecl[iVertex].array.stride,
6983 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6984 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6985 break;
6986 case SVGA3D_DECLUSAGE_FOG:
6987 glEnableClientState(GL_FOG_COORD_ARRAY);
6988 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6989 pState->ext.glFogCoordPointer(type, pVertexDecl[iVertex].array.stride,
6990 (const GLvoid *)(uintptr_t)pVertexDecl[iVertex].array.offset);
6991 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
6992 break;
6993 case SVGA3D_DECLUSAGE_DEPTH:
6994 AssertFailed();
6995 break;
6996 case SVGA3D_DECLUSAGE_SAMPLE:
6997 AssertFailed();
6998 break;
6999 case SVGA3D_DECLUSAGE_MAX: AssertFailed(); break; /* shut up gcc */
7000 }
7001 }
7002
7003#ifdef LOG_ENABLED
7004 if (pVertexDecl[iVertex].array.stride == 0)
7005 Log(("vmsvga3dDrawPrimitives: stride == 0! Can be valid\n"));
7006#endif
7007 }
7008
7009 return VINF_SUCCESS;
7010}
7011
7012static int vmsvga3dDrawPrimitivesCleanupVertexDecls(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t iVertexDeclBase,
7013 uint32_t numVertexDecls, SVGA3dVertexDecl *pVertexDecl)
7014{
7015 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7016
7017 /* Clean up the vertex declarations. */
7018 for (unsigned iVertex = 0; iVertex < numVertexDecls; iVertex++)
7019 {
7020 if (pVertexDecl[iVertex].identity.usage == SVGA3D_DECLUSAGE_POSITIONT)
7021 {
7022 /* Reset the transformation matrices in case of a switch back from pretransformed mode. */
7023 Log(("vmsvga3dDrawPrimitivesCleanupVertexDecls: reset world and projection matrices after transformation reset (pre-transformed -> transformed)\n"));
7024 vmsvga3dResetTransformMatrices(pThisCC, pContext);
7025 }
7026
7027 if (pContext->state.shidVertex != SVGA_ID_INVALID)
7028 {
7029 /* Use numbered vertex arrays when shaders are active. */
7030 pState->ext.glVertexAttribDivisor(iVertexDeclBase + iVertex, 0);
7031 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7032 pState->ext.glDisableVertexAttribArray(iVertexDeclBase + iVertex);
7033 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7034 }
7035 else
7036 {
7037 /* Use the predefined selection of vertex streams for the fixed pipeline. */
7038 switch (pVertexDecl[iVertex].identity.usage)
7039 {
7040 case SVGA3D_DECLUSAGE_POSITION:
7041 case SVGA3D_DECLUSAGE_POSITIONT:
7042 glDisableClientState(GL_VERTEX_ARRAY);
7043 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7044 break;
7045 case SVGA3D_DECLUSAGE_BLENDWEIGHT:
7046 break;
7047 case SVGA3D_DECLUSAGE_BLENDINDICES:
7048 break;
7049 case SVGA3D_DECLUSAGE_NORMAL:
7050 glDisableClientState(GL_NORMAL_ARRAY);
7051 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7052 break;
7053 case SVGA3D_DECLUSAGE_PSIZE:
7054 break;
7055 case SVGA3D_DECLUSAGE_TEXCOORD:
7056 /* Specify the affected texture unit. */
7057#if VBOX_VMSVGA3D_GL_HACK_LEVEL >= 0x103
7058 glClientActiveTexture(GL_TEXTURE0 + pVertexDecl[iVertex].identity.usageIndex);
7059#else
7060 pState->ext.glClientActiveTexture(GL_TEXTURE0 + pVertexDecl[iVertex].identity.usageIndex);
7061#endif
7062 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
7063 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7064 break;
7065 case SVGA3D_DECLUSAGE_TANGENT:
7066 break;
7067 case SVGA3D_DECLUSAGE_BINORMAL:
7068 break;
7069 case SVGA3D_DECLUSAGE_TESSFACTOR:
7070 break;
7071 case SVGA3D_DECLUSAGE_COLOR: /** @todo color component order not identical!! */
7072 glDisableClientState(GL_COLOR_ARRAY);
7073 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7074 break;
7075 case SVGA3D_DECLUSAGE_FOG:
7076 glDisableClientState(GL_FOG_COORD_ARRAY);
7077 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7078 break;
7079 case SVGA3D_DECLUSAGE_DEPTH:
7080 break;
7081 case SVGA3D_DECLUSAGE_SAMPLE:
7082 break;
7083 case SVGA3D_DECLUSAGE_MAX: AssertFailed(); break; /* shut up gcc */
7084 }
7085 }
7086 }
7087 /* Unbind the vertex buffer after usage. */
7088 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, 0);
7089 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7090 return VINF_SUCCESS;
7091}
7092
7093static DECLCALLBACK(int) vmsvga3dBackDrawPrimitives(PVGASTATECC pThisCC, uint32_t cid, uint32_t numVertexDecls, SVGA3dVertexDecl *pVertexDecl,
7094 uint32_t numRanges, SVGA3dPrimitiveRange *pRange, uint32_t cVertexDivisor,
7095 SVGA3dVertexDivisor *pVertexDivisor)
7096{
7097 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7098 AssertReturn(pState, VERR_INTERNAL_ERROR);
7099 uint32_t iCurrentVertex;
7100
7101 Log(("vmsvga3dDrawPrimitives cid=%u numVertexDecls=%d numRanges=%d, cVertexDivisor=%d\n", cid, numVertexDecls, numRanges, cVertexDivisor));
7102
7103 /* Caller already check these, but it cannot hurt to check again... */
7104 AssertReturn(numVertexDecls && numVertexDecls <= SVGA3D_MAX_VERTEX_ARRAYS, VERR_INVALID_PARAMETER);
7105 AssertReturn(numRanges && numRanges <= SVGA3D_MAX_DRAW_PRIMITIVE_RANGES, VERR_INVALID_PARAMETER);
7106 AssertReturn(!cVertexDivisor || cVertexDivisor == numVertexDecls, VERR_INVALID_PARAMETER);
7107
7108 if (!cVertexDivisor)
7109 pVertexDivisor = NULL; /* Be sure. */
7110
7111 PVMSVGA3DCONTEXT pContext;
7112 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
7113 AssertRCReturn(rc, rc);
7114
7115 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7116
7117 /* Check for pretransformed vertex declarations. */
7118 for (unsigned iVertex = 0; iVertex < numVertexDecls; iVertex++)
7119 {
7120 switch (pVertexDecl[iVertex].identity.usage)
7121 {
7122 case SVGA3D_DECLUSAGE_POSITIONT:
7123 Log(("ShaderSetPositionTransformed: (%d,%d)\n", pContext->state.RectViewPort.w, pContext->state.RectViewPort.h));
7124 RT_FALL_THRU();
7125 case SVGA3D_DECLUSAGE_POSITION:
7126 ShaderSetPositionTransformed(pContext->pShaderContext, pContext->state.RectViewPort.w,
7127 pContext->state.RectViewPort.h,
7128 pVertexDecl[iVertex].identity.usage == SVGA3D_DECLUSAGE_POSITIONT);
7129 break;
7130 default: /* Shut up MSC. */ break;
7131 }
7132 }
7133
7134 /* Flush any shader changes; after (!) checking the vertex declarations to deal with pre-transformed vertices. */
7135 if (pContext->pShaderContext)
7136 {
7137 uint32_t rtHeight = 0;
7138
7139 if (pContext->state.aRenderTargets[SVGA3D_RT_COLOR0] != SVGA_ID_INVALID)
7140 {
7141 PVMSVGA3DSURFACE pRenderTarget;
7142 rc = vmsvga3dSurfaceFromSid(pState, pContext->state.aRenderTargets[SVGA3D_RT_COLOR0], &pRenderTarget);
7143 AssertRCReturn(rc, rc);
7144
7145 rtHeight = pRenderTarget->paMipmapLevels[0].mipmapSize.height;
7146 }
7147
7148 ShaderUpdateState(pContext->pShaderContext, rtHeight);
7149 }
7150
7151 /* Try to figure out if instancing is used.
7152 * Support simple instancing case with one set of indexed data and one set per-instance data.
7153 */
7154 uint32_t cInstances = 0;
7155 for (uint32_t iVertexDivisor = 0; iVertexDivisor < cVertexDivisor; ++iVertexDivisor)
7156 {
7157 if (pVertexDivisor[iVertexDivisor].indexedData)
7158 {
7159 if (cInstances == 0)
7160 cInstances = pVertexDivisor[iVertexDivisor].count;
7161 else
7162 Assert(cInstances == pVertexDivisor[iVertexDivisor].count);
7163 }
7164 else if (pVertexDivisor[iVertexDivisor].instanceData)
7165 {
7166 Assert(pVertexDivisor[iVertexDivisor].count == 1);
7167 }
7168 }
7169
7170 /* Process all vertex declarations. Each vertex buffer is represented by one stream. */
7171 iCurrentVertex = 0;
7172 while (iCurrentVertex < numVertexDecls)
7173 {
7174 uint32_t sidVertex = SVGA_ID_INVALID;
7175 uint32_t iVertex;
7176
7177 for (iVertex = iCurrentVertex; iVertex < numVertexDecls; iVertex++)
7178 {
7179 if ( sidVertex != SVGA_ID_INVALID
7180 && pVertexDecl[iVertex].array.surfaceId != sidVertex
7181 )
7182 break;
7183 sidVertex = pVertexDecl[iVertex].array.surfaceId;
7184 }
7185
7186 rc = vmsvga3dDrawPrimitivesProcessVertexDecls(pThisCC, pContext, iCurrentVertex, iVertex - iCurrentVertex,
7187 &pVertexDecl[iCurrentVertex], pVertexDivisor);
7188 AssertRCReturn(rc, rc);
7189
7190 iCurrentVertex = iVertex;
7191 }
7192
7193 /* Now draw the primitives. */
7194 for (unsigned iPrimitive = 0; iPrimitive < numRanges; iPrimitive++)
7195 {
7196 GLenum modeDraw;
7197 unsigned const sidIndex = pRange[iPrimitive].indexArray.surfaceId;
7198 PVMSVGA3DSURFACE pIndexSurface = NULL;
7199 unsigned cVertices;
7200
7201 Log(("Primitive %d: type %s\n", iPrimitive, vmsvga3dPrimitiveType2String(pRange[iPrimitive].primType)));
7202 rc = vmsvga3dPrimitiveType2OGL(pRange[iPrimitive].primType, &modeDraw, pRange[iPrimitive].primitiveCount, &cVertices);
7203 if (RT_FAILURE(rc))
7204 {
7205 AssertRC(rc);
7206 goto internal_error;
7207 }
7208
7209 if (sidIndex != SVGA3D_INVALID_ID)
7210 {
7211 AssertMsg(pRange[iPrimitive].indexWidth == sizeof(uint32_t) || pRange[iPrimitive].indexWidth == sizeof(uint16_t), ("Unsupported primitive width %d\n", pRange[iPrimitive].indexWidth));
7212
7213 rc = vmsvga3dSurfaceFromSid(pState, sidIndex, &pIndexSurface);
7214 if (RT_FAILURE(rc))
7215 {
7216 AssertRC(rc);
7217 goto internal_error;
7218 }
7219
7220 Log(("vmsvga3dDrawPrimitives: index surface sid=%u\n", sidIndex));
7221
7222 if (pIndexSurface->oglId.buffer == OPENGL_INVALID_ID)
7223 {
7224 Log(("vmsvga3dDrawPrimitives: create index buffer fDirty=%d size=%x bytes\n", pIndexSurface->fDirty, pIndexSurface->paMipmapLevels[0].cbSurface));
7225 pContext = &pState->SharedCtx;
7226 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7227
7228 pState->ext.glGenBuffers(1, &pIndexSurface->oglId.buffer);
7229 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7230 pIndexSurface->enmOGLResType = VMSVGA3D_OGLRESTYPE_BUFFER;
7231
7232 pState->ext.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pIndexSurface->oglId.buffer);
7233 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7234
7235 Assert(pIndexSurface->fDirty);
7236
7237 /** @todo rethink usage dynamic/static */
7238 pState->ext.glBufferData(GL_ELEMENT_ARRAY_BUFFER, pIndexSurface->paMipmapLevels[0].cbSurface, pIndexSurface->paMipmapLevels[0].pSurfaceData, GL_DYNAMIC_DRAW);
7239 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7240
7241 pIndexSurface->paMipmapLevels[0].fDirty = false;
7242 pIndexSurface->fDirty = false;
7243
7244 pIndexSurface->f.s.surface1Flags |= SVGA3D_SURFACE_HINT_INDEXBUFFER;
7245
7246 pState->ext.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, OPENGL_INVALID_ID);
7247 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7248
7249 pContext = pState->papContexts[cid];
7250 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7251 }
7252 Assert(pIndexSurface->fDirty == false);
7253
7254 pState->ext.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pIndexSurface->oglId.buffer);
7255 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7256 }
7257
7258 if (!pIndexSurface)
7259 {
7260 /* Render without an index buffer */
7261 Log(("DrawPrimitive %d cPrimitives=%d cVertices=%d index index bias=%d cInstances=%d\n", modeDraw, pRange[iPrimitive].primitiveCount, cVertices, pRange[iPrimitive].indexBias, cInstances));
7262 if (cInstances == 0)
7263 {
7264 glDrawArrays(modeDraw, pRange[iPrimitive].indexBias, cVertices);
7265 }
7266 else
7267 {
7268 pState->ext.glDrawArraysInstanced(modeDraw, pRange[iPrimitive].indexBias, cVertices, cInstances);
7269 }
7270 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7271 }
7272 else
7273 {
7274 Assert(pRange[iPrimitive].indexWidth == pRange[iPrimitive].indexArray.stride);
7275
7276 GLenum indexType;
7277 switch (pRange[iPrimitive].indexWidth)
7278 {
7279 case 1: indexType = GL_UNSIGNED_BYTE; break;
7280 case 2: indexType = GL_UNSIGNED_SHORT; break;
7281 default: AssertMsgFailed(("indexWidth %d\n", pRange[iPrimitive].indexWidth));
7282 RT_FALL_THROUGH();
7283 case 4: indexType = GL_UNSIGNED_INT; break;
7284 }
7285
7286 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));
7287 if (cInstances == 0)
7288 {
7289 /* Render with an index buffer */
7290 if (pRange[iPrimitive].indexBias == 0)
7291 glDrawElements(modeDraw,
7292 cVertices,
7293 indexType,
7294 (GLvoid *)(uintptr_t)pRange[iPrimitive].indexArray.offset); /* byte offset in indices buffer */
7295 else
7296 pState->ext.glDrawElementsBaseVertex(modeDraw,
7297 cVertices,
7298 indexType,
7299 (GLvoid *)(uintptr_t)pRange[iPrimitive].indexArray.offset, /* byte offset in indices buffer */
7300 pRange[iPrimitive].indexBias); /* basevertex */
7301 }
7302 else
7303 {
7304 /* Render with an index buffer */
7305 if (pRange[iPrimitive].indexBias == 0)
7306 pState->ext.glDrawElementsInstanced(modeDraw,
7307 cVertices,
7308 indexType,
7309 (GLvoid *)(uintptr_t)pRange[iPrimitive].indexArray.offset, /* byte offset in indices buffer */
7310 cInstances);
7311 else
7312 pState->ext.glDrawElementsInstancedBaseVertex(modeDraw,
7313 cVertices,
7314 indexType,
7315 (GLvoid *)(uintptr_t)pRange[iPrimitive].indexArray.offset, /* byte offset in indices buffer */
7316 cInstances,
7317 pRange[iPrimitive].indexBias); /* basevertex */
7318 }
7319 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7320
7321 /* Unbind the index buffer after usage. */
7322 pState->ext.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
7323 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7324 }
7325 }
7326
7327internal_error:
7328
7329 /* Deactivate the vertex declarations. */
7330 iCurrentVertex = 0;
7331 while (iCurrentVertex < numVertexDecls)
7332 {
7333 uint32_t sidVertex = SVGA_ID_INVALID;
7334 uint32_t iVertex;
7335
7336 for (iVertex = iCurrentVertex; iVertex < numVertexDecls; iVertex++)
7337 {
7338 if ( sidVertex != SVGA_ID_INVALID
7339 && pVertexDecl[iVertex].array.surfaceId != sidVertex
7340 )
7341 break;
7342 sidVertex = pVertexDecl[iVertex].array.surfaceId;
7343 }
7344
7345 rc = vmsvga3dDrawPrimitivesCleanupVertexDecls(pThisCC, pContext, iCurrentVertex,
7346 iVertex - iCurrentVertex, &pVertexDecl[iCurrentVertex]);
7347 AssertRCReturn(rc, rc);
7348
7349 iCurrentVertex = iVertex;
7350 }
7351
7352#ifdef DEBUG
7353 /* Check whether 'activeTexture' on texture unit 'i' matches what we expect. */
7354 for (uint32_t i = 0; i < RT_ELEMENTS(pContext->aSidActiveTextures); ++i)
7355 {
7356 if (pContext->aSidActiveTextures[i] != SVGA3D_INVALID_ID)
7357 {
7358 PVMSVGA3DSURFACE pTexture;
7359 int rc2 = vmsvga3dSurfaceFromSid(pState, pContext->aSidActiveTextures[i], &pTexture);
7360 AssertContinue(RT_SUCCESS(rc2));
7361
7362 GLint activeTextureUnit = 0;
7363 glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTextureUnit);
7364 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7365
7366 pState->ext.glActiveTexture(GL_TEXTURE0 + i);
7367 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7368
7369 GLint activeTexture = 0;
7370 glGetIntegerv(pTexture->bindingGL, &activeTexture);
7371 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7372
7373 pState->ext.glActiveTexture(activeTextureUnit);
7374 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7375
7376 AssertMsg(pTexture->oglId.texture == (GLuint)activeTexture,
7377 ("%d vs %d unit %d (active unit %d) sid=%u\n", pTexture->oglId.texture, activeTexture, i,
7378 activeTextureUnit - GL_TEXTURE0, pContext->aSidActiveTextures[i]));
7379 }
7380 }
7381#endif
7382
7383#if 0
7384 /* Dump render target to a bitmap. */
7385 if (pContext->state.aRenderTargets[SVGA3D_RT_COLOR0] != SVGA3D_INVALID_ID)
7386 {
7387 vmsvga3dUpdateHeapBuffersForSurfaces(pThisCC, pContext->state.aRenderTargets[SVGA3D_RT_COLOR0]);
7388 PVMSVGA3DSURFACE pSurface;
7389 int rc2 = vmsvga3dSurfaceFromSid(pState, pContext->state.aRenderTargets[SVGA3D_RT_COLOR0], &pSurface);
7390 if (RT_SUCCESS(rc2))
7391 vmsvga3dInfoSurfaceToBitmap(NULL, pSurface, "bmpgl", "rt", "-post");
7392# if 0
7393 /* Stage 0 texture. */
7394 if (pContext->aSidActiveTextures[0] != SVGA3D_INVALID_ID)
7395 {
7396 vmsvga3dUpdateHeapBuffersForSurfaces(pThisCC, pContext->aSidActiveTextures[0]);
7397 rc2 = vmsvga3dSurfaceFromSid(pState, pContext->aSidActiveTextures[0], &pSurface);
7398 if (RT_SUCCESS(rc2))
7399 vmsvga3dInfoSurfaceToBitmap(NULL, pSurface, "bmpgl", "rt", "-post-tx");
7400 }
7401# endif
7402 }
7403#endif
7404
7405 return rc;
7406}
7407
7408
7409static DECLCALLBACK(int) vmsvga3dBackShaderDefine(PVGASTATECC pThisCC, uint32_t cid, uint32_t shid, SVGA3dShaderType type, uint32_t cbData, uint32_t *pShaderData)
7410{
7411 PVMSVGA3DSHADER pShader;
7412 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7413 AssertReturn(pState, VERR_NO_MEMORY);
7414
7415 Log(("vmsvga3dShaderDefine cid=%u shid=%d type=%s cbData=0x%x\n", cid, shid, (type == SVGA3D_SHADERTYPE_VS) ? "VERTEX" : "PIXEL", cbData));
7416
7417 PVMSVGA3DCONTEXT pContext;
7418 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
7419 AssertRCReturn(rc, rc);
7420
7421 AssertReturn(shid < SVGA3D_MAX_SHADER_IDS, VERR_INVALID_PARAMETER);
7422
7423 rc = vmsvga3dShaderParse(type, cbData, pShaderData);
7424 if (RT_FAILURE(rc))
7425 {
7426 AssertRC(rc);
7427 vmsvga3dShaderLogRel("Failed to parse", type, cbData, pShaderData);
7428 return rc;
7429 }
7430
7431 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7432
7433 if (type == SVGA3D_SHADERTYPE_VS)
7434 {
7435 if (shid >= pContext->cVertexShaders)
7436 {
7437 void *pvNew = RTMemRealloc(pContext->paVertexShader, sizeof(VMSVGA3DSHADER) * (shid + 1));
7438 AssertReturn(pvNew, VERR_NO_MEMORY);
7439 pContext->paVertexShader = (PVMSVGA3DSHADER)pvNew;
7440 memset(&pContext->paVertexShader[pContext->cVertexShaders], 0, sizeof(VMSVGA3DSHADER) * (shid + 1 - pContext->cVertexShaders));
7441 for (uint32_t i = pContext->cVertexShaders; i < shid + 1; i++)
7442 pContext->paVertexShader[i].id = SVGA3D_INVALID_ID;
7443 pContext->cVertexShaders = shid + 1;
7444 }
7445 /* If one already exists with this id, then destroy it now. */
7446 if (pContext->paVertexShader[shid].id != SVGA3D_INVALID_ID)
7447 vmsvga3dBackShaderDestroy(pThisCC, cid, shid, pContext->paVertexShader[shid].type);
7448
7449 pShader = &pContext->paVertexShader[shid];
7450 }
7451 else
7452 {
7453 Assert(type == SVGA3D_SHADERTYPE_PS);
7454 if (shid >= pContext->cPixelShaders)
7455 {
7456 void *pvNew = RTMemRealloc(pContext->paPixelShader, sizeof(VMSVGA3DSHADER) * (shid + 1));
7457 AssertReturn(pvNew, VERR_NO_MEMORY);
7458 pContext->paPixelShader = (PVMSVGA3DSHADER)pvNew;
7459 memset(&pContext->paPixelShader[pContext->cPixelShaders], 0, sizeof(VMSVGA3DSHADER) * (shid + 1 - pContext->cPixelShaders));
7460 for (uint32_t i = pContext->cPixelShaders; i < shid + 1; i++)
7461 pContext->paPixelShader[i].id = SVGA3D_INVALID_ID;
7462 pContext->cPixelShaders = shid + 1;
7463 }
7464 /* If one already exists with this id, then destroy it now. */
7465 if (pContext->paPixelShader[shid].id != SVGA3D_INVALID_ID)
7466 vmsvga3dBackShaderDestroy(pThisCC, cid, shid, pContext->paPixelShader[shid].type);
7467
7468 pShader = &pContext->paPixelShader[shid];
7469 }
7470
7471 memset(pShader, 0, sizeof(*pShader));
7472 pShader->id = shid;
7473 pShader->cid = cid;
7474 pShader->type = type;
7475 pShader->cbData = cbData;
7476 pShader->pShaderProgram = RTMemAllocZ(cbData);
7477 AssertReturn(pShader->pShaderProgram, VERR_NO_MEMORY);
7478 memcpy(pShader->pShaderProgram, pShaderData, cbData);
7479
7480#ifdef DUMP_SHADER_DISASSEMBLY
7481 LPD3DXBUFFER pDisassembly;
7482 HRESULT hr = D3DXDisassembleShader((const DWORD *)pShaderData, FALSE, NULL, &pDisassembly);
7483 if (hr == D3D_OK)
7484 {
7485 Log(("Shader disassembly:\n%s\n", pDisassembly->GetBufferPointer()));
7486 pDisassembly->Release();
7487 }
7488#endif
7489
7490 switch (type)
7491 {
7492 case SVGA3D_SHADERTYPE_VS:
7493 rc = ShaderCreateVertexShader(pContext->pShaderContext, (const uint32_t *)pShaderData, cbData, &pShader->u.pVertexShader);
7494 AssertRC(rc);
7495 break;
7496
7497 case SVGA3D_SHADERTYPE_PS:
7498 rc = ShaderCreatePixelShader(pContext->pShaderContext, (const uint32_t *)pShaderData, cbData, &pShader->u.pPixelShader);
7499 AssertRC(rc);
7500 break;
7501
7502 default:
7503 AssertFailedReturn(VERR_INVALID_PARAMETER);
7504 }
7505 if (rc != VINF_SUCCESS)
7506 {
7507 vmsvga3dShaderLogRel("Failed to create", type, cbData, pShaderData);
7508
7509 RTMemFree(pShader->pShaderProgram);
7510 memset(pShader, 0, sizeof(*pShader));
7511 pShader->id = SVGA3D_INVALID_ID;
7512 }
7513
7514 return rc;
7515}
7516
7517static DECLCALLBACK(int) vmsvga3dBackShaderDestroy(PVGASTATECC pThisCC, uint32_t cid, uint32_t shid, SVGA3dShaderType type)
7518{
7519 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7520 AssertReturn(pState, VERR_NO_MEMORY);
7521 PVMSVGA3DSHADER pShader = NULL;
7522
7523 Log(("vmsvga3dShaderDestroy cid=%u shid=%d type=%s\n", cid, shid, (type == SVGA3D_SHADERTYPE_VS) ? "VERTEX" : "PIXEL"));
7524
7525 PVMSVGA3DCONTEXT pContext;
7526 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
7527 AssertRCReturn(rc, rc);
7528
7529 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7530
7531 if (type == SVGA3D_SHADERTYPE_VS)
7532 {
7533 if ( shid < pContext->cVertexShaders
7534 && pContext->paVertexShader[shid].id == shid)
7535 {
7536 pShader = &pContext->paVertexShader[shid];
7537 if (pContext->state.shidVertex == shid)
7538 {
7539 rc = ShaderSetVertexShader(pContext->pShaderContext, NULL);
7540 AssertRC(rc);
7541 }
7542
7543 rc = ShaderDestroyVertexShader(pContext->pShaderContext, pShader->u.pVertexShader);
7544 AssertRC(rc);
7545 }
7546 }
7547 else
7548 {
7549 Assert(type == SVGA3D_SHADERTYPE_PS);
7550 if ( shid < pContext->cPixelShaders
7551 && pContext->paPixelShader[shid].id == shid)
7552 {
7553 pShader = &pContext->paPixelShader[shid];
7554 if (pContext->state.shidPixel == shid)
7555 {
7556 ShaderSetPixelShader(pContext->pShaderContext, NULL);
7557 AssertRC(rc);
7558 }
7559
7560 rc = ShaderDestroyPixelShader(pContext->pShaderContext, pShader->u.pPixelShader);
7561 AssertRC(rc);
7562 }
7563 }
7564
7565 if (pShader)
7566 {
7567 if (pShader->pShaderProgram)
7568 RTMemFree(pShader->pShaderProgram);
7569 memset(pShader, 0, sizeof(*pShader));
7570 pShader->id = SVGA3D_INVALID_ID;
7571 }
7572 else
7573 AssertFailedReturn(VERR_INVALID_PARAMETER);
7574
7575 return VINF_SUCCESS;
7576}
7577
7578static DECLCALLBACK(int) vmsvga3dBackShaderSet(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t cid, SVGA3dShaderType type, uint32_t shid)
7579{
7580 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7581 AssertReturn(pState, VERR_NO_MEMORY);
7582 int rc;
7583
7584 Log(("vmsvga3dShaderSet cid=%u type=%s shid=%d\n", cid, (type == SVGA3D_SHADERTYPE_VS) ? "VERTEX" : "PIXEL", shid));
7585
7586 if (!pContext)
7587 {
7588 rc = vmsvga3dContextFromCid(pState, cid, &pContext);
7589 AssertRCReturn(rc, rc);
7590 }
7591
7592 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7593
7594 if (type == SVGA3D_SHADERTYPE_VS)
7595 {
7596 /* Save for vm state save/restore. */
7597 pContext->state.shidVertex = shid;
7598 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_VERTEXSHADER;
7599
7600 if ( shid < pContext->cVertexShaders
7601 && pContext->paVertexShader[shid].id == shid)
7602 {
7603 PVMSVGA3DSHADER pShader = &pContext->paVertexShader[shid];
7604 Assert(type == pShader->type);
7605
7606 rc = ShaderSetVertexShader(pContext->pShaderContext, pShader->u.pVertexShader);
7607 AssertRCReturn(rc, rc);
7608 }
7609 else
7610 if (shid == SVGA_ID_INVALID)
7611 {
7612 /* Unselect shader. */
7613 rc = ShaderSetVertexShader(pContext->pShaderContext, NULL);
7614 AssertRCReturn(rc, rc);
7615 }
7616 else
7617 AssertFailedReturn(VERR_INVALID_PARAMETER);
7618 }
7619 else
7620 {
7621 /* Save for vm state save/restore. */
7622 pContext->state.shidPixel = shid;
7623 pContext->state.u32UpdateFlags |= VMSVGA3D_UPDATE_PIXELSHADER;
7624
7625 Assert(type == SVGA3D_SHADERTYPE_PS);
7626 if ( shid < pContext->cPixelShaders
7627 && pContext->paPixelShader[shid].id == shid)
7628 {
7629 PVMSVGA3DSHADER pShader = &pContext->paPixelShader[shid];
7630 Assert(type == pShader->type);
7631
7632 rc = ShaderSetPixelShader(pContext->pShaderContext, pShader->u.pPixelShader);
7633 AssertRCReturn(rc, rc);
7634 }
7635 else
7636 if (shid == SVGA_ID_INVALID)
7637 {
7638 /* Unselect shader. */
7639 rc = ShaderSetPixelShader(pContext->pShaderContext, NULL);
7640 AssertRCReturn(rc, rc);
7641 }
7642 else
7643 AssertFailedReturn(VERR_INVALID_PARAMETER);
7644 }
7645
7646 return VINF_SUCCESS;
7647}
7648
7649static DECLCALLBACK(int) vmsvga3dBackShaderSetConst(PVGASTATECC pThisCC, uint32_t cid, uint32_t reg, SVGA3dShaderType type, SVGA3dShaderConstType ctype, uint32_t cRegisters, uint32_t *pValues)
7650{
7651 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7652 AssertReturn(pState, VERR_NO_MEMORY);
7653
7654 Log(("vmsvga3dShaderSetConst cid=%u reg=%x type=%s cregs=%d ctype=%x\n", cid, reg, (type == SVGA3D_SHADERTYPE_VS) ? "VERTEX" : "PIXEL", cRegisters, ctype));
7655
7656 PVMSVGA3DCONTEXT pContext;
7657 int rc = vmsvga3dContextFromCid(pState, cid, &pContext);
7658 AssertRCReturn(rc, rc);
7659
7660 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7661
7662 for (uint32_t i = 0; i < cRegisters; i++)
7663 {
7664#ifdef LOG_ENABLED
7665 switch (ctype)
7666 {
7667 case SVGA3D_CONST_TYPE_FLOAT:
7668 {
7669 float *pValuesF = (float *)pValues;
7670 Log(("ConstantF %d: value=" FLOAT_FMT_STR ", " FLOAT_FMT_STR ", " FLOAT_FMT_STR ", " FLOAT_FMT_STR "\n",
7671 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])));
7672 break;
7673 }
7674
7675 case SVGA3D_CONST_TYPE_INT:
7676 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]));
7677 break;
7678
7679 case SVGA3D_CONST_TYPE_BOOL:
7680 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]));
7681 break;
7682
7683 default:
7684 AssertFailedReturn(VERR_INVALID_PARAMETER);
7685 }
7686#endif
7687 vmsvga3dSaveShaderConst(pContext, reg + i, type, ctype, pValues[i*4 + 0], pValues[i*4 + 1], pValues[i*4 + 2], pValues[i*4 + 3]);
7688 }
7689
7690 switch (type)
7691 {
7692 case SVGA3D_SHADERTYPE_VS:
7693 switch (ctype)
7694 {
7695 case SVGA3D_CONST_TYPE_FLOAT:
7696 rc = ShaderSetVertexShaderConstantF(pContext->pShaderContext, reg, (const float *)pValues, cRegisters);
7697 break;
7698
7699 case SVGA3D_CONST_TYPE_INT:
7700 rc = ShaderSetVertexShaderConstantI(pContext->pShaderContext, reg, (const int32_t *)pValues, cRegisters);
7701 break;
7702
7703 case SVGA3D_CONST_TYPE_BOOL:
7704 rc = ShaderSetVertexShaderConstantB(pContext->pShaderContext, reg, (const uint8_t *)pValues, cRegisters);
7705 break;
7706
7707 default:
7708 AssertFailedReturn(VERR_INVALID_PARAMETER);
7709 }
7710 AssertRCReturn(rc, rc);
7711 break;
7712
7713 case SVGA3D_SHADERTYPE_PS:
7714 switch (ctype)
7715 {
7716 case SVGA3D_CONST_TYPE_FLOAT:
7717 rc = ShaderSetPixelShaderConstantF(pContext->pShaderContext, reg, (const float *)pValues, cRegisters);
7718 break;
7719
7720 case SVGA3D_CONST_TYPE_INT:
7721 rc = ShaderSetPixelShaderConstantI(pContext->pShaderContext, reg, (const int32_t *)pValues, cRegisters);
7722 break;
7723
7724 case SVGA3D_CONST_TYPE_BOOL:
7725 rc = ShaderSetPixelShaderConstantB(pContext->pShaderContext, reg, (const uint8_t *)pValues, cRegisters);
7726 break;
7727
7728 default:
7729 AssertFailedReturn(VERR_INVALID_PARAMETER);
7730 }
7731 AssertRCReturn(rc, rc);
7732 break;
7733
7734 default:
7735 AssertFailedReturn(VERR_INVALID_PARAMETER);
7736 }
7737
7738 return VINF_SUCCESS;
7739}
7740
7741static DECLCALLBACK(int) vmsvga3dBackOcclusionQueryCreate(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext)
7742{
7743 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7744 AssertReturn(pState->ext.glGenQueries, VERR_NOT_SUPPORTED);
7745 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7746
7747 GLuint idQuery = 0;
7748 pState->ext.glGenQueries(1, &idQuery);
7749 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7750 AssertReturn(idQuery, VERR_INTERNAL_ERROR);
7751 pContext->occlusion.idQuery = idQuery;
7752 return VINF_SUCCESS;
7753}
7754
7755static DECLCALLBACK(int) vmsvga3dBackOcclusionQueryDelete(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext)
7756{
7757 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7758 AssertReturn(pState->ext.glDeleteQueries, VERR_NOT_SUPPORTED);
7759 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7760
7761 if (pContext->occlusion.idQuery)
7762 {
7763 pState->ext.glDeleteQueries(1, &pContext->occlusion.idQuery);
7764 }
7765 return VINF_SUCCESS;
7766}
7767
7768static DECLCALLBACK(int) vmsvga3dBackOcclusionQueryBegin(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext)
7769{
7770 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7771 AssertReturn(pState->ext.glBeginQuery, VERR_NOT_SUPPORTED);
7772 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7773
7774 pState->ext.glBeginQuery(GL_ANY_SAMPLES_PASSED, pContext->occlusion.idQuery);
7775 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7776 return VINF_SUCCESS;
7777}
7778
7779static DECLCALLBACK(int) vmsvga3dBackOcclusionQueryEnd(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext)
7780{
7781 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7782 AssertReturn(pState->ext.glEndQuery, VERR_NOT_SUPPORTED);
7783 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7784
7785 pState->ext.glEndQuery(GL_ANY_SAMPLES_PASSED);
7786 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7787 return VINF_SUCCESS;
7788}
7789
7790static DECLCALLBACK(int) vmsvga3dBackOcclusionQueryGetData(PVGASTATECC pThisCC, PVMSVGA3DCONTEXT pContext, uint32_t *pu32Pixels)
7791{
7792 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7793 AssertReturn(pState->ext.glGetQueryObjectuiv, VERR_NOT_SUPPORTED);
7794 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7795
7796 GLuint pixels = 0;
7797 pState->ext.glGetQueryObjectuiv(pContext->occlusion.idQuery, GL_QUERY_RESULT, &pixels);
7798 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7799
7800 *pu32Pixels = (uint32_t)pixels;
7801 return VINF_SUCCESS;
7802}
7803
7804/**
7805 * Worker for vmsvga3dUpdateHeapBuffersForSurfaces.
7806 *
7807 * This will allocate heap buffers if necessary, thus increasing the memory
7808 * usage of the process.
7809 *
7810 * @todo Would be interesting to share this code with the saved state code.
7811 *
7812 * @returns VBox status code.
7813 * @param pThisCC The VGA/VMSVGA context.
7814 * @param pSurface The surface to refresh the heap buffers for.
7815 */
7816static DECLCALLBACK(int) vmsvga3dBackSurfaceUpdateHeapBuffers(PVGASTATECC pThisCC, PVMSVGA3DSURFACE pSurface)
7817{
7818 PVMSVGA3DSTATE pState = pThisCC->svga.p3dState;
7819 AssertReturn(pState, VERR_INVALID_STATE);
7820
7821 /*
7822 * Currently we've got trouble retreving bit for DEPTHSTENCIL
7823 * surfaces both for OpenGL and D3D, so skip these here (don't
7824 * wast memory on them).
7825 */
7826 uint32_t const fSwitchFlags = pSurface->f.s.surface1Flags & VMSVGA3D_SURFACE_HINT_SWITCH_MASK;
7827 if ( fSwitchFlags != SVGA3D_SURFACE_HINT_DEPTHSTENCIL
7828 && fSwitchFlags != (SVGA3D_SURFACE_HINT_DEPTHSTENCIL | SVGA3D_SURFACE_HINT_TEXTURE))
7829 {
7830 /*
7831 * Change OpenGL context to the one the surface is associated with.
7832 */
7833 PVMSVGA3DCONTEXT pContext = &pState->SharedCtx;
7834 VMSVGA3D_SET_CURRENT_CONTEXT(pState, pContext);
7835
7836 /*
7837 * Work thru each mipmap level for each face.
7838 */
7839 for (uint32_t iFace = 0; iFace < pSurface->cFaces; iFace++)
7840 {
7841 PVMSVGA3DMIPMAPLEVEL pMipmapLevel = &pSurface->paMipmapLevels[iFace * pSurface->cLevels];
7842 for (uint32_t i = 0; i < pSurface->cLevels; i++, pMipmapLevel++)
7843 {
7844 if (VMSVGA3DSURFACE_HAS_HW_SURFACE(pSurface))
7845 {
7846 Assert(pMipmapLevel->cbSurface);
7847 Assert(pMipmapLevel->cbSurface == pMipmapLevel->cbSurfacePlane * pMipmapLevel->mipmapSize.depth);
7848
7849 /*
7850 * Make sure we've got surface memory buffer.
7851 */
7852 uint8_t *pbDst = (uint8_t *)pMipmapLevel->pSurfaceData;
7853 if (!pbDst)
7854 {
7855 pMipmapLevel->pSurfaceData = pbDst = (uint8_t *)RTMemAllocZ(pMipmapLevel->cbSurface);
7856 AssertReturn(pbDst, VERR_NO_MEMORY);
7857 }
7858
7859 /*
7860 * OpenGL specifics.
7861 */
7862 switch (pSurface->enmOGLResType)
7863 {
7864 case VMSVGA3D_OGLRESTYPE_TEXTURE:
7865 {
7866 GLint activeTexture;
7867 glGetIntegerv(GL_TEXTURE_BINDING_2D, &activeTexture);
7868 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7869
7870 glBindTexture(GL_TEXTURE_2D, pSurface->oglId.texture);
7871 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7872
7873 /* Set row length and alignment of the output data. */
7874 VMSVGAPACKPARAMS SavedParams;
7875 vmsvga3dOglSetPackParams(pState, pContext, pSurface, &SavedParams);
7876
7877 glGetTexImage(GL_TEXTURE_2D,
7878 i,
7879 pSurface->formatGL,
7880 pSurface->typeGL,
7881 pbDst);
7882 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7883
7884 vmsvga3dOglRestorePackParams(pState, pContext, pSurface, &SavedParams);
7885
7886 /* Restore the old active texture. */
7887 glBindTexture(GL_TEXTURE_2D, activeTexture);
7888 VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
7889 break;
7890 }
7891
7892 case VMSVGA3D_OGLRESTYPE_BUFFER:
7893 {
7894 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, pSurface->oglId.buffer);
7895 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7896
7897 void *pvSrc = pState->ext.glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY);
7898 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7899 if (RT_VALID_PTR(pvSrc))
7900 memcpy(pbDst, pvSrc, pMipmapLevel->cbSurface);
7901 else
7902 AssertPtr(pvSrc);
7903
7904 pState->ext.glUnmapBuffer(GL_ARRAY_BUFFER);
7905 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7906
7907 pState->ext.glBindBuffer(GL_ARRAY_BUFFER, 0);
7908 VMSVGA3D_CHECK_LAST_ERROR(pState, pContext);
7909 break;
7910 }
7911
7912 default:
7913 AssertMsgFailed(("%#x\n", fSwitchFlags));
7914 }
7915 }
7916 /* else: There is no data in hardware yet, so whatever we got is already current. */
7917 }
7918 }
7919 }
7920
7921 return VINF_SUCCESS;
7922}
7923
7924static DECLCALLBACK(int) vmsvga3dBackQueryInterface(PVGASTATECC pThisCC, char const *pszInterfaceName, void *pvInterfaceFuncs, size_t cbInterfaceFuncs)
7925{
7926 RT_NOREF(pThisCC);
7927
7928 int rc = VINF_SUCCESS;
7929 if (RTStrCmp(pszInterfaceName, VMSVGA3D_BACKEND_INTERFACE_NAME_3D) == 0)
7930 {
7931 if (cbInterfaceFuncs == sizeof(VMSVGA3DBACKENDFUNCS3D))
7932 {
7933 if (pvInterfaceFuncs)
7934 {
7935 VMSVGA3DBACKENDFUNCS3D *p = (VMSVGA3DBACKENDFUNCS3D *)pvInterfaceFuncs;
7936 p->pfnInit = vmsvga3dBackInit;
7937 p->pfnPowerOn = vmsvga3dBackPowerOn;
7938 p->pfnTerminate = vmsvga3dBackTerminate;
7939 p->pfnReset = vmsvga3dBackReset;
7940 p->pfnQueryCaps = vmsvga3dBackQueryCaps;
7941 p->pfnChangeMode = vmsvga3dBackChangeMode;
7942 p->pfnCreateTexture = vmsvga3dBackCreateTexture;
7943 p->pfnSurfaceDestroy = vmsvga3dBackSurfaceDestroy;
7944 p->pfnSurfaceInvalidateImage = vmsvga3dBackSurfaceInvalidateImage;
7945 p->pfnSurfaceCopy = vmsvga3dBackSurfaceCopy;
7946 p->pfnSurfaceDMACopyBox = vmsvga3dBackSurfaceDMACopyBox;
7947 p->pfnSurfaceStretchBlt = vmsvga3dBackSurfaceStretchBlt;
7948 p->pfnUpdateHostScreenViewport = vmsvga3dBackUpdateHostScreenViewport;
7949 p->pfnDefineScreen = vmsvga3dBackDefineScreen;
7950 p->pfnDestroyScreen = vmsvga3dBackDestroyScreen;
7951 p->pfnSurfaceBlitToScreen = vmsvga3dBackSurfaceBlitToScreen;
7952 p->pfnSurfaceUpdateHeapBuffers = vmsvga3dBackSurfaceUpdateHeapBuffers;
7953 }
7954 }
7955 else
7956 {
7957 AssertFailed();
7958 rc = VERR_INVALID_PARAMETER;
7959 }
7960 }
7961 else if (RTStrCmp(pszInterfaceName, VMSVGA3D_BACKEND_INTERFACE_NAME_VGPU9) == 0)
7962 {
7963 if (cbInterfaceFuncs == sizeof(VMSVGA3DBACKENDFUNCSVGPU9))
7964 {
7965 if (pvInterfaceFuncs)
7966 {
7967 VMSVGA3DBACKENDFUNCSVGPU9 *p = (VMSVGA3DBACKENDFUNCSVGPU9 *)pvInterfaceFuncs;
7968 p->pfnContextDefine = vmsvga3dBackContextDefine;
7969 p->pfnContextDestroy = vmsvga3dBackContextDestroy;
7970 p->pfnSetTransform = vmsvga3dBackSetTransform;
7971 p->pfnSetZRange = vmsvga3dBackSetZRange;
7972 p->pfnSetRenderState = vmsvga3dBackSetRenderState;
7973 p->pfnSetRenderTarget = vmsvga3dBackSetRenderTarget;
7974 p->pfnSetTextureState = vmsvga3dBackSetTextureState;
7975 p->pfnSetMaterial = vmsvga3dBackSetMaterial;
7976 p->pfnSetLightData = vmsvga3dBackSetLightData;
7977 p->pfnSetLightEnabled = vmsvga3dBackSetLightEnabled;
7978 p->pfnSetViewPort = vmsvga3dBackSetViewPort;
7979 p->pfnSetClipPlane = vmsvga3dBackSetClipPlane;
7980 p->pfnCommandClear = vmsvga3dBackCommandClear;
7981 p->pfnDrawPrimitives = vmsvga3dBackDrawPrimitives;
7982 p->pfnSetScissorRect = vmsvga3dBackSetScissorRect;
7983 p->pfnGenerateMipmaps = vmsvga3dBackGenerateMipmaps;
7984 p->pfnShaderDefine = vmsvga3dBackShaderDefine;
7985 p->pfnShaderDestroy = vmsvga3dBackShaderDestroy;
7986 p->pfnShaderSet = vmsvga3dBackShaderSet;
7987 p->pfnShaderSetConst = vmsvga3dBackShaderSetConst;
7988 p->pfnOcclusionQueryCreate = vmsvga3dBackOcclusionQueryCreate;
7989 p->pfnOcclusionQueryDelete = vmsvga3dBackOcclusionQueryDelete;
7990 p->pfnOcclusionQueryBegin = vmsvga3dBackOcclusionQueryBegin;
7991 p->pfnOcclusionQueryEnd = vmsvga3dBackOcclusionQueryEnd;
7992 p->pfnOcclusionQueryGetData = vmsvga3dBackOcclusionQueryGetData;
7993 }
7994 }
7995 else
7996 {
7997 AssertFailed();
7998 rc = VERR_INVALID_PARAMETER;
7999 }
8000 }
8001 else
8002 rc = VERR_NOT_IMPLEMENTED;
8003 return rc;
8004}
8005
8006
8007extern VMSVGA3DBACKENDDESC const g_BackendLegacy =
8008{
8009 "LEGACY",
8010 vmsvga3dBackQueryInterface
8011};
Note: See TracBrowser for help on using the repository browser.

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