示例#1
0
/*
 * Play with an item. Options include:
 *   - Output statistics (via wiz_roll_item)
 *   - Reroll item (via wiz_reroll_item)
 *   - Change properties (via wiz_tweak_item)
 *   - Change the number of items (via wiz_quantity_item)
 */
static void do_cmd_wiz_play(void)
{
	int item;

	object_type *i_ptr;
	object_type object_type_body;

	object_type *o_ptr;

	struct keypress ch;

	const char *q, *s;

	bool changed = FALSE;
	bool all = TRUE;


	/* Get an item */
	q = "Play with which object? ";
	s = "You have nothing to play with.";
	if (!get_item(&item, q, s, 0, (USE_EQUIP | USE_INVEN | USE_FLOOR))) return;

	o_ptr = object_from_item_idx(item);

	/* Save screen */
	screen_save();


	/* Get local object */
	i_ptr = &object_type_body;

	/* Copy object */
	object_copy(i_ptr, o_ptr);


	/* The main loop */
	while (TRUE)
	{
		/* Display the item */
		wiz_display_item(i_ptr, all);

		/* Get choice */
		if (!get_com("[a]ccept [s]tatistics [r]eroll [t]weak [c]urse [q]uantity [k]nown? ", &ch))
			break;

		if (ch.code == 'A' || ch.code == 'a')
		{
			changed = TRUE;
			break;
		}
		else if (ch.code == 'c' || ch.code == 'C')
			wiz_tweak_curse(i_ptr);
		else if (ch.code == 's' || ch.code == 'S')
			wiz_statistics(i_ptr, p_ptr->depth);
		else if (ch.code == 'r' || ch.code == 'R')
			wiz_reroll_item(i_ptr);
		else if (ch.code == 't' || ch.code == 'T')
			wiz_tweak_item(i_ptr);
		else if (ch.code == 'k' || ch.code == 'K')
			all = !all;
		else if (ch.code == 'q' || ch.code == 'Q')
		{
			bool carried = (item >= 0) ? TRUE : FALSE;
			wiz_quantity_item(i_ptr, carried);
		}
	}


	/* Load screen */
	screen_load();


	/* Accept change */
	if (changed)
	{
		/* Message */
		msg("Changes accepted.");

		/* Change */
		object_copy(o_ptr, i_ptr);

		/* Recalculate bonuses */
		p_ptr->update |= (PU_BONUS);

		/* Combine / Reorder the pack (later) */
		p_ptr->notice |= (PN_COMBINE | PN_REORDER);

		/* Window stuff */
		p_ptr->redraw |= (PR_INVEN | PR_EQUIP );
	}

	/* Ignore change */
	else
	{
		msg("Changes ignored.");
	}
}
示例#2
0
文件: cmd2.c 项目: Hrrunstar/angband
/*
 * Disarms a trap, or a chest
 */
void do_cmd_disarm(cmd_code code, cmd_arg args[])
{
	int y, x, dir;

	s16b o_idx;

	bool more = FALSE;

	dir = args[0].direction;

	/* Get location */
	y = p_ptr->py + ddy[dir];
	x = p_ptr->px + ddx[dir];

	/* Check for chests */
	o_idx = chest_check(y, x);


	/* Verify legality */
	if (!o_idx && !do_cmd_disarm_test(y, x))
	{
		/* Cancel repeat */
		disturb(0, 0);
		return;
	}

	/* Take a turn */
	p_ptr->energy_use = 100;

	/* Apply confusion */
	if (player_confuse_dir(p_ptr, &dir))
	{
		/* Get location */
		y = p_ptr->py + ddy[dir];
		x = p_ptr->px + ddx[dir];

		/* Check for chests */
		o_idx = chest_check(y, x);
	}


	/* Monster */
	if (cave->m_idx[y][x] > 0)
	{
		/* Message */
		msg("There is a monster in the way!");

		/* Attack */
		py_attack(y, x);
	}

	/* Chest */
	else if (o_idx)
	{
		/* Disarm the chest */
		more = do_cmd_disarm_chest(y, x, o_idx);
	}

	/* Disarm trap */
	else
	{
		/* Disarm the trap */
		more = do_cmd_disarm_aux(y, x);
	}

	/* Cancel repeat unless told not to */
	if (!more) disturb(0, 0);
}
示例#3
0
文件: cmd2.c 项目: Hrrunstar/angband
/*
 * Manipulate an adjacent grid in some way
 *
 * Attack monsters, tunnel through walls, disarm traps, open doors.
 *
 * This command must always take energy, to prevent free detection
 * of invisible monsters.
 *
 * The "semantics" of this command must be chosen before the player
 * is confused, and it must be verified against the new grid.
 */
void do_cmd_alter_aux(int dir)
{
	int y, x;

	int feat;

	bool more = FALSE;

	/* Get location */
	y = p_ptr->py + ddy[dir];
	x = p_ptr->px + ddx[dir];


	/* Original feature */
	feat = cave->feat[y][x];

	/* Must have knowledge to know feature XXX XXX */
	if (!(cave->info[y][x] & (CAVE_MARK))) feat = FEAT_NONE;


	/* Take a turn */
	p_ptr->energy_use = 100;

	/* Apply confusion */
	if (player_confuse_dir(p_ptr, &dir))
	{
		/* Get location */
		y = p_ptr->py + ddy[dir];
		x = p_ptr->px + ddx[dir];
	}


	/* Attack monsters */
	if (cave->m_idx[y][x] > 0)
	{
		py_attack(y, x);
	}

	/* Tunnel through walls */
	else if (feat >= FEAT_SECRET)
	{
		more = do_cmd_tunnel_aux(y, x);
	}

#if 0
	/* Bash jammed doors */
	else if (feat >= FEAT_DOOR_HEAD + 0x08)
	{
		more = do_cmd_bash_aux(y, x);
	}
#endif

	/* Open closed doors */
	else if (feat >= FEAT_DOOR_HEAD)
	{
		more = do_cmd_open_aux(y, x);
	}

	/* Disarm traps */
	else if (feat >= FEAT_TRAP_HEAD)
	{
		more = do_cmd_disarm_aux(y, x);
	}

#if 0
	/* Close open doors */
	else if (feat == FEAT_OPEN)
	{
		more = do_cmd_close_aux(y, x);
	}
#endif

	/* Oops */
	else
	{
		msg("You spin around.");
	}

	/* Cancel repetition unless we can continue */
	if (!more) disturb(0, 0);
}
示例#4
0
文件: main.c 项目: ASPLes/turbulence
int main (int argc, char ** argv)
{
	/* install headers for help */
	exarg_add_usage_header  (HELP_HEADER);
	exarg_add_help_header   (HELP_HEADER);
	exarg_post_help_header  (POST_HEADER);
	exarg_post_usage_header (POST_HEADER);

	/* install exarg options */
	exarg_install_arg ("version", "v", EXARG_NONE,
			   "Provides tool version");

	exarg_install_arg ("template", "t", EXARG_NONE,
			   "Produce a module xml template. Use this file as starting point to create a module. Then use --compile.");

	exarg_install_arg ("compile", "p", EXARG_STRING,
			   "Produces the source code associated to a module, using as description the xml module definition provided.");
	
	exarg_install_arg ("out-dir", "o", EXARG_STRING,
			   "Allows to configure the out put dir to be used. If not provided, '.' will be used as default value");

	exarg_install_arg ("enable-autoconf", "e", EXARG_NONE,
			   "Makes the output to produce autoconf support files: autogen.sh and configure.ac. It provides an starting point to build and compile your module.");

	exarg_install_arg ("debug2", NULL, EXARG_NONE,
			   "Increase the level of log to console produced.");

	exarg_install_arg ("debug3", NULL, EXARG_NONE,
			   "Makes logs produced to console to inclue more information about the place it was launched.");

	exarg_install_arg ("color-debug", "c", EXARG_NONE,
			   "Makes console log to be colorified.");	

	/* call to parse arguments */
	exarg_parse (argc, argv);

	ctx = turbulence_ctx_new ();

	/* create a vortex context and init the support module */
	vortex_ctx = vortex_ctx_new ();
	turbulence_ctx_set_vortex_ctx (ctx, vortex_ctx);
	vortex_support_init (vortex_ctx);

	/* configure context debug according to values received */
	turbulence_log_enable  (ctx, axl_true);
	turbulence_log2_enable (ctx, exarg_is_defined ("debug2"));
	turbulence_log3_enable (ctx, exarg_is_defined ("debug3"));

	/* check console color debug */
	turbulence_color_log_enable (ctx, exarg_is_defined ("color-debug"));

	/* check version argument */
	if (exarg_is_defined ("version")) {
		msg ("tbc-mod-gen version: %s", VERSION);
		goto finish;
	} else if (exarg_is_defined ("template")) {
		/* produce a template definition */
		tbc_mod_gen_template_create ();
	} else if (exarg_is_defined ("compile")) {
		/* compile template provided */
		tbc_mod_gen_compile ();
	} else {

		/* no argument was produced */
		error ("no argument was provided, try to use %s --help", argv[0]);
	}

 finish:
	/* terminate exarg */
	exarg_end ();

	/* cleanup support module */
	vortex_support_cleanup (vortex_ctx);
	axl_free (out_dir);

	/* free context */
	turbulence_ctx_free (ctx);
	vortex_ctx_free (vortex_ctx);

	return 0;
}
示例#5
0
Message MessageUtil::receiveMessage()
{
	int sockfd, numbytes;
	char buf[1024];
	struct addrinfo hints, *servinfo, *p;
	int rv;
	char s[INET6_ADDRSTRLEN];

	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;

	if ((rv = getaddrinfo(this->host.c_str(), this->port.c_str(), &hints, &servinfo)) != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
	}

	// loop through all the results and connect to the first we can
	for(p = servinfo; p != NULL; p = p->ai_next) {
		if ((sockfd = socket(p->ai_family, p->ai_socktype,
				p->ai_protocol)) == -1) {
			perror("client: socket");
			continue;
		}

		if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
			close(sockfd);
			perror("client: connect");
			continue;
		}

		break;
	}

	if (p == NULL) {
		fprintf(stderr, "client: failed to connect\n");
	}

	inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
			s, sizeof s);
	printf("client: connecting to %s\n", s);

	freeaddrinfo(servinfo); // all done with this structure

	string h = "GET FROM "+this->destination.getName()+":"+this->destination.getType();
	if(this->destination.getType()=="Topic")
		h += ("-" + this->getSubscriber());
	//bool flag = true;
	if (send(sockfd, h.c_str(), h.length(), 0) == -1)
	{
		logger << "send failed" << flush;
		//flag = false;
	}
	logger << h << flush;

	if ((numbytes = recv(sockfd, buf, 1024, 0)) == -1) {
		perror("recv");
		exit(1);
	}
	string temp,results;
	stringstream ss;
	ss << buf;
	while(getline(ss,temp))
	{
		logger << temp << flush;
		results += temp;
	}
	logger << "\n\nclient: received" << flush;
	logger << results << flush;
	Message msg(results);
	buf[numbytes] = '\0';

	close(sockfd);
	memset(&buf[0], 0, sizeof(buf));
	return msg;
}
BOOL test_pdcp_data_ind(void)
{
  /*
   * This is the list that pdcp_data_ind() takes to put pdcp_data_ind_header_t
   * packets after it receives/validates PDUs and preprends them with pdcp_data_ind_header_t
   * structure. Here, after this list is filled by pdcp_data_ind() we parse/validate
   * every single element in the list
   */
  list_t test_pdu_indication_list;
  mem_block_t* test_sdu = NULL;
  /*
   * pdcp_data_req() method prepended PDU header in front of DUMMY_BUFFER so
   * the size should be 12 bytes
   */
  unsigned char test_sdu_size = PDCP_USER_PLANE_DATA_PDU_LONG_SN_HEADER_SIZE + DUMMY_BUFFER_SIZE;
  unsigned int index = 0;

  /*
   * Initialize linked list
   */
  list_init(&test_pdu_indication_list, NULL);

  /*
   * Ask PDCP to handle a number of data indications
   */
  msg("There are %d PDUs in the list\n", test_pdu_rx_list.nb_elements);

  /*
   * Traverse PDU list and pass each one of them to pdcp_data_ind()
   */
  while (list_get_head(&test_pdu_rx_list) != NULL) {
    msg("\n\nAsking PDCP to receive %d. SDU...\n", 1 + index++);

    test_sdu = list_remove_head(&test_pdu_rx_list);

    if (pdcp_data_ind(0, 0, test_sdu_size, test_sdu, &pdcp_array[0], &test_pdu_indication_list) == FALSE) {
      msg("[TEST] pdcp_data_ind() failed to handle data indication!\n");
      return FALSE;
    } else {
      msg("[TEST] pdcp_data_ind() succcessfuly handled data indication\n");
    }

    /*
     * Parse/validate fields of SDU
     */
    msg("[TEST] Starting to dissect SDU created by PDCP...\n");
    /*
     * Get pdcp_data_ind_header_t added by pdcp_data_ind()
     */
    mem_block_t* test_data_ind_header = list_remove_head(&test_pdu_indication_list);

    if (test_data_ind_header == NULL) {
      msg("[TEST] Data indication header is not valid!\n");
      return FALSE;
    } else {
      pdcp_data_ind_header_t* indication_header = (pdcp_data_ind_header_t*)test_data_ind_header->data;

      /*
       * Verify that radio bearer ID is correct (0)
       */
      if (indication_header->rb_id == 0) {
        msg("[TEST] Radio bearer ID is correct\n");
      } else {
        msg("[TEST] Radio bearer ID is not correct! (expected: 0, parsed: %d)\n", indication_header->rb_id);
        return FALSE;
      }

      /*
       * Verify that SDU size is correct (DUMMY_BUFFER_SIZE)
       */
      if (indication_header->data_size == DUMMY_BUFFER_SIZE + PDCP_USER_PLANE_DATA_PDU_LONG_SN_HEADER_SIZE) {
        msg("[TEST] SDU size is correct\n");
      } else {
        msg("[TEST] SDU size is not correct! (expected: %d, parsed: %d)\n", DUMMY_BUFFER_SIZE, indication_header->data_size);
        return FALSE;
      }

      /*
       * XXX Verify `indication_header->inst` when you know what it is
       */
    }

    /*
     * XXX PDCP PDU header should also be checked here
     */

    /*
     * Verify that serialised data is the stream we've supplied
     *
     * Data comes after `pdcp_data_ind_header_t` and `pdcp_user_plane_data_pdu_header_with_long_sn`
     */
    unsigned char data_index = sizeof(pdcp_data_ind_header_t) + PDCP_USER_PLANE_DATA_PDU_LONG_SN_HEADER_SIZE;

    if (memcmp(DUMMY_BUFFER, (unsigned char*)&(test_data_ind_header->data[data_index]), DUMMY_BUFFER_SIZE) == 0) {
      msg("[TEST] Data payload of pdcp_data_ind_header_t matches with the stream we sent\n");

    } else {
      msg("[TEST] Data payload of pdcp_data_ind_header_t does not match with the stream we sent!\n");

      /*
       * Print octets of both streams
       * XXX This could be a method in test_util.h
       */
      print_byte_stream("[TEST] TXed data: ", DUMMY_BUFFER, DUMMY_BUFFER_SIZE);
      print_byte_stream("[TEST] RXed data: ", (unsigned char*)&(test_data_ind_header->data[data_index]), DUMMY_BUFFER_SIZE);

      return FALSE;
    }
  }

  return TRUE;
}
示例#7
0
void CComponentManager::Script_RegisterComponentType_Common(ScriptInterface::CxPrivate* pCxPrivate, int iid, const std::string& cname, JS::HandleValue ctor, bool reRegister, bool systemComponent)
{
	CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData);
	JSContext* cx = componentManager->m_ScriptInterface.GetContext();
	JSAutoRequest rq(cx);

	// Find the C++ component that wraps the interface
	int cidWrapper = componentManager->GetScriptWrapper(iid);
	if (cidWrapper == CID__Invalid)
	{
		componentManager->m_ScriptInterface.ReportError("Invalid interface id");
		return;
	}
	const ComponentType& ctWrapper = componentManager->m_ComponentTypesById[cidWrapper];

	bool mustReloadComponents = false; // for hotloading

	ComponentTypeId cid = componentManager->LookupCID(cname);
	if (cid == CID__Invalid)
	{
		if (reRegister)
		{
			std::string msg("ReRegistering component type that was not registered before '"+cname+"'");
			componentManager->m_ScriptInterface.ReportError(msg.c_str());
			return;
		}
		// Allocate a new cid number
		cid = componentManager->m_NextScriptComponentTypeId++;
		componentManager->m_ComponentTypeIdsByName[cname] = cid;
		if (systemComponent)
			componentManager->MarkScriptedComponentForSystemEntity(cid);
	}
	else
	{
		// Component type is already loaded, so do hotloading:

		if (!componentManager->m_CurrentlyHotloading && !reRegister)
		{
			std::string msg("Registering component type with already-registered name '"+cname+"'");
			componentManager->m_ScriptInterface.ReportError(msg.c_str());
			return;
		}

		const ComponentType& ctPrevious = componentManager->m_ComponentTypesById[cid];

		// We can only replace scripted component types, not native ones
		if (ctPrevious.type != CT_Script)
		{
			std::string msg("Loading script component type with same name '"+cname+"' as native component");
			componentManager->m_ScriptInterface.ReportError(msg.c_str());
			return;
		}

		// We don't support changing the IID of a component type (it would require fiddling
		// around with m_ComponentsByInterface and being careful to guarantee uniqueness per entity)
		if (ctPrevious.iid != iid)
		{
			// ...though it only matters if any components exist with this type
			if (!componentManager->m_ComponentsByTypeId[cid].empty())
			{
				componentManager->m_ScriptInterface.ReportError("Hotloading script component type mustn't change interface ID");
				return;
			}
		}

		// Remove the old component type's message subscriptions
		std::map<MessageTypeId, std::vector<ComponentTypeId> >::iterator it;
		for (it = componentManager->m_LocalMessageSubscriptions.begin(); it != componentManager->m_LocalMessageSubscriptions.end(); ++it)
		{
			std::vector<ComponentTypeId>& types = it->second;
			std::vector<ComponentTypeId>::iterator ctit = find(types.begin(), types.end(), cid);
			if (ctit != types.end())
				types.erase(ctit);
		}
		for (it = componentManager->m_GlobalMessageSubscriptions.begin(); it != componentManager->m_GlobalMessageSubscriptions.end(); ++it)
		{
			std::vector<ComponentTypeId>& types = it->second;
			std::vector<ComponentTypeId>::iterator ctit = find(types.begin(), types.end(), cid);
			if (ctit != types.end())
				types.erase(ctit);
		}

		mustReloadComponents = true;
	}

	std::string schema = "<empty/>";
	{
		JS::RootedValue prototype(cx);
		if (componentManager->m_ScriptInterface.GetProperty(ctor, "prototype", &prototype) &&
			componentManager->m_ScriptInterface.HasProperty(prototype, "Schema"))
		{
			componentManager->m_ScriptInterface.GetProperty(prototype, "Schema", schema);
		}
	}

	// Construct a new ComponentType, using the wrapper's alloc functions
	ComponentType ct(
		CT_Script,
		iid,
		ctWrapper.alloc,
		ctWrapper.dealloc,
		cname,
		schema,
		DefPersistentRooted<JS::Value>(cx, ctor)
	);
	componentManager->m_ComponentTypesById[cid] = std::move(ct);

	componentManager->m_CurrentComponent = cid; // needed by Subscribe


	// Find all the ctor prototype's On* methods, and subscribe to the appropriate messages:
	JS::RootedValue protoVal(cx);
	if (!componentManager->m_ScriptInterface.GetProperty(ctor, "prototype", &protoVal))
		return; // error

	std::vector<std::string> methods;
	JS::RootedObject proto(cx);
	if (!protoVal.isObjectOrNull())
		return; // error

	proto = protoVal.toObjectOrNull();

	if (!componentManager->m_ScriptInterface.EnumeratePropertyNamesWithPrefix(protoVal, "On", methods))
		return; // error

	for (std::vector<std::string>::const_iterator it = methods.begin(); it != methods.end(); ++it)
	{
		std::string name = (*it).substr(2); // strip the "On" prefix

		// Handle "OnGlobalFoo" functions specially
		bool isGlobal = false;
		if (name.substr(0, 6) == "Global")
		{
			isGlobal = true;
			name = name.substr(6);
		}

		std::map<std::string, MessageTypeId>::const_iterator mit = componentManager->m_MessageTypeIdsByName.find(name);
		if (mit == componentManager->m_MessageTypeIdsByName.end())
		{
			std::string msg("Registered component has unrecognised '" + *it + "' message handler method");
			componentManager->m_ScriptInterface.ReportError(msg.c_str());
			return;
		}

		if (isGlobal)
			componentManager->SubscribeGloballyToMessageType(mit->second);
		else
			componentManager->SubscribeToMessageType(mit->second);
	}

	componentManager->m_CurrentComponent = CID__Invalid;

	if (mustReloadComponents)
	{
		// For every script component with this cid, we need to switch its
		// prototype from the old constructor's prototype property to the new one's
		const std::map<entity_id_t, IComponent*>& comps = componentManager->m_ComponentsByTypeId[cid];
		std::map<entity_id_t, IComponent*>::const_iterator eit = comps.begin();
		for (; eit != comps.end(); ++eit)
		{
			JS::RootedValue instance(cx, eit->second->GetJSInstance());
			if (!instance.isNull())
			{
				componentManager->m_ScriptInterface.SetPrototype(instance, protoVal);
			}
		}
	}
}
示例#8
0
static void aargh(const char *cause) {
  const char *why = strerror(errno);
  if (!why) why = "Unknown error";
  msg("%s: %s (%d)", cause, why, errno);
  exit(1);
}
void CGUIDialogSmartPlaylistEditor::UpdateButtons()
{
  CONTROL_ENABLE(CONTROL_OK); // always enabled since we can have no rules -> match everything (as we do with default partymode playlists)
  
  // if there's no rule available, add a dummy one the user can edit
  if (m_playlist.m_ruleCombination.m_rules.size() <= 0)
    m_playlist.m_ruleCombination.AddRule(CSmartPlaylistRule());

  // name
  if (m_mode == "partyvideo" || m_mode == "partymusic")
  {
    SET_CONTROL_LABEL2(CONTROL_NAME, g_localizeStrings.Get(16035));
    CONTROL_DISABLE(CONTROL_NAME);
  }
  else
    SET_CONTROL_LABEL2(CONTROL_NAME, m_playlist.m_playlistName);
  
  UpdateRuleControlButtons();

  CONTROL_ENABLE_ON_CONDITION(CONTROL_MATCH, m_playlist.m_ruleCombination.m_rules.size() > 1);

  int currentItem = GetSelectedItem();
  CGUIMessage msgReset(GUI_MSG_LABEL_RESET, GetID(), CONTROL_RULE_LIST);
  OnMessage(msgReset);
  m_ruleLabels->Clear();
  for (unsigned int i = 0; i < m_playlist.m_ruleCombination.m_rules.size(); i++)
  {
    CFileItemPtr item(new CFileItem("", false));
    if (m_playlist.m_ruleCombination.m_rules[i]->m_field == FieldNone)
      item->SetLabel(g_localizeStrings.Get(21423));
    else
      item->SetLabel(std::static_pointer_cast<CSmartPlaylistRule>(m_playlist.m_ruleCombination.m_rules[i])->GetLocalizedRule());
    m_ruleLabels->Add(item);
  }
  CGUIMessage msg(GUI_MSG_LABEL_BIND, GetID(), CONTROL_RULE_LIST, 0, 0, m_ruleLabels);
  OnMessage(msg);
  SendMessage(GUI_MSG_ITEM_SELECT, GetID(), CONTROL_RULE_LIST, currentItem);

  if (m_playlist.m_orderDirection != SortOrderDescending)
  {
    CONTROL_SELECT(CONTROL_ORDER_DIRECTION);
  }
  else
  {
    CONTROL_DESELECT(CONTROL_ORDER_DIRECTION);
  }

  // sort out the order fields
  std::vector< std::pair<std::string, int> > labels;
  std::vector<SortBy> orders = CSmartPlaylistRule::GetOrders(m_playlist.GetType());
  for (unsigned int i = 0; i < orders.size(); i++)
    labels.push_back(make_pair(g_localizeStrings.Get(SortUtils::GetSortLabel(orders[i])), orders[i]));
  SET_CONTROL_LABELS(CONTROL_ORDER_FIELD, m_playlist.m_orderField, &labels);

  // setup groups
  labels.clear();
  std::vector<Field> groups = CSmartPlaylistRule::GetGroups(m_playlist.GetType());
  Field currentGroup = CSmartPlaylistRule::TranslateGroup(m_playlist.GetGroup().c_str());
  for (unsigned int i = 0; i < groups.size(); i++)
    labels.push_back(make_pair(CSmartPlaylistRule::GetLocalizedGroup(groups[i]), groups[i]));
  SET_CONTROL_LABELS(CONTROL_GROUP_BY, currentGroup, &labels);

  if (m_playlist.IsGroupMixed())
    CONTROL_SELECT(CONTROL_GROUP_MIXED);
  else
    CONTROL_DESELECT(CONTROL_GROUP_MIXED);

  // disable the group controls if there's no group
  // or only one group which can't be mixed
  if (groups.size() == 0 ||
     (groups.size() == 1 && !CSmartPlaylistRule::CanGroupMix(groups[0])))
  {
    CONTROL_DISABLE(CONTROL_GROUP_BY);
    CONTROL_DISABLE(CONTROL_GROUP_MIXED);
  }
  else
  {
    CONTROL_ENABLE(CONTROL_GROUP_BY);
    CONTROL_ENABLE_ON_CONDITION(CONTROL_GROUP_MIXED, CSmartPlaylistRule::CanGroupMix(currentGroup));
  }
}
示例#10
0
void
gtBaseOpts::parse (int ac, char **av)
{
    bool haveRestrictConfigFile = !statFile (m_sys_restrict_cfg_file.c_str ());
    bool haveDefaultConfigFile = !statFile (m_sys_cfg_file.c_str ());
    bool haveUserConfigFile = false;

    try
    {
        add_options ();
        add_positionals ();

        bpo::command_line_parser parser (ac, av);
        parser.options (m_all_desc);
        parser.positional (m_pos);

        bpo::variables_map cli_vm; // CLI and non-restricted Config File options.
        bpo::variables_map res_vm; // Restricted Config File options.

        bpo::store (parser.run(), cli_vm);

        if (cli_vm.count (OPT_VERBOSE))
            m_haveVerboseOnCli = true;

        if (cli_vm.count (OPT_CFG_FILE))
            haveUserConfigFile = true;

        if (haveRestrictConfigFile)
            processConfigFile (m_sys_restrict_cfg_file, m_cfg_desc, res_vm);

        // Store config file variables on cli variables map
        if (haveRestrictConfigFile &&
            res_vm.count (OPT_NO_USER_CFG_FILE))
        {
            // Restricted config disallows user-supplied config file
            if (haveUserConfigFile)
                commandLineError ("Restricted configuration file disallows the "
                                  "use of the '" OPT_CFG_FILE "' option.");

            if (haveDefaultConfigFile)
                processConfigFile (m_sys_cfg_file, m_cfg_desc, cli_vm);
        }
        else
        {
            // Prefer user-supplied config file over default config file
            if (haveUserConfigFile)
            {
                std::string cfgPath = cli_vm[OPT_CFG_FILE].as<std::string>();
                processConfigFile (cfgPath, m_cfg_desc, cli_vm);
            }
            else if (haveDefaultConfigFile)
            {
                processConfigFile (m_sys_cfg_file, m_cfg_desc, cli_vm);
            }
        }

        if (haveRestrictConfigFile)
        {
            processConfigFile (m_sys_restrict_cfg_file, m_cfg_desc, cli_vm);
            checkForIllegalOverrides(res_vm, cli_vm);
        }
        // This call signals that the variables_map is now "finalized"
        // and calls notifiers to set variables to option values
        // (which we don't currently use)
        bpo::notify (cli_vm);

        m_vm = cli_vm;
    }
    catch (bpo::error &e)
    {
        std::ostringstream msg ("Options Error: ");
        msg << e.what();
        commandLineError (msg.str());
    }

    if (m_vm.count (OPT_HELP))
        displayHelp ();

    if (m_vm.count (OPT_VERSION))
        displayVersion ();

    processOptions ();

//    log_options_used ();
}
示例#11
0
static int
load_of(uval64 rmo_start, uval64 rmo_size)
{
	uval32 stub_addr = rmo_size - (1 << 20);
	char mem_node[64];
	uval64 prop[2];
	int ret;
	char *dum = NULL;

      retry:
	snprintf(mem_node, sizeof(mem_node), "/memory@0x%x", 0);
	prop[0] = 0;
	prop[1] = stub_addr;
	of_set_prop(mem_node, "available", prop, sizeof (prop));

	char oftree[512];
	char ofstub[512];
	char ofdimg[512];

	snprintf(oftree, sizeof(oftree), HYPE_ROOT "/%s/of_tree", oh_pname);
	snprintf(ofstub, sizeof(ofstub), HYPE_ROOT "/%s/of_image", oh_pname);
	snprintf(ofdimg, sizeof(ofdimg), HYPE_ROOT "/%s/of_tree.ofd", oh_pname);

	const char *const args[] = { "ofdfs", "pack", oftree, ofdimg, NULL };
	run_command(args);

	uval32 stub_size;
	struct stat buf;

	ret = stat(ofstub, &buf);
	ASSERT(ret == 0, "Stat failure %s\n", ofstub);
	stub_size = buf.st_size + 4 * PGSIZE;

	uval32 data_size;

	ret = stat(ofdimg, &buf);
	ASSERT(ret == 0, "Stat failure %s\n", ofdimg);
	data_size = buf.st_size;

	uval32 bottom = ALIGN_DOWN(rmo_size - data_size - stub_size, 1 << 20);

	if (stub_addr > bottom) {
		stub_addr = bottom;
		goto retry;
	}

	uval32 data_addr = ALIGN_UP(stub_addr + stub_size, PGSIZE);

	int fd = open(ofstub, O_RDWR);

	ASSERT(fd >= 0, "bad fd for %s\n", ofstub);

	off_t offset = lseek(fd, 0x10, SEEK_SET);

	ASSERT(offset != ((off_t) - 1), "seek failure on %s\n", ofstub);

	write(fd, &data_addr, sizeof (data_addr));

	close(fd);

	msg("Loading OF stub: 0x%x[0x%x]\n", stub_addr, stub_size);
	msg("Loading OF data: 0x%x[0x%x]\n", data_addr, data_size);
	laddr_load(ofstub, rmo_start + stub_addr, &dum);
	laddr_load(ofdimg, rmo_start + data_addr, &dum);

	set_file_printf("r5", "0x%lx", stub_addr);
	set_file_printf("r1", "0x%lx", stub_addr - PGSIZE);
	return 0;
}
示例#12
0
/*
 * Try to create an item again. Output some statistics.    -Bernd-
 *
 * The statistics are correct now.  We acquire a clean grid, and then
 * repeatedly place an object in this grid, copying it into an item
 * holder, and then deleting the object.  We fiddle with the artifact
 * counter flags to prevent weirdness.  We use the items to collect
 * statistics on item creation relative to the initial item.
 */
static void wiz_statistics(object_type *o_ptr, int level)
{
	long i, matches, better, worse, other;
	int j;

	struct keypress ch;
	const char *quality;

	bool good, great, ismatch, isbetter, isworse;

	object_type *i_ptr;
	object_type object_type_body;

	const char *q = "Rolls: %ld, Matches: %ld, Better: %ld, Worse: %ld, Other: %ld";


	/* Allow multiple artifacts, because breaking the game is fine here */
	if (o_ptr->artifact) o_ptr->artifact->created = FALSE;


	/* Interact */
	while (TRUE)
	{
		const char *pmt = "Roll for [n]ormal, [g]ood, or [e]xcellent treasure? ";

		/* Display item */
		wiz_display_item(o_ptr, TRUE);

		/* Get choices */
		if (!get_com(pmt, &ch)) break;

		if (ch.code == 'n' || ch.code == 'N')
		{
			good = FALSE;
			great = FALSE;
			quality = "normal";
		}
		else if (ch.code == 'g' || ch.code == 'G')
		{
			good = TRUE;
			great = FALSE;
			quality = "good";
		}
		else if (ch.code == 'e' || ch.code == 'E')
		{
			good = TRUE;
			great = TRUE;
			quality = "excellent";
		}
		else
		{
#if 0 /* unused */
			good = FALSE;
			great = FALSE;
#endif /* unused */
			break;
		}

		/* Let us know what we are doing */
		msg("Creating a lot of %s items. Base level = %d.",
		           quality, p_ptr->depth);
		message_flush();

		/* Set counters to zero */
		matches = better = worse = other = 0;

		/* Let's rock and roll */
		for (i = 0; i <= TEST_ROLL; i++)
		{
			/* Output every few rolls */
			if ((i < 100) || (i % 100 == 0))
			{
				struct keypress kp;

				/* Do not wait */
				inkey_scan = SCAN_INSTANT;

				/* Allow interupt */
				kp = inkey();
				if (kp.type != EVT_NONE)
				{
					flush();
					break;
				}

				/* Dump the stats */
				prt(format(q, i, matches, better, worse, other), 0, 0);
				Term_fresh();
			}


			/* Get local object */
			i_ptr = &object_type_body;

			/* Wipe the object */
			object_wipe(i_ptr);

			/* Create an object */
			make_object(cave, i_ptr, level, good, great, FALSE, NULL, 0);

			/* Allow multiple artifacts, because breaking the game is fine here */
			if (o_ptr->artifact) o_ptr->artifact->created = FALSE;

			/* Test for the same tval and sval. */
			if ((o_ptr->tval) != (i_ptr->tval)) continue;
			if ((o_ptr->sval) != (i_ptr->sval)) continue;

			/* Check pvals */
			ismatch = TRUE;
			for (j = 0; j < MAX_PVALS; j++)
				if (i_ptr->pval[j] != o_ptr->pval[j])
					ismatch = FALSE;

			isbetter = TRUE;
			for (j = 0; j < MAX_PVALS; j++)
				if (i_ptr->pval[j] < o_ptr->pval[j])
					isbetter = FALSE;

			isworse = TRUE;
			for (j = 0; j < MAX_PVALS; j++)
				if (i_ptr->pval[j] > o_ptr->pval[j])
					isworse = FALSE;

			/* Check for match */
			if (ismatch && (i_ptr->to_a == o_ptr->to_a) &&
				(i_ptr->to_h == o_ptr->to_h) &&
				(i_ptr->to_d == o_ptr->to_d) &&
				(i_ptr->num_pvals == o_ptr->num_pvals))
			{
				matches++;
			}

			/* Check for better */
			else if (isbetter && (i_ptr->to_a >= o_ptr->to_a) &&
			         (i_ptr->to_h >= o_ptr->to_h) &&
			         (i_ptr->to_d >= o_ptr->to_d))
			{
					better++;
			}

			/* Check for worse */
			else if (isworse && (i_ptr->to_a <= o_ptr->to_a) &&
			         (i_ptr->to_h <= o_ptr->to_h) &&
			         (i_ptr->to_d <= o_ptr->to_d))
			{
				worse++;
			}

			/* Assume different */
			else
			{
				other++;
			}
		}

		/* Final dump */
		msg(q, i, matches, better, worse, other);
		message_flush();
	}


	/* Hack -- Normally only make a single artifact */
	if (o_ptr->artifact) o_ptr->artifact->created = TRUE;
}
示例#13
0
/*
 * Ask for and parse a "debug command"
 */
void do_cmd_debug(void)
{
	int py = p_ptr->py;
	int px = p_ptr->px;

	struct keypress cmd;


	/* Get a "debug command" */
	if (!get_com("Debug Command: ", &cmd)) return;

	/* Analyze the command */
	switch (cmd.code)
	{
		/* Ignore */
		case ESCAPE:
		case ' ':
		case KC_ENTER:
		{
			break;
		}

#ifdef ALLOW_SPOILERS

		/* Hack -- Generate Spoilers */
		case '"':
		{
			do_cmd_spoilers();
			break;
		}

#endif


		/* Hack -- Help */
		case '?':
		{
			do_cmd_wiz_help();
			break;
		}

		/* Cure all maladies */
		case 'a':
		{
			do_cmd_wiz_cure_all();
			break;
		}

		/* Make the player powerful */
		case 'A':
		{
			do_cmd_wiz_advance();
			break;
		}
		
		/* Teleport to target */
		case 'b':
		{
			do_cmd_wiz_bamf();
			break;
		}

		/* Create any object */
		case 'c':
		{
			wiz_create_item();
			break;
		}

		/* Create an artifact */
		case 'C':
		{
			char name[80] = "";
			int a_idx = -1;

			/* Avoid the prompt getting in the way */
			screen_save();

			/* Prompt */
			prt("Create which artifact? ", 0, 0);

			/* Get the name */
			if (askfor_aux(name, sizeof(name), NULL))
			{
				/* See if an a_idx was entered */
				a_idx = get_idx_from_name(name);

				/* If not, find the artifact with that name */
				if (a_idx < 1)
					a_idx = lookup_artifact_name(name); 

				/* Did we find a valid artifact? */
				if (a_idx != -1 && a_idx < z_info->a_max)
					wiz_create_artifact(a_idx);
				else
					msg("No artifact found.");
			}
				
			/* Reload the screen */
			screen_load();

			break;
		}

		/* Detect everything */
		case 'd':
		{
			detect_all(TRUE);
			break;
		}
		
		/* Test for disconnected dungeon */
		case 'D':
		{
			disconnect_stats();
			break;
		}

		/* Edit character */
		case 'e':
		{
			do_cmd_wiz_change();
			break;
		}

		case 'f':
		{
			stats_collect();
			break;
		}

		/* Good Objects */
		case 'g':
		{
			int n;
			screen_save();
			n= get_quantity("How many good objects? ", 40);
			screen_load();
			if (n < 1) n = 1;
			acquirement(py, px, p_ptr->depth, n, FALSE);
			break;
		}

		/* GF demo */
		case 'G':
		{
			wiz_gf_demo();
			break;
		}

		/* Hitpoint rerating */
		case 'h':
		{
			do_cmd_rerate();
			break;
		}
        
        /* Hit all monsters in LOS */
        case 'H':
        {
            dispel_monsters(10000);
            break;
        }

		/* Identify */
		case 'i':
		{
			(void)ident_spell();
			break;
		}

		/* Go up or down in the dungeon */
		case 'j':
		{
			do_cmd_wiz_jump();
			break;
		}

		/* Learn about objects */
		case 'l':
		{
			do_cmd_wiz_learn(100);
			break;
		}

		case 'L': do_cmd_keylog(); break;

		/* Magic Mapping */
		case 'm':
		{
			map_area();
			break;
		}

		/* Summon Named Monster */
		case 'n':
		{
			monster_race *r = NULL;
			char name[80] = "";

			/* Avoid the prompt getting in the way */
			screen_save();

			/* Prompt */
			prt("Summon which monster? ", 0, 0);

			/* Get the name */
			if (askfor_aux(name, sizeof(name), NULL))
			{
				/* See if a r_idx was entered */
				int r_idx = get_idx_from_name(name);
				if (r_idx)
					r = &r_info[r_idx];
				else
					/* If not, find the monster with that name */
					r = lookup_monster(name); 
					
				p_ptr->redraw |= (PR_MAP | PR_MONLIST);
			}

			/* Reload the screen */
			screen_load();

			if (r)
				do_cmd_wiz_named(r, TRUE);
			else
				msg("No monster found.");
			
			break;
		}

		/* Object playing routines */
		case 'o':
		{
			do_cmd_wiz_play();
			break;
		}

		/* Phase Door */
		case 'p':
		{
			teleport_player(10);
			break;
		}

		/* Monster pit stats */
		case 'P':
		{
			pit_stats();
			break;
		}
		
		/* Query the dungeon */
		case 'q':
		{
			do_cmd_wiz_query();
			break;
		}

		/* Get full recall for a monster */
		case 'r':
		{
			const monster_race *r_ptr = NULL;

			struct keypress sym;
			char *prompt =
				"Full recall for [a]ll monsters or [s]pecific monster? ";

			if (!get_com(prompt, &sym)) return;

			if (sym.code == 'a' || sym.code == 'A')
			{
				int i;
				for (i = 0; i < z_info->r_max; i++)
					cheat_monster_lore(&r_info[i], &l_list[i]);
				msg("Done.");
			}
			else if (sym.code == 's' || sym.code == 'S')
			{
				char name[80] = "";
					
				/* Avoid the prompt getting in the way */
				screen_save();

				/* Prompt */
				prt("Which monster? ", 0, 0);

				/* Get the name */
				if (askfor_aux(name, sizeof(name), NULL))
				{
					/* See if a r_idx was entered */
					int r_idx = get_idx_from_name(name);
					if (r_idx)
						r_ptr = &r_info[r_idx];
					else
						/* If not, find the monster with that name */
						r_ptr = lookup_monster(name); 
				}

				/* Reload the screen */
				screen_load();

				/* Did we find a valid monster? */
				if (r_ptr)
					cheat_monster_lore(r_ptr, get_lore(r_ptr));
				else
					msg("No monster found.");
			}

			break;
		}

		/* Summon Random Monster(s) */
		case 's':
		{
			int n;
			screen_save();
			n = get_quantity("How many monsters? ", 40);
			screen_load();
			if (n < 1) n = 1;
			do_cmd_wiz_summon(n);
			break;
		}
		
		/* Collect stats (S) */
		case 'S':
		{
			stats_collect();
			break;
		}

		/* Teleport */
		case 't':
		{
			teleport_player(100);
			break;
		}

		/* Create a trap */
		case 'T':
		{
			if (!cave_isfloor(cave, p_ptr->py, p_ptr->px))
				msg("You can't place a trap there!");
			else if (p_ptr->depth == 0)
				msg("You can't place a trap in the town!");
			else
				cave_add_trap(cave, p_ptr->py, p_ptr->px);
			break;
		}

		/* Un-hide all monsters */
		case 'u':
		{
			detect_monsters_entire_level();
			break;
		}

		/* Very Good Objects */
		case 'v':
		{
			int n;
			screen_save();
			n = get_quantity("How many great objects? ", 40);
			screen_load();
			if (n < 1) n = 1;
			acquirement(py, px, p_ptr->depth, n, TRUE);
			break;
		}

		case 'V':
		{
			int n;
			screen_save();
			n = get_quantity("Create all items of what tval? ", 255);
			screen_load();
			if (n)
				wiz_test_kind(n);
			break;
		}

		/* Wizard Light the Level */
		case 'w':
		{
			wiz_light(TRUE);
			break;
		}

		/* Wipe recall for a monster */
		case 'W':
		{
			const monster_race *r_ptr = NULL;
			s16b r_idx = 0; 

			struct keypress sym;
			char *prompt =
				"Wipe recall for [a]ll monsters or [s]pecific monster? ";

			if (!get_com(prompt, &sym)) return;

			if (sym.code == 'a' || sym.code == 'A')
			{
				int i;
				for (i = 0; i < z_info->r_max; i++)
					wipe_monster_lore(&r_info[i], &l_list[i]);
				msg("Done.");
			}
			else if (sym.code == 's' || sym.code == 'S')
			{
				char name[80] = "";

				/* Avoid the prompt getting in the way */
				screen_save();

				/* Prompt */
				prt("Which monster? ", 0, 0);

				/* Get the name */
				if (askfor_aux(name, sizeof(name), NULL))
				{
					/* See if a r_idx was entered */
					r_idx = get_idx_from_name(name);
					if (r_idx)
						r_ptr = &r_info[r_idx];
					else
						/* If not, find the monster with that name */
						r_ptr = lookup_monster(name); 
				}
					
				/* Reload the screen */
				screen_load();

				/* Did we find a valid monster? */
				if (r_ptr)
					wipe_monster_lore(r_ptr, get_lore(r_ptr));
				else
					msg("No monster found.");
			}
	
			break;
		}

		/* Increase Experience */
		case 'x':
		{
			int n;
			screen_save();
			n = get_quantity("Gain how much experience? ", 9999);
			screen_load();
			if (n < 1) n = 1;
			player_exp_gain(p_ptr, n);
			break;
		}

		/* Zap Monsters (Banishment) */
		case 'z':
		{
			int n;
			screen_save();
			n = get_quantity("Zap within what distance? ", MAX_SIGHT);
			screen_load();
			do_cmd_wiz_zap(n);
			break;
		}

		/* Hack */
		case '_':
		{
			do_cmd_wiz_hack_ben();
			break;
		}

		/* Oops */
		default:
		{
			msg("That is not a valid debug command.");
			break;
		}
	}
}
示例#14
0
/*
 * Query the dungeon
 */
static void do_cmd_wiz_query(void)
{
	int py = p_ptr->py;
	int px = p_ptr->px;

	int y, x;

	struct keypress cmd;

	u16b mask = 0x00;


	/* Get a "debug command" */
	if (!get_com("Debug Command Query: ", &cmd)) return;

	/* Extract a flag */
	switch (cmd.code)
	{
		case '0': mask = (1 << 0); break;
		case '1': mask = (1 << 1); break;
		case '2': mask = (1 << 2); break;
		case '3': mask = (1 << 3); break;
		case '4': mask = (1 << 4); break;
		case '5': mask = (1 << 5); break;
		case '6': mask = (1 << 6); break;
		case '7': mask = (1 << 7); break;

		case 'm': mask |= (CAVE_MARK); break;
		case 'g': mask |= (CAVE_GLOW); break;
		case 'r': mask |= (CAVE_ROOM); break;
		case 'i': mask |= (CAVE_VAULT); break;
		case 's': mask |= (CAVE_SEEN); break;
		case 'v': mask |= (CAVE_VIEW); break;
		case 't': mask |= (CAVE_WASSEEN); break;
		case 'w': mask |= (CAVE_WALL); break;
	}

	/* Scan map */
	for (y = Term->offset_y; y < Term->offset_y + SCREEN_HGT; y++)
	{
		for (x = Term->offset_x; x < Term->offset_x + SCREEN_WID; x++)
		{
			byte a = TERM_RED;

			if (!cave_in_bounds_fully(cave, y, x)) continue;

			/* Given mask, show only those grids */
			if (mask && !(cave->info[y][x] & mask)) continue;

			/* Given no mask, show unknown grids */
			if (!mask && (cave->info[y][x] & (CAVE_MARK))) continue;

			/* Color */
			if (cave_ispassable(cave, y, x)) a = TERM_YELLOW;

			/* Display player/floors/walls */
			if ((y == py) && (x == px))
				print_rel(L'@', a, y, x);
			else if (cave_ispassable(cave, y, x))
				print_rel(L'*', a, y, x);
			else
				print_rel(L'#', a, y, x);
		}
	}

	/* Get keypress */
	msg("Press any key.");
	message_flush();

	/* Redraw map */
	prt_map();
}
示例#15
0
文件: cmd2.c 项目: CJNyfalt/angband
/*
 * Perform the basic "tunnel" command
 *
 * Assumes that no monster is blocking the destination
 *
 * Uses "twall" (above) to do all "terrain feature changing".
 *
 * Returns TRUE if repeated commands may continue
 */
static bool do_cmd_tunnel_aux(int y, int x)
{
	bool more = FALSE;


	/* Verify legality */
	if (!do_cmd_tunnel_test(y, x)) return (FALSE);


	/* Sound XXX XXX XXX */
	/* sound(MSG_DIG); */

	/* Titanium */
	if (cave->feat[y][x] >= FEAT_PERM_EXTRA)
	{
		msg("This seems to be permanent rock.");
	}

	/* Granite */
	else if (cave->feat[y][x] >= FEAT_WALL_EXTRA)
	{
		/* Tunnel */
		if ((p_ptr->state.skills[SKILL_DIGGING] > 40 + randint0(1600)) && twall(y, x))
		{
			msg("You have finished the tunnel.");
		}

		/* Keep trying */
		else
		{
			/* We may continue tunelling */
			msg("You tunnel into the granite wall.");
			more = TRUE;
		}
	}

	/* Quartz / Magma */
	else if (cave->feat[y][x] >= FEAT_MAGMA)
	{
		bool okay = FALSE;
		bool gold = FALSE;
		bool hard = FALSE;

		/* Found gold */
		if (cave->feat[y][x] >= FEAT_MAGMA_H)
		{
			gold = TRUE;
		}

		/* Extract "quartz" flag XXX XXX XXX */
		if ((cave->feat[y][x] - FEAT_MAGMA) & 0x01)
		{
			hard = TRUE;
		}

		/* Quartz */
		if (hard)
		{
			okay = (p_ptr->state.skills[SKILL_DIGGING] > 20 + randint0(800));
		}

		/* Magma */
		else
		{
			okay = (p_ptr->state.skills[SKILL_DIGGING] > 10 + randint0(400));
		}

		/* Success */
		if (okay && twall(y, x))
		{
			/* Found treasure */
			if (gold)
			{
				/* Place some gold */
				place_gold(cave, y, x, p_ptr->depth, ORIGIN_FLOOR);

				/* Message */
				msg("You have found something!");
			}

			/* Found nothing */
			else
			{
				/* Message */
				msg("You have finished the tunnel.");
			}
		}

		/* Failure (quartz) */
		else if (hard)
		{
			/* Message, continue digging */
			msg("You tunnel into the quartz vein.");
			more = TRUE;
		}

		/* Failure (magma) */
		else
		{
			/* Message, continue digging */
			msg("You tunnel into the magma vein.");
			more = TRUE;
		}
	}

	/* Rubble */
	else if (cave->feat[y][x] == FEAT_RUBBLE)
	{
		/* Remove the rubble */
		if ((p_ptr->state.skills[SKILL_DIGGING] > randint0(200)) && twall(y, x))
		{
			/* Message */
			msg("You have removed the rubble.");

			/* Hack -- place an object */
			if (randint0(100) < 10)	{
				/* Create a simple object */
				place_object(cave, y, x, p_ptr->depth, FALSE, FALSE,
					ORIGIN_RUBBLE);

				/* Observe the new object */
				if (!squelch_item_ok(object_byid(cave->o_idx[y][x])) &&
					    player_can_see_bold(y, x))
					msg("You have found something!");
			}
		}

		else
		{
			/* Message, keep digging */
			msg("You dig in the rubble.");
			more = TRUE;
		}
	}

	/* Secret doors */
	else if (cave->feat[y][x] >= FEAT_SECRET)
	{
		/* Tunnel */
		if ((p_ptr->state.skills[SKILL_DIGGING] > 30 + randint0(1200)) && twall(y, x))
		{
			msg("You have finished the tunnel.");
		}

		/* Keep trying */
		else
		{
			/* We may continue tunelling */
			msg("You tunnel into the granite wall.");
			more = TRUE;

			/* Occasional Search XXX XXX */
			if (randint0(100) < 25) search(FALSE);
		}
	}

	/* Doors */
	else
	{
		/* Tunnel */
		if ((p_ptr->state.skills[SKILL_DIGGING] > 30 + randint0(1200)) && twall(y, x))
		{
			msg("You have finished the tunnel.");
		}

		/* Keep trying */
		else
		{
			/* We may continue tunelling */
			msg("You tunnel into the door.");
			more = TRUE;
		}
	}

	/* Result */
	return (more);
}
示例#16
0
文件: search.c 项目: megabajt/poldek
static int search(struct cmdctx *cmdctx)
{
    struct poclidek_ctx   *cctx = NULL;
    tn_array               *pkgs = NULL;
    tn_array               *matched_pkgs = NULL;
    int                    i, err = 0, display_bar = 0, bar_v;
    int                    term_height;
    struct pattern         *pt;
    unsigned               flags;
    
    if ((pt = cmdctx->_data) == NULL) {
        logn(LOGERR, _("search: no pattern given"));
        err++;
        goto l_end;
    }
    cmdctx->_data = NULL;            /* we'll free pattern myself */

    cctx = cmdctx->cctx;
    
    flags = cmdctx->_flags;
    flags &= ~OPT_NO_SEARCHSW;
    if (flags == 0)
        cmdctx->_flags |= OPT_SEARCH_DEFAULT;
    
    init_pcre();
    if (!pattern_compile(pt, poldek_ts_get_arg_count(cmdctx->ts))) {
        err++;
        goto l_end;
    }

    poclidek_load_packages(cmdctx->cctx, POCLIDEK_LOAD_ALL);
    if (poldek_ts_get_arg_count(cmdctx->ts) == 0) {
        pkgs = poclidek_get_dent_packages(cctx, NULL);
        
    } else {
        pkgs = poclidek_resolve_packages(NULL, cctx, cmdctx->ts, 0);
    }
    
    if (pkgs == NULL)
        return 0;
    
    matched_pkgs = n_array_new(32, NULL, NULL);

    if (n_array_size(pkgs) > 5 && (cmdctx->_flags & OPT_SEARCH_HDD)) {
        display_bar = 1;
        msg(0, _("Searching packages..."));
    }
    bar_v = 0;
    
    for (i=0; i < n_array_size(pkgs); i++) {
        struct pkg *pkg = n_array_nth(pkgs, i);
        
        if (pkg_match(pkg, pt, cmdctx->_flags)) 
            n_array_push(matched_pkgs, pkg);
        
        if (display_bar) {
            int v, j;
            
            v = i * 40 / n_array_size(pkgs);
            for (j = bar_v; j < v; j++)
                msg(0, "_.");
            bar_v = v;
        }
        
        if (sigint_reached()) {
            msgn(0, _("_interrupted."));
            goto l_end;
        }
    }
    
    if (display_bar) 
        msgn(0, _("_done."));

    term_height = poldek_term_get_height();
    if (n_array_size(matched_pkgs) == 0) 
        cmdctx_printf_c(cmdctx, PRCOLOR_YELLOW, "!No package matches '%s'\n",
                        pt->regexp);
    
    else if (n_array_size(matched_pkgs) < term_height)
        cmdctx_printf_c(cmdctx, PRCOLOR_YELLOW, "!%d package(s) found:\n",
                        n_array_size(matched_pkgs));
    
        
    for (i=0; i<n_array_size(matched_pkgs); i++) {
        struct pkg *pkg;

        pkg = n_array_nth(matched_pkgs, i);
        cmdctx_addtoresult(cmdctx, pkg);
        cmdctx_printf(cmdctx, "%s\n", pkg_id(pkg));
    }

    if (n_array_size(matched_pkgs) >= term_height)
        cmdctx_printf_c(cmdctx, PRCOLOR_YELLOW, "!%d package(s) found.\n",
                        n_array_size(matched_pkgs));
        
l_end:

    if (pkgs)
        n_array_free(pkgs);
    
    if (matched_pkgs)
        n_array_free(matched_pkgs);
    
    if (cmdctx->_data)
        cmdctx->_data = NULL;
    
    if (pt)
        pattern_free(pt);
    return 1;
}
BOOL test_pdcp_data_req(void)
{
  unsigned char* pdcp_test_pdu_buffer = NULL;
  unsigned char pdcp_test_pdu_buffer_size = DUMMY_BUFFER_SIZE + PDCP_USER_PLANE_DATA_PDU_LONG_SN_HEADER_SIZE;
  unsigned int index = 0;

  /*
   * Create an unsigned char buffer out of mem_block_t
   */
  pdcp_test_pdu_buffer = (unsigned char*) calloc(1, pdcp_test_pdu_buffer_size);

  if (pdcp_test_pdu_buffer == NULL) {
    msg("Cannot allocate a buffer for test!\n");
    return FALSE;
  }

  /*
   * Ask PDCP to handle a number of data requests
   */
  for (index = 0; index < NUMBER_OF_TEST_PACKETS; ++index) {
    msg("\n\nAsking PDCP to send %d/%d SDU...\n", index+1, NUMBER_OF_TEST_PACKETS);

    /*
     * Reset test pdu buffer for every run
     */
    memset(pdcp_test_pdu_buffer, 0x00, pdcp_test_pdu_buffer_size);

    /*
     * Ask PDCP to create a PDU with given buffer and enqueue it to `test_pdu_tx_list`
     */
    if (pdcp_data_req(0, 0, 10, DUMMY_BUFFER, &pdcp_array[0], &test_pdu_tx_list) == TRUE) {
      msg("[TEST] Starting to dissect PDU created by PDCP...\n");

      /*
       * XXX mem_block_t doesn't hold buffer size, how do we keep the size
       * information if we pass mem_block_ts via a linked list?
       */
#if 0

      if (pdcp_test_pdu_buffer_size == 0 || pdcp_test_pdu_buffer == NULL) {
        msg("[TEST] PDU created by pdcp_data_req() is invalid!\n");
        return FALSE;
      }

#endif

      /*
       * Serialize incoming mem_block_t into an unsigned character array
       * and add removed PDU to RX list in order to use it in the next test
       * (test_pdcp_data_ind())
       */
      mem_block_t* pdcp_test_pdu = list_remove_head(&test_pdu_tx_list);
      memcpy(pdcp_test_pdu_buffer, pdcp_test_pdu->data, pdcp_test_pdu_buffer_size);
      list_add_tail_eurecom(pdcp_test_pdu, &test_pdu_rx_list);

      /*
       * Verify that this is a data packet by checking
       * if the first bit is 0x00 (PDCP_DATA_PDU)
       */
      if (pdcp_test_pdu_buffer[0] & 0x80) {
        msg("[TEST] First bit is not 0, which means this is not a Data PDU!\n");
        return FALSE;
      } else {
        msg("[TEST] First bit is 0 so this is a Data PDU, OK\n");
      }

      /*
       * Verify that all three reserved bits are 0
       */
      if ((pdcp_test_pdu_buffer[0] & 0x70) != 0) {
        msg("[TEST] Reserved bits are not 0!\n");
        return FALSE;
      } else {
        msg("[TEST] Reserved bits are all 0, OK\n");
      }

      /*
       * Parse and verify sequence number
       */
      u16 sequence_number = pdcp_get_sequence_number_of_pdu_with_long_sn(pdcp_test_pdu_buffer);
      msg("[TEST] Parsed sequence number is %04d\n", sequence_number);

      if (sequence_number != index % WINDOW_SIZE) {
        msg("[TEST] Sequence numbers are out-of-order!\n");
        return FALSE;
      } else {
        msg("[TEST] Sequence number is correct\n");
      }

    } else {
      msg("[TEST] pdcp_data_req() returned FALSE!\n");
      return FALSE;
    }
  }

  return TRUE;
}
示例#18
0
static void
create(const char *filename, int compress, const char **argv)
{
	struct archive *a;
	struct archive_entry *entry;
	ssize_t len;
	int fd;

	a = archive_write_new();
	switch (compress) {
#ifndef NO_BZIP2_CREATE
	case 'j': case 'y':
		archive_write_add_filter_bzip2(a);
		break;
#endif
#ifndef NO_COMPRESS_CREATE
	case 'Z':
		archive_write_add_filter_compress(a);
		break;
#endif
#ifndef NO_GZIP_CREATE
	case 'z':
		archive_write_add_filter_gzip(a);
		break;
#endif
	default:
		archive_write_add_filter_none(a);
		break;
	}
	archive_write_set_format_ustar(a);
	if (filename != NULL && strcmp(filename, "-") == 0)
		filename = NULL;
	archive_write_open_filename(a, filename);

	while (*argv != NULL) {
		struct archive *disk = archive_read_disk_new();
#ifndef NO_LOOKUP
		archive_read_disk_set_standard_lookup(disk);
#endif
		int r;

		r = archive_read_disk_open(disk, *argv);
		if (r != ARCHIVE_OK) {
			errmsg(archive_error_string(disk));
			errmsg("\n");
			exit(1);
		}

		for (;;) {
			int needcr = 0;

			entry = archive_entry_new();
			r = archive_read_next_header2(disk, entry);
			if (r == ARCHIVE_EOF)
				break;
			if (r != ARCHIVE_OK) {
				errmsg(archive_error_string(disk));
				errmsg("\n");
				exit(1);
			}
			archive_read_disk_descend(disk);
			if (verbose) {
				msg("a ");
				msg(archive_entry_pathname(entry));
				needcr = 1;
			}
			r = archive_write_header(a, entry);
			if (r < ARCHIVE_OK) {
				errmsg(": ");
				errmsg(archive_error_string(a));
				needcr = 1;
			}
			if (r == ARCHIVE_FATAL)
				exit(1);
			if (r > ARCHIVE_FAILED) {
#if 0
				/* Ideally, we would be able to use
				 * the same code to copy a body from
				 * an archive_read_disk to an
				 * archive_write that we use for
				 * copying data from an archive_read
				 * to an archive_write_disk.
				 * Unfortunately, this doesn't quite
				 * work yet. */
				copy_data(disk, a);
#else
				/* For now, we use a simpler loop to copy data
				 * into the target archive. */
				fd = open(archive_entry_sourcepath(entry), O_RDONLY);
				len = read(fd, buff, sizeof(buff));
				while (len > 0) {
					archive_write_data(a, buff, len);
					len = read(fd, buff, sizeof(buff));
				}
				close(fd);
#endif
			}
			archive_entry_free(entry);
			if (needcr)
				msg("\n");
		}
		archive_read_close(disk);
		archive_read_free(disk);
		argv++;
	}
	archive_write_close(a);
	archive_write_free(a);
}
int main(int argc, char **argv)
{
  unsigned char index = 0;
  unsigned char test_result = 0;

  /*
   * Initialize memory allocator, list_t for test PDUs, and log generator
   */
  pool_buffer_init();
  list_init(&test_pdu_tx_list, NULL);
  list_init(&test_pdu_rx_list, NULL);
  logInit();

  if (init_pdcp_entity(&pdcp_array[0]) == TRUE && init_pdcp_entity(&pdcp_array[1]) == TRUE)
    msg("[TEST] PDCP entity initialization OK\n");
  else {
    msg("[TEST] Cannot initialize PDCP entities!\n");
    return 1;
  }

  /* Initialize PDCP state variables */
  for (index = 0; index < 2; ++index) {
    if (pdcp_init_seq_numbers(&pdcp_array[index]) == FALSE) {
      msg("[TEST] Cannot initialize sequence numbers of PDCP entity %d!\n", index);
      exit(1);
    } else {
      msg("[TEST] Sequence number state of PDCP entity %d is initialized\n", index);
    }
  }

#if TEST_RX_AND_TX_WINDOW

  /* Test TX window */
  if (test_tx_window() == FALSE)
    test_result = 1;

  /* Test RX window */
  if (test_rx_window() == FALSE)
    test_result = 1;

#endif

#if TEST_PDCP_DATA_REQUEST_AND_INDICATION

  /* Test pdcp_data_req() method in pdcp.c */
  if (test_pdcp_data_req() == FALSE)
    test_result = 1;

  /* Test pdcp_data_ind() method in pdcp.c */
  if (test_pdcp_data_ind() == FALSE)
    test_result = 1;

#endif

  if (test_result) {
    msg("\n\nOne or more tests failed!\n");
  } else {
    msg("\n\nAll tests are successfull!\n");
  }

  return test_result;
}
示例#20
0
static void
extract(const char *filename, int do_extract, int flags)
{
	struct archive *a;
	struct archive *ext;
	struct archive_entry *entry;
	int r;

	a = archive_read_new();
	ext = archive_write_disk_new();
	archive_write_disk_set_options(ext, flags);
#ifndef NO_BZIP2_EXTRACT
	archive_read_support_filter_bzip2(a);
#endif
#ifndef NO_GZIP_EXTRACT
	archive_read_support_filter_gzip(a);
#endif
#ifndef NO_COMPRESS_EXTRACT
	archive_read_support_filter_compress(a);
#endif
#ifndef NO_TAR_EXTRACT
	archive_read_support_format_tar(a);
#endif
#ifndef NO_CPIO_EXTRACT
	archive_read_support_format_cpio(a);
#endif
#ifndef NO_LOOKUP
	archive_write_disk_set_standard_lookup(ext);
#endif
	if (filename != NULL && strcmp(filename, "-") == 0)
		filename = NULL;
	if ((r = archive_read_open_filename(a, filename, 10240))) {
		errmsg(archive_error_string(a));
		errmsg("\n");
		exit(r);
	}
	for (;;) {
		int needcr = 0;
		r = archive_read_next_header(a, &entry);
		if (r == ARCHIVE_EOF)
			break;
		if (r != ARCHIVE_OK) {
			errmsg(archive_error_string(a));
			errmsg("\n");
			exit(1);
		}
		if (verbose && do_extract)
			msg("x ");
		if (verbose || !do_extract) {
			msg(archive_entry_pathname(entry));
			msg(" ");
			needcr = 1;
		}
		if (do_extract) {
			r = archive_write_header(ext, entry);
			if (r != ARCHIVE_OK) {
				errmsg(archive_error_string(a));
				needcr = 1;
			}
			else {
				r = copy_data(a, ext);
				if (r != ARCHIVE_OK)
					needcr = 1;
			}
		}
		if (needcr)
			msg("\n");
	}
	archive_read_close(a);
	archive_read_free(a);
	exit(0);
}
示例#21
0
文件: main.c 项目: ASPLes/turbulence
int  tbc_mod_gen_compile ()
{
	axlDtd   * dtd;
	axlDoc   * doc;
	axlError * error;
	axlNode  * node;
	axlNode  * moddef;
	char     * mod_name;
	char     * tolower;
	char     * toupper;
	char     * description;

	/* parse DTD document */
	dtd = axl_dtd_parse (TBC_MOD_GEN_DTD, -1, &error);
	if (dtd == NULL) {
		/* report error and dealloc resources */
		error ("Failed to parse DTD, error found: %s", axl_error_get (error));
		axl_error_free (error);

		return axl_false;
	} /* end if */
	
	/* nice, now parse the xml file */
	doc = axl_doc_parse_from_file (exarg_get_string ("compile"), &error);
	if (doc == NULL) {
		/* report error and dealloc resources */
		error ("unable to parse file: %s, error found: %s", 
		       exarg_get_string ("compile"),
		       axl_error_get (error));
		axl_error_free (error);
		axl_dtd_free (dtd);
	} /* end if */

	/* nice, now validate content */
	if (! axl_dtd_validate (doc, dtd, &error)) {
		/* report error and dealloc */
		error ("failed to validate module description provided: %s, error found: %s",
		       exarg_get_string ("compile"),
		       axl_error_get (error));
		axl_error_free (error);
		axl_doc_free (doc);
		axl_dtd_free (dtd);
		return axl_false;
	} /* end if */

	/* ok, now produce source code  */
	axl_dtd_free (dtd);

	/* open file */
	moddef   = axl_doc_get_root (doc);
	node     = axl_doc_get (doc, "/mod-def/name");
	mod_name = (char *) axl_node_get_content (node, NULL);
	mod_name = support_clean_name (mod_name);
	tolower  = support_to_lower (mod_name);
	toupper  = support_to_upper (mod_name);

	/* out dir */
	support_open_file (ctx, "%s%s.c", get_out_dir (), mod_name);

	/* place copyright if found */
	node     = axl_doc_get (doc, "/mod-def/copyright");
	if (node != NULL) {
		/* place the copyright */
	}  /* end if */
	
	write ("/* %s implementation */\n", mod_name);
	write ("#include <turbulence.h>\n\n");

	write ("/* use this declarations to avoid c++ compilers to mangle exported\n");
	write (" * names. */\n");
	write ("BEGIN_C_DECLS\n\n");

	write ("/* global turbulence context reference */\n");
	write ("TurbulenceCtx * ctx = NULL;\n\n");

	/* place here additional content */
	node    = axl_doc_get (doc, "/mod-def/source-code/additional-content");
	if (node != NULL) {
		write ("%s\n", axl_node_get_content (node, NULL));
	} /* end if */

	/* init handler */
	write ("/* %s init handler */\n", mod_name);
	write ("static int  %s_init (TurbulenceCtx * _ctx) {\n", tolower);

	push_indent ();
	write ("/* configure the module */\n");
	write ("TBC_MOD_PREPARE (_ctx);\n\n");
	pop_indent ();

	node = axl_doc_get (doc, "/mod-def/source-code/init");
	if (axl_node_get_content (node, NULL)) {
		/* write the content defined */
		write ("%s\n", axl_node_get_content (node, NULL));
	}
	write ("} /* end %s_init */\n\n", tolower);

	/* close handler */
	write ("/* %s close handler */\n", mod_name);
	write ("static void %s_close (TurbulenceCtx * _ctx) {\n", tolower);
	node = axl_doc_get (doc, "/mod-def/source-code/close");
	if (axl_node_get_content (node, NULL)) {
		/* write the content defined */
		write ("%s\n", axl_node_get_content (node, NULL));
	}
	write ("} /* end %s_close */\n\n", tolower);

	/* reconf handler */
	write ("/* %s reconf handler */\n", mod_name);
	write ("static void %s_reconf (TurbulenceCtx * _ctx) {\n", tolower);
	node = axl_doc_get (doc, "/mod-def/source-code/reconf");
	if (axl_node_get_content (node, NULL)) {
		/* write the content defined */
		write ("%s\n", axl_node_get_content (node, NULL));
	}
	write ("} /* end %s_reconf */\n\n", tolower);

	/* unload handler */
	write ("/* %s unload handler */\n", mod_name);
	write ("static void %s_unload (TurbulenceCtx * _ctx) {\n", tolower);
	node = axl_doc_get (doc, "/mod-def/source-code/unload");
	if (axl_node_get_content (node, NULL)) {
		/* write the content defined */
		write ("%s\n", axl_node_get_content (node, NULL));
	}
	write ("} /* end %s_unload */\n\n", tolower);

	/* ppath_selected handler */
	write ("/* %s ppath-selected handler */\n", mod_name);
	write ("static axl_bool %s_ppath_selected (TurbulenceCtx * _ctx, TurbulencePPathDef * ppath_selected, VortexConnection * conn) {\n", tolower);
	node = axl_doc_get (doc, "/mod-def/source-code/ppath-selected");
	if (axl_node_get_content (node, NULL)) {
		/* write the content defined */
		write ("%s\n", axl_node_get_content (node, NULL));
	}
	write ("} /* end %s_ppath_selected */\n\n", tolower);

	/* write handler description */
	write ("/* Entry point definition for all handlers included in this module */\n");
	write ("TurbulenceModDef module_def = {\n");

	push_indent ();

	write ("\"%s\",\n", mod_name);
	node        = axl_doc_get (doc, "/mod-def/description");
	description = (char *) axl_node_get_content (node, NULL);
	write ("\"%s\",\n", description ? description : "");
	write ("%s_init,\n", tolower);
	write ("%s_close,\n", tolower);
	write ("%s_reconf,\n", tolower);
	write ("%s_unload,\n", tolower);
	write ("%s_ppath_selected\n", tolower);
	pop_indent ();

	write ("};\n\n");

	write ("END_C_DECLS\n\n");
	
	/* close content */
	support_close_file (ctx);

	/* create the makefile required */
	support_open_file (ctx, "%sMakefile.am", get_out_dir ());
	
	write ("# Module definition\n");
	write ("EXTRA_DIST = %s\n\n", exarg_get_string ("compile"));
	
	       
	write ("INCLUDES = -Wall -g -ansi $(TURBULENCE_CFLAGS) -I../../src -DCOMPILATION_DATE=`date +%%s` \\\n");
	push_indent ();
	
	write ("-DVERSION=\\\"$(VERSION)\\\" \\\n");
	write ("$(AXL_CFLAGS) $(VORTEX_CFLAGS) $(EXARG_CFLAGS)\n\n");
	pop_indent ();
	
	write ("# configure module binary\n");
	write ("lib_LTLIBRARIES      = %s.la\n", mod_name);
	write ("%s_la_SOURCES  = %s.c %s\n", mod_name, mod_name,
	       HAS_ATTR (moddef, "sources") ? ATTR_VALUE (moddef, "sources") : "");
	write ("%s_la_LDFLAGS  = -module -ldl\n\n", mod_name);
	
	write ("# reconfigure module installation directory\n");
	write ("libdir = `turbulence-config --mod-dir`\n\n");
	
	write ("# configure site module installation\n");
	write ("modconfdir   = `turbulence-config --mod-xml`\n");
	write ("modconf_DATA = %s.xml %s.win32.xml\n\n", mod_name, mod_name);
	
	write ("%s.xml %s.win32.xml:\n", mod_name, mod_name);
	push_indent ();
	write ("echo \"<mod-turbulence location=\\\"`turbulence-config --mod-dir`/%s.so\\\"/>\" > %s.xml\n", mod_name, mod_name);
	write ("echo \"<mod-turbulence location=\\\"../modules/%s.dll\\\"/>\" > %s.win32.xml\n", mod_name, mod_name);
	pop_indent ();

	support_close_file (ctx);

	/* create autoconf if defined */
	if (exarg_is_defined ("enable-autoconf")) {

		msg ("found autoconf support files request..");
		
		/* create the autogen.sh */
		support_open_file (ctx, "%sautogen.sh", get_out_dir ());

		write ("# autogen.sh file created by tbc-mod-gen\n");
		write ("PACKAGE=\"%s: %s\"\n\n", mod_name, description);

		write ("(automake --version) < /dev/null > /dev/null 2>&1 || {\n");

		push_indent ();
		write ("echo;\n");
		write ("echo \"You must have automake installed to compile $PACKAGE\";\n");
		write ("echo;\n");
		write ("exit;\n");
		pop_indent ();

		write ("}\n\n");

		write ("(autoconf --version) < /dev/null > /dev/null 2>&1 || {\n");
		push_indent ();
		write ("echo;\n");
		write ("echo \"You must have autoconf installed to compile $PACKAGE\";\n");
		write ("echo;\n");
		write ("exit;\n");
		pop_indent ();
		write ("}\n\n");

		write ("echo \"Generating configuration files for $PACKAGE, please wait....\"\n");
		write ("echo;\n\n");

		write ("touch NEWS README AUTHORS ChangeLog\n");
		write ("libtoolize --force;\n");
		write ("aclocal $ACLOCAL_FLAGS;\n");
		write ("autoheader;\n");
		write ("automake --add-missing;\n");
		write ("autoconf;\n\n");

		write ("./configure $@ --enable-maintainer-mode --enable-compile-warnings\n");

		support_close_file (ctx);

		support_make_executable (ctx, "%sautogen.sh", get_out_dir ());

		/* now create the configure.ac file */

		support_open_file (ctx, "%sconfigure.ac", get_out_dir ());

		write ("dnl configure.ac template file created by tbc-mod-gen\n");
		write ("AC_INIT(%s.c)\n\n", mod_name);

		write ("dnl declare a global version value\n");
		write ("%s_VERSION=\"0.0.1\"\n", toupper);
		write ("AC_SUBST(%s_VERSION)\n\n", toupper);

		write ("AC_CONFIG_AUX_DIR(.)\n");
		write ("AM_INIT_AUTOMAKE(%s, $%s_VERSION)\n\n", mod_name, toupper);

		write ("AC_CONFIG_HEADER(config.h)\n");
		write ("AM_MAINTAINER_MODE\n");
		write ("AC_PROG_CC\n");
		write ("AC_ISC_POSIX\n");
		write ("AC_HEADER_STDC\n");
		write ("AM_PROG_LIBTOOL\n\n");

		write ("dnl external dependencies\n");
		write ("PKG_CHECK_MODULES(AXL, axl >= %s)\n\n", AXL_VERSION);

		write ("dnl general libries subsitution\n");
		write ("AC_SUBST(AXL_CFLAGS)\n");
		write ("AC_SUBST(AXL_LIBS)\n\n");

		write ("dnl external dependencies\n");
		write ("PKG_CHECK_MODULES(VORTEX, vortex >= %s) \n\n", VORTEX_VERSION);

		write ("dnl general libries subsitution\n");
		write ("AC_SUBST(VORTEX_CFLAGS)\n");
		write ("AC_SUBST(VORTEX_LIBS)\n\n");

		write ("dnl external dependencies\n");
		write ("PKG_CHECK_MODULES(EXARG, exarg)\n\n");

		write ("dnl general libries subsitution\n");
		write ("AC_SUBST(EXARG_CFLAGS)\n");
		write ("AC_SUBST(EXARG_LIBS)\n\n");
		
		write ("dnl external dependencies\n");
		write ("PKG_CHECK_MODULES(TURBULENCE, turbulence >= %s)\n\n", VERSION);

		write ("dnl general libries subsitution\n");
		write ("AC_SUBST(TURBULENCE_CFLAGS)\n");
		write ("AC_SUBST(TURBULENCE_LIBS)\n\n");

		write ("AC_OUTPUT([\n");
		write ("Makefile\n");
		write ("])\n\n");

		write ("echo \"------------------------------------------\"\n");
		write ("echo \"--       mod_template Settings          --\"\n");
		write ("echo \"------------------------------------------\"\n");
		write ("echo \"------------------------------------------\"\n");
		write ("echo \"--            Let it BEEP!              --\"\n");
		write ("echo \"--                                      --\"\n");
		write ("echo \"--     NOW TYPE: make; make install     --\"\n");
		write ("echo \"------------------------------------------\"\n");

		support_close_file (ctx);
		
	} /* end if */

	/* dealloc */
	axl_free (tolower);
	axl_free (toupper);
	axl_doc_free (doc);

	/* create the script file */
	support_open_file (ctx, "%sgen-code", get_out_dir ());

	write ("#!/bin/sh\n\n");

	/* write the mod gen */
	write ("tbc-mod-gen --compile %s --out-dir %s\n", exarg_get_string ("compile"), exarg_get_string ("out-dir"));
	
	support_close_file (ctx);

	support_make_executable (ctx, "%sgen-code", get_out_dir ());

	msg ("%s created!", mod_name);
	axl_free (mod_name);

	return axl_true;
}
示例#22
0
文件: cmd2.c 项目: CJNyfalt/angband
/*
 * Chests have traps too.
 *
 * Exploding chest destroys contents (and traps).
 * Note that the chest itself is never destroyed.
 */
static void chest_trap(int y, int x, s16b o_idx)
{
	int i, trap;

	object_type *o_ptr = object_byid(o_idx);


	/* Ignore disarmed chests */
	if (o_ptr->pval[DEFAULT_PVAL] <= 0) return;

	/* Obtain the traps */
	trap = chest_traps[o_ptr->pval[DEFAULT_PVAL]];

	/* Lose strength */
	if (trap & (CHEST_LOSE_STR))
	{
		msg("A small needle has pricked you!");
		take_hit(p_ptr, damroll(1, 4), "a poison needle");
		(void)do_dec_stat(A_STR, FALSE);
	}

	/* Lose constitution */
	if (trap & (CHEST_LOSE_CON))
	{
		msg("A small needle has pricked you!");
		take_hit(p_ptr, damroll(1, 4), "a poison needle");
		(void)do_dec_stat(A_CON, FALSE);
	}

	/* Poison */
	if (trap & (CHEST_POISON))
	{
		msg("A puff of green gas surrounds you!");
		(void)player_inc_timed(p_ptr, TMD_POISONED, 10 + randint1(20), TRUE, TRUE);
	}

	/* Paralyze */
	if (trap & (CHEST_PARALYZE))
	{
		msg("A puff of yellow gas surrounds you!");
		(void)player_inc_timed(p_ptr, TMD_PARALYZED, 10 + randint1(20), TRUE, TRUE);
	}

	/* Summon monsters */
	if (trap & (CHEST_SUMMON))
	{
		int num = 2 + randint1(3);
		msg("You are enveloped in a cloud of smoke!");
		sound(MSG_SUM_MONSTER);
		for (i = 0; i < num; i++)
		{
			(void)summon_specific(y, x, p_ptr->depth, 0, 1);
		}
	}

	/* Explode */
	if (trap & (CHEST_EXPLODE))
	{
		msg("There is a sudden explosion!");
		msg("Everything inside the chest is destroyed!");
		o_ptr->pval[DEFAULT_PVAL] = 0;
		take_hit(p_ptr, damroll(5, 8), "an exploding chest");
	}
}
示例#23
0
文件: main.c 项目: ASPLes/turbulence
int  tbc_mod_gen_template_create ()
{
	axlDoc     * doc;
	axlNode    * node;
	axlNode    * nodeAux;
	
	msg ("producing a template definition at the location provided");
	
	/* get out dir */
	doc     = axl_doc_create (NULL, NULL, axl_true);
	
	node    = axl_node_create ("mod-def");
	axl_doc_set_root (doc, node);

	nodeAux = axl_node_create ("name");
	axl_node_set_child (node, nodeAux);
	axl_node_set_content (nodeAux, "mod-template", -1);
	
	nodeAux = axl_node_create ("description");
	axl_node_set_child (node, nodeAux);
	axl_node_set_content (nodeAux, "Place here a generic module description", -1);
	
	nodeAux = axl_node_create ("source-code");
	axl_node_set_child (node, nodeAux);
	
	/* update parent */
	node    = nodeAux;

	/* init node */
	axl_node_set_comment (node, "init method, called once the module is loaded", -1);
	nodeAux = axl_node_create ("init");
	axl_node_set_child (node, nodeAux);
	axl_node_set_cdata_content (nodeAux, "/* Place here your mod init code. This will be called once turbulence decides to include the module. */\nreturn axl_true;", -1);
	
	/* close node */
	axl_node_set_comment (node, "close method, called once the module is going to be stoped", -1);
	nodeAux = axl_node_create ("close");
	axl_node_set_child (node, nodeAux);
	axl_node_set_cdata_content (nodeAux, "/* Place here the code required to stop and dealloc resources used by your module */", -1);

	/* reconf node */
	axl_node_set_comment (node, "reconf method, called once it is received a 'reconfiguration signal'", -1);
	nodeAux = axl_node_create ("reconf");
	axl_node_set_child (node, nodeAux);
	axl_node_set_cdata_content (nodeAux, "/* Place here all your optional reconf code if the HUP signal is received */", -1);

	/* unload node */
	axl_node_set_comment (node, "unload method, called once the module is required to be unloaded from memory due to child process creation (or similar)", -1);
	nodeAux = axl_node_create ("unload");
	axl_node_set_child (node, nodeAux);
	axl_node_set_cdata_content (nodeAux, "/* Place here the code required to dealloc resources used by your module because turbulence signaled the child process must not have access */", -1);

	/* ppath-selected node */
	axl_node_set_comment (node, "ppath_selected method, called once a profile path has been selected for a connection.", -1);
	nodeAux = axl_node_create ("ppath-selected");
	axl_node_set_child (node, nodeAux);
	axl_node_set_cdata_content (nodeAux, "/* Place here the code to implement all provisioning that was deferred because non enough data was available at init method (connection and profile path selected) */\nreturn axl_true;", -1);

	/* dump the xml document */
	support_dump_file (ctx, doc, 3, "%stemplate.xml", get_out_dir ());

	/* free document */
	axl_doc_free (doc);

	msg ("template created: OK");
	
	return axl_true;
}
示例#24
0
文件: cmd2.c 项目: CJNyfalt/angband
/*
 * Attempt to disarm the chest at the given location
 *
 * Assume there is no monster blocking the destination
 *
 * Returns TRUE if repeated commands may continue
 */
static bool do_cmd_disarm_chest(int y, int x, s16b o_idx)
{
	int i, j;

	bool more = FALSE;

	object_type *o_ptr = object_byid(o_idx);


	/* Get the "disarm" factor */
	i = p_ptr->state.skills[SKILL_DISARM];

	/* Penalize some conditions */
	if (p_ptr->timed[TMD_BLIND] || no_light()) i = i / 10;
	if (p_ptr->timed[TMD_CONFUSED] || p_ptr->timed[TMD_IMAGE]) i = i / 10;

	/* Extract the difficulty */
	j = i - o_ptr->pval[DEFAULT_PVAL];

	/* Always have a small chance of success */
	if (j < 2) j = 2;

	/* Must find the trap first. */
	if (!object_is_known(o_ptr))
	{
		msg("I don't see any traps.");
	}

	/* Already disarmed/unlocked */
	else if (o_ptr->pval[DEFAULT_PVAL] <= 0)
	{
		msg("The chest is not trapped.");
	}

	/* No traps to find. */
	else if (!chest_traps[o_ptr->pval[DEFAULT_PVAL]])
	{
		msg("The chest is not trapped.");
	}

	/* Success (get a lot of experience) */
	else if (randint0(100) < j)
	{
		msgt(MSG_DISARM, "You have disarmed the chest.");
		player_exp_gain(p_ptr, o_ptr->pval[DEFAULT_PVAL]);
		o_ptr->pval[DEFAULT_PVAL] = (0 - o_ptr->pval[DEFAULT_PVAL]);
	}

	/* Failure -- Keep trying */
	else if ((i > 5) && (randint1(i) > 5))
	{
		/* We may keep trying */
		more = TRUE;
		flush();
		msg("You failed to disarm the chest.");
	}

	/* Failure -- Set off the trap */
	else
	{
		msg("You set off a trap!");
		chest_trap(y, x, o_idx);
	}

	/* Result */
	return (more);
}
示例#25
0
文件: cmd2.c 项目: Hrrunstar/angband
/*
 * Perform the basic "disarm" command
 *
 * Assume there is no monster blocking the destination
 *
 * Returns TRUE if repeated commands may continue
 */
static bool do_cmd_disarm_aux(int y, int x)
{
	int i, j, power;

	const char *name;

	bool more = FALSE;


	/* Verify legality */
	if (!do_cmd_disarm_test(y, x)) return (FALSE);


	/* Get the trap name */
	name = f_info[cave->feat[y][x]].name;

	/* Get the "disarm" factor */
	i = p_ptr->state.skills[SKILL_DISARM];

	/* Penalize some conditions */
	if (p_ptr->timed[TMD_BLIND] || no_light()) i = i / 10;
	if (p_ptr->timed[TMD_CONFUSED] || p_ptr->timed[TMD_IMAGE]) i = i / 10;

	/* XXX XXX XXX Variable power? */

	/* Extract trap "power" */
	power = 5;

	/* Extract the difficulty */
	j = i - power;

	/* Always have a small chance of success */
	if (j < 2) j = 2;

	/* Success */
	if (randint0(100) < j)
	{
		/* Message */
		msgt(MSG_DISARM, "You have disarmed the %s.", name);

		/* Reward */
		player_exp_gain(p_ptr, power);

		/* Forget the trap */
		cave->info[y][x] &= ~(CAVE_MARK);

		/* Remove the trap */
		cave_set_feat(cave, y, x, FEAT_FLOOR);
	}

	/* Failure -- Keep trying */
	else if ((i > 5) && (randint1(i) > 5))
	{
		flush();

		/* Message */
		msg("You failed to disarm the %s.", name);

		/* We may keep trying */
		more = TRUE;
	}

	/* Failure -- Set off the trap */
	else
	{
		/* Message */
		msg("You set off the %s!", name);

		/* Hit the trap */
		hit_trap(y, x);
	}

	/* Result */
	return (more);
}
示例#26
0
文件: cmd2.c 项目: CJNyfalt/angband
/*
 * Perform the basic "open" command on doors
 *
 * Assume there is no monster blocking the destination
 *
 * Returns TRUE if repeated commands may continue
 */
static bool do_cmd_open_aux(int y, int x)
{
	int i, j;

	bool more = FALSE;


	/* Verify legality */
	if (!do_cmd_open_test(y, x)) return (FALSE);


	/* Jammed door */
	if (cave_isjammeddoor(cave, y, x))
	{
		msg("The door appears to be stuck.");
	}

	/* Locked door */
	else if (cave_islockeddoor(cave, y, x))
	{
		/* Disarm factor */
		i = p_ptr->state.skills[SKILL_DISARM];

		/* Penalize some conditions */
		if (p_ptr->timed[TMD_BLIND] || no_light()) i = i / 10;
		if (p_ptr->timed[TMD_CONFUSED] || p_ptr->timed[TMD_IMAGE]) i = i / 10;

		/* Extract the lock power */
		j = cave->feat[y][x] - FEAT_DOOR_HEAD;

		/* Extract the difficulty XXX XXX XXX */
		j = i - (j * 4);

		/* Always have a small chance of success */
		if (j < 2) j = 2;

		/* Success */
		if (randint0(100) < j)
		{
			/* Message */
			msgt(MSG_LOCKPICK, "You have picked the lock.");

			/* Open the door */
			cave_set_feat(cave, y, x, FEAT_OPEN);

			/* Update the visuals */
			p_ptr->update |= (PU_UPDATE_VIEW | PU_MONSTERS);

			/* Experience */
			/* Removed to avoid exploit by repeatedly locking and unlocking door */
			/* player_exp_gain(p_ptr, 1); */
		}

		/* Failure */
		else
		{
			flush();

			/* Message */
			msgt(MSG_LOCKPICK_FAIL, "You failed to pick the lock.");

			/* We may keep trying */
			more = TRUE;
		}
	}

	/* Closed door */
	else
	{
		/* Open the door */
		cave_set_feat(cave, y, x, FEAT_OPEN);

		/* Update the visuals */
		p_ptr->update |= (PU_UPDATE_VIEW | PU_MONSTERS);

		/* Sound */
		sound(MSG_OPENDOOR);
	}

	/* Result */
	return (more);
}
示例#27
0
文件: cmd2.c 项目: Hrrunstar/angband
/*
 * Perform the basic "bash" command
 *
 * Assume there is no monster blocking the destination
 *
 * Returns TRUE if repeated commands may continue
 */
static bool do_cmd_bash_aux(int y, int x)
{
	int bash, temp;

	bool more = FALSE;


	/* Verify legality */
	if (!do_cmd_bash_test(y, x)) return (FALSE);


	/* Message */
	msg("You smash into the door!");

	/* Hack -- Bash power based on strength */
	/* (Ranges from 3 to 20 to 100 to 200) */
	bash = adj_str_blow[p_ptr->state.stat_ind[A_STR]];

	/* Extract door power */
	temp = ((cave->feat[y][x] - FEAT_DOOR_HEAD) & 0x07);

	/* Compare bash power to door power XXX XXX XXX */
	temp = (bash - (temp * 10));

	/* Hack -- always have a chance */
	if (temp < 1) temp = 1;

	/* Hack -- attempt to bash down the door */
	if (randint0(100) < temp)
	{
		/* Break down the door */
		if (randint0(100) < 50)
		{
			cave_set_feat(cave, y, x, FEAT_BROKEN);
		}

		/* Open the door */
		else
		{
			cave_set_feat(cave, y, x, FEAT_OPEN);
		}

		/* Message */
		msgt(MSG_OPENDOOR, "The door crashes open!");

		/* Update the visuals */
		p_ptr->update |= (PU_UPDATE_VIEW | PU_MONSTERS);
	}

	/* Saving throw against stun */
	else if (randint0(100) < adj_dex_safe[p_ptr->state.stat_ind[A_DEX]] +
	         p_ptr->lev)
	{
		/* Message */
		msg("The door holds firm.");

		/* Allow repeated bashing */
		more = TRUE;
	}

	/* High dexterity yields coolness */
	else
	{
		/* Message */
		msg("You are off-balance.");

		/* Hack -- Lose balance ala paralysis */
		(void)inc_timed(TMD_PARALYZED, 2 + randint0(2), TRUE);
	}

	/* Result */
	return (more);
}
示例#28
0
文件: cmd2.c 项目: CJNyfalt/angband
/*
 * Open a closed/locked/jammed door or a closed/locked chest.
 *
 * Unlocking a locked door/chest is worth one experience point.
 */
void do_cmd_open(cmd_code code, cmd_arg args[])
{
	int y, x, dir;

	s16b o_idx;

	bool more = FALSE;

	dir = args[0].direction;

	/* Get location */
	y = p_ptr->py + ddy[dir];
	x = p_ptr->px + ddx[dir];

	/* Check for chests */
	o_idx = chest_check(y, x);


	/* Verify legality */
	if (!o_idx && !do_cmd_open_test(y, x))
	{
		/* Cancel repeat */
		disturb(p_ptr, 0, 0);
		return;
	}

	/* Take a turn */
	p_ptr->energy_use = 100;

	/* Apply confusion */
	if (player_confuse_dir(p_ptr, &dir, FALSE))
	{
		/* Get location */
		y = p_ptr->py + ddy[dir];
		x = p_ptr->px + ddx[dir];

		/* Check for chest */
		o_idx = chest_check(y, x);
	}


	/* Monster */
	if (cave->m_idx[y][x] > 0)
	{
		int m_idx = cave->m_idx[y][x];

		/* Mimics surprise the player */
		if (is_mimicking(m_idx)) {
			become_aware(m_idx);

			/* Mimic wakes up */
			mon_clear_timed(m_idx, MON_TMD_SLEEP, MON_TMD_FLG_NOMESSAGE);
		} else {
			/* Message */
			msg("There is a monster in the way!");

			/* Attack */
			py_attack(y, x);
		}
	}

	/* Chest */
	else if (o_idx)
	{
		/* Open the chest */
		more = do_cmd_open_chest(y, x, o_idx);
	}

	/* Door */
	else
	{
		/* Open the door */
		more = do_cmd_open_aux(y, x);
	}

	/* Cancel repeat unless we may continue */
	if (!more) disturb(p_ptr, 0, 0);
}
示例#29
0
文件: cmd2.c 项目: Hrrunstar/angband
/*
 * Jam a closed door with a spike
 *
 * This command may NOT be repeated
 */
void do_cmd_spike(cmd_code code, cmd_arg args[])
{
	int y, x, dir, item = 0;

	dir = args[0].direction;

	/* Get a spike */
	if (!get_spike(&item))
	{
		/* Message */
		msg("You have no spikes!");

		/* Done */
		return;
	}

	/* Get location */
	y = p_ptr->py + ddy[dir];
	x = p_ptr->px + ddx[dir];


	/* Verify legality */
	if (!do_cmd_spike_test(y, x)) return;


	/* Take a turn */
	p_ptr->energy_use = 100;

	/* Confuse direction */
	if (player_confuse_dir(p_ptr, &dir))
	{
		/* Get location */
		y = p_ptr->py + ddy[dir];
		x = p_ptr->px + ddx[dir];
	}


	/* Monster */
	if (cave->m_idx[y][x] > 0)
	{
		/* Message */
		msg("There is a monster in the way!");

		/* Attack */
		py_attack(y, x);
	}

	/* Go for it */
	else
	{
		/* Verify legality */
		if (!do_cmd_spike_test(y, x)) return;

		/* Successful jamming */
		msg("You jam the door with a spike.");

		/* Convert "locked" to "stuck" XXX XXX XXX */
		if (cave->feat[y][x] < FEAT_DOOR_HEAD + 0x08)
		{
			cave->feat[y][x] += 0x08;
		}

		/* Add one spike to the door */
		if (cave->feat[y][x] < FEAT_DOOR_TAIL)
		{
			cave->feat[y][x] += 0x01;
		}

		/* Use up, and describe, a single spike, from the bottom */
		inven_item_increase(item, -1);
		inven_item_describe(item);
		inven_item_optimize(item);
	}
}
示例#30
0
unconfuse()
{
    player.t_flags &= ~ISHUH;
    msg("You feel less confused now");
}