コード例 #1
0
ファイル: kugelblitz.cpp プロジェクト: CRS-ECHO51/supertux
void
Kugelblitz::kill_fall()
{
  explode();
}
コード例 #2
0
ファイル: user.c プロジェクト: Hobbitron/tmi2
/*
 * Setup standard user command hook system.  This system interfaces
 * with the cmd bin system, the environment's exits, and feeling entries.
 */
nomask static int cmd_hook(string cmd) {
    string file;
    string verb;
    int foo;
    mapping before, after;

    verb = query_verb();

    if (environment() && environment()->valid_exit(verb)) {
        verb = "go";
        cmd = query_verb();
    }

    file = (string)CMD_D->find_cmd(verb, explode(query("PATH"), ":"));

    if (file && file != "") {
#ifdef PROFILING
        before = rusage();
#endif
        foo = (int)call_other(file, "cmd_" + verb, cmd);

#ifdef PROFILING
        after = rusage();
              "/adm/daemons/profile"->log_cmd(verb,before,after);
#endif

        return foo;
    }

    if (environment() && environment()->query("quiet"))
        return 0;

#ifdef PROFILING
    before = rusage();
#endif

    foo = (int)EMOTE_D->parse(verb, cmd);

    if (foo) {
#ifdef PROFILING
        after = rusage();
        "/adm/daemons/profile"->log_cmd(verb,before,after);
#endif
        return foo;
    }

#ifdef PROFILING
    before = rusage();
#endif

#ifndef INTERMUD
    if (verb == "gwiz" || verb == "interwiz") {
        printf("Sorry, %s does not support intermud.\n",capitalize(mud_name()));
        return 1;
    }
#endif /* INTERMUD */

    foo = (int) CHANNELS_D -> parse_channel( verb, cmd );

#ifdef PROFILING
    if ( foo ) {
        after = rsuage();
        "/adm/daemons/profile" -> log_cmd( verb, before, after );
    }
#endif

    return foo;
}
コード例 #3
0
ファイル: Bomb.cpp プロジェクト: Maxs1789/solarus
/**
 * \brief This function is called when an explosion's sprite
 * detects a pixel-perfect collision with a sprite of this entity.
 * \param explosion the explosion
 * \param sprite_overlapping the sprite of the current entity that collides with the explosion
 */
void Bomb::notify_collision_with_explosion(Explosion& /* explosion */, Sprite& /* sprite_overlapping */) {

  if (!is_being_removed()) {
    explode();
  }
}
コード例 #4
0
void fixReplaces(string& req_hdrs, bool is_invite) {

  string replaces;
  string refer_to;
  AmUriParser refer_target;
  vector<string> hdrs;                      // headers from Refer-To URI
  vector<string>::iterator replaces_hdr_it; // Replaces header from Refer-To URI

  DBG("Replaces handler: fixing %s request\n", is_invite?"INVITE":"REFER");

  if (is_invite) {
    replaces = getHeader(req_hdrs, SIP_HDR_REPLACES, true);
    if (replaces.empty()) {
      DBG("Replaces handler: no Replaces in INVITE, ignoring\n");
      return;
    }
  } else {
    refer_to = getHeader(req_hdrs, SIP_HDR_REFER_TO, SIP_HDR_REFER_TO_COMPACT, true);
    if (refer_to.empty()) {
      DBG("Replaces handler: empty Refer-To header, ignoring\n");
      return;
    }

    size_t pos=0; size_t end=0;
    if (!refer_target.parse_contact(refer_to, pos, end)) {
      DBG("Replaces handler: unable to parse Refer-To name-addr, ignoring\n");
      return;
    }

    if (refer_target.uri_headers.empty()) {
      DBG("Replaces handler: no headers in Refer-To target, ignoring\n");
      return;
    }

    hdrs = explode(refer_target.uri_headers, ";");
    for (replaces_hdr_it=hdrs.begin(); replaces_hdr_it != hdrs.end(); replaces_hdr_it++) {

      string s = URL_decode(*replaces_hdr_it);
      const char* Replaces_str = "Replaces";
      if ((s.length() >= 8) &&
	  !strncmp(Replaces_str, s.c_str(), 8)) {
	size_t pos = 8;
	while (s.length()>pos && (s[pos] == ' ' || s[pos] == '\t')) pos++;
	if (s[pos] != '=')
	  continue;
	pos++;
	while (s.length()>pos && (s[pos] == ' ' || s[pos] == '\t')) pos++;
	replaces = s.substr(pos);
	break;
      }
    }
    
    if (replaces_hdr_it == hdrs.end()) {
      DBG("Replaces handler: no Replaces headers in Refer-To target, ignoring\n");
      return;
    }
  }

  DBG("Replaces found: '%s'\n", replaces.c_str());
  size_t ftag_begin; size_t ftag_len;
  size_t ttag_begin; size_t ttag_len;
  size_t cid_len=0;
 
  // todo: parse full replaces header and reconstruct including unknown params
  if (!findTag(replaces, "from-tag=", ftag_begin, ftag_len)) {
    WARN("Replaces missing 'from-tag', ignoring\n");
    return;
  }

  if (!findTag(replaces, "to-tag=", ttag_begin, ttag_len)) {
    WARN("Replaces missing 'to-tag', ignoring\n");
    return;
  }
  while (cid_len < replaces.size() && replaces[cid_len] != ';')
    cid_len++;

  string ftag = replaces.substr(ftag_begin, ftag_len);
  string ttag = replaces.substr(ttag_begin, ttag_len);
  string callid = replaces.substr(0, cid_len);
  bool early_only = replaces.find("early-only") != string::npos;

  DBG("Replaces handler: found callid='%s', ftag='%s', ttag='%s'\n",
      callid.c_str(), ftag.c_str(), ttag.c_str());

  SBCCallRegistryEntry other_dlg;
  if (SBCCallRegistry::lookupCall(ttag, other_dlg)) {
    replaces = other_dlg.callid+
      ";from-tag="+other_dlg.ltag+";to-tag="+other_dlg.rtag;
    if (early_only)
      replaces += ";early_only";
    DBG("Replaces handler: mapped Replaces to: '%s'\n", replaces.c_str());

    if (is_invite) {
      removeHeader(req_hdrs, SIP_HDR_REPLACES);
      req_hdrs+=SIP_HDR_COLSP(SIP_HDR_REPLACES)+replaces+CRLF;
    } else {
      string replaces_enc = SIP_HDR_REPLACES "="+URL_encode(replaces);
      string new_hdrs;
      for (vector<string>::iterator it = hdrs.begin(); it != hdrs.end(); it++) {
	if (it != hdrs.begin())
	  new_hdrs+=";";

	if (it != replaces_hdr_it) {
	  // different hdr, just add it
	  new_hdrs+=*it;
	} else {
	  //reconstructed replaces hdr
	  new_hdrs+=replaces_enc;
	}
      }
      refer_target.uri_headers=new_hdrs;
      removeHeader(req_hdrs, SIP_HDR_REFER_TO);
      removeHeader(req_hdrs, SIP_HDR_REFER_TO_COMPACT);
      req_hdrs+=SIP_HDR_COLSP(SIP_HDR_REFER_TO)+refer_target.nameaddr_str()+CRLF;
    }

  } else {
    DBG("Replaces handler: call with tag '%s' not found\n", ttag.c_str());
  }

 
}
コード例 #5
0
ファイル: test.c プロジェクト: drlaforge/NuclearWar
varargs string format_desc(string raw, int terminal_width, int leading_indent_width, int inner_indent_width, string *highlight, string highlight_color) {
    string result = "";

    string *paragraphs = rexplode(raw, "\n");
    string leading_indent = "";
    string inner_indent = "";


    if(undefinedp(terminal_width) || terminal_width < 10) {
        object tp = this_player();

        terminal_width = 75;
        if(!undefinedp(tp)) {
            int sw = tp->GetScreen()[0];

            if(!undefinedp(sw) && sw > 0) {
                terminal_width = sw;
            }
        }
    }

    if(!undefinedp(leading_indent_width) && leading_indent_width > 0) {
        leading_indent = sprintf("%-*.*s", leading_indent_width, leading_indent_width, " ");
    }
    if(!undefinedp(inner_indent_width) && inner_indent_width > 0) {
        inner_indent = sprintf("%-*.*s", inner_indent_width, inner_indent_width, " ");
    }

    for(int i = 0; i < sizeof(paragraphs); i++) {
        string p = paragraphs[i];

        result += (i != 0 ? "" : "");
        result += leading_indent + implode(explode(sprintf("%-=*s\n", terminal_width, p), "\n"), "\n" + inner_indent);
        result += "\n";
    }

    if(!undefinedp(highlight)) {
        if(undefinedp(highlight_color)) {
            highlight_color = "%^BOLD%^%^YELLOW%^";
        }

        foreach(string h in highlight) {
            string tmp = "";

            tmp = replace_string(result, h, highlight_color + h + "%^RESET%^", 1);
            if(tmp == result) {
                if(strsrch(h, " ") != -1) {
                    string *words = explode(h, " ");

                    for(int i = 0; i < sizeof(words); i++) {
                        string t = replace_string(h, " ", "\n", i+1, i+1);
                        tmp = replace_string(result, t, highlight_color + t + "%^RESET%^", 1);
                        if(tmp != result) {
                            break;
                        }
                    }
                }
            }
            result = tmp;
        }
    }
コード例 #6
0
// script config
server = "tracker.xrj.ch";
port = (int) "9090";
SOCKET_TIMEOUT = 300;

// SmojeID
sArName = explode(nb_config_get("network.hostname"));
smojeid = "";

for (i = 0; i < length(sArName); i++) {
    if (isdigit(sArName[i])) {
        smojeid = strcat(smojeid,sArName[i]);
    }
}

// Cinnect
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
    print("unable to open socket\n");
    close(sock);
    exit(1);
}

if (connect(sock, server, port) < 0){
	printf("Could not connect to %s (port %d)\n", server, port);
	close(sock);
	sleep(10);
	exit(2);
}
printf("Connected to %s (port %d)\n", server, port);
コード例 #7
0
ファイル: get_t2f2_val.c プロジェクト: TimLand/datacl
/* START FUNC DECL */
int 
get_t2f2_val(
	     char *t1,
	     char *lnk1,
	     char *t2,
	     char *lnk2,
	     char *t2f2, /* field in t2 */
	     char *t1f2 /* field in t1 */
	     )
/* STOP FUNC DECL */
{
  int status = 0;
  char *t2f2_X = NULL; size_t n_t2f2_X = 0;
  char *nn_t2f2_X = NULL; size_t nn_n_t2f2_X = 0;
  char *X = NULL; size_t nX = 0;
  char *nn_X = NULL; size_t nn_nX = 0;
  char *X1 = NULL; size_t nX1 = 0;
  char *X2 = NULL; size_t nX2 = 0;
  char *nn_X1 = NULL; size_t nn_nX1 = 0;
  char *nn_X2 = NULL; size_t nn_nX2 = 0;
  TBL_REC_TYPE t1_rec, t2_rec;
  FLD_REC_TYPE lnk1_rec, nn_lnk1_rec; int lnk1_id, nn_lnk1_id;
  FLD_REC_TYPE lnk2_rec, nn_lnk2_rec;int lnk2_id, nn_lnk2_id; 
  FLD_REC_TYPE t2f2_rec, nn_t2f2_rec; int t2f2_id, nn_t2f2_id;
  FLD_REC_TYPE t1f2_rec, nn_t1f2_rec; int t1f2_id, nn_t1f2_id;
  int t1_id, t2_id; 
  long long nR1, nR2;
#define BUFLEN 32
  char rslt_buf[BUFLEN];
  char **Y = NULL; int nY = 0;
  HT_I8_TYPE *ht = NULL;
  int sz_ht;    // size of hash table 
  int n_ht = 0;  // number of occupied entries in hash table 

  /*-------------------------------------------------------------*/
  if ( ( t1 == NULL ) || ( *t1 == '\0' ) ) { go_BYE(-1); }
  if ( ( t2 == NULL ) || ( *t2 == '\0' ) ) { go_BYE(-1); }
  if ( ( strcmp(t1, t2) == 0 ) && ( strcmp(t1f2, t2f2) == 0 ) ) { go_BYE(-1); }

  if ( ( lnk1 == NULL ) || ( *lnk1 == '\0' ) ) { go_BYE(-1); }
  if ( ( lnk2 == NULL ) || ( *lnk2 == '\0' ) ) { go_BYE(-1); }
  /*-------------------------------------------------------------*/

  status = is_tbl(t1, &t1_id, &t1_rec); cBYE(status);
  chk_range(t1_id, 0, g_n_tbl);
  nR1 = g_tbls[t1_id].nR;

  status = is_tbl(t2, &t2_id, &t2_rec); cBYE(status);
  chk_range(t2_id, 0, g_n_tbl);
  nR2 = g_tbls[t2_id].nR;
  /*-------------------------------------------------------------*/
  status = is_fld(NULL, t1_id, lnk1, &lnk1_id, &lnk1_rec, 
		  &nn_lnk1_id, &nn_lnk1_rec); 
  cBYE(status);
  chk_range(lnk1_id, 0, g_n_fld);
  if ( nn_lnk1_id >= 0 ) { 
    status = get_data(nn_lnk1_rec, &nn_X1, &nn_nX1, false); cBYE(status);
  }
  status = get_data(lnk1_rec, &X1, &nX1, false); cBYE(status);
  /*-------------------------------------------------------------*/
  status = is_fld(NULL, t2_id, lnk2, &lnk2_id, &lnk2_rec, 
		  &nn_lnk2_id, &nn_lnk2_rec); 
  cBYE(status);
  chk_range(lnk2_id, 0, g_n_fld);
  if ( nn_lnk2_id >= 0 ) { go_BYE(-1); } 
  status = get_data(lnk2_rec, &X2, &nX2, false); cBYE(status);
  if ( nn_lnk2_id >= 0 ) { 
    status = get_data(nn_lnk2_rec, &nn_X2, &nn_nX2, false); cBYE(status);
  }
  /*-------------------------------------------------------- */
  if ( lnk1_rec.fldtype != lnk2_rec.fldtype ) { go_BYE(-1); }
  /*-------------------------------------------------------- */
  status = is_fld(NULL, t2_id, t2f2, &t2f2_id, &t2f2_rec, 
		  &nn_t2f2_id, &nn_t2f2_rec); 
  cBYE(status);
  chk_range(t2f2_id, 0, g_n_fld);
  status = get_data(t2f2_rec, &t2f2_X, &n_t2f2_X, false); cBYE(status);
  if ( nn_t2f2_id >= 0 ) { 
    status = get_data(nn_t2f2_rec, &nn_t2f2_X, &nn_n_t2f2_X, false); 
    cBYE(status);
  }
  /*--------------------------------------------------------*/
  /* Check supported field types */
  if ( lnk1_rec.fldtype != I4 ) { go_BYE(-1); }
  if ( lnk2_rec.fldtype != I4 ) { go_BYE(-1); }
  if ( t2f2_rec.fldtype != I4 ) { go_BYE(-1); }
  /*-------------------------------------------------------- */
  /* Create space for output */
  int fldsz = 0; size_t filesz = 0;
  int ddir_id    = -1, fileno    = -1; 
  int nn_ddir_id = -1, nn_fileno = -1;

  status = get_fld_sz(I4, &fldsz); cBYE(status);
  filesz = fldsz * nR1; 
  status = mk_temp_file(filesz, &ddir_id, &fileno);
  status = q_mmap(ddir_id, fileno, &X, &nX, 1); cBYE(status);

  status = get_fld_sz(I1, &fldsz); cBYE(status);
  filesz = fldsz * nR1; 
  status = mk_temp_file(filesz, &nn_ddir_id, &nn_fileno);
  status = q_mmap(nn_ddir_id, nn_fileno, &nn_X, &nn_nX, 1); cBYE(status);

  /*-------------------------------------------------------- */
  bool is_fast = false;
  bool definitely_has_null_vals = false;
  long long nn_nR2 = 0;
  if ( nn_X2 != NULL ) { 
    for ( long long i = 0; i < nR2; i++ ) { 
      if ( nn_X2[i] == TRUE ) { 
	nn_nR2++;
      }
    }
  }
  else {
    nn_nR2 = nR2;
  }
  if ( nn_nR2 == 0 ) {
    definitely_has_null_vals = true;
    assign_const_I4((int  *)X,    nR1, 0);
    assign_const_I1((char *)nn_X, nR1, 0);
  }
  else {
    cilkfor ( long long i = 0; i < nR1; i++ ) {
      int *it2f2 = (int *)t2f2_X;
      int *I4_lnk1 = (int *)X1; int I4val1;
      int *I4_lnk2 = (int *)X2; int I4val2;
      int *out = (int *)X; int outval;
      char *out_nn = (char *)nn_X;
      char c_nn;
      I4val1 = I4_lnk1[i];
      /* If the link value is null, then the output value is null */
      if ( ( nn_X1 != NULL ) && ( nn_X1[i] == FALSE ) ) {
	out_nn[i] = FALSE;
	out[i]    = 0;
      }
      else {
	/* We are now looking for I4val1 in the link field of t2 */
	if ( is_fast == false ) { 
	  outval = 0;
	  c_nn = FALSE;
	  for ( long long j = 0; j < nR2; j++ ) {
	    if ( ( nn_X2 != NULL ) && ( nn_X2[j] == FALSE ) ) {
	      continue;
	    }
	    I4val2 = I4_lnk2[j];
	    if ( I4val1 == I4val2 ) {
	      if ( ( nn_t2f2_X == NULL ) || (nn_t2f2_X[j] == TRUE ) ) {
		c_nn = TRUE;
	      }
	      outval = it2f2[j];
	      break;
	    }
	  }
	  out_nn[i] = c_nn;
	  out[i]    = outval;
	}
	else {
	  WHEREAMI; status = -1; continue;
	}
      }
    }
    cBYE(status);
#ifdef CILK
    __cilkrts_end_cilk();
#endif
  }
  rs_munmap(X, nX);
  zero_fld_rec(&t1f2_rec); t1f2_rec.fldtype = I4;
  status = add_fld(t1_id, t1f2, ddir_id, fileno, &t1f2_id, &t1f2_rec);
  cBYE(status);
  if ( definitely_has_null_vals == true ) {
    /* No need to check */
    rs_munmap(nn_X, nn_nX);
    zero_fld_rec(&nn_t1f2_rec); nn_t1f2_rec.fldtype = I1;
    status = add_aux_fld(NULL, t1_id, NULL, t1f2_id, nn_ddir_id, 
	nn_fileno, nn, &nn_t1f2_id, &nn_t1f2_rec);
    cBYE(status);
  }
  else {
    status = vec_f_to_s(nn_X, I1, NULL, nR1, "sum", rslt_buf, BUFLEN);
    cBYE(status);
    status = explode(rslt_buf, ':', &Y, &nY);
    if ( nY != 2 ) { go_BYE(-1); }
    rs_munmap(nn_X, nn_nX);
    if ( strcmp(Y[0], Y[1]) == 0 ) {
      /* num non null values == nR => nn field not needed */
      status = q_delete(nn_ddir_id, nn_fileno); cBYE(status);
    }
    else {
      zero_fld_rec(&nn_t1f2_rec); nn_t1f2_rec.fldtype = I1;
      status = add_aux_fld(NULL, t1_id, NULL, t1f2_id, nn_ddir_id, 
			   nn_fileno, nn, &nn_t1f2_id, &nn_t1f2_rec);
      cBYE(status);
    }
  }
  /*-------------------------------------------------------*/
 BYE:
  if ( Y != NULL ) { 
    for ( int i = 0; i < nY; i++ ) { 
      free_if_non_null(Y[i]);
    }
    free_if_non_null(Y);
  }
  rs_munmap(X, nX);
  rs_munmap(nn_X, nn_nX);
  rs_munmap(X1, nX1);
  rs_munmap(X2, nX2);
  rs_munmap(nn_X1, nn_nX1);
  rs_munmap(nn_X2, nn_nX2);
  rs_munmap(t2f2_X, n_t2f2_X);
  rs_munmap(nn_t2f2_X, nn_n_t2f2_X);
  return(status);
}
コード例 #8
0
ファイル: master.c プロジェクト: mudchina/fy2
}

// Function name:   update_file
// Description:     reads in a file, ignoring lines that begin with '#'
// Arguements:      file: a string that shows what file to read in.
// Return:          Array of nonblank lines that don't begin with '#'
// Note:            must be declared static (else a security hole)
static string *update_file(string file)
{
	string *list;
	string str;
	int i;
	str = read_file(file);
	if (!str)
		return ({});
	list = explode(str, "\n");
	for (i = 0; i < sizeof(list); i++) {
		if (list[i][0] == '#') {
			list[i] = 0;
		}
	}
	return list;
}

// Function name:       epilog
// Return:              List of files to preload
string *epilog(int load_empty)
{
	string *items;

	items = update_file(CONFIG_DIR + "preload");
コード例 #9
0
/** @brief translate text lines and write result in destString*/
void GLogicProcessor::lineTextTranslation(string &destString){
    
    GMemory *longMemory=(GMemory*)inputData.longMemory;
    int translationMode=((GStr<int>*)inputData.pref)->get(22);
    string ln=inputData.data["ln"];
    if(ln!=""){
        if(ln=="rus")translationMode=TRANSLATE_RUS;
        if(ln=="eng")translationMode=TRANSLATE_ENG;
    }
    GVector *dk;
    GMap *d;
    string str;
    if(translationMode==TRANSLATE_ENG){
        str="translationDictEng";
    }else{
        str="translationDictRus";
    }
    longMemory->loadTable(str);
    dk=longMemory->table[str].data;
    indexRecord indexRec=longMemory->createIndex(longMemory->table[str], 0, HASH_SEARCH);
    d=indexRec.mIndex;
    
    str="mainDict";
    longMemory->loadTable(str);
    indexRec=longMemory->createIndex(longMemory->table[str], 0, HASH_SEARCH);
    GMap *dictKey=indexRec.mIndex;
    
    
    string src,line,ld,l1,c,c1,c2,report,res,resD;
    int i,j,start,end,lng,index;
    int mode=inputData.mode;
    
    destString=str_replace("། ","།\n",destString);
    destString=str_replace("།་","།\n",destString);
    destString=str_replace("༎","།\n",destString);
    destString=str_replace("༔ ","༔\n",destString);
    destString=str_replace("༴ ","༴\n",destString);
    destString=str_replace("ག ","ག\n",destString);
    
    vector<string>text=explode("\n",destString);
    
    int id=1;
    //text.resize(1); text[0]="གང་ཟག་ཏུ་ལྟ་(༦)བའམ།";
    //line="རྣམས་";
    //TString st;
    //dk->getTStr(109073, &st);
    //cout<<"st="<<st.size()<<" st[0]="<<st[0]<<endl;
    //exit(0);
    //index=d->getHKey(line);
    //cout<<"index="<<index<<endl;
    //exit(0);
    //cout<<"text.size()="<<text.size()<<endl;
    
    //dictKey->hashError=0;
    //dictKey->maxHashError=0;
    //dictKey->hashCount=0;
    
    report="";
    int step=0;
    
    for(int lineIndex=0;lineIndex<text.size();lineIndex++){
        if(step==1000){
            print(lineIndex<<" from "<<text.size());
            step=0;
        }
        step++;
        str=text[lineIndex];
        //cout<<"str="<<str<<endl;
        src=str;
        lng=(int)str.size();
        if(lng<2)continue;
        if(str.find("་")==-1){
            report+=src+"\n<br>";
            continue;
        }
        str=clearText(str);
        //str=str_replace("[ _\d\ "	\"\*\(\)\{\}\[\]@//\%\&༄༅༔༴༡༢༣༤༥༦༧༨༩༠༎།༑༈༌༐༼༽ऀ-ॿ]","་",str)
        str=str_replace("ཿ","་ཿ་",str);
        str=str_replace("│","",str);
        str=str+"་།";
        str=str_replace("་་","་",str);
        //str=str_replace("([^་])འོ་།","\1་(точка)་",str);
        //str=str_replace("([^་])འམ་།","\1་[འམ=или]་",str);
        str=str_replace("ག་གོ་།","ག་(¶)་",str);
        str=str_replace("ང་ངོ་།","ང་(¶)་",str);
        str=str_replace("ད་དོ་།","ད་(¶)་",str);
        str=str_replace("ན་ནོ་།","ན་(¶)་",str);
        str=str_replace("བ་བོ་།","བ་(¶)་",str);
        str=str_replace("མ་མོ་།","མ་(¶)་",str);
        str=str_replace("ར་རོ་།","ར་(¶)་",str);
        str=str_replace("ལ་ལོ་།","ལ་(¶)་",str);
        str=str_replace("ས་སོ་།","ས་(¶)་",str);
        str=str_replace("་ཏོ་།","་(¶)་",str);
        //str=str_replace("་པའང་","་པ་[འང=уступ.]་",str);
        //str=str_replace("་བའང་","་བ་[འང=уступ.]་",str);
        
        vector<string>l=explode("་",str);
        res="";
        resD="";
        
        lng=(int)l.size();
        start=0;
        end=lng-1;
        
        i=lng;
        
        while(start<lng){
            //make query string decrease end
            end=lng;
            while(end>-1){
                j=start;
                line="";
                //increase start
                while (j < end){
                    line+=l[j]+"་";
                    j++;
                }
                //count+=1
                //cout<<line<<" "<<start<<" "<<end<<endl;
                //if (count >120):
                //return
                index=d->getHKey(line,0);
                if(index!=-1){
                    TString st;
                    dk->getTStr(index, &st);
                    c="="+st[1];
                    res+="["+linkDict(line,&id)+linkEdit(c,&id)+"]་";
                    if(c.find("__")!=-1){
                        end-=1;
                        res+="<br>\n";
                        continue;
                    }
                    if(mode==FULL_REPORT && start==0 && end==lng-1){
                        end-=1;
                        continue;
                    }
                    start=end-1;
                    break;
                }
                //next check big dictionary report
                index=dictKey->getHKey(line,0);
                if(line.size()>3 && index!=-1){
                    resD+="["+linkDict(line,&id)+linkEdit("=",&id)+"] ";
                }
                ln=line+"@";
                
                l1=str_replace("འི་@","་",ln);
                index=d->getHKey(l1,0);
                if(index!=-1){
                    TString st;
                    dk->getTStr(index, &st);
                    c="="+st[1];
                    res+="["+linkDict(l1,&id)+linkEdit(c,&id)+"]་["+linkDict("-འི་",&id)+linkEdit("=g.p",&id)+"]་";
                    start=end-1;
                    break;
                }
                //next check big dictionary report
                index=dictKey->getHKey(l1,0);
                if(line.size()>3 && index!=-1){
                    resD+="["+linkDict(l1,&id)+linkEdit("=",&id)+"] ";
                }
                
                l1=str_replace("ས་@","་",ln);
                index=d->getHKey(l1,0);
                if(index!=-1){
                    TString st;
                    dk->getTStr(index, &st);
                    c="="+st[1];
                    res+="["+linkDict(l1,&id)+linkEdit(c,&id)+"]་["+linkDict("-ས་",&id)+linkEdit("=i.p.",&id)+"]་";
                    start=end-1;
                    break;
                }
                //next check big dictionary report
                index=dictKey->getHKey(l1,0);
                if(line.size()>3 && index!=-1){
                    resD+="["+linkDict(l1,&id)+linkEdit("=",&id)+"] ";
                }
                
                l1=str_replace("ར་@","་",ln);
                index=d->getHKey(l1,0);
                if(index!=-1){
                    TString st;
                    dk->getTStr(index, &st);
                    c="="+st[1];
                    res+="["+linkDict(l1,&id)+linkEdit(c,&id)+"]་["+linkDict("-ར་",&id)+linkDict("=d.l.",&id)+"]་";
                    start=end-1;
                    break;
                }
                //next check big dictionary report
                index=dictKey->getHKey(l1,0);
                if(line.size()>3 && index!=-1){
                    resD+="["+linkDict(l1,&id)+linkEdit("=",&id)+"] ";
                }
                
                l1=str_replace("འོ་@","་",ln);
                index=d->getHKey(l1,0);
                if(index!=-1){
                    TString st;
                    dk->getTStr(index, &st);
                    c="="+st[1];
                    res+="["+linkDict(l1,&id)+linkEdit(c,&id)+"]་["+linkDict("-འོ་",&id)+linkEdit("=(точка)",&id)+"]་";
                    start=end-1;
                    break;
                }
                //next check big dictionary report
                index=dictKey->getHKey(l1,0);
                if(line.size()>3 && index!=-1){
                    resD+="["+linkDict(line,&id)+linkEdit("=",&id)+"] ";
                }
                
                l1=str_replace("འམ་@","་",ln);
                index=d->getHKey(l1,0);
                if(index!=-1){
                    TString st;
                    dk->getTStr(index, &st);
                    c="="+st[1];
                    res+="["+linkDict(l1,&id)+linkEdit(c,&id)+"]་["+linkDict("-འམ་",&id)+linkEdit("=или",&id)+"]་";
                    start=end-1;
                    break;
                }
                //next check big dictionary report
                index=dictKey->getHKey(l1,0);
                if(line.size()>3 && index!=-1){
                    resD+="["+linkDict(l1,&id)+linkEdit("=",&id)+"] ";
                }
                end-=1;
                if(end==start){
                    res+=line;
                    break;
                }
            }
            start++;
        }
        res=str_replace(":|:YP","",res);
        report+=linkOriginal(src,&id)+"<br>\n@<c>"+res+"</c>\n";
        if(resD.size()>10){
            report+="@";
            report+=resD+"<br>\n";
        }else{
            report+="<br>\n";
        }
        
        if(mode==FULL_REPORT){
            res="";
            for (int t=0;t<l.size();t++){
                line=l[t];
                l1=line+"་";
                index=d->getHKey(l1,0);
                if(index!=-1){
                    TString st;
                    dk->getTStr(index, &st);
                    c="="+st[1];
                    res+="["+linkDict(l1,&id)+linkEdit(c,&id)+"]་";
                }
            }
            res=str_replace(":|:YP","",res);
            report+="<c>"+res+"</c>\n<br>\n";
        }
        //break;
        
    }
    report=str_replace("<br>\n<br>", "<br>\n",report);
    //print("@@@@"<<report);
    destString=report;
    
    //cout<<"    dictKey->hashError="<<dictKey->hashError<<" dictKey->maxHashError="<<dictKey->maxHashError<<" dictKey->hashCount="<<dictKey->hashCount<<endl;
    //cout<<"maxHashSize="<<(0xffffffff>>7)<<endl;
    //exit(0);
    
}
コード例 #10
0
ファイル: bomb.cpp プロジェクト: ChristophKuhfuss/supertux
void
Bomb::kill_fall()
{
  explode();
}
コード例 #11
0
ファイル: bomb.cpp プロジェクト: ChristophKuhfuss/supertux
void
Bomb::ignite()
{
  explode();
}
コード例 #12
0
ファイル: 68000exception.c プロジェクト: EtchedPixels/FUZIX
int exception(struct trapdata *framedata)
{
	ptptr proc;
	unsigned int frame, fsize;
	uint8_t trap = framedata->trap;
	unsigned int sig = 0;
	uint16_t m;
	uint16_t *sp = (uint16_t *)framedata;
	uint16_t *usp = get_usp();
	uint16_t *unwind, *context;
	uint8_t err = 0;
	int i;

	/* We translate debug to SIGIOT and A and F line to SIGILL
	   We will need to fix up 68000 v 68010 move to/from SR */
	static const uint8_t trap_to_sig[] = {
		0, 0, SIGSEGV, SIGBUS, SIGILL, SIGFPE,
		SIGABRT/*CHK*/, SIGTRAP/*TRAPV */,
		SIGILL, SIGIOT, SIGILL, SIGFPE };

	proc = udata.u_ptab;

	if (sysinfo.cpu[0] == 10) {
		/* Long or short frame: the CPU tells us the frame format */
		if (framedata->exception[3] & 0x8000) {
			fsize = 29;
			frame = FRAME_C;
		} else  {
			fsize = 4;
			frame = FRAME_D;
		}
	} else {
		frame = FRAME_B;
		fsize = 3;
	}
	if (trap == 0) {
		sig = udata.u_cursig;
		udata.u_cursig = 0;
	} else if (trap < 12) {
		if (trap < 4) {
			/* On a 68010 this frame is 29 words and the event is
			   restartable (although not always usefully). We need to
			   decide whether to set the restart flag case by case */
			if (sysinfo.cpu[0] == 0) {
				frame = FRAME_A;
				fsize = 7;
			}
		}
		sig = trap_to_sig[trap];
	} else if (trap >= 32 && trap < 48)
		sig = SIGTRAP;
	/* This processing only applies to synchronous hardware exceptions */
	if (trap) {
		/* Went boom in kernel space or without a user recovery */
		if (kernel_flag || sig == 0) {
			explode(framedata, frame);
			panic("trap");
		}

		/* Cheating here .. all our exceptions are low 16 signal */
		m = 1 << sig;
		/*
		 *	The caller is ignoring our signal. In some cases this is fine
		 *	but in others it's less clear (eg division by zero) and we
		 *	may need to take different action.
		 */
		if (proc->p_sig[0].s_ignored & m)
			return 0;
		/* Weird case - we took a sync signal and the caller wants us to
		   report it later. */
		if (proc->p_sig[0].s_held & m) {
			/* TODO: if it's not meaningfully restartable we should
			   probably treat this as a kill */
			ssig(proc, sig);
			return 0;
		}
		recalc_cursig();	/* Put any async signal back */
	}
	if (udata.u_sigvec[sig] == SIG_DFL) {
		/* Default action for our signal ? */
		doexit(dump_core(sig));
		/* This will never return. We will go schedule new work */
		panic("exret");
	}
	/* build signal frame

		Our unwinder code does
		move.l 8(sp),sp
		movem.l a0-a1/d0-d1,(sp)+
		move.w (sp)+,ccr
		rts */


	/* Now update the user stack */
	/* - Push the recovery PC */
	/* - Patch the kernel exception frame */
	if (sysinfo.cpu[0]) {
		/* FIXME */
		err |= pushw(&usp, sp[34]);
		err |= pushw(&usp, sp[33]);
		*(uint32_t *)(&sp[33]) = (uint32_t)udata.u_sigvec[sig];
	} else {
		err |= pushw(&usp, sp[31 + fsize]);
		err |= pushw(&usp, sp[30 + fsize]);
		*(uint32_t *)(&sp[30 + fsize]) = (uint32_t)udata.u_sigvec[sig];
	}

	/* FIXME: when we do ptrace we will need to support adding the T
	   flag back here as the exception cleared it */
	err |= pushw(&usp,  framedata->sr);
	/* Push A1 A0 D1 D0 to match MOVEM.L */
	err |= pushl(&usp, framedata->a[1]);
	err |= pushl(&usp, framedata->a[0]);
	err |= pushl(&usp, framedata->d[1]);
	err |= pushl(&usp, framedata->d[0]);

	/* Remember the target for undoing the frame */
	unwind = usp;

	/* Copy in the signal context itself. 30 words of registers, 2 of
	   trap code and then the hardware exception */
	for (i = 0; i < 30 + 2 + fsize; i++)
		err |= pushw(&usp, *sp++);
	context = usp;
	err |= pushl(&usp, (uint32_t)unwind);
	/* Signal context is a secret extra non portable argument */
	err |= pushl(&usp, (uint32_t)context);
	/* We end it with the call frame as seen from the signal handler, a
	   single argument and a return address */
	err |= pushl(&usp, sig);
	err |= pushl(&usp, udata.u_codebase + 0x04);

	set_usp(usp);

	if (err) {
		doexit(dump_core(SIGSTKFLT));
		panic("exret2");
	}
	/* Once built clear the restart state */
	udata.u_sigvec[sig] = SIG_DFL;
	/* Return, RTE and end up on the signal frame */
	return 1;
}
コード例 #13
0
ファイル: main.cpp プロジェクト: CCJY/coliru
int main() {
  std::array<int, 2> t{1, 2};
  explode(t, test2);
}
コード例 #14
0
int
main(int argc, char *argv[])
{
    char line[INBUFSIZE];
    const char *fname = "stdin";
    char *ptr, *tok;
    char defs[INBUFSIZE];
    char stmt[INBUFSIZE];
    FILE *fp = stdin;
    int lineno = 0;
    int inprocess = 0;
    int token, state;
    int errs = 0;

    if ((pname = strrchr(argv[0], '/')) == NULL)
	pname = argv[0];
    else
	pname++;

    if (argc > 2) {
	(void) fprintf(stderr, "Usage: %s [<filename>]\n", pname);
	return 1;
    }

    if (argc == 2)
	if ((fp = fopen(fname = argv[1], "r")) == NULL) {
	    (void) fprintf(stderr, "%s: Cannot open `%s'\n", pname, fname);
	    return 1;
	}

    state = S_DISCARD;

    while ((ptr = fgets(line, sizeof(line), fp)) != NULL) {
	lineno++;
	switch (token = findtoken(gettoken(&ptr, defs))) {
	case T_NEWCODE:
	    state = S_CODE;
	    break;

	case T_ENDCODE:
	    state = S_DISCARD;
	    break;

	case T_COMMENT:
	    state = S_COMMENT;
	    break;

	case T_NEWDEF:
	    state = S_KEYWORD;
	    break;

	case T_ENDDEF:
	    state = S_DISCARD;
	    break;

	case T_VENDOR:
	    state = S_KEYWORD;
	    break;

	case T_HOSTTYPE:
	    state = S_KEYWORD;
	    break;

	case T_MACHTYPE:
	    state = S_KEYWORD;
	    break;

	case T_OSTYPE:
	    state = S_KEYWORD;
	    break;

	case T_MACRO:
	    if (gettoken(&ptr, defs) == NULL) {
		(void) fprintf(stderr, "%s: \"%s\", %d: Missing macro name\n",
			       pname, fname, lineno);
		break;
	    }
	    if (gettoken(&ptr, stmt) == NULL) {
		(void) fprintf(stderr, "%s: \"%s\", %d: Missing macro body\n",
			       pname, fname, lineno);
		break;
	    }
	    (void) fprintf(stdout, "\n#if %s\n# define %s\n#endif\n\n", stmt,
			   defs);
	    break;

	case T_NONE:
	    if (state != S_CODE && *defs != '\0') {
		(void) fprintf(stderr, "%s: \"%s\", %d: Discarded\n",
			       pname, fname, lineno);
		if (++errs == 30) {
		    (void) fprintf(stderr, "%s: Too many errors\n", pname);
		    return 1;
		}
		break;
	    }
	    (void) fprintf(stdout, "%s", line);
	    break;

	default:
	    (void) fprintf(stderr, "%s: \"%s\", %d: Unexpected token\n",
			   pname, fname, lineno);
	    return 1;
	}

	switch (state) {
	case S_DISCARD:
	    if (inprocess) {
		inprocess = 0;
		(void) fprintf(stdout, "#endif\n");
	    }
	    break;

	case S_KEYWORD:
	    tok = gettoken(&ptr, defs);
	    if (token == T_NEWDEF) {
		if (inprocess) {
		    (void) fprintf(stderr, "%s: \"%s\", %d: Missing enddef\n",
				   pname, fname, lineno);
		    return 1;
		}
		if (tok == NULL) {
		    (void) fprintf(stderr, "%s: \"%s\", %d: No defs\n",
				   pname, fname, lineno);
		    return 1;
		}
		(void) fprintf(stdout, "\n\n");
#ifdef LINEDIRECTIVE
		(void) fprintf(stdout, "# %d \"%s\"\n", lineno + 1, fname);
#endif /* LINEDIRECTIVE */
		(void) fprintf(stdout, "#if %s\n", defs);
		inprocess = 1;
	    }
	    else {
		if (tok && *tok)
		    (void) fprintf(stdout, "# if (%s) && !defined(_%s_)\n",
				   explode(defs), keyword[token]);
		else
		    (void) fprintf(stdout, "# if !defined(_%s_)\n", 
				   keyword[token]);

		if (gettoken(&ptr, stmt) == NULL) {
		    (void) fprintf(stderr, "%s: \"%s\", %d: No statement\n",
				   pname, fname, lineno);
		    return 1;
		}
		(void) fprintf(stdout, "# define _%s_\n", keyword[token]);
		(void) fprintf(stdout, "    %s = %s;\n", keyword[token], stmt);
		(void) fprintf(stdout, "# endif\n");
	    }
	    break;

	case S_COMMENT:
	    if (gettoken(&ptr, defs))
		(void) fprintf(stdout, "    /* %s */\n", defs);
	    break;

	case S_CODE:
	    if (token == T_NEWCODE) {
#ifdef LINEDIRECTIVE
		(void) fprintf(stdout, "# %d \"%s\"\n", lineno + 1, fname);
#endif /* LINEDIRECTIVE */
	    }
	    break;

	default:
	    (void) fprintf(stderr, "%s: \"%s\", %d: Unexpected state\n",
			   pname, fname, lineno);
	    return 1;
	}
    }

    if (inprocess) {
	(void) fprintf(stderr, "%s: \"%s\", %d: Missing enddef\n",
		       pname, fname, lineno);
	return 1;
    }

    if (fp != stdin)
	(void) fclose(fp);

    return 0;
}
コード例 #15
0
void
init( char* filename , char* config[] )
{
  FILE* fd;
  char *line, **tmp;
  int i;

  line = (char*)Malloc( sizeof(char*) * LINENUM);

  fd = fopen(filename, "r");
  if( fd == NULL )
  {
     fprintf(stderr, "Cannot read file\n");
     exit(-1);
  }

  for(i=0; i<CONFLEN; i++)
    config[i] = NULL;

  while( (getl(line,  fd ) != NULL) )
  {

    if( isalpha(line[0]) )
    {

      tmp = explode( line );
      if( strcmp( "server_address", tmp[OPTION] ) == 0 )
      {
        if( config[SERVER_ADDRESS] == NULL ) 
        {
          config[SERVER_ADDRESS] = 
            (char*)Malloc( sizeof(char) * strlen( tmp[VALUE] ));
        }

        strcpy( config[SERVER_ADDRESS], tmp[VALUE] );
      }

      if( strcmp( "server_name", tmp[OPTION] ) == 0 )
      {
        
        if( config[SERVER_NAME] == NULL ) 
        {
          config[SERVER_NAME] = 
            (char*)Malloc( sizeof(char) * strlen( tmp[VALUE] ));
        }

        strcpy( config[SERVER_NAME], tmp[VALUE] );
      }

      if( strcmp( "server_port", tmp[OPTION] ) == 0 )
      {
        
        if( config[SERVER_PORT] == NULL ) 
        {
          config[SERVER_PORT] = 
            (char*)Malloc( sizeof(char) * strlen( tmp[VALUE] ));
        }

        strcpy( config[SERVER_PORT], tmp[VALUE] );
      }

      if( strcmp( "print_message_details", tmp[OPTION] ) == 0 )
      { 
        
        if( config[PRINT_MSG] == NULL ) 
        {
          config[PRINT_MSG] = 
            (char*)Malloc( sizeof(char) * strlen( tmp[VALUE] ));
        }

        strcpy( config[PRINT_MSG], tmp[VALUE] );
      }
     
      if( strcmp( "request_count" , tmp[OPTION] ) == 0 )
      {

        if( config[REQ_COUNT] == NULL ) 
        {
          config[REQ_COUNT] = 
            (char*)Malloc( sizeof(char) * strlen( tmp[VALUE] ));
        }

        strcpy( config[REQ_COUNT], tmp[VALUE] );
      }

      if( strcmp( "request_timeout", tmp[OPTION] ) == 0 )
      {

        if( config[REQ_TIMEOUT] == NULL ) 
        {
          config[REQ_TIMEOUT] = 
            (char*)Malloc( sizeof(char) * strlen( tmp[VALUE] ));
        }
        strcpy( config[REQ_TIMEOUT], tmp[VALUE] );
      }



      /*
      printf("%s %s\n", tmp[OPTION], tmp[VALUE]);
      */
    }
  }

  /* set default value */
  if( (config[SERVER_ADDRESS] == NULL &&
      config[SERVER_NAME] == NULL) ||
      config[SERVER_PORT] == NULL )
  {
    fprintf(stderr, "Bad format in config file\n");
    exit(-1);
  }


  if( config[PRINT_MSG] == NULL )
  {
    config[PRINT_MSG] = (char*)Malloc( sizeof(char)*LEN );
    strcpy( config[PRINT_MSG], "ON");
  }


  if( config[REQ_COUNT] == NULL )
  {
    config[REQ_COUNT] = (char*)Malloc( sizeof(char)*LEN );
    strcpy( config[REQ_COUNT], TIMES);
  }


  if( config[REQ_TIMEOUT] == NULL )
  {
    config[REQ_TIMEOUT] = (char*)Malloc( sizeof(char)*LEN );
    strcpy( config[REQ_TIMEOUT], TIMEOUT);
  }


  fclose(fd); 
}
コード例 #16
0
void GLogicProcessor::saveToTranslationDictionary(string &srcStr){
    vector<string>text=explode("[",srcStr);
    int index;
    string key,value;
    GMemory *longMemory=(GMemory*)inputData.longMemory;
    int translationMode=((GStr<int>*)inputData.pref)->get(22);
    GVector *dv;
    GMap *d;
    if(translationMode==TRANSLATE_ENG){
        dv=longMemory->translationDictEng;
        d=longMemory->translationDictGMapEng;
    }else{
        dv=longMemory->translationDictRus;
        d=longMemory->translationDictGMapRus;
    }
    //GMap *dictKey=longMemory->dictionaryGMap;
    
    for(int i=0;i<text.size();i++){
        string line=text[i];
        string reStr="<[^>]*>";
        std::regex key_regex(reStr);
        line = std::regex_replace(line, key_regex, "");
        reStr=".*=.*";
        std::regex key_regex_(reStr);
        line = std::regex_replace(line, key_regex_, "");
        if(line.size()<3)continue;
        index=(int)line.find("/");
        if(index<3)continue;
        index=(int)line.find("]");
        if(index<3)continue;
        line=substr(0, index, line);
        line=str_replace("/_", "/", line);
        vector<string>data=explode("/",line);
        if(data.size()<2)continue;
        key=data[0];
        value=data[1];
        key=key+"་";
        key=str_replace(" ","",key);
        key=str_replace("་་","་",key);
        value=str_replace("__","#",value);
        value=str_replace("_@","@",value);
        value=str_replace("#","__",value);
        value+="@";
        value=str_replace("@@","@",value);
        value=str_replace("{","༼",value);
        value=str_replace("«","༼",value);
        value=str_replace("}","༽",value);
        value=str_replace("»","༽",value);
        value=str_replace("༼༼","༼",value);
        value=str_replace("༽༽","༽",value);
        if(value.size()<3)continue;
        //cout<<"key="<<key<<" value="<<value<<endl;
        index=d->getHKey(key,0);
        //cout<<"index="<<index;
        TString st;
        if(value!="---"){
            st+=key;
            st+=value;
        }else{
            st+="";
            st+="";
        }
        if(index>-1){
            dv->putTStr(index, &st);
        }else{
            d->addRecord(&st);
        }
        
    }
    
}
コード例 #17
0
ファイル: answer10.c プロジェクト: jia32/ECE264
struct YelpDataBST* create_business_bst(const char* businesses_path,
                                        const char* reviews_path)
{
  const char filename = business_path;
  int len;
  int lineno = 0;
  int last_id = -1;
  int num_id = 0;
  YelpDataBST * root = NULL;
  FILE *fp;
  
  fp = fopen(filename,"r");
  if(fp == NULL)
    {
      printf("File error\n");
      return NULL;
    }

  //basic idea here
  //read one line at a time till it reaches to the end
  //use explode to read address
  //when the id matches, insert the address offsets

  //how to get offsets: get current location (before read a line)
  //get the length of each part
  
  while (getline(&buffer,&len,fp)>0)
    //(not reaching the end of the file)
    {
      int arrlen;
      //buffer = fscanf("%s\n",fp);//read next line of file
      char ** strArr = explode(buffer,"\t",&arrlen);//explode that line
      
      if (arrlen == 7)//make sure there are all 8 elements for address
	{
	  int bus_id = atoi(strArr[0]);//insert id first
	  int * offsets = get_offsets(strArr,offset,offsets);
	  if (bus_id != last_id)//count number of id
	    {
	      num_id++;
	      last_id = bus_id;
	    }
	//insert node to bustree	
	  root = BusTree_insert(root, strArr[1],
				bus_id,offsets[0],offsets[1],offsets[2],offsets[3]);
	  file offset = ftell(fp);
	  destroystringarray(streArr,arrlen);
	  free(offsets);
	}
    }
  fseek(fp,0,SEEK_SET);
  free(buffer);
  fclose(fp);
  //---------working on review now------------                                               
  Review * review = malloc(sizeof(Review)*num_id);
  filename = reviews_path;
  
  fp = fopen(filename,"r");

  if(fp == NULL)
    {
      printf("File error.");
      return NULL;
    }
  

  
}
コード例 #18
0
ファイル: clientcontrol.cpp プロジェクト: drtrev/geo
void Clientcontrol::process(Unit unit)
//void Curses::process(Unit unit, Client &client, Server &server, Talk &talk, int keyset[])
  // process data unit
{
  switch (unit.flag) {
    case UNIT_ASSIGN:
      myId = unit.assign.id;
      out << VERBOSE_NORMAL << "Received my client ID: " << myId << '\n';
      users++;
      if (myId < 0) {
        out << VERBOSE_LOUD << "Error with assigned ID: " << myId << '\n';
      }
      break;
    case UNIT_AUDIO:
      out << VERBOSE_LOUD << "Received audio chunk for ID: " << unit.audio.id << '\n';
      talk.receive(unit.audio.data);
      // see if buffer is filling up...
      if (talk.getChunksRecvd() > 2) out << VERBOSE_LOUD << "Buffered " << talk.getChunksRecvd() << " chunks\n"; // TODO remove this
      break;
    case UNIT_GENERIC:
      // used for deactivating bullets for now
      if (unit.generic.objectid < 0 || unit.generic.objectid > BULLETS_MAX - 1) {
        out << VERBOSE_LOUD << "Error: generic unit, bad id: " << unit.generic.objectid << "\n";
      }else{
        // pos will have been received first
        int hit = level.checkCollisionSimple(bullet[unit.generic.objectid].getPos());
        if (hit == 0) {
          out << VERBOSE_LOUD << "--------------Error: we're out of sync. No hit here! bulletid: " << unit.generic.objectid << "\n";
          std::cout << bullet[unit.generic.objectid].getPos() << std::endl;
        }
        explode(bullet[unit.generic.objectid].getPos());
        bullet[unit.generic.objectid].setActive(false);
        out << VERBOSE_QUIET << "bullet deactivated. bulletid: " << unit.generic.objectid << "\n";
      }
      break;
    case UNIT_LOGOFF:
      if (users > 0) {
        if (myId == unit.logoff.id) {
          out << VERBOSE_LOUD << "Error, server says I logged off!\n";
        }else{
          if (myId > unit.logoff.id) myId--;
          //for (int i = unit.logoff.id; i < users - 1; i++) {
            //player[i] = player[i+1]; // when new users logon, they are reset in curses.cpp, see checkNewConnections
          //}
        }
        users--;
      }
      else out << VERBOSE_LOUD << "Error, logoff received but no one left!\n";
      break;
    case UNIT_NEWCLIENT:
      if (unit.newclient.id > -1 && unit.newclient.id < MAX_CLIENTS) {
        users++;
        //player[unit.newclient.id].reset(badcontrol); // not entirely necessary for client, cos just get info from server
      }else{
        out << VERBOSE_LOUD << "Invalid ID for new client\n";
      }
      break;
    case UNIT_POSITION:
      if (unit.position.id > IDHACK_PLAYERPOS_MIN - 1 && unit.position.id < IDHACK_PLAYERPOS_MAX) { // was > -1 and < players
        player[unit.position.id].setX(unit.position.x);
        player[unit.position.id].setY(unit.position.y);
        player[unit.position.id].setZ(unit.position.z);
        //user[unit.position.id].x = unit.position.x;
        //user[unit.position.id].y = unit.position.y;
        //user[unit.position.id].zoom = unit.position.z;
      //map.setUser(unit.position.id, unit.position.x, unit.position.y, unit.position.z);

      }else if (unit.position.id > IDHACK_PLAYERROT_MIN - 1 && unit.position.id < IDHACK_PLAYERROT_MAX) { // was 99 to players+100
        geo::Vector rot(unit.position.x, unit.position.y, unit.position.z);
        player[unit.position.id - IDHACK_PLAYERROT_MIN].setRot(rot);

      }else if (unit.position.id > IDHACK_BULLETPOS_MIN - 1 && unit.position.id < IDHACK_BULLETPOS_MAX) {
        int id = unit.position.id - IDHACK_BULLETPOS_MIN;
        bullet[id].setX(unit.position.x);
        bullet[id].setY(unit.position.y);
        bullet[id].setZ(unit.position.z);
        out << VERBOSE_QUIET << "received bullet pos for bulletid: " << id << "\n";

      }else if (unit.position.id > IDHACK_BULLETROT_MIN - 1 && unit.position.id < IDHACK_BULLETROT_MAX) {
        geo::Vector rot(unit.position.x, unit.position.y, unit.position.z);
        int id = unit.position.id - IDHACK_BULLETROT_MIN;
        bullet[id].setRot(rot);
        bullet[id].setMove(bulletvec, level.getRot());
        bullet[id].setActive(true);
        out << VERBOSE_QUIET << "created bullet: " << id << "\n";

      }else if (unit.position.id == IDHACK_CREATE) {
        // create block
        geo::Vector pos(unit.position.x, unit.position.y, unit.position.z);
        level.createBlock(pos);

      }else if (unit.position.id == IDHACK_LEVELROT) {
        geo::Vector pos(unit.position.x, unit.position.y, unit.position.z);
        level.setRot(pos);

      }else if (unit.position.id == IDHACK_MAKESLOPE) {
        geo::Vector temp(unit.position.x, unit.position.y, unit.position.z);
        LevelNames::Block* block = level.getBlock(temp, 2);
        if (block != NULL) {
          std::cout << "MAKESLOPE: block state: ";
          if (block->state == LevelNames::BLOCK_EMPTY) std::cout << "BLOCK_EMPTY";
          else if (block->state == LevelNames::BLOCK_SOLID) std::cout << "BLOCK_SOLID";
          else if (block->state == LevelNames::BLOCK_SLOPE) std::cout << "BLOCK_SLOPE";
          else std::cout << block->state;
          std::cout << std::endl;

          block->state = LevelNames::BLOCK_SLOPE;
        }else out << VERBOSE_LOUD << "Makeslope received but block not found\n";
      }else out << VERBOSE_LOUD << "Error with position ID - out of range: " << unit.position.id << "\n";

      // temporary output to see what's going on
      //std::cout << "Received position: " << unit.position.x << ", " << unit.position.y << ", " << unit.position.z << std::endl;
      break;
    case UNIT_TRANSFER:
      // store chunk
      if (!transfercontrol.receive(unit)) {
        // send finished transfer, load picture
        Unit unit2;
        unit2.flag = UNIT_TRANSFERFIN;
        unit2.transferfin.to = unit.transfer.from;
        unit2.transferfin.from = unit.transfer.to;
        unit2.transferfin.id = unit.transfer.id;
        net.addUnit(unit2, client);

        //picturecontrol.loadRemote(unit.transfer.from, unit.transfer.id, unit.transfer.filename);
      }
      break;
    case UNIT_TRANSFERFIN:
      if (unit.transferfin.to > -1 && unit.transferfin.to < MAX_CLIENTS) {
        //if (unit.transferfin.id > -1 && unit.transferfin.id < picturecontrol.getPiclen(unit.transferfin.to)) {
        //picturecontrol.incrementLoaded(unit.transferfin.to, unit.transferfin.id);
        //}else{
        //out << VERBOSE_LOUD << "TransferFIN: error with id: " << unit.transferfin.id << '\n';
        //}
      }else{
        out << VERBOSE_LOUD << "TransferFIN: error with to: " << unit.transferfin.to << '\n';
      }
      break;
    case UNIT_TRANSFERREQ:
      transfercontrol.send(unit.transferreq.to, unit.transferreq.from, unit.transferreq.id, unit.transferreq.filename, net, client);
      break;
    default:
      out << VERBOSE_LOUD << "Error, flag not found: " << unit.flag << '\n';
  }
}
コード例 #19
0
ファイル: vsx_widget_desktop.cpp プロジェクト: Who828/vsxu
vsx_widget_desktop::vsx_widget_desktop() {

  interpolating = false;
  root = this;
  enabled = false;

  // messing with the configuration
  skin_path = "_gfx/vsxu/";
  vsx_command_list modelist;
  vsx_command_s* mc = 0;
  load_configuration();
  myf.init(PLATFORM_SHARED_FILES+"font"+DIRECTORY_SEPARATOR+"font-ascii.png");
  vsx_command_list skin_conf;
  skin_conf.load_from_file(skin_path+"skin.conf",true,4);
#ifdef VSXU_PLAYER
  if (!skin_conf.count()) {
    skin_conf.add_raw("color 0 0.3,0.3,0.5,0.4");
    skin_conf.add_raw("color 1 0.2,0.2,0.3,0.4");
    skin_conf.add_raw("color 2 0.2,0.2,0.4,1");
    skin_conf.add_raw("color 3 1,1,1,1");
    skin_conf.add_raw("color 4 0.5,0.5,0.7,1");
    skin_conf.add_raw("color 5 0.5,0.5,0.5,1");
    skin_conf.add_raw("color 6 0.4,0.4,0.5,1");
    skin_conf.add_raw("color 7 0.2,0.3,0.8,1");
    skin_conf.add_raw("color 8 0,0,1,0.0");
    skin_conf.add_raw("color 9 1,1,1,0.75");
    skin_conf.add_raw("color 10 1,1,1,0.75");
    skin_conf.add_raw("color 11 1,1,1,0");
    skin_conf.add_raw("color 12 1,1,1,1");
    skin_conf.add_raw("color 13 1,1,1,1");
  }
#endif
  skin_conf.reset();
  while ( (mc = skin_conf.get()) ) {
    if (mc->cmd == "color") {
      vsx_avector<vsx_string> parts;
      vsx_string deli = ",";
      explode(mc->parts[2],deli, parts);
      vsx_color p;
      p.r = s2f(parts[0]);
      p.g = s2f(parts[1]);
      p.b = s2f(parts[2]);
      p.a = s2f(parts[3]);
      skin_color[s2i(mc->parts[1])] = p;
    }
  }
  // server widget
  sv = add(new vsx_widget_server,"desktop_local");

  sv->color.b = 255.0/255.0;
  sv->color.g = 200.0/255.0;
  sv->color.r = 200.0/255.0;
  sv->size.x = 5;
  sv->size.y = 5;

  //sv->p["a"] = 0.4;

  // preview window
  tv = add(new vsx_window_texture_viewer(),"vsxu_preview");
  tv->init();
  ((vsx_window_texture_viewer*)tv)->set_server(sv);
  //---
  a_focus = sv;
  m_focus = sv;
  k_focus = sv;

  console =  add(new vsx_widget_2d_console,"system_console");

  ((vsx_widget_2d_console*)console)->set_destination(sv);

#ifndef VSXU_PLAYER
  mtex.init_opengl_texture();
  mtex.load_jpeg(skin_path+"desktop.jpg");
#endif

  k_focus = this;
  m_focus = this;

  zpf = 0.0;
  zpa = 0.0;
  xpd = 0.0;
  ypd = 0.0;
  zpd = 0.0;
  zps = 0.0;
  yps = 0.0;
  xps = 0.0;
  yp = 0.0;
  xp = 0.0;
  zp = 2.0;
  ypp = zpp = xpp = 0.0f;


}
コード例 #20
0
ファイル: action-find.c プロジェクト: Nazg-Gul/fm
/**
 * Precompile options for faster usage
 * (i.e. compile regular expressions, )
 *
 * @param __options - pointer to options to be precompiled
 * @return zero on success, non-zero otherwise
 */
static int
precompile_options (action_find_options_t *__options)
{
  wchar_t *file_mask, *regexp;
  int result = ACTION_OK;
  BOOL case_insens;

  /* Validate file name mask */
  if (wcscmp (__options->file_mask, L"") &&
      !TEST_FLAG (__options->flags, AFF_MASK_REGEXP))
    {
      file_mask = L"*";
    }

  /* Precompile regexp for file name mask */
  case_insens = !TEST_FLAG (__options->flags,
                            AFF_MASK_CASE_SENSITIVE);

  if (TEST_FLAG (__options->flags, AFF_MASK_REGEXP))
    {
      __options->re_file_count = 1;
      __options->re_file = malloc (sizeof (regexp_t*));
      regexp = build_regexp (__options->file_mask, case_insens);

      __options->re_file[0] = wregexp_compile (regexp);

      if (!__options->re_file[0])
        {
          /*
           * TODO: Add error handling here
           */
          result = ACTION_ERR;
        }

      free (regexp);
    }
  else
    {
      wchar_t **masks;
      long i, count;

      count = explode (__options->file_mask, L";", &masks);

      __options->re_file_count = count;
      __options->re_file = malloc (count * sizeof (regexp_t*));

      for (i = 0; i < count; ++i)
        {
          regexp = file_mask_to_regexp (masks[i], case_insens);

          __options->re_file[i] = wregexp_compile (regexp);

          if (!__options->re_file[i])
            {
              /*
               * TODO: Add error handling here
               */
              result = ACTION_ERR;
            }
          free (regexp);
        }

      free_explode_array (masks);
    }

  /* Process regexp for file's content */
  if (wcscmp (__options->content, L""))
    {
      case_insens = !TEST_FLAG (__options->flags,
                                AFF_CONTENT_CASE_SENSITIVE);

      /* We should compile regular expression for content */
      if (TEST_FLAG (__options->flags, AFF_CONTENT_REGEXP))
        {
          regexp = build_regexp (__options->content, case_insens);

          /* Compile regexp */
          __options->re_content = wregexp_compile (regexp);

          if (!__options->re_content)
            {
              /*
               * TODO: Add error handling here
               */
              result = ACTION_ERR;
            }

          free (regexp);
        }
      else
        {
          /* For speed improvement we won't use regular expressions */
          /* for searching substrings in files. */
          /* But we'd better convert wide-char content string to */
          /* multi-byte string because we wouldn't convert file's content */
          /* to multi-byte string. */
          wcs2mbs (&__options->mb_content, __options->content);

          if (case_insens)
            {
              /* If searching is case-insensitive, we should */
              /* compare buffers in the same cases. */
              lowercase_buffer (__options->mb_content,
                                strlen (__options->mb_content));
            }
        }
    }

  return result;
}
コード例 #21
0
ファイル: proximityMine.cpp プロジェクト: 03050903/Torque3D
void ProximityMine::processTick( const Move* move )
{
   Parent::processTick( move );

   // Process state machine
   mStateTimeout -= TickSec;

   State lastState = NumStates;;
   while ( mState != lastState )
   {
      lastState = mState;
      switch ( mState )
      {
         case Thrown:
            if ( mAtRest )
            {
               mState = Deployed;
               mStateTimeout = mDataBlock->armingDelay;

               // Get deployed position if mine was not stuck to another surface
               if ( mStickyCollisionPos.isZero() )
               {
                  mObjToWorld.getColumn( 2, &mStickyCollisionNormal );
                  mObjToWorld.getColumn( 3, &mStickyCollisionPos );
               }
               setDeployedPos( mStickyCollisionPos, mStickyCollisionNormal );

               if ( mDataBlock->armingSequence != -1 )
               {
                  mAnimThread = mShapeInstance->addThread();
                  mShapeInstance->setSequence( mAnimThread, mDataBlock->armingSequence, 0.0f );
               }
               if ( mDataBlock->armingSound )
                  SFX->playOnce( mDataBlock->armingSound, &getRenderTransform() );
            }
            break;

         case Deployed:
            // Timeout into Armed state
            if ( mStateTimeout <= 0 )
            {
               mState = Armed;
               mStateTimeout = mDataBlock->autoTriggerDelay ? mDataBlock->autoTriggerDelay : F32_MAX;
            }
            break;

         case Armed:
         {
            // Check for objects within the trigger area
            Box3F triggerBox( mDataBlock->triggerRadius * 2 );
            triggerBox.setCenter( getTransform().getPosition() );

            SimpleQueryList sql;
            getContainer()->findObjects( triggerBox, sTriggerCollisionMask,
               SimpleQueryList::insertionCallback, &sql );
            for ( S32 i = 0; i < sql.mList.size(); i++ )
            {
               // Detect movement in the trigger area
               if ( ( sql.mList[i] == mOwner && !mDataBlock->triggerOnOwner ) ||
                    sql.mList[i]->getVelocity().len() < mDataBlock->triggerSpeed )
                  continue;

               // Mine has been triggered
               mShapeInstance->destroyThread( mAnimThread );
               mAnimThread = NULL;

               mState = Triggered;
               mStateTimeout = mDataBlock->triggerDelay;
               if ( mDataBlock->triggerSequence != -1 )
               {
                  mAnimThread = mShapeInstance->addThread();
                  mShapeInstance->setSequence( mAnimThread, mDataBlock->triggerSequence, 0.0f );
               }
               if ( mDataBlock->triggerSound )
                  SFX->playOnce( mDataBlock->triggerSound, &getRenderTransform() );

               if ( isServerObject() )
                  mDataBlock->onTriggered_callback( this, sql.mList[0] );
            }
            break;
         }

         case Triggered:
            // Timeout into exploded state
            if ( mStateTimeout <= 0 )
            {
               explode();
            }
            break;

         case Exploded:
            // Mine's delete themselves on the server after exploding
            if ( isServerObject() && ( mStateTimeout <= 0 ) )
            {
               deleteObject();
               return;
            }
            break;
      }
   }
}
コード例 #22
0
ファイル: firework.c プロジェクト: Noiwex/luajit-curses
int main(int argc, char **argv)
{
    int i, start, end, row, diff, flag, direction;
    const unsigned seed = (unsigned)time((time_t *)0);

#ifdef XCURSES
    Xinitscr(argc, argv);
#else
    initscr();
#endif
    nodelay(stdscr, TRUE);
    noecho();

    if (has_colors())
        start_color();

    for (i = 0; i < 8; i++)
        init_pair((short)i, color_table[i], COLOR_BLACK);

    srand(seed);
    flag = 0;

    while (getch() == ERR)      /* loop until a key is hit */
    {
        do {
            start = rand() % (COLS - 3);
            end = rand() % (COLS - 3);
            start = (start < 2) ? 2 : start;
            end = (end < 2) ? 2 : end;
            direction = (start > end) ? -1 : 1;
            diff = abs(start - end);

        } while (diff < 2 || diff >= LINES - 2);

        attrset(A_NORMAL);

        for (row = 0; row < diff; row++)
        {
            mvaddstr(LINES - row, row * direction + start,
                (direction < 0) ? "\\" : "/");

            if (flag++)
            {
                myrefresh();
                erase();
                flag = 0;
            }
        }

        if (flag++)
        {
            myrefresh();
            flag = 0;
        }

        explode(LINES - row, diff * direction + start);
        erase();
        myrefresh();
    }

    endwin();

    return 0;
}
コード例 #23
0
ファイル: wavefront.cpp プロジェクト: AndreySeVeN/ouzo-game
S_CBuffer OBJ::Load(const char *source) {
	std::string src(source);
	std::istringstream ss(src);
	std::string line;

	std::vector<vertex_pos_t> positions;
	std::vector<vertex_texcoord_t> texCoords;
	std::vector<vertex_normal_t> normals;
	std::vector<face_t> faces;

	while (std::getline(ss, line)) {
		if (line.empty()) {
			continue;
		}

		std::vector<std::string> parts = explode(line.c_str(), ' ', 3);
		std::string type = parts[0];

		if (type == "#") {
			continue;
		}
		else if (type == "v") {
			float val1 = std::stof(parts[1]);
			float val2 = std::stof(parts[2]);
			float val3 = std::stof(parts[3]);
			positions.push_back({ val1, val2, val3 });
		}
		else if (type == "vt") {
			float val1 = std::stof(parts[1]);
			float val2 = std::stof(parts[2]);
			texCoords.push_back({ val1, val2 });
		}
		else if (type == "vn") {
			float val1 = std::stof(parts[1]);
			float val2 = std::stof(parts[2]);
			float val3 = std::stof(parts[3]);
			normals.push_back({ val1, val2, val3 });
		}
		else if (type == "f") {
			face_t face;

			for (int i = 0; i < 3; ++i) {
				std::string *vert = &parts[i + 1];
				std::vector<std::string> values = explode(vert->c_str(), '/', 3);

				face.posIndices[i] = (unsigned short)std::stoi(values[0]);
				face.texCoordIndices[i] = (unsigned short)std::stoi(values[1]);
				face.normalIndices[i] = (unsigned short)std::stoi(values[2]);
			}

			faces.push_back(face);
		}
	}

	std::vector<vertex_t> vertices;

	for (face_t face : faces) {
		for (int i = 0; i < 3; ++i) {
			vertex_pos_t pos = positions[face.posIndices[i] - 1];
			vertex_texcoord_t texCoord = texCoords[face.texCoordIndices[i] - 1];
			vertex_normal_t normal = normals[face.normalIndices[i] - 1];

			vertices.push_back({
				pos.x, pos.y, pos.z, 1.0f,
				texCoord.u, texCoord.v,
				normal.x, normal.y, normal.z
			});
		}
	}

	S_CBuffer buf = GFX->CreateBuffer(BufferType::VERTEX_BUFFER);
	buf->Orphan(vertices.size() * sizeof(vertex_t), sizeof(vertex_t), &vertices[0]);
	return buf;
}
コード例 #24
0
ファイル: control.c プロジェクト: aapo/fachoda-complex
void control(int b)
{
    struct vector u;
    // Left button
    if (! map_mode) switch (selected_weapon) {
    case 0:
        if ((enable_mouse && button_read(SDL_BUTTON_LEFT)) || kread(gkeys[kc_fire].kc)) bot[b].but.canon=1;
        break;
    case 1:
        if ((enable_mouse && button_reset(SDL_BUTTON_LEFT)) || kreset(gkeys[kc_fire].kc)) bot[b].but.bomb=1;
        break;
    } else if ((enable_mouse && button_read(SDL_BUTTON_LEFT)) || kread(gkeys[kc_fire].kc)) {
        bot[b].u.x = ((xmouse-win_center_x)*(MAP_LEN/2)*TILE_LEN)/zoom+map_x*TILE_LEN;
        bot[b].u.y = ((win_center_y-ymouse)*(MAP_LEN/2)*TILE_LEN)/zoom+map_y*TILE_LEN;
        bot[b].u.z = z_ground(bot[b].u.x, bot[b].u.y, true);
    }
    // Right button
    if ((enable_mouse && button_reset(SDL_BUTTON_RIGHT)) || kreset(gkeys[kc_weapon].kc)) {
        if (abs(xmouse) < 2 && abs(ymouse) < 2) {
            if (! prompt_quit) prompt_quit = true;
            else quit_game = true;
        }
        selected_weapon ^= 1;
    }
    // Esc
    if (prompt_quit) {
        if (kreset(gkeys[kc_yes].kc)) quit_game = true;
        if (kreset(gkeys[kc_no].kc)) prompt_quit = false;
    } else if (kreset(gkeys[kc_esc].kc) && (bot[controlled_bot].camp!=-1 || !enable_resurrection || !resurrect())) {
        prompt_quit = true;
    }

    // Engine
#   define INCR .02
    if (kread(gkeys[kc_motormore].kc) && bot[b].thrust <= 1.-INCR) bot[b].thrust += INCR;
    if (kread(gkeys[kc_motorless].kc) && bot[b].thrust >= INCR) bot[b].thrust -= INCR;
#   undef INCR
    // Views
    if (kreset(gkeys[kc_externview].kc)) {
        map_mode = false;
        view = next_external_view(view);
        snd_thrust=-1;
    }
    if (kreset(gkeys[kc_internview].kc)) {
        map_mode = false;
        if (view == VIEW_IN_PLANE) {
            view = VIEW_DOGFIGHT;
        } else {
            view = VIEW_IN_PLANE;
            snd_thrust=-1;
        }
    }
    if (kreset(gkeys[kc_travelview].kc)) {
        float zs;
        map_mode = false;
        view = VIEW_STANDING;
        copyv(&obj[0].pos,&obj[bot[viewed_bot].vion].rot.x);
        mulv(&obj[0].pos,300+drand48()*600+extcam_dist);
        copyv(&u,&obj[bot[viewed_bot].vion].rot.y);
        mulv(&u,(drand48()-.5)*600);
        addv(&obj[0].pos,&u);
        copyv(&u,&obj[bot[viewed_bot].vion].rot.z);
        mulv(&u,(drand48()-.5)*600);
        addv(&obj[0].pos,&u);
        addv(&obj[0].pos,&obj[bot[viewed_bot].vion].pos);
        if (obj[0].pos.z<(zs=z_ground(obj[0].pos.x,obj[0].pos.y, false)+100)) obj[0].pos.z=zs;
        snd_thrust=-1;
    }
    if (kreset(gkeys[kc_nextbot].kc)) {
        if (view == VIEW_ANYTHING_CHEAT) {
            if (++viewed_obj >= nb_obj) viewed_obj = 0;
        } else if (view == VIEW_DOGFIGHT) {
            next_dog_bot();
        } else {
            do {
                if (++viewed_bot>=NBBOT) viewed_bot=0;
            } while (!enable_view_enemy && bot[viewed_bot].camp!=camp);  // pas controlled_bot.camp car peut etre tue
            snd_thrust=-1;
            if (bot[viewed_bot].camp==-1) playsound(VOICE_MOTOR, SAMPLE_FEU, 1., &voices_in_my_head, true, true);
        }
    }
    if (kreset(gkeys[kc_prevbot].kc)) {
        if (view == VIEW_ANYTHING_CHEAT) {
            if (--viewed_obj<0) viewed_obj = nb_obj-1;
        } else if (view == VIEW_DOGFIGHT) {
            prev_dog_bot();
        } else {
            do {
                if (--viewed_bot<0) viewed_bot=NBBOT-1;
            } while (!enable_view_enemy && bot[viewed_bot].camp!=camp);
            snd_thrust=-1;
            if (bot[viewed_bot].camp==-1) playsound(VOICE_MOTOR, SAMPLE_FEU, 1., &voices_in_my_head, true, true);
        }
    }
    if (kreset(gkeys[kc_mybot].kc)) {
        if (view != VIEW_DOGFIGHT) {
            viewed_bot = b;
            snd_thrust = -1;
        } else {
            float d;
            int DBi, DBm;
            next_dog_bot();
            d=DogBotDist;
            DBi=DogBot; DBm=DogBot;
            do {
                next_dog_bot();
                if (DogBotDist<d && bot[DogBot].camp!=bot[controlled_bot].camp) {
                    d=DogBotDist;
                    DBm=DogBot;
                }
            } while (DogBot!=DBi);
            DogBot=DBm; DogBotDist=d;
        }
    }
    if (!accelerated_mode || frame_count > 64) {
        if (kread(gkeys[kc_zoomout].kc)) {
            if (! map_mode) extcam_dist += 10.;
            else zoom += win_center_x/6;
        }
        if (kread(gkeys[kc_zoomin].kc)) {
            if (! map_mode && extcam_dist > 10.) extcam_dist -= 10.;
            else if ((zoom -= win_center_x/6) < win_center_x) zoom = win_center_x;
        }
        if (kread(gkeys[kc_riseview].kc)) {
            if (! map_mode) {
                if ((sight_teta -= .2) < -M_PI) sight_teta += 2*M_PI;
            } else if ((map_y += 1 + (3*win_width)/zoom) > MAP_LEN/2) {
                map_y = MAP_LEN/2;
            }
        }
        if (kread(gkeys[kc_lowerview].kc)) {
            if (! map_mode) {
                if ((sight_teta += .2) > M_PI) sight_teta -= 2*M_PI;
            } else if ((map_y -= 1 + (3*win_width)/zoom) < -MAP_LEN/2) {
                map_y = -MAP_LEN/2;
            }
        }
        if (kread(gkeys[kc_rightenview].kc)) {
            if (! map_mode) {
                if ((sight_phi -= .2) < -M_PI) sight_phi += 2*M_PI;
            } else if ((map_x += 1 + (3*win_width)/zoom) > MAP_LEN/2) {
                map_x = MAP_LEN/2;
            }
        }
        if (kread(gkeys[kc_leftenview].kc)) {
            if (! map_mode) {
                if ((sight_phi += .2) > M_PI) sight_phi -= 2*M_PI;
            } else if ((map_x -= 1 + (3*win_width)/zoom) < -MAP_LEN/2) {
                map_x = -MAP_LEN/2;
            }
        }
    }
    if (view != VIEW_DOGFIGHT) {
        if (kreset(gkeys[kc_towardview].kc)) { sight_teta = sight_phi = 0; }
        if (kreset(gkeys[kc_backview].kc)) { sight_teta = 0; sight_phi = M_PI; }
        if (kreset(gkeys[kc_leftview].kc)) { sight_teta = 0; sight_phi = M_PI*.5; }
        if (kreset(gkeys[kc_rightview].kc)) { sight_teta = 0; sight_phi = -M_PI*.5; }
        if (kreset(gkeys[kc_upview].kc)) { sight_teta = -M_PI/2; sight_phi = 0; }
    } else {
        view_predef = false;
        if (kread(gkeys[kc_towardview].kc)) { view_predef = true; sight_teta = sight_phi = 0; }
        if (kread(gkeys[kc_backview].kc)) { view_predef = true; sight_teta = 0; sight_phi = M_PI; }
        if (kread(gkeys[kc_leftview].kc)) { view_predef = true; sight_teta = 0; sight_phi = M_PI*.5; }
        if (kread(gkeys[kc_rightview].kc)) { view_predef = true; sight_teta = 0; sight_phi = -M_PI*.5; }
        if (kread(gkeys[kc_upview].kc)) { view_predef = true; sight_teta = -M_PI/2; sight_phi = 0; }
        if (! view_predef) sight_teta = sight_phi = 0;
    }
    view_instruments = kread(gkeys[kc_movetowardview].kc);
    // Commands
    if (kreset(gkeys[kc_gear].kc)) bot[b].but.gear^=1;
    if (kreset(gkeys[kc_flaps].kc)) {
        bot[b].but.flap^=1;
        playsound(VOICE_GEAR, SAMPLE_BIPBIP, 1., &obj[bot[b].vion].pos, false, false);
    }
    bot[b].but.brakes=kread(gkeys[kc_brakes].kc);
    if (kreset(gkeys[kc_business].kc)) bot[b].but.business = 1;
    if (kreset(gkeys[kc_autopilot].kc)) {
        autopilot = ! autopilot;
        playsound(VOICE_GEAR, SAMPLE_BIPBIP, 1., &obj[bot[b].vion].pos, false, false);
        if (autopilot) {
            bot[controlled_bot].target_speed = BEST_SPEED_FOR_CONTROL;
            bot[controlled_bot].target_rel_alt = 100. * ONE_METER;
        }
    }
    // Game control
    if (kreset(gkeys[kc_pause].kc)) {
        gtime_toggle();
        game_paused = ! game_paused;
    }
    draw_high_scores = kread(gkeys[kc_highscores].kc);
    if (kreset(gkeys[kc_accelmode].kc)) { accelerated_mode = ! accelerated_mode; frame_count&=63; }
    if (kreset(gkeys[kc_basenav].kc)) {
        bot[b].u = obj[bot[b].babase].pos;
    }
    if (kreset(gkeys[kc_mapmode].kc)) {
        map_mode = ! map_mode;
        playsound(VOICE_GEAR, SAMPLE_BIPBIP3, 1., &voices_in_my_head, true, false);
    }
    if (kreset(gkeys[kc_suicide].kc) && bot[controlled_bot].camp!=-1) explode(bot[viewed_bot].vion, 0, "commited suicide");
    if (kreset(gkeys[kc_markpos].kc)) bot[b].but.mark=1;
    // Cheats
    if (cheat_mode && kread(gkeys[kc_alti].kc)) {
        obj[bot[viewed_bot].vion].pos.z += 500;
        bot[viewed_bot].vionvit.z = 0;
    }
    if (cheat_mode && kreset(gkeys[kc_gunned].kc)) bot[viewed_bot].gunned=controlled_bot;
    if (!autopilot && !map_mode) {
        if (enable_mouse) {
            bot[b].xctl = ((xmouse-win_center_x)/(double)win_center_x);
            bot[b].yctl = ((ymouse-win_center_y)/(double)win_center_y);
        } else {
            int i=0;
            i=kread(gkeys[kc_left].kc);
            i+=kread(gkeys[kc_right].kc)<<1;
            i+=kread(gkeys[kc_down].kc)<<2;
            i+=kread(gkeys[kc_up].kc)<<3;
            if (i) {
                CtlSensActu += CtlSensitiv;
                if (i&1) bot[b].xctl-=CtlSensActu;
                if (i&2) bot[b].xctl+=CtlSensActu;
                if (i&4) bot[b].yctl-=CtlSensActu;
                if (i&8) bot[b].yctl+=CtlSensActu;
            } else CtlSensActu=0;
            if (bot[b].xctl<-1 || bot[b].xctl>1 || bot[b].yctl<-1 || bot[b].yctl>1) CtlSensActu=0;
            if (!(i&3)) bot[b].xctl*=CtlAmortis;
            if (!(i&12)) bot[b].yctl=CtlYequ+(bot[b].yctl-CtlYequ)*CtlAmortis;
            if (kread(gkeys[kc_center].kc)) {
                bot[b].xctl=0;
                bot[b].yctl=CtlYequ;
                if (kread(gkeys[kc_down].kc) && CtlYequ>-1) CtlYequ-=.02;
                if (kread(gkeys[kc_up].kc) && CtlYequ<1) CtlYequ+=.02;
            }
        }
    } else {    // autopilot or map_mode
        if (autopilot) {
            robot_autopilot(b);
        } else {
            robot_safe(b, SAFE_LOW_ALT);
        }
    }
    CLAMP(bot[b].xctl, 1.);
    CLAMP(bot[b].yctl, 1.);
}
コード例 #25
0
ファイル: tell.c プロジェクト: nbmc/DOGL
static object cmd(string str, object body) {
  string msg, fail;
  object char;
# ifdef ENABLE_INTERMUD3
  string mud, found_mud, *arr, name;
# endif /* ENABLE_INTERMUD3 */

  fail = "";

# ifdef ENABLE_INTERMUD3
  if(sscanf(str, "%s@%s", name, msg) == 2) {
    /* Possable intermud3 tell. */
    name = to_lower(name);
    if(!intermud3_connected()) {
      fail += "The Intermud3 connection is currently down.\n";
    } else if(sscanf(msg, "'%s' %s", mud, msg) == 2) {
      /* Quoted mud name in string */
      if(!(found_mud = valid_mud(mud))) {
        fail += "There is no mud named '" + mud +
            "' on the Intermud3 network.\n";
      } else if(!strlen(msg)) {
        fail += "Unable to send an empty message to mud '" + mud + "'\n";
      } else if(sscanf(msg, ":%s", msg)) {
        /* Found an emoteto message. */
        switch(send_emoteto("$N " + msg, found_mud, name, body->query_name())) {
          case 0:
            fail += "The Intermud3 connection is currently down.\n";
          break;

          case -1:
            fail += "There is no mud named '" + found_mud +
                "' on the Intermud3 network.\n";
          break;

          case 1:
            return success("You tell " + name + "@" + found_mud + ": " +
                body->query_name() + " " + msg + "\n");
          break;
        }
      } else {
        switch(send_tell_message(msg, found_mud, name, body->query_name())) {
          case 0:
            fail += "The Intermud3 connection is currently down.\n";
          break;

          case -1:
            fail += "There is no mud named '" + found_mud +
                "' on the Intermud3 network.\n";
          break;

          case 1:
            return success("You tell " + name + "@" + found_mud + ": " +
                msg + "\n");
          break;
        }
      }
    } else {
      /* Unquoted mud name in string so it could match multiple muds */
      arr = explode(msg, " ");
      mud = arr[0];
      arr = arr[1..];
      while(sizeof(arr)) {
        if(!(found_mud = valid_mud(mud))) {
          mud += " " + arr[0];
          arr = arr[1..];
        } else {
          break;
        }
      }
コード例 #26
0
ファイル: main.cpp プロジェクト: Nomad280279/vsxu
int main(int argc, char* argv[])
{
  app_argc = argc;
  app_argv = argv;
  int     width, height, running, frames, x, y;
  double  t, t1;
  char    titlestr[ 200 ];

  // Initialise GLFW
  glfwInit();

  bool start_fullscreen = false;
  int x_res = 1280;
  int y_res = 720;
  bool manual_resolution_set = false;
  for (int i = 1; i < argc; i++)
  {
    vsx_string arg1 = argv[i];
    if (arg1 == "--help" || arg1 == "/?" || arg1 == "-help" || arg1 == "-?")
    {
      printf(
             "Usage:\n"
          "  vsxu_player [path_to_vsx_file]\n"
          "\n"
          "Flags: \n"
          "  -pl        Preload all visuals on start \n"
          "  -dr        Disable randomizer     \n"
          "  -p [x,y]   Set window position x,y \n"
          "  -s [x,y]   Set window size x,y \n\n\n"
            );
      exit(0);
    } else
    if (arg1 == "-f") {
      start_fullscreen = true;
    } else
    if (arg1 == "-pl") {
      option_preload_all = true;
    } else
    if (arg1 == "-dr") {
      disable_randomizer = true;
    } else
    if (arg1 == "-no") {
      no_overlay = true;
    } else
    if (arg1 == "-s")
    {
      if (i+1 < argc)
      {
        i++;
        vsx_string arg2 = argv[i];
        vsx_avector<vsx_string> parts;
        vsx_string deli = ",";
        explode(arg2, deli, parts);
        if (parts.size() == 2)
        {
          x_res = vsx_string_helper::s2i(parts[0]);
          y_res = vsx_string_helper::s2i(parts[1]);
          manual_resolution_set = true;
        } else
        {
          deli = "x";
          explode(arg2, deli, parts);
          if ( parts.size() == 2 )
          {
            x_res = vsx_string_helper::s2i(parts[0]);
            y_res = vsx_string_helper::s2i(parts[1]);
            manual_resolution_set = true;
          }
        }
      }
    }
  }
  if (start_fullscreen && !manual_resolution_set)
  {
    // try to get the resolution from the desktop for fullscreen
    GLFWvidmode video_mode;
    glfwGetDesktopMode(&video_mode);
    x_res = video_mode.Height;
    y_res = video_mode.Width;
  }
  
  // Open OpenGL window
  glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4);
  if( !glfwOpenWindow( x_res, y_res, 0,0,0,0,16,0, start_fullscreen?GLFW_FULLSCREEN:GLFW_WINDOW ) ) // GLFW_FULLSCREEN
  {
    printf("Error! Could not create an OpenGL context. Please check your GPU drivers...\n");
    glfwTerminate();
    return 0;
  }

  glewInit();

  if (start_fullscreen) glfwEnable( GLFW_MOUSE_CURSOR );
  app_init(0);

  glfwEnable(GLFW_AUTO_POLL_EVENTS);

  for (int i = 1; i < argc; i++) {
    vsx_string arg1 = argv[i];
    if (arg1 == "-p") {
      if (i+1 < argc)
      {
        i++;
        vsx_string arg2 = argv[i];
        vsx_avector<vsx_string> parts;
        vsx_string deli = ",";
        explode(arg2, deli, parts);
        glfwSetWindowPos( vsx_string_helper::s2i(parts[0]), vsx_string_helper::s2i(parts[1]) );
      }
    }
  }

  glfwSetKeyCallback(&key_event);
  glfwSetMouseButtonCallback(&mouse_button_event);
  glfwSetMousePosCallback(&mouse_pos_event);
  glfwSetCharCallback(&key_char_event);
  glfwSetMouseWheelCallback(&mouse_wheel);
  // set window size callback function
  glfwSetWindowSizeCallback(window_size);

  // Enable sticky keys
  glfwEnable( GLFW_STICKY_KEYS );
  glfwSwapInterval(1);

  // Main loop
  running = GL_TRUE;
  frames = 0;

  #if PLATFORM_FAMILY == PLATFORM_FAMILY_UNIX
    sprintf( titlestr, "Vovoid VSXu Player %s [GNU/Linux %d-bit]", vsxu_ver, PLATFORM_BITS);
  #endif
  #if PLATFORM_FAMILY == PLATFORM_FAMILY_WINDOWS
    sprintf( titlestr, "Vovoid VSXu Player %s [Windows %d-bit]", vsxu_ver, PLATFORM_BITS);
  #endif
  glfwSetWindowTitle( titlestr );


  while( running )
  {
    if (mouse_pos_type)
    {
      if (mouse_pos_type == 1) app_mouse_move(last_x,last_y);
      else app_mouse_move_passive(last_x,last_y);
      mouse_pos_type = 0;
    }

    app_pre_draw();

    // Get time and mouse position
    t = glfwGetTime();
    glfwGetMousePos( &x, &y );
    float delta = t-t1;
    t1 = t;
    if (key_pressed != -1)
    {
          //printf("%f\n", delta);
      key_time += delta;
      if (key_time > 0.3f)
      {
        key_repeat_time += delta;
        if (key_repeat_time > initial_key_delay)
        {
          key_repeat_time = 0.0f;
          if (key_character != -1)
            app_char(key_character);
          app_key_down((long)key_pressed);
          initial_key_delay *= 0.99f;
              //printf("repeating key: %d\n", key_character);
        }
      }
    }
    frames ++;

    // Get window size (may be different than the requested size)
    glfwGetWindowSize( &width, &height );
    height = height > 0 ? height : 1;

    // Set viewport
    vsx_gl_state::get_instance()->viewport_set( 0, 0, width, height );

    // Clear color buffer
    glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
    glClear( GL_COLOR_BUFFER_BIT );
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    app_draw(0);

    glfwSwapBuffers();

    // Check if the ESC key was pressed or the window was closed
    running = /*!glfwGetKey( GLFW_KEY_ESC ) &&*/
    glfwGetWindowParam( GLFW_OPENED );
  }

  // Close OpenGL window and terminate GLFW
  glfwTerminate();

  return 0;
}
コード例 #27
0
ファイル: variables.cpp プロジェクト: TeoTwawki/dltcep
int CChitemDlg::check_dialog(int check_or_scan)
{
  CString *lines;
  CString tmp;
  journal_type journal;
  int fh;
  int ret, gret;
  int linecount;
  int i,j;
  trigger trigger;
  action action;
  int num_or, strref;
  int first, last;
  loc_entry tmploc;
  bool got_continue;
  bool warn = (chkflg&WARNINGS)==0;

  gret=0;
  if(check_or_scan!=SCANNING)
  {
    if(check_or_scan==CHECKING) //no JOURNAL
    {
      //checking state headers
      for(i=0;i<the_dialog.statecount;i++)
      {
        switch(check_reference(the_dialog.dlgstates[i].actorstr,1,1,0))
        {
        case 1:
          log("Actor has invalid text in state #%d",i);
          gret=TREESTATE|i;
          break;
        case 2: case 5:
          log("Actor has no included text in state #%d",i);
          gret=TREESTATE|i;
        }
        
        if(chkflg&NOSTRUCT) continue;
        if(the_dialog.dlgstates[i].trnumber<1)
        {        
          log("No transitions in state #%d",i);
          gret=TREESTATE|i;
          continue;
        }
        num_or=the_dialog.dlgstates[i].trnumber+the_dialog.dlgstates[i].trindex;
        if(num_or<1 || num_or>the_dialog.transcount)
        {
          log("Invalid last index of transitions (%d) in state #%d",num_or,i);
          gret=TREESTATE|i;
          continue;
        }

        got_continue = false;
        first = the_dialog.dlgstates[i].trindex;
        last = first + the_dialog.dlgstates[i].trnumber;
        
        for (j=first;j<last;j++)
        {
          num_or=the_dialog.dlgtrans[j].flags;
          if(!(num_or&HAS_TEXT))
          {
            if ((j!=first) && got_continue && !(num_or&HAS_TRIGGER) )
            {
              log("Unconditional continue in state #%d (response #%d) overlaps a previous continue!", i, j);
              //gret=TREESTATE|i;
              gret=TRANSSTATE|j;
            }
            got_continue = true;
          }
        }
      }
    }
    //checking transition headers
    for(i=0;i<the_dialog.transcount;i++)
    {
      num_or=the_dialog.dlgtrans[i].flags;
      if(the_dialog.dlgtrans[i].playerstr<=0)
      {
        if(num_or&HAS_TEXT)
        {
          log("Transition #%d has no player string set, despite flags.",i);
          gret=TRANSSTATE|i;
        }
      }
      else
      {
        if(!(num_or&HAS_TEXT) )
        {
          log("Transition #%d has player string set, but no flags.",i);
          gret=TRANSSTATE|i;
        }
      }
      
      //checking transition trigger reference
      j=the_dialog.dlgtrans[i].trtrindex;
      if(j<0 || j>=the_dialog.header.numtrtrigger)
      {
        if(num_or&HAS_TRIGGER)
        {
          log("Transition #%d has a wrong trigger index (%d).",i,j);
          gret=TRANSSTATE|i;
        }
      }
      else if(j)
      {
        if(!(num_or&HAS_TRIGGER) && warn)
        {
          log("Transition #%d has trigger index (%d), but no flags.",i,j);
          gret=TRANSSTATE|i;
        }
      }
      
      //checking action reference
      j=the_dialog.dlgtrans[i].actionindex;
      if(j<0 || j>=the_dialog.header.numaction)
      {
        if((num_or&HAS_ACTION) )
        {
          log("Transition #%d has a wrong action index (%d).",i,j);
          gret=TRANSSTATE|i;
        }
      }
      else if(j)
      {
        if(!(num_or&HAS_ACTION) && warn)
        {
          log("Transition #%d has action index (%d), but no flags.",i,j);
          gret=TRANSSTATE|i;
        }
      }
      
      //checking journal string ref
      strref=the_dialog.dlgtrans[i].journalstr;
      if(strref<=0)
      {
        if(num_or&HAS_JOURNAL)
        {
          log("Transition #%d has no journal string set, despite flags.",i);
          gret=TRANSSTATE|i;
        }
      }
      else
      {
        if(!(num_or&HAS_JOURNAL) )
        {
          log("Transition #%d has journal string set, but no flags.",i);
          gret=TRANSSTATE|i;
        }
        else
        {
          if((check_or_scan==JOURNAL))
          {
            if((num_or&(HAS_QUEST|HAS_SOLVED))==HAS_QUEST)
            {
              if(journals.Lookup(strref,journal))
              {
                if(!journal.string.IsEmpty())
                {
                  if (journal.string.Find(itemname)<0)
                  {
                    journal.string+=", "+itemname;
                  }
                  journal.type|=HAS_QUEST;
                  journals[strref]=journal;
                }
              }
              else
              {
                journal.type=HAS_QUEST;
                journal.string=itemname;
                journals[strref]=journal;
              }
            }
            else
            {
              journal.type=0;
              journals.Lookup(strref,journal);
              journal.type|=num_or&(HAS_QUEST|HAS_SOLVED);
              journal.string="";
              journals[strref]=journal;
            }
            continue;
          }
        }
        
        switch(check_reference(strref,2,10,0) )
        {
        case 1:
          log("Invalid journal string in transition #%d (reference: %d).",i, strref);
          gret=TRANSSTATE|i;
          break;
        case 2:
          log("Deleted journal string in transition #%d (reference: %d).",i, strref);
          gret=TRANSSTATE|i;
          break;
        case 3:
          //if this isn't a quest journal entry, don't complain about missing title
          if ((num_or&(HAS_QUEST|HAS_SOLVED))!=0)
          {
            log("Titleless journal string in transition #%d (reference: %d).",i, strref);
            gret=TRANSSTATE|i;
          }
          break;
        }
      }
      
      //checking dialog linkage
      RetrieveResref(tmp,the_dialog.dlgtrans[i].nextdlg);
      num_or=the_dialog.dlgtrans[i].stateindex;
      if(the_dialog.dlgtrans[i].flags&LEAF_NODE)
      {
        if(!tmp.IsEmpty())
        {
          log("External dialog linkage %s:%d for leaf node (state #%d)",tmp,num_or,i);
          gret=TRANSSTATE|i;
        }
      }
      else
      {
        if(tmp==SELF_REFERENCE)
        {
          if(the_dialog.header.numstates<=num_or)
          {
            log("Invalid internal link to state %d in transition %d",num_or,i);
            gret=TRANSSTATE|i;
          }
        }
        else
        {
          if(dialogs.Lookup(tmp,tmploc) )
          {
            fh=locate_file(tmploc,0);
            if(the_dialog.CheckExternalLink(fh,num_or) )
            {
              log("Invalid external link to %s:state %d in transition %d",tmp,num_or,i);
              gret=TRANSSTATE|i;
            }
            close(fh);
          }
          else
          {
            log("Invalid dialog reference: %s in transition %d",tmp,i);
            gret=TRANSSTATE|i;
          }
        }
      }
    }
  }
  //syntax checking scripts
  if(check_or_scan!=JOURNAL)
  {
    for(i=0;i<the_dialog.sttriggercount;i++)
    {
      lines=explode(the_dialog.sttriggers[i], '\n', linecount);
      if(linecount==-1)
      {
        log("Out of memory");
        return -1;
      }
      num_or=0;
      for(j=0;j<linecount;j++)
      {
        if(lines[j].IsEmpty())
        {
          ret=-44; //empty top level condition
        }
        else
        {
          ret=compile_trigger(lines[j], trigger);
          if(!pst_compatible_var())
          {
            if((trigger.opcode&0x3fff)==TR_OR)
            {
              if(num_or)
              {
                ret=-42;
              }
              num_or=trigger.bytes[0];
              if (num_or<2 && check_or_scan!=SCANNING)
              {
                ret=-47;
              }
            }
            else if(num_or) num_or--;
          }
        }
        if(ret)
        {
          if(check_or_scan!=SCANNING)
          {
            log("Invalid top level condition: %s at line #%d in %d. state trigger block (%s)", lines[j],j+1,i, get_compile_error(ret));
            gret=STATETR|i; //found errors
          }
        }
        else
        {
          ret=check_or_scan_trigger(&trigger, handle_trigger(trigger.opcode), check_or_scan, j);
          if(ret && (check_or_scan!=SCANNING) )
          {
            log("Top level condition was: %s", lines[j]);
            gret=STATETR|i;
          }
        }
      }
      if(num_or)
      {
        log("Error: %s",get_compile_error(-42));
        gret=STATETR|i;
      }
      if(lines) delete[] lines;
    }
    
    for(i=0;i<the_dialog.trtriggercount;i++)
    {
      lines=explode(the_dialog.trtriggers[i], '\n', linecount);
      if(linecount==-1)
      {
        log("Out of memory");
        return -1;
      }
      num_or=0;
      for(j=0;j<linecount;j++)
      {
        ret=compile_trigger(lines[j], trigger);
        if(!pst_compatible_var())
        {
          if((trigger.opcode&0x3fff)==TR_OR)
          {
            if(num_or) ret=-42;
            num_or=trigger.bytes[0];
            if (num_or<2 && check_or_scan!=SCANNING)
            {
              ret=-47;
            }
          }
          else if(num_or) num_or--;
        }
        if(ret)
        {        
          if(check_or_scan!=SCANNING)
          {
            log("Invalid trigger: %s in line #%d in %d. transition trigger block (%s)",lines[j],j+1,i,  get_compile_error(ret));
            gret=TRANSTR|i;
          }
        }
        else
        {
          ret=check_or_scan_trigger(&trigger, handle_trigger(trigger.opcode), check_or_scan, j);
          if(ret && (check_or_scan!=SCANNING) )
          {
            tmp = lasterrormsg;
            log("Transition trigger was: %s", lines[j]);
            lasterrormsg = tmp + "\n" + lasterrormsg;
            gret=TRANSTR|i;
          }
        }
      }
      if(num_or)
      {
        log("Invalid trigger: in line #%d in %d. transition trigger block (%s)",j, i, get_compile_error(-42));
        gret=TRANSTR|i;
      }
      if(lines) delete[] lines;
    }
  }
  //num_or stores the previous action opcode initializing it to non-special
  num_or=0; 

  for(i=0;i<the_dialog.actioncount;i++)
  {
    lines=explode(the_dialog.actions[i], '\n', linecount);
    if(linecount==-1)
    {
      log("Out of memory");
      return -1;
    }

    for(j=0;j<linecount;j++)
    {
      ret=compile_action(lines[j], action, false);
      if(ret)
      {
        if(check_or_scan!=CHECKING) continue;
        log("Invalid action: %s in line #%d in %d. action block (%s)", lines[j],j+1,i,get_compile_error(ret));
        gret=ACTIONBL|i;
      }
      else
      {
        if(check_or_scan!=JOURNAL)
        {
          ret=check_or_scan_action(&action, handle_action(action.opcode), check_or_scan, j);
          if(check_or_scan!=CHECKING) continue;
          if(ret)
          {
            log("Action was: %s", lines[j]);
            gret=ACTIONBL|i;
            continue;
          }
        }
      }
      
      if(check_or_scan==JOURNAL)
      {
        switch(action.opcode)
        {
        case AC_REMOVE_JOURNAL_IWD:case AC_QUESTDONE_IWD:
          if(has_xpvar())
          {
            journal.type=0;
            journals.Lookup(action.bytes[0], journal);
            journal.string="";
            journal.type|=HAS_SOLVED;
            journals[action.bytes[0]]=journal;
          }
          break;
        case AC_REMOVE_JOURNAL_BG: case AC_QUESTDONE_BG:
          if(!has_xpvar())
          {
            journal.type=0;
            journals.Lookup(action.bytes[0], journal);
            journal.string="";
            journal.type|=HAS_SOLVED;
            journals[action.bytes[0]]=journal;
          }
          break;
        case AC_ADD_JOURNAL:
          if(has_xpvar() || (action.bytes[3]==JT_QUEST))
          {
            if(journals.Lookup(action.bytes[0],journal))
            {
              if(!journal.string.IsEmpty())
              {
                if (journal.string.Find(itemname)<0)
                {
                  journal.string+=", "+itemname;
                }
              }
              journal.type|=HAS_QUEST;
              journals[action.bytes[0]]=journal;
            }
            else
            {
              journal.string=itemname;
              journal.type=HAS_QUEST;
              journals[action.bytes[0]]=journal;
            }
          }
          else
          {
            if (action.bytes[3]==JT_DONE)
            {
              journal.type=0;
              journals.Lookup(action.bytes[0],journal);
              journal.string="";
              journal.type|=HAS_SOLVED;
              journals[action.bytes[0]]=journal;
            }
          }    
        }
        continue;
      }

      if(chkflg&NOCUT) continue;
      if(action.opcode==AC_STCUTMD)
      {
        if((num_or!=AC_CLRACT) && (num_or!=AC_CLRALLACT))
        {
          log("Invalid action: StartCutSceneMode() without ClearActions() in line #%d in %d. action block", j+1,i);
          gret=ACTIONBL|i;
        }
        else if(action.opcode==AC_STARTCUT)
        {
          if(num_or!=AC_STCUTMD)
          {
            log("StartCutScene() without StartCutSceneMode() in line #%d in %d. action block", j+1,i);
            gret=ACTIONBL|i;
          }
        }
      }
      if((action.opcode==AC_STCUTMD) || (action.opcode==AC_STARTCUT) || (action.opcode==AC_CLRACT) || (action.opcode==AC_CLRALLACT)) num_or=action.opcode;
    }
    if(lines) delete[] lines;
  }

  return gret;
}
コード例 #28
0
int AnswerMachineFactory::onLoad()
{
  AmConfigReader cfg;
  if(cfg.loadFile(add2path(AmConfig::ModConfigPath,1, MOD_NAME ".conf")))
    return -1;

  // get application specific global parameters
  configureModule(cfg);

  DefaultVMMode = cfg.getParameterInt("default_vm_mode",DefaultVMMode);
  SimpleMode = cfg.getParameter("simple_mode") == "yes";

  // smtp_server
  SmtpServerAddress = cfg.getParameter("smtp_server",SmtpServerAddress);
  
  // smtp_port
  if(cfg.hasParameter("smtp_port")){
    if(sscanf(cfg.getParameter("smtp_port").c_str(),
	      "%u",&SmtpServerPort) != 1) {
      ERROR("invalid smtp_port specified\n");
      return -1;
    }
  }
  
  DBG("SMTP server set to %s:%u\n",
      SmtpServerAddress.c_str(), SmtpServerPort);

#ifdef USE_MYSQL

  /* Get email templates from MySQL */

  string mysql_server, mysql_user, mysql_passwd, mysql_db;

  mysql_server = cfg.getParameter("mysql_server");
  if (mysql_server.empty()) {
    mysql_server = "localhost";
  }

  mysql_user = cfg.getParameter("mysql_user");
  if (mysql_user.empty()) {
    ERROR("voicemail.conf parameter 'mysql_user' is missing.\n");
    return -1;
  }

  mysql_passwd = cfg.getParameter("mysql_passwd");
  if (mysql_passwd.empty()) {
    ERROR("voicemail.conf parameter 'mysql_passwd' is missing.\n");
    return -1;
  }

  mysql_db = cfg.getParameter("mysql_db");
  if (mysql_db.empty()) {
    mysql_db = "sems";
  }

  try {

    Connection.connect(mysql_db.c_str(), mysql_server.c_str(),
                      mysql_user.c_str(), mysql_passwd.c_str());
    if (!Connection) {
      ERROR("Database connection failed: %s\n", Connection.error());
      return -1;
    }
    Connection.set_option(mysqlpp::Connection::opt_reconnect, true);
  }

  catch (const mysqlpp::Exception& er) {
    // Catch-all for any MySQL++ exceptions
    ERROR("MySQL++ error: %s\n", er.what());
    return -1;
  }

  if(loadEmailTemplatesFromMySQL()){
    ERROR("while loading email templates from MySQL\n");
    return -1;
  }

#else

  /* Get email templates from file system */
  
  if(loadEmailTemplates(cfg.getParameter("email_template_path",
					 DEFAULT_MAIL_TMPL_PATH))){
    ERROR("while loading email templates\n");
    return -1;
  }

  AnnouncePath    = cfg.getParameter("announce_path");
  DefaultAnnounce = cfg.getParameter("default_announce");

#endif

  MaxRecordTime   = cfg.getParameterInt("max_record_time",DEFAULT_RECORD_TIME);
  RecFileExt      = cfg.getParameter("rec_file_ext",DEFAULT_AUDIO_EXT);

  MessageStorage = NULL;
  MessageStorage = AmPlugIn::instance()->getFactory4Di("msg_storage");
  if(NULL == MessageStorage){
    INFO("could not load msg_storage. Voice Box mode will not be available.\n");
  } else {
    if ((msg_storage = MessageStorage->getInstance()) == NULL) {
      ERROR("getting msg_storage instance\n");
      return -1;
    }
  }

  TryPersonalGreeting = 
    cfg.getParameter("try_personal_greeting") == "yes";

  DBG("voicemail will %stry to find a personal greeting.\n", 
      TryPersonalGreeting?"":"not ");

  MailHeaderVariables = explode(cfg.getParameter("mail_header_vars"), ";");
  if (MailHeaderVariables.size()) {
    DBG("variables that will be substituted from " PARAM_HDR " header:\n");
    for (vector<string>::iterator it=
	   MailHeaderVariables.begin(); it != MailHeaderVariables.end(); it++) {
      DBG("         %s\n", it->c_str());
    }
  }    

  DBG("Starting SMTP daemon\n");
  AmMailDeamon::instance()->start();
  
  string s_save_empty_msg = cfg.getParameter("box_save_empty_msg");
  if (!s_save_empty_msg.empty()) {
    SaveEmptyMsg = !(s_save_empty_msg == "no");
  }
  DBG("Voicebox will%s save empty messages.\n", 
      SaveEmptyMsg?"":" not");

  // override email address
  EmailAddress = cfg.getParameter("email_address");

  return 0;
}
コード例 #29
0
bool Application::initialize( int argc, char **argv )
{
    // this is used when hunting for memory leaks
#ifdef YAF3D_ENABLE_HEAPCHECK
    // trigger debugger
    //__asm int 3;
#endif

    std::string arg_levelname;
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments( &argc,argv );
    osg::ArgumentParser::Parameter levelparam( arg_levelname );
    arguments.read( "-level", arg_levelname ); // read the level file if one given

    int   argpos;
    // set proper game mode
    GameState::get()->setMode( GameState::Standalone );
    if ( ( argpos = arguments.find( "-server" ) ) != 0 )
    {
        GameState::get()->setMode( GameState::Server );
        arguments.remove( argpos );
    }
    else if ( ( argpos = arguments.find( "-client" ) ) != 0 )
    {
        GameState::get()->setMode( GameState::Client );
        arguments.remove( argpos );
    }

    // note: before beginning to initialize the framework modules the media path must be set,
    //  other modules need it for loading resources etc.
    //-------------------
    std::vector< std::string > path;
    std::string dir;
    {
        char* p_env = getenv( YAF3D_ENV_MEDIA_DIR );
        if ( p_env )
        {
            _mediaPath = p_env;
        }
        else
        {
            dir = getCurrentWorkingDirectory();
            dir = cleanPath( dir );
            dir += "/";
            path.clear();
            explode( dir, "/", &path );
#ifdef LINUX
            dir = "/";
#endif
#ifdef WIN32
            dir = "";
#endif
            for ( size_t cnt = 0; cnt < path.size() - 2; ++cnt )
                dir += path[ cnt ] + "/";

            dir.erase( dir.size() -1 );
            _mediaPath = dir;
            _mediaPath += YAF3D_MEDIA_PATH;
        }
    }

    //-------------------
    // set the ful binary path of application
    _fulBinaryPath = arguments.getApplicationName();
    _fulBinaryPath = cleanPath( _fulBinaryPath );
    _fulBinaryPath = _fulBinaryPath.substr( 0, _fulBinaryPath.rfind( '/' ) );
    //-------------------

    // load the standard configuration before changing to 'Initializing' state
    Configuration::get()->load();

    // set game state
    _p_gameState->setState( GameState::Initializing );

    // setup log system
    {
        std::string loglevel;
        Log::Level  level = Log::L_ERROR;

        // get the log level from configuration
        Configuration::get()->getSettingValue( YAF3D_GS_LOG_LEVEL, loglevel );

        // check if we have to report an invalid log level in configuration
        if ( loglevel == "error" )
            level = Log::L_ERROR;
        else if ( loglevel == "warning" )
            level = Log::L_WARNING;
        else if ( loglevel == "debug" )
            level = Log::L_DEBUG;
        else if ( loglevel == "info" )
            level = Log::L_INFO;
        else if ( loglevel == "verbose" )
            level = Log::L_VERBOSE;
        else
            log_warning << "Application: configuration contains an invalid log level, possible values are: error, warning, debug, info, verbose. set to error." << std::endl;

        // create log sinks with configured log level
        if ( GameState::get()->getMode() != GameState::Server )
            log.addSink( "file", getMediaPath() + std::string( LOG_FILE_NAME ), level );
        else
            log.addSink( "file", getMediaPath() + std::string( LOG_FILE_NAME_SERVER ), level );

        // only the server needs an console stdout
#ifdef YAF3D_HAS_CONSOLE
        log.addSink( "stdout", std::cout, level );
#endif

    }

    log.enableSeverityLevelPrinting( false );
    log_info << std::endl;
    log << " *******************************************"    << std::endl;
    log << " * yaf3d -- Yet another Framework 3D       *"    << std::endl;
    log << " * version: " << std::string( YAF3D_VERSION ) << "                          *"  << std::endl;
    log << " * project: Yag2002                        *"    << std::endl;
    log << " * site:    http://yag2002.sourceforge.net *"    << std::endl;
    log << " * contact: [email protected]               *"    << std::endl;
    log << " *******************************************"    << std::endl;
    log << "" << std::endl;
    log.enableSeverityLevelPrinting( true );

    log << "Application: time " << yaf3d::getTimeStamp();

    // print cpu info
    {
        std::stringstream cpuinfo;
        cpuinfo << "Application: CPU supports ";
        if ( SDL_HasRDTSC() )
            cpuinfo << "RDTSC ";
        if ( SDL_HasMMX() )
            cpuinfo << "MMX ";
        if ( SDL_HasMMXExt() )
            cpuinfo << "MMXExt ";
        if ( SDL_Has3DNow() )
            cpuinfo << "3DNow ";
        if ( SDL_Has3DNowExt() )
            cpuinfo << "3DNowExt ";
        if ( SDL_HasSSE() )
            cpuinfo << "SSE ";
        if ( SDL_HasSSE2() )
            cpuinfo << "SSE2 ";
        if ( SDL_HasAltiVec() )
            cpuinfo << "AltiVec ";

        log << cpuinfo.str() << std::endl;
    }

    log << "Application: initializing viewer" << std::endl;
    log << "Application: using media path: " << _mediaPath << std::endl;

    // setup the viewer
    //----------

    // load the display settings
    Configuration::get()->getSettingValue( YAF3D_GS_SCREENWIDTH,  _screenWidth  );
    Configuration::get()->getSettingValue( YAF3D_GS_SCREENHEIGHT, _screenHeight );
    Configuration::get()->getSettingValue( YAF3D_GS_FULLSCREEN,   _fullScreen   );
    unsigned int colorBits = 24;
    Configuration::get()->getSettingValue( YAF3D_GS_COLORBITS, colorBits );

    // set the icon and caption title only for non-servers
    if ( GameState::get()->getMode() != GameState::Server )
    {
       // init SDL with video
        SDL_Init( SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE );

        // set application window's title
        _appWindowTitle = YAF3D_APP_TITLE " " YAF3D_VERSION;
        setWindowTitle( _appWindowTitle );

        SDL_Surface* p_bmpsurface = SDL_LoadBMP( YAF3D_APP_ICON );
        if ( p_bmpsurface )
        {
            Uint32 col = SDL_MapRGB( p_bmpsurface->format, 255, 255, 255 );
            SDL_SetColorKey( p_bmpsurface, SDL_SRCCOLORKEY, col );
            SDL_WM_SetIcon( p_bmpsurface, NULL );
        }
    }
    else
    {
        // init SDl witout video for server
        SDL_Init( SDL_INIT_NOPARACHUTE );
    }
    // enable unicode translation
    SDL_EnableUNICODE( 1 );
    SDL_EnableKeyRepeat( SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL ); // enable key repeating

    _p_viewer = new osgSDL::Viewer;
    _rootSceneNode = new osg::Group;
    _rootSceneNode->setName( "_topSceneGroup_" );
    osgSDL::Viewport*   p_viewport = new osgSDL::Viewport( _rootSceneNode.get() );
    osgUtil::SceneView* p_sceneView = p_viewport->getSceneView();
    p_sceneView->setDefaults( osgUtil::SceneView::COMPILE_GLOBJECTS_AT_INIT );
    _p_viewer->addViewport( p_viewport );
    _p_viewer->requestContinuousUpdate( true ); // force event generation for FRAMEs, we need this for animations, etc.

    int flags = SDL_HWSURFACE;
    if ( _fullScreen )
        flags |= SDL_FULLSCREEN;

    _p_viewer->setDisplayMode( _screenWidth, _screenHeight, colorBits, flags );
    _p_viewer->setCursorEnabled( false );
    //------------

    // setup keyboard map
    std::string keybType;
    Configuration::get()->getSettingValue( YAF3D_GS_KEYBOARD, keybType );
    log_info << "Application: setup keyboard map to: " << keybType << std::endl;
    if ( keybType == YAF3D_GS_KEYBOARD_ENGLISH )
        KeyMap::get()->setup( KeyMap::English );
    else
        KeyMap::get()->setup( KeyMap::German );

    // get the instance of gui manager
    _p_guiManager = GuiManager::get();
    // setup networking
    _p_networkDevice = NetworkDevice::get();
    // avoid creating of remote clients so long we are initializing the system
    _p_networkDevice->lockObjects();
    if ( GameState::get()->getMode() == GameState::Server )
    {
        log_info << "Application: loading level file '" << arg_levelname << "'" << std::endl;
        // load the level and setup things
        osg::ref_ptr< osg::Group > sceneroot = LevelManager::get()->loadLevel( YAF3D_LEVEL_SERVER_DIR + arg_levelname );
        if ( !sceneroot.valid() )
            return false;

        // start networking before setting up entities
        std::string servername;
        Configuration::get()->getSettingValue( YAF3D_GS_SERVER_NAME, servername );
        NodeInfo nodeinfo( arg_levelname, servername );
        unsigned int channel = 0;
        Configuration::get()->getSettingValue( YAF3D_GS_SERVER_PORT, channel );

        // try to setup server
        try
        {
            _p_networkDevice->setupServer( channel, nodeinfo );
        }
        catch ( const NetworkException& e )
        {
            log_error << "Application: error starting server, reason: " << e.what() << std::endl;
            return false;
        }

        // complete level loading
        LevelManager::get()->finalizeLoading();

        // the server needs no drawing
        _p_viewer->setUpdateAllViewports( false );
    }
    else if ( GameState::get()->getMode() == GameState::Client )
    {
        std::string url;
        Configuration::get()->getSettingValue( YAF3D_GS_SERVER_IP, url );
        std::string clientname( "vrc-client" );
        NodeInfo nodeinfo( "", clientname );
        unsigned int channel = 0;
        Configuration::get()->getSettingValue( YAF3D_GS_SERVER_PORT, channel );

        // try to setup client networking
        try
        {
            _p_networkDevice->setupClient( url, channel, nodeinfo );
        }
        catch ( const NetworkException& e )
        {
            log_error << "Application: error setting up client networking, reason: " << e.what() << std::endl;
            return false;
        }

        // now load level
        std::string levelname = YAF3D_LEVEL_CLIENT_DIR + _p_networkDevice->getNodeInfo()->getLevelName();
        log_info << "Application: loading level file '" << levelname << "'" << std::endl;
        // load the level and setup things
        osg::ref_ptr< osg::Group > sceneroot = LevelManager::get()->loadLevel( levelname );
        if ( !sceneroot.valid() )
            return false;
        // complete level loading
        LevelManager::get()->finalizeLoading();

        // if we directly start a client with cmd line option then we must send a leave-menu notification to entities
        //  as many entities do special steps when leaving the menu
        EntityNotification notification( YAF3D_NOTIFY_MENU_LEAVE );
        EntityManager::get()->sendNotification( notification );
    }
    else // check for any level file name, so we try to start in Standalone mode
    {
        std::string defaultlevel = arg_levelname.length() ? ( std::string( YAF3D_LEVEL_SALONE_DIR ) + arg_levelname ) : std::string( YAF3D_DEFAULT_LEVEL );
        log_info << "Application: loading level file '" << defaultlevel << "'" << std::endl;
        // set game mode
        GameState::get()->setMode( GameState::Standalone );
        // load the level and setup things
        osg::ref_ptr< osg::Group > sceneroot = LevelManager::get()->loadLevel( defaultlevel );
        if ( !sceneroot.valid() )
            return false;
        // complete level loading
        LevelManager::get()->finalizeLoading();

        // if we directly start a level with cmd line option then we must send a leave-menu notification to entities
        //  as many entities do special steps when leaving the menu
        if ( arg_levelname.length() )
        {
            EntityNotification notification( YAF3D_NOTIFY_MENU_LEAVE );
            EntityManager::get()->sendNotification( notification );
        }
    }

    return true;
}
コード例 #30
0
ファイル: projectile.cpp プロジェクト: AkiraofAstra/Torque3D
void Projectile::simulate( F32 dt )
{         
   if ( isServerObject() && mCurrTick >= mDataBlock->lifetime )
   {
      deleteObject();
      return;
   }
   
   if ( mHasExploded )
      return;

   // ... otherwise, we have to do some simulation work.
   RayInfo rInfo;
   Point3F oldPosition;
   Point3F newPosition;

   oldPosition = mCurrPosition;
   if ( mDataBlock->isBallistic )
      mCurrVelocity.z -= 9.81 * mDataBlock->gravityMod * dt;

   newPosition = oldPosition + mCurrVelocity * dt;

   // disable the source objects collision reponse for a short time while we
   // determine if the projectile is capable of moving from the old position
   // to the new position, otherwise we'll hit ourself
   bool disableSourceObjCollision = (mSourceObject.isValid() && mCurrTick <= SourceIdTimeoutTicks);
   if ( disableSourceObjCollision )
      mSourceObject->disableCollision();
   disableCollision();

   // Determine if the projectile is going to hit any object between the previous
   // position and the new position. This code is executed both on the server
   // and on the client (for prediction purposes). It is possible that the server
   // will have registered a collision while the client prediction has not. If this
   // happens the client will be corrected in the next packet update.

   // Raycast the abstract PhysicsWorld if a PhysicsPlugin exists.
   bool hit = false;

   if ( mPhysicsWorld )
      hit = mPhysicsWorld->castRay( oldPosition, newPosition, &rInfo, Point3F( newPosition - oldPosition) * mDataBlock->impactForce );            
   else 
      hit = getContainer()->castRay(oldPosition, newPosition, csmDynamicCollisionMask | csmStaticCollisionMask, &rInfo);

   if ( hit )
   {
      // make sure the client knows to bounce
      if ( isServerObject() && ( rInfo.object->getTypeMask() & csmStaticCollisionMask ) == 0 )
         setMaskBits( BounceMask );

      // Next order of business: do we explode on this hit?
      if ( mCurrTick > mDataBlock->armingDelay || mDataBlock->armingDelay == 0 )
      {
         MatrixF xform( true );
         xform.setColumn( 3, rInfo.point );
         setTransform( xform );
         mCurrPosition    = rInfo.point;
         mCurrVelocity    = Point3F::Zero;

         // Get the object type before the onCollision call, in case
         // the object is destroyed.
         U32 objectType = rInfo.object->getTypeMask();

         // re-enable the collision response on the source object since
         // we need to process the onCollision and explode calls
         if ( disableSourceObjCollision )
            mSourceObject->enableCollision();

         // Ok, here is how this works:
         // onCollision is called to notify the server scripts that a collision has occurred, then
         // a call to explode is made to start the explosion process. The call to explode is made
         // twice, once on the server and once on the client.
         // The server process is responsible for two things:
         //    1) setting the ExplosionMask network bit to guarantee that the client calls explode
         //    2) initiate the explosion process on the server scripts
         // The client process is responsible for only one thing:
         //    1) drawing the appropriate explosion

         // It is possible that during the processTick the server may have decided that a hit
         // has occurred while the client prediction has decided that a hit has not occurred.
         // In this particular scenario the client will have failed to call onCollision and
         // explode during the processTick. However, the explode function will be called
         // during the next packet update, due to the ExplosionMask network bit being set.
         // onCollision will remain uncalled on the client however, therefore no client
         // specific code should be placed inside the function!
         onCollision( rInfo.point, rInfo.normal, rInfo.object );
         explode( rInfo.point, rInfo.normal, objectType );

         // break out of the collision check, since we've exploded
         // we don't want to mess with the position and velocity
      }
      else
      {
         if ( mDataBlock->isBallistic )
         {
            // Otherwise, this represents a bounce.  First, reflect our velocity
            //  around the normal...
            Point3F bounceVel = mCurrVelocity - rInfo.normal * (mDot( mCurrVelocity, rInfo.normal ) * 2.0);
            mCurrVelocity = bounceVel;

            // Add in surface friction...
            Point3F tangent = bounceVel - rInfo.normal * mDot(bounceVel, rInfo.normal);
            mCurrVelocity  -= tangent * mDataBlock->bounceFriction;

            // Now, take elasticity into account for modulating the speed of the grenade
            mCurrVelocity *= mDataBlock->bounceElasticity;

            // Set the new position to the impact and the bounce
            // will apply on the next frame.
            //F32 timeLeft = 1.0f - rInfo.t;
            newPosition = oldPosition = rInfo.point + rInfo.normal * 0.05f;
         }
      }
   }

   // re-enable the collision response on the source object now
   // that we are done processing the ballistic movement
   if ( disableSourceObjCollision )
      mSourceObject->enableCollision();
   enableCollision();

   if ( isClientObject() )
   {
      emitParticles( mCurrPosition, newPosition, mCurrVelocity, U32( dt * 1000.0f ) );
      updateSound();
   }

   mCurrDeltaBase = newPosition;
   mCurrBackDelta = mCurrPosition - newPosition;
   mCurrPosition = newPosition;

   MatrixF xform( true );
   xform.setColumn( 3, mCurrPosition );
   setTransform( xform );
}