/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	This program is distributed in the hope that it will be 
	useful, but WITHOUT ANY WARRANTY; without even the 
	implied warranty of MERCHANTABILITY or FITNESS FOR A 
	PARTICULAR PURPOSE.

**********************************************************************/



#ifndef ___TREE_CACHE_H___
#define ___TREE_CACHE_H___

#include	"gbparam.h"

typedef struct tree_node_wait {
	struct tree_node_wait *	next;
	XL_SEXP *		data;
	int			flags;
#define TNW_FREE		0x00000001
} TREE_NODE_WAIT;

typedef struct tree_node {
	int			flags;
#define TNF_ERROR		0x00000001
#define TNF_REQUEST		0x00000002
	int			level;
	int			ofs_x;
	int			ofs_y;
	int			w;
	int			h;
	unsigned long *		pixels;
	struct tree_node *	leaf[LEAF_MAX];
	struct tree_node *	parent;
	TREE_NODE_WAIT *	wait_box;
	int			access;
	short			lock;
} TREE_NODE;

typedef struct tree_cache {
	TREE_NODE *		rt;
	int			rt_level;
	int			rect_logsize;
	int			(*get_pixels)();
	int			(*get_query)();
	union resource *	r;
	int			tl_x;
	int			tl_y;
	int			br_x;
	int			br_y;

	unsigned int		trans_timeout;
	unsigned int		cr_err_count;
	TREE_NODE * 		cache;
	TREE_NODE_WAIT *	wait_box_list;
	struct tree_cache *	next;
} TREE_CACHE;

void init_tc(int ses,TREE_CACHE * tc,int level,int rs,
	int (*func_pixels)(),int (*func_query)(),
	union resource * r);
unsigned long _tc_get_pixel(TREE_CACHE * tc,int level,int x,int y,int * lev);
int get_ac_time();
int tc_last_access(int * ret_p);
void tc_gc_obj();
int cmp_access(int a,int b);

void init_tree_cache();
void _unlock_tn(TREE_NODE * tn);
TREE_NODE ** parse_tree(TREE_NODE ** tnp);
void _flush_tree_node();
TREE_NODE * new_tree_node(TREE_CACHE * tc,TREE_NODE * parent,int leaf);
void tc_task2(TKEY d);
void tc_task1(TKEY d);

void _insert_wait_box(TREE_CACHE * tc,TREE_NODE * tn,XL_SEXP * d);
void insert_wait_box(TREE_CACHE * tc,TREE_NODE * tn,XL_SEXP * d);
void _set_gc_wait_box(TREE_CACHE *,TREE_NODE *,int);
void set_gc_wait_box(TREE_CACHE *,TREE_NODE *,int);
void _gc_wait_box(TREE_CACHE * tc);
void tc_gc_wait_box();
void gc_tree_cache();




#endif
