Ejemplo n.º 1
0
void String_Init()
{
	MemHandle Resource;
	DmResID Id;
	context* p = Context();
	StringAlloc();

	for (Id=1000;Id<1000+32;++Id)
	{
		Resource = DmGetResource('lang',Id);
		if (Resource)
		{
			int Size = MemHandleSize(Resource);
			void* Data = MemHandleLock(Resource);
			if (Size && Data && StringAddBinary(Data,Size))
				ArrayAppend(&p->StrModule,&Resource,sizeof(Resource),16);
			else
			{
				if (Data)
					MemHandleUnlock(Resource);
				DmReleaseResource(Resource);
			}
		}
	}
}
Ejemplo n.º 2
0
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Requests for communication from a peer is handled by first checking if the 
// initial message has a message handler registered for it.  Otherwise 
// the message is passed onto the app.
void gsUdpConnAttemptCB(GT2Socket socket, GT2Connection connection, unsigned int ip, 
						unsigned short port, int latency, GT2Byte * message, int len)
{
	// Get the message handler for the connection 
	int index;
	GSUdpMsgHandler aHandler;
	GSUdpRemotePeer aRemotePeer;
	GSUdpEngineObject *aUdp = gsUdpEngineGetEngine();
	char anAddr[GS_IP_ADDR_AND_PORT];
	
	gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Network, GSIDebugLevel_Comment, 
		"[Udp Engine] Connection attempt from %s\n", gt2AddressToString(ip, port, anAddr));
	//If there is a handler, automatically accept a connection if the initial message is
	//the same as the handler's registered initial message
	if (len >= GS_UDP_MSG_HEADER_LEN)
	{    
		memcpy(aHandler.mInitialMsg, message, GS_UDP_MSG_HEADER_LEN);
		
		aRemotePeer.mAddr = ip;
		aRemotePeer.mPort = port;
		aRemotePeer.mConnection = connection;
		
		ArrayAppend(aUdp->mRemotePeers, &aRemotePeer);
		index = ArraySearch(aUdp->mMsgHandlers, &aHandler, gsUdpMsgHandlerCompare, 0, 0);
		if (index != NOT_FOUND)
		{
			GT2ConnectionCallbacks aCallbacks;
			
			aCallbacks.closed = gsUdpClosedRoutingCB;
			aCallbacks.connected = gsUdpConnectedRoutingCB;
			aCallbacks.ping = gsUdpPingRoutingCB;
			aCallbacks.received = gsUdpReceivedRoutingCB;

	       
			// Automatically accept connections for Message Handlers
			gt2Accept(aRemotePeer.mConnection, &aCallbacks);	
			gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Network, GSIDebugLevel_Comment, 
				"[Udp Engine] Connection attempt auto-accepted for message handler\n");
			return;
		}
	}
	// all other messages go to the app
	if (aUdp->mAppConnAttempt) 
	{
		gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Network, GSIDebugLevel_Comment, 
			"[Udp Engine] Connection attempt from %s, asking app to accept/reject\n", gt2AddressToString(ip, port, anAddr));
		aUdp->mAppConnAttempt(ip, port, latency, (unsigned char *)message, (unsigned int)len, aUdp->mAppUserData);
	}
	else 
	{
		// Reject any un-handled connections or unknown connections
		gt2Reject(connection, NULL, 0);
		ArrayRemoveAt(aUdp->mRemotePeers, ArrayLength(aUdp->mRemotePeers) -1);
	}
	GSI_UNUSED(socket);
	GSI_UNUSED(anAddr);
}
Ejemplo n.º 3
0
GPResult
gpiPeerAddMessage(
  GPConnection * connection,
  GPIPeer * peer,
  int type,
  const char * message
)
{
	GPIMessage gpiMessage;
	int len;

	GS_ASSERT(peer != NULL);
	GS_ASSERT(message != NULL);
	
	if (peer == NULL)
		return GP_NETWORK_ERROR;
	if (message == NULL)
		return GP_NETWORK_ERROR;

	// Get the length.
	//////////////////
	len = (int)strlen(message);

	// Clear the message.
	/////////////////////
	memset(&gpiMessage, 0, sizeof(GPIMessage));

	// Copy the type.
	/////////////////
	gpiMessage.type = type;

	// Copy the header to the buffer.
	/////////////////////////////////
	CHECK_RESULT(gpiAppendStringToBuffer(connection, &gpiMessage.buffer, "\\m\\"));
	CHECK_RESULT(gpiAppendIntToBuffer(connection, &gpiMessage.buffer, type));
	CHECK_RESULT(gpiAppendStringToBuffer(connection, &gpiMessage.buffer, "\\len\\"));
	CHECK_RESULT(gpiAppendIntToBuffer(connection, &gpiMessage.buffer, len));
	CHECK_RESULT(gpiAppendStringToBuffer(connection, &gpiMessage.buffer, "\\msg\\\n"));

	// Copy the message to the buffer.
	//////////////////////////////////
	gpiMessage.start = gpiMessage.buffer.len;
	CHECK_RESULT(gpiAppendStringToBufferLen(connection, &gpiMessage.buffer, message, len));
	CHECK_RESULT(gpiAppendCharToBuffer(connection, &gpiMessage.buffer, '\0'));

	// Add it to the list.
	//////////////////////
	ArrayAppend(peer->messages, &gpiMessage);

	// Reset the timeout.
	/////////////////////
	peer->timeout = (time(NULL) + GPI_PEER_TIMEOUT);

	return GP_NO_ERROR;
}
Ejemplo n.º 4
0
bool_t StreamGenExts(anynode* AnyNode,array* Exts, fourcc_t ClassFilter, const tchar_t* TypeFilter)
{
	fourcc_t* i;
	array List;
    ArrayInit(Exts);

    if (TypeFilter && !TypeFilter[0])
        TypeFilter = NULL;

	NodeEnumClass(AnyNode,&List,ClassFilter);
	for (i=ARRAYBEGIN(List,fourcc_t);i!=ARRAYEND(List,fourcc_t);++i)
	{
		const tchar_t* s = NodeStr2(AnyNode,*i,NODE_EXTS);
		while (s && s[0])
		{
            size_t n;
            for (n=0;s[n] && s[n]!=';' && s[n]!=':';++n) {}

            if (!TypeFilter || (s[n]==':' && tcschr(TypeFilter,s[n+1])!=NULL))
            {
                while (s[n] && s[n]!=';')
                    ++n;

                if (n)
                {
                    if (!ARRAYEMPTY(*Exts))
                        ArrayAppend(Exts,T(";"),sizeof(tchar_t),64);
                    ArrayAppend(Exts,s,n*sizeof(tchar_t),64);
                }
            }

            s = tcschr(s,';');
            if (s) ++s;
		}
	}
	ArrayClear(&List);

    if (!ARRAYEMPTY(*Exts) && !ArrayAppend(Exts,T("\0"),sizeof(tchar_t),64))
        ArrayClear(Exts);

    return !ARRAYEMPTY(*Exts);
}
Ejemplo n.º 5
0
void TableEnter(HashTable table, const void *newElem)
{
	int hash, itempos;

	hash = table->hashfn(newElem, table->nbuckets);
	itempos = ArraySearch(table->buckets[hash], newElem, table->compfn, 0, 0);
	if (itempos == NOT_FOUND)
		ArrayAppend(table->buckets[hash], newElem);
	else
		ArrayReplaceAt(table->buckets[hash], newElem, itempos);
}
Ejemplo n.º 6
0
void RebuildEmit(char *Template, ...)
{
		char 	Str[1024];
		va_list args;
		int n,len;
		
		va_start(args,Template);
		vsprintf(Str,Template,args);
		va_end(args);

		//printf("%s",Str);

		len = strlen(Str);
		
		for (n=0;n<len;n++)
			ArrayAppend(&RebuildArray, Str[n]);

}
Ejemplo n.º 7
0
void ArrayPrint(ArrayStore *theArray, char *Template, ...)
{
	char 			tbuf[1024];
	va_list 		args;
	int 			len;
	int				n;
		
	va_start(args,Template);
	vsprintf(tbuf,Template,args);
	va_end(args);
		
	len = strlen(tbuf);

	for (n=0;n<len;n++)
		ArrayAppend(theArray, tbuf[n]);

	return;
}
Ejemplo n.º 8
0
static bool_t AllocBlockGroup(block* Block, bool_t Optional)
{
	int n;
	blockgroup* g;
	for (g=ARRAYBEGIN(BlockGroup,blockgroup);g!=ARRAYEND(BlockGroup,blockgroup);++g)
		if (g->Mask && g->Mask != (1<<BLOCKGROUP)-1)
			break;

	if (g==ARRAYEND(BlockGroup,blockgroup))
	{
		if (!Optional)
			return 0;

		for (g=ARRAYBEGIN(BlockGroup,blockgroup);g!=ARRAYEND(BlockGroup,blockgroup);++g)
			if (!g->Mask)
				break;

		if (g==ARRAYEND(BlockGroup,blockgroup))
		{
			if (!ArrayAppend(&BlockGroup,NULL,sizeof(blockgroup),64))
				return 0;
			g=ARRAYEND(BlockGroup,blockgroup)-1;
			g->Mask = 0;
		}

		if (!AllocBlock(BLOCKSIZE*BLOCKGROUP,&g->Block,1,HEAP_ANY))
			return 0;
	}

	for (n=0;n<BLOCKGROUP;++n)
		if (!(g->Mask & (1<<n)))
		{
			g->Mask |= (1<<n);
			Block->Id = ((g-ARRAYBEGIN(BlockGroup,blockgroup))<<8)+(n+1);
			Block->Ptr = g->Block.Ptr + n*BLOCKSIZE;
			return 1;
		}

	return 0;
}
Ejemplo n.º 9
0
PetscErrorCode LevelSetUpdateIrregularNodeList_2D( LevelSet ls )
{
  int i, j, k, I, J, ni, nj;
  const int numNei = 4;
  const int nei[][2] = {{1,0},{-1,0},{0,-1},{0,1}};
  IrregularNode *n;
  PetscReal **phi, phiHI, phiLO;
  PetscReal sten[3][3];
  PetscReal local[5][5];
  iCoor *band;
  int b;
  PetscErrorCode ierr;
  
  PetscFunctionBegin;
  ierr = GridGet(ls->phi,&phi); CHKERRQ(ierr);
  for( b = 0; b < ArrayLength(ls->band); ++b)
  {
    ierr = ArrayGet(ls->band,b,&band); CHKERRQ(ierr);
    i = band->x;
    j = band->y;
    
    // Cell-centered Irregular Node
    for( J = -2; J <= 2; ++J) {
      for( I = -2; I <= 2; ++I) {
        local[J+2][I+2] = phi[J+j][I+i];
      }
    } // for local 5x5 stencil

    // Cell-centered Irregular Node
    for( J = -1; J < 2; ++J)
    {
      for( I = -1; I < 2; ++I)
      {
        sten[J+1][I+1] = phi[J+j][I+i];
      }
    } // for local 3x3 stencil

    // Add ortho-proj for FMM boundary condition
    for( k = 0; k < numNei; ++k)
    {
      ni = 1 + nei[k][0];
      nj = 1 + nei[k][1];
      if( sten[1][1] * sten[nj][ni] <= 0. )
      {
        ierr = ArrayAppend( ls->irregularNodes, &n ); CHKERRQ(ierr);
        OrthogonalProjection2D( sten, local, &n->op);
        n->pos = *band;
        n->axis  = -1; // no-axis
        n->shift = -1;
        n->signCenter = sten[1][1] > 0. ? 1 : -1;
        n->X.x = n->pos.x + n->op.x;
        n->X.y = n->pos.y + n->op.y;
        break;
      }
    }

    // Add IIM irregular grid point
    // Cell-centered gradients
    for( k = U_FACE; k <= V_FACE; ++k)
    {
      ni = 1 + STAGGERED_GRID[k].x;
      nj = 1 + STAGGERED_GRID[k].y;
      if( sten[1][1] * sten[nj][ni] <= 0. )
      {
        ierr = ArrayAppend( ls->irregularNodes, &n ); CHKERRQ(ierr);
        n->d = sten[1][1] / (sten[1][1] - sten[nj][ni]);
        n->signCenter = sten[1][1] > 0. ? 1 : -1;
        n->signFace = n->d < 0.5 ? -n->signCenter : n->signCenter;
        n->pos = *band;
        n->shift = CELL_CENTER;
        n->axis  = k-U_FACE; // assuming U_FACE == 1, x-axis is 0, y-axis is 1
        n->X.x = n->pos.x + n->d * STAGGERED_GRID[k].x;
        n->X.y = n->pos.y + n->d * STAGGERED_GRID[k].y;
      } // if irreg
    } // for k in {U_FACE,V_FACE}

    // U-Velocity Laplacian
    phiHI = ( sten[1][0] + sten[1][1] ) / 2.;
    phiLO = ( sten[0][0] + sten[0][1] ) / 2.;
    if( phiHI * phiLO <= 0. )
    {
      ierr = ArrayAppend( ls->irregularNodes, &n ); CHKERRQ(ierr);
      n->d = phiHI / (phiHI - phiLO);
      n->signCenter = phiHI > 0. ? 1 : -1;
      n->signFace = n->d < 0.5 ? -n->signCenter : n->signCenter;
      n->pos = *band;
      n->shift = U_FACE;
      n->axis  = V_FACE-U_FACE; // y-axis == 1
      n->X.x = n->pos.x + STAGGERED_GRID[U_FACE].x / 2.;
      n->X.y = n->pos.y + STAGGERED_GRID[U_FACE].y / 2. - n->d;
    } // if irreg

    // V-Velicty Laplacian
    phiHI = ( sten[0][1] + sten[1][1] ) / 2.;
    phiLO = ( sten[0][0] + sten[1][0] ) / 2.;
    if( phiHI * phiLO <= 0. )
    {
      ierr = ArrayAppend( ls->irregularNodes, &n ); CHKERRQ(ierr);
      n->d = phiHI / (phiHI - phiLO);
      n->signCenter = phiHI > 0. ? 1 : -1;
      n->signFace = n->d < 0.5 ? -n->signCenter : n->signCenter;
      n->pos = *band;
      n->shift = V_FACE;
      n->axis  = U_FACE-U_FACE; // x-axis == 0
      n->X.x = n->pos.x + STAGGERED_GRID[V_FACE].x / 2. - n->d;
      n->X.y = n->pos.y + STAGGERED_GRID[V_FACE].y / 2.;
    } // if irreg
  } // for b in band
  PetscFunctionReturn(0);
}
Ejemplo n.º 10
0
void arrayAppend(uint val)
{
	ArrayAppend(CurrentArray, val);
}
Ejemplo n.º 11
0
void gpiAddToNpBlockListInfoCallback(
  GPConnection * pconnection, 
  GPGetInfoResponseArg * arg, 
  void * param
)
{
    SceNpOnlineId onlineId;
    int ret;
    npIdLookupTrans transaction;
    GPIConnection * iconnection = (GPIConnection*)*pconnection;
#ifdef GSI_UNICODE
    char asciiUniquenick[GP_UNIQUENICK_LEN];
#endif

    if(arg->result == GP_NO_ERROR)
    {
        // Make sure its a PS3 uniquenick (e.g. we have the uniquenick)
        ///////////////////////////////////////////////////////////////
        if (_tcslen(arg->uniquenick) != 0)
        {
            memset(&onlineId, 0, sizeof(onlineId));

#ifdef GSI_UNICODE
            UCS2ToAsciiString(arg->uniquenick, (char*)asciiUniquenick);
            strncpy(onlineId.data, asciiUniquenick, SCE_NET_NP_ONLINEID_MAX_LENGTH);
#else
            strncpy(onlineId.data, arg->uniquenick, SCE_NET_NP_ONLINEID_MAX_LENGTH);
#endif

            if (ArrayLength(iconnection->npTransactionList) < GPI_NP_NUM_TRANSACTIONS)
            {
                ret = sceNpLookupCreateTransactionCtx(iconnection->npLookupTitleCtxId);
                if (ret < 0)
                {
                    gsDebugFormat(GSIDebugCat_GP, GSIDebugType_Misc, GSIDebugLevel_HotError,
                        "PS3AddToNpBlockList: sceNpLookupCreateTransactionCtx() failed. ret = 0x%x\n", ret);  
                }
                else
                {
                    transaction.npIdForAdd = (SceNpId*)gsimalloc(sizeof(SceNpId));
                    if(transaction.npIdForAdd == NULL)
                    {
                        sceNpLookupDestroyTransactionCtx(ret);
                        gsDebugFormat(GSIDebugCat_GP, GSIDebugType_Misc, GSIDebugLevel_HotError,
                            "PS3AddToNpBlockList: Out of memory.\n");  
                        return;
                    }
                    transaction.npTransId = ret;
                    transaction.npLookupDone = gsi_false;
                    ArrayAppend(iconnection->npTransactionList, &transaction);

                    // Perform NP lookup to get the NpId
                    /////////////////////////////////////
                    ret = sceNpLookupNpIdAsync(transaction.npTransId, &onlineId, 
                        transaction.npIdForAdd, 0, NULL);
                    if (ret < 0) 
                    {
                        gsDebugFormat(GSIDebugCat_GP, GSIDebugType_Misc, GSIDebugLevel_HotError,
                            "PS3AddToNpBlockList: sceNpLookupNpIdAsync() failed. ret = 0x%x\n", ret);  
                    } 
                }
            }
            else
            {
                // Can only have a max of 32 simultaneous transactions (based on PS3 lib)
                /////////////////////////////////////////////////////////////////////////
                gsDebugFormat(GSIDebugCat_GP, GSIDebugType_Misc, GSIDebugLevel_WarmError,
                    "PS3AddToNpBlockList: Transactions limit reached for np lookups\n");  
            }
        }
        else
            gsDebugFormat(GSIDebugCat_GP, GSIDebugType_Misc, GSIDebugLevel_HotError,
                "PS3AddToNpBlockList: Profile [%d] does not have a uniquenick in namespace %d!\n",
                arg->profile, iconnection->namespaceID);
    }
    else
        gsDebugFormat(GSIDebugCat_GP, GSIDebugType_Misc, GSIDebugLevel_HotError,
            "PS3AddToNpBlockList: Player Info lookup FAILED!\n");

    GSI_UNUSED(pconnection);
    GSI_UNUSED(param);
}
Ejemplo n.º 12
0
PetscErrorCode FiberField_AddToSendbufs( FiberField field )
{
  int i;
  int e;
  const int vlen = ArrayLength(field->verts);
  const int elen = ArrayLength(field->edges);
  const BoundingBox lbbox = field->localBounds;
  int neiIdx;
  VertexEdgeMPI *evmpi;
  iCoor n; // index in 3x3x3 array nei
  Vertex v;
  PetscMPIInt sendRank;
  const PetscMPIInt *neiRanks;
  PetscErrorCode ierr;

  PetscFunctionBegin;

  ierr = DMDAGetNeighbors(field->da, &neiRanks); CHKERRQ(ierr);
  
  // clear send arrays
  // for each vert
  //   if outside nei, err
  //   else add vert to send list

  for (i = 0; i < NUMNEI; i++) {
    ArraySetSize( field->sendbufs[i], 0);
  }
   
  for (i = 0; i < vlen; i++) {
    ierr = ArrayGet( field->verts, i, &v ); CHKERRQ(ierr);

    PositionToNeiIdx( &lbbox, &v->X, &n, &neiIdx);

    // if vertex outside 3x3x3 nei, something went terribly wrong
    if (n.x < 0 || n.x > 2 ||
        n.y < 0 || n.y > 2 ||
        n.z < 0 || n.z > 2 ) {
      ierr = PetscInfo(0, "ERROR: Vertex outside 3x3x3 neighbor region\n"); CHKERRQ(ierr);
      ierr = PetscInfo1(0, "i = %d\n",i); CHKERRQ(ierr);
      ierr = PetscInfo3(0, "X = {%f, %f, %f}\n",v->X.x,v->X.y,v->X.z); CHKERRQ(ierr);
      ierr = PetscInfo3(0, "n = {%d, %d, %d}\n",n.x,n.y,n.z); CHKERRQ(ierr);
      ierr = PetscInfo(0, "ERROR: END MESSAGE\n"); CHKERRQ(ierr);
      SETERRQ(field->comm, 0, "Vertex outside 3x3x3 neighbor region");
    } else { 
      // convert nei index to mpi rank
      sendRank = neiRanks[neiIdx];
      // in the edge case where a vertex leaves the global bounding box, abort
      // handle this case in the physics, not in the communication routine
      if ( sendRank == MPI_PROC_NULL) {
        ierr = PetscInfo(0, "ERROR: Vertex outside global bbox\n"); CHKERRQ(ierr);
        ierr = PetscInfo1(0, "i = %d\n",i); CHKERRQ(ierr);
        ierr = PetscInfo3(0, "X = {%f, %f, %f}\n",v->X.x,v->X.y,v->X.z); CHKERRQ(ierr);
        ierr = PetscInfo3(0, "n = {%d, %d, %d}\n",n.x,n.y,n.z); CHKERRQ(ierr);
        ierr = PetscInfo1(0, "neiIdx = %d\n",neiIdx); CHKERRQ(ierr);
        ierr = PetscInfo(0, "ERROR: END MESSAGE\n"); CHKERRQ(ierr);
        SETERRQ(field->comm, 0, "Vertex outside global bbox\n");
      }

      // add vertex to send list[rank]
      ierr = ArrayAppend( field->sendbufs[neiIdx], &evmpi); CHKERRQ(ierr); 
      evmpi->xID = v->vID;
      evmpi->type= v->type;
      evmpi->X = v->X;
      evmpi->V = v->V;
      for (e = 0; e < MAXEDGES; e++) {
        evmpi->yIDs[e] = v->eID[e];
      }
    }
  }

  int min;
  int vPO;
  struct _Edge *edges = ArrayGetData(field->edges);
  struct _Vertex *vertsPO;
  ierr = FiberFieldGetVertexArrayPO( field, &vertsPO ); CHKERRQ(ierr);
  for (e = 0; e < elen; e++) {
    // the edge is 'owned' by the vertex with the smallest ID
    min = edges[e].vID[0] < edges[e].vID[1] ? 0 : 1;
    vPO = edges[e].vPO[min]; 

    v = &vertsPO[vPO];

    PositionToNeiIdx( &lbbox, &v->X, &n, &neiIdx);

    if (v->vID != edges[e].vID[min] ) {
      ierr = PetscInfo1(0, "v->vID = %d\n", v->vID); CHKERRQ(ierr);
      ierr = PetscInfo1(0, "edges[e].vID[min] = %d\n", edges[e].vID[min]); CHKERRQ(ierr);
      SETERRQ(PETSC_COMM_SELF, 0, "Bad vertex");
    }

    ierr = ArrayAppend( field->sendbufs[neiIdx], &evmpi); CHKERRQ(ierr); 
    evmpi->xID = edges[e].eID; 
    evmpi->type = edges[e].type; 
    evmpi->yIDs[0] = edges[e].vID[0]; 
    evmpi->yIDs[1] = edges[e].vID[1]; 
    evmpi->X.x = edges[e].l0;
  }

  PetscFunctionReturn(0);
}
Ejemplo n.º 13
0
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// UDP Layer must be initialized
// Message handlers are added using this function
// The initial message and header of a message handler cannot be empty
// However, they can be the same.
// User data can be useful for keeping track of Message Handler 
GSUdpErrorCode gsUdpEngineAddMsgHandler(char theInitMsg[GS_UDP_MSG_HEADER_LEN], char theHeader[GS_UDP_MSG_HEADER_LEN], 
									    gsUdpErrorCallback theMsgHandlerError, 
									    gsUdpConnConnectedCallback theMsgHandlerConnected, 
									    gsUdpConnClosedCallback theMsgHandlerClosed, 
									    gsUdpConnPingCallback theMsgHandlerPing,
										gsUdpConnReceivedDataCallback theMsgHandlerRecv,
										void *theUserData)
{
	GSUdpEngineObject *aUdp = gsUdpEngineGetEngine();
	GSUdpMsgHandler aMsgHandler;
	GS_ASSERT(aUdp->mInitialized);
	GS_ASSERT(theInitMsg || theInitMsg[0]);
	GS_ASSERT(theHeader || theHeader[0]);
	if (!aUdp->mInitialized)
	{
		gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Network, GSIDebugLevel_Debug,
			"[Udp Engine] Engine not initialized\n");
		return GS_UDP_NETWORK_ERROR;
	}
	
	// setup a message handler that the UDP engine will use to pass connection attempts to
	
	//check for valid input
	if (!theInitMsg[0])
	{
		gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Network, GSIDebugLevel_Debug,
			"[Udp Engine] Invalid init message\n");
		return GS_UDP_PARAMETER_ERROR;
	}

	if (!theHeader[0])
	{
		gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Network, GSIDebugLevel_Debug,
			"[Udp Engine] Invalid header\n");
		return GS_UDP_PARAMETER_ERROR;
	}

	// This check is not necessary.  Some SDKs may not use all callbacks
	/*if (!theMsgHandlerError || !theMsgHandlerConnected || !theMsgHandlerClosed 
		|| !theMsgHandlerPing || !theMsgHandlerRecv)
	{
		gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Network, GSIDebugLevel_Debug,
			"[Udp Engine] Invalid callback(s)");
		return GS_UDP_PARAMETER_ERROR;
	}
	*/
	aMsgHandler.mClosed = theMsgHandlerClosed;
	aMsgHandler.mConnected = theMsgHandlerConnected;
	aMsgHandler.mPingReply = theMsgHandlerPing;
	aMsgHandler.mReceived = theMsgHandlerRecv;
	
	aMsgHandler.mNetworkError = theMsgHandlerError;

	memcpy(aMsgHandler.mInitialMsg, theInitMsg, GS_UDP_MSG_HEADER_LEN);
	memcpy(aMsgHandler.mHeader, theHeader, GS_UDP_MSG_HEADER_LEN);
		
	aMsgHandler.mPendingConnections = ArrayNew(sizeof(GSUdpRemotePeer *), 1, NULL);
	if (aMsgHandler.mPendingConnections == NULL)
	{
		gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Memory, GSIDebugLevel_HotError, 
			"[Udp Engine] No more memory!!!\n");
		return GS_UDP_NO_MEMORY;
	}
	aMsgHandler.mUserData = theUserData;
	ArrayAppend(aUdp->mMsgHandlers, &aMsgHandler);
	
	return GS_UDP_NO_ERROR;
}
Ejemplo n.º 14
0
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// UDP Layer must be initialized
// theIp and thePort cannot be 0 (Zero)
// Starts a request to open a communication channel with another peer based on 
// IP and port.  
GSUdpErrorCode gsUdpEngineStartTalkingToPeer(unsigned int theIp, unsigned short thePort,
									  char theInitMsg[GS_UDP_MSG_HEADER_LEN], int timeOut)
{
	char anAddr[GS_IP_ADDR_AND_PORT];
	GSUdpRemotePeer aRemotePeer;	
	GSUdpMsgHandler aHandler;
	GSUdpEngineObject *aUdp = gsUdpEngineGetEngine();
	GT2ConnectionCallbacks aCallbacks;
	int index;
	GS_ASSERT(aUdp->mInitialized);
	GS_ASSERT(theIp);
	GS_ASSERT(thePort);

	if (!aUdp->mInitialized)
	{
		gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Network, GSIDebugLevel_Debug,
			"[Udp Engine] Engine not initialized\n");
		return GS_UDP_NETWORK_ERROR;
	}
	
	if (theIp == 0 || thePort == 0)
	{
		gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Network, GSIDebugLevel_Debug,
			"[Udp Engine] Invalid parameter(s), check ip, port");
		return GS_UDP_PARAMETER_ERROR;
	}
	
	aRemotePeer.mAddr = theIp;  // In Network Byte Order for GT2
	aRemotePeer.mPort = thePort;  // In Host Byte Order for GT2

	index = ArraySearch(aUdp->mRemotePeers, &aRemotePeer, gsUdpRemotePeerCompare, 0, 0);
	if (index != NOT_FOUND)
	{
		GSUdpRemotePeer *aPeerFound = (GSUdpRemotePeer *)ArrayNth(aUdp->mRemotePeers, index);
		GT2ConnectionState aState = gt2GetConnectionState(aPeerFound->mConnection);
		if (aState == GT2Connected)
		{
			gsDebugFormat(GSIDebugCat_Common, GSIDebugType_Network, GSIDebugLevel_Debug,
				"[Udp Engine] Engine is already talking to remote address\n");
			return GS_UDP_ADDRESS_ALREADY_IN_USE;
		}
		else if (aState == GT2Connecting)
		{
			memcpy(aHandler.mInitialMsg, theInitMsg, GS_UDP_MSG_HEADER_LEN);
			
			index = ArraySearch(aUdp->mMsgHandlers, &aHandler, gsUdpMsgHandlerCompare, 0, 0);
			if (index != NOT_FOUND)
			{
				GSUdpMsgHandler *aHandlerFound = (GSUdpMsgHandler *)ArrayNth(aUdp->mMsgHandlers, index);
				ArrayAppend(aHandlerFound->mPendingConnections, aPeerFound);
			}
		}
	}	
	else
	{
		gt2AddressToString(theIp, thePort, anAddr);
		aCallbacks.closed = gsUdpClosedRoutingCB;
		aCallbacks.connected = gsUdpConnectedRoutingCB;
		aCallbacks.ping = gsUdpPingRoutingCB;
		aCallbacks.received = gsUdpReceivedRoutingCB;

		// start the connect without blocking since we want the engine to be as asynchronous as possible
		gt2Connect(aUdp->mSocket, &aRemotePeer.mConnection, anAddr, (unsigned char *)theInitMsg, GS_UDP_MSG_HEADER_LEN, timeOut, &aCallbacks, GT2False);

		ArrayAppend(aUdp->mRemotePeers, &aRemotePeer);
		
		memcpy(aHandler.mInitialMsg, theInitMsg, GS_UDP_MSG_HEADER_LEN);
		
		index = ArraySearch(aUdp->mMsgHandlers, &aHandler, gsUdpMsgHandlerCompare, 0, 0);
		if (index != NOT_FOUND)
		{
			GSUdpRemotePeer *aRemotePeerPtr = (GSUdpRemotePeer *)ArrayNth(aUdp->mRemotePeers, ArrayLength(aUdp->mRemotePeers) - 1);
			GSUdpMsgHandler *aHandlerFound = (GSUdpMsgHandler *)ArrayNth(aUdp->mMsgHandlers, index);
			ArrayAppend(aHandlerFound->mPendingConnections, &aRemotePeerPtr);
		}
		else
		{
			aUdp->mAppPendingConnections++;
		}
	}
	return GS_UDP_NO_ERROR;
}
Ejemplo n.º 15
0
int SaveIonization(cfac_t *cfac, int nb, int *b, int nf, int *f, char *fn) {
  int i, j, k;
  int ie, ip;
  FILE *file;
  LEVEL *lev1, *lev2;
  CI_RECORD r;
  CI_HEADER ci_hdr;
  F_HEADER fhdr;
  double delta, emin, emax, e, emax0;
  double qk[MAXNE], qku[MAXNUSR];
  int nq, nqk;  
  ARRAY subte;
  int isub, n_tegrid0, n_egrid0, n_usr0;
  int te_set, e_set, usr_set;
  double c, e0, e1;

  emin = 1E10;
  emax = 1E-10;
  k = 0;
  for (i = 0; i < nb; i++) {
    lev1 = GetLevel(cfac, b[i]);
    for (j = 0; j < nf; j++) {
      lev2 = GetLevel(cfac, f[j]);
      e = lev2->energy - lev1->energy;
      if (e > 0) k++;
      if (e < emin && e > 0) emin = e;
      if (e > emax) emax = e;
    }
  }
  if (k == 0) {
    return 0;
  }

  if (tegrid[0] < 0) {
    te_set = 0;
  } else {
    te_set = 1;
  }
  if (egrid[0] < 0) {
    e_set = 0;
  } else {
    e_set = 1;
  }
  if (usr_egrid[0] < 0) {
    usr_set = 0;
  } else {
    usr_set = 1;
  }
  n_tegrid0 = n_tegrid;
  n_egrid0 = n_egrid;
  n_usr0 = n_usr;

  if (egrid_limits_type == 0) {
    emax0 = 0.5*(emin + emax)*egrid_max;
  } else {
    emax0 = egrid_max;
  }

  ArrayInit(&subte, sizeof(double), 128, NULL, NULL);
  ArrayAppend(&subte, &emin);
  c = TE_MAX_MIN;
  if (!e_set || !te_set) {
    e = c*emin;
    while (e < emax) {
      ArrayAppend(&subte, &e);
      e *= c;
    }
  }
  ArrayAppend(&subte, &emax);

  egrid_type = 1;
  pw_type = 0;
  if (usr_egrid_type < 0) usr_egrid_type = 1;
  nqk = NPARAMS;
  r.params = malloc(sizeof(float)*nqk);
    
  fhdr.type = DB_CI;
  strcpy(fhdr.symbol, cfac_get_atomic_symbol(cfac));
  fhdr.atom = cfac_get_atomic_number(cfac);
  ci_hdr.nele = GetNumElectrons(cfac, b[0]);
  ci_hdr.qk_mode = qk_mode;
  ci_hdr.nparams = nqk;
  ci_hdr.pw_type = pw_type;
  ci_hdr.egrid_type = egrid_type;
  ci_hdr.usr_egrid_type = usr_egrid_type;
  file = OpenFile(fn, &fhdr);

  e0 = emin*0.999;
  for (isub = 1; isub < subte.dim; isub++) {
    e1 = *((double *) ArrayGet(&subte, isub));
    if (isub == subte.dim-1) e1 = e1*1.001;
    emin = e1;
    emax = e0;
    k = 0;
    for (i = 0; i < nb; i++) {
      lev1 = GetLevel(cfac, b[i]);
      for (j = 0; j < nf; j++) {
	lev2 = GetLevel(cfac, f[j]);
	e = lev2->energy - lev1->energy;
	if (e < e0 || e >= e1) continue;
	if (e < emin) emin = e;
	if (e > emax) emax = e;
	k++;
      }
    }
    if (k == 0) {
      e0 = e1;
      continue;
    }

    if (qk_mode == QK_CB) {
      SetIEGrid(1, emin, emax);
    } else {
      if (n_tegrid0 == 0) {
	n_tegrid = 3;
      }
      if (!te_set) {
	e = 2.0*(emax-emin)/(emax+emin);
	if (e < EPS3) {
	  SetIEGrid(1, emin, emax);
	} else if (e < 0.5) {
	  SetIEGrid(2, emin, emax);
	} else {
	  if (k == 2) n_tegrid = 2;
	  SetIEGrid(n_tegrid, emin, emax);
	}
      }
    }

    n_egrid = n_egrid0;
    n_usr = n_usr0;
    if (!usr_set) usr_egrid[0] = -1.0;
    if (!e_set) egrid[0] = -1.0;
    
    e = 0.5*(emin + emax);
    if (egrid_limits_type == 0) {
      emin = egrid_min*e;
      emax = egrid_max*e;
    } else {
      emin = egrid_min;
      emax = egrid_max;
    }
    if (emax < emax0) {
      emax = 50.0*e;
      if (emax > emax0) emax = emax0;
    }
    
    if (n_egrid <= 0) {    
      n_egrid = 6;
    }
    if (egrid[0] < 0.0) {
      SetCIEGrid(n_egrid, emin, emax, e);
    }
    
    usr_different = 1;
    if (n_usr > 0 && usr_egrid[0] < 0.0) {
      SetUsrCIEGrid(n_usr, emin, emax, e);
      usr_egrid_type = 1;
      usr_different = 0;
    }   
    if (n_usr <= 0) {
      SetUsrCIEGridDetail(n_egrid, egrid);
      usr_egrid_type = 1;
      usr_different = 0;
    } 
    
    if (qk_mode != QK_CB) {
      SetTransitionOptions(cfac, G_BABUSHKIN, M_NR, 4, 4);
      SetRRTEGrid(1, e, e);
      SetPEGridLimits(egrid_min, egrid_max, egrid_limits_type);
      SetPEGridDetail(n_egrid, egrid);
      PrepRREGrids(e, emax0);
    }    
		  
    for (ie = 0; ie < n_egrid; ie++) {
      for (i = 0; i < n_tegrid; i++) {
	xegrid[i][ie] = egrid[ie]/tegrid[i];
	if (egrid_type == 1) xegrid[i][ie] += 1.0;
	log_xegrid[i][ie] = log(xegrid[i][ie]);
      }
    }
    yegrid0[0] = log(1E-5);
    delta = (log(0.5) - yegrid0[0])/(NINT-1.0);
    for (i = 1; i < NINT; i++) {
      yegrid0[i] = yegrid0[i-1] + delta;
    }
    for (i = 0; i < NINT; i++) {
      yegrid0[i] = exp(yegrid0[i]);
    }

    if (pw_scratch.nkl == 0) {
      SetCIPWGrid(0, NULL, NULL);
    }

    r.strength = malloc(sizeof(float)*n_usr);

    ci_hdr.n_tegrid = n_tegrid;
    ci_hdr.n_egrid = n_egrid;
    ci_hdr.n_usr = n_usr;
    ci_hdr.tegrid = tegrid;
    ci_hdr.egrid = egrid;
    ci_hdr.usr_egrid = usr_egrid;
    InitFile(file, &fhdr, &ci_hdr);

    for (i = 0; i < nb; i++) {
      lev1 = GetLevel(cfac, b[i]);
      for (j = 0; j < nf; j++) {
	lev2 = GetLevel(cfac, f[j]);
	e = lev2->energy - lev1->energy;
	if (e < e0 || e >= e1) continue;
	
        nq = IonizeStrength(cfac, qku, qk, &e, b[i], f[j]);
	if (nq < 0) continue;
	
        r.b = b[i];
	r.f = f[j];
	r.kl = nq;
	
	for (ip = 0; ip < nqk; ip++) {
	  r.params[ip] = (float) qk[ip];
	}
      
	for (ie = 0; ie < n_usr; ie++) {
	  r.strength[ie] = (float) qku[ie];
	}
	
	WriteCIRecord(file, &r);
      }
    }

    DeinitFile(file, &fhdr);

    free(r.strength);
    ReinitRadial(cfac, 1);
    FreeRecQk();
    FreeRecPk();
    FreeIonizationQk();
    
    e0 = e1;
  }

  free(r.params);

  ReinitRecombination(1);
  ReinitIonization(1);

  ArrayFree(&subte);
  CloseFile(file, &fhdr);

  return 0;
}