Пример #1
0
void TreeNode::xPathQuery(const String& xPath, const Enumerator<TreeNode*>& enumerator, bool includeHiddenChildren, const NumberFormat* numberFormat)
{
	// Get tokens of xPath:
	Array<String> tokens;
	StringTokenizer(xPath, "/").tokenizeTo(tokens);

	int tokenIndex = 0;

	// If we have tokens:
	if (tokens.isEmpty() == false)
	{
		TreeNode* currentNode;
		if (xPath.beginsWith('/') == true)
		{
			currentNode = &getRootNode();
			if (currentNode->getName() == tokens[0])
			{
				++tokenIndex;
			}
			else
			{
				return;
			}
		}
		else
		{
			currentNode = this;
		}
		currentNode->xPathTestNode(tokens, tokenIndex, enumerator, includeHiddenChildren, numberFormat);
	}
}
Пример #2
0
String NativePath::pretty() const
{
    if (isEmpty()) return *this;

    String result = *this;

    // Replace relative directives like '}' (used in FS1 only) with a full symbol.
    if (result.length() > 1 && (result.first() == '}' || result.first() == '>'))
    {
        return String(NATIVE_BASE_SYMBOLIC) + DIR_SEPARATOR + result.mid(1);
    }

    // If within one of the known native directories, cut out the known path,
    // replacing it with a symbolic. This retains the absolute nature of the path
    // while omitting potentially redundant/verbose information.
    if (QDir::isAbsolutePath(result))
    {
        NativePath basePath = App::app().nativeBasePath();
        if (result.beginsWith(basePath))
        {
            result = NATIVE_BASE_SYMBOLIC + result.mid(basePath.length());
        }
        else
        {
#ifdef MACOSX
            NativePath contentsPath = App::app().nativeAppContentsPath();
            if (result.beginsWith(contentsPath))
            {
                return "(app)" + result.mid(contentsPath.length());
            }
#endif
            NativePath homePath = QDir::homePath(); // actual native home dir, not FS2 "/home"
            if (result.beginsWith(homePath))
            {
                result = NATIVE_HOME_SYMBOLIC + result.mid(homePath.length());
            }
        }
    }

    return result;
}
void StructurePermissionList::migrateLists(ZoneServer* zoneServer, uint64 ownerObjectID) {
	Locker locker(&lock);

	ManagedReference<GuildManager*> guildManager = zoneServer->getGuildManager();
	ManagedReference<PlayerManager*> playerManager = zoneServer->getPlayerManager();

	for (int i = 0; i < permissionLists.size(); i++) {
		String listName = permissionLists.elementAt(i).getKey();
		addList(listName);

		SortedVector<String>* list = &permissionLists.get(i);

		for (int j = 0; j < list->size(); j++) {
			String name = list->get(j);

			if (name.beginsWith("guild:")) {
				String abbrev = name.replaceAll("guild:","");

				if (abbrev == "" || !guildManager->guildAbbrevExists(abbrev)) {
					continue;
				}

				ManagedReference<GuildObject*> guild = guildManager->getGuildFromAbbrev(abbrev);

				if (guild == NULL) {
					continue;
				}

				grantPermission(listName, guild->getObjectID());

			} else {
				if (!playerManager->existsName(name)) {
					continue;
				}

				ManagedReference<CreatureObject*> player = playerManager->getPlayer(name);

				if (player == NULL || !player->isPlayerCreature()) {
					continue;
				}

				grantPermission(listName, player->getObjectID());
			}
		}
	}

	ownerID = ownerObjectID;

	permissionLists.removeAll();
}
Пример #4
0
void VendorDataComponent::performVendorBark(SceneObject* target) {
	if (isOnStrike()) {
		return;
	}

	ManagedReference<CreatureObject*> vendor = cast<CreatureObject*>(parent.get().get());
	if (vendor == NULL)
		return;

	ManagedReference<CreatureObject*> player = cast<CreatureObject*>(target);
	if (player == NULL || !player->isPlayerCreature())
		return;

	resetLastBark();
	addBarkTarget(target);

	EXECUTE_TASK_2(vendor, player, {
			Locker locker(vendor_p);

			VendorDataComponent* data = cast<VendorDataComponent*>(vendor_p->getDataObjectComponent()->get());

			if (data == NULL)
				return;

			vendor_p->faceObject(player_p);
			vendor_p->updateDirection(Math::deg2rad(vendor_p->getDirectionAngle()));

			SpatialChat* chatMessage = NULL;
			String barkMessage = data->getAdPhrase();

			if (barkMessage.beginsWith("@")) {
				StringIdChatParameter message;
				message.setStringId(barkMessage);
				message.setTT(player_p->getObjectID());
				chatMessage = new SpatialChat(vendor_p->getObjectID(), player_p->getObjectID(), message, player_p->getObjectID(), Races::getMoodID(data->getAdMood()), 0);

			} else {
				UnicodeString uniMessage(barkMessage);
				chatMessage = new SpatialChat(vendor_p->getObjectID(), player_p->getObjectID(), uniMessage, player_p->getObjectID(), Races::getMoodID(data->getAdMood()), 0, 0);
			}

			vendor_p->broadcastMessage(chatMessage, true);
			vendor_p->doAnimation(data->getAdAnimation());

			Reference<VendorReturnToPositionTask*> returnTask = new VendorReturnToPositionTask(vendor_p, data->getOriginalDirection());
			vendor_p->addPendingTask("vendorreturn", returnTask, 3000);
		});
int VehicleObjectImplementation::notifyObjectDestructionObservers(TangibleObject* attacker, int condition) {
	unlock();

	ManagedReference<CreatureObject* > linkedCreature = this->linkedCreature.get();

	if (linkedCreature != NULL) {
		linkedCreature->sendSystemMessage("@pet/pet_menu:veh_disabled");

		ManagedReference<VehicleObject*> vehicle = _this.getReferenceUnsafeStaticCast();
		String vehicleName = vehicle->getDisplayedName();
		if (!vehicleName.beginsWith("(disabled)"))
		{
			UnicodeString disabledName = "(disabled) " + vehicleName;
			vehicle->setCustomObjectName(disabledName, true);
		}

		try {
			if (attacker != _this.getReferenceUnsafeStaticCast()) {
				Locker clocker(linkedCreature, attacker);

				linkedCreature->updateCooldownTimer("mount_dismount", 0);
				linkedCreature->executeObjectControllerAction(STRING_HASHCODE("dismount"));

			} else {
				Locker locker(linkedCreature);

				linkedCreature->updateCooldownTimer("mount_dismount", 0);
				linkedCreature->executeObjectControllerAction(STRING_HASHCODE("dismount"));
			}


		} catch (Exception& e) {
		}
	}

	if (attacker != _this.getReferenceUnsafeStaticCast())
		wlock(attacker);
	else
		wlock();

	return CreatureObjectImplementation::notifyObjectDestructionObservers(attacker, condition);
}
bool PlanetManagerImplementation::validateRegionName(const String& name) {
	String lowerCase = name.toLowerCase();
	Locker locker(_this.getReferenceUnsafeStaticCast());

	if (hasRegion(name) || hasRegion(lowerCase))
		return false;

	for (int i = 0; i < regionMap.getTotalRegions(); ++i) {
		String regionName = regionMap.getRegion(i)->getRegionName();

		if (regionName.beginsWith("@")) {
			String fullName = StringIdManager::instance()->getStringId(regionName.hashCode()).toString().toLowerCase();

			if ((!fullName.isEmpty()) && (lowerCase == fullName || fullName.contains(lowerCase) || lowerCase.contains(fullName)))
				return false;
		}
	}

	return true;
}
Пример #7
0
    void findPartialPath(String const &path, FoundFiles &found) const
    {
        String baseName = path.fileName().lower();
        String dir      = path.fileNamePath().lower();

        if(!dir.empty() && !dir.beginsWith("/"))
        {
            // Always begin with a slash. We don't want to match partial folder names.
            dir = "/" + dir;
        }

        DENG2_GUARD_READ(this);

        ConstIndexRange range = index.equal_range(baseName);
        for(Index::const_iterator i = range.first; i != range.second; ++i)
        {
            File *file = i->second;
            if(file->path().fileNamePath().endsWith(dir, Qt::CaseInsensitive))
            {
                found.push_back(file);
            }
        }
    }
Пример #8
0
bool SkillManager::fullfillsSkillPrerequisites(const String& skillName, CreatureObject* creature) {
	Skill* skill = skillMap.get(skillName.hashCode());

	if (skill == NULL) {
		return false;
	}

	Vector<String>* requiredSpecies = skill->getSpeciesRequired();
	if (requiredSpecies->size() > 0) {
		bool foundSpecies = false;
		for (int i = 0; i < requiredSpecies->size(); i++) {
			if (creature->getSpeciesName() == requiredSpecies->get(i)) {
				foundSpecies = true;
				break;
			}
		}
		if (!foundSpecies) {
			return false;
		}
	}

	//Check for required skills.
	Vector<String>* requiredSkills = skill->getSkillsRequired();
	for (int i = 0; i < requiredSkills->size(); ++i) {
		String requiredSkillName = requiredSkills->get(i);
		Skill* requiredSkill = skillMap.get(requiredSkillName.hashCode());

		if (requiredSkill == NULL) {
			continue;
		}

		if (!creature->hasSkill(requiredSkillName)) {
			return false;
		}
	}

	PlayerObject* ghost = creature->getPlayerObject();
	if(ghost == NULL || ghost->getJediState() < skill->getJediStateRequired()) {
		return false;
	}

	if (ghost->isPrivileged())
		return true;

	if (skillName.beginsWith("force_sensitive")) { // Check for Force Sensitive boxes.
		int index = skillName.indexOf("0");
		if (index != -1) {
			String skillNameFinal = skillName.subString(0, skillName.length() - 3);
			if (creature->getScreenPlayState("VillageUnlockScreenPlay:" + skillNameFinal) < 2) {
				return false;
			}
		}
	}

	if(skillName == "force_title_jedi_rank_01" && getForceSensitiveSkillCount(creature, false) < 24) {
		return false;
	}

	if(skillName == "force_title_jedi_rank_03" && !knightPrereqsMet(creature, "")) {
		return false;
	}

	return true;
}
Пример #9
0
bool SkillManager::surrenderSkill(const String& skillName, CreatureObject* creature, bool notifyClient) {
	Skill* skill = skillMap.get(skillName.hashCode());

	if (skill == NULL)
		return false;

	Locker locker(creature);

	SkillList* skillList = creature->getSkillList();

	if(skillName == "force_title_jedi_novice" && getForceSensitiveSkillCount(creature, true) > 0) {
		return false;
	}

	if(skillName.beginsWith("force_sensitive_") &&
		getForceSensitiveSkillCount(creature, false) <= 24 &&
		creature->hasSkill("force_title_jedi_rank_01"))
		return false;

	for (int i = 0; i < skillList->size(); ++i) {
		Skill* checkSkill = skillList->get(i);

		if (checkSkill->isRequiredSkillOf(skill))
			return false;
	}

	if(creature->hasSkill("force_title_jedi_rank_03") && skillName.contains("force_discipline_") && !knightPrereqsMet(creature, skillName)) {
		return false;
	}

	//If they have already surrendered the skill, then return true.
	if (!creature->hasSkill(skill->getSkillName()))
		return true;

	creature->removeSkill(skill, notifyClient);

	//Remove skill modifiers
	VectorMap<String, int>* skillModifiers = skill->getSkillModifiers();

	ManagedReference<PlayerObject*> ghost = creature->getPlayerObject();

	for (int i = 0; i < skillModifiers->size(); ++i) {
		VectorMapEntry<String, int>* entry = &skillModifiers->elementAt(i);
		creature->removeSkillMod(SkillModManager::SKILLBOX, entry->getKey(), entry->getValue(), notifyClient);

	}

	if (ghost != NULL) {
		//Give the player the used skill points back.
		ghost->addSkillPoints(skill->getSkillPointsRequired());

		//Remove abilities but only if the creature doesn't still have a skill that grants the
		//ability.  Some abilities are granted by multiple skills. For example Dazzle for dancers
		//and musicians.
		Vector<String>* skillAbilities = skill->getAbilities();
		if (skillAbilities->size() > 0) {
			SortedVector<String> abilitiesLost;
			for (int i = 0; i < skillAbilities->size(); i++) {
				abilitiesLost.put(skillAbilities->get(i));
			}
			for (int i = 0; i < skillList->size(); i++) {
				Skill* remainingSkill = skillList->get(i);
				Vector<String>* remainingAbilities = remainingSkill->getAbilities();
				for(int j = 0; j < remainingAbilities->size(); j++) {
					if (abilitiesLost.contains(remainingAbilities->get(j))) {
						abilitiesLost.drop(remainingAbilities->get(j));
						if (abilitiesLost.size() == 0) {
							break;
						}
					}
				}
			}
			if (abilitiesLost.size() > 0) {
				removeAbilities(ghost, abilitiesLost, notifyClient);
			}
		}

		//Remove draft schematic groups
		Vector<String>* schematicsGranted = skill->getSchematicsGranted();
		SchematicMap::instance()->removeSchematics(ghost, *schematicsGranted, notifyClient);

		//Update maximum experience.
		updateXpLimits(ghost);

		/// Update Force Power Max
		ghost->setForcePowerMax(creature->getSkillMod("jedi_force_power_max"), true);

		SkillList* list = creature->getSkillList();

		int totalSkillPointsWasted = 250;

		for (int i = 0; i < list->size(); ++i) {
			Skill* skill = list->get(i);

			totalSkillPointsWasted -= skill->getSkillPointsRequired();
		}

		if (ghost->getSkillPoints() != totalSkillPointsWasted) {
			creature->error("skill points mismatch calculated: " + String::valueOf(totalSkillPointsWasted) + " found: " + String::valueOf(ghost->getSkillPoints()));
			ghost->setSkillPoints(totalSkillPointsWasted);
		}

		ManagedReference<PlayerManager*> playerManager = creature->getZoneServer()->getPlayerManager();
		if (playerManager != NULL) {
			creature->setLevel(playerManager->calculatePlayerLevel(creature));
		}
	}

	/// Update client with new values for things like Terrain Negotiation
	CreatureObjectDeltaMessage4* msg4 = new CreatureObjectDeltaMessage4(creature);
	msg4->updateAccelerationMultiplierBase();
	msg4->updateAccelerationMultiplierMod();
	msg4->updateSpeedMultiplierBase();
	msg4->updateSpeedMultiplierMod();
	msg4->updateRunSpeed();
	msg4->updateTerrainNegotiation();
	msg4->close();
	creature->sendMessage(msg4);

	SkillModManager::instance()->verifySkillBoxSkillMods(creature);

	return true;
}
Пример #10
0
/**
 * The path inside the zip might be mapped to another virtual location.
 *
 * @return  @c true= iff @a path was mapped to another location.
 *
 * @todo This is clearly implemented in the wrong place. Path mapping
 *       should be done at a higher level.
 */
static bool applyGamePathMappings(String &path)
{
    // Manually mapped to Defs?
    if (path.beginsWith('@'))
    {
        path.remove(0, 1);
        if (path.at(0) == '/') path.remove(0, 1);

        path = String("$(App.DefsPath)/$(GamePlugin.Name)/auto") / path;
        return true;
    }

    // Manually mapped to Data?
    if (path.beginsWith('#'))
    {
        path.remove(0, 1);
        if (path.at(0) == '/') path.remove(0, 1);

        // Is there a prefix to be omitted in the name?
        if (int slash = path.lastIndexOf('/'))
        {
            // The slash must not be too early in the string.
            if (slash >= 2)
            {
                // Good old negative indices.
                if (path.at(slash - 2) == '.' && path.at(slash - 1) >= '1' && path.at(slash - 1) <= '9')
                    path.remove(slash - 2, 2);
            }
        }

        path = String("$(App.DataPath)/$(GamePlugin.Name)/auto") / path;
        return true;
    }

    // Implicitly mapped to another location?
    if (!path.contains('/'))
    {
        // No directory separators; i.e., a root file.
        FileType const &ftype = DD_GuessFileTypeFromFileName(path.fileName());

        switch (ftype.defaultClass())
        {
        case RC_PACKAGE:
            // Mapped to the Data directory.
            path = String("$(App.DataPath)/$(GamePlugin.Name)/auto") / path;
            return true;

        case RC_DEFINITION:
            // Mapped to the Defs directory?
            path = String("$(App.DefsPath)/$(GamePlugin.Name)/auto") / path;
            return true;

        default:
            return false;
        }
    }

    // Key-named directories in the root might be mapped to another location.
    FS1::Schemes const &schemes = App_FileSystem().allSchemes();
    DENG2_FOR_EACH_CONST(FS1::Schemes, i, schemes)
    {
        if ((*i)->mapPath(path))
        {
            return true;
        }
    }
    return false;
}
Пример #11
0
void SuiManager::handleCharacterBuilderSelectItem(CreatureObject* player, SuiBox* suiBox, uint32 cancel, Vector<UnicodeString>* args) {
	ZoneServer* zserv = player->getZoneServer();

	if (args->size() < 1)
		return;

	bool otherPressed = false;
	int index = 0;

	if(args->size() > 1) {
		otherPressed = Bool::valueOf(args->get(0).toString());
		index = Integer::valueOf(args->get(1).toString());
	} else {
		index = Integer::valueOf(args->get(0).toString());
	}

	if (!suiBox->isCharacterBuilderBox())
		return;

	ManagedReference<SuiCharacterBuilderBox*> cbSui = cast<SuiCharacterBuilderBox*>( suiBox);

	CharacterBuilderMenuNode* currentNode = cbSui->getCurrentNode();

	PlayerObject* ghost = player->getPlayerObject();

	//If cancel was pressed then we kill the box/menu.
	if (cancel != 0)
		return;

	//Back was pressed. Send the node above it.
	if (otherPressed) {
		CharacterBuilderMenuNode* parentNode = currentNode->getParentNode();

		if(parentNode == NULL)
			return;

		cbSui->setCurrentNode(parentNode);

		ghost->addSuiBox(cbSui);
		player->sendMessage(cbSui->generateMessage());
		return;
	}

	CharacterBuilderMenuNode* node = currentNode->getChildNodeAt(index);

	//Node doesn't exist or the index was out of bounds. Should probably resend the menu here.
	if (node == NULL) {
		ghost->addSuiBox(cbSui);
		player->sendMessage(cbSui->generateMessage());
		return;
	}

	if (node->hasChildNodes()) {
		//If it has child nodes, display them.
		cbSui->setCurrentNode(node);
		ghost->addSuiBox(cbSui);
		player->sendMessage(cbSui->generateMessage());
	} else {

		String templatePath = node->getTemplatePath();

		if (templatePath.indexOf(".iff") < 0) { // Non-item selections

			if (templatePath == "unlearn_all_skills") {

				SkillManager::instance()->surrenderAllSkills(player);
				player->sendSystemMessage("All skills unlearned.");

			} else if (templatePath == "cleanse_character") {

				if (!player->isInCombat()) {
					player->sendSystemMessage("You have been cleansed from the signs of previous battles.");

					for (int i = 0; i < 9; ++i) {
						player->setWounds(i, 0);
					}

					player->setShockWounds(0);
				} else {
					player->sendSystemMessage("Not within combat.");
				}

			} else if (templatePath == "reset_buffs") {

				if (!player->isInCombat()) {
					player->sendSystemMessage("Your buffs have been reset.");

					player->clearBuffs(true);

					ghost->setFoodFilling(0);
					ghost->setDrinkFilling(0);
				} else {
					player->sendSystemMessage("Not within combat.");
				}

			} else if (templatePath.beginsWith("crafting_apron_")) {

				//"object/tangible/wearables/apron/apron_chef_s01.iff"
				//"object/tangible/wearables/ithorian/apron_chef_jacket_s01_ith.iff"

				uint32 itemCrc = ( player->getSpecies() != CreatureObject::ITHORIAN ) ? 0x5DDC4E5D : 0x6C191FBB;

				ManagedReference<WearableObject*> apron = zserv->createObject(itemCrc, 2).castTo<WearableObject*>();

				if (apron == NULL) {
					player->sendSystemMessage("There was an error creating the requested item. Please contact customer support with this issue.");
					ghost->addSuiBox(cbSui);
					player->sendMessage(cbSui->generateMessage());

					error("could not create frog crafting apron");
					return;
				}

				apron->createChildObjects();

				if (apron->isWearableObject()) {
					uint32 bitmask = apron->getOptionsBitmask() | OptionBitmask::YELLOW;
					apron->setOptionsBitmask(bitmask, false);

					UnicodeString modName = "(General)";
					apron->addSkillMod(SkillModManager::WEARABLE, "general_assembly", 25);
					apron->addSkillMod(SkillModManager::WEARABLE, "general_experimentation", 25);

					if(templatePath == "crafting_apron_armorsmith") {
						modName = "(Armorsmith)";
						apron->addSkillMod(SkillModManager::WEARABLE, "armor_assembly", 25);
						apron->addSkillMod(SkillModManager::WEARABLE, "armor_experimentation", 25);
						apron->addSkillMod(SkillModManager::WEARABLE, "armor_repair", 25);
					} else if(templatePath == "crafting_apron_weaponsmith") {
						modName = "(Weaponsmith)";
						apron->addSkillMod(SkillModManager::WEARABLE, "weapon_assembly", 25);
						apron->addSkillMod(SkillModManager::WEARABLE, "weapon_experimentation", 25);
						apron->addSkillMod(SkillModManager::WEARABLE, "weapon_repair", 25);
						apron->addSkillMod(SkillModManager::WEARABLE, "grenade_assembly", 25);
						apron->addSkillMod(SkillModManager::WEARABLE, "grenade_experimentation", 25);
					} else if(templatePath == "crafting_apron_tailor") {
						modName = "(Tailor)";
						apron->addSkillMod(SkillModManager::WEARABLE, "clothing_assembly", 25);
						apron->addSkillMod(SkillModManager::WEARABLE, "clothing_experimentation", 25);
						apron->addSkillMod(SkillModManager::WEARABLE, "clothing_repair", 25);
					} else if(templatePath == "crafting_apron_chef") {
						modName = "(Chef)";
						apron->addSkillMod(SkillModManager::WEARABLE, "food_assembly", 25);
						apron->addSkillMod(SkillModManager::WEARABLE, "food_experimentation", 25);
					} else if(templatePath == "crafting_apron_architect") {
						modName = "(Architect)";
						apron->addSkillMod(SkillModManager::WEARABLE, "structure_assembly", 25);
						apron->addSkillMod(SkillModManager::WEARABLE, "structure_experimentation", 25);
						apron->addSkillMod(SkillModManager::WEARABLE, "structure_complexity", 25);
					} else if(templatePath == "crafting_apron_droid_engineer") {
						modName = "(Droid Engineer)";
						apron->addSkillMod(SkillModManager::WEARABLE, "droid_assembly", 25);
						apron->addSkillMod(SkillModManager::WEARABLE, "droid_experimentation", 25);
						apron->addSkillMod(SkillModManager::WEARABLE, "droid_complexity", 25);
					} else if(templatePath == "crafting_apron_doctor") {
						modName = "(Doctor)";
						apron->addSkillMod(SkillModManager::WEARABLE, "medicine_assembly", 25);
						apron->addSkillMod(SkillModManager::WEARABLE, "medicine_experimentation", 25);
					} else if(templatePath == "crafting_apron_combat_medic") {
						modName = "(Combat Medic)";
						apron->addSkillMod(SkillModManager::WEARABLE, "combat_medicine_assembly", 25);
						apron->addSkillMod(SkillModManager::WEARABLE, "combat_medicine_experimentation", 25);
					}

					UnicodeString apronName = "Crafting Apron " + modName;
					apron->setCustomObjectName(apronName, false);
				}

				ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory");
				apron->sendTo(player, true);
				inventory->transferObject(apron, -1, true);

				StringIdChatParameter stringId;
				stringId.setStringId("@faction_perk:bonus_base_name"); //You received a: %TO.
				stringId.setTO(apron);
				player->sendSystemMessage(stringId);

			} else if (templatePath == "enhance_character") {

				ManagedReference<SceneObject*> scob = cbSui->getUsingObject();
				if (scob != NULL) {

					if (scob->getGameObjectType() == SceneObjectType::CHARACTERBUILDERTERMINAL) {
						CharacterBuilderTerminal* bluefrog = cast<CharacterBuilderTerminal*>( scob.get());
						bluefrog->enhanceCharacter(player);
					}
				}

			} else if (templatePath == "credits") {

				player->addCashCredits(50000, true);
				player->sendSystemMessage("You have received 50.000 Credits");

			} else if (templatePath == "faction_rebel") {

				ghost->increaseFactionStanding("rebel", 100000);

			} else if (templatePath == "faction_imperial") {

				ghost->increaseFactionStanding("imperial", 100000);

			} else if (templatePath == "language") {

				ManagedReference<SceneObject*> scob = cbSui->getUsingObject();
				if (scob != NULL) {

					if (scob->getGameObjectType() == SceneObjectType::CHARACTERBUILDERTERMINAL) {
						CharacterBuilderTerminal* bluefrog = cast<CharacterBuilderTerminal*>( scob.get());
						bluefrog->giveLanguages(player);
					}
				}

			} else if (templatePath == "apply_dots") {
				ManagedReference<SceneObject*> scob = cbSui->getUsingObject();
				player->addDotState(CreatureState::POISONED, scob->getObjectID(), 100, CreatureAttribute::HEALTH, 60, 80, 0);
				player->addDotState(CreatureState::BLEEDING, scob->getObjectID(), 100, CreatureAttribute::ACTION, 60, 80, 0);
				player->addDotState(CreatureState::DISEASED, scob->getObjectID(), 100, CreatureAttribute::ACTION, 60, 80, 0);
				player->addDotState(CreatureState::ONFIRE, scob->getObjectID(), 100, CreatureAttribute::HEALTH, 60, 80, 0);
			} else if (templatePath == "clear_dots") {
				player->clearDots();
			} else if (templatePath == "max_xp") {
				ghost->maximizeExperience();
				player->sendSystemMessage("You have maximized all xp types.");
			} else {

				if (templatePath.length() > 0) {

					SkillManager::instance()->awardSkill(templatePath, player, true, true, true);
					if (player->hasSkill(templatePath))
						player->sendSystemMessage("You have learned a skill.");

				} else {

					player->sendSystemMessage("Unknown selection.");

				}
			}

			ghost->addSuiBox(cbSui);
			player->sendMessage(cbSui->generateMessage());
		} else { // Items

			if (templatePath.contains("event_perk")) {
				if (ghost->getEventPerkCount() >= 5) {
					player->sendSystemMessage("@event_perk:pro_too_many_perks"); // You cannot rent any more items right now.
					ghost->addSuiBox(cbSui);
					player->sendMessage(cbSui->generateMessage());
					return;
				}
			}

			ManagedReference<SceneObject*> item = zserv->createObject(node->getTemplateCRC(), 1);

			if (item == NULL) {
				player->sendSystemMessage("There was an error creating the requested item. Please contact customer support with this issue.");
				ghost->addSuiBox(cbSui);
				player->sendMessage(cbSui->generateMessage());

				error("could not create frog item: " + node->getDisplayName());
				return;
			}

			item->createChildObjects();

			if (item->isEventPerkDeed()) {
				EventPerkDeed* deed = cast<EventPerkDeed*>(item.get());
				deed->setOwner(player);
				ghost->addEventPerk(deed);
			}

			ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory");
			item->sendTo(player, true);
			inventory->transferObject(item, -1, true);

			StringIdChatParameter stringId;
			stringId.setStringId("@faction_perk:bonus_base_name"); //You received a: %TO.
			stringId.setTO(item);
			player->sendSystemMessage(stringId);

			ghost->addSuiBox(cbSui);
			player->sendMessage(cbSui->generateMessage());
		}
	}
}
Пример #12
0
TEST_F(LuaMobileTest, LuaMobileTemplatesTest) {
	CreatureTemplateManager::DEBUG_MODE = 1;

	// Verify that all mobiles load
	ASSERT_EQ(CreatureTemplateManager::instance()->loadTemplates(), 0);

	// Verify loot group map loaded
	ASSERT_EQ(LootGroupMap::ERROR_CODE, 0);

	// Verify factions load
	FactionManager::instance()->loadData();
	ASSERT_FALSE(FactionManager::instance()->getFactionMap()->isEmpty());

	// Load Templates
	ASSERT_TRUE( TemplateManager::instance() != NULL );
	if( TemplateManager::instance()->loadedTemplatesCount == 0 ){
		TemplateManager::instance()->loadLuaTemplates();
		ASSERT_EQ(TemplateManager::ERROR_CODE, 0);
	}
	// verify DNA manager loads
	DnaManager::instance()->loadSampleData();
	ASSERT_TRUE( DnaManager::instance() != NULL);


	// Test Creature Templates
	HashTableIterator<uint32, Reference<CreatureTemplate*> > creatureIterator = CreatureTemplateManager::instance()->iterator();
	while (creatureIterator.hasNext()) {
		CreatureTemplate* creature = creatureIterator.next();
		std::string templateName( creature->getTemplateName().toCharArray() );
		//Verify non-empty objectName is a valid string
		String objName = creature->getObjectName();
		if (!objName.isEmpty()) {
			std::string name = objName.toCharArray();
			EXPECT_TRUE( mobNames.contains(objName) ) << "Mobile " << templateName << " has invalid objectName: "  << name;
		}

		// Check configured templates
		Vector<String> objTemps = creature->getTemplates();
		EXPECT_FALSE( objTemps.isEmpty() ) << "Mobile " << templateName << " does not have any templates configured";
		int objectType = 0;
		for( int j=0; j< objTemps.size(); j++ ){
			SharedObjectTemplate* templateData = templateManager->getTemplate(objTemps.get(j).hashCode());
			std::string objName = objTemps.get(j).toCharArray();
			EXPECT_TRUE( templateData != NULL ) << "Mobile " << templateName << " has invalid template configured: " << objName;

			// Check Template Genetics math to find invalid mobs
			if (templateData != NULL) {
				SharedCreatureObjectTemplate* creoData = dynamic_cast<SharedCreatureObjectTemplate*> (templateData);
				if (creoData != NULL) {
				}
			}

			if (objectType == 0) {
				objectType = templateData->getGameObjectType();
			}
		}
		// Verify that control device template is valid
		String controlDeviceTemplate = creature->getControlDeviceTemplate();
		if (!controlDeviceTemplate.isEmpty()) {
			SharedObjectTemplate* controlDeviceTemplateData = templateManager->getTemplate(controlDeviceTemplate.hashCode());
			EXPECT_TRUE( controlDeviceTemplateData != NULL ) << "Control device template " << controlDeviceTemplate.toCharArray() << " from " << templateName << " does not exist.";
			EXPECT_TRUE( controlDeviceTemplate.beginsWith("object/intangible/pet/") ) << "Control device template " << controlDeviceTemplate.toCharArray() << " from " << templateName << " is not a pet/droid control device template.";
		}

		// Verify that faction is valid
		String faction = creature->getFaction();
		if (!faction.isEmpty()) {
			EXPECT_TRUE( FactionManager::instance()->isFaction(faction) ) << "Faction, " << faction.toCharArray() << ", from mobile template " << templateName << " does not exist.";
		}

		// Verify level
		int level = creature->getLevel();
		EXPECT_TRUE( level > 0 ) << "Level is not a positive value on mobile: " << templateName;

		// Verify hit chance
		float hitChance = creature->getChanceHit();
		EXPECT_TRUE( hitChance > 0 ) << "ChanceHit is not a positive value on mobile: " << templateName;

		// Verify xp
		int xp = creature->getBaseXp();
		EXPECT_TRUE( xp >= 0 ) << "Xp has a negative value on mobile: " << templateName;

		// Verify damage
		int minDamage = creature->getDamageMin();
		int maxDamage = creature->getDamageMax();
		EXPECT_TRUE( minDamage > 0 ) << "Min damage is not a positive value on mobile: " << templateName;
		EXPECT_TRUE( maxDamage >= minDamage ) << "Max damage is lower than min damage on mobile: " << templateName;

		// Verify HAM
		int minHam = creature->getBaseHAM();
		int maxHam = creature->getBaseHAMmax();
		EXPECT_TRUE( minHam > 0 ) << "Base ham is not a positive value on mobile: " << templateName;
		EXPECT_TRUE( maxHam >= minHam ) << "Base ham max is lower than base ham on mobile: " << templateName;

		// Verify armor
		int armor = creature->getArmor();
		EXPECT_TRUE( armor >= 0 && armor <= 3 ) << "Armor is not a valid value on mobile: " << templateName;

		// Verify resists
		float kinetic = creature->getKinetic();
		EXPECT_TRUE( kinetic >= -1 && kinetic <= 200 ) << "Kinetic resist is not a valid value on mobile: " << templateName;
		float energy = creature->getEnergy();
		EXPECT_TRUE( energy >= -1 && energy <= 200 ) << "Energy resist is not a valid value on mobile: " << templateName;
		float electricity = creature->getElectricity();
		EXPECT_TRUE( electricity >= -1 && electricity <= 200 ) << "Electricity resist is not a valid value on mobile: " << templateName;
		float stun = creature->getStun();
		EXPECT_TRUE( stun >= -1 && stun <= 200 ) << "Stun resist is not a valid value on mobile: " << templateName;
		float blast = creature->getBlast();
		EXPECT_TRUE( blast >= -1 && blast <= 200 ) << "Blast resist is not a valid value on mobile: " << templateName;
		float heat = creature->getHeat();
		EXPECT_TRUE( heat >= -1 && heat <= 200 ) << "Heat resist is not a valid value on mobile: " << templateName;
		float cold = creature->getCold();
		EXPECT_TRUE( cold >= -1 && cold <= 200 ) << "Cold resist is not a valid value on mobile: " << templateName;
		float acid = creature->getAcid();
		EXPECT_TRUE( acid >= -1 && acid <= 200 ) << "Acid resist is not a valid value on mobile: " << templateName;
		float lightSaber = creature->getLightSaber();
		EXPECT_TRUE( lightSaber >= -1 && lightSaber <= 200 ) << "LightSaber resist is not a valid value on mobile: " << templateName;

		// Verify creature resources
		String meat = creature->getMeatType();
		float meatMax = creature->getMeatMax();
		if (!meat.isEmpty()) {
			String meatResources = "meat_domesticated,meat_wild,meat_herbivore,meat_carnivore,meat_reptilian,meat_avian,meat_insect";
			StringTokenizer tokenizer(meatResources);
			tokenizer.setDelimeter(",");
			bool match = false;
			String token;
			while (tokenizer.hasMoreTokens()) {
				tokenizer.getStringToken(token);
				if (meat == token)
					match = true;
			}
			EXPECT_TRUE( match ) << "Meat type on mobile " << templateName << " is not a valid meat resource";
			EXPECT_TRUE( meatMax > 0 ) << "Meat amount on mobile " << templateName << " is zero.";
		} else {
			EXPECT_TRUE( meatMax == 0 ) << "MeatAmount is not zero yet has no type defined on mobile " << templateName;
		}

		String hide = creature->getHideType();
		float hideMax = creature->getHideMax();
		if (!hide.isEmpty()) {
			String hideResources = "hide_bristley,hide_leathery,hide_scaley,hide_wooly";
			StringTokenizer tokenizer(hideResources);
			tokenizer.setDelimeter(",");
			bool match = false;
			String token;
			while (tokenizer.hasMoreTokens()) {
				tokenizer.getStringToken(token);
				if (hide == token)
					match = true;
			}
			EXPECT_TRUE( match ) << "Hide type on mobile " << templateName << " is not a valid hide resource";
			EXPECT_TRUE( hideMax > 0 ) << "Hide amount on mobile " << templateName << " is zero.";
		} else {
			EXPECT_TRUE( hideMax == 0 ) << "HideAmount is not zero yet has no type defined on mobile " << templateName;
		}

		String bone = creature->getBoneType();
		float boneMax = creature->getBoneMax();
		if (!bone.isEmpty()) {
			String boneResources = "bone_avian,bone_mammal";
			StringTokenizer tokenizer(boneResources);
			tokenizer.setDelimeter(",");
			bool match = false;
			String token;
			while (tokenizer.hasMoreTokens()) {
				tokenizer.getStringToken(token);
				if (bone == token)
					match = true;
			}
			EXPECT_TRUE( match ) << "Bone type on mobile " << templateName << " is not a valid bone resource";
			EXPECT_TRUE( boneMax > 0 ) << "Bone amount on mobile " << templateName << " is zero.";
		} else {
			EXPECT_TRUE( boneMax == 0 ) << "BoneAmount is not zero yet has no type defined on mobile " << templateName;
		}

		String milk = creature->getMilkType();
		float milkMax = creature->getMilk();
		if (!milk.isEmpty()) {
			String milkResources = "milk_domesticated,milk_wild";
			StringTokenizer tokenizer(milkResources);
			tokenizer.setDelimeter(",");
			bool match = false;
			String token;
			while (tokenizer.hasMoreTokens()) {
				tokenizer.getStringToken(token);
				if (milk == token)
					match = true;
			}
			EXPECT_TRUE( match ) << "Milk type on mobile " << templateName << " is not a valid milk resource";
			EXPECT_TRUE( milkMax > 0 ) << "Milk amount on mobile " << templateName << " is zero.";
		} else {
			EXPECT_TRUE( milkMax == 0 ) << "Milk is not zero yet has no type defined on mobile " << templateName;
		}

		// Verify taming chance
		float tamingChance = creature->getTame();
		EXPECT_TRUE( tamingChance >= 0 && tamingChance <= 1 ) << "Taming chance is not a valid value on mobile: " << templateName;

		// Verify diet on creatures
		if (boneMax > 0 || hideMax > 0 || meatMax > 0 || milkMax > 0 || tamingChance > 0) {
			uint32 diet = creature->getDiet();
			EXPECT_TRUE( diet != 0 ) << "Diet is NONE on creature type mobile " << templateName;
		}

		// Verify scale
		float scale = creature->getScale();
		EXPECT_TRUE( scale > 0 ) << "Scale is not a positive value on mobile: " << templateName;

		// Verify PACK mobs have a social group
		uint32 creatureBitmask = creature->getCreatureBitmask();
		String socialGroup = creature->getSocialGroup();
		if (creatureBitmask & CreatureFlag::PACK) {
			EXPECT_FALSE( socialGroup.isEmpty() ) << "Social group is empty on pack mobile: " << templateName;
		}

		// Verify loot group percentages
		LootGroupCollection* groupCollection = creature->getLootGroups();
		if( groupCollection->count() > 0 ){


			for( int i = 0; i < groupCollection->count(); i++ ){

				LootGroupCollectionEntry* collectionEntry = groupCollection->get(i);
				LootGroups* groups = collectionEntry->getLootGroups();
				if( groups->count() > 0){

					int totalChance = 0;
					for( int j = 0; j < groups->count(); j++ ){

						LootGroupEntry* lootGroup = groups->get(j);
						totalChance += lootGroup->getLootChance();

						// Verify loot group is configured correctly
						LootGroupTemplate* foundGroup = lootGroupMap->getLootGroupTemplate( lootGroup->getLootGroupName() );
						std::string groupName( lootGroup->getLootGroupName().toCharArray() );
						EXPECT_TRUE( foundGroup != NULL ) << "Loot group " << groupName << " from " << templateName << " was not found in LootGroupMap";

					}

					EXPECT_EQ( 10000000, totalChance ) << "Loot groups total chance is incorrect " << templateName;
				}
			}
		}

		// Verify weapon groups exist
		Vector<String> weapons = creature->getWeapons();
		for (int i = 0; i < weapons.size(); i++) {
			String weaponGroup = weapons.get(i);
			std::string groupName( weaponGroup.toCharArray() );
			Vector<String> group = CreatureTemplateManager::instance()->getWeapons(weaponGroup);
			EXPECT_TRUE( group.size() > 0 ) << "Weapon group " << groupName << " from " << templateName << " was not found in weaponMap";
		}

		// Verify conversation template exist, and the mob has converse option bit
		uint32 convoTemplate = creature->getConversationTemplate();
		uint32 optionsBitmask = creature->getOptionsBitmask();
		if (convoTemplate != 0) {
			ConversationTemplate* convoTemp = CreatureTemplateManager::instance()->getConversationTemplate(convoTemplate);
			EXPECT_TRUE( convoTemp != NULL ) << "Conversation template from " << templateName << " was not found.";
			EXPECT_TRUE( optionsBitmask & OptionBitmask::CONVERSE ) << templateName << " has a convo template but not the CONVERSE options bit.";
		}
		// Verify that mobs with converse option bit have a convo template
		if (optionsBitmask & OptionBitmask::CONVERSE) {
			EXPECT_TRUE( convoTemplate != 0 ) << templateName << " has the CONVERSE options bit but not a convo template.";
		}

		// Verify that outfits exist
		String outfit = creature->getOutfit();
		if (!outfit.isEmpty()) {
			MobileOutfitGroup* outfitGroup = CreatureTemplateManager::instance()->getMobileOutfitGroup(outfit);
			EXPECT_TRUE( outfitGroup != NULL ) << "Outfit group " << outfit.toCharArray() << " from " << templateName << " was not found.";
		}

		// Verify attacks are valid commands
		CreatureAttackMap* cam = creature->getAttacks();
		for (int i = 0; i < cam->size(); i++) {
			String commandName = cam->getCommand(i);

			EXPECT_TRUE( commandName.isEmpty() || commandConfigManager->contains(commandName) ) << "Attack: " << commandName.toCharArray() << " is not a valid command in mobile template: " << templateName;
		}

		// Very attackable npcs
		uint32 pvpBitmask = creature->getPvpBitmask();
		if ((pvpBitmask & CreatureFlag::ATTACKABLE) && objectType == 1025) {
			// Verify attackable npcs have attacks
			EXPECT_TRUE( cam->size() > 0 ) << "Attackable npc " << templateName << " does not have attacks.";
		}
	}

	// Test Lair Templates
	HashTableIterator<uint32, Reference<LairTemplate*> > lairIterator = CreatureTemplateManager::instance()->lairTemplateIterator();
	while (lairIterator.hasNext()) {
		LairTemplate* lair = lairIterator.next();
		std::string templateName( lair->getName().toCharArray() );

		// Verify that mobiles exist and that their weighting is positive
		VectorMap<String, int>* mobiles = lair->getMobiles();
		for (int i = 0; i < mobiles->size(); i++) {
			int weighting = mobiles->elementAt(i).getValue();
			String mobile = mobiles->elementAt(i).getKey();
			std::string mobName = mobile.toCharArray();
			EXPECT_TRUE( CreatureTemplateManager::instance()->getTemplate(mobile) != NULL ) << "Mobile " << mobName << " in lair template " << templateName << " does not exist";
			EXPECT_TRUE( weighting > 0 ) << "Mobile " << mobName << " in lair template " << templateName << " has a non positive weighting";
		}

		// Verify that boss mobiles exist and that their count is positive
		VectorMap<String, int>* bossMobiles = lair->getBossMobiles();
		for (int i = 0; i < bossMobiles->size(); i++) {
			int count = bossMobiles->elementAt(i).getValue();
			String bossMob = bossMobiles->elementAt(i).getKey();
			std::string bossName = bossMob.toCharArray();
			EXPECT_TRUE( CreatureTemplateManager::instance()->getTemplate(bossMob) != NULL ) << "Boss mobile " << bossName << " in lair template " << templateName << " does not exist";
			EXPECT_TRUE( count > 0 ) << "Boss mobile " << bossName << " in lair template " << templateName << " has a non positive spawn count";
		}

		// Verify spawn limit is positive
		int limit = lair->getSpawnLimit();
		EXPECT_TRUE( limit > 0 ) << "Spawn limit in lair template " << templateName << " is not positive";

		// Verify any configured buildings exist
		int buildingCount = 0;
		for(int i=0; i<=4; i++){

			Vector<String>* buildings = lair->getBuildings( i );
			if( buildings == NULL )
				continue;

			buildingCount += buildings->size();

			for( int j=0; j < buildings->size(); j++ ){
				String buildingTemplate = buildings->get(j);
				std::string buildingStr = buildingTemplate.toCharArray();
				SharedObjectTemplate* templateObject = templateManager->getTemplate(buildingTemplate.hashCode());
				EXPECT_TRUE( templateObject != NULL && templateObject->isSharedTangibleObjectTemplate() ) << "Building template " << buildingStr << " in lair template " << templateName << " does not exist";
				if( lair->getBuildingType() == LairTemplate::LAIR ){
					EXPECT_TRUE( buildingTemplate.beginsWith( "object/tangible/lair/") ) << "Building template " << buildingStr << " in lair template " << templateName << " is not a child of object/tangible/lair/";
				}
				if( lair->getBuildingType() == LairTemplate::THEATER ){
					EXPECT_TRUE( buildingTemplate.beginsWith( "object/building/poi/") ) << "Building template " << buildingStr << " in lair template " << templateName << " is not a child of object/building/poi/";
				}
			}
		}

		// Verify mission buildings exist and are lairs
		String missionBuilding = lair->getMissionBuilding(10);
		if (!missionBuilding.isEmpty()) {
			std::string buildingStr = missionBuilding.toCharArray();
			SharedObjectTemplate* templateObject = templateManager->getTemplate(missionBuilding.hashCode());
			EXPECT_TRUE( templateObject != NULL && templateObject->isSharedTangibleObjectTemplate() ) << "Mission building template " << buildingStr << " in lair template " << templateName << " does not exist";
			EXPECT_TRUE( missionBuilding.beginsWith( "object/tangible/lair/") ) << "Mission building template " << buildingStr << " in lair template " << templateName << " is not a child of object/tangible/lair/";
		}

		if( lair->getBuildingType() == LairTemplate::THEATER ){
			EXPECT_TRUE( buildingCount > 0 ) << "There are no buildings configured in theater type lair template " << templateName;
		}
		if( lair->getBuildingType() == LairTemplate::NONE ){
			EXPECT_TRUE( buildingCount == 0 ) << "There are buildings configured in 'none' type lair template " << templateName;
		}
		if( lair->getBuildingType() == LairTemplate::LAIR ){
			EXPECT_TRUE( buildingCount > 0 ) << "There are no buildings configured in lair type lair template " << templateName;
		}

	}

	// Test Spawn Groups
	HashTableIterator<uint32, Reference<SpawnGroup*> > spawnIterator = CreatureTemplateManager::instance()->spawnGroupIterator();
	while (spawnIterator.hasNext()) {
		SpawnGroup* group = spawnIterator.next();
		std::string templateName( group->getTemplateName().toCharArray() );

		Vector<String> lairTemplates;

		// Verify spawn list
		Vector<Reference<LairSpawn*> >* spawnList = group->getSpawnList();
		for (int i = 0; i < spawnList->size(); i++) {
			LairSpawn* spawn = spawnList->get(i);
			std::string lairName( spawn->getLairTemplateName().toCharArray() );

			// Verify lair template exists and isn't duplicated in the group
			String lairTemplateName = spawn->getLairTemplateName();
			Reference<LairTemplate*> lairTemplate = CreatureTemplateManager::instance()->getLairTemplate(lairTemplateName.hashCode());
			EXPECT_TRUE( lairTemplate != NULL ) << "Lair template " << lairName << " in spawn group " << templateName << " does not exist.";
			EXPECT_FALSE( lairTemplates.contains(lairTemplateName) ) << "Lair template " << lairName << " is duplicated in spawn group " << templateName;
			lairTemplates.add(lairTemplateName);

			// Verify spawn limit is at least -1
			float spawnLimit = spawn->getSpawnLimit();
			EXPECT_TRUE( spawnLimit >= -1 ) << "SpawnLimit for lairTemplate " << lairName << " in spawn group " << templateName << " is less than -1.";

			// Verify difficulties
			int minDiff = spawn->getMinDifficulty();
			int maxDiff = spawn->getMaxDifficulty();
			EXPECT_TRUE( minDiff > 0 ) << "MinDifficulty for lairTemplate " << lairName << " in spawn group " << templateName << " is not positive.";
			EXPECT_TRUE( maxDiff >= minDiff ) << "MaxDifficulty for lairTemplate " << lairName << " in spawn group " << templateName << " is less than min difficulty.";

			// Verify number to spawn is not negative
			int numberToSpawn = spawn->getNumberToSpawn();
			EXPECT_TRUE( numberToSpawn >= 0 ) << "NumberToSpawn for lairTemplate " << lairName << " in spawn group " << templateName << " is negative.";

			// Verify weighting is positive
			int weighting = spawn->getWeighting();
			EXPECT_TRUE( weighting > 0 ) << "Weighting for lairTemplate " << lairName << " in spawn group " << templateName << " is not positive.";

			// Verify size is at least 1
			float size = spawn->getSize();
			EXPECT_TRUE( size >= 1 ) << "Size for lairTemplate " << lairName << " in spawn group " << templateName << " is less than 1.";
		}
	}

	// Test Destroy Mission Spawn Groups
	HashTableIterator<uint32, Reference<SpawnGroup*> > missionIterator = CreatureTemplateManager::instance()->destroyMissionGroupIterator();
	while (missionIterator.hasNext()) {
		SpawnGroup* group = missionIterator.next();
		std::string templateName( group->getTemplateName().toCharArray() );

		Vector<String> lairTemplates;

		// Verify spawn list
		Vector<Reference<LairSpawn*> >* spawnList = group->getSpawnList();
		for (int i = 0; i < spawnList->size(); i++) {
			LairSpawn* spawn = spawnList->get(i);
			std::string lairName( spawn->getLairTemplateName().toCharArray() );

			// Verify lair template exists
			String lairTemplateName = spawn->getLairTemplateName();
			Reference<LairTemplate*> lairTemplate = CreatureTemplateManager::instance()->getLairTemplate(lairTemplateName.hashCode());
			EXPECT_TRUE( lairTemplate != NULL ) << "Lair template " << lairName << " in destroy mission spawn group " << templateName << " does not exist.";
			EXPECT_FALSE( lairTemplates.contains(lairTemplateName) ) << "Lair template " << lairName << " is duplicated in destroy mission spawn group " << templateName;
			lairTemplates.add(lairTemplateName);

			if (lairTemplate != NULL) {
				// Verify that lair template has a valid mission building or is of type LAIR
				String missionBuilding = lairTemplate->getMissionBuilding(10);
				if (!missionBuilding.isEmpty()) {
					std::string buildingStr = missionBuilding.toCharArray();
					SharedObjectTemplate* templateObject = templateManager->getTemplate(missionBuilding.hashCode());
					EXPECT_TRUE( templateObject != NULL && templateObject->isSharedTangibleObjectTemplate() ) << "Mission building template " << buildingStr << " in lair template " << lairName << ", part of destroy mission group " << templateName << " does not exist";
					EXPECT_TRUE( missionBuilding.beginsWith( "object/tangible/lair/") ) << "Mission building template " << buildingStr << " in lair template " << lairName << ", part of destroy mission group " << templateName << " is not a child of object/tangible/lair/";
				} else {
					EXPECT_TRUE( lairTemplate->getBuildingType() == LairTemplate::LAIR ) << "Lair template " << lairName << ", part of destroy mission group " << templateName << " is not of type LAIR";
				}
			}

			// Verify difficulties
			int minDiff = spawn->getMinDifficulty();
			int maxDiff = spawn->getMaxDifficulty();
			EXPECT_TRUE( minDiff > 0 ) << "MinDifficulty for lairTemplate " << lairName << " in destroy mission spawn group " << templateName << " is not positive.";
			EXPECT_TRUE( maxDiff >= minDiff ) << "MaxDifficulty for lairTemplate " << lairName << " in destroy mission spawn group " << templateName << " is less than min difficulty.";

			// Verify size is at least 1
			float size = spawn->getSize();
			EXPECT_TRUE( size >= 1 ) << "Size for lairTemplate " << lairName << " in destroy mission spawn group " << templateName << " is less than 1.";
		}
	}
}
Пример #13
0
void TreeNode::xPathTestNode(const Array<String>& tokens, int tokenIndex, const Enumerator<TreeNode*>& enumerator, bool includeHiddenChildren, const NumberFormat* numberFormat)
{
	if (tokenIndex == tokens.getCount())
	{
		// If no further path-tokens are available, we are at the end of the path,
		// and have found a target-node to add to the result:
		enumerator.enumerate(this);
	}
	else
	{
		int nextTokenIndex = tokenIndex + 1;
		const String& token = tokens[tokenIndex];
		if (token == "..")
		{
			if (parent != NULL)
			{
				parent->xPathTestNode(tokens, nextTokenIndex, enumerator, includeHiddenChildren, numberFormat);
			}
			else
			{
				argumentError("XPath invalid for current tree!" ERROR_AT);
				return;
			}
		}
		else if (token == '.')
		{
			xPathTestNode(tokens, nextTokenIndex, enumerator, includeHiddenChildren, numberFormat);
		}
		else
		{
			int where = token.findFirst('[');
			if (where == String::END)
			{
				// If no [ was found:
				// For every child-node:
				int childCount = includeHiddenChildren == true ? getChildCountIncludingHiddenChildren() : getChildCount();
				for (int i = 0; i < childCount; ++i)
				{
					TreeNode* childNode = getChild(i);
					if (childNode->getName() == token || token == '*')
					{
						// If name of child-node is valid for the next path-token:
						childNode->xPathTestNode(tokens, nextTokenIndex, enumerator, includeHiddenChildren, numberFormat);
					}
				}
			}
			else
			{
				// If [ was found:
				String name = token.subString(0, where).trimTail();
				int countOfNodesWithMatchingName = 0;
				// For every child-node:
				int childCount = includeHiddenChildren == true ? getChildCountIncludingHiddenChildren() : getChildCount();
				for (int i = 0; i < childCount; ++i)
				{
					TreeNode* childNode = getChild(i);
					if (childNode->getName() == name || name == '*')
					{
						++countOfNodesWithMatchingName;

						// If name of child-node is valid for the next path-token,
						// get expression between [ and ]:
						String expression = token.subString(where + 1, token.findLast(']') - (where + 1));
						if (expression.beginsWith('@') == true)
						{
							// If we are dealing with an attribute:
							int equalPos = expression.findFirst('=');
							if (equalPos == String::END)
							{
								String attributeName = expression.subString(1);
								if (childNode->hasAttribute(attributeName) == true)
								{
									childNode->xPathTestNode(tokens, nextTokenIndex, enumerator, includeHiddenChildren, numberFormat);
								}
							}
							else
							{
								String attributeName = expression.subString(1, equalPos-1).trimTail();
								String value = expression.subString(equalPos + 1).trimFront();
								String attribute;
								if (getAttributeIfAvailable(attributeName, attribute, numberFormat) == true && attribute == value)
								{
									childNode->xPathTestNode(tokens, nextTokenIndex, enumerator, includeHiddenChildren, numberFormat);
								}
							}
						}
						else if (expression.isDec() == true)
						{
							// If we are dealing with a node-indexer:
							if (expression.parseInt() == countOfNodesWithMatchingName)
							{
								childNode->xPathTestNode(tokens, nextTokenIndex, enumerator, includeHiddenChildren, numberFormat);
							}
						}
						else
						{
							argumentError("Unsupported XPath expression: " + token + ERROR_AT);
						}

					} // if (childNode->getName() == name || name == '*')

				} // for (int i = 0; i < childCount; ++i)

			} // else if (where == String::END)

		} // else if (token == "..") else if if (token == '.')

	} // else if (tokenIndex == tokens.getLength())

}
Пример #14
0
void CommandServer::incomingRequestEventHandler(ServerSocket & sender, const std::string & connectionId, const std::string & data) 
{
	LOG_DEBUG("incoming request connectionId=" + connectionId + " data=" + data);
	String query = String(data);

	if (query == QueryStatus) 
	{
		//Find the phoneline status and answer
		UserProfile * userprofile = _wengoPhone.getUserProfileHandler().getCurrentUserProfile();
		if (userprofile) {
			IPhoneLine * phoneLine = userprofile->getActivePhoneLine();
			if (phoneLine && phoneLine->isConnected()) {
				_serverSocket->writeToClient(connectionId, QueryStatus + "|1");
			} else {
				_serverSocket->writeToClient(connectionId, QueryStatus + "|0");
			}
		}

	} 
	else if (query == QueryBringToFront) 
	{
		bringMainWindowToFrontEvent();
	} 
	else if (query.beginsWith(QueryCall)) 
	{
		//Extract the number from query & place the call
		StringList l = query.split("/");

		if (l.size() == 2) 
		{
			LOG_DEBUG("call peer=" + l[1]);
			UserProfile * userprofile = _wengoPhone.getUserProfileHandler().getCurrentUserProfile();
			if (userprofile) 
			{
				IPhoneLine * phoneLine = userprofile->getActivePhoneLine();
				if (phoneLine && phoneLine->isConnected()) 
				{
					phoneLine->makeCall(l[1]);
					_serverSocket->writeToClient(connectionId, data + "|1");
					return;
				}
			}
		}

		_serverSocket->writeToClient(connectionId, data + "|0");
	} 
	else if (query.beginsWith(QuerySms)) 
	{
		LOG_WARN("not yet implemented");

	} 
	else if (query.contains(QueryChat)) 
	{
		UserProfile * userProfile = _wengoPhone.getUserProfileHandler().getCurrentUserProfile();
		if (userProfile) 
		{
			IPhoneLine * phoneLine = userProfile->getActivePhoneLine();
			if (phoneLine && phoneLine->isConnected()) 
			{
				// extract the nickname from 1|o|chat/pseudo=value&sip=value
				StringList l = query.split("/");
				std::string nickname;
				if (l.size() == 2) 
				{
					int sepPos = l[1].find("&");
					nickname = l[1].substr(7, sepPos - 7);
				}
				////

				// get THE Wengo account
				IMAccountList imAccountList = userProfile->getIMAccountManager().getIMAccountsOfProtocol(EnumIMProtocol::IMProtocolWengo);
				////

				// create the IMContactSet
				IMAccount *imAccount = userProfile->getIMAccountManager().getIMAccount( imAccountList.begin()->second );	//VOXOX - JRT - 2009.04.24 
				IMContact imContact(*imAccount, nickname);
				IMContactSet imContactSet;
				imContactSet.insert(imContact);
				////

				// create the chat session
				std::string temp = "";
				ChatHandler & chatHandler = userProfile->getChatHandler();
				chatHandler.createSession(imAccount->getKey(), imContactSet, IMChat::Chat, temp );	//VOXOX - JRT - 2009.04.24
				////
				
				OWSAFE_DELETE(imAccount);
			}
		}
		// failed
		_serverSocket->writeToClient(connectionId, QueryChat + "|0");

	} else if (query.beginsWith(QueryAddContact)) {

		UserProfile * userProfile = _wengoPhone.getUserProfileHandler().getCurrentUserProfile();
		if (userProfile) {

			ContactInfo contactInfo;
			String tmp = query.substr(QueryAddContact.size(), query.size() - 1);

			StringList args = tmp.split("&");
			for (unsigned i = 0; i < args.size(); i++) {

				String tmp = args[i];
				if (!tmp.size()) {
					continue;
				}

				StringList list = tmp.split("=");
				if ((!(list.size() == 2)) || list[0].empty()) {
					continue;
				}

				// remove the first and the last quote if any
				String value = list[1];

				if (list[0] == NICKNAME_STR) {
					contactInfo.wengoName = value;
				} else if (list[0] == SIP_STR) {
					contactInfo.sip = value;
				} else if (list[0] == FIRSTNAME_STR) {
					contactInfo.firstname = value;
				} else if (list[0] == LASTNAME_STR) {
					contactInfo.lastname = value;
				} else if (list[0] == COUNTRY_STR) {
					contactInfo.country = value;
				} else if (list[0] == CITY_STR) {
					contactInfo.city = value;
				} else if (list[0] == STATE_STR) {
					contactInfo.state = value;
				} else if (list[0] == GROUP_STR) {
					contactInfo.group = value;
				} else if (list[0] == WDEALSERVICETITLE_STR) {
					contactInfo.wdealServiceTitle = value;
				} else if (list[0] == URL_STR) {
					if (value.beginsWith("\"")) {
						value = value.substr(1, value.size() - 2);
					}
					contactInfo.website = value;
				}
			}

			showAddContactEvent(contactInfo);
		}

	} else {

		Config & config = ConfigManager::getInstance().getCurrentConfig();

		//"emulate" a http server. Needed for Flash sockets
		std::string tmp = "<?xml version=\"1.0\"?>\n"
			"<!DOCTYPE cross-domain-policy SYSTEM \"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd\">\n"
			"<cross-domain-policy>\n";
		StringList domains = config.getCmdServerAuthorizedDomains();
		StringList::const_iterator it = domains.begin(), end = domains.end();
		for (;it!=end; ++it) {
			tmp += "<allow-access-from domain=\"" + *it + "\" to-ports=\"*\" />\n";
		}
		tmp += "<allow-access-from domain=\"localhost\" to-ports=\"*\" />\n"
				"</cross-domain-policy>";
		_serverSocket->writeToClient(connectionId, buildHttpForFlash(tmp));
	}
}
void VehicleControlDeviceImplementation::spawnObject(CreatureObject* player) {
	ZoneServer* zoneServer = getZoneServer();

	ManagedReference<TangibleObject*> controlledObject = this->controlledObject.get();

	if (controlledObject == NULL)
		return;

	if (!isASubChildOf(player))
		return;

	if (player->getParent() != NULL || player->isInCombat()) {
		player->sendSystemMessage("@pet/pet_menu:cant_call_vehicle"); // You can only unpack vehicles while Outside and not in Combat.
		return;
	}

	ManagedReference<TradeSession*> tradeContainer = player->getActiveSession(SessionFacadeType::TRADE).castTo<TradeSession*>();

	if (tradeContainer != NULL) {
		server->getZoneServer()->getPlayerManager()->handleAbortTradeMessage(player);
	}

	controlledObject->initializePosition(player->getPositionX(), player->getPositionZ(), player->getPositionY());
	ManagedReference<CreatureObject*> vehicle = NULL;
	
	if (controlledObject->isCreatureObject())
	{
	
		vehicle = cast<CreatureObject*>(controlledObject.get());
		vehicle->setCreatureLink(player);
		vehicle->setControlDevice(_this.getReferenceUnsafeStaticCast());
		if (vehicle->isDestroyed())
		{
			String vehicleName = vehicle->getDisplayedName();
			if (!vehicleName.beginsWith("(disabled)"))
			{
				UnicodeString disabledName = "(disabled) " + vehicle->getDisplayedName();
				vehicle->setCustomObjectName(disabledName, true);
			}
		}

	}
	
	Zone* zone = player->getZone();
	
	if (zone == NULL)
		return;

	//controlledObject->insertToZone(player->getZone());
	zone->transferObject(controlledObject, -1, true);
	controlledObject->inflictDamage(player, 0, System::random(50), true);
	
	if (vehicle != NULL && controlledObject->getServerObjectCRC() == 0x32F87A54) // Jetpack
	{
	
		controlledObject->setCustomizationVariable("/private/index_hover_height", 40, true); // Illusion of flying.
		player->executeObjectControllerAction(STRING_HASHCODE("mount"), controlledObject->getObjectID(), ""); // Auto mount.
		
	}

	updateStatus(1);

	if (vehicleControlObserver != NULL)
		player->dropObserver(ObserverEventType::STARTCOMBAT, vehicleControlObserver);
}