Пример #1
0
FileReader::~FileReader()
{
    terminate();
}
Пример #2
0
LevelDBStorage::~LevelDBStorage()
{
  terminate(process);
  wait(process);
  delete process;
}
Пример #3
0
int main(int argc,char *argv[])
{
  int prompt , k, ns, i;
  site *s;
  double inv_space_vol;
  
  int color,spin, color1, spin1;
  
  int key[4];
  int dummy[4];
  FILE *corr_fp;
  
  complex pr_tmp; 
  wilson_propagator *qdest;
  wilson_propagator qtemp1;

  wilson_vector *psi = NULL;
  w_prop_file *wpf;
  wilson_quark_source wqs;
  
  key[XUP] = 1;
  key[YUP] = 1;
  key[ZUP] = 1;
  key[TUP] = 0;

  initialize_machine(&argc,&argv);
#ifdef HAVE_QDP
  QDP_initialize(&argc, &argv);
#endif
  /* Remap standard I/O */
  if(remap_stdio_from_args(argc, argv) == 1)terminate(1);

  g_sync();
  prompt = setup(); 
  setup_restrict_fourier(key, dummy);

  psi = create_wv_field();

  /* Initialize the source type */
  init_wqs(&wqs);

  while( readin(prompt) == 0){
    
    
    /**************************************************************/
    /*load staggered propagator*/
    
    reload_ksprop_to_site3(ks_prop_startflag, 
			   start_ks_prop_file, &ksqs, F_OFFSET(prop), 1);
    
    FORALLSITES(i,s){
      for(color = 0; color < 3; color++)for(k = 0; k < 3; k++)
	s->stag_propagator.e[color][k] = s->prop[color].c[k];
    }
    
    /* Initialize FNAL correlator file */
    
    corr_fp = open_fnal_meson_file(savefile_c);

    /* Load Wilson propagator for each kappa */

    for(k=0; k<num_kap; k++){
      kappa = kap[k];
      wpf = r_open_wprop(startflag_w[k], startfile_w[k]);
      for(spin=0;spin<4;spin++)
	for(color=0;color<3;color++){
	  if(reload_wprop_sc_to_field(startflag_w[k], wpf,
				      &wqs, spin, color, psi, 1) != 0)
	    terminate(1);
	  FORALLSITES(i,s){
	    copy_wvec(&psi[i],&lattice[i].quark_propagator.c[color].d[spin]);
	  }
	}
      r_close_wprop(startflag_w[k],wpf);

      /*******************************************************************/
      /* Rotate the heavy quark */
      
      rotate_w_quark(F_OFFSET(quark_propagator), 
		     F_OFFSET(quark_propagator_copy), d1[k]);  
      // result in quark_propagator_copy


      /**************************************************************/
      /*Calculate and print out the spectrum with the rotated heavy
        quark propagators*/

      spectrum_hl_rot(corr_fp, F_OFFSET(stag_propagator), 
		      F_OFFSET(quark_propagator_copy), k);
      
      
      /**************************************************************/
      /*Smear quarks, calculate and print out the spectrum with the
        smeared heavy quark propagators*/
      
      for(color=0;color<3;color++)for(spin=0;spin<4;spin++){
	restrict_fourier_site(F_OFFSET(quark_propagator.c[color].d[spin]),
			      sizeof(wilson_vector), FORWARDS);
      }
      
      for(ns=0; ns<num_smear;ns++){
	if(strcmp(smearfile[ns],"none")==0) continue;

	inv_space_vol = 1./((double)nx*ny*nz);

	/* Either read a smearing file, or take it to be a point sink */
	if(strlen(smearfile[ns]) != 0){

	   get_smearings_bi_serial(smearfile[ns]);
	
	   restrict_fourier_site(F_OFFSET(w),
				 sizeof(complex), FORWARDS);
	
	   FORALLSITES(i,s){
	     for(color=0;color<3;color++)for(spin=0;spin<4;spin++)
	      for(color1=0;color1<3;color1++)for(spin1=0;spin1<4;spin1++){
		  pr_tmp = 
		    s->quark_propagator.c[color].d[spin].d[spin1].c[color1];
	  
		  s->quark_propagator_copy.c[color].d[spin].d[spin1].c[color1].real =
		    pr_tmp.real * s->w.real - pr_tmp.imag * s->w.imag;
	      
		  s->quark_propagator_copy.c[color].d[spin].d[spin1].c[color1].imag =
		    pr_tmp.real * s->w.imag + pr_tmp.imag * s->w.real;
		}
	   }
	  } else { /* Point sink */
	   FORALLSITES(i,s){
	     for(color=0;color<3;color++)for(spin=0;spin<4;spin++)
	      for(color1=0;color1<3;color1++)for(spin1=0;spin1<4;spin1++){
		  pr_tmp = 
		    s->quark_propagator.c[color].d[spin].d[spin1].c[color1];
		  
		  s->quark_propagator_copy.c[color].d[spin].d[spin1].c[color1].real =
		    pr_tmp.real;
	      
		  s->quark_propagator_copy.c[color].d[spin].d[spin1].c[color1].imag =
		    pr_tmp.imag;
		}
	   }
	  }
	
	  for(color=0;color<3;color++)for(spin=0;spin<4;spin++){
	      restrict_fourier_site(F_OFFSET(quark_propagator_copy.c[color].d[spin]),
				    sizeof(wilson_vector), BACKWARDS);
	    }	
	  
	  FORALLSITES(i,s)
	  {
	    qdest = &(s->quark_propagator_copy);
	    qtemp1 = s->quark_propagator_copy;
	    for(spin=0;spin<4;spin++)for(color=0;color<3;color++)
 	      for(spin1=0;spin1<4;spin1++)for(color1=0;color1<3;color1++)
	      {
		qdest->c[color].d[spin1].d[spin].c[color1].real = 
		  qtemp1.c[color].d[spin].d[spin1].c[color1].real;
		qdest->c[color].d[spin1].d[spin].c[color1].imag = 
		  qtemp1.c[color].d[spin].d[spin1].c[color1].imag;
	      }
	  }
Пример #4
0
void RTMFPServer::run() {

	try {
		_startDatetimeStr = DateTimeFormatter::format(LocalDateTime(), "%b %d %Y %H:%M:%S");
		_pSocket->bind(SocketAddress("0.0.0.0",_port));
		NOTE("RTMFP server sendbufsize %d recvbufsize %d recvtmo %d sendtmo %d", 
				_pSocket->getSendBufferSize(),
				_pSocket->getReceiveBufferSize(),
				_pSocket->getReceiveTimeout().milliseconds(),
				_pSocket->getSendTimeout().milliseconds()
				);

		sockets.add(*_pSocket,*this);  //_mainSockets
		NOTE("RTMFP server starts on %u port",_port);

		if(_shellPort > 0) { 
			_shellSocket.bind(SocketAddress("0.0.0.0", _shellPort));
			sockets.add(_shellSocket, *this);
			NOTE("RTMFP server shell command portal on %u prot", _shellPort);
		}

		onStart();

		RTMFPManager manager(*this);
		bool terminate=false;
		while(!terminate)
			handle(terminate);

	} catch(Exception& ex) {
		FATAL("RTMFPServer, %s",ex.displayText().c_str());
	} catch (exception& ex) {
		FATAL("RTMFPServer, %s",ex.what());
	} catch (...) {
		FATAL("RTMFPServer, unknown error");
	}

	sockets.remove(*_pSocket); // _mainSockets

	// terminate handle
	terminate();
	
	// clean sessions, and send died message if need
	_handshake.clear();
	_sessions.clear();

	// stop receiving and sending engine (it waits the end of sending last session messages)
	poolThreads.clear();

	// close UDP socket
	_pSocket->close();

	// close shell command port 
	if(_shellPort > 0) { 
		_shellSocket.close();
	}

	sockets.clear();
	//_mainSockets.clear();
	_port=0;
	onStop();

	if(_pCirrus) {
		delete _pCirrus;
		_pCirrus = NULL;
	}

	if(_pSocket) {
		delete _pSocket;
		_pSocket = NULL;
	}
	
	NOTE("RTMFP server stops");
}
Пример #5
0
void
chat_expect(char *s)
{
    char *expect;
    char *reply;

    if (strcmp(s, "HANGUP") == 0) {
	++hup_next;
        return;
    }
 
    if (strcmp(s, "ABORT") == 0) {
	++abort_next;
	return;
    }

    if (strcmp(s, "CLR_ABORT") == 0) {
	++clear_abort_next;
	return;
    }

    if (strcmp(s, "REPORT") == 0) {
	++report_next;
	return;
    }

    if (strcmp(s, "CLR_REPORT") == 0) {
	++clear_report_next;
	return;
    }

    if (strcmp(s, "TIMEOUT") == 0) {
	++timeout_next;
	return;
    }

    if (strcmp(s, "ECHO") == 0) {
	++echo_next;
	return;
    }

    if (strcmp(s, "SAY") == 0) {
	++say_next;
	return;
    }

/*
 * Fetch the expect and reply string.
 */
    for (;;) {
	expect = expect_strtok (s, "-");
	s      = (char *) 0;

	if (expect == (char *) 0)
	    return;

	reply = expect_strtok (s, "-");

/*
 * Handle the expect string. If successful then exit.
 */
	if (get_string (expect))
	    return;

/*
 * If there is a sub-reply string then send it. Otherwise any condition
 * is terminal.
 */
	if (reply == (char *) 0 || exit_code != 3)
	    break;

	chat_send (reply);
    }

/*
 * The expectation did not occur. This is terminal.
 */
    if (fail_reason)
	chat_logf("Failed (%s)", fail_reason);
    else
	chat_logf("Failed");
    terminate(exit_code);
}
Пример #6
0
/* Generischer Kampfzauber */
int sp_kampfzauber(struct castorder * co)
{
  fighter * fi = co->magician.fig;
  int level = co->level;
  double power = co->force;
  const spell * sp = co->sp;
  battle *b = fi->side->battle;
  troop at, dt;
  message *m;
  /* Immer aus der ersten Reihe nehmen */
  int force, enemies;
  int killed = 0;
  const char *damage;

  if (power <= 0)
    return 0;
  at.fighter = fi;
  at.index = 0;

  switch (sp->id) {
      /* lovar halbiert im Schnitt! */
    case SPL_FIREBALL:
      damage = spell_damage(0);
      force = lovar(get_force(power, 0));
      break;
    case SPL_HAGEL:
      damage = spell_damage(2);
      force = lovar(get_force(power, 4));
      break;
    case SPL_METEORRAIN:
      damage = spell_damage(1);
      force = lovar(get_force(power, 1));
      break;
    default:
      damage = spell_damage(10);
      force = lovar(get_force(power, 10));
  }

  enemies = count_enemies(b, fi, FIGHT_ROW, BEHIND_ROW - 1, SELECT_ADVANCE);
  if (enemies == 0) {
    message *m =
      msg_message("battle::out_of_range", "mage spell", fi->unit, sp);
    message_all(b, m);
    msg_release(m);
    return 0;
  }

  while (force > 0 && killed < enemies) {
    dt = select_enemy(fi, FIGHT_ROW, BEHIND_ROW - 1, SELECT_ADVANCE);
    assert(dt.fighter);
    --force;
    killed += terminate(dt, at, AT_COMBATSPELL, damage, false);
  }

  m = msg_message("battle::combatspell", "mage spell dead",
    fi->unit, sp, killed);
  message_all(b, m);
  msg_release(m);

  return level;
}
Пример #7
0
Display::~Display()
{
    terminate();
}
int server(char* port) {

	int completed=0;


	node *IP_list = NULL;
	int noOfConnections=0;
	int cmdNo;

	fd_set read_fds, write_fds,read_fds_copy,write_fds_copy;
	FD_ZERO(&read_fds);
	FD_ZERO(&write_fds);
	
	//int fdMax = STDIN_FILENO;
	int fdMax = 0; // 0 is file descriptor for standard input 
	int serverSocket, nSocket,selected;  
	struct sockaddr_in serverAddress,clientAddress;
	struct sockaddr_storage getPeerInfo;
	socklen_t clientAddrLen = sizeof(clientAddress);

	char msg[5000]; 
	int numBytes;

	serverSocket= socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);  

	printf("Server created \n");
	
	if(serverSocket == -1) {
		printf("Server: Socket creation failed\n");
	}

	fdMax = serverSocket;
	/* Beej: Allows other sockets to bind() to this port, unless there is an active listening socket bound to the port already. 
	This enables you to get around those "Address already in use" error messages when you try to restart your server after a crash. */
	int socketReuse = 1; 
	setsockopt(serverSocket,SOL_SOCKET,SO_REUSEADDR,&socketReuse,sizeof(int));


	serverAddress.sin_addr.s_addr = INADDR_ANY;
	serverAddress.sin_family = AF_INET;
	serverAddress.sin_port = htons(atoi(port)); //network Byte order

	// bind
	if(bind(serverSocket,(struct sockaddr*)&serverAddress,sizeof(serverAddress))== -1) {
		printf("Server: Binding failed\n");
		close(serverSocket); 
	}
	printf("Server has been bound to port %d \n",atoi(port));

	//printf("Server sockets is %d \n",serverSocket);

	listen(serverSocket,10);

	FD_SET(STDIN_FILENO,&read_fds);
	FD_SET(serverSocket,&read_fds);
	
	while(1) {
		// Create copies of fd_sets because select will modify them
		read_fds_copy = read_fds;
		write_fds_copy = write_fds;
		if (select(fdMax+1, &read_fds_copy,NULL, NULL, NULL) == -1) {
			perror("Server : Select error");
			continue;
		}
		for(selected = 0;selected<=fdMax;selected++) {
			if(FD_ISSET(selected,&read_fds_copy)) {
				/* Need to handle  3 scenarios
				1. Data available from Server socket (New Client arrives)
				2. Data available from Standard Input (Commands)
				3. Data available from clients (SYNC? )
				*/
				if(selected==serverSocket){ // Scenario 1
					printf("Server : A client is trying to connect.\n");
					
					memset(&clientAddress, 0, sizeof(clientAddrLen));
					if ((nSocket = accept(serverSocket,(struct sockaddr*)&clientAddress,&clientAddrLen))==-1) {
						printf("Server: Accept failed\n");
					}
					
					if (noOfConnections >= 4) {
						close(nSocket);
						printf("Server : Connection limit exceeded!\n");
						continue;
					}

					memset(msg,0,5000);
					// receive clients listening port number
					numBytes = recv(nSocket,msg,5000,0);
					printf("New connection from %s : %d \n",inet_ntoa(clientAddress.sin_addr),atoi(msg));
					printf("Client has been registered .Yay!\n");


					setsockopt(nSocket,SOL_SOCKET,SO_REUSEADDR,&socketReuse,sizeof(int));
					push(clientAddress,nSocket,atoi(msg),&IP_list);
										noOfConnections++;

					sendAll(IP_list,noOfConnections);
					FD_SET(nSocket,&read_fds);
					
					if(nSocket > fdMax) 
						fdMax = nSocket;
				} // End Scenario 1
				if(selected==0){ // Scenario 2
					memset(msg,0,sizeof(msg)); // clear msg array
					if ((numBytes = read(selected, msg, sizeof(msg))) <= 0)
						perror("Server read error");

					cmdNo=parse(msg);
					int fd;

					switch(cmdNo){
						case 0: // HELP
						help();
						break;
						case 1:
						creator(); //CREATOR
						break;
						case 2:
						display(port,1); //DISPLAY 
						break;
						case 3: //REGISTER
						printf("REGISTER command not available for server\n");
						break;
						case 4: //CONNECT 
						printf("CONNECT command not available for server\n");
						break;
						case 5: //LIST
						displayList(IP_list); 
						break;
						case 6: //TERMINATE 
						fd=terminate(&IP_list);
                            if(fd!=-1){
                                FD_CLR(fd,&read_fds);
                                FD_CLR(fd,&write_fds);

                                fdMax = getMaxFD(IP_list);
                                noOfConnections--;
                                if(noOfConnections==0){
                                    IP_list=NULL;
                                }

                            }
                            else{
                                printf("Invalid connection ID \n");

                            }
						break;
						break;
						case 7: //QUIT
						quit(&IP_list);
						return 1;
						break;
						case 8: //GET
						printf("GET command not available for server\n");
						break;
						case 9: //PUT
						printf("PUT command not available for server\n");
						break;
						case 10: //SYNC
						printf("SYNC command not available for server\n");
						break;
					}
				} // End Scenario 2

                else { // Scenario 3

					if ((numBytes = recv(selected, msg, 5000, 0)) <= 0) {
						if (numBytes == 0)
						{

							if(getpeername(selected,(struct sockaddr*)&getPeerInfo,&clientAddrLen)<0)
							{
								perror("Server : Error\n");
								return 0;
							}

							struct sockaddr_in *s = (struct sockaddr_in *)&getPeerInfo;

							char* IPAdd = (char*)malloc(sizeof(char)*INET6_ADDRSTRLEN);
							int targetPort = ntohs(ntohs(s->sin_port));
							inet_ntop(AF_INET, &(s->sin_addr), IPAdd, INET6_ADDRSTRLEN);

							printf("Server: Connection closed by IP %s\n",IPAdd);

							
							delete(IPAdd,targetPort,&IP_list);
							FD_CLR(selected,&read_fds);
							close(selected);
							noOfConnections--;

							if(noOfConnections == 0){
								printf("All connections are closed\n");
								IP_list=NULL;}
							else
							{
								// Broad cast current peer list
								fdMax = getMaxFD(IP_list);
								sendAll(IP_list,noOfConnections);
								
							}
						}
						else
						{
							//perror("Server");
						}
					}
					else// we got some data from a client
					{


						char command1[4];
						char command2[6];
                        memcpy(command1,msg,4); // Extract first 3 characters from incoming data
                        memcpy(command2,msg,6); // Extract first 3 characters from incoming data


                        if(!(strcmp(command1,"SYNC")) || (!(strcmp(command1,"sync")))) { // Check if it is GET command


                        	printf("Triggering SYNC on all connected peers!\n");


                        	node *curr=IP_list;
                        	
							syncRelay(curr);
							memset(msg,0,5000); // reset read buffer
							curr=curr->next;
							completed++;
					



                        }


                        else if(!(strcmp(command2,"E_SYNC")) || (!(strcmp(command2,"e_sync")))) { // Check if it is GET command

                        	printf("ESYNC received\n");
                        	int i;

                        	node *curr=IP_list;


                        	if(completed!=noOfConnections){
                        		for(i=0;i<completed;i++){
                        			curr=curr->next;
                        		}
                        		syncRelay(curr);
                        		completed++;
                        	}
                        	else if(completed==noOfConnections){
                        		completed=0;
                        	}


							memset(msg,0,5000); // reset read buffer



                        }

					}
                }
			}
		}
	}
}
Пример #9
0
static void
server (int fd, int server_init)
{
int ret;
char buffer[MAX_BUF + 1];
  /* this must be called once in the program
   */
  global_init ();

  if (debug)
    {
      gnutls_global_set_log_function (server_log_func);
      gnutls_global_set_log_level (4711);
    }

  gnutls_anon_allocate_server_credentials (&anoncred);

  session = initialize_tls_session ();

  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) fd);
  gnutls_transport_set_push_function (session, push);

  do 
    {
      ret = gnutls_handshake (session);
    }
  while (ret < 0 && gnutls_error_is_fatal(ret) == 0);
  if (ret < 0)
    {
      close (fd);
      gnutls_deinit (session);
      fail ("server: Handshake has failed (%s)\n\n", gnutls_strerror (ret));
      terminate();
    }
  if (debug)
    success ("server: Handshake was completed\n");

  if (debug)
    success ("server: TLS version is: %s\n",
             gnutls_protocol_get_name (gnutls_protocol_get_version
                                       (session)));

  /* see the Getting peer's information example */
  /* print_info(session); */

  if (server_init)
    {
      if (debug) success("server: Sending dummy packet\n");
      ret = gnutls_rehandshake(session);
      if (ret < 0)
        {
          fail ("gnutls_rehandshake: %s\n", gnutls_strerror(ret));
          terminate();
        }

      if (debug) success("server: Initiating rehandshake\n");
      do 
        {
          ret = gnutls_handshake (session);
        }
      while (ret < 0 && gnutls_error_is_fatal(ret) == 0);

      if (ret < 0)
        {
          fail ("server: 2nd gnutls_handshake: %s\n", gnutls_strerror(ret));
          terminate();
        }
    }

  for (;;)
    {
      memset (buffer, 0, MAX_BUF + 1);

      do {
        ret = gnutls_record_recv (session, buffer, MAX_BUF);
      } while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);

      if (ret == 0)
        {
          if (debug)
            success ("server: Peer has closed the GnuTLS connection\n");
          break;
        }
      else if (ret < 0)
        {
          if (!server_init && ret == GNUTLS_E_REHANDSHAKE)
            {
              if (debug) success("Initiating rehandshake due to client request\n");
              do 
                {
                  ret = gnutls_handshake (session);
                }
              while (ret < 0 && gnutls_error_is_fatal(ret) == 0);
              if (ret == 0) break;
            }

          fail ("server: Received corrupted data(%s). Closing...\n", gnutls_strerror(ret));
          terminate();
        }
      else if (ret > 0)
        {
          /* echo data back to the client
           */
          do {
            ret = gnutls_record_send (session, buffer, strlen (buffer));
          } while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);
        }
    }
  

  /* do not wait for the peer to close the connection.
   */
  gnutls_bye (session, GNUTLS_SHUT_WR);

  close (fd);
  gnutls_deinit (session);

  gnutls_anon_free_server_credentials (anoncred);

  gnutls_global_deinit ();

  if (debug)
    success ("server: finished\n");
}
Пример #10
0
static void
client (int fd, int server_init)
{
  int ret;
  char buffer[MAX_BUF + 1];
  gnutls_anon_client_credentials_t anoncred;
  /* Need to enable anonymous KX specifically. */

  global_init ();

  if (debug)
    {
      gnutls_global_set_log_function (client_log_func);
      gnutls_global_set_log_level (4711);
    }

  gnutls_anon_allocate_client_credentials (&anoncred);

  /* Initialize TLS session
   */
  gnutls_init (&session, GNUTLS_CLIENT|GNUTLS_DATAGRAM);
  gnutls_dtls_set_mtu( session, 1500);

  /* Use default priorities */
  gnutls_priority_set_direct (session, "NONE:+VERS-DTLS1.0:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ANON-ECDH:+CURVE-ALL", NULL);

  /* put the anonymous credentials to the current session
   */
  gnutls_credentials_set (session, GNUTLS_CRD_ANON, anoncred);

  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) fd);
  gnutls_transport_set_push_function (session, push);

  /* Perform the TLS handshake
   */
  do 
    {
      ret = gnutls_handshake (session);
    }
  while (ret < 0 && gnutls_error_is_fatal(ret) == 0);

  if (ret < 0)
    {
      fail ("client: Handshake failed\n");
      gnutls_perror (ret);
      exit(1);
    }
  else
    {
      if (debug)
        success ("client: Handshake was completed\n");
    }

  if (debug)
    success ("client: TLS version is: %s\n",
             gnutls_protocol_get_name (gnutls_protocol_get_version
                                       (session)));

  if (!server_init)
    {
      if (debug) success("Initiating client rehandshake\n");
      do 
        {
          ret = gnutls_handshake (session);
        }
      while (ret < 0 && gnutls_error_is_fatal(ret) == 0);

      if (ret < 0)
        {
          fail ("2nd client gnutls_handshake: %s\n", gnutls_strerror(ret));
          terminate();
        }
    }
  else
    {
      do {
        ret = gnutls_record_recv (session, buffer, MAX_BUF);
      } while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);
    }

  if (ret == 0)
    {
      if (debug)
        success ("client: Peer has closed the TLS connection\n");
      goto end;
    }
  else if (ret < 0)
    {
      if (server_init && ret == GNUTLS_E_REHANDSHAKE)
        {
          if (debug) success("Initiating rehandshake due to server request\n");
          do 
            {
              ret = gnutls_handshake (session);
            }
          while (ret < 0 && gnutls_error_is_fatal(ret) == 0);
        }

      if (ret != 0)
        {
          fail ("client: Error: %s\n", gnutls_strerror (ret));
          exit(1);
        }
    }

  do {
    ret = gnutls_record_send (session, MSG, strlen (MSG));
  } while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);
  gnutls_bye (session, GNUTLS_SHUT_WR);

end:

  close (fd);

  gnutls_deinit (session);

  gnutls_anon_free_client_credentials (anoncred);

  gnutls_global_deinit ();
}
Пример #11
0
int quark_renorm( void ) {
register int i, dir;
register site *s;
int j, cgn;
Real mass_x2, finalrsq;
Real pix, piy, piz, pit;
Real sin_pmu, q_mu, prop_a, prop_b, z_fac, m_func, ftmp = 0;
Real r1, r2, r3;
int pmu, px, py, pz, pt;
int pxn, pyn, pzn, ptn;
int currentnode;
int j1, jm2, k, dirs[4];
msg_tag *mtag[2];
int j_mass;
su3_vector **psim = NULL;
int xi, j2, j3, j4, parity;
  imp_ferm_links_t **fn;

int multiflag;
FILE *fp_mom_ks[MAX_NUM_MASS];	/* for writing mom propagator files */
char filename[50];
 int prec = PRECISION;   /* Make internal precision for CG the same as
			    the prevailing precision */

    pix = 2.*PI / (Real)nx;
    piy = 2.*PI / (Real)ny;
    piz = 2.*PI / (Real)nz;
    pit = 2.*PI / (Real)nt;

    cgn = 0;

    if( num_mass == 1){
	multiflag = 0;
    }
    else{
	multiflag = 1;
	psim = (su3_vector **)malloc(num_mass*sizeof(su3_vector *));
	for(j=0; j<num_mass; j++){
	    psim[j] = (su3_vector *)malloc(sites_on_node*sizeof(su3_vector));
	}
    }

    /* Open the momentum propagator files */
    if(this_node == 0){
	for(j=0; j<num_mass; j++){
	    sprintf(filename,"mom_pt_prop.m_%d",j);
	    fp_mom_ks[j] = fopen(filename, "ab");
	    if(fp_mom_ks[j] == NULL){
		printf("quark_renorm: Node %d can't open file %s, error %d\n",
		       this_node,filename,errno);fflush(stdout);
		terminate(1);
	    }
	}
    }

    rephase( ON );	/* Turn staggered phases on */

    /* Create fat and long links */
    restore_fermion_links_from_site(fn_links, PRECISION);
    fn = get_fm_links(fn_links);
    /* If we want HISQ support, we need the Naik term epsilon index
        here for now we use fn[0] only, which has no epsilon
        correction. */

    /* Loop over the 16 source points */
    for(xi=0; xi<16; xi++){

	/* Initialize color trace of the propagator */
	FORALLSITES(i,s){
	    for(j=0; j<num_mass; j++){
		s->trace_prop[j].real = 0.0;
		s->trace_prop[j].imag = 0.0;
	    }
	}

	j1 = xi%2;
	k = xi/2;
	j2 = k%2;
	k /= 2;
	j3 = k%2;
	k /= 2;
	j4 = k%2;
	parity = (j1+j2+j3+j4)%2;
/*	dirs[XUP] = j1;
	dirs[YUP] = j2;
	dirs[ZUP] = j3;
	dirs[TUP] = j4; */

	/* Loop over colors of source vector */
	for(j=0; j<3; j++){

	    /* initialize the source in phi */
	    FORALLSITES(i,s){
		clearvec( &(s->phi));
	    }

	    /* Point source at site xi in the hypercube at origin */
	    if( node_number(j1,j2,j3,j4) == this_node ){
		i=node_index(j1,j2,j3,j4);
		lattice[i].phi.c[j].real = -1.0;
	    }

	    if( multiflag == 0){
		for(j_mass=0; j_mass<num_mass; j_mass++){
		    FORALLSITES(i,s){
			clearvec( &(s->xxx1));
		    }

		    if(parity == 0){
			/* do a C.G. (source in phi, result in xxx1) */
		      cgn += ks_congrad( F_OFFSET(phi), F_OFFSET(xxx1),
					 mass[j_mass], niter, nrestart, 
					 rsqprop,  PRECISION, 
					 EVEN, &finalrsq, fn[0]);
		      /* Multiply by -Madjoint */
		      dslash_site( F_OFFSET(xxx1), F_OFFSET(ttt), ODD,
				   fn[0]);
		      mass_x2 = 2.*mass[j_mass];
		      FOREVENSITES(i,s){
			scalar_mult_su3_vector( &(s->xxx1), -mass_x2,
						&(s->ttt));
		      }
		    }
		    else{
Пример #12
0
int 
eval_options (int argc, char **argv, struct target_opts* defaults, 
              const char** exe_opts)
{
    const char opt_timeout[]  = "-t";
    const char opt_data_dir[] = "-d";
    const char opt_t_flags[]  = "-x";
    const char opt_compat[]   = "--compat";
    const char opt_exit[]     = "--exit";
    const char opt_help[]     = "--help";
    const char opt_ignore[]   = "--ignore";
    const char opt_nocompat[] = "--nocompat";
    const char opt_signal[]   = "--signal";
    const char opt_sleep[]    = "--sleep";
    const char opt_ulimit[]   = "--ulimit";
    const char opt_verbose[]  = "--verbose";
    const char opt_warn[]     = "--warn";

    int i;

    assert (0 != argv);
    assert (0 != defaults);

    memset (defaults, 0, sizeof (target_opts));

    /* The chain of preprocesor logic below initializes the defaults->c_warn 
       and defaults->l_warn values.
    */
#ifdef __GNUG__
    parse_warn_opts ("Gcc", defaults);
#elif defined (__HP_aCC)
    parse_warn_opts ("Acc", defaults);
#elif defined (__IBMCPP__)
    parse_warn_opts ("Xlc", defaults);
#elif defined (__SUNPRO_CC)
    parse_warn_opts ("Sunpro", defaults);
#elif defined (SNI)
    parse_warn_opts ("Cds", defaults);
#elif defined (__APOGEE__) /* EDG variant that doesn't define __EDG__. */
    parse_warn_opts ("Como", defaults);

/* The following are EDG variants, that define __EDG__ */
#elif defined (__DECCXX)
    parse_warn_opts ("Cxx", defaults);
#elif defined (_SGI_COMPILER_VERSION)
    parse_warn_opts ("Mipspro", defaults);
#elif defined (__INTEL_COMPILER)
    parse_warn_opts ("Icc", defaults);

/* So we need to check for __EDG__ after we check for them. */
#elif defined (__EDG__)
    parse_warn_opts ("Eccp", defaults);
#endif

    if (1 == argc || '-' != argv [1][0])
        return 1;

    for (i = 1; i < argc && '-' == argv [i][0]; ++i) {

        /* the name of the option being processed */
        const char* optname = argv [i];

        /* the option's argument, if any */
        const char* optarg  = 0;

        char* end = 0;

        switch (argv [i][1]) {
        case '?':   /* display help and exit with status of 0 */
        case 'h':
            show_usage (0);

        case 'r':
            ++i; /* Ignore -r option (makefile compat) */
            break;

        case 't':   /* executable timeout in seconds */
            optname = opt_timeout;
            optarg  = get_short_val (argv, &i);
            if (optarg) {
                if (!isdigit (*optarg))
                    bad_value (optname, optarg);

                errno = 0;
                defaults->timeout = unsigned (strtol (optarg, &end, 10));
                if (*end || errno)
                    bad_value (optname, optarg);
            }
            else
                missing_value (optname);

            break;

        case 'd':   /* directory containing example reference files */
            optname = opt_data_dir;
            defaults->data_dir = get_short_val (argv, &i);
            if (!defaults->data_dir)
                missing_value (optname);
            break;

        case 'v':   /* enable verbose mode */
            optname = opt_verbose;
            ++defaults->verbose;
            break;

        case 'x':   /* command line options to pass to targets */
            optname  = opt_t_flags;
            *exe_opts = get_short_val (argv, &i);
            if (!*exe_opts)
                missing_value (optname);
            break;

        case '-':   /* long options */
        {
            const size_t arglen = strlen (argv [i]);

            /* abort processing on --, eat token */
            if ('\0' == argv [i][2])
                return i+1;

            if (   sizeof opt_compat - 1 == arglen
                && !memcmp (opt_compat, argv [i], sizeof opt_compat)) {
                /* enter compatibility mode */
                defaults->compat = 1;
                break;
            }
            else if (   sizeof opt_nocompat - 1 == arglen
                     && !memcmp (opt_nocompat, argv [i], sizeof opt_nocompat)) {
                /* exit compatibility mode */
                defaults->compat = 0;
                break;
            }
            else if (   sizeof opt_exit - 1 <= arglen
                     && !memcmp (opt_exit, argv [i], sizeof opt_exit - 1)) {
                /* exit immediately with the specified status */
                optname = opt_exit;
                optarg  = get_long_val (argv, &i, sizeof opt_exit - 1);
                if (optarg && *optarg) {
                    if (!isdigit (*optarg))
                        bad_value (optname, optarg);

                    errno = 0;
                    const long code = strtol (optarg, &end, 10);
                    if ('\0' == *end && !errno)
                        exit (int (code));
                }
            }
            else if (   sizeof opt_help - 1 == arglen
                     && !memcmp (opt_help, argv [i], sizeof opt_help - 1)) {
                /* display help and exit with status of 0 */
                optname = opt_help;
                show_usage (0);
                break;
            }
            else if (   sizeof opt_sleep - 1 <= arglen
                     && !memcmp (opt_sleep, argv [i], sizeof opt_sleep - 1)) {
                /* sleep for the specified number of seconds */ 
                optname = opt_sleep;
                optarg  = get_long_val (argv, &i, sizeof opt_sleep - 1);
                if (optarg && *optarg) {
                    if (!isdigit (*optarg))
                        bad_value (optname, optarg);

                    errno = 0;
                    const long nsec = strtol (optarg, &end, 10);
                    if ('\0' == *end && 0 <= nsec && !errno) {
                        rw_sleep (int (nsec));
                        break;
                    }
                }
            }
            else if (   sizeof opt_signal - 1 <= arglen
                     && !memcmp (opt_signal, argv [i], sizeof opt_signal - 1)) {
                /* send ourselves the specified signal */
                optname = opt_signal;
                optarg  = get_long_val (argv, &i, sizeof opt_signal - 1);
                if (optarg && *optarg) {
                    const int signo = get_signo (optarg);
                    if (0 <= signo) {
                        if (0 > raise (signo))
                            terminate (1, "raise(%s) failed: %s\n",
                                       get_signame (signo), strerror (errno));
                        break;
                    }
                }
            }
            else if (   sizeof opt_ignore - 1 <= arglen
                     && !memcmp (opt_ignore, argv [i], sizeof opt_ignore - 1)) {
                /* ignore the specified signal */
                optname = opt_ignore;
                optarg  = get_long_val (argv, &i, sizeof opt_ignore - 1);
                if (optarg && *optarg) {
                    const int signo = get_signo (optarg);
                    if (0 <= signo) {
                        if (rw_signal (signo, 0 /* SIG_IGN */))
                            terminate (1, "rw_signal(%s, ...) failed: %s\n",
                                       get_signame (signo), strerror (errno));
                        break;
                    }
                }
            }
            else if (   sizeof opt_ulimit - 1 <= arglen
                     && !memcmp (opt_ulimit, argv [i], sizeof opt_ulimit - 1)) {
                /* set child process resource utilization limits */
                optname = opt_ulimit;
                optarg  = get_long_val (argv, &i, sizeof opt_ulimit - 1);
                if (optarg && *optarg) {
                    if (!parse_limit_opts (optarg, defaults)) {
                        break;
                    }
                }
            }
            else if (   sizeof opt_warn - 1 <= arglen
                     && !memcmp (opt_warn, argv [i], sizeof opt_warn - 1)) {
                /* set compiler warning mode */
                optname = opt_warn;
                optarg  = get_long_val (argv, &i, sizeof opt_warn - 1);
                if (optarg && *optarg) {
                    if (!parse_warn_opts (optarg, defaults)) {
                        break;
                    }
                }
            }
            /* fall through */
        }
        default:
            if (optarg) {
                if (*optarg)
                    bad_value (optname, optarg);
                else
                    missing_value (optname);
            }

            if (argv [i])
                bad_option (argv [i]);
            else
                missing_value (optname);
        }
    }

    return i;
}
Пример #13
0
void FileReader::stop()
{
    terminate();
}
Пример #14
0
void conn_data_handler P1(int, fd)
{
    int conn_index;
    int buf_index;
    int num_bytes;
    int msgtype;
    int leftover;
    char *buf;
    int res, msglen, expecting;
    long unread_bytes;

    if ((conn_index = index_by_fd(fd)) == -1) {
	fprintf(stderr, "conn_data_handler: invalid fd.\n");
	return;
    }
    debug(512, ("conn_data_handler: read on fd %d\n", fd));

    /* append new data to end of leftover data (if any) */
    leftover = all_conns[conn_index].leftover;
    buf = (char *) &all_conns[conn_index].buf[0];
    num_bytes = OS_socket_read(fd, buf + leftover, (IN_BUF_SIZE - 1) - leftover);

    switch (num_bytes) {
    case -1:
	switch (errno) {
#ifdef WIN32
	case WSAEWOULDBLOCK:
#endif
	case EWOULDBLOCK:
	    debug(512, ("conn_data_handler: read on fd %d: Operation would block.\n",
			fd));
	    break;
	default:
	    perror("conn_data_handler: read");
	    terminate(conn_index);
	    break;
	}
	break;
    case 0:
	if (all_conns[conn_index].state == CONN_CLOSED)
	    fprintf(stderr, "get_user_data: tried to read from closed fd.\n");
	terminate(conn_index);
	break;
    default:
	debug(512, ("conn_data_handler: read %d bytes on fd %d\n", num_bytes, fd));
	num_bytes += leftover;
	buf_index = 0;
	expecting = 0;
	while (num_bytes > sizeof(int) && buf_index < (IN_BUF_SIZE - 1)) {
	    /* get message type */
	    memcpy((char *) &msgtype, (char *) &buf[buf_index], sizeof(int));
	    debug(512, ("conn_data_handler: message type: %d\n", msgtype));

	    if (msgtype == NAMEBYIP) {
		if (buf[buf_index + sizeof(int)] == '\0') {
		    /* no data here...resync */
		    buf_index++;
		    num_bytes--;
		    continue;
		}
		if (expecting && num_bytes < expecting) {
		    /*
		     * message truncated...back up to DATALEN message; exit
		     * loop...and try again later
		     */
		    buf_index -= (sizeof(int) + sizeof(int));
		    num_bytes += (sizeof(int) + sizeof(int));
		    break;
		}
		res = name_by_ip(conn_index, &buf[buf_index]);
	    } else if (msgtype == IPBYNAME) {
		if (buf[buf_index + sizeof(int)] == '\0') {
		    /* no data here...resync */
		    buf_index++;
		    num_bytes--;
		    continue;
		}
		if (expecting && num_bytes < expecting) {
		    /*
		     * message truncated...back up to DATALEN message; exit
		     * loop...and try again later
		     */
		    buf_index -= (sizeof(int) + sizeof(int));
		    num_bytes += (sizeof(int) + sizeof(int));
		    break;
		}
		res = ip_by_name(conn_index, &buf[buf_index]);
	    } else if (msgtype == DATALEN) {
		if (num_bytes > (sizeof(int) + sizeof(int))) {
		    memcpy((char *) &expecting, (char *) &buf[buf_index + sizeof(int)], sizeof(int));
		    /*
		     * advance to next message
		     */
		    buf_index += (sizeof(int) + sizeof(int));
		    num_bytes -= (sizeof(int) + sizeof(int));
		    if (expecting > IN_BUF_SIZE || expecting <= 0) {
			fprintf(stderr, "conn_data_handler: bad data length %d\n", expecting);
			expecting = 0;
		    }
		    continue;
		} else {
		    /*
		     * not enough bytes...assume truncated; exit loop...we'll
		     * handle this message later
		     */
		    break;
		}
	    } else {
		fprintf(stderr, "conn_data_handler: unknown message type %08x\n", msgtype);
		/* advance through buffer */
		buf_index++;
		num_bytes--;
		continue;
	    }

	    msglen = (int) (sizeof(int) + strlen(&buf[buf_index + sizeof(int)]) +1);
	    if (res) {
		/*
		 * ok...advance to next message
		 */
		buf_index += msglen;
		num_bytes -= msglen;
	    } else if (msglen < num_bytes || (expecting && expecting == msglen)) {
		/*
		 * failed...
		 */

		/*
		 * this was a complete message...advance to the next one
		 */
		msglen = (int) (sizeof(int) + strlen(&buf[buf_index + sizeof(int)]) +1);
		buf_index += msglen;
		num_bytes -= msglen;
		expecting = 0;
	    }
	    else if (!OS_socket_ioctl(fd, FIONREAD, &unread_bytes) &&
		     unread_bytes > 0) {
		/*
		 * msglen == num_bytes could be a complete message... if
		 * there's unread data we'll assume it was truncated
		 */
		break;
	    } else {
		/*
		 * nothing more?  then discard message (it was the last one)
		 */
		buf_index = 0;
		num_bytes = 0;
		break;
	    }
	}

	/* keep track of leftover buffer contents */
	if (num_bytes && buf_index)
	    memmove(buf, &buf[buf_index], num_bytes);
	buf[num_bytes] = '\0';
	all_conns[conn_index].leftover = num_bytes;

	break;
    }
}
Пример #15
0
bool Display::initialize()
{
    if (isInitialized())
    {
        return true;
    }

    mD3d9Module = LoadLibrary(TEXT("d3d9.dll"));
    if (mD3d9Module == NULL)
    {
        terminate();
        return false;
    }

    typedef IDirect3D9* (WINAPI *Direct3DCreate9Func)(UINT);
    Direct3DCreate9Func Direct3DCreate9Ptr = reinterpret_cast<Direct3DCreate9Func>(GetProcAddress(mD3d9Module, "Direct3DCreate9"));

    if (Direct3DCreate9Ptr == NULL)
    {
        terminate();
        return false;
    }

    typedef HRESULT (WINAPI *Direct3DCreate9ExFunc)(UINT, IDirect3D9Ex**);
    Direct3DCreate9ExFunc Direct3DCreate9ExPtr = reinterpret_cast<Direct3DCreate9ExFunc>(GetProcAddress(mD3d9Module, "Direct3DCreate9Ex"));

    // Use Direct3D9Ex if available. Among other things, this version is less
    // inclined to report a lost context, for example when the user switches
    // desktop. Direct3D9Ex is available in Windows Vista and later if suitable drivers are available.
    if (Direct3DCreate9ExPtr && SUCCEEDED(Direct3DCreate9ExPtr(D3D_SDK_VERSION, &mD3d9ex)))
    {
        ASSERT(mD3d9ex);
        mD3d9ex->QueryInterface(IID_IDirect3D9, reinterpret_cast<void**>(&mD3d9));
        ASSERT(mD3d9);
    }
    else
    {
        mD3d9 = Direct3DCreate9Ptr(D3D_SDK_VERSION);
    }

    if (mD3d9)
    {
        if (mDc != NULL)
        {
        //  UNIMPLEMENTED();   // FIXME: Determine which adapter index the device context corresponds to
        }

        HRESULT result = mD3d9->GetDeviceCaps(mAdapter, mDeviceType, &mDeviceCaps);

        if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY)
        {
            return error(EGL_BAD_ALLOC, false);
        }

        if (mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(2, 0))
        {
            terminate();
            return error(EGL_NOT_INITIALIZED, false);
        }

        mMinSwapInterval = 4;
        mMaxSwapInterval = 0;

        if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_IMMEDIATE) {mMinSwapInterval = std::min(mMinSwapInterval, 0); mMaxSwapInterval = std::max(mMaxSwapInterval, 0);}
        if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_ONE)       {mMinSwapInterval = std::min(mMinSwapInterval, 1); mMaxSwapInterval = std::max(mMaxSwapInterval, 1);}
        if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_TWO)       {mMinSwapInterval = std::min(mMinSwapInterval, 2); mMaxSwapInterval = std::max(mMaxSwapInterval, 2);}
        if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_THREE)     {mMinSwapInterval = std::min(mMinSwapInterval, 3); mMaxSwapInterval = std::max(mMaxSwapInterval, 3);}
        if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_FOUR)      {mMinSwapInterval = std::min(mMinSwapInterval, 4); mMaxSwapInterval = std::max(mMaxSwapInterval, 4);}

        const D3DFORMAT renderTargetFormats[] =
        {
            D3DFMT_A1R5G5B5,
        //  D3DFMT_A2R10G10B10,   // The color_ramp conformance test uses ReadPixels with UNSIGNED_BYTE causing it to think that rendering skipped a colour value.
            D3DFMT_A8R8G8B8,
            D3DFMT_R5G6B5,
            D3DFMT_X1R5G5B5,
            D3DFMT_X8R8G8B8
        };

        const D3DFORMAT depthStencilFormats[] =
        {
        //  D3DFMT_D16_LOCKABLE,
            D3DFMT_D32,
        //  D3DFMT_D15S1,
            D3DFMT_D24S8,
            D3DFMT_D24X8,
        //  D3DFMT_D24X4S4,
            D3DFMT_D16,
        //  D3DFMT_D32F_LOCKABLE,
        //  D3DFMT_D24FS8
        };

        D3DDISPLAYMODE currentDisplayMode;
        mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);

        ConfigSet configSet;

        for (int formatIndex = 0; formatIndex < sizeof(renderTargetFormats) / sizeof(D3DFORMAT); formatIndex++)
        {
            D3DFORMAT renderTargetFormat = renderTargetFormats[formatIndex];

            HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, renderTargetFormat);

            if (SUCCEEDED(result))
            {
                for (int depthStencilIndex = 0; depthStencilIndex < sizeof(depthStencilFormats) / sizeof(D3DFORMAT); depthStencilIndex++)
                {
                    D3DFORMAT depthStencilFormat = depthStencilFormats[depthStencilIndex];
                    HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, depthStencilFormat);

                    if (SUCCEEDED(result))
                    {
                        HRESULT result = mD3d9->CheckDepthStencilMatch(mAdapter, mDeviceType, currentDisplayMode.Format, renderTargetFormat, depthStencilFormat);

                        if (SUCCEEDED(result))
                        {
                            // FIXME: enumerate multi-sampling

                            configSet.add(currentDisplayMode, mMinSwapInterval, mMaxSwapInterval, renderTargetFormat, depthStencilFormat, 0);
                        }
                    }
                }
            }
        }

        // Give the sorted configs a unique ID and store them internally
        EGLint index = 1;
        for (ConfigSet::Iterator config = configSet.mSet.begin(); config != configSet.mSet.end(); config++)
        {
            Config configuration = *config;
            configuration.mConfigID = index;
            index++;

            mConfigSet.mSet.insert(configuration);
        }

        if (!createDevice())
        {
            terminate();

            return false;
        }
    }

    if (!isInitialized())
    {
        terminate();

        return false;
    }

    return true;
}
MessageDefinitionLoader::Impl::~Impl() {
  terminate();
  wait();
}
Пример #17
0
int main(int argc, char *argv[])  {
#ifndef COULOMB
  int todo,sm_lev,lsmeared=0;
#else
  su3_matrix *links, *ape_links;
#endif
  int prompt;
  double dtime;
  
  initialize_machine(&argc,&argv);
  
  /* Remap standard I/O */
  if(remap_stdio_from_args(argc, argv) == 1)terminate(1);
  
  
  g_sync();
  /* set up */
  prompt = setup();
  
  /* loop over input sets */
  while( readin(prompt) == 0){
    
    if(prompt == 2)continue;
    dtime = -dclock();
    
#ifdef COULOMB
    if(this_node == 0) 
      printf("Fixing to Coulomb gauge\n");
    fixflag = COULOMB_GAUGE_FIX;
    
    gaugefix(TUP,(Real)1.8,500,GAUGE_FIX_TOL);
    
    links = create_G_from_site();
    ape_links = create_G();
    ape_smear_field_dir( links, TUP, ape_links, staple_weight, u0, 0, ape_iter, 0.0 ); 
    free(links);
    hvy_pot( ape_links, max_t, max_x );
    free(ape_links);
#else
    
    /* fix to axial gauge */
    if( startflag != CONTINUE){
      ax_gauge();
      fixflag = AXIAL_GAUGE_FIX;
      tot_smear = 0;
    }
    
    /* Compute unsmeared simple, i.e one-plaquette, glueball operators */
    if( no_smear_level > 0 ){
      gball_simp(tot_smear);
    }
    
    /* Loop over the different smearing levels */
    for(sm_lev=0; sm_lev < no_smear_level; sm_lev++ ){
      
      /* Do the smearing iterations */
      for(todo=smear_num[sm_lev]; todo > 0; --todo ){
	smearing();
        lsmeared=1;
      }

      if(this_node==0 && lsmeared!=0)
#ifdef HYP_3D_SMEARING
        printf("HYP SMEARING COMPLETED\n"); 
#else
        printf("APE SMEARING COMPLETED\n"); 
#endif
      tot_smear += smear_num[sm_lev];
      
      /* Compute simple, i.e one-plaquette, glueball operators */
      gball_simp(tot_smear);
      
#ifndef HYBRIDS_MEASURE
      /* Compute on-axis time-like Wilson loops */
      w_loop1(tot_smear);
#else
      /* Compute on-axis time-like hybrid potential loops 
	 and on-axis time-like Wilson loops */
      hybrid_loop1(tot_smear);
#endif
      
      /* Compute off-axis time-like Wilson loops, if desired */
      if( off_axis_flag == 1 ){
	w_loop2(tot_smear);
      }
    }
#endif
    if(this_node==0)printf("RUNNING COMPLETED\n");
    
    dtime += dclock();
    if(this_node==0){
      printf("Time = %e seconds\n",dtime);
    }
    fflush(stdout);
    dtime = -dclock();
    
    /* save lattice if requested */
    if( saveflag != FORGET ){
      save_lattice( saveflag, savefile, stringLFN );
    }
  }
  return 0;
}
Пример #18
0
/*
 * chat [-esSvV] [-f chat-file] [-r report-file] [-t timeout]
 *      [-T phone-number] [-U phone-number2] [chat-script]
 * where chat-script has the form:
 *	[...[[expect[-send[-expect...]] send expect[-send[-expect]] ...]]]
 *
 * Perform a UUCP-dialer-like chat script on stdin and stdout.
 */
int
main(int argc, char *argv[])
{
    int option;

    tzset();

    while ((option = getopt(argc, argv, "ef:r:sSt:T:U:vV")) != -1) {
	switch (option) {
	case 'e':
	    ++echo;
	    break;

	case 'f':
	    if (chat_file != NULL)
		free(chat_file);
	    chat_file = copy_of(optarg);
	    break;

	case 'r':
	    if (report_fp != NULL)
		fclose(report_fp);
	    if (report_file != NULL)
		free(report_file);
	    report_file = copy_of(optarg);
	    report_fp = fopen(report_file, "a");
	    if (report_fp != NULL) {
		if (verbose)
		    fprintf(report_fp, "Opening \"%s\"...\n", report_file);
	    } else
		fatal(2, "cannot open \"%s\" for appending", report_file);
	    break;

	case 's':
	    ++to_stderr;
	    break;

	case 'S':
	    to_log = 0;
	    break;

	case 't':
	    timeout = atoi(optarg);
	    break;

	case 'T':
	    if (phone_num != NULL)
		free(phone_num);
	    phone_num = copy_of(optarg);
	    break;

	case 'U':
	    if (phone_num2 != NULL)
		free(phone_num2);
	    phone_num2 = copy_of(optarg);
	    break;

	case 'v':
	    ++verbose;
	    break;

	case 'V':
	    ++Verbose;
	    break;

	default:
	    usage();
	    break;
	}
    }

    argc -= optind;
    argv += optind;

/*
 * Default the report file to the stderr location
 */
    if (report_fp == NULL)
	report_fp = stderr;

    if (to_log) {
	openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);

	if (verbose)
	    setlogmask(LOG_UPTO(LOG_INFO));
	else
	    setlogmask(LOG_UPTO(LOG_WARNING));
    }

    if (chat_file != NULL) {
	if (*argv != NULL)
	    usage();
	else {
            init();
	    do_file(chat_file);
	}
    } else {
	init();
	while (*argv != NULL && argc > 0) {
	    chat_expect(*argv);
	    argv++;
	    argc--;

	    if (*argv != NULL && argc > 0) {
		chat_send(*argv);
		argv++;
		argc--;
	    }
	}
    }

    terminate(0);
    return 0;
}
Пример #19
0
// -----------------------------------------------------------------
// Access from node0 only
int read_gauge_hdr(gauge_file *gf) {
  FILE *fp = gf->fp;
  gauge_header *gh = gf->header;
  int32type tmp, btmp;
  int j, stat, byterevflag = 0;
  char myname[] = "read_gauge_hdr";

  // Read header, do byte reversal, if necessary, and check consistency
  // Read and verify magic number
  stat = sread_data(fp, &gh->magic_number, sizeof(gh->magic_number),
                    myname, "magic number");
  if (stat != 0)
    terminate(1);

  tmp = gh->magic_number;
  btmp = gh->magic_number;
  byterevn((int32type *)&btmp, 1);

  /** See if header chunk is BEGI = 1111836489 for big endian
    or the byte reverse 1229407554 for little endian **/
  if (tmp == GAUGE_VERSION_NUMBER)
    byterevflag = 0;
  else if (btmp == GAUGE_VERSION_NUMBER) {
    byterevflag = 1;
    gh->magic_number = btmp;
//    printf("Reading with byte reversal\n");
    if (sizeof(float) != sizeof(int32type)) {
      printf("read_gauge_hdr: Can't byte reverse\n");
      printf("requires size of int32type(%d) = size of float(%d)\n",
             (int)sizeof(int32type), (int)sizeof(float));
      terminate(1);
    }
  }
  else if (tmp == LIME_MAGIC_NO || btmp == LIME_MAGIC_NO) {
    // LIME format suggests a SciDAC file
    // Print error, set flag and return
    printf("%s: Looks like a SciDAC-formatted file\n", myname);
    gh->magic_number = LIME_MAGIC_NO;
    return 0;
  }
  else {
    // End of the road
    printf("read_gauge_hdr: Unrecognized magic number in gauge header\n");
    printf("Expected %x but read %x\n", GAUGE_VERSION_NUMBER, tmp);
    printf("Expected %s but read %d\n", (char *)GAUGE_VERSION_NUMBER, tmp);
    terminate(1);
    return byterevflag;
  }

  // Read and process header information
  // Get lattice dimensions
  stat = sread_byteorder(byterevflag, fp, gh->dims, sizeof(gh->dims),
                         myname, "dimensions");
  if (stat != 0)
    terminate(1);

  // Check lattice dimensions for consistency
  if (gh->dims[0] != nx ||
      gh->dims[1] != ny ||
      gh->dims[2] != nz ||
      gh->dims[3] != nt) {
    /* So we can use this routine to discover the dimensions,
       we provide that if nx = ny = nz = nt = -1 initially
       we don't die */
    if (nx != -1 || ny != -1 || nz != -1 || nt != -1) {
      printf("%s: Incorrect lattice dimensions ",myname);
      for (j = 0; j < NDIMS; j++)
        printf("%d ", gh->dims[j]);
      printf("\n");
      fflush(stdout);
      terminate(1);
    }
    else {
      nx = gh->dims[0];
      ny = gh->dims[1];
      nz = gh->dims[2];
      nt = gh->dims[3];
      volume = nx * ny * nz * nt;
    }
  }
  // Read date and time stamp
  stat = sread_data(fp, gh->time_stamp, sizeof(gh->time_stamp),
                    myname, "time stamp");
  if (stat != 0)
    terminate(1);

  // Read header byte length
  gh->header_bytes = sizeof(gh->magic_number) + sizeof(gh->dims)
                   + sizeof(gh->time_stamp) + sizeof(gh->order);

  // Read data order
  stat = sread_byteorder(byterevflag, fp, &gh->order, sizeof(gh->order),
                         myname, "order parameter");
  if (stat != 0)
    terminate(1);

  return byterevflag;
}
Пример #20
0
 void
 program_failed(const string& msg)
 {
   cerr << msg << endl;
   terminate();
 }
Пример #21
0
    SceneManager::SceneManager(GLint width, GLint height)
#endif
    {
        Log << Function << endl;

        // The projection matrix is represented by the perspective matrix given by glm, assign it to each one of the objects
        GLfloat aspect = static_cast<GLfloat>(width) / static_cast<GLfloat>(height);
        projectionMatrix = glm::perspective(
            45.0f,      // Field of view, is the amount of zoom. A wide angle is 90 and a narrow angle is 30
            aspect,     // Depends on the size of the window
            0.1f,       // Near clipping plane
            500.0f      // Far clipping plane
        );

        // Read the resources.txt file to obtain the valid configuration for the engine
        string resourcesFileName = "resources.txt";
#if defined(__ANDROID__)
        AAssetManager* mgr = AAssetManager_fromJava(*env, assetManager);
        AAsset* pFile = AAssetManager_open(mgr, resourcesFileName.c_str(), AASSET_MODE_UNKNOWN);
        if (!pFile)
#else
        ifstream resourcesFile(resourcesFileName, ios::in);
        if (!resourcesFile.is_open())
#endif
        {
            Log << Error << "Unable to read the resources file: " << resourcesFileName << endl;
            terminate();
        }

#if defined(__ANDROID__)
        // Get the file size
        size_t fileSize = AAsset_getLength(pFile);
        // Read data from the file
        char* pData = (char*)calloc(fileSize + 1, sizeof(char));
        AAsset_read(pFile, pData, fileSize);
        // fix the string to be zero-terminated
        pData[fileSize] = 0;
        // Copy the data to a stringstream
        stringstream resourcesFile(pData);
        AAsset_close(pFile);
        free(pData);
#endif

        Log << Debug << "Parsing the resources.txt file." << endl;
        string line, name, vertex, fragment, object, texture, projection, modelview;
        vector<string> cubeTextures{ NumCubeFaces };
        GLuint size, bufferType;
        vec3 pos, scl, rot;
        char token;
        bool finished = true;

        while (getline(resourcesFile, line))
        {
            stringstream ssLine(line);
            // Ignore empty lines on the configuration file
            if(line.size() == 0)
                continue;

            ssLine >> token;
            switch (token)
            {
            // If the line is a comment get the next token
            case '#':
                continue;
            // Start of object definition
            case '.':
                // Create a new scene object
                Log << Debug << "Starting an object definition." << endl;
                sceneobjects.push_back(make_unique<SceneObject>());
                finished = false;
                break;
            // End of an object definition
            case '-':
                Log << Debug << "End an object definition." << endl;
                finished = true;
                break;
            // Attributes used on the shaders
            case 'A':
                ssLine >> name >> size >> bufferType;
                Log << Debug << "Adding the attribute: " << name << endl;
                attributes.push_back(make_unique<Variable>(name, size, (BufferType)bufferType));
                break;
            // Uniforms used on the shaders
            case 'U':
                ssLine >> name;
                Log << Debug << "Adding the uniform: " << name << endl;
                uniforms.push_back(make_unique<Variable>(name));
                break;
            // Shaders creation
            case 'S':
                ssLine >> vertex >> fragment;
                Log << Debug << "Creating the shaders." << endl;
#if defined (__ANDROID__)
                sceneobjects.back()->SetShader(make_shared<Shader>(&mgr, vertex, fragment, attributes, uniforms));
#else
                sceneobjects.back()->SetShader(make_shared<Shader>(vertex, fragment, attributes, uniforms));
#endif
                break;
            // Object definitions
            case 'O':
                ssLine >> object;
                Log << Debug << "Loading a model." << endl;
#if defined (__ANDROID__)
                sceneobjects.back()->SetMesh(make_unique<Mesh>(&mgr, object, sceneobjects.back()->GetShader()));
#else
                sceneobjects.back()->SetMesh(make_unique<Mesh>(object, sceneobjects.back()->GetShader()));
#endif
                break;
            // Textures
            case 'T':
                ssLine >> texture;
                Log << Debug << "Loading a texture." << endl;
#if defined(__ANDROID__)
                sceneobjects.back()->SetTexture(make_unique<Texture>(&mgr, texture, sceneobjects.back()->GetShader()));
#else
                sceneobjects.back()->SetTexture(make_unique<Texture>(texture, sceneobjects.back()->GetShader()));
#endif
                break;
            // Initial coordinates
            case 'C':
                Log << Debug << "Adding coordinates to the object." << endl;
                ssLine >> pos.x >> pos.y >> pos.z >> scl.x >> scl.y >> scl.z >> rot.x >> rot.y >> rot.z >> angle;
                sceneobjects.back()->SetCoordinates(pos, scl, rot, angle);
                break;
            // Projection matrix
            case 'P':
                ssLine >> projection;
                break;
            // Modelview matrix
            case 'M':
                ssLine >> modelview;
                break;
            // Skybox
            case 'B':
                Log << Debug << "Adding a skybox." << endl;
                ssLine >> cubeTextures[0] >> cubeTextures[1] >> cubeTextures[2] >> cubeTextures[3] >> cubeTextures[4] >> cubeTextures[5];
                sceneobjects.back()->SetSkymap();
#if defined(__ANDROID__)
                sceneobjects.back()->SetMesh(make_unique<Mesh>(&mgr, string(""), sceneobjects.back()->GetShader()));
                sceneobjects.back()->SetTexture(make_unique<Texture>(&mgr, cubeTextures, sceneobjects.back()->GetShader()));
#else
                sceneobjects.back()->SetMesh(make_unique<Mesh>(string(""), sceneobjects.back()->GetShader()));
                sceneobjects.back()->SetTexture(make_unique<Texture>(cubeTextures, sceneobjects.back()->GetShader()));
#endif
                break;
            // Terrain Heightmap
            case 'H':
                Log << Debug << "Loading the terrain." << endl;
                ssLine >> texture >> object;
#if defined(__ANDROID__)
                sceneobjects.back()->SetTexture(make_unique<Texture>(&mgr, texture, sceneobjects.back()->GetShader()));
                sceneobjects.back()->SetMesh(make_unique<Mesh>(&mgr, object, sceneobjects.back()->GetShader(), &sceneobjects.back()->GetTexture()));
#else
                sceneobjects.back()->SetTexture(make_unique<Texture>(texture, sceneobjects.back()->GetShader()));
                sceneobjects.back()->SetMesh(make_unique<Mesh>(object, sceneobjects.back()->GetShader(), &sceneobjects.back()->GetTexture()));
#endif
                break;
            default:
                continue;
            }

            // Check if the definition of an object is complete or if more lines are needed
            if (finished)
            {
                // Get the projection and modelview uniforms
                if (!projection.empty())
                {
                    sceneobjects.back()->SetProjectionUni(glGetUniformLocation(sceneobjects.back()->GetShader()->getProgramObject(), "Projection"));
                    projection.clear();
                }
                if (!modelview.empty())
                {
                    sceneobjects.back()->SetModelviewUni(glGetUniformLocation(sceneobjects.back()->GetShader()->getProgramObject(), "Modelview"));
                    modelview.clear();
                }

                // Clear the attributes and uniforms in order to load the next object
                attributes.clear();
                uniforms.clear();
            }
        }
#if !defined(__ANDROID__)
        // Close de the resources file
        resourcesFile.close();
#endif

        // Set the initial position of the camera
        camera = vec3(2.5f, -1.0f, -5.0f);

        // Initial value of the rotation angle
        angle = 0.0f;
    }
void QTrackerDirectSyncResult::run()
{
    runQuery();
    terminate();
}
Пример #23
0
bool CWGLManager::initialize(const SIrrlichtCreationParameters& params, const SExposedVideoData& videodata)
{
	// store params, videoData is set later as it would be overwritten else
	Params=params;

	// Create a window to test antialiasing support
	const fschar_t* ClassName = __TEXT("CWGLManager");
	HINSTANCE lhInstance = GetModuleHandle(0);

	// Register Class
	WNDCLASSEX wcex;
	wcex.cbSize        = sizeof(WNDCLASSEX);
	wcex.style         = CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc   = (WNDPROC)DefWindowProc;
	wcex.cbClsExtra    = 0;
	wcex.cbWndExtra    = 0;
	wcex.hInstance     = lhInstance;
	wcex.hIcon         = NULL;
	wcex.hCursor       = LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName  = 0;
	wcex.lpszClassName = ClassName;
	wcex.hIconSm       = 0;
	wcex.hIcon         = 0;
	RegisterClassEx(&wcex);

	RECT clientSize;
	clientSize.top = 0;
	clientSize.left = 0;
	clientSize.right = Params.WindowSize.Width;
	clientSize.bottom = Params.WindowSize.Height;

	DWORD style = WS_POPUP;
	if (!Params.Fullscreen)
		style = WS_SYSMENU | WS_BORDER | WS_CAPTION | WS_CLIPCHILDREN | WS_CLIPSIBLINGS;

	AdjustWindowRect(&clientSize, style, FALSE);

	const s32 realWidth = clientSize.right - clientSize.left;
	const s32 realHeight = clientSize.bottom - clientSize.top;

	const s32 windowLeft = (GetSystemMetrics(SM_CXSCREEN) - realWidth) / 2;
	const s32 windowTop = (GetSystemMetrics(SM_CYSCREEN) - realHeight) / 2;

	HWND temporary_wnd=CreateWindow(ClassName, __TEXT(""), style, windowLeft,
			windowTop, realWidth, realHeight, NULL, NULL, lhInstance, NULL);

	if (!temporary_wnd)
	{
		os::Printer::log("Cannot create a temporary window.", ELL_ERROR);
		UnregisterClass(ClassName, lhInstance);
		return false;
	}

	HDC HDc = GetDC(temporary_wnd);

	// Set up pixel format descriptor with desired parameters
	PIXELFORMATDESCRIPTOR tmp_pfd = {
		sizeof(PIXELFORMATDESCRIPTOR),             // Size Of This Pixel Format Descriptor
		1,                                         // Version Number
		(DWORD)(PFD_DRAW_TO_WINDOW |               // Format Must Support Window
		PFD_SUPPORT_OPENGL |                       // Format Must Support OpenGL
		(Params.Doublebuffer?PFD_DOUBLEBUFFER:0) | // Must Support Double Buffering
		(Params.Stereobuffer?PFD_STEREO:0)),       // Must Support Stereo Buffer
		PFD_TYPE_RGBA,                             // Request An RGBA Format
		Params.Bits,                               // Select Our Color Depth
		0, 0, 0, 0, 0, 0,                          // Color Bits Ignored
		0,                                         // No Alpha Buffer
		0,                                         // Shift Bit Ignored
		0,                                         // No Accumulation Buffer
		0, 0, 0, 0,	                               // Accumulation Bits Ignored
		Params.ZBufferBits,                        // Z-Buffer (Depth Buffer)
		BYTE(Params.Stencilbuffer ? 1 : 0),        // Stencil Buffer Depth
		0,                                         // No Auxiliary Buffer
		PFD_MAIN_PLANE,                            // Main Drawing Layer
		0,                                         // Reserved
		0, 0, 0                                    // Layer Masks Ignored
	};
	pfd=tmp_pfd;

	for (u32 i=0; i<6; ++i)
	{
		if (i == 1)
		{
			if (Params.Stencilbuffer)
			{
				os::Printer::log("Cannot create a GL device with stencil buffer, disabling stencil shadows.", ELL_WARNING);
				Params.Stencilbuffer = false;
				pfd.cStencilBits = 0;
			}
			else
				continue;
		}
		else
		if (i == 2)
		{
			pfd.cDepthBits = 24;
		}
		else
		if (i == 3)
		{
			if (Params.Bits!=16)
				pfd.cDepthBits = 16;
			else
				continue;
		}
		else
		if (i == 4)
		{
			// try single buffer
			if (Params.Doublebuffer)
				pfd.dwFlags &= ~PFD_DOUBLEBUFFER;
			else
				continue;
		}
		else
		if (i == 5)
		{
			os::Printer::log("Cannot create a GL device context", "No suitable format for temporary window.", ELL_ERROR);
			ReleaseDC(temporary_wnd, HDc);
			DestroyWindow(temporary_wnd);
			UnregisterClass(ClassName, lhInstance);
			return false;
		}

		// choose pixelformat
		PixelFormat = ChoosePixelFormat(HDc, &pfd);
		if (PixelFormat)
			break;
	}

	SetPixelFormat(HDc, PixelFormat, &pfd);
	os::Printer::log("Temporary context");
	HGLRC hrc=wglCreateContext(HDc);
	if (!hrc)
	{
		os::Printer::log("Cannot create a temporary GL rendering context.", ELL_ERROR);
		ReleaseDC(temporary_wnd, HDc);
		DestroyWindow(temporary_wnd);
		UnregisterClass(ClassName, lhInstance);
		return false;
	}

	CurrentContext.OpenGLWin32.HDc = HDc;
	CurrentContext.OpenGLWin32.HRc = hrc;
	CurrentContext.OpenGLWin32.HWnd = temporary_wnd;

	if (!activateContext(CurrentContext))
	{
		os::Printer::log("Cannot activate a temporary GL rendering context.", ELL_ERROR);
		wglDeleteContext(hrc);
		ReleaseDC(temporary_wnd, HDc);
		DestroyWindow(temporary_wnd);
		UnregisterClass(ClassName, lhInstance);
		return false;
	}

	core::stringc wglExtensions;
#ifdef WGL_ARB_extensions_string
	PFNWGLGETEXTENSIONSSTRINGARBPROC irrGetExtensionsString = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB");
	if (irrGetExtensionsString)
		wglExtensions = irrGetExtensionsString(HDc);
#elif defined(WGL_EXT_extensions_string)
	PFNWGLGETEXTENSIONSSTRINGEXTPROC irrGetExtensionsString = (PFNWGLGETEXTENSIONSSTRINGEXTPROC)wglGetProcAddress("wglGetExtensionsStringEXT");
	if (irrGetExtensionsString)
		wglExtensions = irrGetExtensionsString(HDc);
#endif
	const bool pixel_format_supported = (wglExtensions.find("WGL_ARB_pixel_format") != -1);
	const bool multi_sample_supported = ((wglExtensions.find("WGL_ARB_multisample") != -1) ||
		(wglExtensions.find("WGL_EXT_multisample") != -1) || (wglExtensions.find("WGL_3DFX_multisample") != -1) );
#ifdef _DEBUG
	os::Printer::log("WGL_extensions", wglExtensions);
#endif

#ifdef WGL_ARB_pixel_format
	PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormat_ARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");
	if (pixel_format_supported && wglChoosePixelFormat_ARB)
	{
		// This value determines the number of samples used for antialiasing
		// My experience is that 8 does not show a big
		// improvement over 4, but 4 shows a big improvement
		// over 2.

		if (Params.AntiAlias > 32)
			Params.AntiAlias = 32;

		f32 fAttributes[] = {0.0, 0.0};
		s32 iAttributes[] =
		{
			WGL_DRAW_TO_WINDOW_ARB,1,
			WGL_SUPPORT_OPENGL_ARB,1,
			WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
			WGL_COLOR_BITS_ARB,(Params.Bits==32) ? 24 : 15,
			WGL_ALPHA_BITS_ARB,(Params.Bits==32) ? 8 : 1,
			WGL_DEPTH_BITS_ARB,Params.ZBufferBits, // 10,11
			WGL_STENCIL_BITS_ARB,Params.Stencilbuffer ? 1 : 0,
			WGL_DOUBLE_BUFFER_ARB,Params.Doublebuffer ? 1 : 0,
			WGL_STEREO_ARB,Params.Stereobuffer ? 1 : 0,
			WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
#ifdef WGL_ARB_multisample
			WGL_SAMPLES_ARB,Params.AntiAlias, // 20,21
			WGL_SAMPLE_BUFFERS_ARB, 1,
#elif defined(WGL_EXT_multisample)
			WGL_SAMPLES_EXT,AntiAlias, // 20,21
			WGL_SAMPLE_BUFFERS_EXT, 1,
#elif defined(WGL_3DFX_multisample)
			WGL_SAMPLES_3DFX,AntiAlias, // 20,21
			WGL_SAMPLE_BUFFERS_3DFX, 1,
#endif
#ifdef WGL_ARB_framebuffer_sRGB
			WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, Params.HandleSRGB ? 1:0,
#elif defined(WGL_EXT_framebuffer_sRGB)
			WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT, Params.HandleSRGB ? 1:0,
#endif
//			WGL_DEPTH_FLOAT_EXT, 1,
			0,0,0,0
		};
		int iAttrSize = sizeof(iAttributes)/sizeof(int);
		const bool framebuffer_srgb_supported = ((wglExtensions.find("WGL_ARB_framebuffer_sRGB") != -1) ||
			(wglExtensions.find("WGL_EXT_framebuffer_sRGB") != -1));
		if (!framebuffer_srgb_supported)
		{
			memmove(&iAttributes[24],&iAttributes[26],sizeof(int)*(iAttrSize-26));
			iAttrSize -= 2;
		}
		if (!multi_sample_supported)
		{
			memmove(&iAttributes[20],&iAttributes[24],sizeof(int)*(iAttrSize-24));
			iAttrSize -= 4;
		}

		s32 rv=0;
		// Try to get an acceptable pixel format
		do
		{
			int pixelFormat=0;
			UINT numFormats=0;
			const BOOL valid = wglChoosePixelFormat_ARB(HDc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);

			if (valid && numFormats)
				rv = pixelFormat;
			else
				iAttributes[21] -= 1;
		}
		while(rv==0 && iAttributes[21]>1);
		if (rv)
		{
			PixelFormat=rv;
			Params.AntiAlias=iAttributes[21];
		}
	}
	else
#endif
		Params.AntiAlias=0;

	// this only terminates the temporary HRc
	destroyContext();
	destroySurface();
	terminate();
	DestroyWindow(temporary_wnd);
	UnregisterClass(ClassName, lhInstance);

	// now get new window
	CurrentContext.OpenGLWin32.HWnd=videodata.OpenGLWin32.HWnd;
	// get hdc
	if (!(CurrentContext.OpenGLWin32.HDc=GetDC((HWND)videodata.OpenGLWin32.HWnd)))
	{
		os::Printer::log("Cannot create a GL device context.", ELL_ERROR);
		return false;
	}
	if (!PrimaryContext.OpenGLWin32.HWnd)
	{
		PrimaryContext.OpenGLWin32.HWnd=CurrentContext.OpenGLWin32.HWnd;
		PrimaryContext.OpenGLWin32.HDc=CurrentContext.OpenGLWin32.HDc;
	}

	return true;
}
Пример #24
0
int mrilu_cl_field(     /* Return value is number of iterations taken */
    wilson_vector *src,	/* type wilson_vector (source vector - OVERWRITTEN!)*/
    wilson_vector *dest, /* type wilson_vector (answer and initial guess )*/
    quark_invert_control *qic,	/* parameters controlling inversion */
    void *dmp		/* parameters defining the Dirac matrix */
    )
{
  /* Unpack required members of the structures */
  int max_restarts = qic->nrestart;  /* Number of restarts */
  int nrestart = 0;
  int restart = qic->max;            /* Restart interval */
  int MaxCG = restart*qic->max;     /* maximum number of iterations */
  Real RsdCG = qic->resid;	/* desired residual -
                                 normalized as sqrt(r*r)/sqrt(src_e*src_e */
  Real RRsdCG = qic->relresid;       /* desired relative residual - */
  int flag = qic->start_flag;	/* 0: use a zero initial guess; 1: use dest */

  dirac_clover_param *dcp
    = (dirac_clover_param *)dmp;	/* Cast pass-through pointer */

  Real Kappa = dcp->Kappa;	/* hopping */
  Real Clov_c = dcp->Clov_c;	/* Perturbative clover coeff */
  Real U0 = dcp->U0;		/* Tadpole correction to Clov_c */
  /* End of unpacking required members of structures */

  wilson_vector *tmp=NULL,*mp=NULL,*r=NULL,*p=NULL;

  int N_iter;
  register int i;
  register site *s;
  Real size_src;
  double rsq, c;
  complex a, ctmp;
  double_complex d;
  register Real MKsq = -Kappa*Kappa;
  Real CKU0 = Kappa*Clov_c/(U0*U0*U0);
#ifdef CGTIME
  double dtime;
#endif
  msg_tag *tago[8],*tage[8];
  int is_startedo, is_startede;
  
  is_startedo = is_startede = 0;

  if(even_sites_on_node!=odd_sites_on_node){
    printf("Need same number of even and odd sites on each node\n");
    terminate(1);
  }
  
  /* Compute R_e and R_o and put in "clov" and "clov_diag" */
  compute_clov(gen_clov, CKU0);

  /* Invert R_o only, leaving R_e on even sites and 1/R_o on odd sites 
     in "clov" and "clov_diag" */
  compute_clovinv(gen_clov, ODD);

  /* now we can allocate temporary variables and copy them */
  /* PAD may be used to avoid cache trashing */
#define PAD 0
    
  tmp    = (wilson_vector *) malloc((sites_on_node+PAD)*sizeof(wilson_vector));
  mp     = (wilson_vector *) malloc((sites_on_node+PAD)*sizeof(wilson_vector));
  r      = (wilson_vector *) malloc((sites_on_node+PAD)*sizeof(wilson_vector));
  p      = r  + even_sites_on_node;

  if(tmp == NULL || mp == NULL || r == NULL ){
    printf("hopilu_cl_field(%d): No room for temporaries\n",this_node);
    terminate(1);
  }

  /* MR_ILU: */

#ifdef CGTIME
  dtime = -dclock();
#endif
  
  /* now we copy src to temporary */
  FORALLSITES(i,s) {
    r[i] = src[i];
  }

  /* Transform source - result is in r (even) - and dest (odd) */


  size_src = ilu_xfm_source(dest, r, mp, Kappa, &is_startede, tage);

#if 0
  /* src = L^(-1)*src */
  mult_this_ldu_field(gen_clov, r, mp, ODD);
  dslash_w_field_special(mp, mp, PLUS, EVEN, tage, is_startede);
  is_startede = 1;

  /* Normalisation  */
  rsq = 0.0;

  FOREVENSITESDOMAIN(i,s) {
    scalar_mult_add_wvec( &(r[i]), &(mp[i]), Kappa, &(r[i]) );
    rsq += (double)magsq_wvec( &(r[i]) );
    /* Save transformed source: Overwrite src on even sites */
    copy_wvec( &(r[i]), &(src[i]) );
  }
Пример #25
0
fmiStatus fmiTerminate(fmiComponent c){
    return terminate("fmiTerminate", c);
}
Пример #26
0
Item get_first_item(Queue q)
{
    if (is_empty(q))
        terminate("Error, no items to get\n\n");
    return q->first->data;
}
Пример #27
0
void setup_layout(){
register int i,j,k,dir;

#ifdef HAVE_QMP
 if(QMP_get_msg_passing_type()==QMP_GRID){
   printf("This layout should not be used on a grid architecture\n");
   terminate(1);
 }
#endif

    if(mynode()==0){
	printf("LAYOUT = Hypercubes, options = ");
	printf("tstretch,");
	printf("\n");
    }

    /* Figure out dimensions of rectangle */
    if( (nx*ny*nz*nt)%numnodes() == 0){
      squaresize[XUP] = nx; squaresize[YUP] = ny;
      squaresize[ZUP] = nz; squaresize[TUP] = nt;
    }
    else if ( (nx*ny*nz*(nt+1))%numnodes() == 0){
      squaresize[XUP] = nx; squaresize[YUP] = ny;
      squaresize[ZUP] = nz; squaresize[TUP] = nt+1;
    }
    nsquares[XUP] = nsquares[YUP] = nsquares[ZUP] = nsquares[TUP] = 1;

    i = 1;	/* current number of hypercubes */
    while(i<numnodes()){
	/* figure out which prime to divide by starting with largest */
	k = MAXPRIMES-1;
	while( (numnodes()/i)%prime[k] != 0 && k>0 ) --k;
	/* figure out which direction to divide */

	/* find largest even dimension of h-cubes */
	for(j=1,dir=XUP;dir<=TUP;dir++)
	    if( squaresize[dir]>j && squaresize[dir]%prime[k]==0 )
		j=squaresize[dir];

	/* if one direction with largest dimension has already been
	   divided, divide it again.  Otherwise divide first direction
	   with largest dimension. */
	for(dir=XUP;dir<=TUP;dir++)
	    if( squaresize[dir]==j && nsquares[dir]>1 )break;
	if( dir > TUP)for(dir=XUP;dir<=TUP;dir++)
	    if( squaresize[dir]==j )break;
	/* This can fail if I run out of prime factors in the dimensions */
	if(dir > TUP){
	    if(mynode()==0)printf(
	    "LAYOUT: Can't lay out this lattice, not enough factors of %d\n"
		,prime[k]);
	    terminate(1);
	}

	/* do the surgery */
	i*=prime[k]; squaresize[dir] /= prime[k]; nsquares[dir] *= prime[k];
    }

    sites_on_node =
	    squaresize[XUP]*squaresize[YUP]*squaresize[ZUP]*squaresize[TUP];
    sites_on_lastnodes = sites_on_node;

if( mynode()==0)
  printf("ON MOST NODES %d x %d x %d x %d\n",squaresize[XUP],squaresize[YUP],
                squaresize[ZUP],squaresize[TUP]);
    if( !((nx*ny*nz*nt)%numnodes() == 0) && (nx*ny*nz*(nt+1))%numnodes() == 0 ){
	/* stretched t direction by one */
	if( mynode()==0)printf("SOME NODES HAVE FEWER SITES\n");
	if( mynode() >=  nsquares[XUP]*nsquares[YUP]*nsquares[ZUP]*(nsquares[TUP]-1) ){
	    sites_on_node = squaresize[XUP]*squaresize[YUP]*squaresize[ZUP]*(squaresize[TUP]-1);
	    sites_on_lastnodes = sites_on_node;
	}
    }

    /* Need even number of sites per hypercube */
    if( mynode()==0)if( sites_on_node%2 != 0){
	printf("SORRY, CAN'T LAY OUT THIS LATTICE\n");
	terminate(0);
    }
if( mynode()==0 && sites_on_node%2 != 0)
	printf("WATCH OUT FOR EVEN/ODD SITES ON NODE BUG!!!\n");
    even_sites_on_node = odd_sites_on_node = sites_on_node/2;
}