summaryrefslogtreecommitdiff
path: root/src/glx/x11/glxcurrent.c
blob: 0d0c419a846ed0ae4f4283b80e11628c369a5c6d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
** 
** http://oss.sgi.com/projects/FreeB
** 
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
** 
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
** 
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
*/

/**
 * \file glxcurrent.c
 * Client-side GLX interface for current context management.
 */

#include "glxclient.h"
#include "glapi.h"
#include "glheader.h"
#include "indirect_init.h"

#ifdef GLX_DIRECT_RENDERING
#include "xf86dri.h"
#endif

/*
** We setup some dummy structures here so that the API can be used
** even if no context is current.
*/

static GLubyte dummyBuffer[__GLX_BUFFER_LIMIT_SIZE];

/*
** Dummy context used by small commands when there is no current context.
** All the
** gl and glx entry points are designed to operate as nop's when using
** the dummy context structure.
*/
static __GLXcontext dummyContext = {
    &dummyBuffer[0],
    &dummyBuffer[0],
    &dummyBuffer[0],
    &dummyBuffer[__GLX_BUFFER_LIMIT_SIZE],
    sizeof(dummyBuffer),
};


/*
** All indirect rendering contexts will share the same indirect dispatch table.
*/
static __GLapi *IndirectAPI = NULL;


/*
 * Current context management and locking
 */

#if defined( USE_XTHREADS )

/* thread safe */
static GLboolean TSDinitialized = GL_FALSE;
static xthread_key_t ContextTSD;

_X_HIDDEN __GLXcontext *__glXGetCurrentContext(void)
{
   if (!TSDinitialized) {
      xthread_key_create(&ContextTSD, NULL);
      TSDinitialized = GL_TRUE;
      return &dummyContext;
   }
   else {
      void *p;
      xthread_get_specific(ContextTSD, &p);
      if (!p)
         return &dummyContext;
      else
         return (__GLXcontext *) p;
   }
}

_X_HIDDEN void __glXSetCurrentContext(__GLXcontext *c)
{
   if (!TSDinitialized) {
      xthread_key_create(&ContextTSD, NULL);
      TSDinitialized = GL_TRUE;
   }
   xthread_set_specific(ContextTSD, c);
}


/* Used by the __glXLock() and __glXUnlock() macros */
_X_HIDDEN xmutex_rec __glXmutex;

#elif defined( PTHREADS )

_X_HIDDEN pthread_mutex_t __glXmutex = PTHREAD_MUTEX_INITIALIZER;

# if defined( GLX_USE_TLS )

/**
 * Per-thread GLX context pointer.
 * 
 * \c __glXSetCurrentContext is written is such a way that this pointer can
 * \b never be \c NULL.  This is important!  Because of this
 * \c __glXGetCurrentContext can be implemented as trivial macro.
 */
__thread void * __glX_tls_Context __attribute__((tls_model("initial-exec")))
    = &dummyContext;

_X_HIDDEN void __glXSetCurrentContext( __GLXcontext * c )
{
    __glX_tls_Context = (c != NULL) ? c : &dummyContext;
}

# else

static pthread_once_t once_control = PTHREAD_ONCE_INIT;

/**
 * Per-thread data key.
 * 
 * Once \c init_thread_data has been called, the per-thread data key will
 * take a value of \c NULL.  As each new thread is created the default
 * value, in that thread, will be \c NULL.
 */
static pthread_key_t ContextTSD;

/**
 * Initialize the per-thread data key.
 * 
 * This function is called \b exactly once per-process (not per-thread!) to
 * initialize the per-thread data key.  This is ideally done using the
 * \c pthread_once mechanism.
 */
static void init_thread_data( void )
{
    if ( pthread_key_create( & ContextTSD, NULL ) != 0 ) {
	perror( "pthread_key_create" );
	exit( -1 );
    }
}

_X_HIDDEN void __glXSetCurrentContext( __GLXcontext * c )
{
    pthread_once( & once_control, init_thread_data );
    pthread_setspecific( ContextTSD, c );
}

_X_HIDDEN __GLXcontext * __glXGetCurrentContext( void )
{
    void * v;

    pthread_once( & once_control, init_thread_data );

    v = pthread_getspecific( ContextTSD );
    return (v == NULL) ? & dummyContext : (__GLXcontext *) v;
}

# endif /* defined( GLX_USE_TLS ) */

#elif defined( THREADS )

#error Unknown threading method specified.

#else

/* not thread safe */
_X_HIDDEN __GLXcontext *__glXcurrentContext = &dummyContext;

#endif


_X_HIDDEN void __glXSetCurrentContextNull(void)
{
    __glXSetCurrentContext(&dummyContext);
#ifdef GLX_DIRECT_RENDERING
    _glapi_set_dispatch(NULL);  /* no-op functions */
#endif
}


/************************************************************************/

PUBLIC GLXContext glXGetCurrentContext(void)
{
    GLXContext cx = __glXGetCurrentContext();
    
    if (cx == &dummyContext) {
	return NULL;
    } else {
	return cx;
    }
}

PUBLIC GLXDrawable glXGetCurrentDrawable(void)
{
    GLXContext gc = __glXGetCurrentContext();
    return gc->currentDrawable;
}


/************************************************************************/

/**
 * Sends a GLX protocol message to the specified display to make the context
 * and the drawables current.
 *
 * \param dpy     Display to send the message to.
 * \param opcode  Major opcode value for the display.
 * \param gc_id   Context tag for the context to be made current.
 * \param draw    Drawable ID for the "draw" drawable.
 * \param read    Drawable ID for the "read" drawable.
 * \param reply   Space to store the X-server's reply.
 *
 * \warning
 * This function assumes that \c dpy is locked with \c LockDisplay on entry.
 */
static Bool SendMakeCurrentRequest(Display *dpy, CARD8 opcode,
				   GLXContextID gc_id, GLXContextTag gc_tag,
				   GLXDrawable draw, GLXDrawable read,
				   xGLXMakeCurrentReply *reply)
{
    Bool ret;


    LockDisplay(dpy);

    if (draw == read) {
	xGLXMakeCurrentReq *req;

	GetReq(GLXMakeCurrent,req);
	req->reqType = opcode;
	req->glxCode = X_GLXMakeCurrent;
	req->drawable = draw;
	req->context = gc_id;
	req->oldContextTag = gc_tag;
    }
    else {
	__GLXdisplayPrivate *priv = __glXInitialize(dpy);

	/* If the server can support the GLX 1.3 version, we should
	 * perfer that.  Not only that, some servers support GLX 1.3 but
	 * not the SGI extension.
	 */

	if ((priv->majorVersion > 1) || (priv->minorVersion >= 3)) {
	    xGLXMakeContextCurrentReq *req;

	    GetReq(GLXMakeContextCurrent,req);
	    req->reqType = opcode;
	    req->glxCode = X_GLXMakeContextCurrent;
	    req->drawable = draw;
	    req->readdrawable = read;
	    req->context = gc_id;
	    req->oldContextTag = gc_tag;
	}
	else {
	    xGLXVendorPrivateWithReplyReq *vpreq;
	    xGLXMakeCurrentReadSGIReq *req;

	    GetReqExtra(GLXVendorPrivateWithReply,
			sz_xGLXMakeCurrentReadSGIReq-sz_xGLXVendorPrivateWithReplyReq,vpreq);
	    req = (xGLXMakeCurrentReadSGIReq *)vpreq;
	    req->reqType = opcode;
	    req->glxCode = X_GLXVendorPrivateWithReply;
	    req->vendorCode = X_GLXvop_MakeCurrentReadSGI;
	    req->drawable = draw;
	    req->readable = read;
	    req->context = gc_id;
	    req->oldContextTag = gc_tag;
	}
    }

    ret = _XReply(dpy, (xReply*) reply, 0, False);

    UnlockDisplay(dpy);
    SyncHandle();

    return ret;
}


#ifdef GLX_DIRECT_RENDERING
static __GLXDRIdrawable *
FetchDRIDrawable(Display *dpy,
		 GLXDrawable glxDrawable, GLXContext gc, Bool pre13)
{
    __GLXdisplayPrivate * const priv = __glXInitialize(dpy);
    __GLXDRIdrawable *pdraw;
    __GLXscreenConfigs *psc;
    XID drawable;

    if (priv == NULL)
	return NULL;
    
    psc = &priv->screenConfigs[gc->screen];
    if (psc->drawHash == NULL)
	return NULL;

    if (__glxHashLookup(psc->drawHash, glxDrawable, (void *) &pdraw) == 0)
	return pdraw;

    /* If this is glXMakeCurrent (pre GLX 1.3) we allow creating the
     * GLX drawable on the fly.  Otherwise we pass None as the X
     * drawable */
    if (pre13)
	drawable = glxDrawable;
    else
	drawable = None;

    pdraw = psc->driScreen->createDrawable(psc, drawable,
					   glxDrawable, gc->mode);
    if (__glxHashInsert(psc->drawHash, glxDrawable, pdraw)) {
	(*pdraw->destroyDrawable)(pdraw);
	return NULL;
    }

    return pdraw;
}
#endif /* GLX_DIRECT_RENDERING */


/**
 * Make a particular context current.
 * 
 * \note This is in this file so that it can access dummyContext.
 */
static Bool MakeContextCurrent(Display *dpy, GLXDrawable draw,
			       GLXDrawable read, GLXContext gc,
			       Bool pre13)
{
    xGLXMakeCurrentReply reply;
    const GLXContext oldGC = __glXGetCurrentContext();
    const CARD8 opcode = __glXSetupForCommand(dpy);
    const CARD8 oldOpcode = ((gc == oldGC) || (oldGC == &dummyContext))
      ? opcode : __glXSetupForCommand(oldGC->currentDpy);
    Bool bindReturnValue;


    if (!opcode || !oldOpcode) {
	return GL_FALSE;
    }

    /* Make sure that the new context has a nonzero ID.  In the request,
     * a zero context ID is used only to mean that we bind to no current
     * context.
     */
    if ((gc != NULL) && (gc->xid == None)) {
	return GL_FALSE;
    }

    _glapi_check_multithread();

#ifdef GLX_DIRECT_RENDERING
    /* Bind the direct rendering context to the drawable */
    if (gc && gc->driContext) {
	__GLXDRIdrawable *pdraw = FetchDRIDrawable(dpy, draw, gc, pre13);
	__GLXDRIdrawable *pread = FetchDRIDrawable(dpy, read, gc, pre13);

	bindReturnValue =
	    (gc->driContext->bindContext) (gc->driContext, pdraw, pread);
    } else
#endif
    {
	/* Send a glXMakeCurrent request to bind the new context. */
	bindReturnValue = 
	  SendMakeCurrentRequest(dpy, opcode, gc ? gc->xid : None,
				 ((dpy != oldGC->currentDpy) || oldGC->isDirect)
				 ? None : oldGC->currentContextTag,
				 draw, read, &reply);
    }


    if (!bindReturnValue) {
	return False;
    }

#ifdef GLX_DIRECT_RENDERING
    if ((dpy != oldGC->currentDpy || (gc && gc->driContext)) &&
	!oldGC->isDirect && oldGC != &dummyContext) {
#else
    if ((dpy != oldGC->currentDpy) && oldGC != &dummyContext) {
#endif
	xGLXMakeCurrentReply dummy_reply;

	/* We are either switching from one dpy to another and have to
	 * send a request to the previous dpy to unbind the previous
	 * context, or we are switching away from a indirect context to
	 * a direct context and have to send a request to the dpy to
	 * unbind the previous context.
	 */
	(void) SendMakeCurrentRequest(oldGC->currentDpy, oldOpcode, None,
				      oldGC->currentContextTag, None, None,
				      & dummy_reply);
    }
#ifdef GLX_DIRECT_RENDERING
    else if (oldGC->driContext) {
	oldGC->driContext->unbindContext(oldGC->driContext);
    }
#endif


    /* Update our notion of what is current */
    __glXLock();
    if (gc == oldGC) {
	/* Even though the contexts are the same the drawable might have
	 * changed.  Note that gc cannot be the dummy, and that oldGC
	 * cannot be NULL, therefore if they are the same, gc is not
	 * NULL and not the dummy.
	 */
	gc->currentDrawable = draw;
	gc->currentReadable = read;
    } else {
	if (oldGC != &dummyContext) {
	    /* Old current context is no longer current to anybody */
	    oldGC->currentDpy = 0;
	    oldGC->currentDrawable = None;
	    oldGC->currentReadable = None;
	    oldGC->currentContextTag = 0;

	    if (oldGC->xid == None) {
		/* We are switching away from a context that was
		 * previously destroyed, so we need to free the memory
		 * for the old handle.
		 */
#ifdef GLX_DIRECT_RENDERING
		/* Destroy the old direct rendering context */
		if (oldGC->driContext) {
		    oldGC->driContext->destroyContext(oldGC->driContext,
						      oldGC->psc,
						      oldGC->createDpy);
		    oldGC->driContext = NULL;
		}
#endif
		__glXFreeContext(oldGC);
	    }
	}
	if (gc) {
	    __glXSetCurrentContext(gc);

	    gc->currentDpy = dpy;
	    gc->currentDrawable = draw;
	    gc->currentReadable = read;

#ifdef GLX_DIRECT_RENDERING    
            if (!gc->driContext) {
#endif
               if (!IndirectAPI)
                  IndirectAPI = __glXNewIndirectAPI();
               _glapi_set_dispatch(IndirectAPI);

#ifdef GLX_USE_APPLEGL
               do {
                   extern void XAppleDRIUseIndirectDispatch(void);
                   XAppleDRIUseIndirectDispatch();
               } while (0);
#endif

		__GLXattribute *state = 
		  (__GLXattribute *)(gc->client_state_private);

		gc->currentContextTag = reply.contextTag;
		if (state->array_state == NULL) {
		    (void) glGetString(GL_EXTENSIONS);
		    (void) glGetString(GL_VERSION);
		    __glXInitVertexArrayState(gc);
		}
#ifdef GLX_DIRECT_RENDERING    
	    }
	    else {
		gc->currentContextTag = -1;
	    }
#endif
	} else {
	    __glXSetCurrentContextNull();
	}
    }
    __glXUnlock();
    return GL_TRUE;
}


PUBLIC Bool glXMakeCurrent(Display *dpy, GLXDrawable draw, GLXContext gc)
{
    return MakeContextCurrent(dpy, draw, draw, gc, True);
}

PUBLIC GLX_ALIAS(Bool, glXMakeCurrentReadSGI,
	  (Display *dpy, GLXDrawable d, GLXDrawable r, GLXContext ctx),
	  (dpy, d, r, ctx, False), MakeContextCurrent)

PUBLIC GLX_ALIAS(Bool, glXMakeContextCurrent,
	  (Display *dpy, GLXDrawable d, GLXDrawable r, GLXContext ctx),
	  (dpy, d, r, ctx, False), MakeContextCurrent)