コード例 #1
0
ファイル: pawssummary.cpp プロジェクト: garinh/planeshift
void pawsSummaryWindow::SetVerify( csArray<psCharVerificationMesg::Attribute> stats,
                                   csArray<psCharVerificationMesg::Attribute> skills )
{
    statsList->Clear();
    skillsList->Clear();
    
    for ( size_t x = 0; x < skills.GetSize(); x++ )
    {       
        if (skills[x].value)
        {
            pawsListBoxRow* row = skillsList->NewRow();
            pawsTextBox* name = (pawsTextBox*)row->GetColumn(0);
            name->SetText( skills[x].name );

            pawsTextBox* val = (pawsTextBox*)row->GetColumn(1);
            val->FormatText( "%d", skills[x].value );
        }
    }
    
    for ( size_t x = 0; x < stats.GetSize(); x++ )
    {       
        if (stats[x].value)
        {
            pawsListBoxRow* row = statsList->NewRow();
            pawsTextBox* name = (pawsTextBox*)row->GetColumn(0);
            name->SetText( stats[x].name );
                       
            pawsTextBox* val = (pawsTextBox*)row->GetColumn(1);
            val->FormatText( "%d", stats[x].value );
        }
    }
     
    serverStatus->SetText(PawsManager::GetSingleton().Translate("Verification complete"));     
}
コード例 #2
0
ファイル: pawsmanager.cpp プロジェクト: garinh/planeshift
bool PawsManager::LoadChildWidgets( const char* widgetFile, csArray<pawsWidget *> &loadedWidgets )
{
    bool errors=false;
    loadedWidgets.DeleteAll();
    csString fullPath = localization->FindLocalizedFile(widgetFile);

    csRef<iDocumentNode> topNode = ParseWidgetFile( fullPath );
    if (!topNode) return false;
    csRef<iDocumentNodeIterator> iter = topNode->GetNodes();

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

        if ( node->GetType() != CS_NODE_ELEMENT )
            continue;

        // This is a widget so read it's factory to create it.
        pawsWidget * widget = LoadWidget(node);
        if (widget)
            loadedWidgets.Push(widget);
        else
            errors = true;
    }
    return (!errors);
}
コード例 #3
0
ファイル: bsptree.cpp プロジェクト: GameLemur/Crystal-Space
void csBSPTree::Build (csTriangle* triangles, csPlane3* planes,
	size_t num_triangles, const csVector3* vertices,
	const csArray<int>& triidx)
{
  CS_ASSERT (triidx.GetSize () > 0);
  if (triidx.GetSize () == 1)
  {
    splitters.Push (triidx[0]);
    return;
  }

  size_t idx = FindBestSplitter (triangles, planes, num_triangles, vertices,
  	triidx);
  CS_ASSERT (idx != (size_t)-1);
  splitters.Push (triidx[idx]);

  csArray<int> left;
  csArray<int> right;
  size_t i;
  split_plane = planes[triidx[idx]];
  for (i = 0 ; i < triidx.GetSize () ; i++)
    if (i != idx)
    {
      int idxi = triidx[i];
      csTriangle& trj = triangles[idxi];
      int cla = ClassifyPlane (split_plane, vertices[trj.a]);
      int clb = ClassifyPlane (split_plane, vertices[trj.b]);
      int clc = ClassifyPlane (split_plane, vertices[trj.c]);
      if ((cla == -clb && cla != 0) ||
	  (cla == -clc && cla != 0) ||
	  (clb == -clc && clb != 0))
      {
	// There is a split.
	left.Push (idxi);
	right.Push (idxi);
      }
      else
      {
	if (cla == -1 || clb == -1 || clc == -1)
	  left.Push (idxi);
	else if (cla == 1 || clb == 1 || clc == 1)
	  right.Push (idxi);
        else
	  splitters.Push (idxi);
      }
    }
  if (left.GetSize () > 0)
  {
    child1 = TreeNodes()->Alloc ();
    child1->Build (triangles, planes, num_triangles, vertices, left);
  }
  if (right.GetSize () > 0)
  {
    child2 = TreeNodes()->Alloc ();
    child2->Build (triangles, planes, num_triangles, vertices, right);
  }
}
コード例 #4
0
void psNetMsgProfiles::AddEnoughRecords(csArray<psOperProfile*> & arr, int neededIndex, const char * desc)
{
    while (neededIndex >= (int)arr.GetSize())
    {
        csStringFast<100> fullDesc = GetMsgTypeName((int)arr.GetSize()) + "-" + csStringFast<100>(desc);
        psOperProfile * newProf = new psOperProfile(fullDesc);
        arr.Push(newProf);
        profs.Push(newProf);
    }
}
コード例 #5
0
ファイル: gmeventmanager.cpp プロジェクト: garinh/planeshift
int GMEventManager::GetAllGMEventsForPlayer (PID playerID,
                                             csArray<int>& completedEvents,
                                             int& runningEventAsGM,
                                             csArray<int>& completedEventsAsGM)
{
    int runningEvent = -1, id, index=0;
    GMEvent* gmEvent;

    completedEvents.DeleteAll();
    completedEventsAsGM.DeleteAll();

    if ((gmEvent = GetGMEventByGM(playerID, RUNNING, index)))
    {
        runningEventAsGM = gmEvent->id;
    }
    else
    {
        runningEventAsGM = -1;
    }

    index = 0;
    do
    {
        gmEvent = GetGMEventByGM(playerID, COMPLETED, index);
        if (gmEvent)
        {
            id = gmEvent->id;
            completedEventsAsGM.Push(id);
        }
    }
    while (gmEvent);

    index = 0;
    gmEvent = GetGMEventByPlayer(playerID, RUNNING, index);
    if (gmEvent)
        runningEvent = gmEvent->id;

    index = 0;
    do
    {
        gmEvent = GetGMEventByPlayer(playerID, COMPLETED, index);
        if (gmEvent)
        {
            id = gmEvent->id;
            completedEvents.Push(id);
        }
    }
    while (gmEvent);

    return (runningEvent);
}
コード例 #6
0
void csPixelShaderParser::WriteProgram (
	const csArray<csPSProgramInstruction>& instrs, 
	csString& str) const
{
  for(size_t i = 0; i < instrs.GetSize (); i++)
  {
    const csPSProgramInstruction& instr = instrs.Get (i);

    csString line;
    GetInstructionLine (instr, line);
    str << line;
    str << '\n';
  }
}
コード例 #7
0
ファイル: furdata.cpp プロジェクト: GameLemur/Crystal-Space
  void csFurStrand::SetUV( const csArray<csGuideFur> &guideFurs,
    const csArray<csGuideFurLOD> &guideFursLOD )
  {
    csVector2 strandUV(0);

    for ( size_t j = 0 ; j < GUIDE_HAIRS_COUNT ; j ++ )
      if (guideHairsRef[j].index < guideFurs.GetSize() )
        strandUV += guideHairsRef[j].distance * 
          guideFurs.Get(guideHairsRef[j].index).uv;
      else
        strandUV += guideHairsRef[j].distance * 
          guideFursLOD.Get(guideHairsRef[j].index - guideFurs.GetSize()).uv;

    uv = strandUV;
  }
コード例 #8
0
ファイル: terrainldr.cpp プロジェクト: garinh/cs
bool csTerrainObjectLoader::ParseMaterialPalette (iDocumentNode *node,
       iLoaderContext *ldr_context, csArray<iMaterialWrapper*>& palette)
{
  csRef<iDocumentNodeIterator> it = node->GetNodes ();
  while (it->HasNext ())
  {
    csRef<iDocumentNode> child = it->Next ();
    if (child->GetType () != CS_NODE_ELEMENT) continue;
    const char *value = child->GetValue ();
    csStringID id = xmltokens.Request (value);
    switch (id)
    {
      case XMLTOKEN_MATERIAL:
      {
        const char* matname = child->GetContentsValue ();
        csRef<iMaterialWrapper> mat = ldr_context->FindMaterial (matname);
        if (!mat)
        {
          synldr->ReportError (
            "crystalspace.terrain.object.loader.materialpalette",
            child, "Couldn't find material '%s'!", matname);
          return false;
        }
        palette.Push (mat);
        break;
      }
      default:
        synldr->ReportError (
          "crystalspace.terrain.object.loader.materialpalette",
          child, "Unknown token in materials list!");
    }
  }
  return true;
}
コード例 #9
0
ファイル: furdata.cpp プロジェクト: GameLemur/Crystal-Space
  void csFurStrand::Update( const csArray<csGuideFur> &guideFurs,
    const csArray<csGuideFurLOD> &guideFursLOD, float controlPointsLOD)
  {
    for ( size_t i = 0 ; i < GetControlPointsCount(controlPointsLOD); i++ )
    {
      controlPoints[i] = csVector3(0);

      for ( size_t j = 0 ; j < GUIDE_HAIRS_COUNT ; j ++ )
        if ( guideHairsRef[j].index < guideFurs.GetSize() )
          controlPoints[i] += guideHairsRef[j].distance * 
            (guideFurs.Get(guideHairsRef[j].index).controlPoints[i]);
        else
          controlPoints[i] += guideHairsRef[j].distance * (guideFursLOD.Get
            (guideHairsRef[j].index - guideFurs.GetSize()).controlPoints[i]);
    }
  }
コード例 #10
0
ファイル: box.cpp プロジェクト: garinh/cs
bool csBox3::ProjectOutline (const csVector3& origin,
                             int axis, float where, csArray<csVector2>& poly) const
{
    int idx = CalculatePointSegment (origin);
    const Outline &ol = outlines[idx];
    int num_array = MIN (ol.num, 6);

    int i;
    for (i = 0 ; i < num_array ; i++)
    {
        csVector3 isect;
        if (!csIntersect3::SegmentAxisPlane (origin, GetCorner (ol.vertices[i]),
                                             axis, where, isect))
            return false;
        csVector2 v;
        switch (axis)
        {
        case CS_AXIS_X:
            v.x = isect.y;
            v.y = isect.z;
            break;
        case CS_AXIS_Y:
            v.x = isect.x;
            v.y = isect.z;
            break;
        case CS_AXIS_Z:
            v.x = isect.x;
            v.y = isect.y;
            break;
        }
        poly.Push (v);
    }
    return true;
}
コード例 #11
0
ファイル: bsptree.cpp プロジェクト: GameLemur/Crystal-Space
size_t csBSPTree::FindBestSplitter (csTriangle* triangles, csPlane3* planes,
	size_t /*num_triangles*/, const csVector3* vertices,
	const csArray<int>& triidx)
{
  size_t i, j;
  float mincost = 1000000.0;
  size_t minidx = (size_t)-1;
  for (i = 0 ; i < triidx.GetSize () ; i++)
  {
    int cnt_splits = 0;
    int cnt_left = 0;
    int cnt_right = 0;
    csPlane3& pl = planes[triidx[i]];
    for (j = 0 ; j < triidx.GetSize () ; j++)
      if (i != j)
      {
        csTriangle& trj = triangles[triidx[j]];
	int cla = ClassifyPlane (pl, vertices[trj.a]);
	int clb = ClassifyPlane (pl, vertices[trj.b]);
	int clc = ClassifyPlane (pl, vertices[trj.c]);
	if ((cla == -clb && cla != 0) ||
	    (cla == -clc && cla != 0) ||
	    (clb == -clc && clb != 0))
	{
	  // There is a split.
	  cnt_splits++;
	}
	else
	{
	  if (cla == -1 || clb == -1 || clc == -1)
	    cnt_left++;
	  else if (cla == 1 || clb == 1 || clc == 1)
	    cnt_right++;
	}
      }
    float split = float (cnt_splits) / float (triidx.GetSize ());
    float balance = float (ABS (cnt_left-cnt_right)) / float (triidx.GetSize ());
    float cost = 10.0 * split + balance;
    if (cost < mincost)
    {
      minidx = i;
      mincost = cost;
    }
  }
  return minidx;
}
コード例 #12
0
bool Tribe::LoadNPCMemoryBuffer(const char* name, csArray<NPC*> npcs)
{
    // Check just to be sure
    if(npcs.GetSize() == 0) return false;

    Memory* newLocation = FindMemory(csString(name));

    if(!newLocation)
    {
        return false;
    }

    for(size_t i=0; i<npcs.GetSize(); i++)
    {
        npcs[i]->SetBufferMemory(newLocation);
    }
    return true;
}
コード例 #13
0
void Tribe::LoadNPCMemoryBuffer(Tribe::Memory* memory, csArray<NPC*> npcs)
{
    if(!memory) return;

    // Just Assign
    for(size_t i=0; i<npcs.GetSize(); i++)
    {
        npcs[i]->SetBufferMemory(memory);
    }
}
コード例 #14
0
void Tribe::SendPerception(const char* pcpt, csArray<NPC*> npcs)
{
    Perception perception(pcpt);
    for(size_t i=0; i<npcs.GetSize(); i++)
    {
        NPC* npc = npcs[i];
        RDebug(this, 5, "--> Percept npc %s(%s): %s",npc->GetName(),ShowID(npc->GetEID()),perception.ToString(npc).GetDataSafe());

        npc->TriggerEvent(&perception);
    }
}
コード例 #15
0
ファイル: lootrandomizer.cpp プロジェクト: huigou/planeshift
bool LootRandomizer::GetModifiers(uint32_t itemID,
                                  csArray<psGMSpawnMods::ItemModifier>& mods)
{
    csHash<LootModifier*, uint32_t>::GlobalIterator it =
        LootModifiersById.GetIterator();
    while(it.HasNext())
    {
        LootModifier* lootModifier = it.Next();
        if(!lootModifier->IsAllowed(itemID))
        {
            continue;
        }

        psGMSpawnMods::ItemModifier mod;
        mod.name = lootModifier->name;
        mod.id = lootModifier->id;
        mod.type = lootModifier->mod_id;
        mods.Push(mod);
    }

    return mods.GetSize() != 0;
}
コード例 #16
0
ファイル: furdata.cpp プロジェクト: GameLemur/Crystal-Space
  void csFurStrand::Generate( size_t controlPointsCount,
    const csArray<csGuideFur> &guideFurs, 
    const csArray<csGuideFurLOD> &guideFursLOD )
  {
    // Allocate control points
    this -> controlPointsCount = controlPointsCount;

    controlPoints = new csVector3[ controlPointsCount ];

    for ( size_t i = 0 ; i < controlPointsCount ; i ++ )
    {
      controlPoints[i] = csVector3(0);

      for ( size_t j = 0 ; j < GUIDE_HAIRS_COUNT ; j ++ )
        if ( guideHairsRef[j].index < guideFurs.GetSize() )
          controlPoints[i] += guideHairsRef[j].distance *
            guideFurs.Get(guideHairsRef[j].index).controlPoints[i];
        else
          controlPoints[i] += guideHairsRef[j].distance *
            guideFursLOD.Get(guideHairsRef[j].index - 
            guideFurs.GetSize()).controlPoints[i];
    }
  }
コード例 #17
0
ファイル: creationmanager.cpp プロジェクト: huigou/planeshift
int CharCreationManager::CalculateCPLife(csArray<uint32_t> &events)
{
    int cpCost = 0;
    for(size_t li = 0; li < events.GetSize(); li++)
    {
        CharCreationManager::LifeEventChoiceServer* event;
        event = psserver->charCreationManager->FindLifeEvent(events[li]);

        if(event)
        {
            cpCost+=event->cpCost;
        }
    }

    return cpCost;
}
コード例 #18
0
ファイル: netmanager.cpp プロジェクト: garinh/planeshift
void NetManager::Multicast (MsgEntry* me, const csArray<PublishDestination>& multi, int except, float range)
{
    for (size_t i=0; i<multi.GetSize(); i++)
    {
        if (multi[i].client==except)  // skip the exception client to avoid circularity
            continue;

        Client *c = clients.Find(multi[i].client);
        if (c && c->IsReady() )
        {
            if (range == 0 || multi[i].dist < range)
            {
                me->clientnum = multi[i].client;
                SendMessage(me);      // This copies the mem block, so we can reuse.
            }
        }
    }
}
コード例 #19
0
ファイル: assetmanager.cpp プロジェクト: Dracophoenix1/ares
bool AssetManager::UpdateAssets (const csArray<BaseAsset>& update)
{
  // @@@ Removing assets is not yet supported. At least they will not get unloaded.
  // The assets table will be updated however. So a Save/Load will remove the asset.
  csRefArray<iAsset> newassets;

  // @@@ Remove the collection for removed assets!

  for (size_t i = 0 ; i < update.GetSize () ; i++)
  {
    const BaseAsset& a = update[i];
    iAsset* currentAsset = HasAsset (a);
    if (currentAsset)
    {
      newassets.Push (currentAsset);
    }
    else
    {
      csString normpath = a.GetNormalizedPath ();
      csString file = a.GetFile ();
      csString mount = a.GetMountPoint ();
      csString colName;
      colName.Format ("__col__%d__", colCounter++);
      iCollection* collection = engine->CreateCollection (colName);
      if (!LoadAsset (normpath, file, mount, collection))
	return false;

      RegisterModification ();

      csRef<IntAsset> asset;
      asset.AttachNew (new IntAsset (file, a.IsWritable ()));
      asset->SetMountPoint (mount);
      asset->SetNormalizedPath (normpath);
      asset->SetCollection (collection);
      newassets.Push (asset);
    }
  }
  assets = newassets;

  return true;
}
コード例 #20
0
ファイル: creationmanager.cpp プロジェクト: huigou/planeshift
int CharCreationManager::CalculateCPChoices(csArray<uint32_t> &choices, int fatherMod, int motherMod)
{
    int cpCost = 0;
    for(size_t ci = 0; ci < choices.GetSize(); ci++)
    {
        CharCreationManager::CreationChoice* choice = FindChoice(choices[ci]);
        if(choice)
        {
            if(choice->choiceArea == FATHER_JOB)
            {
                cpCost+= choice->cpCost*fatherMod;
            }
            else if(choice->choiceArea == MOTHER_JOB)
            {
                cpCost+= choice->cpCost*motherMod;
            }
            else
                cpCost+= choice->cpCost;
        }
    }

    return cpCost;
}
コード例 #21
0
      void CanvasCommonBase::csGLPixelFormatPicker::ReadPickerValue (
        const char* valuesStr, csArray<int>& values)
      {
        if ((valuesStr != 0) && (*valuesStr != 0))
        {
          CS_ALLOC_STACK_ARRAY(char, myValues, strlen (valuesStr) + 1);
          strcpy (myValues, valuesStr);

          char* currentVal = myValues;
          while ((currentVal != 0) && (*currentVal != 0))
          {
            char* comma = strchr (currentVal, ',');
            if (comma != 0) *comma = 0;

            char dummy;
            int val;
            if (sscanf (currentVal, "%d%c", &val, &dummy) == 1)
            {
                values.Push (val);
            }
            currentVal = comma ? comma + 1 : 0;
          }
        }
コード例 #22
0
psCharUploadMessage::psCharUploadMessage(bool verify,  const char* name, const char* lastname, int race, int gender,
        csArray<uint32_t> choices, int motherMod, int fatherMod, csArray<uint32_t> lifeEvents,
        int selectedFace, int selectedHairStyle, int selectedBeardStyle,
        int selectedHairColour, int selectedSkinColour, const char* bio, const char* path )
{
    msg.AttachNew(new MsgEntry( sizeof(bool) +
                                strlen(name) * sizeof(char) + 1 +
                                strlen(lastname) * sizeof(char) + 1 +
                                sizeof(int32_t) * 11 +
                                sizeof(int32_t) * choices.GetSize() +
                                sizeof(int32_t) * lifeEvents.GetSize() +
                                strlen(bio) * sizeof(char) + 1 +
                                strlen(path) * sizeof(char) + 1));


    msg->SetType(MSGTYPE_CHAR_CREATE_UPLOAD);
    msg->Add( verify );
    msg->Add( name );
    msg->Add( lastname );
    msg->Add( (int32_t)race );
    msg->Add( (int32_t)gender );

    msg->Add( (int32_t)selectedFace );
    msg->Add( (int32_t)selectedHairStyle );
    msg->Add( (int32_t)selectedBeardStyle );
    msg->Add( (int32_t)selectedHairColour );
    msg->Add( (int32_t)selectedSkinColour );

    msg->Add( (int32_t) choices.GetSize() );
    for ( size_t choiceIndex = 0; choiceIndex < choices.GetSize(); choiceIndex++ )
        msg->Add( (int32_t)choices[choiceIndex] );

    msg->Add( (int32_t) lifeEvents.GetSize() );
    for ( size_t lifeIndex = 0; lifeIndex < lifeEvents.GetSize(); lifeIndex++ )
        msg->Add( (int32_t)lifeEvents[lifeIndex] );

    msg->Add( (int32_t) motherMod );
    msg->Add( (int32_t) fatherMod );
    msg->Add( bio );
    msg->Add( path );

    valid = !(msg->overrun);
}
コード例 #23
0
void pawsPetitionGMWindow::AddPetitions(csArray<psPetitionInfo> &petitions)
{
    // figure out the selected petition


    if (petitionList->GetRowCount() <= 0)
        petitionList->Select(NULL);

    int selRow = petitionList->GetSelectedRowNum();
    if (selRow != -1)
    {
        csString escalation = petitionList->GetTextCellValue(selRow, PGMCOL_LVL);
        if (escalation.GetData() != NULL)
            selectedPet.escalation = atoi(escalation.GetData());
        else
            selectedPet.escalation = -1;
        selectedPet.assignedgm =      petitionList->GetTextCellValue(selRow, PGMCOL_GM);
        selectedPet.player =          petitionList->GetTextCellValue(selRow, PGMCOL_PLAYER);
        selectedPet.status =          petitionList->GetTextCellValue(selRow, PGMCOL_STATUS);
        selectedPet.created =         petitionList->GetTextCellValue(selRow, PGMCOL_CREATED);
        selectedPet.petition =        petitionList->GetTextCellValue(selRow, PGMCOL_PETITION);
        selectedPet.online =          petitionList->GetTextCellValue(selRow, PGMCOL_ONLINE) == "yes";
    }
    else
    {
        selectedPet.escalation = -1;
    }
    petitionList->Select(NULL);

    // Clear the list box and add the user's petitions
    petitionList->Clear();
    psPetitionInfo info;
    petCount = 0;
    for (size_t i = 0; i < petitions.GetSize(); i++)
    {
        info = petitions.Get(i);
        petCount++;

        // Set the data for this row:
        petitionList->NewRow(i);
        SetText(i, PGMCOL_LVL, "%d", info.escalation);
        SetText(i, PGMCOL_GM, "%s", info.assignedgm.GetDataSafe());
        SetText(i, PGMCOL_PLAYER, "%s", info.player.GetData());
        SetText(i, PGMCOL_ONLINE, "%s", (info.online ? "yes" : "no"));
        SetText(i, PGMCOL_STATUS, "%s", info.status.GetData());
        SetText(i, PGMCOL_CREATED, "%s", info.created.GetData());
        SetText(i, PGMCOL_PETITION, "%s", info.petition.GetData());

        // reselect the petition
        if (selectedPet.escalation != -1)
        {
            if (selectedPet.created == info.created
             && selectedPet.player == info.player)
            {
                petitionList->Select(petitionList->GetRow(i));
            }
        }
    }
    // make absolutely sure that there are petitions
    if (petCount <= 0)
    {
        petitionList->NewRow(0);
        SetText(0, 1, PawsManager::GetSingleton().Translate("No Petitions"));
    }
}
コード例 #24
0
ファイル: lootrandomizer.cpp プロジェクト: huigou/planeshift
bool LootRandomizer::SetAttribute(const csString &op, const csString &attrName, float modifier, RandomizedOverlay* overlay, psItemStats* baseItem, csArray<ValueModifier> &values)
{
    float* value[3] = { NULL, NULL, NULL };
    // Attribute Names:
    // item
    //        weight
    //        damage
    //            slash
    //            pierce
    //            blunt
    //            ...
    //        protection
    //            slash
    //            pierce
    //            blunt
    //            ...
    //        speed

    csString AttributeName(attrName);
    AttributeName.Downcase();
    if(AttributeName.StartsWith("var."))
    {
        //if var. was found we have a script variable
        //parse it and place it in the array which will be used later
        //to handle those variables.
        ValueModifier val;

        //start the name of the variable after var.
        val.name = attrName.Slice(4);
        val.value = modifier;
        val.op = op;

        //add the variable to the array
        values.Push(val);
        return true;
    }
    if(AttributeName.Compare("item.weight"))
    {
        // Initialize the value if needed
        if(CS::IsNaN(overlay->weight))
        {
            overlay->weight = baseItem->GetWeight();
        }

        value[0] = &overlay->weight;
    }
    else if(AttributeName.Compare("item.speed"))
    {
        // Initialize the value if needed
        if(CS::IsNaN(overlay->latency))
        {
            overlay->latency = baseItem->Weapon().Latency();
        }

        value[0] = &overlay->latency;
    }
    else if(AttributeName.Compare("item.damage"))
    {
        for(int i = 0; i < 3; i++)
        {
            // Initialize the value if needed
            if(CS::IsNaN(overlay->damageStats[i]))
            {
                overlay->damageStats[i] = baseItem->Weapon().Damage((PSITEMSTATS_DAMAGETYPE)i);
            }
        }

        value[0] = &overlay->damageStats[PSITEMSTATS_DAMAGETYPE_SLASH];
        value[1] = &overlay->damageStats[PSITEMSTATS_DAMAGETYPE_BLUNT];
        value[2] = &overlay->damageStats[PSITEMSTATS_DAMAGETYPE_PIERCE];
    }
    else if(AttributeName.Compare("item.damage.slash"))
    {
        // Initialize the value if needed
        if(CS::IsNaN(overlay->damageStats[PSITEMSTATS_DAMAGETYPE_SLASH]))
        {
            overlay->damageStats[PSITEMSTATS_DAMAGETYPE_SLASH] = baseItem->Weapon().Damage(PSITEMSTATS_DAMAGETYPE_SLASH);
        }

        value[0] = &overlay->damageStats[PSITEMSTATS_DAMAGETYPE_SLASH];
    }
    else if(AttributeName.Compare("item.damage.pierce"))
    {
        // Initialize the value if needed
        if(CS::IsNaN(overlay->damageStats[PSITEMSTATS_DAMAGETYPE_PIERCE]))
        {
            overlay->damageStats[PSITEMSTATS_DAMAGETYPE_PIERCE] = baseItem->Weapon().Damage(PSITEMSTATS_DAMAGETYPE_PIERCE);
        }

        value[0] = &overlay->damageStats[PSITEMSTATS_DAMAGETYPE_PIERCE];
    }
    else if(AttributeName.Compare("item.damage.blunt"))
    {
        // Initialize the value if needed
        if(CS::IsNaN(overlay->damageStats[PSITEMSTATS_DAMAGETYPE_BLUNT]))
        {
            overlay->damageStats[PSITEMSTATS_DAMAGETYPE_BLUNT] = baseItem->Weapon().Damage(PSITEMSTATS_DAMAGETYPE_BLUNT);
        }

        value[0] = &overlay->damageStats[PSITEMSTATS_DAMAGETYPE_BLUNT];
    }
    else if(AttributeName.Compare("item.protection"))
    {
        for(int i = 0; i < 3; i++)
        {
            // Initialize the value if needed
            if(CS::IsNaN(overlay->damageStats[i]))
            {
                overlay->damageStats[i] = baseItem->Armor().Protection((PSITEMSTATS_DAMAGETYPE)i);
            }
        }

        value[0] = &overlay->damageStats[PSITEMSTATS_DAMAGETYPE_SLASH];
        value[1] = &overlay->damageStats[PSITEMSTATS_DAMAGETYPE_BLUNT];
        value[2] = &overlay->damageStats[PSITEMSTATS_DAMAGETYPE_PIERCE];
    }
    else if(AttributeName.Compare("item.protection.slash"))
    {
        // Initialize the value if needed
        if(CS::IsNaN(overlay->damageStats[PSITEMSTATS_DAMAGETYPE_SLASH]))
        {
            overlay->damageStats[PSITEMSTATS_DAMAGETYPE_SLASH] = baseItem->Armor().Protection(PSITEMSTATS_DAMAGETYPE_SLASH);
        }

        value[0] = &overlay->damageStats[PSITEMSTATS_DAMAGETYPE_SLASH];
    }
    else if(AttributeName.Compare("item.protection.pierce"))
    {
        // Initialize the value if needed
        if(CS::IsNaN(overlay->damageStats[PSITEMSTATS_DAMAGETYPE_PIERCE]))
        {
            overlay->damageStats[PSITEMSTATS_DAMAGETYPE_PIERCE] = baseItem->Armor().Protection(PSITEMSTATS_DAMAGETYPE_PIERCE);
        }

        value[0] = &overlay->damageStats[PSITEMSTATS_DAMAGETYPE_PIERCE];
    }
    else if(AttributeName.Compare("item.protection.blunt"))
    {
        // Initialize the value if needed
        if(CS::IsNaN(overlay->damageStats[PSITEMSTATS_DAMAGETYPE_BLUNT]))
        {
            overlay->damageStats[PSITEMSTATS_DAMAGETYPE_BLUNT] = baseItem->Armor().Protection(PSITEMSTATS_DAMAGETYPE_BLUNT);
        }

        value[0] = &overlay->damageStats[PSITEMSTATS_DAMAGETYPE_BLUNT];
    }

    SetAttributeApplyOP(value, modifier, 3, op);

    return true;
}
コード例 #25
0
ファイル: maya_mdl.cpp プロジェクト: GameLemur/Crystal-Space
bool Maya4Model::WriteSPR(const char* spritename, csArray<Animation*>& anims) 
{
  FILE *f;
  Maya4Model spr;

  if (spritename == 0 || strlen(spritename) == 0)
  {
  csFPrintf(stderr, "Unable to save: 0 sprite name\n");
  return false;
  }

  csPrintf("Writing out SPR file: %s\n",spritename);

  f = CS::Platform::File::Open (spritename, "w");
  if (!f)
  {
    csFPrintf(stderr,"Unable to open file (%s) to write out CS sprite.\n",spritename);
  }

  csFPrintf(f,"<meshfact>\n");
  csFPrintf(f,"   <plugin>crystalspace.mesh.loader.factory.sprite.3d</plugin>\n");
  csFPrintf(f,"   <params>\n");
  
  if (filenode)
    filenode->Write(f);
  else
	csFPrintf(f,"    <material>no_maya_material</material>\n");

  for (int frame=0; frame<((animnode)?animnode->GetFrames():1); frame++)
  {
    csPrintf("Processing frame %d...\n",frame+1);

    if (frame>0)
      meshnode->ClearCS();

    // Move vertices for each frame
    meshnode->ApplyAnimDeltas(animnode,frame);

    // Fixups must be done on a frame by frame basis
    meshnode->FixupUniqueVertexMappings();

    csFPrintf(f,"    <frame name=\"f%d\">\n",frame+1);
    meshnode->WriteVertices(f);
    csFPrintf(f,"    </frame>\n");
  }

  // Now write out animation actions
  if (!anims.GetSize())
  {
    setError("At least one action animation is required.");  
    return false;
  }

  size_t i;
  for (i=0;i<anims.GetSize ();i++)
  {
    Animation* anim = anims[i];
    
    int stop,start = anim->startframe;
    csString name = anim->name;
	int frame_duration = anim->duration;
	Animation *curr_anim = anim;

    csPrintf("Writing out Animation %s\n",(const char *)name);

    if (i != anims.GetSize ()-1)
      stop = anim->startframe-1;
    else
      stop = (animnode)?animnode->GetFrames():start;
	
	if (stop>start)
	  frame_duration /= (stop-start);
	else
	  frame_duration = 1000;

	if (!frame_duration)
	  frame_duration = 67; // default is 15 fps.

	// now determine displacement to use
	DisplacementGroup disg;
	disg.startframe=0;
	disg.stopframe =0;
	disg.vertex=0;

	DisplacementGroup &dg = (curr_anim->displacements.GetSize ())? curr_anim->displacements[0] : disg;
	int displacementnum = 1;

    csFPrintf(f,"   <action name=\"%s\">\n",(const char *)name);

    for (int i=start; i<=stop; i++)
    {
	  if (i<dg.startframe || i>dg.stopframe)
	  {
        csFPrintf(f,"     <f name=\"f%d\" delay=\"%d\" />\n",i,frame_duration);
	  }
	  else
	  {
		int frame2 = (i+1>stop)?start:i+1;
		float displacement = meshnode->GetDisplacement(animnode, i-1,
		  frame2-1, dg.vertex);
		csFPrintf(f,"     <f name=\"f%d\" displacement=\"%f\" />\n",i,displacement);
		if (i==dg.stopframe) // get next displacement group
		{
		  dg = curr_anim->displacements[displacementnum++];
		}
	  }
    }

    csFPrintf(f,"   </action>\n");
  }

  csPrintf("Writing out Triangles.\n");

  // Now write out all triangles
  meshnode->WriteTriangles(f);
  
  // Now write out sockets
  for (i=0;i<sockets.GetSize ();i++)
  {
    Animation* socket = sockets[i];
    
    csString name = socket->name;
    int    tri  = socket->startframe; // really triangle #

    csPrintf("Writing out Socket %s Tri %d\n",(const char *)name,tri);

    csFPrintf(f,"   <socket name=\"%s\" tri=\"%d\" />\n",(const char *)name, tri);
  }

  // Wrap up the file
  csFPrintf(f,"  </params>\n</meshfact>\n");

  fclose(f);

  return true;
}
コード例 #26
0
ファイル: lootrandomizer.cpp プロジェクト: huigou/planeshift
void LootRandomizer::ApplyModifier(psItemStats* baseItem, RandomizedOverlay* overlay, csArray<uint32_t> &modifierIds)
{
    LootModifier mod;

    //set up default mod data
    mod.cost_modifier = 1;
    mod.name = baseItem->GetName();
    csArray<ValueModifier> variableValues;

    //creates the full lootmodifier from the ids being applied.
    //0 should be left empty in the database as it acts as NO HIT.
    for(size_t i = 0; i < modifierIds.GetSize(); i++)
    {
        uint32_t modID = modifierIds.Get(i);
        if(modID) //0 means nothing to do, no need to search for the void.
        {
            LootModifier* partialModifier = GetModifier(modID);
            if(partialModifier)
            {
                overlay->active = true;
                AddModifier(&mod, partialModifier);
            }
        }
    }
    //all is done no modifiers where found. so we just get out
    if(overlay->active == false)
        return;

    overlay->name = mod.name;
    overlay->price = psMoney(baseItem->GetPrice().GetTrias() * mod.cost_modifier);
    if(mod.mesh.Length() > 0)
        overlay->mesh = mod.mesh;
    if(mod.icon.Length() > 0)
        overlay->icon = mod.icon;

    // Apply effect
    csString xmlItemMod;

    xmlItemMod.Append("<ModiferEffects>");
    xmlItemMod.Append(mod.effect);
    xmlItemMod.Append("</ModiferEffects>");

    // Read the ModiferEffects XML into a doc*/
    csRef<iDocument> xmlDoc = ParseString(xmlItemMod);
    if(!xmlDoc)
    {
        Error1("Parse error in Loot Randomizer");
        return;
    }
    csRef<iDocumentNode> root    = xmlDoc->GetRoot();
    if(!root)
    {
        Error1("No XML root in Loot Randomizer");
        return;
    }
    csRef<iDocumentNode> topNode = root->GetNode("ModiferEffects");//Are we sure it is "Modifer"?
    if(!topNode)
    {
        Error1("No <ModiferEffects> in Loot Randomizer");
        return;
    }

    csRef<iDocumentNodeIterator> nodeList = topNode->GetNodes("ModiferEffect");

    // For Each ModiferEffect
    csRef<iDocumentNode> node;
    while(nodeList->HasNext())
    {
        node = nodeList->Next();
        //Determine the Effect
        csString EffectOp = node->GetAttribute("operation")->GetValue();
        csString EffectName = node->GetAttribute("name")->GetValue();
        float EffectValue = node->GetAttribute("value")->GetValueAsFloat();

        //Add to the Attributes
        if(!SetAttribute(EffectOp, EffectName, EffectValue, overlay, baseItem, variableValues))
        {
            // display error and continue
            Error2("Unable to set attribute %s on new loot item.",EffectName.GetData());
        }
    }

    // Apply stat_req_modifier
    csString xmlStatReq;

    xmlStatReq.Append("<StatReqs>");
    xmlStatReq.Append(mod.stat_req_modifier);
    xmlStatReq.Append("</StatReqs>");

    // Read the Stat_Req XML into a doc
    xmlDoc = ParseString(xmlStatReq);
    if(!xmlDoc)
    {
        Error1("Parse error in Loot Randomizer");
        return;
    }
    root    = xmlDoc->GetRoot();
    if(!root)
    {
        Error1("No XML root in Loot Randomizer");
        return;
    }
    topNode = root->GetNode("StatReqs");
    if(!topNode)
    {
        Error1("No <statreqs> in Loot Randomizer");
        return;
    }

    nodeList = topNode->GetNodes("StatReq");
    // For Each Stat_Req
    while(nodeList->HasNext())
    {
        node = nodeList->Next();
        //Determine the STAT
        ItemRequirement req;
        req.name = node->GetAttribute("name")->GetValue();
        req.min_value = node->GetAttribute("value")->GetValueAsFloat();
        //Add to the Requirements
        overlay->reqs.Push(req);
    }

    // Apply equip script
    if(!mod.equip_script.IsEmpty())
    {
        csString scriptXML = GenerateScriptXML(mod.name, mod.equip_script, variableValues);
        overlay->equip_script = ApplicativeScript::Create(psserver->entitymanager, psserver->GetCacheManager(), scriptXML);
    }

    //clamp speed at 1.5s to keep consistency with item_stats
    if(!CS::IsNaN(overlay->latency) && overlay->latency < 1.5F)
        overlay->latency = 1.5F;
}
コード例 #27
0
ファイル: lootrandomizer.cpp プロジェクト: huigou/planeshift
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;
}
コード例 #28
0
void OptimiseData::ParseMeshObj(csArray<csString>& libsNeeded, csArray<csString>& materialsNeeded,
                                csString& mapInPath, csRef<iDocumentNode> meshobj)
{
  csRef<iDocumentNodeIterator> meshobjs = meshobj->GetNodes("meshobj");
  while(meshobjs->HasNext())
  {
    ParseMeshObj(libsNeeded, materialsNeeded, mapInPath, meshobjs->Next());
  }

  if(meshobj->GetNode("params"))
  {
    meshobj = meshobj->GetNode("params");
    if(meshobj->GetNode("factory"))
    {
      bool found = false;
      for(size_t i=0; i<meshFactsOut.GetSize(); i++)
      {
        if(csString(meshFactsOut[i]->GetRoot()->GetNode("library")->GetNode("meshfact")->GetAttributeValue("name")).Compare(meshobj->GetNode("factory")->GetContentsValue()))
        {
          libsNeeded.PushSmart(meshobj->GetNode("factory")->GetContentsValue());
          found = true;
        }
      }

      if(!found)
      {
        // Print error and mark data as incorrect.
        csFPrintf(stderr, "ERROR: Mesh object %s uses mesh factory %s but there is no factory data!\n",
          meshobj->GetAttributeValue("name"), meshobj->GetNode("factory")->GetContentsValue());
      }
    }
    if(meshobj->GetNode("material"))
    {
      bool found = false;
      for(size_t i=0; i<materials.GetSize(); i++)
      {
        if(csString(materials[i]->GetAttributeValue("name")).Compare(meshobj->GetNode("material")->GetContentsValue()))
        {
          materialsNeeded.PushSmart(meshobj->GetNode("material")->GetContentsValue());
          found = true;
        }
      }

      if(!found)
      {
        // Print error and mark data as incorrect.
        csFPrintf(stderr, "ERROR: Mesh object %s uses material %s but there is no such material declaration!\n",
          meshobj->GetAttributeValue("name"), meshobj->GetNode("material")->GetContentsValue());
      }
    }
  }
  else if(meshobj->GetNode("paramsfile"))
  {
    csString paramsPath = mapInPath + "/" + meshobj->GetNode("paramsfile")->GetContentsValue();
    csRef<iFile> file = vfs->Open(paramsPath, VFS_FILE_READ);
    csRef<iDocument> paramsDoc = docSys->CreateDocument();
    paramsDoc->Parse(file);
    meshobj = paramsDoc->GetRoot()->GetNode("params");
    if(meshobj->GetNode("factory"))
    {
      bool found = false;
      for(size_t i=0; i<meshFactsOut.GetSize(); i++)
      {
        if(csString(meshFactsOut[i]->GetRoot()->GetNode("library")->GetNode("meshfact")->GetAttributeValue("name")).Compare(meshobj->GetNode("factory")->GetContentsValue()))
        {
          libsNeeded.PushSmart(meshobj->GetNode("factory")->GetContentsValue());
          found = true;
        }
      }

      if(!found)
      {
        // Print error and mark data as incorrect.
        csFPrintf(stderr, "ERROR: Mesh object %s uses mesh factory %s but there is no factory data!\n",
          meshobj->GetParent()->GetAttributeValue("name"), meshobj->GetNode("factory")->GetContentsValue());
      }
    }
    if(meshobj->GetNode("material"))
    {
      bool found = false;
      for(size_t i=0; i<materials.GetSize(); i++)
      {
        if(csString(materials[i]->GetAttributeValue("name")).Compare(meshobj->GetNode("material")->GetContentsValue()))
        {
          materialsNeeded.PushSmart(meshobj->GetNode("material")->GetContentsValue());
          found = true;
        }
      }

      if(!found)
      {
        // Print error and mark data as incorrect.
        csFPrintf(stderr, "ERROR: Mesh object %s uses material %s but there is no such material declaration!\n",
          meshobj->GetParent()->GetAttributeValue("name"), meshobj->GetNode("material")->GetContentsValue());
      }
    }
  }
}
コード例 #29
0
ファイル: plugmgr.cpp プロジェクト: GameLemur/Crystal-Space
 virtual bool HasNext ()
 {
   return idx < pointers.GetSize ();
 }
コード例 #30
0
bool psEffectObjLabel::SetText(int rows, ...)
{
    size_t lettercount = 0;

    static csArray<psEffectTextElement> elemBuffer;
    psEffectTextElement newElem;
    psEffectTextRow * row = 0;
    int y = 0;

    // calculate dimensions of text area
    int maxWidth = 0;
    int maxHeight = 0;

    elemBuffer.Empty();

    va_list arg;
    va_start(arg, rows);

    // Loop through all rows
    for (int a=0; a<rows; a++)
    {
        row = va_arg(arg, psEffectTextRow *);

        // Text and Formatting
        newElem.colour = row->colour;
        newElem.hasOutline = row->hasOutline;
        newElem.hasShadow = row->hasShadow;
        newElem.shadowColour = row->shadowColour;
        newElem.outlineColour = row->outlineColour;
        newElem.text = row->text;
        newElem.align = row->align;
        newElem.width = 0;
        newElem.height = 0;
        for(uint b=0; b<newElem.text.Length(); b++)
        {
            newElem.width += width[newElem.text[b]];
            if( newElem.height < height[newElem.text[b]] )
            {
                newElem.height = height[newElem.text[b]];
            }
        }
        newElem.x = 0;
        newElem.y = y;
        elemBuffer.Push(newElem);
        y += newElem.height;
        lettercount += newElem.text.Length();

        int right = newElem.x + newElem.width;
        int bottom = newElem.y + newElem.height;

        if (right > maxWidth)
            maxWidth = right;
        if (bottom > maxHeight)
            maxHeight = bottom;
    }
    va_end(arg);

    CS_ASSERT(facState!=0);
    iMeshObjectFactory * fact = meshFact->GetMeshObjectFactory();
    int mw,mh;
    fact->GetMaterialWrapper()->GetMaterial()->GetTexture()->GetOriginalDimensions(mw, mh);

    facState->SetVertexCount( (int)lettercount * 4 );
    facState->SetTriangleCount( (int)lettercount * 2 );

    size_t elementCount = elemBuffer.GetSize();
    int cp = 0;

    for(size_t i=0; i<elementCount; i++)
    {
        int x = elemBuffer[i].width;
        
        switch (elemBuffer[i].align)
        {
            case ETA_LEFT:
                x = maxWidth;
                break;
            case ETA_CENTER:
                x = (maxWidth-x)/2;
                break;
            case ETA_RIGHT:
                x = maxWidth-x;
                break;
        }
        int y = elemBuffer[i].y;
        csString text = elemBuffer[i].text;
        float scalefactor = labelwidth / (float)maxWidth;
        for(size_t j=0; j<text.Length(); j++)
        {
            uint c = text.GetAt(j);
            float fx1, fy1, fx2, fy2;

            fx1 = (float)x * scalefactor - labelwidth/2.0;
            fy1 = (float)(maxHeight/2 - y) * scalefactor;
            fx2 = (float)(x+width[c]) * scalefactor - labelwidth/2.0;
            fy2 = (float)(maxHeight/2 - y + height[c]) * scalefactor;
            //printf("rendering char %d pos %d,%d w/h %d,%d xp/yp %d,%d - %f %f %f %f\n", cp/4, x, y, width[c], height[c], xpos[c], ypos[c], fx1, fy1, fx2, fy2);
            facState->GetVertices()[cp  ].Set(fx2,0,fy1); 
            facState->GetVertices()[cp+1].Set(fx1,0,fy1); 
            facState->GetVertices()[cp+2].Set(fx1,0,fy2); 
            facState->GetVertices()[cp+3].Set(fx2,0,fy2);
            //printf("character %c: x %d y %d w %d\n", c, xpos[c], ypos[c], width[c]);
            float fracx1 = (float)xpos[c] / mw;
            float fracy1 = (float)ypos[c] / mh;
            float fracx2 = (float)(xpos[c]+width[c]) / mw;
            float fracy2 = (float)(ypos[c]+height[c]) / mh;
            //printf("texels %c %d,%d - %f %f %f %f\n", text[j], xpos[c], ypos[c], fracx1, fracy1, fracx2, fracy2);
            facState->GetTexels()[cp  ].Set( fracx2, fracy2 );
            facState->GetTexels()[cp+1].Set( fracx1, fracy2 );
            facState->GetTexels()[cp+2].Set( fracx1, fracy1 );
            facState->GetTexels()[cp+3].Set( fracx2, fracy1 );
            facState->GetNormals()[0].Set(0,1,0);
            facState->GetNormals()[1].Set(0,1,0);
            facState->GetNormals()[2].Set(0,1,0);
            facState->GetNormals()[3].Set(0,1,0);
            facState->GetTriangles()[(cp/2)  ].Set( cp  , cp+2, cp+3);
            facState->GetTriangles()[(cp/2)+1].Set( cp+2, cp  , cp+1);
            cp += 4;
            x += width[c];
        }
        csVector3 color((float)((newElem.colour>>16) & 255)/255.0F,
                      (float)((newElem.colour>> 8) & 255)/255.0F,
                      (float)((newElem.colour    ) & 255)/255.0F);
        CS::ShaderVarStringID varName = stringSet->Request("color modulation");
        csShaderVariable* var = mesh->GetSVContext()->GetVariableAdd(varName);
        if(var)
        {
            var->SetValue(color);
        }
    }
    facState->CalculateNormals();
//    facState->SetLighting(false);
//    fact->SetMixMode(CS_FX_ADD);
    return true;
}