gl-renderer.c 92.7 KB
Newer Older
1 2
/*
 * Copyright © 2012 Intel Corporation
3
 * Copyright © 2015 Collabora, Ltd.
4
 * Copyright © 2016 NVIDIA Corporation
5
 *
6 7 8 9 10 11 12
 * 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:
13
 *
14 15 16 17 18 19 20 21 22 23 24 25
 * 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.
26 27
 */

28
#include "config.h"
29

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

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

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

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

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

62 63
#define BUFFER_DAMAGE_COUNT 2

64 65 66 67 68 69 70 71 72 73
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
};

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

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

	struct weston_matrix output_matrix;
90 91
};

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

99 100 101 102 103 104
struct gl_renderer;

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

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

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

	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];
137 138
};

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

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

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

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

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

164 165
	/* Extension needed for SHM YUV texture */
	int offset[3]; /* offset per plane */
166 167
	int hsub[3];  /* horizontal subsampling per plane */
	int vsub[3];  /* vertical subsampling per plane */
168

169 170 171
	struct weston_surface *surface;

	struct wl_listener surface_destroy_listener;
172
	struct wl_listener renderer_destroy_listener;
173 174
};

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

182 183 184
	EGLDisplay egl_display;
	EGLContext egl_context;
	EGLConfig egl_config;
185

186 187
	EGLSurface dummy_surface;

188 189 190
	struct wl_array vertices;
	struct wl_array vtxcnt;

191 192 193
	PFNGLEGLIMAGETARGETTEXTURE2DOESPROC image_target_texture_2d;
	PFNEGLCREATEIMAGEKHRPROC create_image;
	PFNEGLDESTROYIMAGEKHRPROC destroy_image;
194
	PFNEGLSWAPBUFFERSWITHDAMAGEEXTPROC swap_buffers_with_damage;
195 196
	PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC create_platform_window;

197 198 199 200 201 202 203 204 205
	int has_unpack_subimage;

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

	int has_egl_image_external;

206 207
	int has_egl_buffer_age;

208 209
	int has_configless_context;

210 211
	int has_surfaceless_context;

212 213 214
	int has_dmabuf_import;
	struct wl_list dmabuf_images;

215 216
	int has_gl_texture_rg;

217 218 219 220 221 222 223 224 225
	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;
226 227

	struct wl_signal destroy_signal;
228 229

	struct wl_listener output_destroy_listener;
230 231 232 233

	int has_dmabuf_import_modifiers;
	PFNEGLQUERYDMABUFFORMATSEXTPROC query_dmabuf_formats;
	PFNEGLQUERYDMABUFMODIFIERSEXTPROC query_dmabuf_modifiers;
234 235
};

236 237
static PFNEGLGETPLATFORMDISPLAYEXTPROC get_platform_display = NULL;

238 239 240 241 242 243 244 245 246 247
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;
}

248
static inline struct gl_output_state *
249 250
get_output_state(struct weston_output *output)
{
251
	return (struct gl_output_state *)output->renderer_state;
252 253
}

254 255 256
static int
gl_renderer_create_surface(struct weston_surface *surface);

257
static inline struct gl_surface_state *
258 259
get_surface_state(struct weston_surface *surface)
{
260 261 262
	if (!surface->renderer_state)
		gl_renderer_create_surface(surface);

263
	return (struct gl_surface_state *)surface->renderer_state;
264 265
}

266
static inline struct gl_renderer *
267 268
get_renderer(struct weston_compositor *ec)
{
269
	return (struct gl_renderer *)ec->renderer;
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
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;
}

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
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);
}

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
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
}

368
static void
369
gl_renderer_print_egl_error_state(void)
370 371 372 373 374 375 376 377
{
	EGLint code;

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

378 379 380
#define max(a, b) (((a) > (b)) ? (a) : (b))
#define min(a, b) (((a) > (b)) ? (b) : (a))

381 382 383 384 385 386 387 388 389
/*
 * 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.
 */
390
static int
391
calculate_edges(struct weston_view *ev, pixman_box32_t *rect,
392 393
		pixman_box32_t *surf_rect, GLfloat *ex, GLfloat *ey)
{
394

395 396
	struct clip_context ctx;
	int i, n;
397
	GLfloat min_x, max_x, min_y, max_y;
398 399 400 401
	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
402 403
	};

404 405 406 407
	ctx.clip.x1 = rect->x1;
	ctx.clip.y1 = rect->y1;
	ctx.clip.x2 = rect->x2;
	ctx.clip.y2 = rect->y2;
408 409

	/* transform surface to screen space: */
410
	for (i = 0; i < surf.n; i++)
411 412
		weston_view_to_global_float(ev, surf.x[i], surf.y[i],
					    &surf.x[i], &surf.y[i]);
413 414

	/* find bounding box: */
415 416 417 418 419 420 421 422
	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]);
423 424 425 426 427
	}

	/* First, simple bounding box check to discard early transformed
	 * surface rects that do not intersect with the clip region:
	 */
428 429
	if ((min_x >= ctx.clip.x2) || (max_x <= ctx.clip.x1) ||
	    (min_y >= ctx.clip.y2) || (max_y <= ctx.clip.y1))
430 431 432 433 434 435
		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:
	 */
436
	if (!ev->transform.enabled)
437
		return clip_simple(&ctx, &surf, ex, ey);
438

439 440 441 442 443
	/* 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.
444
	 */
445
	n = clip_transformed(&ctx, &surf, ex, ey);
446 447 448

	if (n < 3)
		return 0;
449 450 451 452

	return n;
}

453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
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)
{
470
	bool merged = false;
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
	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;
}

502
static int
503
texture_region(struct weston_view *ev, pixman_region32_t *region,
504 505
		pixman_region32_t *surf_region)
{
506 507
	struct gl_surface_state *gs = get_surface_state(ev->surface);
	struct weston_compositor *ec = ev->surface->compositor;
508
	struct gl_renderer *gr = get_renderer(ec);
509 510 511
	GLfloat *v, inv_width, inv_height;
	unsigned int *vtxcnt, nvtx = 0;
	pixman_box32_t *rects, *surf_rects;
512 513 514 515
	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);
516 517
	surf_rects = pixman_region32_rectangles(surf_region, &nsurf);

518 519 520 521 522 523 524 525
	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;
	}
526 527 528
	/* worst case we can have 8 vertices per rect (ie. clipped into
	 * an octagon):
	 */
529 530
	v = wl_array_add(&gr->vertices, nrects * nsurf * 8 * 4 * sizeof *v);
	vtxcnt = wl_array_add(&gr->vtxcnt, nrects * nsurf * sizeof *vtxcnt);
531

532
	inv_width = 1.0 / gs->pitch;
533
        inv_height = 1.0 / gs->height;
534 535 536 537 538

	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];
539
			GLfloat sx, sy, bx, by;
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
			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.
			 */
557
			n = calculate_edges(ev, rect, surf_rect, ex, ey);
558 559 560 561 562
			if (n < 3)
				continue;

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

			vtxcnt[nvtx++] = n;
		}
	}

584 585
	if (used_band_compression)
		free(rects);
586 587 588 589
	return nvtx;
}

static void
590
triangle_fan_debug(struct weston_view *view, int first, int count)
591
{
592
	struct weston_compositor *compositor = view->surface->compositor;
593
	struct gl_renderer *gr = get_renderer(compositor);
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
	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;
	}

621 622
	glUseProgram(gr->solid_shader.program);
	glUniform4fv(gr->solid_shader.color_uniform, 1,
623 624
			color[color_idx++ % ARRAY_LENGTH(color)]);
	glDrawElements(GL_LINES, nelems, GL_UNSIGNED_SHORT, buffer);
625
	glUseProgram(gr->current_shader->program);
626 627 628 629
	free(buffer);
}

static void
630
repaint_region(struct weston_view *ev, pixman_region32_t *region,
631 632
		pixman_region32_t *surf_region)
{
633
	struct weston_compositor *ec = ev->surface->compositor;
634
	struct gl_renderer *gr = get_renderer(ec);
635 636 637 638 639 640 641 642 643 644
	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
645
	 * it has a non-zero area (at least 3 vertices, actually).
646
	 */
647
	nfans = texture_region(ev, region, surf_region);
648

649 650
	v = gr->vertices.data;
	vtxcnt = gr->vtxcnt.data;
651 652 653 654 655 656 657 658 659 660 661

	/* 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]);
662
		if (gr->fan_debug)
663
			triangle_fan_debug(ev, first, vtxcnt[i]);
664 665 666 667 668 669
		first += vtxcnt[i];
	}

	glDisableVertexAttribArray(1);
	glDisableVertexAttribArray(0);

670 671
	gr->vertices.size = 0;
	gr->vtxcnt.size = 0;
672 673
}

674 675 676 677
static int
use_output(struct weston_output *output)
{
	static int errored;
678 679
	struct gl_output_state *go = get_output_state(output);
	struct gl_renderer *gr = get_renderer(output->compositor);
680 681 682 683 684 685 686 687 688 689
	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");
690
		gl_renderer_print_egl_error_state();
691 692 693 694 695 696
		return -1;
	}

	return 0;
}

697 698 699 700
static int
shader_init(struct gl_shader *shader, struct gl_renderer *gr,
		   const char *vertex_source, const char *fragment_source);

701
static void
702
use_shader(struct gl_renderer *gr, struct gl_shader *shader)
703
{
704 705 706 707 708 709 710 711 712 713 714
	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");
	}

715
	if (gr->current_shader == shader)
716 717
		return;
	glUseProgram(shader->program);
718
	gr->current_shader = shader;
719 720 721
}

static void
722
shader_uniforms(struct gl_shader *shader,
723 724
		struct weston_view *view,
		struct weston_output *output)
725 726
{
	int i;
727
	struct gl_surface_state *gs = get_surface_state(view->surface);
728
	struct gl_output_state *go = get_output_state(output);
729 730

	glUniformMatrix4fv(shader->proj_uniform,
731
			   1, GL_FALSE, go->output_matrix.d);
732
	glUniform4fv(shader->color_uniform, 1, gs->color);
733
	glUniform1f(shader->alpha_uniform, view->alpha);
734

735
	for (i = 0; i < gs->num_textures; i++)
736 737 738 739
		glUniform1i(shader->tex_uniforms[i], i);
}

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

755 756 757 758 759 760
	/* 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;

761 762
	pixman_region32_init(&repaint);
	pixman_region32_intersect(&repaint,
763
				  &ev->transform.boundingbox, damage);
764
	pixman_region32_subtract(&repaint, &repaint, &ev->clip);
765 766 767 768 769 770

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

	glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

771
	if (gr->fan_debug) {
772
		use_shader(gr, &gr->solid_shader);
773
		shader_uniforms(&gr->solid_shader, ev, output);
774 775
	}

776
	use_shader(gr, gs->shader);
777
	shader_uniforms(gs->shader, ev, output);
778

779
	if (ev->transform.enabled || output->zoom.active ||
780
	    output->current_scale != ev->surface->buffer_viewport.buffer.scale)
781 782 783 784
		filter = GL_LINEAR;
	else
		filter = GL_NEAREST;

785
	for (i = 0; i < gs->num_textures; i++) {
786
		glActiveTexture(GL_TEXTURE0 + i);
787 788 789
		glBindTexture(gs->target, gs->textures[i]);
		glTexParameteri(gs->target, GL_TEXTURE_MIN_FILTER, filter);
		glTexParameteri(gs->target, GL_TEXTURE_MAG_FILTER, filter);
790 791 792 793
	}

	/* blended region is whole surface minus opaque region: */
	pixman_region32_init_rect(&surface_blend, 0, 0,
794
				  ev->surface->width, ev->surface->height);
795 796 797 798 799
	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);
800

801
	/* XXX: Should we be using ev->transform.opaque here? */
802 803 804 805 806 807 808 809 810
	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)) {
811
		if (gs->shader == &gr->texture_shader_rgba) {
812 813 814 815 816
			/* 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.
			 */
817
			use_shader(gr, &gr->texture_shader_rgbx);
818
			shader_uniforms(&gr->texture_shader_rgbx, ev, output);
819 820
		}

821
		if (ev->alpha < 1.0)
822 823 824 825
			glEnable(GL_BLEND);
		else
			glDisable(GL_BLEND);

826
		repaint_region(ev, &repaint, &surface_opaque);
827 828 829
	}

	if (pixman_region32_not_empty(&surface_blend)) {
830
		use_shader(gr, gs->shader);
831
		glEnable(GL_BLEND);
832
		repaint_region(ev, &repaint, &surface_blend);
833 834 835
	}

	pixman_region32_fini(&surface_blend);
836
	pixman_region32_fini(&surface_opaque);
837 838 839 840 841

out:
	pixman_region32_fini(&repaint);
}

842
static void
843
repaint_views(struct weston_output *output, pixman_region32_t *damage)
844 845
{
	struct weston_compositor *compositor = output->compositor;
846
	struct weston_view *view;
847

848 849 850
	wl_list_for_each_reverse(view, &compositor->view_list, link)
		if (view->plane == &compositor->primary_plane)
			draw_view(view, output, damage);
851 852
}

853
static void
854 855 856
draw_output_border_texture(struct gl_output_state *go,
			   enum gl_renderer_border_side side,
			   int32_t x, int32_t y,
857 858
			   int32_t width, int32_t height)
{
859
	struct gl_border_image *img = &go->borders[side];
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
	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);
	}

887
	if (go->border_status & (1 << side)) {
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 915 916 917 918 919 920
		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);
}

921 922 923 924 925 926 927 928 929 930 931
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;
}

932
static void
933 934
draw_output_borders(struct weston_output *output,
		    enum gl_border_status border_status)
935 936 937 938
{
	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;
939 940 941 942
	struct gl_border_image *top, *bottom, *left, *right;
	struct weston_matrix matrix;
	int full_width, full_height;

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

946 947 948 949 950 951 952
	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;
953 954 955 956

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

957 958 959 960 961 962
	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);
963 964 965 966 967

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

968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
	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);
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 1017 1018 1019 1020 1021 1022
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);
}

1023
static void
1024 1025
output_get_damage(struct weston_output *output,
		  pixman_region32_t *buffer_damage, uint32_t *border_damage)
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
{
	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();
		}
	}

1042
	if (buffer_age == 0 || buffer_age - 1 > BUFFER_DAMAGE_COUNT) {
1043
		pixman_region32_copy(buffer_damage, &output->region);
1044 1045
		*border_damage = BORDER_ALL_DIRTY;
	} else {
1046
		for (i = 0; i < buffer_age - 1; i++)
1047
			*border_damage |= go->border_damage[(go->buffer_damage_index + i) % BUFFER_DAMAGE_COUNT];
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057

		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,
1058
						      &go->buffer_damage[(go->buffer_damage_index + i) % BUFFER_DAMAGE_COUNT]);
1059 1060
		}
	}
1061 1062 1063 1064
}

static void
output_rotate_damage(struct weston_output *output,
1065 1066
		     pixman_region32_t *output_damage,
		     enum gl_border_status border_status)
1067 1068 1069 1070 1071 1072 1073
{
	struct gl_output_state *go = get_output_state(output);
	struct gl_renderer *gr = get_renderer(output->compositor);

	if (!gr->has_egl_buffer_age)
		return;

1074 1075
	go->buffer_damage_index += BUFFER_DAMAGE_COUNT - 1;
	go->buffer_damage_index %= BUFFER_DAMAGE_COUNT;
1076

1077 1078
	pixman_region32_copy(&go->buffer_damage[go->buffer_damage_index], output_damage);
	go->border_damage[go->buffer_damage_index] = border_status;
1079 1080
}

1081 1082 1083 1084 1085 1086 1087 1088
/* 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.
 */
1089
static void
1090
gl_renderer_repaint_output(struct weston_output *output,
1091 1092
			      pixman_region32_t *output_damage)
{
1093
	struct gl_output_state *go = get_output_state(output);
1094
	struct weston_compositor *compositor = output->compositor;
1095
	struct gl_renderer *gr = get_renderer(compositor);
1096 1097
	EGLBoolean ret;
	static int errored;
1098 1099 1100
	int i, nrects, buffer_height;
	EGLint *egl_damage, *d;
	pixman_box32_t *rects;
1101
	pixman_region32_t buffer_damage, total_damage;
1102
	enum gl_border_status border_damage = BORDER_STATUS_CLEAN;
1103

1104 1105 1106
	if (use_output(output) < 0)
		return;

1107 1108 1109 1110 1111
	/* 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);
1112

1113 1114 1115 1116 1117 1118 1119 1120 1121
	/* 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);

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

1136
	pixman_region32_init(&total_damage);
1137 1138
	pixman_region32_init(&buffer_damage);

1139 1140
	output_get_damage(output, &buffer_damage, &border_damage);
	output_rotate_damage(output, output_damage, go->border_status);
1141 1142

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

1145
	repaint_views(output, &total_damage);
1146 1147

	pixman_region32_fini(&total_damage);
1148
	pixman_region32_fini(&buffer_damage);
1149

1150
	draw_output_borders(output, border_damage);
1151

1152
	pixman_region32_copy(&output->previous_damage, output_damage);
1153 1154
	wl_signal_emit(&output->frame_signal, output);

1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
	if (gr->swap_buffers_with_damage) {
		pixman_region32_init(&buffer_damage);
		weston_transformed_region(output->width, output->height,
					  output->transform,
					  output->current_scale,
					  output_damage, &buffer_damage);

		if (output_has_borders(output)) {
			pixman_region32_translate(&buffer_damage,
						  go->borders[GL_RENDERER_BORDER_LEFT].width,
						  go->borders[GL_RENDERER_BORDER_TOP].height);
			output_get_border_damage(output, go->border_status,
						 &buffer_damage);
		}

		rects = pixman_region32_rectangles(&buffer_damage, &nrects);
		egl_damage = malloc(nrects * 4 * sizeof(EGLint));

		buffer_height = go->borders[GL_RENDERER_BORDER_TOP].height +
				output->current_mode->height +
				go->borders[GL_RENDERER_BORDER_BOTTOM].height;

		d = egl_damage;
		for (i = 0; i < nrects; ++i) {
			*d++ = rects[i].x1;
			*d++ = buffer_height - rects[i].y2;
			*d++ = rects[i].x2 - rects[i].x1;
			*d++ = rects[i].y2 - rects[i].y1;
		}
		ret = gr->swap_buffers_with_damage(gr->egl_display,
						   go->egl_surface,
						   egl_damage, nrects);
		free(egl_damage);
		pixman_region32_fini(&buffer_damage);
	} else {
		ret = eglSwapBuffers(gr->egl_display, go->egl_surface);
	}

1193 1194 1195
	if (ret == EGL_FALSE && !errored) {
		errored = 1;
		weston_log("Failed in eglSwapBuffers.\n");
1196
		gl_renderer_print_egl_error_state();
1197 1198
	}

1199
	go->border_status = BORDER_STATUS_CLEAN;
1200
}
1201

1202
static int
1203
gl_renderer_read_pixels(struct weston_output *output,
1204 1205 1206 1207 1208
			       pixman_format_code_t format, void *pixels,
			       uint32_t x, uint32_t y,
			       uint32_t width, uint32_t height)
{
	GLenum gl_format;
1209 1210 1211 1212
	struct gl_output_state *go = get_output_state(output);

	x += go->borders[GL_RENDERER_BORDER_LEFT].width;
	y += go->borders[GL_RENDERER_BORDER_BOTTOM].height;
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234

	switch (format) {
	case PIXMAN_a8r8g8b8:
		gl_format = GL_BGRA_EXT;
		break;
	case PIXMAN_a8b8g8r8:
		gl_format = GL_RGBA;
		break;
	default:
		return -1;
	}

	if (use_output(output) < 0)
		return -1;

	glPixelStorei(GL_PACK_ALIGNMENT, 1);
	glReadPixels(x, y, width, height, gl_format,
		     GL_UNSIGNED_BYTE, pixels);

	return 0;
}

1235
static void
1236
gl_renderer_flush_damage(struct weston_surface *surface)
1237
{
1238 1239
	struct gl_renderer *gr = get_renderer(surface->compositor);
	struct gl_surface_state *gs = get_surface_state(surface);
1240
	struct weston_buffer *buffer = gs->buffer_ref.buffer;
1241
	struct weston_view *view;
1242
	bool texture_used;
1243
	pixman_box32_t *rectangles;
1244
	uint8_t *data;
1245
	int i, j, n;
1246

1247 1248
	pixman_region32_union(&gs->texture_damage,
			      &gs->texture_damage, &surface->damage);
1249

1250 1251 1252
	if (!buffer)
		return;

1253
	/* Avoid upload, if the texture won't be used this time.
1254 1255 1256
	 * We still accumulate the damage in texture_damage, and
	 * hold the reference to the buffer, in case the surface
	 * migrates back to the primary plane.
1257
	 */
1258
	texture_used = false;
1259 1260
	wl_list_for_each(view, &surface->views, surface_link) {
		if (view->plane == &surface->compositor->primary_plane) {
1261
			texture_used = true;
1262 1263 1264 1265
			break;
		}
	}
	if (!texture_used)
1266 1267
		return;

1268 1269
	if (!pixman_region32_not_empty(&gs->texture_damage) &&
	    !gs->needs_full_upload)
1270
		goto done;
1271

1272
	data = wl_shm_buffer_get_data(buffer->shm_buffer);
1273

1274
	if (!gr->has_unpack_subimage) {
1275
		wl_shm_buffer_begin_access(buffer->shm_buffer);
1276