rogue25b2/gods/
rogue25b2/player/
rogue25b2/space/planets/
rogue25b2/space/prototypes/
rogue25b2/space/ships/
rogue25b2/src/
/***************************************************************************\
[*]    ___    ____   ____   __   __  ____ [*]   ROGUE: ROM With Attitude  [*]
[*]   /#/ )  /#/  ) /#/  ) /#/  /#/ /#/   [*]    All rights reserved      [*]
[*]  /#/ <  /#/  / /#/ _  /#/  /#/ /#/--  [*]   Copyright(C) 2000-2001    [*]
[*] /#/   \(#(__/ (#(__/ (#(__/#/ (#(___  [*] Kenneth Conley (Mendanbar)  [*]
[*]  Expression of Digital Creativity..   [*]  roguemud@yahoogroups.com   [*]
[-]---------------------------------------+-+-----------------------------[-]
[*] File: event.cpp                                                       [*]
[*] Usage: Primary code for events                                        [*]
\***************************************************************************/

#include "types.h"
#include "event.h"
#include "queue.h"
#include "merc.h"

Queue *EventQueue;
extern UInt32 pulse;

void InitEvents(void) {
    EventQueue = new Queue;
}


void ProcessEvents(void) {
    Event *	theEvent;
    SInt32	newTime;

    while (pulse >= EventQueue->QueueKey()) {
	if (!(theEvent = (Event *)EventQueue->QueueHead())) {
	    log("SYSERR: Attempt to get a NULL event!");
	    return;
	}
	if ((newTime = theEvent->Run()) > 0)
	    theEvent->queue = EventQueue->Enqueue(theEvent, newTime + pulse);
	else
	    delete theEvent;
    }
}


void FreeAllEvents(void) {
    Event *TheEvent;
    while ((TheEvent = (Event *)EventQueue->QueueHead())) {
	delete TheEvent;
    }
    delete EventQueue;
}


Event::Event(EVENTFUNC(*function), Ptr event_obj, UInt32 when) {
    if (when < 1)
	when = 1;

    this->func = function;
    this->running = false;
    this->event_obj = event_obj;
    this->queue = EventQueue->Enqueue(this, when + pulse);
}


Event::~Event(void) {
    if (this->event_obj)
	FREE(this->event_obj);
}


UInt32 Event::Time(void) {
    return (this->queue->key - pulse);
}


SInt32 Event::Run(void) {
    this->running = true;
    SInt32 result = (this->func)(this->event_obj, this);
    this->running = false;
    return result;
}


void Event::Cancel(void) {
    if (!this->running) {
	EventQueue->Dequeue(this->queue);
	delete this;
    }
}


Event *FindEventFunc(LList<Event *> & list, EVENTFUNC(*func)) {
    Event *	event;
    LListIterator<Event *>	iter(list);
	
    while ((event = iter.Next())) {
	if (event->func == func)
	    return event;
    }
    return NULL;
}