Exemple #1
0
/*
	Update()
*/
BOOL CId3v1Tag::Update(void)
{
	BOOL bFlag = FALSE;
	
	if(!strnull(m_ID3v1) && !strnull(m_szFileName))
	{
		UpdateTagFromTags();
		{
			CBinFileEx file;

			if(file.Open(m_szFileName,FALSE))
			{
				if(file.SeekEx((LONGLONG)sizeof(m_ID3v1) * -1L,FILE_END))
					if(file.Write(m_ID3v1,sizeof(m_ID3v1))!=FILE_EOF)
						bFlag = TRUE;
				
				file.Close();
			}
		}
	}
	
	return(bFlag);
}
Exemple #2
0
static void test_get_user_creds_one(const char *id, const char *name, uid_t uid, gid_t gid, const char *home, const char *shell) {
        const char *rhome = NULL;
        const char *rshell = NULL;
        uid_t ruid = UID_INVALID;
        gid_t rgid = GID_INVALID;
        int r;

        log_info("/* %s(\"%s\", \"%s\", "UID_FMT", "GID_FMT", \"%s\", \"%s\") */",
                 __func__, id, name, uid, gid, home, shell);

        r = get_user_creds(&id, &ruid, &rgid, &rhome, &rshell, 0);
        log_info_errno(r, "got \"%s\", "UID_FMT", "GID_FMT", \"%s\", \"%s\": %m",
                       id, ruid, rgid, strnull(rhome), strnull(rshell));
        if (!synthesize_nobody() && streq(name, NOBODY_USER_NAME)) {
                log_info("(skipping detailed tests because nobody is not synthesized)");
                return;
        }
        assert_se(r == 0);
        assert_se(streq_ptr(id, name));
        assert_se(ruid == uid);
        assert_se(rgid == gid);
        assert_se(path_equal(rhome, home));
        assert_se(path_equal(rshell, shell));
}
Exemple #3
0
void YesKick ()
{
	if( !self->k_kicking )
		return;

	if ( !self->k_playertokick || strnull(self->k_playertokick->classname) ) {
        NextClient();
		return;
	}

	if( DoKick( self->k_playertokick, self ) && self->k_playertokick == self )
		return; // selfkick success ;)

	NextClient();
}
Exemple #4
0
void readgsp(void)
{
    stream istr;

    istr = stropen(getparam("gsp"), "r");
    get_history(istr);
    gsp = ggsp = get_gsprof(istr);
    strclose(istr);
    if (! strnull(getparam("grav"))) {
        istr = stropen(getparam("grav"), "r");
        get_history(istr);
        ggsp = get_gsprof(istr);
        strclose(istr);
    }
}
Exemple #5
0
static dbyte
s_file_mode (const char *filename)
{
#   if (defined (__WINDOWS__))
    DWORD
        dwfa;
    dbyte
        mode;

    assert (filename);
    if (s_system_devicename (filename))
        return (0);                     //  Not allowed on device names

    dwfa = GetFileAttributes (filename);
    if (dwfa == 0xffffffff)
        return (0);
    mode = 0;

    if (dwfa & FILE_ATTRIBUTE_DIRECTORY)
        mode |= S_IFDIR;
    else
        mode |= S_IFREG;
    if (!(dwfa & FILE_ATTRIBUTE_HIDDEN))
        mode |= S_IREAD;
    if (!(dwfa & FILE_ATTRIBUTE_READONLY))
        mode |= S_IWRITE;
    if (s_dos_exe_file (filename))
        mode |= S_IEXEC;
    return (mode);
#   else
    static struct stat
        stat_buf;

    assert (filename);
    if (strnull (filename))
        return (0);
    else
    if (stat ((char *) filename, &stat_buf) == 0)
        return ((dbyte) stat_buf.st_mode);
    else
        return (0);
#   endif
}
Exemple #6
0
// multi kick
void m_kick ()
{
	int i, k;
	gedict_t *p;
	char arg_x[1024], *str;
	int argc = trap_CmdArgc();

    if( !is_adm( self ) )
    {
        G_sprint(self, 2, "You are not an admin\n");
        return;
    }

	trap_CmdArgv( 1, arg_x, sizeof( arg_x ) );

	if ( argc < 2 || !only_digits(arg_x) ) {
        G_sprint(self, 2, "mkick <id1 [id2 [id3 ...]] [reason]>\n");
		return;
	}

	for ( k = 0, i = 1; i < argc; i++ ) {
		trap_CmdArgv( i, arg_x, sizeof( arg_x ) );

		if ( !only_digits(arg_x) )
			break;

		if ( !(p = SpecPlayer_by_id( atoi(arg_x) )) && !(p = not_connected_by_id( atoi(arg_x) )) ) {
			G_sprint(self, 2, "mkick: client %s not found\n", arg_x);
			continue;
		}

		if( !DoKick( p, self ) )
			continue;

		k++;
	}

	if ( !k )
		return;

	if ( !strnull( str = params_str(i, -1) ) ) // show reason
		G_bprint(2, "\x90%s\x91\n", str);
}
Exemple #7
0
// ktpro (c)
void force_spec()
{
	qbool found = false;
	gedict_t *p = NULL;
	char *c_fs, arg_2[1024];
	int i_fs, argc = trap_CmdArgc();

	if ( !is_adm( self ) )
		return;

	trap_CmdArgv( 1, arg_2, sizeof( arg_2 ) );
	c_fs = (argc >= 2 ? arg_2 : ezinfokey(self, "fs"));

	if ( strnull( c_fs ) ) {
		G_sprint(self, 2, "set setinfo \"fs\" properly\n");
		G_sprint(self, 2, "to force spec all not ready players\n");
		G_sprint(self, 2, "type: %s\n", redtext("setinfo fs \"*\""));
		G_sprint(self, 2, "or: %s to force spec specified player\n", redtext("setinfo fs \"playername\""));
		G_sprint(self, 2, "or just: %s\n", redtext("/force_spec \"playername\""));
		return;
	}

	if ( streq( c_fs, "*") || streq( c_fs, "* ") ) {
		//ok move all not ready players to specs
		for( p = world; (p = find_plr( p )); ) {
			if ( p->ready || p == self )
				continue;

			found = true;
			do_force_spec(p, self, true);
		}
	}
	else {
		p = ( (i_fs = atoi( c_fs ) ) < 0 ? spec_by_id( -i_fs ) : SpecPlayer_by_IDorName( c_fs ));
		if ( p ) {
			found = true;
			do_force_spec(p, self, p->ct != ctSpec);
		}
	}

	if ( !found ) 
		G_sprint(self, 2, "can't find specified players\n");
}
Exemple #8
0
int main(int argc, string argv[])
{
  stream fstr, istr, ostr;
  gsprof *gsp;
  bodyptr btab = NULL, p;
  int nbody;
  real tnow, r;
  string intags[MaxBodyFields];

  initparam(argv, defv);
  layout_body(bodyfields, Precision, NDIM);
  fstr = stropen(getparam("gsp"), "r");
  get_history(fstr);
  gsp = get_gsprof(fstr);
  istr = stropen(getparam("in"), "r");
  get_history(istr);
  if (! get_snap(istr, &btab, &nbody, &tnow, intags, TRUE))
    error("%s: snapshot input failed\n", getargv0());
  if (! set_member(intags, PosTag))
    error("%s: position data missing\n", getargv0());
  if (streq(getparam("option"), "rho"))
    for (p = btab; p < NthBody(btab, nbody); p = NextBody(p))
      Aux(p) = rho_gsp(gsp, absv(Pos(p)));
  else if (streq(getparam("option"), "drho"))
    for (p = btab; p < NthBody(btab, nbody); p = NextBody(p))
      Aux(p) = drho_gsp(gsp, absv(Pos(p)));
  else if (streq(getparam("option"), "mass"))
    for (p = btab; p < NthBody(btab, nbody); p = NextBody(p))
      Aux(p) = mass_gsp(gsp, absv(Pos(p)));
  else if (streq(getparam("option"), "phi"))
    for (p = btab; p < NthBody(btab, nbody); p = NextBody(p))
      Aux(p) = phi_gsp(gsp, absv(Pos(p)));
  else 
    error("%s: unknown option %s\n", getargv0(), getparam("option"));
  if (! strnull(getparam("out"))) {
    ostr = stropen(getparam("out"), "w");
    put_history(ostr);
    put_snap(ostr, &btab, &nbody, &tnow, set_union(bodyfields, intags));
    strclose(ostr);
  }
  return (0);
}
Exemple #9
0
MODULE get_command (THREAD *thread)
{
    char
        *value;
    tcb = thread-> tcb;                 /*  Point to thread's context        */
    strcrop (buffer);
    strlwc  (buffer);
    value = strskp (buffer);
    if (value != buffer)
        strcpy (buffer, value);

    if (strnull (buffer))
        the_next_event = none_event;
    else
    if (streq (buffer, "help"))
        the_next_event = help_event;
    else
    if (strchr (buffer, '?'))
        the_next_event = help_event;
    else
    if (strncmp (buffer, "set server", 10) == 0)
        the_next_event = server_ip_event;
    else
    if (streq (buffer, "set debug"))
        the_next_event = debug_event;
    else
    if (streq (buffer, "set recursive"))
        the_next_event = recursive_event;
    else
    if (streq (buffer, "exit"))
        the_next_event = exit_event;
    else
    if (streq (buffer, "quit"))
        the_next_event = exit_event;
    else
      {
        if (strchr (buffer, ' ') != NULL)
            the_next_event = invalid_event;
        else
            the_next_event = request_event;
      }
}
Exemple #10
0
/*  ---------------------------------------------------------------------[<]-
    Function: service_main

    Synopsis: This routine performs the service initialization and then calls
              the user defined service_start() routine to perform majority
              of the work.
    ---------------------------------------------------------------------[>]-*/
static char *
service_get_config_filename (const char *binary_name)
{
    char 
        *res = NULL;

    if (!binary_name || strnull(binary_name))
        return NULL;

    /* we allocate 4 extra char to append the ".cfg" extension */
    res = mem_alloc (strlen(binary_name) + 4 + 1);
    if (res)
      {
        strcpy (res, binary_name);
        strip_file_path (res);
        res = fixed_extension (res, res, "cfg");
      }

    return res;
}
Exemple #11
0
void AdminKick ()
{
	int argc = trap_CmdArgc();

    if( !is_adm( self ) )
    {
        G_sprint(self, 2, "You are not an admin\n");
        return;
    }

    if( self->k_kicking ) {
        ExitKick( self );
		return;
	}

	if ( argc >= 2 ) {
		gedict_t *p;
		char arg_2[1024], *str;

		trap_CmdArgv( 1, arg_2, sizeof( arg_2 ) );

		if ( !(p = SpecPlayer_by_IDorName( arg_2 )) && !(p = not_connected_by_IDorName( arg_2 )) ) {
			G_sprint(self, 2, "kick: client %s not found\n", arg_2);
			return;
		}

		if ( DoKick( p, self ) && !strnull( str = params_str(2, -1) ) ) // show reason
			G_bprint(2, "\x90%s\x91\n", str);

		return;
	}

    G_sprint(self, 2, "Kicking process started\n"
					  "�����������������������\n"
					  "Type \371 to kick, \356 for next, %s to leave\n", redtext("kick"));

    self->k_kicking = g_globalvars.time;
    self->k_playertokick = world;

    NextClient();
}
Exemple #12
0
stream execmap(string prog)
{
  int handle[2];
  char handbuf[32];
  string names[] = { MassTag, NULL }, exprs[] = { NULL, NULL };

  exprs[0] = getparam("mass");
  buildmap(prog, names, exprs, NULL, NULL, Precision, NDIM, TRUE);
  pipe(handle);
  if (fork() == 0) {                            // if this is child process
    close(handle[0]);
    sprintf(handbuf, "-%d", handle[1]);
    execl(prog, getargv0(), getparam("in"), handbuf, getparam("times"),
	  getparam("require"), MassTag "," PosTag,
	  strnull(getparam("require")) ? "true" : "false",
	  getparam("seed"), NULL);
    error("%s: execl %s failed\n", getargv0(), prog);
  }
  close(handle[1]);
  sprintf(handbuf, "-%d", handle[0]);
  return (stropen(handbuf, "r"));
}
Exemple #13
0
/* <crt_help>:
 * We assume that the calling program uses a HELP-library!!
 * This procedure interfaces to the HELP-dialog by clearing the screen,
 * calling HELP, and restoring the screen on exit.
 *
 * If 'library' is null, this program ultimately will be installed, and use the
 * standard VMS help-library.  However, if it is not currently run from the
 * system-directory, then we must assume this is a test-run, from a private
 * directory.  In this case, assume the help-library is in the same directory
 * as the program is run from.
 */
void	crt_help (char *library, char *program)
{
	char	pathname[MAX_PATH], *c_;

	if (! library)
	{
		if (! whoami (pathname, 4))
		{
			strcpy (strnull(pathname), "HELPLIB.HLB");
			if (canopen (library = pathname))
			{
				warn ("Cannot open %s", pathname);
				return;
			}
		}
	}

	crt_quit (FALSE);
	crt__ED (1,1);
	help (library, program, crt_width());
	crt_refresh();
}
Exemple #14
0
int main(int argc, string argv[])
{
  stream outstr = NULL;
  int nmodel;
  real tzero = 0.0;

  initparam(argv, defv);
  layout_body(bodyfields, Precision, NDIM);
  npol = getdparam("n");
  mpol = getdparam("m");
  nbody = getiparam("nbody");
  btab = (bodyptr) allocate(nbody * SizeofBody);
  init_random(getiparam("seed"));
  nmodel = getiparam("nmodel");
  if (! ((npol == 1.0 && mpol == -1.0) ||
	 (npol == 0.5 && mpol == -0.5)))
    polysolve(getdparam("hstep"), getbparam("listmodel"));
  if (! strnull(getparam("out"))) {
    outstr = stropen(getparam("out"), "w");
    put_history(outstr);
  }
  while (--nmodel >= 0) {
    if (npol == 1.0 && mpol == -1.0)
      polymodel1();
    else if (npol == 0.5 && mpol == -0.5)
      polymodel2();
    else
      polymodel();
    if (getbparam("besort"))
      qsort(btab, nbody, SizeofBody, berank);
    if (getbparam("zerocm"))
      snapcenter(btab, nbody, MassField.offset);
    if (outstr != NULL)
      put_snap(outstr, &btab, &nbody, &tzero, bodyfields);
    fflush(outstr);
  }
  return (0);
}
Exemple #15
0
/*
	Load()

	Carica l'oggetto immagine nel controllo.
*/
BOOL CDibCtrl::Load(CImage* pImage,BOOL bRebuildPalette/*=TRUE*/,BOOL bClearBeforeDraw/*=TRUE*/)
{
	CWaitCursor cursor;
	m_bValidDib = FALSE;
	
	// verifica se e' stata chiamata la Load() da file
	if(!strnull(m_szLibraryName))
	{
		m_ImageFactory.Delete();
		m_pImage = NULL;
		memset(m_szLibraryName,'\0',sizeof(m_szLibraryName));
	}

	// se e' stato passato un oggetto valido
	if(pImage)
	{
		m_bValidDib = TRUE;

		// non crea nessun oggetto nuovo ma usa quello ricevuto in input
		m_pImage = pImage;
		
		// usa lo stesso oggetto per ogni immagine, per cui occhio con il parametro per ricalcolare la paletta
		m_ImageDraw.SetImage(m_pImage);
		
		if(bRebuildPalette)
		{
			m_ImageDraw.BuildLogPalette();
			RealizePalette(FALSE);
		}
		
		Paint(bClearBeforeDraw);
	}

	if(!m_bValidDib)
		Clear();

	return(m_bValidDib);
}
Exemple #16
0
void vote_check_map ()
{
	int   vt_req = get_votes_req( OV_MAP, true );
	char  *m  = "";

	if ( maps_voted_idx < 0 || strnull( m = GetMapName(maps_voted[maps_voted_idx].map_id) ) )
		return;

	if ( !k_matchLess )
	if ( match_in_progress )
		return;

	if ( maps_voted[maps_voted_idx].admins )
		G_bprint(2, "%s\n", redtext("Admin veto"));
	else if( !vt_req  )
		G_bprint(2, "%s votes for mapchange.\n", redtext("Majority"));
	else
		return;

	vote_clear( OV_MAP );

	changelevel( m );
}
Exemple #17
0
MODULE check_recipient_left (THREAD *thread)
{
    static char
        buffer[512];
  
    tcb = thread-> tcb;                 /*  Point to thread's context        */
    
    mem_free (tcb-> next_recipient);
    tcb-> next_recipient = NULL;
    
    getstrfld (tcb-> rcpt_uids,
               tcb-> rcpt_cnt++,
               0,
               ",;",
               buffer);

    if (strnull (buffer))
        the_next_event = no_event;
    else
      {
        the_next_event = yes_event;
        tcb-> next_recipient = mem_strdup (buffer);
      }
}
Exemple #18
0
local void newrun(void)
{
  eps = getdparam("eps");			// get input parameters
  dtime = getdparam("dtime");
  nstatic = getiparam("nstatic");
#if !defined(QUICKSCAN)
  theta = getdparam("theta");
#endif
  usequad = getbparam("usequad");
  tstop = getdparam("tstop");
  dtout = getdparam("dtout");
  options = getparam("options");
  outputs = getparam("outputs");
  if (! strnull(infile))			// if data file was given
    inputdata();				// then read inital data
  else {					// else make initial data
    nbody = getiparam("nbody");			// get number of bodies
    init_random(getiparam("seed"));		// set random number gen.
    testdata();					// and make plummer model
  }
  rsize = 1.0;					// start root w/ unit cube
  nstep = 0;					// begin counting steps
  tout = tnow;					// schedule first output
}
Exemple #19
0
// KTX has in-built modifications to several maps - frogbot routing relies on entity order so we have
//   to customise again here.  Called after all markers created, but before traveltime calculations
static void CustomiseFrogbotMap (void)
{
	gedict_t* ent = NULL;

	// KTX may have added a quad, so to keep routes compatible with PR1-version, we add it as a marker after others
	if (streq(g_globalvars.mapname, "aerowalk") && !FrogbotOptionEnabled(FB_OPTION_EDITOR_MODE))
	{
		gedict_t* quad = ez_find (world, "item_artifact_super_damage");
		if (quad) {
			gedict_t* nearest_marker;

			quad->fb.fl_marker = false;
			nearest_marker = LocateMarker (quad->s.v.origin);
			quad->fb.fl_marker = true;
			StartItemFB (quad);
			quad->fb.T |= MARKER_DYNAMICALLY_ADDED;

			// Quad is in same zone as nearest marker, and linked by the first path that's valid
			SetZone (nearest_marker->fb.Z_, quad->fb.index + 1);
			SetGoalForMarker (18, quad);
			AddPath (nearest_marker, quad);
			AddPath (quad, nearest_marker);

			SpawnMarkerIndicator (quad);
		}
	}

	// We stopped it from removing the telespawn earlier on...
	if (!cvar ("k_end_tele_spawn") && streq ("end", g_globalvars.mapname)) {
		vec3_t      TS_ORIGIN = { -392, 608, 40 }; // tele spawn
		gedict_t*   p = NULL;
		gedict_t*   m = NULL;

		for (p = world; (p = find (p, FOFCLSN, "info_player_deathmatch")); ) {
			if (VectorCompare (p->s.v.origin, TS_ORIGIN)) {
				p->classname = "info_player_deathmatch_removed";

				// Remove any spawn marker
				for (m = world; (m = find (m, FOFCLSN, "spawnpoint")); ) {
					if (m->k_lastspawn == p) {
						ent_remove (m);
						break;
					}
				}
				break;
			}
		}
	}

	// Expand bounding box of all items
	if (!isRACE()) {
		for (ent = world; (ent = nextent(ent)); ) {
			if (streq(ent->classname, "info_teleport_destination") ||
				streq(ent->classname, "info_player_deathmatch")) {
				continue;
			}

			if (streq(ent->classname, "marker")) {
				vec3_t mins = { -65, -65, -24 };
				vec3_t maxs = { 65,  65,  32 };
				vec3_t viewoffset = { 80, 80, 24 };
				int i;

				for (i = 0; i < 3; ++i) {
					if (ent->fb.fixed_size[i]) {
						mins[i] = -ent->fb.fixed_size[i] / 2 - (i < 2 ? 15 : 0);
						maxs[i] = ent->fb.fixed_size[i] / 2 - (i < 2 ? 15 : 0);
						viewoffset[i] = (maxs[i] - mins[i]) / 2;
					}
				}
				VectorCopy(viewoffset, ent->s.v.view_ofs);
				setsize(ent, PASSVEC3(mins), PASSVEC3(maxs));
			}
			else if ((int)ent->s.v.flags & FL_ITEM) {
				PlaceItemFB(ent);
			}
		}
	}

	// Link all teleporters
	if (FrogbotOptionEnabled (FB_OPTION_EDITOR_MODE)) {
		for (ent = world; (ent = ez_find (ent, "trigger_teleport")); ) {
			// If this teleport takes us to the marker close to the grenade, set arrow_time
			if (!strnull (ent->target)) {
				gedict_t* target = find (world, FOFS (targetname), ent->target);

				AddPath (ent, target);
			}
		}
	}
}
Exemple #20
0
void ReqAdmin ()
{
    //  check for election
    if( is_elected(self, etAdmin) )
    {
        G_sprint(self, 2, "Abort %sion first\n", redtext("elect"));
        return;
    }

    if( is_adm( self ) )
    {
        G_bprint(2, "%s is no longer an %s\n", self->netname, redtext("admin"));

        if( self->k_kicking )
            ExitKick( self );

        self->k_admin = 0; // ok, remove all admin flags

		on_unadmin( self );

        return;
    }

    if( self->k_adminc )
	{
        G_sprint(self, 2, "%s code canceled\n", redtext("admin"));
    	self->k_adminc = 0;
		return;
	}

	if( !cvar( "k_admins" ) ) {
		G_sprint(self, 2, "%s on this server!\n", redtext("NO admins"));
		return;
	}

	if ( VIP_IsFlags( self, VIP_ADMIN ) ) // this VIP does't required pass
    {
		BecomeAdmin(self, AF_REAL_ADMIN);
		return;
    }
	
	// parse /admin <pass>
	if ( trap_CmdArgc() == 2 ) {
		char arg_2[1024];
		char *pass = cvar_string( "k_admincode" );
		int till = Q_rint(self->k_adm_lasttime + 5 - g_globalvars.time);

		if( self->k_adm_lasttime && till > 0  ) { // probably must help against brute force
			G_sprint(self, 2, "Wait %d second%s!\n", till, count_s(till) );
			return;
		}

		trap_CmdArgv( 1, arg_2, sizeof( arg_2 ) );

		if ( !strnull(pass) && strneq(pass, "none") && streq(arg_2, pass) )
			BecomeAdmin(self, AF_REAL_ADMIN);
		else {
            G_sprint(self, 2, "%s...\n", redtext("Access denied"));
			self->k_adm_lasttime = g_globalvars.time;
		}

		return;
	}

    self->k_adminc = 6;
    self->k_added  = 0;

    // You can now use numbers to enter code
    G_sprint(self, 2, "Use %s or %s to enter code\n", redtext("numbers"), redtext("impulses") );
}
Exemple #21
0
/*
	ParseHeader()

	Analizza l'header ICY, caricando la lista interna con i valori dei campi.
*/
int CIcy::ParseHeader(LPCSTR pIcyHeaderData)
{
	/*
	header icy:

	ICY 200 OK
	icy-notice1:<BR>This stream requires <a href="http://www.winamp.com/">Winamp</a><BR>
	icy-notice2:SHOUTcast Distributed Network Audio Server/SolarisSparc v1.9.2<BR>
	icy-name:Secret Agent: The soundtrack for your stylish, mysterious, dangerous life. For Spys and P.I.'s too! [SomaFM]
	icy-genre:Downtempo Lounge Spy
	icy-url:http://www.somafm.com
	Content-Type:audio/mpeg
	icy-pub:1
	icy-metaint:24576
	icy-br:128

	errori:

	ICY 400 Server Full
	icy-notice1:<BR>SHOUTcast Distributed Network Audio Server/win32 v1.9.2<BR>
	icy-notice2:This server has reached its user limit<BR>

	ICY 403 Service Forbidden
	icy-notice1:<BR>SHOUTcast Distributed Network Audio Server/Linux v1.8.9<BR>
	icy-notice2:The resource requested is forbidden<BR>
	
	streamripper/live365:
	
	http://streamripper.sourceforge.net/dc.php
	http://www.dslreports.com/shownews/3472
	*/
	if(strnicmp(pIcyHeaderData,"ICY",3)!=0 && strnicmp(pIcyHeaderData,"HTTP",4)!=0)
		return(HTTP_STATUS_BAD_REQUEST);
	
	int nCode = 0;
	char szCode[8];
	int i = 0;
	char* p = (char*)pIcyHeaderData;
	// salta per arrivare al codice d'errore dato che con http la risposta inizia con (ad es.): HTTP/1.1 301 [...]
	if(strnicmp(pIcyHeaderData,"HTTP",4)==0)
		p+=8;
	while(*p && !isdigit(*p))
		p++;
	for(i=0; *p && isdigit(*p) && i < sizeof(szCode);)
		szCode[i++] = *p++;
	nCode = atoi(szCode);
	switch(nCode)
	{
		case HTTP_CODE_MOVED_PERMANENTLY:
		case HTTP_CODE_MOVED_TEMPORARILY:
			GetHeaderValue(pIcyHeaderData,"Location",m_szLocation,sizeof(m_szLocation));
			return(nCode);
		default:
			break;
	}

	char* pIcyHeaders[] = {
		"Content-Type:",	// Content-Type: application/octet-stream, Content-Type: audio/mpeg, etc.
		"ice-audio-info",	// ice-audio-info: bitrate=128;samplerate=44100;channels=2
		"icy-br",
		"icy-description",
		"icy-genre",
		"icy-metaint",
		"icy-name",
		"icy-notice1",
		"icy-notice2",
		"icy-pub",
		"icy-url",
		"Server:",		// Server: Icecast 2.3.2 oppure icy-notice2: SHOUTcast Distributed Network Audio Server/win32 v1.9.5<BR>
		"Location:",
		NULL,
	};
	
	m_listICYHeaders.DeleteAll();
	
	for(i=0; pIcyHeaders[i]!=NULL; i++)
	{
		HTTPHEADER* h = (HTTPHEADER*)m_listICYHeaders.Add();
		if(h)
		{
			strcpyn(h->name,pIcyHeaders[i],HTTPHEADER_NAME_LEN+1);
			if(GetHeaderValue(pIcyHeaderData,h->name,h->value,HTTPHEADER_VALUE_LEN)!=0)
			{
				strcpy(h->value,"");
			}
			else
			{
				char buffer[HTTPHEADER_VALUE_LEN+1];
				while(substr(h->value,"<BR>","",buffer,sizeof(buffer))!=0)
					strcpyn(h->value,buffer,HTTPHEADER_VALUE_LEN);
				while(substr(h->value,"<br>","",buffer,sizeof(buffer))!=0)
					strcpyn(h->value,buffer,HTTPHEADER_VALUE_LEN);
			}
			
			TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::ParseHeader(): [%s]->[%s]\n",h->name,h->value));

		}
	}

	if(strnull(GetHeaderValue("Server:")) && stristr(GetHeaderValue("icy-notice2"),"shoutcast") && stristr(GetHeaderValue("icy-notice2"),"server"))
	{
		ITERATOR iter;
		HTTPHEADER* h;

		if((iter = m_listICYHeaders.First())!=(ITERATOR)NULL)
		{
			do
			{
				if((h = (HTTPHEADER*)iter->data)!=(HTTPHEADER*)NULL)
				{
					if(stricmp(h->name,"Server:")==0)
					{
						strcpyn(h->value,GetHeaderValue("icy-notice2"),HTTPHEADER_VALUE_LEN);
						break;
					}
				}

				iter = m_listICYHeaders.Next(iter);
			
			} while(iter!=(ITERATOR)NULL);
		}
	}

	TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"\nCIcy::GetHeaderValue(): Content-Type [%s]\n",GetHeaderValue("Content-Type:")));
	TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): ice-audio-info [%s]\n",GetHeaderValue("ice-audio-info")));
	TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): icy-br [%s]\n",GetHeaderValue("icy-br")));
	TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): icy-description [%s]\n",GetHeaderValue("icy-description")));
	TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): icy-genre [%s]\n",GetHeaderValue("icy-genre")));
	TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): icy-metaint [%s]\n",GetHeaderValue("icy-metaint")));
	TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): icy-name [%s]\n",GetHeaderValue("icy-name")));
	TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): icy-notice1 [%s]\n",GetHeaderValue("icy-notice1")));
	TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): icy-notice2 [%s]\n",GetHeaderValue("icy-notice2")));
	TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): icy-pub [%s]\n",GetHeaderValue("icy-pub")));
	TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): icy-url [%s]\n",GetHeaderValue("icy-url")));
	TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): Server [%s]\n",GetHeaderValue("Server:")));
	TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): Location [%s]\n\n",GetHeaderValue("Location:")));

	return(nCode);
}
Exemple #22
0
Bool
ini_scan_section (
    FILE *inifile,
    char **keyword,
    char **value)
{
    int
        remaining;                      /*  Space remaining in line buffer   */
    char
        *first,
        *valueptr,
        *lineptr;

    /*  Read through file until we find what we are looking for              */
    while (file_read (inifile, iniline)) {
        strcrop (iniline);
        if (strnull (iniline))
            continue;                   /*  Skip empty lines                 */

        /*  Calculate space remaining in buffer after this line; we need to
         *  know this later if we start reading continuation lines.
         */
        remaining = LINE_MAX - strlen (iniline);
            
        first = strskp (iniline);       /*  Skip leading spaces              */
        if (*first == ';' || *first == '#' || *first == 0)
            continue;                   /*  Comment line                     */
        else
        if (*first == '!') {
            first = strskp (first + 1);
            trace (first);
        }
        else                            /*  Have name = value                */
        if (sscanf (first, "[%[^]]", ini_section) == 1) {
            *keyword = strlwc (ini_section);
            *value   = NULL;
            return (FALSE);             /*  New section name                 */
        }
        else
        if (streq (first, "[]")) {      /*  Allow empty section names        */
            strcpy (ini_section, "");
            *keyword = ini_section;
            *value   = NULL;
            return (FALSE);             /*  New section name                 */
        }
        else {
            if (*first == '"') {        /*  Name in quotes                   */
                valueptr = strchr (first + 1, '"');
                if (valueptr) {
                    first++;
                    *valueptr = ' ';
                    valueptr = strchr (valueptr + 1, '=');
                }
            }
            else
                valueptr = strchr (first, '=');

            if (valueptr == NULL) {
                coprintf ("E: illegal definition in ini file");
                return (FALSE);
            }
            *valueptr++ = '\0';
            strcpy (ini_keyword, strcrop (strlwc (first)));
            while (*valueptr == ' ')
                valueptr++;             /*    and leading spaces             */
            
            if (*valueptr == '"') {     /*  Have value in quotes             */
                /*  Get continuation lines as necessary and possible         */
                first = &strlast (valueptr);
                while (*first == '-' && remaining > 0) {
                    if (!file_readn (inifile, first, remaining))
                        break;                  /*  Abrubt end of file       */
                    strcrop (first);
                    remaining -= strlen (first) - 1;
                    first     += strlen (first) - 1;
                } 
                /*  Now find closing quote and terminate value there         */
                for (lineptr = valueptr + 1; *lineptr; lineptr++) {
                    if (*lineptr == '\\')
                        lineptr++;      /*  Ignore next char                 */
                    else
                    if (*lineptr == '"') {
                        lineptr [1] = '\0';
                        break;          /*  Closing quote, end of value      */
                    }
                }
            }
            else {                      /*  Have unquoted value              */
                strconvch (valueptr, ';', '\0');
                strconvch (valueptr, '#', '\0');
            }
            strcrop (valueptr);
            strcpy (ini_value, valueptr);
            *keyword = ini_keyword;
            *value   = ini_value;
            return (TRUE);              /*  Found keyword = value            */
        }
    }
    *keyword = NULL;
    return (FALSE);                     /*  End of file                      */
}
Exemple #23
0
int main(int argc, string argv[])
{
    glutInit(&argc, argv);
    initparam(argv, defv);
    instr = stropen(getparam("in"), "r");
    refscale = getdparam("refscale");
    if (! strnull(getparam("colordata"))) {	/* color data wanted?	    */
        if (getbparam("dopcolor"))
	    error("%s: colordata precludes dopcolor\n", getargv0());
	if (! scanopt(PhiTag "," SmoothTag "," RhoTag "," EntFuncTag ","
		      UinternTag "," UdotIntTag "," UdotRadTag ","
		      UdotVisTag "," TauTag "," BirthTag "," DeathTag ","
		      AuxTag, getparam("colordata")))
	    error("%s: %s unknown\n", getargv0(), getparam("colordata"));
	bodytags[1] = getparam("colordata");	/* replace key w/ field...  */
	butbind[2] = COLORMAP;
    } else if (getbparam("dopcolor")) {
        dopcolor = TRUE;
	bodytags[1] = VelTag;			/* replace key w/ velocity  */
	butbind[2] = COLORMAP;
    }
    if (! strnull(getparam("vectordata"))) {
        if (! scanopt(VelTag "," AccTag "," AuxVecTag,
		      getparam("vectordata")))
	    error("%s: %s unknown\n", getargv0(), getparam("vectordata"));
	if (! (streq(getparam("vectordata"), VelTag) && dopcolor))
	    bodytags[2] = getparam("vectordata");
	butbind[2] = VSCALE;
    }
    maxfast = getiparam("maxfast");
    if (sscanf(getparam("defcolors"), "%x,%x", &pcolor, &bcolor) != 2)
	error("%s: can't scan defcolor parameter\n", getargv0());
    if (sscanf(getparam("viewsize"), "%ix%i", &wscreen, &hscreen) != 2)
	error("%s: can't scan viewsize parameter\n", getargv0());
    layout_body(bodytags, Precision, NDIM);
    if (! strnull(getparam("colordata"))) {
        scalaroff =
	  streq(bodytags[1], PhiTag)     ? PhiField.offset :
	  streq(bodytags[1], SmoothTag)  ? SmoothField.offset :
	  streq(bodytags[1], RhoTag)     ? RhoField.offset :
	  streq(bodytags[1], EntFuncTag) ? EntFuncField.offset :
	  streq(bodytags[1], UinternTag) ? UinternField.offset :
	  streq(bodytags[1], UdotIntTag) ? UdotIntField.offset :
	  streq(bodytags[1], UdotRadTag) ? UdotRadField.offset :
	  streq(bodytags[1], UdotVisTag) ? UdotVisField.offset :
	  streq(bodytags[1], TauTag)     ? TauField.offset :
	  streq(bodytags[1], BirthTag)   ? BirthField.offset :
	  streq(bodytags[1], DeathTag)   ? DeathField.offset :
	  streq(bodytags[1], AuxTag)     ? AuxField.offset : -1;
	assert(scalaroff != -1);
    }
    if (! strnull(getparam("vectordata"))) {
        vectoroff =
	  streq(getparam("vectordata"), VelTag)    ? VelField.offset :
	  streq(getparam("vectordata"), AccTag)    ? AccField.offset :
	  streq(getparam("vectordata"), AuxVecTag) ? AuxVecField.offset : -1;
	assert(vectoroff != -1);
    }
    if (! getdata())
        error("%s: no data in input file\n", getargv0());
    initgraphics(argv[0]);
    glutMainLoop();
    return (0);
}
Exemple #24
0
/*
	Balloon()
*/
void CTrayIcon::Balloon(	LPCSTR	lpcszTitle/* = NULL*/,				// titolo
                            LPCSTR	lpcszText/* = NULL*/,				// testo
                            UINT		nIconType/* = MB_ICONINFORMATION*/,	// icona (nativo: info, warning, errore - esteso: custom)
                            UINT		nTimeout/* = BALLOON_DEFAULT_TIMEOUT*/,	// timeout per rimozione
                            UINT		nIconID/* = (UINT)-1L*/,				// handle x icona custom (esclude il nome file), solo per esteso
                            LPCSTR	lpcszIconFileName/* = NULL*/,			// nome file x icona custom (esclude l'handle), solo per esteso
                            CSize	iconSize/* = CSize(16,16)*/,			// dimensione icona custom, solo per esteso
                            UINT		nCloseIconID/* = (UINT)-1L*/			// id risorsa per icona chiusura, solo per esteso
                       )
{
    // controlla se deve visualizzare o rimuovere il balloon
    BOOL bRemoveBalloon = !lpcszTitle || !lpcszText;

    // il balloon (nativo) richiede win >= 2K
    if(m_nBalloonType==BALLOON_USE_NATIVE)
    {
        // imposta il titolo
        char szTitle[BALLOON_MAX_TOOLTIP_TITLE+1] = {0};
        if(lpcszTitle)
        {
            strcpyn(szTitle,lpcszTitle,sizeof(szTitle));

            // se il testo sfora, sostituisce la fine con [...] (solo se non e' gia' stato accorciato...)
            if(strlen(lpcszTitle) >= BALLOON_MAX_TOOLTIP_TITLE && !strstr(lpcszTitle,ABBREVIATE_DEFAULT_STRING))
            {
                CFilenameFactory fn;
                strcpyn(szTitle,fn.Abbreviate(lpcszTitle,BALLOON_MAX_TOOLTIP_TITLE-1),sizeof(szTitle));
            }
        }

        // imposta il testo
        char szText[BALLOON_MAX_TOOLTIP_TEXT+1] = {0};
        if(lpcszText)
            strcpyn(szText,lpcszText,sizeof(szText));

        // imposta il tipo di icona da utilizzare
        DWORD dwIconType = NIIF_NONE;
        if(!bRemoveBalloon)
        {
            switch(nIconType)
            {
            case MB_ICONINFORMATION:
                dwIconType = NIIF_INFO;
                break;
            case MB_ICONWARNING:
                dwIconType = NIIF_WARNING;
                break;
            case MB_ICONERROR:
                dwIconType = NIIF_ERROR;
                break;
            }
        }

        // ricava il timeout per la rimozione del balloon
        if(!bRemoveBalloon)
        {
            nTimeout = (nTimeout >= 1 && nTimeout <= 30) ? nTimeout : BALLOON_DEFAULT_TIMEOUT;
            nTimeout *= 1000L;
        }
        else
            nTimeout = 0;

        m_nTimeout = nTimeout;

        // imposta il timer per la rimozione del balloon
        if(!bRemoveBalloon)
            if(nTimeout!=0)
            {
                if(m_nTimerId!=0L)
                {
                    ::KillTimer(AfxGetMainWnd()->m_hWnd,m_nTimerId);
                    m_nTimerId = 0L;
                }

                m_nTimerId = ::SetTimer(AfxGetMainWnd()->m_hWnd,(UINT)this,m_nTimeout,(TIMERPROC)BalloonTimerProc);
            }

        // notifica al sistema i cambi relativi al balloon
        m_NotifyIconData.uFlags = NIF_INFO;
        if(!bRemoveBalloon)
        {
            strcpyn(m_NotifyIconData.szInfoTitle,szTitle,sizeof(m_NotifyIconData.szInfoTitle)-1);
            strcpyn(m_NotifyIconData.szInfo,szText,sizeof(m_NotifyIconData.szInfo)-1);
        }
        else
        {
            memset(m_NotifyIconData.szInfoTitle,'\0',sizeof(m_NotifyIconData.szInfoTitle)-1);
            memset(m_NotifyIconData.szInfo,'\0',sizeof(m_NotifyIconData.szInfo)-1);
        }
        m_NotifyIconData.dwInfoFlags = dwIconType;
        m_NotifyIconData.uTimeout = nTimeout;
        ::Shell_NotifyIcon(NIM_MODIFY,&m_NotifyIconData);

        // in modo che le notifiche successive non considerino il balloon
        m_NotifyIconData.szInfoTitle[0] = '\0';
        m_NotifyIconData.szInfo[0] = '\0';
    }
    else if(m_nBalloonType==BALLOON_USE_EXTENDED)
    {
        // ricava le coordinate a cui visualizzare
        CPoint ptPosition;
        m_TrayPosition.GetPosition(ptPosition);

        // ricava il timeout per la rimozione del balloon
        if(!bRemoveBalloon)
        {
            nTimeout = (nTimeout >= 1 && nTimeout <= 30) ? nTimeout : BALLOON_DEFAULT_TIMEOUT;
            nTimeout *= 1000L;
        }
        else
            nTimeout = 0;

        m_nTimeout = nTimeout;

        if(!bRemoveBalloon)
        {
            // imposta il timer per la rimozione del balloon
            if(nTimeout!=0)
            {
                if(m_nTimerId!=0L)
                {
                    ::KillTimer(AfxGetMainWnd()->m_hWnd,m_nTimerId);
                    m_nTimerId = 0L;
                }

                m_nTimerId = ::SetTimer(AfxGetMainWnd()->m_hWnd,(UINT)this,m_nTimeout,(TIMERPROC)BalloonTimerProc);
            }

            // imposta lo stile
            if(m_szCssStyles[0]!='\0')
                m_TrayTooltip.SetCssStyles(m_szCssStyles);

            // formatta il testo
            char szText[1024];
            if(nCloseIconID!=(UINT)-1L)
                m_nCloseIconID = nCloseIconID;
            _snprintf(szText,
                      sizeof(szText)-1,
                      "<table>"
                      "<tr>"
                      "<td align=left><h4>%s</h4></td>"
                      "<td align=right><a><icon idres=%d width=16 height=16 style=g hotstyle></a></td>"
                      "</tr>"
                      "</table><hr><br>"
                      "%s",
                      lpcszTitle,
                      m_nCloseIconID,
                      lpcszText);

            // visualizza il tooltip
            if(nIconID!=(UINT)-1L)
            {
                // carica l'icona dall'handle
                m_TrayTooltip.SetEffectBk(CPPDrawManager::EFFECT_SOLID,0);
                m_TrayTooltip.SetDelayTime(PPTOOLTIP_TIME_AUTOPOP,1000);
                m_TrayTooltip.SetBehaviour(PPTOOLTIP_CLOSE_LEAVEWND);
//				m_TrayTooltip.SetColorBk(RGB(255,255,255));
                m_TrayTooltip.ShowHelpTooltip(&ptPosition,szText,nIconID,iconSize);
            }
            else
            {
                // chiude l'handle solo se non e' in share
                if(m_hBalloonIcon!=(HICON)NULL && !m_bSharedIcon)
                    ::DestroyIcon(m_hBalloonIcon);
                m_hBalloonIcon = (HICON)NULL;

                // carica l'icona dal file
                if(!strnull(lpcszIconFileName))
                {
                    m_hBalloonIcon = (HICON)::LoadImage(NULL,lpcszIconFileName,IMAGE_ICON,iconSize.cx,iconSize.cy,LR_DEFAULTCOLOR|LR_LOADFROMFILE);
                    m_bSharedIcon = FALSE;
                }
                else // carica l'icona predefinita
                {
                    switch(nIconType)
                    {
                    case MB_ICONERROR:
                        m_hBalloonIcon = ::LoadIcon(NULL,IDI_ERROR);
                        break;
                    case MB_ICONWARNING:
                        m_hBalloonIcon = ::LoadIcon(NULL,IDI_WARNING);
                        break;
                    case MB_ICONINFORMATION:
                    default:
                        m_hBalloonIcon = ::LoadIcon(NULL,IDI_INFORMATION);
                        break;
                    }

                    m_bSharedIcon = TRUE;
                }

                if(m_hBalloonIcon)
                {
                    m_TrayTooltip.SetEffectBk(CPPDrawManager::EFFECT_SOLID,0);
                    m_TrayTooltip.SetDelayTime(PPTOOLTIP_TIME_AUTOPOP,1000);
                    m_TrayTooltip.SetBehaviour(PPTOOLTIP_CLOSE_LEAVEWND);
//					m_TrayTooltip.SetColorBk(RGB(255,255,255));
                    m_TrayTooltip.ShowHelpTooltip(&ptPosition,szText,m_hBalloonIcon);
                }
            }
        }
    }
}
Exemple #25
0
int main(int argc, string argv[])
{
  string *produce, snap_tags[MaxBodyFields], frame_tags[MaxBodyFields];
  snapshot *snaplist = NULL, *ssp, frame = { NULL, 0, 0.0, NULL };
  stream instr, outstr;
  int n, nbody, i;
  bodyptr btab, bp, sp;
  bool roff, voff;

  initparam(argv, defv);
  produce = burststring(getparam("produce"), ", ");
  layout_body(produce, Precision, NDIM);
  instr = stropen(getparam("in"), "r");
  get_history(instr);
  snaplist = ssp = (snapshot *) allocate(sizeof(snapshot));
  n = nbody = 0;
  while (get_snapshot(instr, *ssp, snap_tags, FALSE)) {
    if (! set_equal(snap_tags, produce))
      error("%s: input file lacks required items\n", getprog());
    n++;
    nbody += ssp->nbody;
    get_history(instr);
    ssp->link = (snapshot *) allocate(sizeof(snapshot));
    ssp = ssp->link;
  }
  strclose(instr);
  eprintf("[%s: read %d frames, %d bodies]\n", getprog(), n, nbody);
  if (! strnull(getparam("frame"))) {
    instr = stropen(getparam("frame"), "r");
    get_history(instr);
    if (! get_snapshot(instr, frame, frame_tags, FALSE))
      error("%s: no snapshot in frame file\n", getprog());
    strclose(instr);
    if (frame.nbody < n)
      error("%s: need at least %d points in frame\n", getprog(), n);
  }
  roff = (frame.nbody > 0) && set_member(frame_tags, PosTag);
  voff = (frame.nbody > 0) && set_member(frame_tags, VelTag);
  bp = btab = (bodyptr) allocate(nbody * SizeofBody);
  ssp = snaplist;
  for (i = 0; i < n; i++) {
    sp = ssp->bodies;
    while (sp < NthBody(ssp->bodies, ssp->nbody)) {
      memmove((void *) bp, (void *) sp, (size_t) SizeofBody);
      if (roff) {
	ADDV(Pos(bp), Pos(bp), Pos(NthBody(frame.bodies, i)));
      }
      if (voff) {
	ADDV(Vel(bp), Vel(bp), Vel(NthBody(frame.bodies, i)));
      }
      bp = NextBody(bp);
      sp = NextBody(sp);
    }
    ssp = ssp->link;
  }
  outstr = stropen(getparam("out"), "w");
  put_history(outstr);
  put_snap(outstr, &btab, &nbody, &frame.time, produce);
  strclose(outstr);
  return (0);
}
Exemple #26
0
void T_Damage( gedict_t * targ, gedict_t * inflictor, gedict_t * attacker, float damage )
{
	vec3_t          dir;
	gedict_t       *oldself;
	float           save;
	float           take;
	int				i, c1 = 8, c2 = 4, hdp;
	float			dmg_dealt = 0, virtual_take = 0;
	float			non_hdp_damage; // save damage before handicap apply for kickback calculation
	float			native_damage = damage; // save damage before apply any modificator
	char            *attackerteam, *targteam, *attackername, *victimname;
	qbool			tp4teamdmg = false;

	//midair and instagib
	float playerheight = 0, midheight = 0;
	qbool midair = false, inwater = false, do_dmg = false, rl_dmg = false, stomp_dmg = false;

	// can't apply damage to dead
	if ( !targ->s.v.takedamage || ISDEAD( targ ) )
		return;

	// can't damage other players in race
	if ( isRACE() && ( attacker != targ ) )
	{
			if ( targ->ct == ctPlayer || attacker->ct == ctPlayer )
				return;
	}

	// ignore almost all damage in CA while coutdown
	if ( isCA() && match_in_progress && ra_match_fight != 2 )
	{
		if ( !( 	dtTELE1 == targ->deathtype	// always do tele damage
				 || dtTELE2 == targ->deathtype	// always do tele damage
				 || dtTELE3 == targ->deathtype	// always do tele damage
				 || dtSUICIDE == targ->deathtype // do suicide damage anyway
			  )
		)
			return;
	}	

	// used by buttons and triggers to set activator for target firing
	damage_attacker = attacker;
	damage_inflictor = inflictor;

	attackerteam = getteam( attacker );
	targteam = getteam( targ );

	if ( (int)cvar("k_midair") )
		midair = true;

	// in bloodfest boss damage factor.
	if ( k_bloodfest && attacker->bloodfest_boss )
	{
		damage *= 4;
	}

	// check for quad damage powerup on the attacker
	// midair quad makes rockets fast, but no change to damage
	if ( attacker->super_damage_finished > g_globalvars.time
	     && strneq( inflictor->s.v.classname, "door" ) && dtSTOMP != targ->deathtype
		 && !midair 
	   )
		damage *= ( deathmatch == 4 ? 8 : 4 ); // in dmm4 quad is octa actually

	// ctf strength rune
	if ( attacker->ctf_flag & CTF_RUNE_STR )
		damage *= 2;

	// ctf resistance rune
	if ( targ->ctf_flag & CTF_RUNE_RES )
	{
		damage /= 2;
		ResistanceSound( targ );
	}

	// did we hurt enemy flag carrier?
	if ( (targ->ctf_flag & CTF_FLAG) && (!streq(targteam, attackerteam)) )
	{
		attacker->carrier_hurt_time = g_globalvars.time;
	}

	// in teamplay 4 we do no armor or health damage to teammates (unless telefrag), but do apply velocity changes
	if ( tp_num() == 4 && streq(targteam, attackerteam) && ( isCA() || targ != attacker ) && !TELEDEATH(targ) )
	{
		tp4teamdmg = true;
	}

	if ( midair || cvar("k_instagib") )
	{
		traceline( PASSVEC3(targ->s.v.origin),
				targ->s.v.origin[0], 
				targ->s.v.origin[1], 
				targ->s.v.origin[2] - 2048,
				true, targ );

		playerheight = targ->s.v.absmin[2] - g_globalvars.trace_endpos[2] + ( cvar("k_instagib") ? 1 : 0 );
	}

	// get some data before apply damage in mid air mode
	if ( midair )
	{
		inwater = ( ((int)targ->s.v.flags & FL_INWATER) && targ->s.v.waterlevel > 1 );

		if ( streq( inflictor->s.v.classname, "rocket" ))
			midheight = targ->s.v.origin[2] - inflictor->s.v.oldorigin[2];

		rl_dmg = ( targ->ct == ctPlayer && dtRL == targ->deathtype );
		stomp_dmg = ( targ->ct == ctPlayer && dtSTOMP == targ->deathtype );

		if ( !rl_dmg ) {
			// damage types which ignore "lowheight"
			do_dmg =   targ->ct != ctPlayer				// always do damage to non player, secret doors etc...
				 	|| dtWATER_DMG == targ->deathtype	// always do water damage
				 	|| dtLAVA_DMG  == targ->deathtype	// always do lava damage
				 	|| dtSLIME_DMG == targ->deathtype	// always do slime damage
				 	|| dtSTOMP == targ->deathtype	// always do stomp damage
				 	|| dtTELE1 == targ->deathtype	// always do tele damage
				 	|| dtTELE2 == targ->deathtype	// always do tele damage
				 	|| dtTELE3 == targ->deathtype	// always do tele damage
					|| dtSUICIDE == targ->deathtype; // do suicide damage anyway
		}
	}

	non_hdp_damage = damage; // save damage before handicap apply for kickback calculation

	// #handicap#
	if ( attacker != targ ) // attack no self
	if ( attacker->ct == ctPlayer && targ->ct == ctPlayer ) // player vs player
	if ( ( hdp = GetHandicap(attacker) ) != 100 ) // skip checks if hdp == 100
	if (    dtAXE  == targ->deathtype
 		 || dtSG   == targ->deathtype
		 || dtSSG  == targ->deathtype
		 || dtNG   == targ->deathtype
		 || dtSNG  == targ->deathtype
		 || dtGL   == targ->deathtype
		 || dtRL   == targ->deathtype
		 || dtLG_BEAM     == targ->deathtype
		 || dtLG_DIS      == targ->deathtype
		 || dtLG_DIS_SELF == targ->deathtype // even that impossible
	   ) {
		damage *= 0.01f * hdp;
	}

	// save damage based on the target's armor level

	save = newceil( targ->s.v.armortype * damage );

	if ( tp4teamdmg )
		save = 0; // we do not touch armor

	if ( save >= targ->s.v.armorvalue )
	{
		save = targ->s.v.armorvalue;
		targ->s.v.armortype = 0;	// lost all armor
		targ->s.v.items -= ( ( int ) targ->s.v.items & ( IT_ARMOR1 | IT_ARMOR2 | IT_ARMOR3 ) );
	}

	dmg_dealt += save;

	if ( match_in_progress == 2 )
		targ->s.v.armorvalue = targ->s.v.armorvalue - save;

	take = newceil( damage - save );

	// mid air damage modificators
	if ( midair )
	{
		int k_midair_minheight, midair_minheight;

		k_midair_minheight = (int)cvar("k_midair_minheight");	

		if ( k_midair_minheight == 1 )
			midair_minheight = 128;
		else if ( k_midair_minheight == 2 )
			midair_minheight = 256;
		else if ( k_midair_minheight == 3 )
			midair_minheight = 512;
		else if ( k_midair_minheight == 4 )
			midair_minheight = 1024;
		else
			midair_minheight = 64;

		if ( rl_dmg || stomp_dmg )
			take = 9999;

		if ( playerheight < midair_minheight && rl_dmg )
			take = 0; // no dmg done if target is not high enough

		if ( playerheight < 45 && !inwater && rl_dmg )
			take = 0; // no rl dmg in such case

		if ( !rl_dmg && !do_dmg )
			take = 0; // unknown damage for midair, so do not damage

		if ( rl_dmg && targ == attacker )
			take = 0; // no self rl damage
	}

	// instagib damage modificators
	if ( cvar("k_instagib") )
	{
		if ( inflictor->ct == ctPlayer )
			take = 5000;

		if ( attacker == targ )
			take = 0;
	}

	// helps kill player in prewar at "wrong" places
	if ( match_in_progress != 2 && native_damage > 450 )
		take = 99999;

	// team play damage avoidance and godmode or invincibility check

	virtual_take = max(0, take); // virtual_take used for calculating dmg_dealt only in case of k_dmgfrags

	// ignore this checks for suicide damage
	if ( dtSUICIDE != targ->deathtype )
	{
		if ( ( int ) targ->s.v.flags & FL_GODMODE )
		{
			take = 0; // what if god was one of us
		}
		else if ( targ->invincible_finished >= g_globalvars.time )
		{
			if ( targ->invincible_sound < g_globalvars.time )
			{
				sound( targ, CHAN_AUTO, "items/protect3.wav", 1, ATTN_NORM );
				targ->invincible_sound = g_globalvars.time + 2;
			}

			take = 0;
		}
		else if ( ( tp_num() == 1 || ( tp_num() == 3 && targ != attacker ) )
		 	&& !strnull( attackerteam )
		 	&& streq( targteam, attackerteam )
		 	&& attacker->ct == ctPlayer
		 	&& strneq( inflictor->s.v.classname, "door" )
		 	&& !TELEDEATH( targ ) // do telefrag damage in tp
	   	)
	   	{
			// teamplay == 1 don't damage self and mates (armor affected anyway)
			// teamplay == 3 don't damage mates, do damage to self (armor affected anyway)

			take = 0;	   	
	   	}
	   	else if ( tp4teamdmg )
	   	{
			take = 0; // we do not touch health	   	
	   	}
	}

	take = max(0, take); // avoid negative take, if any

	if ( cvar("k_dmgfrags") )
	{
		if ( TELEDEATH( targ ) )
		{
			// tele doesn't count for any dmgfrags damage
			dmg_dealt = 0; 
		}
		else if ( targ->invincible_finished >= g_globalvars.time )
		{
			// damage dealt _not_ capped by victim's health if victim has pent
			dmg_dealt += virtual_take;
		}
		else
		{
			// damage dealt capped by victim's health
			dmg_dealt += bound( 0, virtual_take, targ->s.v.health );
		}
	}
	else
	{
		// damage dealt capped by victim's health
		dmg_dealt += bound( 0, take, targ->s.v.health );
	}

	// add to the damage total for clients, which will be sent as a single
	// message at the end of the frame
	// FIXME: remove after combining shotgun blasts?
	if ( targ->ct == ctPlayer )
	{
		targ->s.v.dmg_take += take;
		targ->s.v.dmg_save += save;
		targ->s.v.dmg_inflictor = EDICT_TO_PROG( inflictor );
	}

	if ( save )
	{
		if (( streq( inflictor->s.v.classname, "worldspawn" ) || strnull( attacker->s.v.classname ))
	        	|| ( targ->deathtype == dtWATER_DMG )
	                || ( targ->deathtype == dtEXPLO_BOX )
	                || ( targ->deathtype == dtFALL )
	                || ( targ->deathtype == dtSQUISH )
	                || ( targ->deathtype == dtCHANGELEVEL )
	                || ( targ->deathtype == dtFIREBALL )
	                || ( targ->deathtype == dtSLIME_DMG )
	                || ( targ->deathtype == dtLAVA_DMG )
	                || ( targ->deathtype == dtTRIGGER_HURT )
		)
				attackername = "world";
		else
			attackername = attacker->s.v.netname;
			victimname = targ->s.v.netname;

		log_printf(
			"\t\t<event>\n"
			"\t\t\t<damage>\n"
			"\t\t\t\t<time>%f</time>\n"
			"\t\t\t\t<attacker>%s</attacker>\n"
			"\t\t\t\t<target>%s</target>\n"
			"\t\t\t\t<type>%s</type>\n"
			"\t\t\t\t<quad>%d</quad>\n"
			"\t\t\t\t<splash>%d</splash>\n"
			"\t\t\t\t<value>%d</value>\n"
			"\t\t\t\t<armor>1</armor>\n"
			"\t\t\t</damage>\n"
			"\t\t</event>\n",
			g_globalvars.time - match_start_time,
			cleantext(attackername),
			cleantext(victimname),
			death_type( targ->deathtype ),
			(int)(attacker->super_damage_finished > g_globalvars.time ? 1 : 0 ),
			dmg_is_splash,
			(int)save
		);
	}

	// figure momentum add
	if ( inflictor != world
		 && (	targ->s.v.movetype == MOVETYPE_WALK
			  || ( k_bloodfest && ( (int)targ->s.v.flags & FL_MONSTER ) )
			 )
	)
	{
		float nailkick;

		for ( i = 0; i < 3; i++ )
			dir[i] = targ->s.v.origin[i] - ( inflictor->s.v.absmin[i] + inflictor->s.v.absmax[i] ) * 0.5;

		VectorNormalize( dir );

		dir[2] = ((dtLG_DIS_SELF == targ->deathtype || dtLG_DIS == targ->deathtype) && dir[2] < 0) ? -dir[2] : dir[2];

		if ( midair && non_hdp_damage < 60 && attacker != targ ) {
			c1 = 11;
			c2 = 6;
		}

		// Yawnmode: nails increases kickback
		// - Molgrum
		if ( k_yawnmode && streq( inflictor->s.v.classname, "spike" ) )
			nailkick = 1.2;
		else
			nailkick = 1.0;

		for ( i = 0; i < 3; i++ ) 
			targ->s.v.velocity[i] += dir[i] * non_hdp_damage * c1 * nailkick * ( midair && playerheight >= 45 ? ( 1 + ( playerheight - 45 ) / 64 ) : 1 );

		if ( midair && playerheight < 45 )
			targ->s.v.velocity[2] += dir[2] * non_hdp_damage * c2 * nailkick; // only for z component

		if ( k_bloodfest && ( (int)targ->s.v.flags & FL_MONSTER ) )
		{
			targ->s.v.flags = (int)targ->s.v.flags & ~FL_ONGROUND;		
		}
	}

	if ( match_in_progress == 2 && (int)cvar("k_dmgfrags") )
	{
		if ( attacker->ct == ctPlayer && targ->ct == ctPlayer && attacker != targ )
		{
			if ( isDuel() || isFFA() || strneq(attackerteam, targteam) )
			{
				int dmg_frags;
				attacker->ps.dmg_frags += dmg_dealt; // add dealt
				dmg_frags = attacker->ps.dmg_frags / 100; // 1 frag = 100 damage
				attacker->s.v.frags = (int)(attacker->s.v.frags + dmg_frags);
				attacker->ps.dmg_frags -= dmg_frags * 100;
			}
		}
	}

	// do the damage

	if (    match_in_progress == 2
		 || dtSUICIDE == targ->deathtype // do suicide damage anyway
		 || TELEDEATH( targ )
		 || ( k_practice && targ->ct != ctPlayer ) // #practice mode#
		 || take >= 99999 // do such huge damage even in prewar, prewar because indirectly here match_in_progress != 2
	   ) 
	{
		targ->s.v.health -= take;

//		G_bprint( 2, "%s %f\n", targ->s.v.classname, targ->s.v.health );

		if ( take )
		{
			if (( streq( inflictor->s.v.classname, "worldspawn" ) || strnull( attacker->s.v.classname ))
		        	|| ( targ->deathtype == dtWATER_DMG )
		                || ( targ->deathtype == dtEXPLO_BOX )
		                || ( targ->deathtype == dtFALL )
		                || ( targ->deathtype == dtSQUISH )
		                || ( targ->deathtype == dtCHANGELEVEL )
		                || ( targ->deathtype == dtFIREBALL )
		                || ( targ->deathtype == dtSLIME_DMG )
		                || ( targ->deathtype == dtLAVA_DMG )
		                || ( targ->deathtype == dtTRIGGER_HURT )
			)
				attackername = "world";
			else
				attackername = attacker->s.v.netname;
				victimname = targ->s.v.netname;

			log_printf(
				"\t\t<event>\n"
				"\t\t\t<damage>\n"
				"\t\t\t\t<time>%f</time>\n"
				"\t\t\t\t<attacker>%s</attacker>\n"
				"\t\t\t\t<target>%s</target>\n"
				"\t\t\t\t<type>%s</type>\n"
				"\t\t\t\t<quad>%d</quad>\n"
				"\t\t\t\t<splash>%d</splash>\n"
				"\t\t\t\t<value>%d</value>\n"
				"\t\t\t\t<armor>0</armor>\n"
				"\t\t\t</damage>\n"
				"\t\t</event>\n",
				g_globalvars.time - match_start_time,
				cleantext(attackername),
				cleantext(victimname),
				death_type( targ->deathtype ),
				(int)(attacker->super_damage_finished > g_globalvars.time ? 1 : 0 ),
				dmg_is_splash,
				(int)take
			);
		}

		if ( !targ->s.v.health || dtSUICIDE == targ->deathtype )
			targ->s.v.health = -1; // qqshka, no zero health, heh, imo less bugs after this
	}

	// show damage in sbar
	if ( match_in_progress != 2 && ISLIVE( targ ) && !k_matchLess )
	{
		if ( !midair || ( (int)targ->s.v.flags & FL_ONGROUND ) )
		{
			if ( targ->ct == ctPlayer )			
				targ->s.v.currentammo = 1000 + Q_rint(damage);

			if ( attacker != targ && attacker->ct == ctPlayer)
				attacker->s.v.health = 1000 + Q_rint(damage);
		}
	}

	// update damage stats like: give/taked/team damage
	if ( attacker->ct == ctPlayer && targ->ct == ctPlayer )
	{
		if ( attacker == targ )
		{
			// self damage

			attacker->ps.dmg_self += dmg_dealt;
		}
		else
		{
			int items = targ->s.v.items;

			// damage to enemy weapon
			if ( items & (IT_ROCKET_LAUNCHER | IT_LIGHTNING) )
			{
				attacker->ps.dmg_eweapon += dmg_dealt;
			}

			if ( tp_num() && streq(attackerteam, targteam) )
			{
				attacker->ps.dmg_team += dmg_dealt;
			}
			else 
			{
				attacker->ps.dmg_g += dmg_dealt;
				targ->ps.dmg_t     += dmg_dealt;
			}

			// real hits

			if ( take || save )
			{
				if ( dtRL == targ->deathtype )
					attacker->ps.wpn[wpRL].rhits++;

				if ( dtGL == targ->deathtype )
					attacker->ps.wpn[wpGL].rhits++;
			}

			// virtual hits

			if ( virtual_take || save )
			{
				if ( dtRL == targ->deathtype )
				{
					attacker->ps.wpn[wpRL].vhits++;
					// virtual given rl damage
					attacker->ps.dmg_g_rl += ( virtual_take + save );
				}

				if ( dtGL == targ->deathtype )
					attacker->ps.wpn[wpGL].vhits++;
			}
		}
	}

	// mid air bonuses
	if ( midair && match_in_progress == 2 && attacker != targ && take && rl_dmg)
			MidairDamageBonus(attacker, midheight);

	if ( midair && match_in_progress == 2 && stomp_dmg ) {
		attacker->ps.mid_stomps++;
		targ->s.v.frags -= 3;
	}

 	// if targed killed, do appropriate action and return
	if ( ISDEAD( targ ) )
	{
		Killed( targ, attacker, inflictor );
		return;
	}

	// react to the damage - call pain function
	oldself = self;
	self = targ;

  	if ( (int)self->s.v.flags & FL_MONSTER )
  	{
		GetMadAtAttacker( attacker );
  	}

	if ( self->th_pain )
	{
		self->th_pain( attacker, take );
	}

	self = oldself;
}
Exemple #27
0
void output(void) {
    real teff;
    int n;
    string outtags[MaxBodyFields];
    char namebuf[256];
    struct stat buf;
    stream outstr;
    string streamtags[] = { MassTag, PosTag, VelTag, PhiTag, AccTag, NULL };

    diagnostics();				// compute std diagnostics
    if (logstr != NULL) {
        //fprintf(logstr, "\n    %8s%8s%8s%8s%8s%8s%8s%8s\n",
        //"time", "|T+U|", "T", "-U", "-T/U", "|Vcom|", "|Jtot|", "CPUtot");
        //fprintf(logstr, "    %8.3f%8.4f%8.4f%8.4f%8.5f%8.5f%8.4f%8.2f\n",
        // tnow, ABS(etot[0]), etot[1], -etot[2], -etot[1]/etot[2],
        // absv(cmvel), absv(amvec), cputime());
    }
    teff = tnow + dtime/8;			// anticipate slightly...
    if (! strnull(outfile) && teff >= tout) {	// time for data output?
        n = 0;
        if (scanopt(outputs, PosTag))		// if listed in outputs
            outtags[n++] = PosTag;			// include tag in list
        if (scanopt(outputs, VelTag))
            outtags[n++] = VelTag;
        if (scanopt(outputs, MassTag) || (nstep == 0))
            outtags[n++] = MassTag;
        if (scanopt(outputs, PhiTag))
            outtags[n++] = PhiTag;			// select potential data
        if (scanopt(outputs, AccTag))
            outtags[n++] = AccTag;			// select acceleration data
        outtags[n] = NULL;
        sprintf(namebuf, outfile, nstep);		// make up output file name
        if (stat(namebuf, &buf) != 0) {		// no output file exists?
            outstr = stropen(namebuf, "w");		// create & open for output
            put_history(outstr);			// write out hiatory data
        } else					// else file already exists
            outstr = stropen(namebuf, "a");		// reopen and append output
        put_snap(outstr, &bodytab, &nbody, &tnow, outtags);
        strclose(outstr);				// close up output file
        if (logstr != NULL)
            fprintf(logstr, "\n\tdata output to file %s at time %f\n",
                    namebuf, tnow);
        tout += dtout;				// schedule next output
    }
    if (! strnull(strfile)) {
        if (! streq(strfile, "-")) {
            sprintf(namebuf, strfile, nstep);
            if (stat(namebuf, &buf) != 0) {
                outstr = stropen(namebuf, "w");
                put_history(outstr);
            } else
                outstr = stropen(namebuf, "a");
        } else
            outstr = stdout;
        put_snap(outstr, &bodytab, &nbody, &tnow, streamtags);
        fflush(outstr);
        if (! streq(strfile, "-"))
            strclose(outstr);
    }
    if (! strnull(savefile))			// was state file given?
        savestate(savefile);			// save data for restart
    forcehead = FALSE;				// insure headers print
    fflush(NULL);					// empty all output buffers
}
Exemple #28
0
void c2html(const char *filename, char *err, struct colors *c)
{
	/* <- core function -> here the C source 
	   code is tranlated to an HTML web page. */

	struct /* common bits */
	{
		unsigned char color : 1;  /* color the code */
		unsigned char qt1 : 1;  /* double quotes */
		unsigned char qt2 : 1;  /* single quotes */
		unsigned char cm1 : 1;  /* multi-line comments */
		unsigned char cm2 : 1;  /* single-line comments */
		unsigned char num : 1;  /* numerical constants */
		unsigned char pre : 1;  /* preprocessors */
		unsigned char cont : 1;  /* preprocessors */
	}
	bits = { 1, 0, 0, 0, 0, 0, 0, 0 };

	if(!strlen(filename))
	{
		puts("\nPlease enter a filename.");
		return;
	}

	if(*filename==':')
	{
		bits.color = 0;
		filename++;
	}
	else if(*filename=='?')
	{
		userdef_colors(c);
		filename++;
	}

	FILE *cfile,*hfile;
	cfile = hfile = NULL;

	char htmlfile[STR_MAX];
	strcpy(htmlfile,filename);
	strcat(htmlfile,".html");

	if((cfile = fopen(filename,"r"))==NULL)
	{
		sprintf(err,"Could not open file: %s",filename);
		return;
	}

	unsigned short int line_length = 0;
	char input_str[STR_MAX];
	printf("\nHow many letters per line? ");
	fgets(input_str,STR_MAX,stdin);
	string(input_str);
	line_length = atoi(input_str);
	if(line_length <= 1) line_length = 80;

	printf("\nAnalyzing file: %s ...\n\n",filename);

	register char move = 0;
	unsigned int strmax, strnow, lines, pages;
	unsigned long int charcount = 0;
	unsigned long int letters = 0;
	strmax = strnow = lines = pages = 0;

	for(;move!=EOF;strnow++, charcount++)
	{
		move = fgetc(cfile);
		if(move=='\n')
		{
			strmax = strnow>strmax ? strnow:strmax;
			strnow = 0;
			lines++;
		}
		if(move<128 && move!='\n' && move!= '\r')
			letters++;
	}

	pages = lines/50;
	pages += lines%50 < 10 ? 0 : 1;

	printf("No. of pages = %d\n",pages);
	printf("No. of lines = %d\n",lines);
	printf("No. of chars = %ld\n",charcount);
	printf("No. of letters = %ld\n",letters);
	
	if(charcount<=1)
	{
		strcpy(err,"Too few characters.");
		fclose(cfile);
		return;
	}

	if((hfile = fopen(htmlfile,"w"))==NULL)
	{
		sprintf(err,"Could not create file: %s",htmlfile);
		fclose(cfile);
		return;
	}

	printf("\nTranslating file: %s ...    ",filename);

	fprintf(hfile,"<HTML><HEAD><TITLE>%s</TITLE></HEAD>\n",filename);
	fprintf(hfile,"<BODY TEXT=%s BGCOLOR=white><CENTER><H1>%s</H1></CENTER><HR><CODE>\n",c->text,filename);

	char *wstr = NULL, *wwstr = NULL;
	if((wstr = (char *) malloc
	(sizeof(char)*(strmax+1)))==NULL)
	{
		strcpy(err,"Out of memory.");
		fclose(hfile);
		fclose(cfile);
		return;
	}
	else *wstr = '\0';

	unsigned int digits = 0;
	unsigned int _lines = lines;
	for(;_lines;digits++) _lines /= 10;

	char *nstr = NULL;
	if((nstr = (char *) malloc
	(sizeof(char)*(digits+1)))==NULL)
	{
		strcpy(err,"Out of memory.");
		free(wstr);
		fclose(hfile);
		fclose(cfile);
		return;
	}
	else *nstr = '\0';
	fclose(cfile);

	unsigned int lnum = 0; 
	unsigned register int cnum = 0;
	cfile = fopen(filename,"r");

	/* C keywords */
	char keys[33][9] =
	{ 
		"auto","break","case","char",
		"const","continue","default",
		"double","do","else","enum",
		"extern","float","for","goto",
		"if","int","long","register",
		"return","short","signed",
		"sizeof","static","struct",
		"switch","typedef","union",
		"unsigned","void","volatile",
		"while", "inline"
	};

	for(bits.cont=0;fgets(wstr,strmax,cfile)!=NULL;lnum++)
	{
		unsigned int remaining = 0;
		unsigned int split_offset = 0;
		remainder:

		/* show translation progress */
		char prog[4] = "00%";
		double progn = (lnum*100)/lines;
		if(progn<100)
		numstr(prog,(int)progn,progn<10?1:2);
		strcat(prog,"%");

		if(strlen(prog)==2)
		printf("\b\b%s",prog);
		if(strlen(prog)==3)
		printf("\b\b\b%s",prog);
		
		/* insert line numbers */
		short int numlength = 0;
		if(remaining)
			goto so_go_on;
		numstr(nstr,lnum,digits);
		numlength = strlen(nstr);
		fprintf(hfile,"<B>%s</B> &nbsp;",nstr);
		so_go_on:

		/* check if the line has been commented off */
		if(bits.cm1&&lnum)
		fprintf(hfile,"<FONT COLOR=%s>",c->comment);

		/* reset the booleans in bits */
		if(bits.cont && bits.pre)
			fprintf(hfile,"<B>");
		else
			bits.pre = 0;
		if(bits.cont && bits.qt1)
			fprintf(hfile,"<FONT COLOR=%s>",c->string);
		else
			bits.qt1 = 0;
		bits.qt2 = 0;
		bits.cm2 = 0;
		bits.num = 0;

		unsigned int line_len = 0;
		line_len = line_length - numlength;

		if(remaining)
		{
			numstr(nstr,lnum,digits);
			numlength = strlen(nstr);
			strnull(nstr);
			strbluff(nstr,"&nbsp;" ,numlength);
			fprintf(hfile,"%s &nbsp;",nstr);
			char *t = allocs(line_len+1);
			strmid(t,wwstr,split_offset,line_len);
			strcpy(wstr,t);
			split_offset += strlen(wstr);
			remaining -= strlen(wstr);
		}

		if(strlen(wstr)>line_len && remaining <= 0)
		{
			split_offset = 0;
			char *t = allocs(line_len+1);
			strmid(t,wstr,split_offset,line_len);
			wwstr = clones(wstr);
			strcpy(wstr,t);
			split_offset += strlen(wstr);
			remaining = strlen(wwstr)-line_len;
		}

		for(cnum=0;cnum<strlen(wstr);cnum++)
		{
			/* color up the keywords */
			int keyw;
			for(keyw=0;keyw<33;keyw++)
			if(!strncmp(&wstr[cnum],keys[keyw],
				strlen(keys[keyw]))&&!(
			   wstr[cnum-1]>='A'&&
			   wstr[cnum-1]<='Z')&&!(
			   wstr[cnum-1]>='a'&&
			   wstr[cnum-1]<='z')&&!(
			   wstr[cnum-1]>='0'&&
			   wstr[cnum-1]<='9')&&
			   wstr[cnum-1]!='_'
               &&(!bits.cm1)
               &&(!bits.cm2)
               &&(!bits.qt1)
               &&(!bits.qt2)
               &&bits.color)
			{
				if(!(wstr[cnum+strlen(keys[keyw])]>='A'&&
			         wstr[cnum+strlen(keys[keyw])]<='Z')&&!(
			         wstr[cnum+strlen(keys[keyw])]>='a'&&
			         wstr[cnum+strlen(keys[keyw])]<='z')&&!(
					 wstr[cnum+strlen(keys[keyw])]>='0'&&
			         wstr[cnum+strlen(keys[keyw])]<='9')&&
			         wstr[cnum+strlen(keys[keyw])]!='_') {
				fprintf(hfile,"<FONT COLOR=%s>%s</FONT>",c->keyword,keys[keyw]);
				cnum += strlen(keys[keyw]);
				}
			}

			/* color up the comments */
			if(!strncmp(&wstr[cnum],"/*",2)
			   &&!bits.qt1
			   &&!bits.qt2
			   &&!bits.cm2
			   &&bits.color)
			{
				fprintf(hfile,"<FONT COLOR=%s>/",c->comment);
				bits.cm1 = 1;
			}
			else if(!strncmp(&wstr[cnum],"*/",2)
				    &&!bits.qt1
					&&!bits.qt2
				    &&!bits.cm2
					&&(bits.cm1)
					&&bits.color)
			{
				fprintf(hfile,"*/</FONT>");
				cnum++;
				bits.cm1 = 0;
			}
			else if((!strncmp(&wstr[cnum],"//",2))
				     &&!bits.qt1
					 &&!bits.qt2
				     &&!bits.cm2
					 &&!bits.cm1
					 &&bits.color)
			{
				fprintf(hfile,"<FONT COLOR=%s>/",c->comment);
				bits.cm2 = 1;
			}
			/* color up the strings */
			else if(wstr[cnum]==34
				    &&(!bits.cm2)
					&&(!bits.cm1)
					&&(!bits.pre)
					&&bits.color)
			{
				if(wstr[cnum-1]!='\\') {
				if(!bits.qt1)
				{
					fprintf(hfile,"<FONT COLOR=%s>%c",c->string,34);
					bits.qt1 = 1;
				}
				else
				{
					fprintf(hfile,"%c</FONT>",34);
					bits.qt1 = 0;
				} }
			}
			/* color up the chars */
			else if(wstr[cnum]==39
					&&(!bits.qt1)
				    &&(!bits.cm2)
					&&(!bits.cm1)
					&&(!bits.pre)
					&&bits.color)
			{
				if(wstr[cnum-1]!='\\') {
				if(!bits.qt2)
				{
					fprintf(hfile,"<FONT COLOR=%s>%c",c->chr,39);
					bits.qt2 = 1;
				}
				else
				{
					fprintf(hfile,"%c</FONT>",39);
					bits.qt2 = 0;
				} }
			}
			/* color up the numbers */
			else if(wstr[cnum]>='0'&&
				    wstr[cnum]<='9'&&!(
					wstr[cnum-1]>'A'&&
					wstr[cnum-1]<'Z')&&!(
					wstr[cnum-1]>'a'&&
					wstr[cnum-1]<'z')&&
					wstr[cnum-1]!='_'
				    &&(!bits.cm2)
					&&(!bits.cm1)
					&&(!bits.qt1)
					&&(!bits.qt2)
					&&(!bits.num)
					&&(!bits.pre)
					&&bits.color)
			{
				fprintf(hfile,"<FONT COLOR=%s>%c",c->numbers,wstr[cnum]);
				bits.num = 1;
			}
			else if(bits.num /* to end number colouring */
				    &&((wstr[cnum]<'0')
				    ||(wstr[cnum]>'9')))
			{
			    fprintf(hfile,"</FONT>%c",wstr[cnum]);
				bits.num = 0;
			}
			/* color up the preprocessors */
			else if(wstr[cnum]=='#'
				    &&(!bits.cm2)
					&&(!bits.cm1)
					&&(!bits.qt1)
					&&(!bits.qt2)
					&&(!bits.pre)
					&&(bits.color))
			{
				fprintf(hfile,"<B>#");
				bits.pre = 1;
			}

			/* replace the C symbols
			 with their HTML equivalent */
			else if(wstr[cnum-1]==' '&&wstr[cnum]==' ')
			fprintf(hfile,"&nbsp;");
			else if(wstr[cnum]=='\t')
			fprintf(hfile,"&nbsp; ");
			else if(wstr[cnum]=='<')
			fprintf(hfile,"&lt;");
			else if(wstr[cnum]=='>')
			fprintf(hfile,"&gt;");
			else if(wstr[cnum]=='\n') {
				fprintf(hfile,"</FONT>");
				if(wstr[cnum-1]=='\\')
					bits.cont = 1;
				else
					bits.cont = 0;
			break;
			} else
			fprintf(hfile,"%c",wstr[cnum]);
		}

		if(bits.pre)
		fprintf(hfile,"</B>");
		/* end font tag */
		if(bits.cm1||
		   bits.cm2||
		   bits.qt1||
		   bits.qt2||
		   bits.num)
		fprintf(hfile,"</FONT>");
		/* end the line */
		fprintf(hfile,"<BR>\n");

		if(remaining)
			goto remainder;
	}

	fputs("</CODE><HR NOSHADE><FONT FACE=Arial>\n",hfile);
	fprintf(hfile,"No. of pages = %d<BR>\n",pages);
	fprintf(hfile,"No. of lines = %d<BR>\n",lines);
	fprintf(hfile,"No. of chars = %ld<BR>\n",charcount);
	fprintf(hfile,"No. of letters = %ld\n",letters);
	fputs("</FONT></BODY></HTML>",hfile);
	puts("\b\b\b100%\n\nTranslation Complete.");
	printf("HTML File: %s stored.\n",htmlfile);
	free(wstr);
	fclose(hfile);
	fclose(cfile);
}
Exemple #29
0
int get_votes_req( int fofs, qbool diff )
{
	float percent = 51;
	int   votes, vt_req, idx, el_type;

	votes   = get_votes( fofs );

	switch ( fofs ) {
		case OV_BREAK:   percent = cvar(k_matchLess ? "k_vp_map" : "k_vp_break"); break; // in matchless mode there is no /break but /next_map so using "k_vp_map"
		case OV_PICKUP:  percent = cvar("k_vp_pickup"); break;
		case OV_RPICKUP: percent = cvar("k_vp_rpickup"); break;
		case OV_MAP:
					    percent = cvar("k_vp_map");
						idx = vote_get_maps ();
						if ( idx >= 0 && !strnull( GetMapName(maps_voted[idx].map_id) ) )
							votes = maps_voted[idx].map_votes;
						else
							votes = 0;
						break;
		case OV_ELECT:
						if ( (el_type = get_elect_type ()) == etAdmin ) {
							percent = cvar("k_vp_admin");
							break;
						}
						else if ( el_type == etCaptain ) {
							percent = cvar("k_vp_captain");
							break;
						}
						else {
							percent = 100; break; // unknown/none election
							break;
						}

						break;

		case OV_NOSPECS: percent = cvar("k_vp_nospecs"); break;
		case OV_COOP:    percent = cvar("k_vp_coop"); break;
		case OV_ANTILAG: percent = cvar("k_vp_antilag"); break;
	}

	percent = bound(0.51, bound(51, percent, 100)/100, 1); // calc and bound percentage between 50% to 100%

	vt_req  = ceil( percent * CountPlayers() );

	if ( fofs == OV_ELECT )
		vt_req = max(2, vt_req); // if election, at least 2 votes needed
	else if ( fofs == OV_BREAK && k_matchLess && match_in_progress == 1 )
		vt_req = max(2, vt_req); // at least 2 votes in this case
	else if ( fofs == OV_BREAK )
		vt_req = max(1, vt_req); // at least 1 vote in any case
	else if ( fofs == OV_RPICKUP )
		vt_req = max(3, vt_req); // at least 3 votes in this case
	else if ( fofs == OV_NOSPECS )
		vt_req = max(2, vt_req); // at least 2 votes in this case
	else if ( fofs == OV_COOP )
		vt_req = max(1, vt_req); // at least 1 votes in this case
	else if ( fofs == OV_ANTILAG )
		vt_req = max(2, vt_req); // at least 2 votes in this case

	if ( diff )
		return max(0, vt_req - votes);

	return max(0, vt_req);
}
Exemple #30
0
char *
conv_number_str (
    const char *number,                 /*  Number to convert                */
    int   flags,                        /*  Number formatting flags          */
    char  dec_point,                    /*  Decimal point: '.' or ','        */
    int   decimals,                     /*  Number of decimals, or 0         */
    int   dec_format,                   /*  How are decimals shown?          */
    int   width,                        /*  Output field width, or 0         */
    int   sign_format                   /*  How are negatives shown?         */
)
{
    static char
        formatted [FORMAT_MAX + 1],     /*  Formatted return string          */
        zero [CONV_MAX_DECS + 2];       /*  Default value if needed          */
    int
        sep_stop,                       /*  Where we put next sep_char       */
        dec_stop,                       /*  Where we put decimal point       */
        decs_wanted = decimals,         /*  Number of decimals wanted        */
        decs_seen,                      /*  Number of decimals output        */
        sign_pos,                       /*  Where we put sign, if any        */
        digits;                         /*  Number of digits read so far     */
    char
       *dest,                           /*  Store formatted number here      */
        sign_char,                      /*  Number's sign: ' ', '+', '-'     */
        sep_char,                       /*  Thousands separator '.' or ','   */
        drop_zero,                      /*  We suppress this char            */
        ch;                             /*  Next character in picture        */
    Bool
        have_zero;                      /*  TRUE if whole number is zero     */

    ASSERT (width <= FORMAT_MAX);
    ASSERT (dec_point == '.' || dec_point == ',');

    conv_reason = 0;                    /*  No conversion errors so far      */

    /*  ---------------------------------   Prepare to copy digits  ---------*/

    if (decs_wanted > CONV_MAX_DECS)
      {
        conv_reason = CONV_ERR_DECS_OVERFLOW;
        return (NULL);                  /*  Error - too many decimals        */
      }
    /*  If value is empty, use "0" with enough decimals as default value     */
    /*  We allow one whole digit and as many decimals as needed.             */
    if (strnull (number))
      {
        strpad (zero, '0', decs_wanted + 1);
        number = zero;
      }

    /*  Pick-up sign character if present                                    */
    if (*number == ' ' || *number == '+' || *number == '-')
        sign_char = *number++;
    else
        sign_char = ' ';

    /*  While leading zero is '0' we blank-out zeros in the number           */
    drop_zero = (char) (flags & FLAG_N_ZERO_FILL? ' ': '0');

    /*  Prepare for decimals                                                 */
    if ((flags & FLAG_N_DECIMALS) == 0)
        decs_wanted = 0;

    if (strchr (number, '.'))
        dec_stop = (int) (strchr (number, '.') - (char *) number);
    else
        dec_stop = strlen (number) - decs_wanted;

    if (dec_stop < 1)
      {
        conv_reason = CONV_ERR_DECS_MISSING;
        return (NULL);                  /*  Error - too few decimals         */
      }

    /*  Prepare for thousands-separators if FLAG_N_THOUSANDS                 */
    if ((flags & FLAG_N_THOUSANDS) && !(flags & FLAG_N_ZERO_FILL))
      {
        /*  Get number of whole digits, allowing for decimals & dec sign     */
        sep_char = (char) (dec_point == '.'? ',': '.');
        sep_stop = (dec_stop - (decs_wanted? decs_wanted + 1: 0)) % 3;
        if (sep_stop == 0)
            sep_stop = 3;               /*  Get into range 1..3              */
      }
    else
      {
        sep_char = ' ';
        sep_stop = 0;                   /*  No thousands separators          */
      }

    /*  ---------------------------------   Copy the digits  ----------------*/

    digits    = 0;                      /*  No digits loaded yet             */
    decs_seen = 0;                      /*  No decimals output yet           */
    have_zero = TRUE;                   /*  Assume number is zero            */
    dest      = formatted;              /*  Format number                    */
    while (*number)                     /*    until we hit the terminator    */
      {
        ch = *number++;
        if (ch == '.')
            continue;                   /*  Ignore '.' in number             */

        digits++;

        if (ch == drop_zero && digits < dec_stop)
            ch = ' ';
        else
        if (isdigit (ch))
          {
            drop_zero = ' ';
            if (ch > '0')
                have_zero = FALSE;
          }
        if (ch != ' ' || (width > 0 && !(flags & FLAG_N_LEFT)))
          {
            *dest++ = ch;               /*  Output this digit                */
            if (digits > dec_stop)
                decs_seen++;            /*  Count the decimal digit          */
            else
            if (digits == dec_stop)     /*  Handle decimal stop              */
              {                         /*    with optional point            */
                if (flags & FLAG_N_DECIMALS)
                    *dest++ = dec_point;
                sep_stop = 0;           /*  And kill further thousand seps   */
              }
          }
        /*  Output thousands separator unless we are in blank area           */
        if (digits == sep_stop)
          {
            if (ch != ' ')
                *dest++ = sep_char;
            sep_stop += 3;
          }
      }
    *dest = 0;                          /*  Terminate the string nicely      */
    /*  ---------------------------------   Post-format the result  ---------*/

    if (decs_wanted > 0)
      {
        /*  Output trailing decimal zeroes if not supplied                   */
        if (decs_seen == 0)
            *dest++ = dec_point;
        while (decs_seen < decs_wanted)
          {
            *dest++ = '0';
            decs_seen++;
          }
        /*  Drop all decimals if format is DEC_HIDE_ALL                      */
        if (dec_format == DECS_HIDE_ALL)
            while (*dest != dec_point)
                dest--;                 /*  Drop-off trailing zero           */
        else
        /*  Drop trailing decimal zeroes if format is DEC_DROP_ZEROS         */
        if (dec_format == DECS_DROP_ZEROS)
            while (*dest != dec_point)
              {
                if (*(dest - 1) > '0')
                    break;
                else
                    dest--;             /*  Drop-off trailing zero           */
              }
        *dest = 0;                      /*  Terminate the string nicely      */
      }

    /*  Justify within width if width > 0                                    */
    sign_pos = 0;                       /*  Sign normally comes at start     */
    digits   = strlen (formatted);
    if (flags & FLAG_N_SIGNED)
      {
        digits++;                       /*  Allow for eventual sign          */
        if (sign_format == SIGN_FINANCIAL)
            digits++;                   /*  Sign shown like (123)            */
      }
    while (digits < width)
      {
        if (flags & FLAG_N_LEFT && !(flags & FLAG_N_ZERO_FILL))
            strcat (formatted, " ");
        else
          {
            stropen (formatted, FALSE); /*  Insert blank at start of string  */
            if (flags & FLAG_N_ZERO_FILL)
                formatted [0] = '0';
            else
                sign_pos++;             /*  Skip leading space               */
          }
        digits++;
      }

    /*  Format sign if FLAG_N_SIGNED                                         */
    if (flags & FLAG_N_SIGNED)
      {
        if (sign_format == SIGN_NEG_LEAD
        ||  sign_format == SIGN_ALL_LEAD
        ||  sign_format == SIGN_FINANCIAL)
            stropen (formatted, FALSE);

        if (sign_format == SIGN_NEG_TRAIL
        ||  sign_format == SIGN_ALL_TRAIL
        ||  sign_format == SIGN_FINANCIAL)
            strcat (formatted, " ");

        if (!have_zero)                 /*  Zero has no sign                 */
            switch (sign_format)
              {
                case SIGN_NEG_LEAD:
                    if (sign_char != '-')
                        break;          /*  Fall through if negative sign    */
                case SIGN_ALL_LEAD:
                    formatted [sign_pos] = sign_char;
                    break;

                case SIGN_NEG_TRAIL:
                    if (sign_char != '-')
                        break;          /*  Fall through if negative sign    */
                case SIGN_ALL_TRAIL:
                    strlast (formatted) = sign_char;
                    break;

                case SIGN_FINANCIAL:
                    if (sign_char == '-')
                      {
                        formatted [0]       = '(';
                        strlast (formatted) = ')';
                      }
                    break;
              }
      }

    /*  If all zeroes, return a blank string if FLAG_N_ZERO_BLANK            */
    if ((flags & FLAG_N_ZERO_BLANK) && have_zero)
      {
        memset (formatted, ' ', width);
        formatted [width] = 0;
      }

    if (width > 0 && (strlen (formatted) > (size_t) width))
      {
        conv_reason = CONV_ERR_NUM_OVERFLOW;
        return (NULL);                  /*  Overflow -- number too large     */
      }
    else
        return (formatted);
}