Пример #1
0
void SpellManager::SaveSpell(Client* client, csString spellName)
{
    psSpell* spell = client->GetCharacterData()->GetSpellByName(spellName);
    if(spell)
    {
        psserver->SendSystemInfo(client->GetClientNum(),
                                 "You know the %s spell already!",spellName.GetData());
        return;
    }

    spell = cacheManager->GetSpellByName(spellName);
    if(!spell)
    {
        psserver->SendSystemInfo(client->GetClientNum(),
                                 "%s isn't a defined spell!",spellName.GetData());
        return;
    }


    client->GetCharacterData()->AddSpell(spell);

    psServer::CharacterLoader.SaveCharacterData(client->GetCharacterData(),client->GetActor());

    SendSpellBook(NULL,client);
    psserver->SendSystemInfo(client->GetClientNum(),
                             "%s added to your spell book!",spellName.GetData());
}
Пример #2
0
bool ZoneHandler::ForceLoadWindowWidget(bool enable, csString loadWindowName)
{
    if(enable)
    {
        //check first if the window name is valid. shouldn't end up here
        if(loadWindowName.IsEmpty())
        {
            return false;
        }
        else //if it's valid we load it and set it as load window for now
        {
            PawsManager::GetSingleton().LoadWidget(loadWindowName.GetData());

            //request the load window to update the new window
            if(loadWindow)
                loadWindow->PublishMOTD();

            return FindLoadWindow(true, loadWindowName.GetData());
        }
    }
    else //restore the pointers to the normal window and removes the specified window from the memory
    {
        //restore the ties to the default load window
        bool result = FindLoadWindow(true);
        //as we have reloaded the load window we can remove the widget we don't need anymore
        if(loadWindowName.Length())
            PawsManager::GetSingleton().RemoveWidget(loadWindowName.GetData(), false);

        return result;
    }

    return true;
}
Пример #3
0
    void HandleAnswer(const csString & answer)
    {
        PendingQuestion::HandleAnswer(answer);

        if ( dynamic_cast<psItem*>(item) == NULL )
        {
            Error2("Item held in PendingLootPrompt with id %u has been lost",id);
            return;
        }

        gemActor* looter = gemSupervisor->FindPlayerEntity(looterID);
        gemActor* roller = gemSupervisor->FindPlayerEntity(rollerID);

        gemActor* getter = (answer == "yes") ? looter : roller ;

        // If the getter left the world, default to the other player
        if (!getter /*|| !getter->InGroup()*/ )
        {
            getter = (answer == "yes") ? roller : looter ;

            // If the other player also vanished, get rid of the item and be done with it...
            if (!getter /*|| !getter->InGroup()*/ )
            {
                cacheManager->RemoveInstance(item);
                return;
            }
        }

        // Create the loot message
        csString lootmsg;
        lootmsg.Format("%s was %s a %s by roll winner %s",
                       lootername.GetData(),
                       (getter == looter) ? "allowed to loot" : "stopped from looting",
                       item->GetName(),
                       rollername.GetData() );

        // Attempt to give to getter
        bool dropped = getter->GetCharacterData()->Inventory().AddOrDrop(item);

        if (!dropped)
            lootmsg.Append(", but can't hold anymore");

        // Send out the loot message
        psSystemMessage loot(getter->GetClientID(), MSG_LOOT, lootmsg.GetData() );
        getter->SendGroupMessage(loot.msg);

        psLootEvent evt(
                       looteeID,
                       looteename,
                       getter->GetCharacterData()->GetPID(),
                       lootername,
                       item->GetUID(),
                       item->GetName(),
                       item->GetStackCount(),
                       (int)item->GetCurrentStats()->GetQuality(),
                       0
                       );
        evt.FireEvent();
    }
Пример #4
0
csString psOperProfile::Dump(double totalConsumption, const csString & unitName)
{
    double perc = consumption/totalConsumption*100;
    if (perc > 0)
        return csString().Format(
                "count=%-5u perc=%.1lf %s=%-2i avg-%s=%.3f max=%.3f Name=%s\n",
                unsigned(count), perc, unitName.GetData(), int(consumption),
                unitName.GetData(), consumption/count, maxCons, desc.GetData());
    else
        return "";
}
Пример #5
0
bool AssetManager::LoadAsset (const csString& normpath, const csString& file, const csString& mount,
    iCollection* collection)
{
  csRef<iString> path;
  if (!normpath.IsEmpty ())
  {
    csRef<scfStringArray> fullPath = ConstructPath ();
    path = FindAsset (fullPath, normpath, file);
    if (!path)
      return Error ("Cannot find asset '%s' in the asset path!\n", normpath.GetData ());
  }

  csString rmount;
  if (mount.IsEmpty ())
  {
    rmount.Format ("/assets/__mnt_%d__/", mntCounter);
    mntCounter++;
  }
  else
  {
    rmount = mount;
  }

  if (path)
  {
    vfs->Mount (rmount, path->GetData ());
    printf ("Mounting '%s' to '%s'\n", path->GetData (), rmount.GetData ());
    fflush (stdout);
  }

  vfs->PushDir (rmount);
  // If the file doesn't exist we don't try to load it. That's not an error
  // as it might be saved later.
  bool exists = vfs->Exists (file);
  vfs->PopDir ();
  if (exists)
  {
    if (!LoadLibrary (rmount, file, collection))
      return false;
  }
  else
  {
    Warn ("Warning! File '%s/%s' does not exist!\n",
	(!path) ? rmount.GetData () : path->GetData (), file.GetData ());
  }

  //if (!path.IsEmpty ())
    //vfs->Unmount (rmount, path);
  return true;
}
Пример #6
0
bool LoadPrerequisiteXML(csRef<psQuestPrereqOp>& prerequisite, psQuest * self, csString script)
{
    csRef<iDocumentSystem> xml = csPtr<iDocumentSystem>(new csTinyDocumentSystem);
    csRef<iDocument> doc = xml->CreateDocument();
    const char* error = doc->Parse( script );
    if ( error )
    {
        Error3("%s\n%s",error, script.GetDataSafe() );
        return false;
    }

    csRef<iDocumentNode> root    = doc->GetRoot();
    if(!root)
    {
        Error1("No XML root in prerequisite script");
        return false;
    }
    csRef<iDocumentNode> topNode = root->GetNode("pre");
    if (topNode)
    {
        return LoadPrerequisiteXML(topNode,self,prerequisite);
    }
    else
    {
        Error3("Could not find <pre> tag in prerequisite script '%s' for quest '%s'!",
               script.GetData(),(self?self->GetName():"(null)"));
        return false;
    }

    return true;
}
void pawsNpcDialogWindow::NpcSays(csString &inText,GEMClientActor* actor)
{
    //this is used only when using the chat bubbles interface
    if(!useBubbles)
    {
        return;
    }

    clickedOnResponseBubble = false;

    //display npc response
    if(IsVisible() && actor && psengine->GetCharManager()->GetTarget() == actor)
    {
        dynamic_cast<pawsMultiLineTextBox*>(speechBubble->FindWidget("BubbleText"))->SetText(inText.GetData());
        speechBubble->Show();
        FindWidget("Bubble1")->Hide();
        FindWidget("Bubble2")->Hide();
        FindWidget("Bubble3")->Hide();
        FindWidget("LeftArrow")->Hide();
        FindWidget("RightArrow")->Hide();
        FindWidget("FreeBubble")->Hide();

        ticks = csGetTicks();
        timeDelay = (csTicks)(2000 + 50*strlen(inText.GetData()) + 2000); // add 2 seconds for network delay
        timeDelay =  timeDelay>14000?14000:timeDelay; // clamp to 14000 max

        Show(); //show the npc dialog
    }
}
Пример #8
0
csRef<iDocument> ParseFile(iObjectRegistry* object_reg, const csString & name)
{
    csRef<iVFS> vfs;
    csRef<iDocumentSystem>  xml;
    csRef<iDocument> doc;
    const char* error;
    
    vfs =  csQueryRegistry<iVFS > ( object_reg);
    assert(vfs);
    csRef<iDataBuffer> buff = vfs->ReadFile(name);
    if (buff == NULL)
    {
        //Error2("Could not find file: %s", name.GetData());
        return NULL;
    }
    xml =  csQueryRegistry<iDocumentSystem> (object_reg);
    if (!xml.IsValid())
        xml.AttachNew(new csTinyDocumentSystem);
    assert(xml);
    doc = xml->CreateDocument();
    assert(doc);
    error = doc->Parse( buff );
    if ( error )
    {
        Error3("Parse error in %s: %s", name.GetData(), error);
        return NULL;
    }
    return doc;    
}
Пример #9
0
void pawsExchangeWindow::StartExchange( csString& player, bool withPlayer )
{
    csString text;
    if(!player.IsEmpty())
    {
        text.Format("Trading with %s",player.GetData());
    }

    int width;

    Clear();            
    Show();
            
    pawsTextBox* textBox = dynamic_cast <pawsTextBox*> (FindWidget("other_player"));
    if (textBox != NULL)
        textBox->SetText( text );

    if (withPlayer)
        width = 350;
    else
        width = 175;
    SetRelativeFrameSize(GetActualWidth(width), defaultFrame.Height());

    // Autoshow the inventory
    pawsWidget* widget = PawsManager::GetSingleton().FindWidget("SmallInventoryWindow");
    
    if (widget)
    {
        wasSmallInventoryOpen = widget->IsVisible();
        widget->Show();
    }
}        
Пример #10
0
void pawsControlWindow::AddWindow(csString wndName, csString btnName)
{
    WBName newName;
    pawsButton* btn = (pawsButton*)FindWidget(btnName.GetData());

    if (!btn)
    {
        printf("Couldn't find button %s!\n",btnName.GetData());
        return;
    }

    newName.buttonName = btnName;
    newName.windowName = wndName;
    newName.id = btn->GetID();
    wbs.Push(newName);
}
Пример #11
0
bool pawsStyles::LoadStyles(const csString &fileName)
{
    csRef<iVFS> vfs =  csQueryRegistry<iVFS > (objectReg);
    assert(vfs);
    csRef<iDataBuffer> buff = vfs->ReadFile(fileName);
    if(buff == NULL)
    {
        Error2("Could not find file: %s", fileName.GetData());
        return false;
    }
    csRef<iDocumentSystem> xml;
    xml.AttachNew(new csTinyDocumentSystem);
    assert(xml);
    csRef<iDocument> doc = xml->CreateDocument();
    assert(doc);
    const char* error = doc->Parse(buff);
    if(error)
    {
        Error3("Parse error in %s: %s", fileName.GetData(), error);
        return false;
    }
    csRef<iDocumentNode> root = doc->GetRoot();
    if(root == NULL) return false;
    csRef<iDocumentNode> topNode = root->GetNode("styles");
    if(topNode == NULL)
    {
        Error2("Missing <styles> tag in %s", fileName.GetData());
        return false;
    }

    csRef<iDocumentNodeIterator> iter = topNode->GetNodes("style");
    while(iter->HasNext())
    {
        csRef<iDocumentNode> styleNode = iter->Next();
        csString name = styleNode->GetAttributeValue("name");
        if(styles.In(csString(name)))
        {
            // This is not an error anymore.  Custom skins can and should supercede standard styles.
            //Error2("Warning: PAWS style '%s' defined more than once", name.GetData());
        }
        else
            styles.Put(csString(name), styleNode);
    }

    InheritStyles();
    return true;
}
bool pawsNumbersPromptWindow::TextIsValidForOutput(const csString & text)
{
    if (text.Length() == 0)
        return false;

    int number = atoi(text.GetData());
    return TextIsValidForEditing(text) && (number >= 0) && (number >= minNumber);
}
bool pawsNumbersPromptWindow::TextIsValidForEditing(const csString & text)
{
    if (text.Length() > (unsigned int)maxDigits)
        return false;
                
    for (size_t i=0; i < text.Length(); i++)
        if (!isdigit(text.GetAt(i)) )
            return false;

    if ( 
          (text.GetData() != NULL) 
             && 
          (atoi(text.GetData()) > maxNumber) 
       )
          return false;
    return true;
}
Пример #14
0
csRef<iImage> BaseMapGen::LoadImage (const csString& filename, int format)
{
  csPrintf ("Trying to load '%s'... \t", filename.GetData());
  fflush (stdout);
  csRef<iImage> image;
  csRef<iImageIO> imageio = csQueryRegistry<iImageIO> (object_reg);
  csRef<iVFS> VFS = csQueryRegistry<iVFS> (object_reg);

  csRef<iDataBuffer> buf = VFS->ReadFile (filename.GetData(), false);
  if (!buf)
  {
    Report ("Failed to load image file '%s'!", filename.GetData());
    return GenerateErrorTexture (32, 32);
  }
  image = imageio->Load (buf, format);
  image.IsValid() ? csPrintf ("success.\n") : csPrintf ("failed.\n");

  return image;
}
Пример #15
0
void ZoneHandler::MovePlayerTo(const csVector3 &Pos, float yrot,
                               const csString &newSector, const csVector3 &Vel)
{
    if(!celclient->IsReady())
        return;

    iSector* sector = psengine->GetEngine()->FindSector(newSector);
    if(sector != NULL)
    {
        Notify9(LOG_LOAD, "Setting position of player %f %f %f rot %f in sector '%s' velocity: %f %f %f",
            Pos.x, Pos.y, Pos.z, yrot, newSector.GetData(), Vel.x, Vel.y, Vel.z);
        celclient->GetMainPlayer()->SetPosition(Pos, yrot, sector);          // set new position
        celclient->GetMainPlayer()->SetVelocity(Vel);
    }
    else
    {
        Error2("Couldn't find sector '%s'", newSector.GetData());
    }
}
Пример #16
0
//-----------------------------------------------------------------------------
bool psNPCLoader::SaveToFile(int id, csString &filename)
{
    filename.Insert(0,"/this/");

    psCharacterLoader loader;
    npc = loader.LoadCharacterData(id,false);

    if(!npc)
    {
        CPrintf(CON_ERROR, "Error: Couldn't load NPC with id: %i\n",id);
        return false;
    }

    //*npc = *character;  // removed



    npcID = id;
    area  = npc->GetCharName();

    csRef<iDocumentSystem> xml;
    xml.AttachNew(new csTinyDocumentSystem);
    csRef<iDocument> doc = xml->CreateDocument();
    csRef<iDocumentNode> root = doc->CreateRoot();
    npcRoot = root->CreateNodeBefore(CS_NODE_ELEMENT);
    npcRoot->SetValue("npc");


    WriteBasicInfo();
    WriteDescription();
    WriteLocation();
    WriteStats();
    WriteMoney();
    WriteEquipment();
    WriteFactions();
    WriteSkills();
    WriteMerchantInfo();
    WriteTrainerInfo();
    WriteKnowledgeAreas();
    WriteSpecificKnowledge();

    csRef<iVFS> vfs =  csQueryRegistry<iVFS> (psserver->GetObjectReg());

    if(!vfs)
        return false;

    csString error = doc->Write(vfs, filename);
    if(!error.IsEmpty())
    {
        CPrintf(CON_ERROR, "Error writing to file %s: %s\n",filename.GetData(), error.GetData());
        return false;
    }

    return true;
}
Пример #17
0
bool GMEventManager::CompleteGMEvent (Client* client, csString eventName)
{
    int zero = 0;
    GMEvent* theEvent = GetGMEventByName(eventName, RUNNING, zero);
    if (!theEvent)
    {
        psserver->SendSystemInfo(client->GetClientNum(), "Event %s wasn't found.", eventName.GetData());
        return false;
    }
    return CompleteGMEvent(client, theEvent->gmID, (theEvent->gmID == client->GetPID()));
}
Пример #18
0
//Returns true if it made it visible, returns false if it made it invisible or error
bool pawsControlWindow::HandleWindow(csString widgetStr)
{
    pawsWidget* widget = PawsManager::GetSingleton().FindWidget(widgetStr.GetData());
    if (!widget)
    {
        printf("%s isn't loaded\n",widgetStr.GetData());
        return false;
    }

    if ( widget->IsVisible() )
    {
        widget->Hide();
        if ( this->Includes(PawsManager::GetSingleton().GetCurrentFocusedWidget()) )
            PawsManager::GetSingleton().SetCurrentFocusedWidget(NULL);  // Don't leave focus on us after hiding
        return false;
    }
    else
    {
        widget->Show();
        return true;
    }
}
Пример #19
0
void ChatManager::SendAlliance(const csString & sender, EID senderEID, psGuildAlliance * alliance, psChatMessage& msg)
{
    ClientIterator iter(*psserver->GetConnections());
    psGuildMember * member;

    while(iter.HasNext())
    {
        Client *client = iter.Next();
        if (!client->IsReady()) continue;
        if (client->GetAllianceID() != alliance->GetID()) continue;
        member = client->GetCharacterData()->GetGuildMembership();
        if ( (!member) || (!member->HasRights(RIGHTS_VIEW_CHAT_ALLIANCE)) ) continue;
        // Send the chat message
        psChatMessage newMsg(client->GetClientNum(), senderEID, sender, 0, msg.sText, msg.iChatType, msg.translate);
        newMsg.SendMessage();
        // The message is saved to the chat history of all the clients in the same alliance (PS#2789)
        client->GetActor()->LogChatMessage(sender.GetData(), msg);
    }
}
Пример #20
0
bool BanManager::AddBan(AccountID account, csString ipRange, time_t duration, csString reason, bool banIP)
{
    if (GetBanByAccount(account))
        return false;  // Already banned

    time_t now = time(0);

    BanEntry* newentry = new BanEntry;
    newentry->account = account;
    newentry->start = now;
    newentry->end = now + duration;
    newentry->ipRange = ipRange;
    newentry->reason = reason;
    newentry->banIP = banIP;

    csString escaped;
    db->Escape(escaped, reason.GetData());
    int ret = db->Command("INSERT INTO bans "
                          "(account,ip_range,start,end,reason,ban_ip) "
                          "VALUES ('%u','%s','%u','%u','%s','%u')",
                          newentry->account.Unbox(),
                          newentry->ipRange.GetData(),
                          newentry->start,
                          newentry->end,
                          escaped.GetData(),
                          newentry->banIP );
    if (ret == -1)
    {
        delete newentry;
        return false;
    }

    if (newentry->account.IsValid())
        banList_IDHash.Put(newentry->account,newentry);

    if (newentry->ipRange.Length() && newentry->banIP)
        banList_IPRList.Push(newentry);

    return true;
}
Пример #21
0
bool psEffectManager::LoadFromDirectory(const csString & path, bool includeSubDirs, iView * parentView)
{
    bool success = true;
#ifndef DONT_DO_EFFECTS
    csRef<iVFS> vfs =  csQueryRegistry<iVFS> (psCSSetup::object_reg);
    assert(vfs);

    if (!vfs->Exists(path))
    {
        csReport(psCSSetup::object_reg, CS_REPORTER_SEVERITY_ERROR, "Eulora_effects", "Failed to load effects from directory; %s does not exist", path.GetData());
        return false;
    }

    if (!vfs->ChDir(path))
    {
        csReport(psCSSetup::object_reg, CS_REPORTER_SEVERITY_ERROR, "Eulora_effects", "Failed to load effects from directory; %s read failed", path.GetData());
        return false;
    }

    csRefArray<iThreadReturn> threadReturns;

    csRef<iStringArray> files = vfs->FindFiles("*");
    for (size_t a=0; a<files->GetSize(); ++a)
    {
        const char * file = files->Get(a);
        if (file[0] == '.')
            continue;

        if (strcmp(file, path) == 0)
            continue;

        size_t len = strlen(file);
        char lastChar = file[len-1];
        if (lastChar == '/' || lastChar == '\\')
        {
            if (includeSubDirs)
            {
                if (!LoadFromDirectory(file, true, parentView))
                {
                    success = false;
                }
            }
        }
        else if (len > 4 && ((lastChar == 'f' || lastChar == 'F') && (file[len-2] == 'f' || file[len-2] == 'F') && (file[len-3] == 'e' || file[len-3] == 'E') && file[len-4] == '.'))
        {
            threadReturns.Push(LoadEffects(file, parentView));
        }
    }
#endif
    csRef<iThreadManager> threadman = csQueryRegistry<iThreadManager>(object_reg);
    return threadman->Wait(threadReturns);
}
Пример #22
0
bool psEffectManager::LoadFromEffectsList(const csString & fileName, iView * parentView)
{
#ifndef DONT_DO_EFFECTS
    csRef<iVFS> vfs =  csQueryRegistry<iVFS> (psCSSetup::object_reg);
    assert(vfs);
    
    if (!vfs->Exists(fileName))
        return false;

    csRef<iDocument> doc;
    csRef<iDocumentNodeIterator> xmlbinds;
    csRef<iDocumentSystem>  xml;
    const char* error;

    csRef<iDataBuffer> buff = vfs->ReadFile(fileName);
    if (buff == 0)
    {
        csReport(psCSSetup::object_reg, CS_REPORTER_SEVERITY_ERROR, "Eulora_effects", "Could not find file: %s", fileName.GetData());
        return false;
    }
    xml =  csQueryRegistry<iDocumentSystem> (psCSSetup::object_reg);
    doc = xml->CreateDocument();
    assert(doc);
    error = doc->Parse( buff );
    if ( error )
    {
        csReport(psCSSetup::object_reg, CS_REPORTER_SEVERITY_ERROR, "Eulora_effects",
                 "Parse error in %s: %s", fileName.GetData(), error);
        return false;
    }
    if (doc == 0)
        return false;

    csRef<iDocumentNode> root = doc->GetRoot();
    if (root == 0)
    {
        csReport(psCSSetup::object_reg, CS_REPORTER_SEVERITY_ERROR, "Eulora_effects", "No root in XML");
        return false;
    }

    csRefArray<iThreadReturn> threadReturns;
    csRef<iDocumentNode> listNode = root->GetNode("effectsFileList");
    if (listNode != 0)
    {
        xmlbinds = listNode->GetNodes("effectsFile");
        csRef<iDocumentNode> fileNode;
        while (xmlbinds->HasNext())
        {
            fileNode = xmlbinds->Next();

            csString effectFile = fileNode->GetAttributeValue("file");
            if (vfs->Exists(effectFile))
            {
                threadReturns.Push(LoadEffects(effectFile, parentView));
            }
        }
    }
    csRef<iThreadManager> threadman = csQueryRegistry<iThreadManager>(object_reg);
    return threadman->Wait(threadReturns);
#endif
    return true;
}
Пример #23
0
bool FileUtil::CopyFile(csString from, csString to, bool vfsPath, bool executable, bool silent)
{
    csString n1;
    csString n2;

    csString file = to;
    csRef<iDataBuffer> buff = vfs->GetRealPath(to);
    if(vfsPath)
    {
        // Make parent dir if needed.
        csString parent = to;
        MakeDirectory(parent.Truncate(parent.FindLast('/')));

        if(!buff)
        {
            if(!silent)
                printf("Couldn't get the real filename for %s!\n",to.GetData());
            return false;
        }

        file = buff->GetData();
    }

    // Get current permissions for later.
    csRef<iDataBuffer> fromBuff = vfs->GetRealPath(from);
    csRef<FileStat> fromStat = StatFile(fromBuff->GetData());

    csRef<FileStat> stat = StatFile(file);
    if(stat && stat->readonly)
    {
        if(!silent)
            printf("Won't write to %s, because it's readonly\n",file.GetData());
        return true; // Return true to bypass DLL checks and stuff
    }

    if (!vfsPath)
    {
        n1 = "/this/" + from;
        n2 = "/this/" + to;
    }
    else
    {
        n1= from;
        n2= to;
    }

    csRef<iDataBuffer> buffer = vfs->ReadFile(n1.GetData(),true);

    if (!buffer)
    {
        if(!silent)
            printf("Couldn't read file %s!\n",n1.GetData());
        return false;
    }

    if (!vfs->WriteFile(n2.GetData(), buffer->GetData(), buffer->GetSize() ) )
    {
        if(!silent)
            printf("Couldn't write to %s!\n", n2.GetData());
        return false;
    }

#ifdef CS_PLATFORM_UNIX
    /**
     * On unix type systems we might need to set permissions after copy.
     * If the 'from' stat is null, the file is probably in a zip.
     * So we use the permissions of the parent folder of the 'to' location.
     */
    if(!fromStat.IsValid())
    {
        n2.Truncate(n2.FindLast('/')+1);
        csRef<iDataBuffer> db = vfs->GetRealPath(n2);
        fromStat = StatFile(db->GetData());
    }
    SetPermissions(buff->GetData(), fromStat);
    if(executable)
    {
        if(chmod(buff->GetData(), fromStat->mode | S_IXUSR | S_IXGRP) == -1)
            printf("Failed to set permissions on file %s.\n", to.GetData());
    }
#endif

    return true;
}
void pawsItemDescriptionWindow::ShowItemDescription(csString &desc, csString &itemName, csString &icon, int count)
{
    csString displayName;
    displayName.Format("%s (%d)",itemName.GetData(),count);
    ShowItemDescription(desc,displayName,icon);
}
Пример #25
0
void SpellManager::Cast(gemActor* caster, const csString &spellName, float kFactor, Client* client)
{
    psSpell* spell = NULL;

    if( spellName=="" )
    {
        //this is a request to send the current active magic list
        caster->SendActiveSpells();
        return;
    }

    // Allow developers to cast any spell
    bool canCastAllSpells;
    if(client)
    {
        canCastAllSpells = cacheManager->GetCommandManager()->Validate(client->GetSecurityLevel(), "cast all spells");
    }
    else
    {
        canCastAllSpells = true; // For now grant the NPC client the same priveledge as game masters and developers.
    }

    // Allow developers to cast any spell, even if unknown to the character.
    if(canCastAllSpells)
    {
        spell = cacheManager->GetSpellByName(spellName);
    }
    else
    {
        spell = client->GetCharacterData()->GetSpellByName(spellName);
    }

    //spells with empty glyphlists are not enabled
    if(!spell || spell->GetGlyphList().IsEmpty())
    {
        if(client)
        {
            psserver->SendSystemInfo(client->GetClientNum(), "You don't know a spell called %s.",spellName.GetData());
        }
        else
        {
            Debug3(LOG_SUPERCLIENT,caster->GetEID().Unbox(),"%s don't know a spell called %s.",caster->GetName(),spellName.GetDataSafe());
        }
        return;
    }

    // Clamp kFactor to sane values.
    if(kFactor < 0.0)
    {
        kFactor = 0.0;
    }
    if(kFactor > 100.0)
    {
        kFactor = 100.0;
    }

    csString reason;
    if(!spell->CanCast(caster, kFactor, reason, canCastAllSpells))
    {
        if(client)
        {
            psserver->SendSystemInfo(client->GetClientNum(), reason.GetData());
        }
        else
        {
            Debug3(LOG_SUPERCLIENT,caster->GetEID().Unbox(),"%s: %s.",caster->GetName(),reason.GetDataSafe());
        }

        return;
    }

    spell->Cast(caster, kFactor, client);
}
Пример #26
0
bool psMiniGameSession::Load(csString &responseString)
{
#ifdef DEBUG_MINIGAMES
    Debug2(LOG_ANY, 0, "Loading minigame: %s", responseString.GetData());
#endif

    options = 0;

    if(!responseString.StartsWith("<Examine>", false))
    {
        Error2("Invalid response string for minigame %s.", name.GetData());
        return false;
    }

    csRef<iDocument> doc = ParseString(responseString);
    if(!doc)
    {
        Error2("Parse error in minigame %s response string.", name.GetData());
        return false;
    }

    csRef<iDocumentNode> root = doc->GetRoot();
    if(!root)
    {
        Error2("No XML root in minigame %s response string.", name.GetData());
        return false;
    }

    csRef<iDocumentNode> topNode = root->GetNode("Examine");
    if(!topNode)
    {
        Error2("No <Examine> tag in minigame %s response string.", name.GetData());
        return false;
    }

    csRef<iDocumentNode> boardNode = topNode->GetNode("GameBoard");
    if(!boardNode)
    {
        Error2("No <Board> tag in minigame %s response string.", name.GetData());
        return false;
    }

    const char* gameName = boardNode->GetAttributeValue("Name");
    psMiniGameBoardDef* gameBoardDef = manager->FindGameDef(gameName);
    if(!gameBoardDef)
    {
        Error2("Game board \"%s\" not defined.", gameName);
        return false;
    }

    // Get the optional layout string; will override the default layout
    const char* layoutStr = boardNode->GetAttributeValue("Layout");
    uint8_t* layout = NULL;
    if(layoutStr && strlen(layoutStr) != size_t(gameBoardDef->GetRows() * gameBoardDef->GetCols()))
    {
        Error2("Layout string in action_location minigame %s response string invalid. Using default.", gameName);
    }
    else if(layoutStr)
    {
        layout = new uint8_t[gameBoardDef->GetLayoutSize()];
        gameBoardDef->PackLayoutString(layoutStr, layout);
    }

    // get the gameboard def options
    options |= gameBoardDef->GetGameboardOptions();

    // get the session type. "Personal" means a minigame session per player; each player gets their
    // own personal session (i.e. no watchers, and restricted to single player games). Expected application
    // for personal minigames is in-game puzzles, including quest steps maybe.
    // "Public" is the more traditional, two player leisure games, such as Groffels Toe.
    csString sessionStr(boardNode->GetAttributeValue("Session"));
    sessionStr.Downcase();
    if(sessionStr == "personal")
    {
        options |= PERSONAL_GAME;
    }
    else if(sessionStr.Length() > 0 && sessionStr != "public")
    {
        Error2("Session setting for minigame %s invalid. Defaulting to \'Public\'", gameName);
    }

    // whether to observe the end game settings. If so, the server observes the moves made and
    // can identify the end game pattern(s). Default = No.
    csString endgameStr(boardNode->GetAttributeValue("EndGame"));
    endgameStr.Downcase();
    if(endgameStr == "yes")
    {
        options |= OBSERVE_ENDGAME;
    }
    else if(endgameStr.Length() > 0 && endgameStr != "no")
    {
        Error2("ObserveEndGame setting for %s invalid. Defaulting to \'No\'", gameName);
    }

    // read any script name for winner
    csString scriptStr(boardNode->GetAttributeValue("Script"));
    if(scriptStr.Length() > 0)
    {
        if(options & OBSERVE_ENDGAME)
        {
            winnerScript = scriptStr;
        }
        else
        {
            Error2("Ignoring invalid script for %s.", gameName);
        }
    }
    // read parameters for the script
    csString param0(boardNode->GetAttributeValue("Param0"));
    if(param0.Length() > 0)
        paramZero = param0;
    csString param1(boardNode->GetAttributeValue("Param1"));
    if(param1.Length() > 0)
        paramOne = param1;
    csString param2(boardNode->GetAttributeValue("Param2"));
    if(param2.Length() > 0)
        paramTwo = param2;

    // Setup the game board
    gameBoard.Setup(gameBoardDef, layout);
    delete [] layout;

    // if session is personal, check its a 1-player game
    if((options & PERSONAL_GAME) && gameBoard.GetNumPlayers() > 1)
    {
        Error2("Personal game %s has 2 or more players, which is untenable.", gameName);
        return false;
    }

    // initialise players
    MinigamePlayer* player, *previousPlayer = NULL;
    for(int p=0; p<gameBoard.GetNumPlayers(); p++)
    {
        player = new MinigamePlayer();
        if(!player)
        {
            Error2("Cannot initialise players for %s.", gameName);
            return false;
        }

        player->playerID = (uint32_t)-1;
        player->playerName = NULL;
        player->nextMover = NULL;

        // organise order of play, if appropriate
        if(gameBoard.GetPlayerTurnRule() >= ORDERED)
        {
            if(p == 0)
            {
                nextPlayerToMove = player;
            }
            else
            {
                previousPlayer->nextMover = player;
            }
            previousPlayer = player;
        }

        players.Push(player);
    }
    if(previousPlayer)
    {
        previousPlayer->nextMover = nextPlayerToMove;
    }

    // determine style of minigame: currently based on number of players only
    minigameStyle = (gameBoard.GetNumPlayers()==1) ? MG_PUZZLE : MG_GAME;

    return true;
}
Пример #27
0
void AdviceManager::HandleAdviceRequest( Client *advisee, csString message )
{
    //    psserver->SendSystemInfo( advisee->GetClientNum(), "Sorry for the inconvenience, you cannot request advice right now. The advice system is under maintenaince and will be available after a server restart soon.");
    //    return;

    if ( advisee->GetAdvisor() )
    {
        psserver->SendSystemInfo( advisee->GetClientNum(), "You cannot request advice while you are an advisor. Lay down your advisor role using \"/advisor off\", then request advice.");
        return;
    }

    if ( advisors.GetSize() == 0 )                             //No advisors are online
    {
        //Send back an message that there is no advisor online
        psserver->SendSystemInfo( advisee->GetClientNum(),"The world has no advisors at the moment. You may ask for further help on IRC or on our forums. You may also try to ask players around you for help with \"/tell <player name> <message>\".");
        return;
    }

    // find existing Advicee in the List
    AdviceSession *activeSession = AdviseeList.Get(advisee->GetClientNum(), NULL);

    // Create an adviceSession if one doesn't exist and the message is valid
    if ( !activeSession )
    {
        WordArray words(message);
        // Check to make sure the request is 'good'
        if ( words.GetCount() < 2 )
        {
            psserver->SendSystemInfo( advisee->GetClientNum(),
                                     "An Advisor will need more information than this to help you, please include as much as you can in your request.");
            return;
        }

        Debug2( LOG_ANY, advisee->GetClientNum(), "Creating AdviceSession for %d", advisee->GetClientNum() );
        activeSession = new AdviceSession( this, NULL, advisee, message );
        AdviseeList.Put(activeSession->AdviseeClientNum, activeSession);  // Advice is no longer pending.
    }
    else
    {
        // One unadvised unanswered question at a time
        if (!activeSession->GetAdvisor() && !activeSession->answered)
        {
            psserver->SendSystemError(advisee->GetClientNum(), "Please wait for an advisor to respond to your previous inquiry before asking another question.");
            return;
        }
    }
    //at this point active session will always be valid because it's either recovered from the
    //stored sessions or it was just created.
    // Create psAdviceRequestTimeoutGameEvent to timeout question.
    if (activeSession->timeoutEvent == NULL && activeSession->requestEvent == NULL)
    {
        psAdviceRequestTimeoutGameEvent *ev = new psAdviceRequestTimeoutGameEvent( this, ADVICE_QUESTION_TIMEOUT, advisee->GetActor(), activeSession );
        activeSession->requestEvent = ev;
        psserver->GetEventManager()->Push(ev);
    }
    else
    {
        WordArray words(message);

        // Check to make sure the request is 'good'
        if ( words.GetCount() < 2 )
        {
            psserver->SendSystemInfo(advisee->GetClientNum(), "An Advisor will need more information than this to help you, please include as much as you can in your request.");
            activeSession->answered = true;
            return;
        }

        if ( activeSession->timeoutEvent )
        {
            activeSession->timeoutEvent->valid = false;
        }
        psAdviceSessionTimeoutGameEvent *ev = new psAdviceSessionTimeoutGameEvent( this, activeSession->answered?ADVICE_SESSION_TIMEOUT:ADVICE_SESSION_TIMEOUT/2, advisee->GetActor(), activeSession );
        activeSession->timeoutEvent = ev;
        psserver->GetEventManager()->Push(ev);
    }

    //we set the session as unanswered as we have a new message.
    activeSession->answered = false;
    activeSession->lastRequest = message;

    csString buf;

    if ( activeSession->AdvisorClientNum != (uint32_t)-1 )
    {
        // Source Client Name, Target Client Name, Message
        buf.Format("%s, %s, \"%s\"", advisee->GetName(), activeSession->GetAdvisor()->GetActor()->GetName(), message.GetData() );
        psserver->GetLogCSV()->Write(CSV_ADVICE, buf);

        psChatMessage msgAdvisor( activeSession->AdvisorClientNum, 0, advisee->GetName(), 0, message , CHAT_ADVICE, false );
        msgAdvisor.SendMessage();

        // Send message to GM chars as well
        for (size_t i = 0; i < advisors.GetSize(); i++)
        {
            if (!advisors[i].GM || advisors[i].id == activeSession->AdvisorClientNum)
                continue;
            psChatMessage msgAdvisor( advisors[i].id, 0, advisee->GetName(), 0, message, CHAT_ADVICE, false);
            msgAdvisor.SendMessage();
        }
    }
    else
    {
        // Source Client Name, Target Client Name, Message
        buf.Format("%s, %s, \"%s\"", advisee->GetName(), "All Advisors", message.GetData() );
        psserver->GetLogCSV()->Write(CSV_ADVICE, buf);

        for (size_t i = 0; i < advisors.GetSize(); i++)
        {
            psChatMessage msgAdvisor( advisors[i].id, 0, advisee->GetName(), 0, message, CHAT_ADVICE, false);
            msgAdvisor.SendMessage();
        }
    }
    psChatMessage msgChat( advisee->GetClientNum() , 0, advisee->GetName(), 0, message, CHAT_ADVICE, false);
    msgChat.SendMessage();


}
Пример #28
0
void AdviceManager::HandleAdviceResponse( Client *advisor, csString sAdvisee, csString message)
{
    if ( !advisor->GetAdvisor() )
    {
        psserver->SendSystemInfo(advisor->GetClientNum(),"You need to be an advisor to use this command.");
        return;
    }

    csString buf;
    // Source Client Name, Target Client Name, Message
    buf.Format("%s, %s, \"%s\"", advisor->GetName(), sAdvisee.GetData() , message.GetData());
    psserver->GetLogCSV()->Write(CSV_ADVICE, buf);

    // Find Advisee Client by name
    if (sAdvisee.Length())
    {
        sAdvisee = NormalizeCharacterName(sAdvisee);
    }
    Client *advisee = psserver->GetConnections()->Find(sAdvisee);
    if (!advisee)
    {
        // Create a new message to report TELL error and send
        // back to original person.
        csString sMsg("No player named ");
        sMsg += sAdvisee;
        sMsg += " is logged on to the system currently.";
        psserver->SendSystemError(advisor->GetClientNum(), sMsg);
        return;
    }

    // Can't allow you to advise yourself
    if ( advisee == advisor )
    {
        psserver->SendSystemError(advisor->GetClientNum(), "You are not allowed to advise yourself. Please wait for another advisor.");
        return;
    }

    // find existing Advicee in the List
    AdviceSession key;
    key.AdviseeClientNum = advisee->GetClientNum();
    AdviceSession *activeSession = AdviseeList.Get(advisee->GetClientNum(), NULL);

    if (!activeSession || (activeSession  && ( !activeSession->requestEvent ) && ( activeSession->GetAdvisor() == NULL ) ) )
    {
        psserver->SendSystemError(advisor->GetClientNum(), "%s has not requested help.", advisee->GetName());
        return;
    }

    if (activeSession  && ( activeSession->AdviseeClientNum != advisee->GetClientNum() ) )
    {
        Debug2( LOG_ANY, advisee->GetClientNum(), "Grabbed wrong advisor session: %d", activeSession->AdviseeClientNum );
    }

    if ( ( activeSession->GetAdvisor() != NULL ) && ( activeSession->AdvisorClientNum != advisor->GetClientNum() ) )
    {
        psserver->SendSystemError(advisor->GetClientNum(), "%s is being advised already, thank you.",  advisee->GetName());
        return;
    }

    if ( message.Length() == 0  && activeSession->status == SESSION_STATUS_UNKNOWN ) // advisor is claiming a session
    {
        // check to make sure advisor has only one claimed session.
        AdviceSession *loopSession;

        csHash< AdviceSession* >::GlobalIterator loop( AdviseeList.GetIterator() );

        while(loop.HasNext())
        {
        	loopSession = loop.Next();
            if (activeSession->status == SESSION_STATUS_CLAIMED && loopSession->GetAdvisor() == advisor )
            {
                psserver->SendSystemInfo(advisor->GetClientNum(), "You cannot have two messengers waiting for you at the same time, please answer %s's request first." , loopSession->adviseeName.GetData() );
                return;
            }
        }

        activeSession->SetAdvisor( advisor );
        psserver->SendSystemInfo(advisee->GetClientNum(), "An advisor is preparing an answer to your question, please be patient.");
        psserver->SendSystemInfo(advisor->GetClientNum(), "You have claimed the session with %s. Please provide an answer." , advisee->GetName() );

        for (size_t i = 0; i < advisors.GetSize(); i++)
        {
            if ( advisors[i].id != activeSession->AdvisorClientNum )
            {
                psserver->SendSystemInfo(advisors[i].id, "%s has proclaimed they know the answer to %s's question.", advisor->GetName(), advisee->GetName() );
            }
        }
        activeSession->status = SESSION_STATUS_CLAIMED;
    }
    else
    {
        if (message.IsEmpty())
        {
            psserver->SendSystemInfo(advisor->GetClientNum(), "Please enter the advice you wish to give.");
            return;
        }

        psChatMessage msgChat(activeSession->AdviseeClientNum, 0, advisor->GetName(), advisee->GetName(), message ,CHAT_ADVISOR,false);

        if ( activeSession->GetAdvisor() == NULL || activeSession->status != SESSION_STATUS_OWNED )
        {
            // Check to make sure the advice is 'good'
            // if ( message.Length() < 20 )
            // {
                // psserver->SendSystemInfo(advisor->GetClientNum(), "Please be more specific when answering questions. Your advice has been ignored.");
                // return;
            // }

            //activeSession->AdvisorClientNum = me->clientnum;
            activeSession->SetAdvisor( advisor );
            advisor->IncrementAdvisorPoints(activeSession->advisorPoints);
            psserver->CharacterLoader.SaveCharacterData( advisor->GetCharacterData(), advisor->GetActor(), true );

            // Send Confirmation to advisor
            psserver->SendSystemInfo( advisor->GetClientNum(), "You are now advising %s.",advisee->GetName());

            // Send Confirmation to all other advisors so they know they lost this one.
            for (size_t i = 0; i < advisors.GetSize(); i++)
            {
                if ( advisors[i].id != activeSession->AdvisorClientNum )
                {
                    psserver->SendSystemInfo( advisors[i].id, "%s has been assigned to %s.",  advisee->GetName(), advisor->GetName() );
                    if ( advisors[i].GM )
                        continue;
                    msgChat.msg->clientnum = advisors[i].id;
                    msgChat.SendMessage();
                }
            }
            activeSession->status = SESSION_STATUS_OWNED;
        }

        if ( activeSession->requestEvent )
            activeSession->requestEvent->valid = false;  // This keeps the cancellation timeout from firing.

        activeSession->answered = true;

        // Send Message to Advisee
        msgChat.msg->clientnum = activeSession->AdviseeClientNum;
        msgChat.SendMessage();

        // Send Message to advisor
        msgChat.msg->clientnum = activeSession->AdvisorClientNum;
        msgChat.SendMessage();

        // Send message to GM chars as well
        for (size_t i = 0; i < advisors.GetSize(); i++)
        {
            if (!advisors[i].GM || advisors[i].id == activeSession->AdvisorClientNum)
                continue;
            msgChat.msg->clientnum = advisors[i].id;
            msgChat.SendMessage();
        }
    }

    // Add timeout for Advisor-Advisee relationship
    // this will allow later questions by the same client to go to a different advisor
    // spreading the wealth and burden amongst all ;)
    if ( activeSession->timeoutEvent )
    {
        activeSession->timeoutEvent->valid = false;
    }
    psAdviceSessionTimeoutGameEvent *ev = new psAdviceSessionTimeoutGameEvent( this, activeSession->answered?ADVICE_SESSION_TIMEOUT:ADVICE_SESSION_TIMEOUT/2, advisee->GetActor(), activeSession );
    activeSession->timeoutEvent = ev;
    psserver->GetEventManager()->Push(ev);

}
void pawsGroupWindow::HandleMembers( csString& members )
{
    memberList->Clear();

    csRef<iDocumentSystem> xml =  csQueryRegistry<iDocumentSystem > ( PawsManager::GetSingleton().GetObjectRegistry());
    csRef<iDocument> doc = xml->CreateDocument();
    const char* error = doc->Parse( members );

    if ( error )
    {
        Error2("Error in XML: %s\n", error );
        return;
    }

    csRef<iDocumentNode> root = doc->GetRoot();
    if(!root)
    {
        Error2("No XML root in %s", members.GetData());
        return;
    }
    csRef<iDocumentNode> xmlmembers = root->GetNode("L");
    if(!xmlmembers)
    {
        Error2("No <L> tag in %s", members.GetData());
        return;

    }

    csRef<iDocumentNodeIterator> iter = xmlmembers->GetNodes("M");

    while ( iter->HasNext() )
    {
        csRef<iDocumentNode> member = iter->Next();

        pawsListBoxRow* box = memberList->NewRow();
        pawsWidget* stats = box->GetColumn(0)->FindWidget("stats");
        pawsProgressBar *progress;
        pawsTextBox *text;
        pawsWidget *icon;

        box->SetName ( member->GetAttributeValue("N") );

        icon = stats->FindWidget("ICON");
        icon->SetBackground(csString(member->GetAttributeValue("R")) + " Icon");

        chatWindow->AddAutoCompleteName( member->GetAttributeValue("N") );

        //Set name
        text = (pawsTextBox*)stats->FindWidget("NAME");
        text->SetText( member->GetAttributeValue("N") );

        //Set HP
        progress = (pawsProgressBar*)stats->FindWidget("HP");
        progress->SetTotalValue( 1 );
        progress->SetCurrentValue(member->GetAttributeValueAsFloat("H")/100);

        //Set mana
        progress = (pawsProgressBar*)stats->FindWidget("MANA");
        progress->SetTotalValue( 1 );
        progress->SetCurrentValue(member->GetAttributeValueAsFloat("M")/100);

    }
}
Пример #30
0
csString LootRandomizer::GenerateScriptXML(csString &name, csString &equip_script, csArray<ValueModifier> &values)
{
    csString scriptXML;
    csHash<float, csString> results;

    //prepare the heading of the apply script
    scriptXML.Format("<apply aim=\"Actor\" name=\"%s\" type=\"buff\">", name.GetData());

    //parse the values and try to find the default values for all variables
    //and put them in the hash in order to simplify access.
    for(size_t i = 0; i < values.GetSize(); ++i)
    {
        //Do it only for the VAL references which identify a default value.
        if(values[i].op.CompareNoCase("VAL"))
        {
            results.PutUnique(values[i].name, values[i].value);
            //delete the entry as we don't need it anymore, in order to reduce the
            //amount of items to check later
            values.DeleteIndex(i);
            //reduce the index as we have removed an item
            i--;
        }
    }
    //then do all the others operation entries, in order of definition.
    for(size_t i = 0; i < values.GetSize(); ++i)
    {
        //first of all check if the item is available in its default value
        //if it's not we are ignoring the operation as the variable is not
        //defined.
        if(results.Contains(values[i].name))
        {
            //we don't check for null as at this point it's safe the presence
            //of the variable in the hash (due to the check of contains).
            float* value[1] = {results.GetElementPointer(values[i].name)};
            SetAttributeApplyOP(value, values[i].value, 1, values[i].op);
        }
        else
        {
            Error2("Unable to find base value for variable %s", values[i].name.GetData());
        }
    }

    // If we have any variables defined, we add their definitions
    // on top of the script.
    if(!results.IsEmpty())
    {
        scriptXML.AppendFmt("<let vars=\"");
        csHash<float, csString>::GlobalIterator it = results.GetIterator();
        while(it.HasNext())
        {
            csTuple2<float, csString> entry = it.NextTuple();
            scriptXML.AppendFmt("%s = %f;", entry.second.GetData(), entry.first);
        }
        scriptXML.AppendFmt("\">%s</let></apply>", equip_script.GetData());
    }
    else
    {
        scriptXML.AppendFmt("%s</apply>", equip_script.GetData());
    }

    return scriptXML;
}