#include <stdlib.h>
#include <glib.h>
#include <clutter/clutter.h>

static const unsigned char default_texture_data[4] = { 0xff, 0xff, 0xff, 0xff };

static void
on_text_paint (ClutterActor *actor)
{
  CoglTextureVertex vertices[4];
  CoglHandle material, texture;
  ClutterActorBox paint_box;
  gfloat width, height;

  clutter_actor_get_allocation_box (actor, &paint_box);
  clutter_actor_box_get_size (&paint_box, &width, &height);

  if (width == 0 || height == 0)
    return;

  vertices[0].x = width / 2;
  vertices[0].y = 0;
  vertices[0].z = 0;
  vertices[0].tx = 0;
  vertices[0].ty = 1.0;
  cogl_color_set_from_4ub (&(vertices[0].color), 255, 255, 255, 0);
  cogl_color_premultiply (&(vertices[0].color));

  vertices[1].x = width;
  vertices[1].y = 0;
  vertices[1].z = 0;
  vertices[1].tx = 1.0;
  vertices[1].ty = 1.0;
  cogl_color_set_from_4ub (&(vertices[1].color), 255, 255, 255, 255);
  cogl_color_premultiply (&(vertices[1].color));

  vertices[2].x = width;
  vertices[2].y = height;
  vertices[2].z = 0;
  vertices[2].tx = 1.0;
  vertices[2].ty = 0.0;
  cogl_color_set_from_4ub (&(vertices[2].color), 255, 255, 255, 255);
  cogl_color_premultiply (&(vertices[2].color));

  vertices[3].x = width / 2;
  vertices[3].y = height;
  vertices[3].z = 0;
  vertices[3].tx = 0.0;
  vertices[3].ty = 0.0;
  cogl_color_set_from_4ub (&(vertices[3].color), 255, 255, 255, 0);
  cogl_color_premultiply (&(vertices[3].color));

  texture = cogl_texture_new_from_data (1, 1,
                                        COGL_TEXTURE_NONE,
                                        COGL_PIXEL_FORMAT_RGBA_8888_PRE,
                                        COGL_PIXEL_FORMAT_RGBA_8888_PRE,
                                        0,
                                        default_texture_data);

  material = cogl_material_new ();
  cogl_material_set_layer (material, 0, texture);
  cogl_set_source (material);
  cogl_polygon (vertices, 4, TRUE);
}

int
main (int argc, char *argv[])
{
  ClutterActor *stage, *text;
  ClutterColor black;

  clutter_init (&argc, &argv);

  stage = clutter_stage_new ();
  g_signal_connect (stage, "destroy", G_CALLBACK (clutter_main_quit), NULL);
  clutter_stage_set_title (CLUTTER_STAGE (stage), "Fade out text");

  clutter_color_from_string (&black, "black");

  text = clutter_text_new_full ("Sans 96px", "Hello, World!", &black);
  g_signal_connect_after (text, "paint", G_CALLBACK (on_text_paint), NULL);
  clutter_actor_set_anchor_point_from_gravity (text, CLUTTER_GRAVITY_CENTER);
  clutter_actor_set_position (text,
                              clutter_actor_get_width (stage) / 2,
                              clutter_actor_get_height (stage) / 2);
  clutter_container_add_actor (CLUTTER_CONTAINER (stage), text);

  clutter_actor_show (stage);

  clutter_main ();

  return EXIT_SUCCESS;
}