Esempio n. 1
0
// Spawn a monster
//LMA: added handling of skill summons.
void CMonster::SpawnMonster( CPlayer* player, CMonster* thismon )
{
    BEGINPACKET( pak, 0x792 );
	ADDWORD    ( pak, clientid );
	ADDFLOAT   ( pak, Position->current.x*100 );
	ADDFLOAT   ( pak, Position->current.y*100 );

	if((thismon->bonushp>0||thismon->bonusmp>0)&&(thismon->skillid>0))
	{
    	ADDFLOAT   ( pak, 0xcdcdcdcd );
    	ADDFLOAT   ( pak, 0xcdcdcdcd );
    }
    else
    {
     	ADDFLOAT   ( pak, Position->destiny.x*100 );
    	ADDFLOAT   ( pak, Position->destiny.y*100 );
    }

	if(IsDead( ))
	{
	   ADDWORD    ( pak, 0x0003 );
	   ADDWORD    ( pak, 0x0000 );
    }
	else if(IsOnBattle( ))
	{
       //LMA: for supportive summons (lucky ghost...)
       if(Battle->bufftarget==Battle->target)
       {
    	   ADDWORD    ( pak, 0x0002 );
    	   ADDWORD    ( pak, 0x0000 );
       }
       else
       {
    	   ADDWORD    ( pak, 0x0002 );
    	   ADDWORD    ( pak, Battle->target );
       }

    }
	else if(IsMoving( ))
	{
	   ADDWORD    ( pak, 0x0001 );
	   ADDWORD    ( pak, 0x0000 );
    }
    else
    {
    	ADDWORD    ( pak, 0x0000 );
    	ADDWORD    ( pak, 0x0000 );
    }

    if(IsSummon( ) )
    {
        ADDBYTE    ( pak, 0x01 );
    }
    else
    {
        ADDBYTE    ( pak, 0x00 );
    }

    //LMA: Little check, for now we "only" have a DWORD for monster's HP so there is a limit
    //broken by some monsters (Turak boss)
    if(Stats->HP>MAXHPMOB)
    {
        LogDebugPriority(3);
        LogDebug("Too much HP for monster %i (%I64i->%I64i)",thismon->montype,Stats->HP,MAXHPMOB);
        LogDebugPriority(4);
        Stats->HP=(long long) MAXHPMOB;
    }

    ADDDWORD   ( pak, Stats->HP );

	if(thismon->owner != player->clientid)
    {
        CMap* map = GServer->MapList.Index[Position->Map];

        //LMA: adding team...
        if (thismon->team!=0)
        {
            ADDDWORD( pak,thismon->team);
        }
        else
        {
            if(IsSummon( ) && map->allowpvp!=0)
            {
                //Hostil
                ADDDWORD( pak, 0x00000064 );
            }
            else if (IsSummon( ) && map->allowpvp==0)
            {
                //Friendly
                ADDDWORD ( pak, 0x00000000 );
            }
            else
            {
                //Hostil
                ADDDWORD( pak, 0x00000064 );
            }

            //TODO: LMA, test if necessary or not anymore...
            /*
            else if(thismon->montype>=1474&&thismon->montype<=1489)
            {
                //LMA: Xmas trees are friendly.
                ADDDWORD ( pak, 0x00000000 );
            }
            */

        }

    }
    else
    {
        //Friendly
        ADDDWORD( pak, 0x00000000 );
    }

    ADDDWORD( pak, GServer->BuildBuffs( this ) );
	ADDWORD   ( pak, montype );
	ADDWORD   ( pak, 0x0000 );
	if(IsSummon( ))
    {
        ADDWORD( pak, owner );

        if (thismon->skillid>0)
        {
           ADDWORD( pak, thismon->skillid ); //id del skill (si es summon de skill)
        }
        else
        {
           ADDWORD( pak, 0x0000 ); //id del skill (si es summon de skill)
        }

    }
	player->client->SendPacket( &pak );

    //LMA: supportive summons (lucky ghost)
    if(IsSummon()&&buffid>0&&(player==GetOwner()))
    {
        Log(MSG_INFO,"The summon is spawned");
        /*CPlayer* player = GetOwner( );
        if (ownplayer==NULL)
           return true;*/
        StartAction( player,SUMMON_BUFF,buffid);
        Log(MSG_INFO,"completly");
        buffid=0;  //only one buff
    }

}
Esempio n. 2
0
//LMA: AIP
//ainumber is monster->AI type is add=0 idle=1 attacking=2 attacked=3 after killing target=4 hp<1=5
void CMonster::DoAi(int ainumberorg,char type)
{
    //LMA: reseting some timers.
    if (type==0||type==1||type==4||type==5)
    {
        nextAi_attacked=clock();
    }


    //LMA: does the monster have a special AIP?
    int ainumber=ainumberorg;
    if (sp_aip!=0)
    {
        ainumber=sp_aip;
        Log(MSG_INFO,"AIP overwritten from %i to %i for monster %i (cid %i)",ainumberorg,ainumber,montype,clientid);
    }

    CAip* script = NULL;
    int AIWatch = GServer->Config.AIWatch;
    int aiindex = (ainumber*0x10000)+(type*0x100);

    bool lma_debug=false;
    int nb_turns=0;


    /*if(ainumber==25||ainumber==499)
    {
        Log(MSG_INFO,"a monster does AIP index %i, type %i",type);
        lma_debug=true;
        LogDebugPriority(3);
    }*/

    //NPC Leum and chelsie and gawain
    /*if(ainumber==1113||ainumber==1090||ainumber==1091)
    {
        lma_debug=true;
        LogDebugPriority(3);
    }*/

    //void NPCs used in Ulverick stuff (NPC 1791 to 1795 but aip is 471 to 475).
    //Only for 471 / 1791 for now.
    //if(ainumber>=471&&ainumber<=475)
    //if(ainumber==471)
    /*if((ainumber>=455&&ainumber>=457)||ainumber==471)
    {
        //Log(MSG_INFO,"Doing AI for NPC %u",ainumber);
        lma_debug=true;
        LogDebugPriority(3);
    }*/

    /*if (Position->Map==2&&ainumber==1805)
    {
        lma_debug=true;
        LogDebugPriority(3);
    }*/

    //LMA: findchar and nearchar set to NULL.
    nearChar=NULL;
    findChar=NULL;

    if(ainumber == AIWatch && type == 5) //watched monster died
    {
        Log(MSG_INFO,"Monster died. Activating AI type 5");
    }

    //LMA: New way, faster?
    while(GServer->AipListMap.find(aiindex)!=GServer->AipListMap.end())
    {
        nb_turns++;
        if (lma_debug)
            LogDebug("BEGIN%i CDT Turn %i",ainumber,nb_turns);

        script = GServer->AipListMap[aiindex];
        if(ainumber == AIWatch)LogDebug( "Found entry. Now starting process for AI %i", ainumber);
        if(ainumber == AIWatch)Log(MSG_INFO,"Found entry. Now starting process for AI %i", ainumber);
        int success = AI_SUCCESS; //needs to be AI_SUCCESS otherwise would not perform conditionless actions
        int thisaction = 0;

        for (dword i = 0; i < script->ConditionCount; i++)
        {
            int command = script->Conditions[i]->opcode;
            //if (command > 30 || command < 0) continue;
            if (command > 32 || command < 0) continue;

            //LMA: adding the AIPId
            //success = (*GServer->aiCondFunc[command])(GServer, this, script->Conditions[i]->data);
            success = (*GServer->aiCondFunc[command])(GServer, this, script->Conditions[i]->data,ainumber);
            if(ainumber == AIWatch)LogDebug( "aiCondition %03u returned %d", command, success);
            if(ainumber == AIWatch)Log(MSG_INFO,"aiCondition %03u returned %d", command, success);

            //LMA: Special case (quite a stupid one if you're asking me)
            if(command==20&&type==1&&success==AI_FAILURE)
            {
                //they tried to do a check target level on idle... Let's say it went ok...
                success=AI_SUCCESS;
            }

            if (success == AI_FAILURE)
            {
                if (lma_debug)
                {
                    LogDebug( "DoAI%i aiCondition %03u, %i/%i Failure.",ainumber,command,i,script->ConditionCount-1);
                }

                break;
            }
            else
            {
                if (lma_debug)
                {
                    LogDebug( "DoAI%i aiCondition %03u, %i/%i Success.",ainumber,command,i,script->ConditionCount-1);
                }

            }

        }

        if (lma_debug)
        {
            LogDebug("DoAI%i END CDT Turn %i",ainumber,nb_turns);
        }
        if(ainumber == AIWatch)Log(MSG_INFO,"DoAI%i END CDT Turn %i",ainumber,nb_turns);



        if (success == AI_SUCCESS)
        {
            if (lma_debug)
            {
                LogDebug("DoAI%i BEGIN ACT Turn %i",ainumber,nb_turns);
            }
            if(ainumber == AIWatch)Log(MSG_INFO,"DoAI%i BEGIN ACT Turn %i",ainumber,nb_turns);

            //LMA: Special case, if we have a LTB and a qsd trigger in the same script, we do the LTB first.
            if(script->offset_ltb!=-1&&script->offset_qsd_trigger!=-1)
            {
                //We do the LTB.
                int command = script->Actions[script->offset_ltb]->opcode;
                if (command > 38 || command < 0) continue;

                //LMA: adding the AIPId
                //success = (*GServer->aiActFunc[command])(GServer, this, script->Actions[script->offset_ltb]->data);
                success = (*GServer->aiActFunc[command])(GServer, this, script->Actions[script->offset_ltb]->data,ainumber);
                if(ainumber == AIWatch)LogDebug( "aiAction forced: %03u returned %d", command, success);
                if(ainumber == AIWatch)Log(MSG_INFO,"aiAction forced: %03u returned %d", command, success);

                if(lma_debug)
                {
                    LogDebug( "DoAI%i aiAction Forced: %03u returned %d, %i/%i",ainumber,command, success,script->offset_ltb,script->ActionCount-1);
                }

            }

            for (dword i = 0; i < script->ActionCount; i++)
            {
                if(script->offset_ltb!=-1&&script->offset_qsd_trigger!=-1&&i==script->offset_ltb)
                {
                    //We cancel the LTB, already done earlier.
                    LogDebug( "DoAI%i aiAction: We cancel %i since it should be already done",ainumber,i);
                    continue;
                }

                int command = script->Actions[i]->opcode;
                if (command > 38 || command < 0) continue;

                //LMA: adding the AIPId
                //success = (*GServer->aiActFunc[command])(GServer, this, script->Actions[i]->data);
                success = (*GServer->aiActFunc[command])(GServer, this, script->Actions[i]->data,ainumber);
                if(ainumber == AIWatch)LogDebug( "aiAction: %03u returned %d", command, success);
                if(ainumber == AIWatch)Log(MSG_INFO,"aiAction: %03u returned %d", command, success);

                if(lma_debug)
                {
                    LogDebug( "DoAI%i aiAction: %03u returned %d, %i/%i",ainumber,command, success,i,script->ActionCount-1);
                }

            }

            if(success == AI_SUCCESS)
            {
                if(lma_debug)
                {
                    LogDebug("DoAI%i END ACT SUCCESS Turn %i",ainumber,nb_turns);
                }

                //LMA: Santa is special, he continues (Xmas Tree Spawning), same for some special others (gifts summoning)
                if(ainumber!=1205&&ainumber!=2048&&ainumber!=2049)
                {
                    if(lma_debug)
                    {
                        GServer->pakGMObjVar(NULL, 1249,2);
                        LogDebugPriority(4);
                    }

                    thisnpc->refNPC=0;
                    nearChar=NULL;
                    findChar=NULL;

                    return; //automatically return after performing the first successful action
                }

            }
            else
            {
              if(lma_debug)
              {
                    LogDebug("DoAI%i END ACT FAILURE Turn %i",ainumber,nb_turns);
              }

            }

        }

        aiindex++;
    }

    if(lma_debug)
    {
        GServer->pakGMObjVar(NULL, 1249,2);
        LogDebugPriority(4);
    }


    thisnpc->refNPC=0;
    nearChar=NULL;
    findChar=NULL;


    return;
}
Esempio n. 3
0
// Main server function
int main(int argc, char *argv[])
{
	//LMA: Opening log.
	LogHandleSp(1);
	LogDebugPriority(0,true);   //LMA: LogDebug won't appear in Logs or screen.

    srand( (unsigned)time(NULL) );
    srand( rand()*time(NULL) );

    //LMA: TEST DEACTIVATING ERROR TRAPPING
    //Uncomment following line to use "console" mode (control+C).
    //StartSignal( );

	LOG_THISSERVER = LOG_WORLD_SERVER;
    InitWinSocket( );
    string fileconf = "worldserver.conf";
    if(argc>1)
    {
        fileconf = argv[1];
    }
	CWorldServer *server = new (nothrow) CWorldServer( fileconf );
    if(server==NULL)
        return -1;
    pthread_attr_init(&server->at);
    pthread_attr_setdetachstate(&server->at, PTHREAD_CREATE_JOINABLE);
    // Connect mysql
    MYSQL mysql;
	server->DB = new CDatabase( server->Config.SQLServer.pcServer,
	                    server->Config.SQLServer.pcUserName,
	                    server->Config.SQLServer.pcPassword,
	                    server->Config.SQLServer.pcDatabase,
	                    server->Config.SQLServer.pcPort, &mysql );
    server->port = server->Config.CharPort;
	if(server->Config.usethreads)
	   Log( MSG_INFO, "Using Threads" );
	// Start server
	server->port = server->Config.WorldPort;

	if(server->DB->Connect( )==0) Log( MSG_INFO, "Connected to MySQL server" );
	else
	{
        delete server;
        server = NULL;
        #ifdef _WIN32
		system("pause");
		#endif
		return -1;
	}

	server->StartServer();
	// Close server
    pthread_attr_destroy(&server->at);
    server->DB->Disconnect( );
	CloseWinSocket( );
	StopSignal( );
	Log(MSG_INFO, "Cleaning memory, please wait..." );
	delete server;
	server = NULL;

	//LMA: closing log.
	LogHandleSp(0);

	return EXIT_SUCCESS;
}
Esempio n. 4
0
// Map Process
PVOID MapProcess( PVOID TS )
{
    bool ok_cont=false;
    UINT loopcount=0;
    clock_t time_skill=0;
    bool only_npc=false;    //LMA: AIP is done by NPC even when no player in map.
    bool only_summon=false;  //LMA: test for summons when no one's around (sad is a summon's life ^_^).
    UINT nb_summons_map=0;  //LMA: test for summons when no one's around (sad is a summon's life ^_^).

    //LMA: temp monster used for NPCs.
    fPoint tempPos;
    tempPos.x=0;
    tempPos.y=0;
    tempPos.z=0;
    CMonster* NPCmonster = new (nothrow) CMonster( tempPos, 0, 0, 0, 0  );

    while(GServer->ServerOnline)
    {
        loopcount++;            //geobot: refresh only every 100 cycles
        if (loopcount < 100)
        {
            continue;
        }

        loopcount = 0;

        pthread_mutex_lock( &GServer->PlayerMutex );
        pthread_mutex_lock( &GServer->MapMutex );

		

        for(UINT i=0;i<GServer->MapList.Map.size();i++)
        {
            CMap* map = GServer->MapList.Map.at(i);

            //LMA: test for Union.
            only_npc=false;
            only_summon=false;  //LMA: test for summons when no one's around (sad is a summon's life ^_^).
            nb_summons_map=0;
            if( map->PlayerList.size()<1 )
            {
                only_npc = true;    //LMA: AIP is done by NPC even when no player in map.

                //LMA: doing summons too if there are any in map.
                if(map->nb_summons > 0)
                {
                    only_summon = true;
                }
                //continue;
            }

            if (!only_npc||only_summon)
            {
                // Player update //------------------------
                for(UINT j=0;j<map->PlayerList.size();j++)
                {
                    CPlayer* player = map->PlayerList.at(j);
					//check for delayed trigger
					if(player->TriggerDelay != 0 )	//only one problem. If the player logs out before the delayed action trigger is executed than it never will be. Oh Dear! The missing children will really be missing. lol. It's fine though because they never truly despawn. they just disappear from the player's visibility list.
					{
						clock_t etime = clock() - player->DelayStartTime;
						if( etime >= player->TriggerDelay )
						{
							player->ExecuteQuestTrigger(player->TriggerHash,true);
							player->TriggerDelay = 0;	//reset delays and stuff
							player->TriggerHash = 0;
						}
					}
                    if(!player->Session->inGame) continue;

                    if(player->IsDead( ))
                    {
                          player->lastRegenTime = 0;
                          player->lastShowTime = 0;
                          continue;
                     }
                    player->RefreshHPMP();         //LMA HP / MP Jumping
                    if(player->UpdateValues( )) //Does nothing except for rides... equals to true if player isn't on the back seat
                        player->UpdatePosition(false);
                    if(player->IsOnBattle( ))
                        player->DoAttack( );

                    player->RefreshBuff( );
                    player->PlayerHeal( );
                    player->Regeneration( );
                    player->CheckPlayerLevelUP( );

                    player->CheckDoubleEquip(); //LMA: Core fix for double weapon and shield
                    player->CheckZulies( );

                    //Fuel handling.
                    if (player->Status->Stance == DRIVING && (player->last_fuel>0) && (clock()-player->last_fuel > 60000))
                    {
                      //We kill some fuel every now and then :)
                      player->TakeFuel();
                      player->last_fuel=clock();
                    }

                    //LMA: mileage coupon checks.
                    time_t etime=time(NULL);
                    if(player->no_exp&&(etime>=player->timer_no_exp))
                    {
                      BEGINPACKET( pak, 0x702 );
                      ADDSTRING( pak, "[Mileage] Null Xp vanished.");
                      ADDBYTE( pak, 0 );
                      player->client->SendPacket(&pak);
                      player->timer_no_exp=0;
                      player->no_exp=false;
                    }
                    if(player->bonusxp>1&&(etime>=player->timerxp))
                    {
                      BEGINPACKET( pak, 0x702 );
                      ADDSTRING( pak, "[Mileage] Bonus Xp vanished.");
                      ADDBYTE( pak, 0 );
                      player->client->SendPacket(&pak);
                      player->bonusxp=1;
                      player->timerxp=0;
                      player->wait_validation=0;
                    }
                    if(player->bonusddrop>1&&(etime>=player->timerddrop))
                    {
                      BEGINPACKET( pak, 0x702 );
                      ADDSTRING( pak, "[Mileage] Medal of Fortune vanished.");
                      ADDBYTE( pak, 0 );
                      player->client->SendPacket(&pak);
                      player->bonusddrop=1;
                      player->timerddrop=0;
                      player->wait_validation_ddrop=0;
                    }
                    if(player->bonusstatdrop>1&&(etime>=player->timerstatdrop))
                    {
                      BEGINPACKET( pak, 0x702 );
                      ADDSTRING( pak, "[Mileage] Medal of Excellence vanished.");
                      ADDBYTE( pak, 0 );
                      player->client->SendPacket(&pak);
                      player->bonusstatdrop=1;
                      player->timerstatdrop=0;
                      player->wait_validation_statdrop=0;
                    }
                    if(player->bonusgraydrop>0&&(etime>=player->timergraydrop))
                    {
                      BEGINPACKET( pak, 0x702 );
                      ADDSTRING( pak, "[Mileage] Medal of Retrieval vanished.");
                      ADDBYTE( pak, 0 );
                      player->client->SendPacket(&pak);
                      player->bonusgraydrop=0;
                      player->timergraydrop=0;
                      player->wait_validation_graydrop=0;
                    }
                    if(player->Shop->ShopType>0&&(etime>=player->Shop->mil_shop_time))
                    {
                      BEGINPACKET( pak, 0x702 );
                      ADDSTRING( pak, "[Mileage] Mileage shop expired !");
                      ADDBYTE( pak, 0 );
                      player->client->SendPacket(&pak);
                      player->Shop->ShopType=0;
                      player->Shop->mil_shop_time=0;
                    }
                    if(player->Shop->ShopType>0&&(etime>=player->Shop->mil_shop_time))
                    {
                      BEGINPACKET( pak, 0x702 );
                      ADDSTRING( pak, "[Mileage] Mileage shop expired !");
                      ADDBYTE( pak, 0 );
                      player->client->SendPacket(&pak);
                      player->Shop->ShopType=0;
                      player->Shop->mil_shop_time=0;
                    }

                }

                // Monster update //------------------------
                pthread_mutex_lock( &map->MonsterMutex );

                //spawn TD monsters
                unsigned nextmon = map->TDMobList[map->TDNextSpawn];
                if(nextmon != 0)
                {
                    //Log(MSG_DEBUG,"Spawning TD mobs");
                    clock_t etime = clock() - map->lastTDSpawnTime;
                    if(etime >= map->TDMobDelay) // check if elapsed time is greater than spawn delay
                    {
                         //spawn the next monster on the list
                         //Log(MSG_DEBUG,"Spawning TD mob of type %i at position %i in the list for map %i",nextmon, map->TDNextSpawn, map->id);
                         map->AddMonster(nextmon, GServer->WPList[map->id][1].pos, 0, 0, 0, 1, 0, 999 ); //spawn a TD mob with no AI
                         //Log(MSG_DEBUG,"Spawned mob in addmonster");
                         map->TDMobList[map->TDNextSpawn] = 0; //clear the spawn
                         //Log(MSG_DEBUG,"cleared the spawn");
                         map->TDNextSpawn++; //move the pointer
                         //Log(MSG_DEBUG,"moved the pointer");
                         if(map->TDNextSpawn > 100)map->TDNextSpawn = 0;
                         map->lastTDSpawnTime = clock();
                    }
                }
                //TD spawn end

                for(UINT j=0;j<map->MonsterList.size();j++)
                {
                    CMonster* monster = map->MonsterList.at(j);
                    //UINT thistimer = monster->AItimer;
                    clock_t etime = clock() - monster->lastAiUpdate;

                    //LMA: only summon ?
                    if (only_summon&&!monster->IsSummon())
                    {
                        continue;
                    }
                    else if(only_summon)
                    {
                        nb_summons_map++;
                    }

					if(monster->hitcount == 0xFF)//this is a delay for new monster spawns this might olso fix invisible monsters(if they attack directly on spawning the client dosn't get the attack packet(its not in it's visible list yet))
                    {
                        monster->hitcount = 0;
                        //monster->DoAi(monster->thisnpc->AI, 0);
                        monster->DoAi(monster->MonAI, 0);		//AI on spawn
                        monster->lastAiUpdate=clock();
                    }

                    //PY handling day only or night only monsters. 
                    
					if(!map->IsNight( ) && monster->Status->nightonly)// if day, delete all night time monsters
                    {
                        //Log( MSG_INFO, "Night Only monster deleted. Type %i", monster->montype);
                        map->DeleteMonster( monster, true, j );
                        continue;
                    }
                    if(map->IsNight() && monster->Status->dayonly)
                    {
                        //Log( MSG_INFO, "Day Only monster deleted. Type %i", monster->montype);
                        map->DeleteMonster( monster, true, j );
                        continue;
                    }

                    //Do TD stuff
                    if(monster->MonAI == 999 && etime >= monster->AITimer) //It's a TD mob
                    {
                        monster->UpdatePosition(monster->stay_still );
                        float distance = GServer->distance( monster->Position->current, monster->Position->destiny );
                        //Log( MSG_INFO, "Found a TD monster %f from target. Waypoint type = %i stance %i speed %i", distance,GServer->WPList[map->id][monster->NextWayPoint].WPType,monster->Stats->stance, monster->Stats->Move_Speed);
                        //Log( MSG_INFO, "monster location X: %f Y: %f",monster->Position->current.x, monster->Position->current.y);
                        //Log( MSG_INFO, "WP location X: %f Y: %f ", GServer->WPList[map->id][monster->NextWayPoint].pos.x,GServer->WPList[map->id][monster->NextWayPoint].pos.y);
                        if(distance < 1) //monster has reached it's destination
                        {
                            switch(GServer->WPList[map->id][monster->NextWayPoint].WPType)
                            {
                                case 1: //Start waypoint
                                case 2: //regular waypoint. Increment waypoint counter. Set detiny to next waypoint
                                {
                                    //Log( MSG_INFO, "Monster reached waypoint %i type: %i", monster->NextWayPoint,GServer->WPList[map->id][monster->NextWayPoint].WPType);
                                    monster->NextWayPoint++;
                                    monster->Position->destiny.x = GServer->WPList[map->id][monster->NextWayPoint].pos.x;
                                    monster->Position->destiny.y = GServer->WPList[map->id][monster->NextWayPoint].pos.y;
                                    BEGINPACKET( pak, 0x797 );
                                	ADDWORD    ( pak, monster->clientid );
                                	ADDWORD    ( pak, 0x0000 );
                                	ADDWORD    ( pak, monster->Stats->Move_Speed ); //speed
                                	ADDFLOAT   ( pak, monster->Position->destiny.x * 100 );
                                	ADDFLOAT   ( pak, monster->Position->destiny.y * 100 );
                                	ADDWORD    ( pak, 0xcdcd );
                                	ADDBYTE    ( pak, monster->Stats->stance );  //should be walking
                                	GServer->SendToVisible(&pak, monster);
                                }
                                break;
                                case 3: //Final waypoint. do stuff. suicide
                                {
                                    //Log( MSG_INFO, "Reached final waypoint");
                                    //monster->Stats->HP = 0;
                                    map->DeleteMonster( monster, true, j );
                                    //Log( MSG_INFO, "monster successfully deleted");
                                    continue;
                                }
                                break;
                                default:
                                    Log( MSG_INFO, "WPType %i not recognized",GServer->WPList[map->id][monster->NextWayPoint].WPType);
                                break;
                            }
                        }
                        else
                        {
                            //send move packet again to try to synchronise the monster movement
                            BEGINPACKET( pak, 0x797 );
                        	ADDWORD    ( pak, monster->clientid );
                        	ADDWORD    ( pak, 0x0000 );
                        	ADDWORD    ( pak, monster->Stats->Move_Speed ); //speed
                        	ADDFLOAT   ( pak, monster->Position->destiny.x * 100 );
                        	ADDFLOAT   ( pak, monster->Position->destiny.y * 100 );
                        	ADDWORD    ( pak, 0xcdcd );
                        	ADDBYTE    ( pak, monster->Stats->stance );  //should be walking
                        	GServer->SendToVisible(&pak, monster);
                        }
                        monster->lastAiUpdate = clock();
                    }
                    //End TD stuff

                    //if(!monster->PlayerInRange( )) continue;
                    if(!monster->UpdateValues( )) continue;
                    monster->UpdatePosition( true );
                    if(monster->IsOnBattle( ))
                    {
                         monster->DoAttack( );   // why was this commented? Monsters were not attacking
                         //monster->DoAi(monster->thisnpc->AI, 2);  //don't use thisnpc->AI any more.
                         if(etime >= monster->AITimer)
                         {
                             monster->DoAi(monster->MonAI, 2);
                             monster->lastAiUpdate = clock();
                         }
                         //Log(MSG_INFO,"Monster type: %i current HP: %i",monster->montype, monster->Stats->HP);
                    }
                    else
                    {
                         //monster->DoAi(monster->thisnpc->AI, 1);
                         if(etime >= monster->AITimer)
                         {
                            monster->DoAi(monster->MonAI, 1);
                            monster->lastAiUpdate = clock();
                         }
                    }
                    monster->RefreshBuff( );
                    if (monster->IsSummon())
                    {
                        monster->SummonUpdate(monster,map, j);
                        continue;
                    }
                    if(monster->IsDead())
                    {
                        if(clock() - monster->DeathDelayTimer > GServer->Config.DeathDelay)
                        {
                            //Log(MSG_DEBUG,"Found dead monster montype %i",monster->montype);
                            monster->OnDie( );  //all this does is give exp
                            //Log(MSG_DEBUG,"back from giving exp");
                            monster->DoAi(monster->MonAI, 5);
                            //Log(MSG_DEBUG,"ran AI");
                            map->DeleteMonster( monster, true, j );
                            //Log(MSG_DEBUG,"deleted monster");
                            continue;
                        }
                        else
                        {
                            //Log(MSG_DEBUG,"Dead monster found. waiting for death delay timer");
                        }
                    }

                }

                //LMA: was there any summons in this map?
                if(only_summon&&nb_summons_map==0)
                {
                    map->nb_summons=0;
                }

            }

            if(only_npc&&!only_summon)
            {
                pthread_mutex_lock( &map->MonsterMutex );
            }

            //LMA: AIP for NPC.
            for(UINT j=0;j<map->NPCList.size();j++)
            {
                CNPC* npc = map->NPCList.at(j);

                //LMA: We don't worry about IFO Objects...
                if(npc->npctype>10000)
                {
                    continue;
                }

                if(npc->thisnpc->AI != 0 && npc->thisnpc->AI != 30)
                {
                    //check every minute. Conditions seem to be based on 6 minute segments
                    //LMA: untrue for some NPCs, special case for UW...
					//PY: NO we don't check every minute. We check whatever interval the AIP file asks for

                    bool is_time_ok=false;

                    // int delay=60000;    //each AIP 60 seconds.
                    //LMA: AIP Timer.
                    //delay = npc->thisnpc->AiTimer;

                    if(npc->thisnpc->AiTimer == 0)
                    {
						//npc->thisnpc->AiTimer = 60000;
                        //Log(MSG_WARNING,"NPC %i hadn't timer, file AI=%i",npc->npctype,npc->thisnpc->AI);
						//PY: If the NPC doesn't have a timer then let's give it one
						CAip* script = NULL;
						for(unsigned k=0; k < GServer->AipList.size(); k++)
						{
							if (GServer->AipList.at(k)->AInumber == npc->thisnpc->AI)
							{
								script = GServer->AipList.at(k);
								break;
							}
						}
						if(script == NULL)
						{
							Log( MSG_WARNING, "Invalid AI script for AI %i Setting AI to 30 (blank)", npc->thisnpc->AI );
							npc->thisnpc->AI = 30;
							continue;
						}
						//Set the timer
						npc->thisnpc->AiTimer = script->minTime;
                    }
					//PY: Any npc reaching this point has a valid timer. It has either been set or removed
					
                    
					//PY MORE Bloody lmame special cases
					//If he had just set the frickin timer correctly like i did above, all this crap would be un-necessary

					//Leum, for Union War (no need to do his stuff always). //PY: NO this is BS
                    //if(npc->npctype==1113&&GServer->ObjVar[1113][1]>0)
                    //{
                        //LogDebug("Doing an update for Leum each 10 seconds since UW is on");
                    //    delay=10000;
                    //}

                    //PY: What the hell is this shit? commenting it out
					//Walls for map 66 (no need to do his stuff always)
                    //if(npc->npctype>=1024&&npc->npctype<=1027&&GServer->ObjVar[1249][2]>0&&GServer->ObjVar[1249][2]<=90)
                    //{
                        //LogDebug("Doing an update for Wall %i each second quest from Hope is on",npc->npctype);
                    //    delay=1000;
                    //}

                    //PY: Seriously??
					//Hope map 66 (no need to do his stuff always)
                    //if(npc->npctype==1249&&GServer->ObjVar[1249][2]>0&&GServer->ObjVar[1249][2]<=90)
                    //{
                        //LogDebug("Doing an update for Hope each 10 seconds quest from Hope is on",npc->npctype);
                    //    delay=10000;
                    //}

                    //PY and more special cases........
					//Williams
                    //if(npc->npctype==1075)
                    //{
                        //Each 5 minutes
                    //    delay=300000;
                    //}

                    //LMA END


                     //if(60000<(UINT)GServer->round((clock( ) - npc->lastAiUpdate)))
                     //if(is_time_ok)
                     //if(delay<(UINT)GServer->round((clock( ) - npc->lastAiUpdate)))
                     //PY NOPE!! How about we do it right
					UINT thistimer = npc->thisnpc->AiTimer * 1000; //this is always set in seconds in AIP
					if(thistimer<(UINT)GServer->round((clock( ) - npc->lastAiUpdate))) //check AIP conditions when the timer calls for it
					{
                         CNPCData* thisnpc = GServer->GetNPCDataByID( npc->npctype );
                         if(thisnpc == NULL)
                         {
                             Log( MSG_WARNING, "Invalid montype %i", npc->npctype );
                             continue;
                         }

                         //LMA: before this temp monster was created and deleted every time, now we only do it once...
                         //new code, we overwrite the temp monster each time rather than creating / deleting him each time.
                        NPCmonster->Position->source = npc->pos;
                        NPCmonster->Position->current = npc->pos;
                        NPCmonster->Position->destiny = npc->pos;
                         NPCmonster->montype=npc->npctype;
                         NPCmonster->Position->Map=map->id;
                         NPCmonster->Position->lastMoveTime = clock( );
                         NPCmonster->SpawnTime = clock( );
                         NPCmonster->lastSighCheck = clock( );
                         NPCmonster->lastLifeUpdate = time(NULL);

                         //old code:
                         //CMonster* NPCmonster = new (nothrow) CMonster( npc->pos, npc->npctype, map->id, 0, 0  );
                         NPCmonster->aip_npctype=npc->npctype;
                         NPCmonster->aip_clientid=npc->clientid;
                         NPCmonster->thisnpc = thisnpc;

                         int lma_previous_eventID = npc->thisnpc->eventid;
                         //Log(MSG_INFO,"XCIDAIBEGIN NPC %i map %i cid %i",npc->npctype,map->id,npc->clientid);

                         NPCmonster->DoAi(NPCmonster->MonAI, 1);
                         //Log(MSG_INFO,"XCIDAIEND NPC %i map %i cid %i",npc->npctype,map->id,npc->clientid);

                        
						 //PY: AAAAAAAAAGGGGGGGGGGHHHHHHHHHH. NO! just NO!!. Stop with the bloody special cases. Fix the damn core code already!!!!!!!
						 //Williams (temple of Oblivion)
                        /*if(npc->npctype == 1075)
                        {
                            //each 5 minutes
                            //saving values for him
                            if(GServer->LastTempleAccess[0]!=GServer->ObjVar[npc->npctype][0]||GServer->LastTempleAccess[1]!=GServer->ObjVar[npc->npctype][1])
                            {
                                GServer->DB->QExecute("UPDATE list_npcs SET eventid=%i, extra_param=%i WHERE type=1075",GServer->ObjVar[1075][0],GServer->ObjVar[1075][1]);
                                /*Log(MSG_WARNING,"Doing an update for Williams each 5 minutes, values changed (%i->%i, %i->%i)",
                                GServer->LastTempleAccess[0],GServer->ObjVar[npc->npctype][0],
                                GServer->LastTempleAccess[1],GServer->ObjVar[npc->npctype][1]);
                            }*/
                            /*else
                            {
                                Log(MSG_WARNING,"Doing an update for Williams each 5 minutes.");
                            }*/
							/*
                            GServer->LastTempleAccess[0]=GServer->ObjVar[npc->npctype][0];
                            GServer->LastTempleAccess[1]=GServer->ObjVar[npc->npctype][1];
                        }*/

                         
						 //PY: I have absolutely no idea what this bit does. I suspuct it's also a load of bollux but I'm leaving it in for now
						 //ToDo Figure this out and tidy it up

						 //LMA: check if eventID changed, if we do it in AIP conditions / actions, it just fails...
                         if (lma_previous_eventID!=NPCmonster->thisnpc->eventid)
                         {
                            //Log(MSG_WARNING,"(1)Event ID not the same NPC %i from %i to %i in map %i, npc->thisnpc->eventid=%i !",npc->npctype,lma_previous_eventID,NPCmonster->thisnpc->eventid,map->id,npc->thisnpc->eventid);
                            LogDebugPriority(3);
                            LogDebug("(1)Event ID not the same NPC %i from %i to %i in map %i, npc->thisnpc->eventid=%i !",npc->npctype,lma_previous_eventID,NPCmonster->thisnpc->eventid,map->id,npc->thisnpc->eventid);
                            LogDebugPriority(4);
                            npc->thisnpc->eventid=NPCmonster->thisnpc->eventid;
                            npc->event=npc->thisnpc->eventid;
                            //LMA: We have to change the event ID here since we didn't send the clientID :(
                            BEGINPACKET( pak, 0x790 );
                            ADDWORD    ( pak, npc->clientid );
                            ADDWORD    ( pak, npc->thisnpc->eventid );
                            GServer->SendToAllInMap(&pak,map->id);
                         }

                        //LMA: We don't clear anymore, too much hassle :(
                        //We declare the temporary monster just once...
                        /*GServer->ClearClientID(NPCmonster->clientid);
                         delete NPCmonster;*/
                         npc->lastAiUpdate = clock();
                     }

                }

                //LMA: Sometimes another NPC does the job for you.
                if(npc->thisnpc->eventid!=GServer->ObjVar[npc->npctype][0])
                {
                    int new_event_id=GServer->ObjVar[npc->npctype][0];
                    LogDebugPriority(3);
                    //Log(MSG_WARNING,"(2)Event ID not the same NPC %i from %i to %i in map %i, npc->thisnpc->eventid=%i !",npc->npctype,npc->thisnpc->eventid,new_event_id,map->id,npc->thisnpc->eventid);
                    LogDebug("(2)Event ID not the same NPC %i from %i to %i in map %i, npc->thisnpc->eventid=%i !",npc->npctype,npc->thisnpc->eventid,new_event_id,map->id,npc->thisnpc->eventid);
                    LogDebugPriority(4);
                    npc->thisnpc->eventid=new_event_id;
                    npc->event=new_event_id;
                    //LMA: We have to change the event ID here since we didn't send the clientID :(
                    BEGINPACKET( pak, 0x790 );
                    ADDWORD    ( pak, npc->clientid );
                    ADDWORD    ( pak, npc->thisnpc->eventid );
                    GServer->SendToAllInMap(&pak,map->id);
                }

            }

            pthread_mutex_unlock( &map->MonsterMutex );
        }

        pthread_mutex_unlock( &GServer->MapMutex );
        pthread_mutex_unlock( &GServer->PlayerMutex );

        #ifdef _WIN32
        Sleep(GServer->Config.MapDelay);
        #else
        usleep(GServer->Config.MapDelay);
        #endif
    }
    pthread_exit( NULL );

    //LMA: we delete the temporary monster.
    GServer->ClearClientID(NPCmonster->clientid);
    delete NPCmonster;
	return 0;
}