//#include "RunDraw.h"
#include "SchedTask.h"

SchedDefineTask(Draw);

static int
run(SchedTask *smanager, void *rbuf, void *wbuf)
{
#if 0
    PolygonPack *pp = (PolygonPack*)smanager->get_input(rbuf, 0);
    PolygonPack *next_pp = 
	(PolygonPack*)smanager->allocate(sizeof(PolygonPack));
    PolygonPack *free_pp = next_pp;
    PolygonPack *tmp_pp;

    TrianglePackPtr triPack;
    VertexPackPtr vMin, vMid, vMax;
    VertexPackPtr vMid10
	= (VertexPackPtr)smanager->allocate(sizeof(VertexPack));
    NormalPackPtr normal1,normal2, normal3;
    SpanPackPtr *spackList = (SpanPackPtr*)smanager->get_input(rbuf, 1);
    spack = (SpanPackPtr)smanager->get_input(rbuf, 2);
    send_spack = (SpanPackPtr)smanager->allocate(sizeof(SpanPack));
    prev_index = (long)smanager->get_param(0);

    // spack と send_spack は swap しながら DMA を繰り返すので
    // 自分で allocate した send_spack を覚えてないといけない
    SpanPackPtr free_spack = send_spack;

    int charge_y_top = (long)smanager->get_param(1);
    int charge_y_end = (long)smanager->get_param(2);

    do {
	if (pp->next != NULL) {
	    smanager->dma_load(next_pp, (memaddr)pp->next,
			       sizeof(PolygonPack), POLYGON_PACK_LOAD);
	} else {
	    next_pp = NULL;
	}

	for (int i = 0; i < pp->info.size; i++) {
	    triPack = &pp->tri[i];

	    TriangleTexInfoPtr tri_tex_info = &triPack->tex_info;

	    make_vertex(triPack, &vMin, &vMid, &vMax, &normal1, &normal2, &normal3);
	    make_vMid10(vMid10, vMin, vMid, vMax);

	    /**
	     * ポリゴンを、x軸に水平に分割して二つの三角形を作り、
	     * それぞれから Span を求める
	     *
	     *      vMax
	     *        |\
	     *        | \
	     *        |  \
	     *        |   \
	     * vMid10 ------ vMid
	     *        |   /
	     *        |  /
	     *        | /
	     *        |/
	     *      vMin
	     *
	     * (vMax, vMid, vMin) という triangle を
	     * (vMax, vMid, vMid10) (vMin, vMid, vMid10) という
	     * 二つの Triangle に分けている
	     */
	    half_triangle(smanager, spackList, charge_y_top, charge_y_end,
			  tri_tex_info, vMin, vMid, vMid10,
                          normal1,normal2,normal3,
			  (int)(vMax->y - vMin->y), vMax->tex_y - vMin->tex_y);
	    half_triangle(smanager, spackList, charge_y_top, charge_y_end,
			  tri_tex_info, vMax, vMid, vMid10,
                          normal1,normal2,normal3,
			  (int)(vMax->y - vMin->y), vMax->tex_y - vMin->tex_y);
	}

	smanager->dma_wait(POLYGON_PACK_LOAD);	

	tmp_pp = pp;
	pp = next_pp;
	next_pp = tmp_pp;
    } while (pp);

    smanager->dma_wait(SPAN_PACK_STORE);
    smanager->dma_store(spack, (memaddr)spackList[prev_index],
			sizeof(SpanPack), SPAN_PACK_STORE);
    smanager->dma_wait(SPAN_PACK_STORE);

    free(free_pp);
    free(free_spack);
    free(vMid10);
#endif
    return 0;
}
