gl-renderer.c 83.8 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 <stdlib.h>
34 35
#include <string.h>
#include <ctype.h>
36 37
#include <float.h>
#include <assert.h>
38
#include <linux/input.h>
39
#include <drm_fourcc.h>
40

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

46
#include "shared/helpers.h"
47
#include "weston-egl-ext.h"
48

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

59 60
#define BUFFER_DAMAGE_COUNT 2

61 62 63 64 65 66 67 68 69 70
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
};

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

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

	struct weston_matrix output_matrix;
87 88
};

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

96 97 98 99 100 101
struct gl_renderer;

struct egl_image {
	struct gl_renderer *renderer;
	EGLImageKHR image;
	int refcount;
102
};
103

104 105 106 107 108 109
enum import_type {
	IMPORT_TYPE_INVALID,
	IMPORT_TYPE_DIRECT,
	IMPORT_TYPE_GL_CONVERSION
};

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

	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];
134 135
};

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

	GLuint textures[3];
	int num_textures;
142
	bool needs_full_upload;
143
	pixman_region32_t texture_damage;
144

145 146 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 */
	GLenum gl_format;
	GLenum gl_pixel_type;

151
	struct egl_image* images[3];
152 153
	GLenum target;
	int num_images;
154 155

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

	struct weston_surface *surface;

	struct wl_listener surface_destroy_listener;
164
	struct wl_listener renderer_destroy_listener;
165 166
};

167
struct gl_renderer {
168 169
	struct weston_renderer base;
	int fragment_shader_debug;
170
	int fan_debug;
171 172
	struct weston_binding *fragment_binding;
	struct weston_binding *fan_binding;
173

174 175 176
	EGLDisplay egl_display;
	EGLContext egl_context;
	EGLConfig egl_config;
177

178 179
	EGLSurface dummy_surface;

180 181 182
	struct wl_array vertices;
	struct wl_array vtxcnt;

183 184 185
	PFNGLEGLIMAGETARGETTEXTURE2DOESPROC image_target_texture_2d;
	PFNEGLCREATEIMAGEKHRPROC create_image;
	PFNEGLDESTROYIMAGEKHRPROC destroy_image;
186
	PFNEGLSWAPBUFFERSWITHDAMAGEEXTPROC swap_buffers_with_damage;
187 188
	PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC create_platform_window;

189 190 191 192 193 194 195 196 197
	int has_unpack_subimage;

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

	int has_egl_image_external;

198 199
	int has_egl_buffer_age;

200 201
	int has_configless_context;

202 203
	int has_surfaceless_context;

204 205 206
	int has_dmabuf_import;
	struct wl_list dmabuf_images;

207 208 209 210 211 212 213 214 215
	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;
216 217

	struct wl_signal destroy_signal;
218 219
};

220 221
static PFNEGLGETPLATFORMDISPLAYEXTPROC get_platform_display = NULL;

222 223 224 225 226 227 228 229 230 231
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;
}

232
static inline struct gl_output_state *
233 234
get_output_state(struct weston_output *output)
{
235
	return (struct gl_output_state *)output->renderer_state;
236 237
}

238 239 240
static int
gl_renderer_create_surface(struct weston_surface *surface);

241
static inline struct gl_surface_state *
242 243
get_surface_state(struct weston_surface *surface)
{
244 245 246
	if (!surface->renderer_state)
		gl_renderer_create_surface(surface);

247
	return (struct gl_surface_state *)surface->renderer_state;
248 249
}

250
static inline struct gl_renderer *
251 252
get_renderer(struct weston_compositor *ec)
{
253
	return (struct gl_renderer *)ec->renderer;
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
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;
}

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

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

352
static void
353
gl_renderer_print_egl_error_state(void)
354 355 356 357 358 359 360 361
{
	EGLint code;

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

362 363 364
#define max(a, b) (((a) > (b)) ? (a) : (b))
#define min(a, b) (((a) > (b)) ? (b) : (a))

365 366 367 368 369 370 371 372 373
/*
 * 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.
 */
374
static int
375
calculate_edges(struct weston_view *ev, pixman_box32_t *rect,
376 377
		pixman_box32_t *surf_rect, GLfloat *ex, GLfloat *ey)
{
378

379 380
	struct clip_context ctx;
	int i, n;
381
	GLfloat min_x, max_x, min_y, max_y;
382 383 384 385
	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
386 387
	};

388 389 390 391
	ctx.clip.x1 = rect->x1;
	ctx.clip.y1 = rect->y1;
	ctx.clip.x2 = rect->x2;
	ctx.clip.y2 = rect->y2;
392 393

	/* transform surface to screen space: */
394
	for (i = 0; i < surf.n; i++)
395 396
		weston_view_to_global_float(ev, surf.x[i], surf.y[i],
					    &surf.x[i], &surf.y[i]);
397 398

	/* find bounding box: */
399 400 401 402 403 404 405 406
	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]);
407 408 409 410 411
	}

	/* First, simple bounding box check to discard early transformed
	 * surface rects that do not intersect with the clip region:
	 */
412 413
	if ((min_x >= ctx.clip.x2) || (max_x <= ctx.clip.x1) ||
	    (min_y >= ctx.clip.y2) || (max_y <= ctx.clip.y1))
414 415 416 417 418 419
		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:
	 */
420
	if (!ev->transform.enabled)
421
		return clip_simple(&ctx, &surf, ex, ey);
422

423 424 425 426 427
	/* 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.
428
	 */
429
	n = clip_transformed(&ctx, &surf, ex, ey);
430 431 432

	if (n < 3)
		return 0;
433 434 435 436

	return n;
}

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
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)
{
	bool merged;
	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;
}

486
static int
487
texture_region(struct weston_view *ev, pixman_region32_t *region,
488 489
		pixman_region32_t *surf_region)
{
490 491
	struct gl_surface_state *gs = get_surface_state(ev->surface);
	struct weston_compositor *ec = ev->surface->compositor;
492
	struct gl_renderer *gr = get_renderer(ec);
493 494 495
	GLfloat *v, inv_width, inv_height;
	unsigned int *vtxcnt, nvtx = 0;
	pixman_box32_t *rects, *surf_rects;
496 497 498 499
	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);
500 501
	surf_rects = pixman_region32_rectangles(surf_region, &nsurf);

502 503 504 505 506 507 508 509
	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;
	}
510 511 512
	/* worst case we can have 8 vertices per rect (ie. clipped into
	 * an octagon):
	 */
513 514
	v = wl_array_add(&gr->vertices, nrects * nsurf * 8 * 4 * sizeof *v);
	vtxcnt = wl_array_add(&gr->vtxcnt, nrects * nsurf * sizeof *vtxcnt);
515

516
	inv_width = 1.0 / gs->pitch;
517
        inv_height = 1.0 / gs->height;
518 519 520 521 522

	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];
523
			GLfloat sx, sy, bx, by;
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
			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.
			 */
541
			n = calculate_edges(ev, rect, surf_rect, ex, ey);
542 543 544 545 546
			if (n < 3)
				continue;

			/* emit edge points: */
			for (k = 0; k < n; k++) {
547 548
				weston_view_from_global_float(ev, ex[k], ey[k],
							      &sx, &sy);
549 550 551 552
				/* position: */
				*(v++) = ex[k];
				*(v++) = ey[k];
				/* texcoord: */
553 554
				weston_surface_to_buffer_float(ev->surface,
							       sx, sy,
555 556
							       &bx, &by);
				*(v++) = bx * inv_width;
557 558 559 560 561
				if (gs->y_inverted) {
					*(v++) = by * inv_height;
				} else {
					*(v++) = (gs->height - by) * inv_height;
				}
562 563 564 565 566 567
			}

			vtxcnt[nvtx++] = n;
		}
	}

568 569
	if (used_band_compression)
		free(rects);
570 571 572 573
	return nvtx;
}

static void
574
triangle_fan_debug(struct weston_view *view, int first, int count)
575
{
576
	struct weston_compositor *compositor = view->surface->compositor;
577
	struct gl_renderer *gr = get_renderer(compositor);
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
	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;
	}

605 606
	glUseProgram(gr->solid_shader.program);
	glUniform4fv(gr->solid_shader.color_uniform, 1,
607 608
			color[color_idx++ % ARRAY_LENGTH(color)]);
	glDrawElements(GL_LINES, nelems, GL_UNSIGNED_SHORT, buffer);
609
	glUseProgram(gr->current_shader->program);
610 611 612 613
	free(buffer);
}

static void
614
repaint_region(struct weston_view *ev, pixman_region32_t *region,
615 616
		pixman_region32_t *surf_region)
{
617
	struct weston_compositor *ec = ev->surface->compositor;
618
	struct gl_renderer *gr = get_renderer(ec);
619 620 621 622 623 624 625 626 627 628
	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
629
	 * it has a non-zero area (at least 3 vertices, actually).
630
	 */
631
	nfans = texture_region(ev, region, surf_region);
632

633 634
	v = gr->vertices.data;
	vtxcnt = gr->vtxcnt.data;
635 636 637 638 639 640 641 642 643 644 645

	/* 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]);
646
		if (gr->fan_debug)
647
			triangle_fan_debug(ev, first, vtxcnt[i]);
648 649 650 651 652 653
		first += vtxcnt[i];
	}

	glDisableVertexAttribArray(1);
	glDisableVertexAttribArray(0);

654 655
	gr->vertices.size = 0;
	gr->vtxcnt.size = 0;
656 657
}

658 659 660 661
static int
use_output(struct weston_output *output)
{
	static int errored;
662 663
	struct gl_output_state *go = get_output_state(output);
	struct gl_renderer *gr = get_renderer(output->compositor);
664 665 666 667 668 669 670 671 672 673
	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");
674
		gl_renderer_print_egl_error_state();
675 676 677 678 679 680
		return -1;
	}

	return 0;
}

681 682 683 684
static int
shader_init(struct gl_shader *shader, struct gl_renderer *gr,
		   const char *vertex_source, const char *fragment_source);

685
static void
686
use_shader(struct gl_renderer *gr, struct gl_shader *shader)
687
{
688 689 690 691 692 693 694 695 696 697 698
	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");
	}

699
	if (gr->current_shader == shader)
700 701
		return;
	glUseProgram(shader->program);
702
	gr->current_shader = shader;
703 704 705
}

static void
706
shader_uniforms(struct gl_shader *shader,
707 708
		struct weston_view *view,
		struct weston_output *output)
709 710
{
	int i;
711
	struct gl_surface_state *gs = get_surface_state(view->surface);
712
	struct gl_output_state *go = get_output_state(output);
713 714

	glUniformMatrix4fv(shader->proj_uniform,
715
			   1, GL_FALSE, go->output_matrix.d);
716
	glUniform4fv(shader->color_uniform, 1, gs->color);
717
	glUniform1f(shader->alpha_uniform, view->alpha);
718

719
	for (i = 0; i < gs->num_textures; i++)
720 721 722 723
		glUniform1i(shader->tex_uniforms[i], i);
}

static void
724 725
draw_view(struct weston_view *ev, struct weston_output *output,
	  pixman_region32_t *damage) /* in global coordinates */
726
{
727
	struct weston_compositor *ec = ev->surface->compositor;
728
	struct gl_renderer *gr = get_renderer(ec);
729
	struct gl_surface_state *gs = get_surface_state(ev->surface);
730 731
	/* repaint bounding region in global coordinates: */
	pixman_region32_t repaint;
732 733
	/* opaque region in surface coordinates: */
	pixman_region32_t surface_opaque;
734 735 736 737 738
	/* non-opaque region in surface coordinates: */
	pixman_region32_t surface_blend;
	GLint filter;
	int i;

739 740 741 742 743 744
	/* 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;

745 746
	pixman_region32_init(&repaint);
	pixman_region32_intersect(&repaint,
747
				  &ev->transform.boundingbox, damage);
748
	pixman_region32_subtract(&repaint, &repaint, &ev->clip);
749 750 751 752 753 754

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

	glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

755
	if (gr->fan_debug) {
756
		use_shader(gr, &gr->solid_shader);
757
		shader_uniforms(&gr->solid_shader, ev, output);
758 759
	}

760
	use_shader(gr, gs->shader);
761
	shader_uniforms(gs->shader, ev, output);
762

763
	if (ev->transform.enabled || output->zoom.active ||
764
	    output->current_scale != ev->surface->buffer_viewport.buffer.scale)
765 766 767 768
		filter = GL_LINEAR;
	else
		filter = GL_NEAREST;

769
	for (i = 0; i < gs->num_textures; i++) {
770
		glActiveTexture(GL_TEXTURE0 + i);
771 772 773
		glBindTexture(gs->target, gs->textures[i]);
		glTexParameteri(gs->target, GL_TEXTURE_MIN_FILTER, filter);
		glTexParameteri(gs->target, GL_TEXTURE_MAG_FILTER, filter);
774 775 776 777
	}

	/* blended region is whole surface minus opaque region: */
	pixman_region32_init_rect(&surface_blend, 0, 0,
778
				  ev->surface->width, ev->surface->height);
779 780 781 782 783
	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);
784

785
	/* XXX: Should we be using ev->transform.opaque here? */
786 787 788 789 790 791 792 793 794
	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)) {
795
		if (gs->shader == &gr->texture_shader_rgba) {
796 797 798 799 800
			/* 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.
			 */
801
			use_shader(gr, &gr->texture_shader_rgbx);
802
			shader_uniforms(&gr->texture_shader_rgbx, ev, output);
803 804
		}

805
		if (ev->alpha < 1.0)
806 807 808 809
			glEnable(GL_BLEND);
		else
			glDisable(GL_BLEND);

810
		repaint_region(ev, &repaint, &surface_opaque);
811 812 813
	}

	if (pixman_region32_not_empty(&surface_blend)) {
814
		use_shader(gr, gs->shader);
815
		glEnable(GL_BLEND);
816
		repaint_region(ev, &repaint, &surface_blend);
817 818 819
	}

	pixman_region32_fini(&surface_blend);
820
	pixman_region32_fini(&surface_opaque);
821 822 823 824 825

out:
	pixman_region32_fini(&repaint);
}

826
static void
827
repaint_views(struct weston_output *output, pixman_region32_t *damage)
828 829
{
	struct weston_compositor *compositor = output->compositor;
830
	struct weston_view *view;
831

832 833 834
	wl_list_for_each_reverse(view, &compositor->view_list, link)
		if (view->plane == &compositor->primary_plane)
			draw_view(view, output, damage);
835 836
}

837
static void
838 839 840
draw_output_border_texture(struct gl_output_state *go,
			   enum gl_renderer_border_side side,
			   int32_t x, int32_t y,
841 842
			   int32_t width, int32_t height)
{
843
	struct gl_border_image *img = &go->borders[side];
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
	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);
	}

871
	if (go->border_status & (1 << side)) {
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
		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);
}

905 906 907 908 909 910 911 912 913 914 915
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;
}

916
static void
917 918
draw_output_borders(struct weston_output *output,
		    enum gl_border_status border_status)
919 920 921 922
{
	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;
923 924 925 926
	struct gl_border_image *top, *bottom, *left, *right;
	struct weston_matrix matrix;
	int full_width, full_height;

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

930 931 932 933 934 935 936
	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;
937 938 939 940

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

941 942 943 944 945 946
	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);
947 948 949 950 951

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

952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
	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);
968
}
969

970 971 972 973 974 975 976 977 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
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);
}

1007
static void
1008 1009
output_get_damage(struct weston_output *output,
		  pixman_region32_t *buffer_damage, uint32_t *border_damage)
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
{
	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();
		}
	}

1026
	if (buffer_age == 0 || buffer_age - 1 > BUFFER_DAMAGE_COUNT) {
1027
		pixman_region32_copy(buffer_damage, &output->region);
1028 1029
		*border_damage = BORDER_ALL_DIRTY;
	} else {
1030
		for (i = 0; i < buffer_age - 1; i++)
1031
			*border_damage |= go->border_damage[(go->buffer_damage_index + i) % BUFFER_DAMAGE_COUNT];
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041

		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,
1042
						      &go->buffer_damage[(go->buffer_damage_index + i) % BUFFER_DAMAGE_COUNT]);
1043 1044
		}
	}
1045 1046 1047 1048
}

static void
output_rotate_damage(struct weston_output *output,
1049 1050
		     pixman_region32_t *output_damage,
		     enum gl_border_status border_status)
1051 1052 1053 1054 1055 1056 1057
{
	struct gl_output_state *go = get_output_state(output);
	struct gl_renderer *gr = get_renderer(output->compositor);

	if (!gr->has_egl_buffer_age)
		return;

1058 1059
	go->buffer_damage_index += BUFFER_DAMAGE_COUNT - 1;
	go->buffer_damage_index %= BUFFER_DAMAGE_COUNT;
1060

1061 1062
	pixman_region32_copy(&go->buffer_damage[go->buffer_damage_index], output_damage);
	go->border_damage[go->buffer_damage_index] = border_status;
1063 1064
}

1065 1066 1067 1068 1069 1070 1071 1072
/* 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.
 */
1073
static void
1074
gl_renderer_repaint_output(struct weston_output *output,
1075 1076
			      pixman_region32_t *output_damage)
{
1077
	struct gl_output_state *go = get_output_state(output);
1078
	struct weston_compositor *compositor = output->compositor;
1079
	struct gl_renderer *gr = get_renderer(compositor);
1080 1081
	EGLBoolean ret;
	static int errored;
1082 1083 1084
	int i, nrects, buffer_height;
	EGLint *egl_damage, *d;
	pixman_box32_t *rects;
1085
	pixman_region32_t buffer_damage, total_damage;
1086
	enum gl_border_status border_damage = BORDER_STATUS_CLEAN;
1087

1088 1089 1090
	if (use_output(output) < 0)
		return;

1091 1092 1093 1094 1095
	/* 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);
1096

1097 1098 1099 1100 1101 1102 1103 1104 1105
	/* 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);

1106 1107 1108
	/* if debugging, redraw everything outside the damage to clean up
	 * debug lines from the previous draw on this buffer:
	 */
1109
	if (gr->fan_debug) {
1110 1111 1112 1113
		pixman_region32_t undamaged;
		pixman_region32_init(&undamaged);
		pixman_region32_subtract(&undamaged, &output->region,
					 output_damage);
1114
		gr->fan_debug = 0;
1115
		repaint_views(output, &undamaged);
1116
		gr->fan_debug = 1;
1117 1118 1119
		pixman_region32_fini(&undamaged);
	}

1120
	pixman_region32_init(&total_damage);
1121 1122
	pixman_region32_init(&buffer_damage);

1123 1124
	output_get_damage(output, &buffer_damage, &border_damage);
	output_rotate_damage(output, output_damage, go->border_status);
1125 1126

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

1129
	repaint_views(output, &total_damage);
1130 1131

	pixman_region32_fini(&total_damage);
1132
	pixman_region32_fini(&buffer_damage);
1133

1134
	draw_output_borders(output, border_damage);
1135

1136
	pixman_region32_copy(&output->previous_damage, output_damage);
1137 1138
	wl_signal_emit(&output->frame_signal, output);

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153