gl-renderer.c 87.1 KB
Newer Older
1 2
/*
 * Copyright © 2012 Intel Corporation
3
 * Copyright © 2015 Collabora, Ltd.
4
 *
5 6 7 8 9 10 11
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
12
 *
13 14 15 16 17 18 19 20 21 22 23 24
 * The above copyright notice and this permission notice (including the
 * next paragraph) shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
25 26
 */

27
#include "config.h"
28

29 30 31
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>

32
#include <stdbool.h>
33
#include <stdint.h>
34
#include <stdlib.h>
35 36
#include <string.h>
#include <ctype.h>
37 38
#include <float.h>
#include <assert.h>
39
#include <linux/input.h>
40
#include <drm_fourcc.h>
41

42
#include "gl-renderer.h"
43
#include "vertex-clipping.h"
44
#include "linux-dmabuf.h"
45
#include "linux-dmabuf-unstable-v1-server-protocol.h"
46

47
#include "shared/helpers.h"
48
#include "shared/platform.h"
49
#include "weston-egl-ext.h"
50

51
struct gl_shader {
52 53 54 55 56 57
	GLuint program;
	GLuint vertex_shader, fragment_shader;
	GLint proj_uniform;
	GLint tex_uniforms[3];
	GLint alpha_uniform;
	GLint color_uniform;
58
	const char *vertex_source, *fragment_source;
59 60
};

61 62
#define BUFFER_DAMAGE_COUNT 2

63 64 65 66 67 68 69 70 71 72
enum gl_border_status {
	BORDER_STATUS_CLEAN = 0,
	BORDER_TOP_DIRTY = 1 << GL_RENDERER_BORDER_TOP,
	BORDER_LEFT_DIRTY = 1 << GL_RENDERER_BORDER_LEFT,
	BORDER_RIGHT_DIRTY = 1 << GL_RENDERER_BORDER_RIGHT,
	BORDER_BOTTOM_DIRTY = 1 << GL_RENDERER_BORDER_BOTTOM,
	BORDER_ALL_DIRTY = 0xf,
	BORDER_SIZE_CHANGED = 0x10
};

73 74 75 76 77 78 79
struct gl_border_image {
	GLuint tex;
	int32_t width, height;
	int32_t tex_width;
	void *data;
};

80
struct gl_output_state {
81
	EGLSurface egl_surface;
82
	pixman_region32_t buffer_damage[BUFFER_DAMAGE_COUNT];
83
	int buffer_damage_index;
84
	enum gl_border_status border_damage[BUFFER_DAMAGE_COUNT];
85
	struct gl_border_image borders[4];
86
	enum gl_border_status border_status;
87 88

	struct weston_matrix output_matrix;
89 90
};

91 92
enum buffer_type {
	BUFFER_TYPE_NULL,
93
	BUFFER_TYPE_SOLID, /* internal solid color surfaces without a buffer */
94 95 96 97
	BUFFER_TYPE_SHM,
	BUFFER_TYPE_EGL
};

98 99 100 101 102 103
struct gl_renderer;

struct egl_image {
	struct gl_renderer *renderer;
	EGLImageKHR image;
	int refcount;
104
};
105

106 107 108 109 110 111
enum import_type {
	IMPORT_TYPE_INVALID,
	IMPORT_TYPE_DIRECT,
	IMPORT_TYPE_GL_CONVERSION
};

112
struct dmabuf_image {
113
	struct linux_dmabuf_buffer *dmabuf;
114 115
	int num_images;
	struct egl_image *images[3];
116
	struct wl_list link;
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135

	enum import_type import_type;
	GLenum target;
	struct gl_shader *shader;
};

struct yuv_plane_descriptor {
	int width_divisor;
	int height_divisor;
	uint32_t format;
	int plane_index;
};

struct yuv_format_descriptor {
	uint32_t format;
	int input_planes;
	int output_planes;
	int texture_type;
	struct yuv_plane_descriptor plane[4];
136 137
};

138
struct gl_surface_state {
139
	GLfloat color[4];
140
	struct gl_shader *shader;
141 142 143

	GLuint textures[3];
	int num_textures;
144
	bool needs_full_upload;
145
	pixman_region32_t texture_damage;
146

147 148 149
	/* These are only used by SHM surfaces to detect when we need
	 * to do a full upload to specify a new internal texture
	 * format */
150
	GLenum gl_format[3];
151 152
	GLenum gl_pixel_type;

153
	struct egl_image* images[3];
154 155
	GLenum target;
	int num_images;
156 157

	struct weston_buffer_reference buffer_ref;
158
	enum buffer_type buffer_type;
159
	int pitch; /* in pixels */
160
	int height; /* in pixels */
161
	int y_inverted;
162

163 164 165 166
	/* Extension needed for SHM YUV texture */
	int offset[3]; /* offset per plane */
	int hvsub[3];  /* horizontal vertical subsampling per plane */

167 168 169
	struct weston_surface *surface;

	struct wl_listener surface_destroy_listener;
170
	struct wl_listener renderer_destroy_listener;
171 172
};

173
struct gl_renderer {
174 175
	struct weston_renderer base;
	int fragment_shader_debug;
176
	int fan_debug;
177 178
	struct weston_binding *fragment_binding;
	struct weston_binding *fan_binding;
179

180 181 182
	EGLDisplay egl_display;
	EGLContext egl_context;
	EGLConfig egl_config;
183

184 185
	EGLSurface dummy_surface;

186 187 188
	struct wl_array vertices;
	struct wl_array vtxcnt;

189 190 191
	PFNGLEGLIMAGETARGETTEXTURE2DOESPROC image_target_texture_2d;
	PFNEGLCREATEIMAGEKHRPROC create_image;
	PFNEGLDESTROYIMAGEKHRPROC destroy_image;
192
	PFNEGLSWAPBUFFERSWITHDAMAGEEXTPROC swap_buffers_with_damage;
193 194
	PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC create_platform_window;

195 196 197 198 199 200 201 202 203
	int has_unpack_subimage;

	PFNEGLBINDWAYLANDDISPLAYWL bind_display;
	PFNEGLUNBINDWAYLANDDISPLAYWL unbind_display;
	PFNEGLQUERYWAYLANDBUFFERWL query_buffer;
	int has_bind_display;

	int has_egl_image_external;

204 205
	int has_egl_buffer_age;

206 207
	int has_configless_context;

208 209
	int has_surfaceless_context;

210 211 212
	int has_dmabuf_import;
	struct wl_list dmabuf_images;

213 214
	int has_gl_texture_rg;

215 216 217 218 219 220 221 222 223
	struct gl_shader texture_shader_rgba;
	struct gl_shader texture_shader_rgbx;
	struct gl_shader texture_shader_egl_external;
	struct gl_shader texture_shader_y_uv;
	struct gl_shader texture_shader_y_u_v;
	struct gl_shader texture_shader_y_xuxv;
	struct gl_shader invert_color_shader;
	struct gl_shader solid_shader;
	struct gl_shader *current_shader;
224 225

	struct wl_signal destroy_signal;
226 227

	struct wl_listener output_destroy_listener;
228 229
};

230 231
static PFNEGLGETPLATFORMDISPLAYEXTPROC get_platform_display = NULL;

232 233 234 235 236 237 238 239 240 241
static inline const char *
dump_format(uint32_t format, char out[4])
{
#if BYTE_ORDER == BIG_ENDIAN
	format = __builtin_bswap32(format);
#endif
	memcpy(out, &format, 4);
	return out;
}

242
static inline struct gl_output_state *
243 244
get_output_state(struct weston_output *output)
{
245
	return (struct gl_output_state *)output->renderer_state;
246 247
}

248 249 250
static int
gl_renderer_create_surface(struct weston_surface *surface);

251
static inline struct gl_surface_state *
252 253
get_surface_state(struct weston_surface *surface)
{
254 255 256
	if (!surface->renderer_state)
		gl_renderer_create_surface(surface);

257
	return (struct gl_surface_state *)surface->renderer_state;
258 259
}

260
static inline struct gl_renderer *
261 262
get_renderer(struct weston_compositor *ec)
{
263
	return (struct gl_renderer *)ec->renderer;
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
static struct egl_image*
egl_image_create(struct gl_renderer *gr, EGLenum target,
		 EGLClientBuffer buffer, const EGLint *attribs)
{
	struct egl_image *img;

	img = zalloc(sizeof *img);
	img->renderer = gr;
	img->refcount = 1;
	img->image = gr->create_image(gr->egl_display, EGL_NO_CONTEXT,
				      target, buffer, attribs);

	if (img->image == EGL_NO_IMAGE_KHR) {
		free(img);
		return NULL;
	}

	return img;
}

static struct egl_image*
egl_image_ref(struct egl_image *image)
{
	image->refcount++;

	return image;
}

static int
egl_image_unref(struct egl_image *image)
{
	struct gl_renderer *gr = image->renderer;

	assert(image->refcount > 0);

	image->refcount--;
	if (image->refcount > 0)
		return image->refcount;

	gr->destroy_image(gr->egl_display, image->image);
	free(image);

	return 0;
}

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
static struct dmabuf_image*
dmabuf_image_create(void)
{
	struct dmabuf_image *img;

	img = zalloc(sizeof *img);
	wl_list_init(&img->link);

	return img;
}

static void
dmabuf_image_destroy(struct dmabuf_image *image)
{
	int i;

	for (i = 0; i < image->num_images; ++i)
		egl_image_unref(image->images[i]);

	if (image->dmabuf)
		linux_dmabuf_buffer_set_user_data(image->dmabuf, NULL, NULL);

	wl_list_remove(&image->link);
}

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
static const char *
egl_error_string(EGLint code)
{
#define MYERRCODE(x) case x: return #x;
	switch (code) {
	MYERRCODE(EGL_SUCCESS)
	MYERRCODE(EGL_NOT_INITIALIZED)
	MYERRCODE(EGL_BAD_ACCESS)
	MYERRCODE(EGL_BAD_ALLOC)
	MYERRCODE(EGL_BAD_ATTRIBUTE)
	MYERRCODE(EGL_BAD_CONTEXT)
	MYERRCODE(EGL_BAD_CONFIG)
	MYERRCODE(EGL_BAD_CURRENT_SURFACE)
	MYERRCODE(EGL_BAD_DISPLAY)
	MYERRCODE(EGL_BAD_SURFACE)
	MYERRCODE(EGL_BAD_MATCH)
	MYERRCODE(EGL_BAD_PARAMETER)
	MYERRCODE(EGL_BAD_NATIVE_PIXMAP)
	MYERRCODE(EGL_BAD_NATIVE_WINDOW)
	MYERRCODE(EGL_CONTEXT_LOST)
	default:
		return "unknown";
	}
#undef MYERRCODE
}

362
static void
363
gl_renderer_print_egl_error_state(void)
364 365 366 367 368 369 370 371
{
	EGLint code;

	code = eglGetError();
	weston_log("EGL error state: %s (0x%04lx)\n",
		egl_error_string(code), (long)code);
}

372 373 374
#define max(a, b) (((a) > (b)) ? (a) : (b))
#define min(a, b) (((a) > (b)) ? (b) : (a))

375 376 377 378 379 380 381 382 383
/*
 * Compute the boundary vertices of the intersection of the global coordinate
 * aligned rectangle 'rect', and an arbitrary quadrilateral produced from
 * 'surf_rect' when transformed from surface coordinates into global coordinates.
 * The vertices are written to 'ex' and 'ey', and the return value is the
 * number of vertices. Vertices are produced in clockwise winding order.
 * Guarantees to produce either zero vertices, or 3-8 vertices with non-zero
 * polygon area.
 */
384
static int
385
calculate_edges(struct weston_view *ev, pixman_box32_t *rect,
386 387
		pixman_box32_t *surf_rect, GLfloat *ex, GLfloat *ey)
{
388

389 390
	struct clip_context ctx;
	int i, n;
391
	GLfloat min_x, max_x, min_y, max_y;
392 393 394 395
	struct polygon8 surf = {
		{ surf_rect->x1, surf_rect->x2, surf_rect->x2, surf_rect->x1 },
		{ surf_rect->y1, surf_rect->y1, surf_rect->y2, surf_rect->y2 },
		4
396 397
	};

398 399 400 401
	ctx.clip.x1 = rect->x1;
	ctx.clip.y1 = rect->y1;
	ctx.clip.x2 = rect->x2;
	ctx.clip.y2 = rect->y2;
402 403

	/* transform surface to screen space: */
404
	for (i = 0; i < surf.n; i++)
405 406
		weston_view_to_global_float(ev, surf.x[i], surf.y[i],
					    &surf.x[i], &surf.y[i]);
407 408

	/* find bounding box: */
409 410 411 412 413 414 415 416
	min_x = max_x = surf.x[0];
	min_y = max_y = surf.y[0];

	for (i = 1; i < surf.n; i++) {
		min_x = min(min_x, surf.x[i]);
		max_x = max(max_x, surf.x[i]);
		min_y = min(min_y, surf.y[i]);
		max_y = max(max_y, surf.y[i]);
417 418 419 420 421
	}

	/* First, simple bounding box check to discard early transformed
	 * surface rects that do not intersect with the clip region:
	 */
422 423
	if ((min_x >= ctx.clip.x2) || (max_x <= ctx.clip.x1) ||
	    (min_y >= ctx.clip.y2) || (max_y <= ctx.clip.y1))
424 425 426 427 428 429
		return 0;

	/* Simple case, bounding box edges are parallel to surface edges,
	 * there will be only four edges.  We just need to clip the surface
	 * vertices to the clip rect bounds:
	 */
430
	if (!ev->transform.enabled)
431
		return clip_simple(&ctx, &surf, ex, ey);
432

433 434 435 436 437
	/* Transformed case: use a general polygon clipping algorithm to
	 * clip the surface rectangle with each side of 'rect'.
	 * The algorithm is Sutherland-Hodgman, as explained in
	 * http://www.codeguru.com/cpp/misc/misc/graphics/article.php/c8965/Polygon-Clipping.htm
	 * but without looking at any of that code.
438
	 */
439
	n = clip_transformed(&ctx, &surf, ex, ey);
440 441 442

	if (n < 3)
		return 0;
443 444 445 446

	return n;
}

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
static bool
merge_down(pixman_box32_t *a, pixman_box32_t *b, pixman_box32_t *merge)
{
	if (a->x1 == b->x1 && a->x2 == b->x2 && a->y1 == b->y2) {
		merge->x1 = a->x1;
		merge->x2 = a->x2;
		merge->y1 = b->y1;
		merge->y2 = a->y2;
		return true;
	}
	return false;
}

static int
compress_bands(pixman_box32_t *inrects, int nrects,
		   pixman_box32_t **outrects)
{
464
	bool merged = false;
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
	pixman_box32_t *out, merge_rect;
	int i, j, nout;

	if (!nrects) {
		*outrects = NULL;
		return 0;
	}

	/* nrects is an upper bound - we're not too worried about
	 * allocating a little extra
	 */
	out = malloc(sizeof(pixman_box32_t) * nrects);
	out[0] = inrects[0];
	nout = 1;
	for (i = 1; i < nrects; i++) {
		for (j = 0; j < nout; j++) {
			merged = merge_down(&inrects[i], &out[j], &merge_rect);
			if (merged) {
				out[j] = merge_rect;
				break;
			}
		}
		if (!merged) {
			out[nout] = inrects[i];
			nout++;
		}
	}
	*outrects = out;
	return nout;
}

496
static int
497
texture_region(struct weston_view *ev, pixman_region32_t *region,
498 499
		pixman_region32_t *surf_region)
{
500 501
	struct gl_surface_state *gs = get_surface_state(ev->surface);
	struct weston_compositor *ec = ev->surface->compositor;
502
	struct gl_renderer *gr = get_renderer(ec);
503 504 505
	GLfloat *v, inv_width, inv_height;
	unsigned int *vtxcnt, nvtx = 0;
	pixman_box32_t *rects, *surf_rects;
506 507 508 509
	pixman_box32_t *raw_rects;
	int i, j, k, nrects, nsurf, raw_nrects;
	bool used_band_compression;
	raw_rects = pixman_region32_rectangles(region, &raw_nrects);
510 511
	surf_rects = pixman_region32_rectangles(surf_region, &nsurf);

512 513 514 515 516 517 518 519
	if (raw_nrects < 4) {
		used_band_compression = false;
		nrects = raw_nrects;
		rects = raw_rects;
	} else {
		nrects = compress_bands(raw_rects, raw_nrects, &rects);
		used_band_compression = true;
	}
520 521 522
	/* worst case we can have 8 vertices per rect (ie. clipped into
	 * an octagon):
	 */
523 524
	v = wl_array_add(&gr->vertices, nrects * nsurf * 8 * 4 * sizeof *v);
	vtxcnt = wl_array_add(&gr->vtxcnt, nrects * nsurf * sizeof *vtxcnt);
525

526
	inv_width = 1.0 / gs->pitch;
527
        inv_height = 1.0 / gs->height;
528 529 530 531 532

	for (i = 0; i < nrects; i++) {
		pixman_box32_t *rect = &rects[i];
		for (j = 0; j < nsurf; j++) {
			pixman_box32_t *surf_rect = &surf_rects[j];
533
			GLfloat sx, sy, bx, by;
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
			GLfloat ex[8], ey[8];          /* edge points in screen space */
			int n;

			/* The transformed surface, after clipping to the clip region,
			 * can have as many as eight sides, emitted as a triangle-fan.
			 * The first vertex in the triangle fan can be chosen arbitrarily,
			 * since the area is guaranteed to be convex.
			 *
			 * If a corner of the transformed surface falls outside of the
			 * clip region, instead of emitting one vertex for the corner
			 * of the surface, up to two are emitted for two corresponding
			 * intersection point(s) between the surface and the clip region.
			 *
			 * To do this, we first calculate the (up to eight) points that
			 * form the intersection of the clip rect and the transformed
			 * surface.
			 */
551
			n = calculate_edges(ev, rect, surf_rect, ex, ey);
552 553 554 555 556
			if (n < 3)
				continue;

			/* emit edge points: */
			for (k = 0; k < n; k++) {
557 558
				weston_view_from_global_float(ev, ex[k], ey[k],
							      &sx, &sy);
559 560 561 562
				/* position: */
				*(v++) = ex[k];
				*(v++) = ey[k];
				/* texcoord: */
563 564
				weston_surface_to_buffer_float(ev->surface,
							       sx, sy,
565 566
							       &bx, &by);
				*(v++) = bx * inv_width;
567 568 569 570 571
				if (gs->y_inverted) {
					*(v++) = by * inv_height;
				} else {
					*(v++) = (gs->height - by) * inv_height;
				}
572 573 574 575 576 577
			}

			vtxcnt[nvtx++] = n;
		}
	}

578 579
	if (used_band_compression)
		free(rects);
580 581 582 583
	return nvtx;
}

static void
584
triangle_fan_debug(struct weston_view *view, int first, int count)
585
{
586
	struct weston_compositor *compositor = view->surface->compositor;
587
	struct gl_renderer *gr = get_renderer(compositor);
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
	int i;
	GLushort *buffer;
	GLushort *index;
	int nelems;
	static int color_idx = 0;
	static const GLfloat color[][4] = {
			{ 1.0, 0.0, 0.0, 1.0 },
			{ 0.0, 1.0, 0.0, 1.0 },
			{ 0.0, 0.0, 1.0, 1.0 },
			{ 1.0, 1.0, 1.0, 1.0 },
	};

	nelems = (count - 1 + count - 2) * 2;

	buffer = malloc(sizeof(GLushort) * nelems);
	index = buffer;

	for (i = 1; i < count; i++) {
		*index++ = first;
		*index++ = first + i;
	}

	for (i = 2; i < count; i++) {
		*index++ = first + i - 1;
		*index++ = first + i;
	}

615 616
	glUseProgram(gr->solid_shader.program);
	glUniform4fv(gr->solid_shader.color_uniform, 1,
617 618
			color[color_idx++ % ARRAY_LENGTH(color)]);
	glDrawElements(GL_LINES, nelems, GL_UNSIGNED_SHORT, buffer);
619
	glUseProgram(gr->current_shader->program);
620 621 622 623
	free(buffer);
}

static void
624
repaint_region(struct weston_view *ev, pixman_region32_t *region,
625 626
		pixman_region32_t *surf_region)
{
627
	struct weston_compositor *ec = ev->surface->compositor;
628
	struct gl_renderer *gr = get_renderer(ec);
629 630 631 632 633 634 635 636 637 638
	GLfloat *v;
	unsigned int *vtxcnt;
	int i, first, nfans;

	/* The final region to be painted is the intersection of
	 * 'region' and 'surf_region'. However, 'region' is in the global
	 * coordinates, and 'surf_region' is in the surface-local
	 * coordinates. texture_region() will iterate over all pairs of
	 * rectangles from both regions, compute the intersection
	 * polygon for each pair, and store it as a triangle fan if
639
	 * it has a non-zero area (at least 3 vertices, actually).
640
	 */
641
	nfans = texture_region(ev, region, surf_region);
642

643 644
	v = gr->vertices.data;
	vtxcnt = gr->vtxcnt.data;
645 646 647 648 649 650 651 652 653 654 655

	/* position: */
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof *v, &v[0]);
	glEnableVertexAttribArray(0);

	/* texcoord: */
	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof *v, &v[2]);
	glEnableVertexAttribArray(1);

	for (i = 0, first = 0; i < nfans; i++) {
		glDrawArrays(GL_TRIANGLE_FAN, first, vtxcnt[i]);
656
		if (gr->fan_debug)
657
			triangle_fan_debug(ev, first, vtxcnt[i]);
658 659 660 661 662 663
		first += vtxcnt[i];
	}

	glDisableVertexAttribArray(1);
	glDisableVertexAttribArray(0);

664 665
	gr->vertices.size = 0;
	gr->vtxcnt.size = 0;
666 667
}

668 669 670 671
static int
use_output(struct weston_output *output)
{
	static int errored;
672 673
	struct gl_output_state *go = get_output_state(output);
	struct gl_renderer *gr = get_renderer(output->compositor);
674 675 676 677 678 679 680 681 682 683
	EGLBoolean ret;

	ret = eglMakeCurrent(gr->egl_display, go->egl_surface,
			     go->egl_surface, gr->egl_context);

	if (ret == EGL_FALSE) {
		if (errored)
			return -1;
		errored = 1;
		weston_log("Failed to make EGL context current.\n");
684
		gl_renderer_print_egl_error_state();
685 686 687 688 689 690
		return -1;
	}

	return 0;
}

691 692 693 694
static int
shader_init(struct gl_shader *shader, struct gl_renderer *gr,
		   const char *vertex_source, const char *fragment_source);

695
static void
696
use_shader(struct gl_renderer *gr, struct gl_shader *shader)
697
{
698 699 700 701 702 703 704 705 706 707 708
	if (!shader->program) {
		int ret;

		ret =  shader_init(shader, gr,
				   shader->vertex_source,
				   shader->fragment_source);

		if (ret < 0)
			weston_log("warning: failed to compile shader\n");
	}

709
	if (gr->current_shader == shader)
710 711
		return;
	glUseProgram(shader->program);
712
	gr->current_shader = shader;
713 714 715
}

static void
716
shader_uniforms(struct gl_shader *shader,
717 718
		struct weston_view *view,
		struct weston_output *output)
719 720
{
	int i;
721
	struct gl_surface_state *gs = get_surface_state(view->surface);
722
	struct gl_output_state *go = get_output_state(output);
723 724

	glUniformMatrix4fv(shader->proj_uniform,
725
			   1, GL_FALSE, go->output_matrix.d);
726
	glUniform4fv(shader->color_uniform, 1, gs->color);
727
	glUniform1f(shader->alpha_uniform, view->alpha);
728

729
	for (i = 0; i < gs->num_textures; i++)
730 731 732 733
		glUniform1i(shader->tex_uniforms[i], i);
}

static void
734 735
draw_view(struct weston_view *ev, struct weston_output *output,
	  pixman_region32_t *damage) /* in global coordinates */
736
{
737
	struct weston_compositor *ec = ev->surface->compositor;
738
	struct gl_renderer *gr = get_renderer(ec);
739
	struct gl_surface_state *gs = get_surface_state(ev->surface);
740 741
	/* repaint bounding region in global coordinates: */
	pixman_region32_t repaint;
742 743
	/* opaque region in surface coordinates: */
	pixman_region32_t surface_opaque;
744 745 746 747 748
	/* non-opaque region in surface coordinates: */
	pixman_region32_t surface_blend;
	GLint filter;
	int i;

749 750 751 752 753 754
	/* In case of a runtime switch of renderers, we may not have received
	 * an attach for this surface since the switch. In that case we don't
	 * have a valid buffer or a proper shader set up so skip rendering. */
	if (!gs->shader)
		return;

755 756
	pixman_region32_init(&repaint);
	pixman_region32_intersect(&repaint,
757
				  &ev->transform.boundingbox, damage);
758
	pixman_region32_subtract(&repaint, &repaint, &ev->clip);
759 760 761 762 763 764

	if (!pixman_region32_not_empty(&repaint))
		goto out;

	glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

765
	if (gr->fan_debug) {
766
		use_shader(gr, &gr->solid_shader);
767
		shader_uniforms(&gr->solid_shader, ev, output);
768 769
	}

770
	use_shader(gr, gs->shader);
771
	shader_uniforms(gs->shader, ev, output);
772

773
	if (ev->transform.enabled || output->zoom.active ||
774
	    output->current_scale != ev->surface->buffer_viewport.buffer.scale)
775 776 777 778
		filter = GL_LINEAR;
	else
		filter = GL_NEAREST;

779
	for (i = 0; i < gs->num_textures; i++) {
780
		glActiveTexture(GL_TEXTURE0 + i);
781 782 783
		glBindTexture(gs->target, gs->textures[i]);
		glTexParameteri(gs->target, GL_TEXTURE_MIN_FILTER, filter);
		glTexParameteri(gs->target, GL_TEXTURE_MAG_FILTER, filter);
784 785 786 787
	}

	/* blended region is whole surface minus opaque region: */
	pixman_region32_init_rect(&surface_blend, 0, 0,
788
				  ev->surface->width, ev->surface->height);
789 790 791 792 793
	if (ev->geometry.scissor_enabled)
		pixman_region32_intersect(&surface_blend, &surface_blend,
					  &ev->geometry.scissor);
	pixman_region32_subtract(&surface_blend, &surface_blend,
				 &ev->surface->opaque);
794

795
	/* XXX: Should we be using ev->transform.opaque here? */
796 797 798 799 800 801 802 803 804
	pixman_region32_init(&surface_opaque);
	if (ev->geometry.scissor_enabled)
		pixman_region32_intersect(&surface_opaque,
					  &ev->surface->opaque,
					  &ev->geometry.scissor);
	else
		pixman_region32_copy(&surface_opaque, &ev->surface->opaque);

	if (pixman_region32_not_empty(&surface_opaque)) {
805
		if (gs->shader == &gr->texture_shader_rgba) {
806 807 808 809 810
			/* Special case for RGBA textures with possibly
			 * bad data in alpha channel: use the shader
			 * that forces texture alpha = 1.0.
			 * Xwayland surfaces need this.
			 */
811
			use_shader(gr, &gr->texture_shader_rgbx);
812
			shader_uniforms(&gr->texture_shader_rgbx, ev, output);
813 814
		}

815
		if (ev->alpha < 1.0)
816 817 818 819
			glEnable(GL_BLEND);
		else
			glDisable(GL_BLEND);

820
		repaint_region(ev, &repaint, &surface_opaque);
821 822 823
	}

	if (pixman_region32_not_empty(&surface_blend)) {
824
		use_shader(gr, gs->shader);
825
		glEnable(GL_BLEND);
826
		repaint_region(ev, &repaint, &surface_blend);
827 828 829
	}

	pixman_region32_fini(&surface_blend);
830
	pixman_region32_fini(&surface_opaque);
831 832 833 834 835

out:
	pixman_region32_fini(&repaint);
}

836
static void
837
repaint_views(struct weston_output *output, pixman_region32_t *damage)
838 839
{
	struct weston_compositor *compositor = output->compositor;
840
	struct weston_view *view;
841

842 843 844
	wl_list_for_each_reverse(view, &compositor->view_list, link)
		if (view->plane == &compositor->primary_plane)
			draw_view(view, output, damage);
845 846
}

847
static void
848 849 850
draw_output_border_texture(struct gl_output_state *go,
			   enum gl_renderer_border_side side,
			   int32_t x, int32_t y,
851 852
			   int32_t width, int32_t height)
{
853
	struct gl_border_image *img = &go->borders[side];
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
	static GLushort indices [] = { 0, 1, 3, 3, 1, 2 };

	if (!img->data) {
		if (img->tex) {
			glDeleteTextures(1, &img->tex);
			img->tex = 0;
		}

		return;
	}

	if (!img->tex) {
		glGenTextures(1, &img->tex);
		glBindTexture(GL_TEXTURE_2D, img->tex);

		glTexParameteri(GL_TEXTURE_2D,
				GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D,
				GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D,
				GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D,
				GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	} else {
		glBindTexture(GL_TEXTURE_2D, img->tex);
	}

881
	if (go->border_status & (1 << side)) {
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
		glPixelStorei(GL_UNPACK_ROW_LENGTH_EXT, 0);
		glPixelStorei(GL_UNPACK_SKIP_PIXELS_EXT, 0);
		glPixelStorei(GL_UNPACK_SKIP_ROWS_EXT, 0);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA_EXT,
			     img->tex_width, img->height, 0,
			     GL_BGRA_EXT, GL_UNSIGNED_BYTE, img->data);
	}

	GLfloat texcoord[] = {
		0.0f, 0.0f,
		(GLfloat)img->width / (GLfloat)img->tex_width, 0.0f,
		(GLfloat)img->width / (GLfloat)img->tex_width, 1.0f,
		0.0f, 1.0f,
	};

	GLfloat verts[] = {
		x, y,
		x + width, y,
		x + width, y + height,
		x, y + height
	};

	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, verts);
	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, texcoord);
	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);

	glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices);

	glDisableVertexAttribArray(1);
	glDisableVertexAttribArray(0);
}

915 916 917 918 919 920 921 922 923 924 925
static int
output_has_borders(struct weston_output *output)
{
	struct gl_output_state *go = get_output_state(output);

	return go->borders[GL_RENDERER_BORDER_TOP].data ||
	       go->borders[GL_RENDERER_BORDER_RIGHT].data ||
	       go->borders[GL_RENDERER_BORDER_BOTTOM].data ||
	       go->borders[GL_RENDERER_BORDER_LEFT].data;
}

926
static void
927 928
draw_output_borders(struct weston_output *output,
		    enum gl_border_status border_status)
929 930 931 932
{
	struct gl_output_state *go = get_output_state(output);
	struct gl_renderer *gr = get_renderer(output->compositor);
	struct gl_shader *shader = &gr->texture_shader_rgba;
933 934 935 936
	struct gl_border_image *top, *bottom, *left, *right;
	struct weston_matrix matrix;
	int full_width, full_height;

937 938 939
	if (border_status == BORDER_STATUS_CLEAN)
		return; /* Clean. Nothing to do. */

940 941 942 943 944 945 946
	top = &go->borders[GL_RENDERER_BORDER_TOP];
	bottom = &go->borders[GL_RENDERER_BORDER_BOTTOM];
	left = &go->borders[GL_RENDERER_BORDER_LEFT];
	right = &go->borders[GL_RENDERER_BORDER_RIGHT];

	full_width = output->current_mode->width + left->width + right->width;
	full_height = output->current_mode->height + top->height + bottom->height;
947 948 949 950

	glDisable(GL_BLEND);
	use_shader(gr, shader);

951 952 953 954 955 956
	glViewport(0, 0, full_width, full_height);

	weston_matrix_init(&matrix);
	weston_matrix_translate(&matrix, -full_width/2.0, -full_height/2.0, 0);
	weston_matrix_scale(&matrix, 2.0/full_width, -2.0/full_height, 1);
	glUniformMatrix4fv(shader->proj_uniform, 1, GL_FALSE, matrix.d);
957 958 959 960 961

	glUniform1i(shader->tex_uniforms[0], 0);
	glUniform1f(shader->alpha_uniform, 1);
	glActiveTexture(GL_TEXTURE0);

962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
	if (border_status & BORDER_TOP_DIRTY)
		draw_output_border_texture(go, GL_RENDERER_BORDER_TOP,
					   0, 0,
					   full_width, top->height);
	if (border_status & BORDER_LEFT_DIRTY)
		draw_output_border_texture(go, GL_RENDERER_BORDER_LEFT,
					   0, top->height,
					   left->width, output->current_mode->height);
	if (border_status & BORDER_RIGHT_DIRTY)
		draw_output_border_texture(go, GL_RENDERER_BORDER_RIGHT,
					   full_width - right->width, top->height,
					   right->width, output->current_mode->height);
	if (border_status & BORDER_BOTTOM_DIRTY)
		draw_output_border_texture(go, GL_RENDERER_BORDER_BOTTOM,
					   0, full_height - bottom->height,
					   full_width, bottom->height);
978
}
979

980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
static void
output_get_border_damage(struct weston_output *output,
			 enum gl_border_status border_status,
			 pixman_region32_t *damage)
{
	struct gl_output_state *go = get_output_state(output);
	struct gl_border_image *top, *bottom, *left, *right;
	int full_width, full_height;

	if (border_status == BORDER_STATUS_CLEAN)
		return; /* Clean. Nothing to do. */

	top = &go->borders[GL_RENDERER_BORDER_TOP];
	bottom = &go->borders[GL_RENDERER_BORDER_BOTTOM];
	left = &go->borders[GL_RENDERER_BORDER_LEFT];
	right = &go->borders[GL_RENDERER_BORDER_RIGHT];

	full_width = output->current_mode->width + left->width + right->width;
	full_height = output->current_mode->height + top->height + bottom->height;
	if (border_status & BORDER_TOP_DIRTY)
		pixman_region32_union_rect(damage, damage,
					   0, 0,
					   full_width, top->height);
	if (border_status & BORDER_LEFT_DIRTY)
		pixman_region32_union_rect(damage, damage,
					   0, top->height,
					   left->width, output->current_mode->height);
	if (border_status & BORDER_RIGHT_DIRTY)
		pixman_region32_union_rect(damage, damage,
					   full_width - right->width, top->height,
					   right->width, output->current_mode->height);
	if (border_status & BORDER_BOTTOM_DIRTY)
		pixman_region32_union_rect(damage, damage,
					   0, full_height - bottom->height,
					   full_width, bottom->height);
}

1017
static void
1018 1019
output_get_damage(struct weston_output *output,
		  pixman_region32_t *buffer_damage, uint32_t *border_damage)
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
{
	struct gl_output_state *go = get_output_state(output);
	struct gl_renderer *gr = get_renderer(output->compositor);
	EGLint buffer_age = 0;
	EGLBoolean ret;
	int i;

	if (gr->has_egl_buffer_age) {
		ret = eglQuerySurface(gr->egl_display, go->egl_surface,
				      EGL_BUFFER_AGE_EXT, &buffer_age);
		if (ret == EGL_FALSE) {
			weston_log("buffer age query failed.\n");
			gl_renderer_print_egl_error_state();
		}
	}

1036
	if (buffer_age == 0 || buffer_age - 1 > BUFFER_DAMAGE_COUNT) {
1037
		pixman_region32_copy(buffer_damage, &output->region);
1038 1039
		*border_damage = BORDER_ALL_DIRTY;
	} else {
1040
		for (i = 0; i < buffer_age - 1; i++)
1041
			*border_damage |= go->border_damage[(go->buffer_damage_index + i) % BUFFER_DAMAGE_COUNT];
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051

		if (*border_damage & BORDER_SIZE_CHANGED) {
			/* If we've had a resize, we have to do a full
			 * repaint. */
			*border_damage |= BORDER_ALL_DIRTY;
			pixman_region32_copy(buffer_damage, &output->region);
		} else {
			for (i = 0; i < buffer_age - 1; i++)
				pixman_region32_union(buffer_damage,
						      buffer_damage,
1052
						      &go->buffer_damage[(go->buffer_damage_index + i) % BUFFER_DAMAGE_COUNT]);
1053 1054
		}
	}
1055 1056 1057 1058
}

static void
output_rotate_damage(struct weston_output *output,
1059 1060
		     pixman_region32_t *output_damage,
		     enum gl_border_status border_status)
1061 1062 1063 1064 1065 1066 1067
{
	struct gl_output_state *go = get_output_state(output);
	struct gl_renderer *gr = get_renderer(output->compositor);

	if (!gr->has_egl_buffer_age)
		return;

1068 1069
	go->buffer_damage_index += BUFFER_DAMAGE_COUNT - 1;
	go->buffer_damage_index %= BUFFER_DAMAGE_COUNT;
1070

1071 1072
	pixman_region32_copy(&go->buffer_damage[go->buffer_damage_index], output_damage);
	go->border_damage[go->buffer_damage_index] = border_status;
1073 1074
}

1075 1076 1077 1078 1079 1080 1081 1082
/* NOTE: We now allow falling back to ARGB gl visuals when XRGB is
 * unavailable, so we're assuming the background has no transparency
 * and that everything with a blend, like drop shadows, will have something
 * opaque (like the background) drawn underneath it.
 *
 * Depending on the underlying hardware, violating that assumption could
 * result in seeing through to another display plane.
 */
1083
static void
1084
gl_renderer_repaint_output(struct weston_output *output,
1085 1086
			      pixman_region32_t *output_damage)
{
1087
	struct gl_output_state *go = get_output_state(output);
1088
	struct weston_compositor *compositor = output->compositor;
1089
	struct gl_renderer *gr = get_renderer(compositor);
1090 1091
	EGLBoolean ret;
	static int errored;
1092 1093 1094
	int i, nrects, buffer_height;
	EGLint *egl_damage, *d;
	pixman_box32_t *rects;
1095
	pixman_region32_t buffer_damage, total_damage;
1096
	enum gl_border_status border_damage = BORDER_STATUS_CLEAN;
1097

1098 1099 1100
	if (use_output(output) < 0)
		return;

1101 1102 1103 1104 1105
	/* Calculate the viewport */
	glViewport(go->borders[GL_RENDERER_BORDER_LEFT].width,
		   go->borders[GL_RENDERER_BORDER_BOTTOM].height,
		   output->current_mode->width,
		   output->current_mode->height);
1106

1107 1108 1109 1110 1111 1112 1113 1114 1115
	/* Calculate the global GL matrix */
	go->output_matrix = output->matrix;
	weston_matrix_translate(&go->output_matrix,
				-(output->current_mode->width / 2.0),
				-(output->current_mode->height / 2.0), 0);
	weston_matrix_scale(&go->output_matrix,
			    2.0 / output->current_mode->width,
			    -2.0 / output->current_mode->height, 1);

1116 1117 1118
	/* if debugging, redraw everything outside the damage to clean up
	 * debug lines from the previous draw on this buffer:
	 */
1119
	if (gr->fan_debug) {
1120 1121 1122 1123
		pixman_region32_t undamaged;
		pixman_region32_init(&undamaged);
		pixman_region32_subtract(&undamaged, &output->region,
					 output_damage);
1124
		gr->fan_debug = 0;
1125
		repaint_views(output, &undamaged);
1126
		gr->fan_debug = 1;
1127 1128 1129
		pixman_region32_fini(&undamaged);
	}

1130
	pixman_region32_init(&total_damage);
1131 1132
	pixman_region32_init(&buffer_damage);

1133 1134
	output_get_damage(output, &buffer_damage, &border_damage);
	output_rotate_damage(output, output_damage, go->border_status);
1135 1136

	pixman_region32_union(&total_damage, &buffer_damage, output_damage);
1137
	border_damage |= go->border_status;
1138

1139
	repaint_views(output, &total_damage);