Beispiel #1
0
TextBox::TextBox(int w, int h)
{
	shader = LoadShaders("Shaders/Text/textBox.vert", "Shaders/Text/textBox.frag");
	WIDTH = w;
	HEIGHT = h;
	InitParameters();
}
Beispiel #2
0
/**
 * @fn Initialize()
 * @brief Setup the simulation.
 */ 
void Initialize()
{
  // Initialize the UI
  InitParameters();
  
  // First initialize extensions.
  int err = glewInit();

  if (GLEW_OK != err)
  {
    /* problem: glewInit failed, something is seriously wrong */
    fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
    exit(-1);
  }

  // Create the Cg context
  cgSetErrorCallback(cgErrorCallback);

  // Create cgContext.
  g_cgContext = cgCreateContext();
  
  // Create and initialize the Flo simulator object
  g_pFlo = new Flo(g_iFloWidth, g_iFloHeight);
  g_pFlo->Initialize(g_cgContext);

  glDisable(GL_DEPTH_TEST);
  glDisable(GL_LIGHTING);
}
Beispiel #3
0
IDirect3DDevice9* CreateDevice9(HINSTANCE dll, IDirect3D9** d3d9, D3DADAPTER_IDENTIFIER9 *d3dai)
{
    qDebug("creating d3d9 device...");
    typedef IDirect3D9* (WINAPI *Create9Func)(UINT SDKVersion);
    Create9Func Create9 = (Create9Func)GetProcAddress(dll, "Direct3DCreate9");
    if (!Create9) {
        qWarning("Symbol not found: Direct3DCreate9");
        return NULL;
    }
    *d3d9 = Create9(D3D_SDK_VERSION);
    if (!(*d3d9)) {
        qWarning("Direct3DCreate9 failed");
        return NULL;
    }
    if (d3dai)
        DX_WARN((*d3d9)->GetAdapterIdentifier(D3DADAPTER_DEFAULT, 0, d3dai));

    D3DPRESENT_PARAMETERS d3dpp;
    InitParameters(&d3dpp);
    DWORD flags = D3DCREATE_FPU_PRESERVE | D3DCREATE_MULTITHREADED | D3DCREATE_MIXED_VERTEXPROCESSING;
    IDirect3DDevice9 *d3d9dev = NULL;
    DX_ENSURE(((*d3d9)->CreateDevice(D3DADAPTER_DEFAULT,
                                     D3DDEVTYPE_HAL, GetShellWindow(),// GetDesktopWindow(), //GetShellWindow()?
                                     flags,
                                     &d3dpp, &d3d9dev))
              , NULL);
    qDebug("IDirect3DDevice9 created");
    return d3d9dev;
}
Beispiel #4
0
//----------------------------------------------------------
//  Ctor
//----------------------------------------------------------
TapCamera::TapCamera() :
                dragging_( false ),
                pinching_( false ),
                momentum_( false ),
                ball_radius_( 0.75f ),
                pinch_start_distance_SQ_( 0.f ),
                camera_rotation_( 0.f ),
                camera_rotation_start_( 0.f ),
                camera_rotation_now_( 0.f ),
                momemtum_steps_( 0.f ),
                flip_z_( 0.f )
{
    //Init offset
    InitParameters();

    vec_flip_ = Vec2( 1.f, -1.f );
    flip_z_ = -1.f;
    vec_pinch_transform_factor_ = Vec3( 1.f, 1.f, 1.f );

    vec_ball_center_ = Vec2( 0, 0 );
    vec_ball_now_ = Vec2( 0, 0 );
    vec_ball_down_ = Vec2( 0, 0 );

    vec_pinch_start_ = Vec2( 0, 0 );
    vec_pinch_start_center_ = Vec2( 0, 0 );

    vec_flip_ = Vec2( 0, 0 );

}
Beispiel #5
0
QSimpleTextItem::QSimpleTextItem()
{
    sTEXT = "Text";                       //默认文本

    m_rect.setRect(0,0,100,100);                         //给背景矩形赋初始值
    InitParameters();
}
//Function to Call the above Initialization Function in the Proper Order so as to assure that all inter-dependencies between successive calls are met. The argument defines which branch will be initialized
void PairInitializer::MakeProperInitializations(int branch, IntMatRef Homologies) {
    //A. Make General Initializations in proper order to ensure proper tree construction and parameters intialization //{
        //1. Initialize the Parameters from the Parameters File
        InitParameters();

        //2. Initialize the Rand Number Generator Engine by creating a new instance of the BoostRandomGenerator class
        InitRandomGenerator();

        //3. Initialize the Number of Steps that the left-right subtree resampling will be performed (from the previously created Parameters instance)
        InitNumOfSteps();

        //4. Initialize the Sequences (i.e. Bare Seqeunces, Initial Alignment, Sequence Headers etc) from the Corresponding Input Files
        InitSequences();

        //5. Initialize the AlignmentHomologies based on the previously read initial alignment
        InitAlignmentHomologies(Homologies);

        //6. Initialize (create) the Felsenstein Tree structure based on the red sequences and parameters
        InitTree();

        //7. Now that the tree structure is ready, Initialize ALL the Substitution Matrices for EVERY possible length of the Tree (and based on the defined - by the parameters - substitution model)
        InitOverallSubstitutionMatrices();

        //8.In a same way as before, now that the tree structure is ready, Initialize ALL the Felsenstein Pruning Tables for EVERY Node of the tree
        InitTreeFPTables();

    //}

    //B. Proceed to Make Proper Initializations for the variables and parameters concerning ONLY the subtree of interest (i.e. either the left or the right subtree) //{
        //1. Initialize the Subtree parameter to be aware of which subtree is being resampled
        InitBranch(branch);

        //2. Initialize the corresponding SubtreeIdxs for the current subtree
        InitBranchIdxs();

        //3. Initialize the Lengths corresponding only to the current subtree
        InitLengths();

        //4. Initialize the FPTables corresponding only to the current subtree
        InitFPTables();

        //5. Initialize (calculate) the Corresponding RegionHomologies based on the AlignmentHomologies corresponding only to the current fragment
        InitRegionHomologies();

        //6. Initialize the Start and End Indices for the current subtree
        InitStartAndEndIndices();

        //7. Initialize the Substitution Matrices corresponding only to the current subtree (and equivalently to the current subtree's lengths)
        InitSubstitutionMatrices();

        //8. Initialize the Dimensions (based on the previously estimated EndIdxs) corresponding  to the current subtree
        InitDimensions();

        //9. Now that everything is properly initialized, proceed to resample the whole alignment region (considering the given homologies) in order to come up with an evolution history, the Soans, the SoansIdxs and the Tihls for EVERY positon of the Root node (defined by the current subtree)
        ResampleHistoryGivenHomologies();

    //}

}
RooPolynomialFixEdgeNew::RooPolynomialFixEdgeNew(const RooPolynomialFixEdgeNew& other, const char* name) : 
  RooAbsPdf(other,name),x("x",this,other.x),
  histo(other.histo),yield(other.yield),
  c3("c3",this,other.c3),c4("c4",this,other.c4),c5("c5",this,other.c5),
  c6("c6",this,other.c6),c7("c7",this,other.c7),c8("c8",this,other.c8),
  c9("c9",this,other.c9),c10("c10",this,other.c10)
{
  if(!InitParameters())
    cout<<"Warning:"<<name<<" paramaters are not right at initialization"<<endl<<endl<<endl;
}
logical OPFunctionDecl :: Call (PropertyHandle *co, ParmList *parm_list, int8 set_operation )
{
  logical             term  = NO;
  InitParameters(parm_list);
  
  term = CallIntern(co,set_operation);

  DeInitParameters();
  

  return(term);
}
bool CCommonParm::Init(int argc, char *argv[]) {
    if (!AnalizeParameters(argc, argv))
        return false;

    if (!CheckParameters())
        return false;

    if (!InitParameters())
        return false;

    return true;
}
Beispiel #10
0
//-------------------------------------------------------------------------------
//
// DoParameters
//
// Makes sure we have valid Data and Parameters handle(s). Locks and initializes
// these items.
// 
// NOTE:
// This routine is NOT guaranteed to be called by Photoshop. If a user enters the
// CTRL-F keyboard shortcut to invoke the last filter command this routine will
// NOT be called. If the filter is ran by the actions pallete or an automation
// plug in this routine will NOT be called.
//
// NOTE:
// The fields in the gFilterRecord are not all valid at this stage.
//-------------------------------------------------------------------------------
void DoParameters(void)
{
	if (gFilterRecord->parameters == NULL)
		CreateParametersHandle();
	if ((*gDataHandle) == 0)
		CreateDataHandle();
	if (*gResult == noErr)
	{
		LockHandles();
		InitParameters();
		InitData();
	}
}
Beispiel #11
0
int ActingAsServer(int argc, char* argv[], bool dbg) {
    SerialCom comm;
    PipeShell shell;
    int nPort = 1;
    int nBaud = 9600;
    int nBits = 8;
    int nStop = 1;
    char cParity = 'N';
    char sIfName[32];
    char sLcdDev[32];
    int distance = 26000;
    int neg_mode = 0;
    bool trace_gws = dbg;
    bool trace_lcd = false;
    bool trace_neg = false;

    memset(sIfName, 0x00, 32);
    memset(sLcdDev, 0x00, 32);
    strcpy(sIfName, "wlan0");
    strcpy(sLcdDev, "/dev/ttyS0");

    if (svrInitInstance()) {
        InitParameters(true);
        BufInit(&local_gws_buff);
        ScInit(&comm, 0); //nonblock mode
        ReadFileConf(&comm, &nPort, &nBaud, &nBits, &nStop, &cParity,
                     sIfName,sLcdDev,&distance,&neg_mode,
                     &trace_gws,&trace_lcd,&trace_neg);
        ReadCmdLine(argc, argv, &nPort, &nBaud, &nBits, &nStop, &cParity,
                    &trace_lcd,&trace_neg);
        if (false == ScOpen(&comm, nPort, nBaud, nBits, nStop, cParity)) {
            ShowStatusBar("%s", "Can not open GWS radio port.\n");
        } else {
            ShowStatusBar("%s", "GWS port OK.\n");
        }
        PipeShellInit(&shell);
        svrInitCommandHandler(&comm,&shell,sIfName,trace_gws);
        ShowStatusBar("%s" VT100_RESET "\n", "gwsman server ready.\n");
        if (lcd_main(sLcdDev,distance,neg_mode,trace_lcd,trace_neg) < 0) {
            printf("\n\n");
            fflush(stdout);
            while (svrTestInstance(static_chp.m_semInstance)) usleep(100000);
        } else fflush(stdout);
        ScExit(&comm);
        BufExit(&local_gws_buff);
        svrExitCommandHandler();
    }
    svrExitInstance();
    return 1;
}
Beispiel #12
0
//-------------------------------------------------------------------------------
//
// DoPrepare
//
// Almost identical to DoParameters. Make sure we have valid Data and Parameters
// handle(s) and lock and initialize as necessary. Sets the bufferSpace and 
// maxSpace variables in the gFilterRecord so memory is used at an optimum.
//
// NOTE:
// The fields in the gFilterRecord are not all valid at this stage. We will take a
// guess at the actual tile size information.
// 
//-------------------------------------------------------------------------------
void DoPrepare(void)
{
	if (gFilterRecord->parameters != NULL && (*gDataHandle) != 0)
		LockHandles();
	else
	{
		if (gFilterRecord->parameters == NULL)
			CreateParametersHandle();
		if ((*gDataHandle) == 0)
			CreateDataHandle();
		if (*gResult == noErr)
		{
			LockHandles();
			InitParameters();
			InitData();
		}
	}
	
	// we don't need any buffer space
	gFilterRecord->bufferSpace = 0; 

	// give as much memory back to Photoshop as you can
	// we only need a tile per plane plus the maskData
	// inTileHeight and inTileWidth are invalid at this
	// point. Assume the tile size is 256 max.
	VRect filterRect = GetFilterRect();
	int32 tileHeight = filterRect.bottom - filterRect.top;
	int32 tileWidth = filterRect.right - filterRect.left;
	if (tileHeight > 256)
		tileHeight = 256;
	if (tileWidth > 256)
		tileWidth = 256;

	int32 tileSize = tileHeight * tileWidth;
	int32 planes = gFilterRecord->planes;
	if (gFilterRecord->maskData != NULL)
		planes++;
	// duplicate because we have two copies, inData and outData
	planes *= 2;

	int32 totalSize = tileSize * planes;
	// this is worst case and can be dropped considerably
	if (gFilterRecord->maxSpace > totalSize)
		gFilterRecord->maxSpace = totalSize;
}
RooPolynomialFixEdgeNew::RooPolynomialFixEdgeNew(const char *name, const char *title,RooAbsReal& _x,
					   TH1*Histo,RooFormula* Yield,RooAbsReal& _c3,RooAbsReal& _c4,RooAbsReal& _c5,
					   RooAbsReal& _c6,RooAbsReal& _c7,RooAbsReal& _c8,RooAbsReal& _c9,RooAbsReal& _c10) :
  RooAbsPdf(name,title),
  x("x","Dependent",this,_x),
  histo(Histo),
  yield(Yield),
  c3("c3","c3",this,_c3),
  c4("c4","c4",this,_c4),
  c5("c5","c5",this,_c5),
  c6("c6","c6",this,_c6),
  c7("c7","c7",this,_c7),
  c8("c8","c8",this,_c8),
  c9("c9","c9",this,_c9),
  c10("c10","c10",this,_c10)
{
  if(!InitParameters())
    cout<<"Warning:"<<name<<" paramaters are not right at initialization"<<endl<<endl<<endl;
}
//=======================================================================
//function : ShHealOper_FillHoles()
//purpose  : Constructor
//=======================================================================
ShHealOper_FillHoles::ShHealOper_FillHoles ()
{
  InitParameters();
}
Beispiel #15
0
void TapCamera::Reset( const bool bAnimate )
{
    InitParameters();
    Update();

}
Beispiel #16
0
int main(int argc, char **argv)
{
  float *Hydrograph = NULL;
  float ***MM5Input = NULL;
  float **PrecipLapseMap = NULL;
  float **PrismMap = NULL;
  unsigned char ***ShadowMap = NULL;
  float **SkyViewMap = NULL;
  float ***WindModel = NULL;
  int MaxStreamID, MaxRoadID;
  float SedDiams[NSEDSIZES];     /* Sediment particle diameters (mm) */
  clock_t start, finish1;
  double runtime = 0.0;
  int t = 0;
  float roadarea;
  time_t tloc;
  int flag;
  int i;
  int j;
  int x;						/* row counter */
  int y;						/* column counter */
  int shade_offset;				/* a fast way of handling arraay position given the number of mm5 input options */
  int NStats;					/* Number of meteorological stations */
  uchar ***MetWeights = NULL;	/* 3D array with weights for interpolating meteorological variables between the stations */

  int NGraphics;				/* number of graphics for X11 */
  int *which_graphics;			/* which graphics for X11 */
  char buffer[32];

  AGGREGATED Total = {			/* Total or average value of a  variable over the entire basin */
    {0.0, NULL, NULL, NULL, NULL, 0.0},												/* EVAPPIX */
    {0.0, 0.0, 0.0, 0.0, 0.0, NULL, NULL, 0.0, 0, 0.0},								/* PRECIPPIX */
    {{0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, 0.0, 0.0, 0.0},							/* PIXRAD */
    {0.0, 0.0},																		/* RADCLASSPIX */
    {0.0, 0.0, 0, NULL, NULL, 0.0, 0, 0.0, 0.0, 0.0, 0.0, NULL, 
	NULL, NULL, NULL, NULL, NULL, 0.0},												/* ROADSTRUCT*/
    {0, 0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},		/* SNOWPIX */
    {0, 0.0, NULL, NULL, NULL, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
     0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},			/*SOILPIX */
    { 0.0, 0.0, 0.0, 0.0, 0.0},														/*SEDPIX */
    { 0.0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},							/*FINEPIX */
    0.0, 0.0, 0.0, 0.0, 0.0, 0l, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
  };
  CHANNEL ChannelData = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  NULL, NULL, NULL, NULL};
  DUMPSTRUCT Dump;
  EVAPPIX **EvapMap = NULL;
  INPUTFILES InFiles;
  LAYER Soil;
  LAYER Veg;
  LISTPTR Input = NULL;			/* Linked list with input strings */
  MAPSIZE Map;					/* Size and location of model area */
  MAPSIZE Radar;				/* Size and location of area covered by precipitation radar */
  MAPSIZE MM5Map;				/* Size and location of area covered by MM5 input files */
  METLOCATION *Stat = NULL;
  OPTIONSTRUCT Options;			/* Structure with information which program options to follow */
  PIXMET LocalMet;				/* Meteorological conditions for current pixel */
  FINEPIX ***FineMap	= NULL;
  PRECIPPIX **PrecipMap = NULL;
  RADARPIX **RadarMap	= NULL;
  RADCLASSPIX **RadMap	= NULL;
  PIXRAD **RadiationMap = NULL;
  ROADSTRUCT **Network	= NULL;	/* 2D Array with channel information for each pixel */
  SNOWPIX **SnowMap		= NULL;
  MET_MAP_PIX **MetMap	= NULL;
  SNOWTABLE *SnowAlbedo = NULL;
  SOILPIX **SoilMap		= NULL;
  SEDPIX **SedMap		= NULL;
  SOILTABLE *SType	    = NULL;
  SEDTABLE *SedType		= NULL;
  SOLARGEOMETRY SolarGeo;		/* Geometry of Sun-Earth system (needed for INLINE radiation calculations */
  TIMESTRUCT Time;
  TOPOPIX **TopoMap = NULL;
  UNITHYDR **UnitHydrograph = NULL;
  UNITHYDRINFO HydrographInfo;	/* Information about unit hydrograph */
  VEGPIX **VegMap = NULL;
  VEGTABLE *VType = NULL;
  WATERBALANCE Mass =			/* parameter for mass balance calculations */
    { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,  
      0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };

/*****************************************************************************
  Initialization Procedures 
*****************************************************************************/
  if (argc != 2) {
    fprintf(stderr, "\nUsage: %s inputfile\n\n", argv[0]);
    fprintf(stderr, "DHSVM uses two output streams: \n");
    fprintf(stderr, "Standard Out, for the majority of output \n");
    fprintf(stderr, "Standard Error, for the final mass balance \n");
    fprintf(stderr, "\nTo pipe output correctly to files: \n");
    fprintf(stderr, "(cmd > f1) >& f2 \n");
    fprintf(stderr, "where f1 is stdout_file and f2 is stderror_file\n");
    exit(EXIT_FAILURE);
  }

  sprintf(commandline, "%s %s", argv[0], argv[1]);
  printf("%s \n", commandline);
  fprintf(stderr, "%s \n", commandline);
  strcpy(InFiles.Const, argv[1]);

  printf("\nRunning DHSVM %s\n", version);
  printf("\nSTARTING INITIALIZATION PROCEDURES\n\n");

  /* Start recording time */
  start = clock();

  ReadInitFile(InFiles.Const, &Input);
  InitConstants(Input, &Options, &Map, &SolarGeo, &Time);

  InitFileIO(Options.FileFormat);
  InitTables(Time.NDaySteps, Input, &Options, &SType, &Soil, &VType, &Veg,
	     &SnowAlbedo);

  InitTerrainMaps(Input, &Options, &Map, &Soil, &TopoMap, &SoilMap, &VegMap);

  CheckOut(Options.CanopyRadAtt, Veg, Soil, VType, SType, &Map, TopoMap, 
	   VegMap, SoilMap);

  if (Options.HasNetwork)
    InitChannel(Input, &Map, Time.Dt, &ChannelData, SoilMap, &MaxStreamID, &MaxRoadID, &Options);
  else if (Options.Extent != POINT)
    InitUnitHydrograph(Input, &Map, TopoMap, &UnitHydrograph,
		       &Hydrograph, &HydrographInfo);
 
  InitNetwork(Map.NY, Map.NX, Map.DX, Map.DY, TopoMap, SoilMap, 
	      VegMap, VType, &Network, &ChannelData, Veg, &Options);

  InitMetSources(Input, &Options, &Map, Soil.MaxLayers, &Time,
		 &InFiles, &NStats, &Stat, &Radar, &MM5Map);

  /* the following piece of code is for the UW PRISM project */
  /* for real-time verification of SWE at Snotel sites */
  /* Other users, set OPTION.SNOTEL to FALSE, or use TRUE with caution */

  if (Options.Snotel == TRUE && Options.Outside == FALSE) {
    printf
      ("Warning: All met stations locations are being set to the vegetation class GLACIER\n");
    printf
      ("Warning: This requires that you have such a vegetation class in your vegetation table\n");
    printf("To disable this feature set Snotel OPTION to FALSE\n");
    for (i = 0; i < NStats; i++) {
      printf("veg type for station %d is %d ", i,
	     VegMap[Stat[i].Loc.N][Stat[i].Loc.E].Veg);
      for (j = 0; j < Veg.NTypes; j++) {
	    if (VType[j].Index == GLACIER) {
	      VegMap[Stat[i].Loc.N][Stat[i].Loc.E].Veg = j;
		  break;
		}
      }
      if (j == Veg.NTypes) {	/* glacier class not found */
	    ReportError("MainDHSVM", 62);
	  }
      printf("setting to glacier type (assumed bare class): %d\n", j);
    }
  }

  InitMetMaps(Time.NDaySteps, &Map, &Radar, &Options, InFiles.WindMapPath,
	      InFiles.PrecipLapseFile, &PrecipLapseMap, &PrismMap,
	      &ShadowMap, &SkyViewMap, &EvapMap, &PrecipMap,
	      &RadarMap, &RadMap, SoilMap, &Soil, VegMap, &Veg, TopoMap,
	      &MM5Input, &WindModel);

  InitInterpolationWeights(&Map, &Options, TopoMap, &MetWeights, Stat, NStats);

  InitDump(Input, &Options, &Map, Soil.MaxLayers, Veg.MaxLayers, Time.Dt,
	   TopoMap, &Dump, &NGraphics, &which_graphics);

  if (Options.HasNetwork == TRUE) {
    InitChannelDump(&Options, &ChannelData, Dump.Path);
    ReadChannelState(Dump.InitStatePath, &(Time.Start), ChannelData.streams);
  }

  InitSnowMap(&Map, &SnowMap);
  InitAggregated(Veg.MaxLayers, Soil.MaxLayers, &Total);

  InitModelState(&(Time.Start), &Map, &Options, PrecipMap, SnowMap, SoilMap,
		 Soil, SType, VegMap, Veg, VType, Dump.InitStatePath,
		 SnowAlbedo, TopoMap, Network, &HydrographInfo, Hydrograph);

  InitNewMonth(&Time, &Options, &Map, TopoMap, PrismMap, ShadowMap,
	       RadMap, &InFiles, Veg.NTypes, VType, NStats, Stat, 
	       Dump.InitStatePath);

  InitNewDay(Time.Current.JDay, &SolarGeo);

  if (NGraphics > 0) {
    printf("Initialzing X11 display and graphics \n");
    InitXGraphics(argc, argv, Map.NY, Map.NX, NGraphics, &MetMap);
  }

  shade_offset = FALSE;
  if (Options.Shading == TRUE)
    shade_offset = TRUE;

  /* Done with initialization, delete the list with input strings */
  DeleteList(Input);

  /*****************************************************************************
  Sediment Initialization Procedures 
  *****************************************************************************/
  if(Options.Sediment) {
     time (&tloc);
     srand (tloc);
  /* Randomize Random Generator */
 
  /* Commenting the line above and uncommenting the line below 
     allows for the comparison of scenarios. */
  /*  srand48 (0);  */
    printf("\nSTARTING SEDIMENT INITIALIZATION PROCEDURES\n\n");

    ReadInitFile(Options.SedFile, &Input);

    InitParameters(Input, &Options, &Map, &Network, &ChannelData, TopoMap,
		   &Time, SedDiams);

    InitSedimentTables(Time.NDaySteps, Input, &SedType, &SType, &VType, &Soil, &Veg);

    InitFineMaps(Input, &Options, &Map, &Soil, &TopoMap, &SoilMap, 
		  &FineMap);

    if (Options.HasNetwork){ 
      printf("Initializing channel sediment\n\n");
      InitChannelSedimentDump(&ChannelData, Dump.Path, Options.ChannelRouting); 
      InitChannelSediment(ChannelData.streams, &Total);
      InitChannelSediment(ChannelData.roads, &Total);
    }

    InitSedMap( &Map, &SedMap);

    /* Done with initialization, delete the list with input strings */
    DeleteList(Input);
  }

  /* setup for mass balance calculations */
  Aggregate(&Map, &Options, TopoMap, &Soil, &Veg, VegMap, EvapMap, PrecipMap,
	      RadMap, SnowMap, SoilMap, &Total, VType, Network, SedMap, FineMap,
	      &ChannelData, &roadarea);

  Mass.StartWaterStorage =
    Total.Soil.IExcess + Total.CanopyWater + Total.SoilWater + Total.Snow.Swq +
    Total.Soil.SatFlow;
  Mass.OldWaterStorage = Mass.StartWaterStorage;

  if (Options.Sediment) {
    Mass.StartChannelSedimentStorage = Total.ChannelSedimentStorage;
    Mass.LastChannelSedimentStorage = Mass.StartChannelSedimentStorage;
  }

  /* computes the number of grid cell contributing to one segment */
  if (Options.StreamTemp) 
	Init_segment_ncell(TopoMap, ChannelData.stream_map, Map.NY, Map.NX, ChannelData.streams);

/*****************************************************************************
  Perform Calculations 
*****************************************************************************/
  while (Before(&(Time.Current), &(Time.End)) ||
	 IsEqualTime(&(Time.Current), &(Time.End))) {
    ResetAggregate(&Soil, &Veg, &Total, &Options);

    if (IsNewMonth(&(Time.Current), Time.Dt))
      InitNewMonth(&Time, &Options, &Map, TopoMap, PrismMap, ShadowMap,
		   RadMap, &InFiles, Veg.NTypes, VType, NStats, Stat, 
		   Dump.InitStatePath);

    if (IsNewDay(Time.DayStep)) {
      InitNewDay(Time.Current.JDay, &SolarGeo);
      PrintDate(&(Time.Current), stdout);
      printf("\n");
    }

    /* determine surface erosion and routing scheme */
    SedimentFlag(&Options, &Time); 

    InitNewStep(&InFiles, &Map, &Time, Soil.MaxLayers, &Options, NStats, Stat,
		InFiles.RadarFile, &Radar, RadarMap, &SolarGeo, TopoMap, RadMap,
        SoilMap, MM5Input, WindModel, &MM5Map);

    /* initialize channel/road networks for time step */
    if (Options.HasNetwork) {
      channel_step_initialize_network(ChannelData.streams);
      channel_step_initialize_network(ChannelData.roads);
    }

    for (y = 0; y < Map.NY; y++) {
      for (x = 0; x < Map.NX; x++) {
	    if (INBASIN(TopoMap[y][x].Mask)) {
		  if (Options.Shading)
	        LocalMet =
	        MakeLocalMetData(y, x, &Map, Time.DayStep, &Options, NStats,
			       Stat, MetWeights[y][x], TopoMap[y][x].Dem,
			       &(RadMap[y][x]), &(PrecipMap[y][x]), &Radar,
			       RadarMap, PrismMap, &(SnowMap[y][x]),
			       SnowAlbedo, MM5Input, WindModel, PrecipLapseMap,
			       &MetMap, NGraphics, Time.Current.Month,
			       SkyViewMap[y][x], ShadowMap[Time.DayStep][y][x],
			       SolarGeo.SunMax, SolarGeo.SineSolarAltitude);
		  else
	        LocalMet =
	        MakeLocalMetData(y, x, &Map, Time.DayStep, &Options, NStats,
			       Stat, MetWeights[y][x], TopoMap[y][x].Dem,
			       &(RadMap[y][x]), &(PrecipMap[y][x]), &Radar,
			       RadarMap, PrismMap, &(SnowMap[y][x]),
			       SnowAlbedo, MM5Input, WindModel, PrecipLapseMap,
			       &MetMap, NGraphics, Time.Current.Month, 0.0,
			       0.0, SolarGeo.SunMax,
			       SolarGeo.SineSolarAltitude);
		  
		  for (i = 0; i < Soil.MaxLayers; i++) {
	        if (Options.HeatFlux == TRUE) {
	          if (Options.MM5 == TRUE)
		        SoilMap[y][x].Temp[i] =
				MM5Input[shade_offset + i + N_MM5_MAPS][y][x];
			  else
		        SoilMap[y][x].Temp[i] = Stat[0].Data.Tsoil[i];
			}
	        else
	          SoilMap[y][x].Temp[i] = LocalMet.Tair;
		  }
		  
		  MassEnergyBalance(&Options, y, x, SolarGeo.SineSolarAltitude, Map.DX, Map.DY, 
			    Time.Dt, Options.HeatFlux, Options.CanopyRadAtt, Options.RoadRouting, 
			    Options.Infiltration, Veg.MaxLayers, &LocalMet, &(Network[y][x]), 
			    &(PrecipMap[y][x]), &(VType[VegMap[y][x].Veg-1]), &(VegMap[y][x]),
			    &(SType[SoilMap[y][x].Soil-1]), &(SoilMap[y][x]), &(SnowMap[y][x]), 
				&(EvapMap[y][x]), &(Total.Rad), &ChannelData, SkyViewMap);
		 
		  PrecipMap[y][x].SumPrecip += PrecipMap[y][x].Precip;
		}
	  }
    }

	/* Average all RBM inputs over each segment */
	if (Options.StreamTemp) {
	  channel_grid_avg(ChannelData.streams);
	}

 #ifndef SNOW_ONLY

    /* set sediment inflows to zero - they are incremented elsewhere */
    if ((Options.HasNetwork) && (Options.Sediment)){ 
      InitChannelSedInflow(ChannelData.streams);
      InitChannelSedInflow(ChannelData.roads);
	}
    
    RouteSubSurface(Time.Dt, &Map, TopoMap, VType, VegMap, Network,
		    SType, SoilMap, &ChannelData, &Time, &Options, Dump.Path,
		    SedMap, FineMap, SedType, MaxStreamID, SnowMap);

    if (Options.HasNetwork)
      RouteChannel(&ChannelData, &Time, &Map, TopoMap, SoilMap, &Total, 
		   &Options, Network, SType, PrecipMap, SedMap,
		   LocalMet.Tair, LocalMet.Rh, SedDiams);

    /* Sediment Routing in Channel and output to sediment files */
    if ((Options.HasNetwork) && (Options.Sediment)){
      SPrintDate(&(Time.Current), buffer);
      flag = IsEqualTime(&(Time.Current), &(Time.Start));

      if (Options.ChannelRouting){
	    if (ChannelData.roads != NULL) {
	      RouteChannelSediment(ChannelData.roads, Time, &Dump, &Total, SedDiams);
	      channel_save_sed_outflow_text(buffer, ChannelData.roads,
					ChannelData.sedroadout,
					ChannelData.sedroadflowout, flag);
		  RouteCulvertSediment(&ChannelData, &Map, TopoMap, SedMap, 
			       &Total, SedDiams);
		}
	    RouteChannelSediment(ChannelData.streams, Time, &Dump, &Total, SedDiams);
 	    channel_save_sed_outflow_text(buffer, ChannelData.streams,
				      ChannelData.sedstreamout,
				      ChannelData.sedstreamflowout, flag);
	  }
      else {
	    if (ChannelData.roads != NULL) {
			channel_save_sed_inflow_text(buffer, ChannelData.roads,
			ChannelData.sedroadinflow, SedDiams,flag);
		}
	    channel_save_sed_inflow_text(buffer, ChannelData.streams,
			ChannelData.sedstreaminflow, SedDiams,flag);
      }
      SaveChannelSedInflow(ChannelData.roads, &Total);
      SaveChannelSedInflow(ChannelData.streams, &Total);
    }
    
    if (Options.Extent == BASIN)
      RouteSurface(&Map, &Time, TopoMap, SoilMap, &Options,
		   UnitHydrograph, &HydrographInfo, Hydrograph,
		   &Dump, VegMap, VType, SType, &ChannelData, SedMap,
		   PrecipMap, SedType, LocalMet.Tair, LocalMet.Rh, SedDiams);

#endif

    if (NGraphics > 0)
      draw(&(Time.Current), IsEqualTime(&(Time.Current), &(Time.Start)),
	   Time.DayStep, &Map, NGraphics, which_graphics, VType,
	   SType, SnowMap, SoilMap, SedMap, FineMap, VegMap, TopoMap, PrecipMap,
	   PrismMap, SkyViewMap, ShadowMap, EvapMap, RadMap, MetMap, Network,
	   &Options);
    
    Aggregate(&Map, &Options, TopoMap, &Soil, &Veg, VegMap, EvapMap, PrecipMap,
	      RadMap, SnowMap, SoilMap, &Total, VType, Network, SedMap, FineMap,
	      &ChannelData, &roadarea);
    
    MassBalance(&(Time.Current), &(Dump.Balance), &(Dump.SedBalance), &Total, 
		&Mass, &Options);

    ExecDump(&Map, &(Time.Current), &(Time.Start), &Options, &Dump, TopoMap,
	     EvapMap, RadiationMap, PrecipMap, RadMap, SnowMap, MetMap, VegMap, &Veg, 
		 SoilMap, SedMap, Network, &ChannelData, FineMap, &Soil, &Total, 
		 &HydrographInfo,Hydrograph);
	
    IncreaseTime(&Time);
	t += 1;
  }

  ExecDump(&Map, &(Time.Current), &(Time.Start), &Options, &Dump, TopoMap,
	   EvapMap, RadiationMap, PrecipMap, RadMap, SnowMap, MetMap, VegMap, &Veg, SoilMap,
	   SedMap, Network, &ChannelData, FineMap, &Soil, &Total, &HydrographInfo, Hydrograph);

  FinalMassBalance(&(Dump.FinalBalance), &Total, &Mass, &Options, roadarea);

  /*printf("\nSTARTING CLEANUP\n\n");
  cleanup(&Dump, &ChannelData, &Options);*/
  printf("\nEND OF MODEL RUN\n\n");

  /* record the run time at the end of each time loop */
  finish1 = clock ();
  runtime = (finish1-start)/CLOCKS_PER_SEC;
  printf("***********************************************************************************");
  printf("\nRuntime Summary:\n");
  printf("%6.2f hours elapsed for the simulation period of %d hours (%.1f days) \n", 
	  runtime/3600, t*Time.Dt/3600, (float)t*Time.Dt/3600/24);

  return EXIT_SUCCESS;
}
Beispiel #17
0
Bsemff_BCL::Bsemff_BCL(double m2):Bsemff(m2),Kv(0),Ks(0),bvk(0),bsk(0){
  double t0 = mBpi*pow(sqrt(mB0)-sqrt(mH),2);
  SetAux(t0);
  InitParameters();
}
Beispiel #18
0
void TextBox::setSize(ivec2 size)
{
	WIDTH = size.x;
	HEIGHT = size.y;
	InitParameters();
}
Beispiel #19
0
/*****************************************************************************
  函数名称:QSimpleTextItem(QRectF Rect, QString sText)
  函数意义:带参数构造函数
  参数含义:Rect文本的背景矩形框大小,sText初始文本
*****************************************************************************/
QSimpleTextItem::QSimpleTextItem(QRectF Rect, QString sText)
{
    sTEXT = sText;                        //默认文本
    m_rect = Rect;                        //给背景矩形赋初始值
    InitParameters();
}
Beispiel #20
0
/*
______________________________________________________________________________________________

Main
______________________________________________________________________________________________

*/
int main(int argc, char *argv[])
{
	// --- Init Cluster variable ---------------------------------------------------------

	// carmen 0 => local execution i.e. show time on screen
	// carmen 1 => cluster execution i.e. refresh Performance.dat (default)

#if defined PARMPI
	// --- MPI Runtime system initialization
	// size - total number of processors
	// rnak - current CPU
	MPI_Init(&argc,&argv);
	MPI_Comm_size(MPI_COMM_WORLD, &size);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#else
  	size=1;
	rank=0;
#endif
  
	if (argc == 2)
		Cluster = atoi(argv[1]);

	// --- Print messages on screen- -----------------------------------------------------

	cout << "carmen: begin execution.\n\n";
	printf("Carmen %4.2f \n",CarmenVersion);
	cout << "Copyright (C) 2000-2005 by Olivier Roussel.\n";
	cout << "All rights reserved.\n\n";
	
#if defined PARMPI
	//Synchronize all parallel branches
  	MPI_Barrier(MPI_COMM_WORLD);
#endif

  	CPUTime.start();
  
  // --- Create first node of the tree structure ---------------------------------------

	Node 	*Mesh=0;
	FineMesh *FMesh=0;

	
	// --- Init global values (See Parameters.h and Parameters.cpp) ----------------------------

	cout << "carmen: init computation ...\n";
	InitParameters();

  // --- Debug output information for parallel execution -------------------------------------
  
#if defined PARMPI                                                                            
  	if (Multiresolution) 
  	{
		printf("\nParallel Multiresolution solver not implemented yet!\n");
		exit(0);
	}
	
  	printf("My Rank=%d\n",rank);
  
  	// --- Each CPU print his coordinates in the virtual processor cart ------------------------
	printf("Cart_i = %d;     Cart_j = %d;     Cart_k = %d;\n",coords[0],coords[1],coords[2]);
	
  	// --- Each CPU print his computation domain
  	printf("Xmin = %lf;     XMax = %lf;\n",XMin[1],XMax[1]);
	printf("Ymin = %lf;     YMax = %lf;\n",XMin[2],XMax[2]);
	printf("Zmin = %lf;     ZMax = %lf;\n",XMin[3],XMax[3]);
	
  	// --- And the local scale number ----------------------------------------------------------
  	printf("ScaleNb = %d\n",ScaleNb);
#endif
  
	// --- Allocate ----------------------------------------------------------------------------

	if (Multiresolution)
		Mesh = new Node;
	else
		FMesh = new FineMesh;

	// --- Init tree structure -----------------------------------------------------------------

	if (Multiresolution)
	{
		InitTree(Mesh);
		RefreshTree(Mesh);
	}

	// --- Compute initial integral values and init time step ----------------------------------

	if (Multiresolution)
		Mesh->computeIntegral();
	else
		FMesh->computeIntegral();
	
	// -- Write integral values --
	
	
			
	// -- Compute initial time step --
	InitTimeStep();

	if (rank==0) PrintIntegral("Integral.dat");

	// --- Save initial values into files ------------------------------------------------------

	if (PrintEvery == 0)
	{
		if (Multiresolution)
			View(Mesh, "Tree_0.dat", "Mesh_0.dat", "Average_0.dat");
		else
			View(FMesh,"Average_0.dat");
	}
	
	// --- When PrintEvery != 0, save initial values into specific name format ---

	if (PrintEvery != 0)
	{
		if (Multiresolution)
			ViewEvery(Mesh, 0);
		else
			ViewEvery(FMesh, 0);
	}

  	// --- Parallel execution only --------------------------------------------
  	// --- Save to disk DX header for ouput files -----------------------------
  	// --- This file is needed for the external postprocessing (merging files from the different processors)

#if defined PARMPI

	real 	tempXMin[4];
	real	tempXMax[4];
	
  	// --- Save original task parameters for the parallel execution
  	int tempScaleNb=ScaleNb;

  	// --- Simulate sequantial running
  	ScaleNb=AllTaskScaleNb;

  	for (int i=0;i<4;i++) 
  	{
  		tempXMin[i]=XMin[i];
		tempXMax[i]=XMax[i];
		// --- Simulate sequantial running
		XMin[i]=AllXMin[i];
		XMax[i]=AllXMax[i];
  	}

  	// --- Write header with parameters, as we have run sequantial code
  	if (rank==0) FMesh->writeHeader("header.txt");

  	// Restore variables
  	for (int i=0;i<4;i++) 
  	{
		XMin[i]=tempXMin[i];
   		XMax[i]=tempXMax[i];
	}
	
  	ScaleNb=tempScaleNb;

#endif  
  
  	// --- Done ---

	cout << "carmen: done.\n";

	// --- Write solver type ---

	if (Multiresolution)
		cout << "carmen: multiresolution (MR) solver.\n";
	else
		cout << "carmen: finite volume (FV) solver.\n";

	// --- Write number of iterations ---

	if (IterationNb == 1)
		cout << "carmen: compute 1 iteration ...\n";
  	else
		cout << "carmen: compute " << IterationNb << " iterations ...\n";
	
	printf("\n\n\n");

	// --- Begin time iteration ----------------------------------------------------------------

	for (IterationNo = 1; IterationNo <= IterationNb; IterationNo++)
	{

		// --- Time evolution procedure ---
		if (Multiresolution)
			TimeEvolution(Mesh);
		else
			TimeEvolution(FMesh);

		// --- Remesh ---
		 if (Multiresolution) Remesh(Mesh);

		// --- Check CPU Time ---
	  	CPUTime.check();

		// --- Write information every (Refresh) iteration ---
		if ((IterationNo-1)%Refresh == 0)
		{                                          
			// - Write integral values -
			if (rank==0) PrintIntegral("Integral.dat");

			if (Cluster == 0)
				ShowTime(CPUTime);  // Show time on screen
		  //else
			if (rank==0) Performance("carmen.prf"); // Refresh file "carmen.prf"
    		}

		// --- Backup data every (10*Refresh) iteration ---
		if ((IterationNo-1)%(10*Refresh) == 0 && UseBackup)
		{
			if (Multiresolution)
				Backup(Mesh);
			else
				Backup(FMesh);
    		}

		// --- Print solution if IterationNo = PrintIt1 to PrintIt6 ---
		if (Multiresolution)
			ViewIteration(Mesh);
		else
			ViewIteration(FMesh);

		// --- Print solution if IterationNo is a multiple of PrintEvery ---

		if (PrintEvery != 0)
		{
     			if (IterationNo%PrintEvery == 0)
			{
				if (Multiresolution)
					ViewEvery(Mesh, IterationNo);
				else
					ViewEvery(FMesh, IterationNo);
			}
		}

	// --- End time iteration ------------------------------------------------------------------
	}	

	// --- Backup final data  ------------------------------------------------------------------

	IterationNo--;

	if (UseBackup)
  {
		if (Multiresolution)
			Backup(Mesh);
		else
			Backup(FMesh);
	}

	// --- Write integral values ---------------------------------------------------------------
	
	if (rank==0) PrintIntegral("Integral.dat");
	
	IterationNo++;

	// --- Save values into file ---------------------------------------------------------------

	if (Multiresolution)
		View(Mesh, "Tree.dat", "Mesh.dat", "Average.dat");
	else
		View(FMesh, "Average.dat");

	cout << "\ncarmen: done.\n";
	
	// --- Analyse performance and save it into file -------------------------------------------
				
	if (rank==0) Performance("carmen.prf");	

	// --- End ---------------------------------------------------------------------------------

	if (Multiresolution)
		delete Mesh;
	else
		delete FMesh;


#if defined PARMPI

  	//free memory for the MPI runtime variables
	delete[] disp;
	delete[] blocklen;
	int sz;
	MPI_Buffer_detach(&MPIbuffer,&sz);
	// for (int i = 0; i < 4*Dimension; i++)	MPI_Request_free(&req[i]);
	MPI_Finalize();
	
#endif
    
  	cout <<"carmen: end execution.\n";
	return EXIT_SUCCESS;
}
MyFigureGlut::MyFigureGlut(const char* title, int win_width, int win_height, int method) 
  : FigureGlut(title, win_width, win_height, method)
{
  Draw_Method = method;
  InitParameters();
}
MyFigureGlut::MyFigureGlut(const char* title, int win_width, int win_height, int* argc, TCHAR* argv[]) 
  : FigureGlut(title, win_width, win_height, argc, argv)
{
  InitParameters();
}
Beispiel #23
0
int main(int argc, char *argv[])
{
  int i,j,k,l,inmethod,outmethod,info,errorstat;
  int nogrids,nomeshes,nofile,dim,elementsredone=0;
  int nodes3d,elements3d,showmem;
  Real mergeeps;
  char prefix[MAXFILESIZE];
  struct GridType *grids;
  struct CellType *cell[MAXCASES];
  struct FemType data[MAXCASES];
  struct BoundaryType *boundaries[MAXCASES];
  struct ElmergridType eg;

  showmem = TRUE;

  printf("\nStarting program Elmergrid\n");

  InitParameters(&eg);

  grids = (struct GridType*)malloc((size_t) (MAXCASES)*sizeof(struct GridType));     
  InitGrid(grids);
  info = TRUE;

  if(argc <= 1) {
    errorstat = LoadCommands(argv[1],&eg,grids,argc-1,info);     
    Instructions();
    if(errorstat) Goodbye();
  }
  if(argc == 2) {
    errorstat = LoadCommands(argv[1],&eg,grids,argc-1,info);     
    if(errorstat) Goodbye();
  }
  else if(argc < 4) {
    Instructions();
    Goodbye();
  } 
  else {
    errorstat = InlineParameters(&eg,argc,argv);
    if(errorstat) Goodbye();
  }


  if(!eg.outmethod || !eg.inmethod) {
    printf("Please define the input and output formats\n");
  }
  if(eg.inmethod != 1) {
    if(eg.outmethod == 1 || eg.outmethod == 8 || eg.outmethod == 9 || eg.outmethod == 10) {
      printf("input of type %d can't create output of type %d\n",
	     eg.inmethod,eg.outmethod);
      errorstat++;
      Goodbye();
    }
  }
#if 0
  if(eg.inmethod != 8 && eg.outmethod == 5) {
    printf("To write Easymesh format you need to read easymesh format!\n");
    errorstat++;
  }
#endif

  if(eg.timeron) timer_activate(eg.infofile);

  /**********************************/
  printf("\nElmergrid loading data:\n");
  printf(  "-----------------------\n");

  dim = eg.dim;
  nofile = 0;
  nomeshes = 0;
  nogrids = 0;
  inmethod = eg.inmethod;
  outmethod = eg.outmethod;


 read_another_file:    

  timer_show();
  
  switch (inmethod) {

  case 1:        
    if(LoadElmergrid(&grids,&nogrids,eg.filesin[nofile],eg.relh,info) == 1) {   
      if(dim == 3) ExampleGrid3D(&grids,&nogrids,info);
      if(dim == 2) ExampleGrid2D(&grids,&nogrids,info);
      if(dim == 1) ExampleGrid1D(&grids,&nogrids,info);
      SaveElmergrid(grids,nogrids,eg.filesin[nofile],info); 
      printf("Because file %s didn't exist, it was created for you.\n",eg.filesin[nofile]);
      Goodbye();
    }
    LoadCommands(eg.filesin[nofile],&eg,grids,2,info); 
    break;

  case 2: 
    boundaries[nofile] = (struct BoundaryType*)
      malloc((size_t) (MAXBOUNDARIES)*sizeof(struct BoundaryType)); 	
    for(i=0;i<MAXBOUNDARIES;i++) {
      boundaries[nofile][i].created = FALSE; 
      boundaries[nofile][i].nosides = 0;
    }
    if(LoadElmerInput(&(data[nofile]),boundaries[nofile],eg.filesin[nofile],info))
      Goodbye();
    nomeshes++;
    break;

  case 3: 
    if(LoadSolutionElmer(&(data[nofile]),TRUE,eg.filesin[nofile],info)) 
      Goodbye();
    nomeshes++;
    break;

  case 4:
    boundaries[nofile] = (struct BoundaryType*)
      malloc((size_t) (MAXBOUNDARIES)*sizeof(struct BoundaryType)); 	
    if(LoadAnsysInput(&(data[0]),boundaries[0],eg.filesin[nofile],info)) 
      Goodbye();
    nomeshes++;
    break;

  case 5: 
    boundaries[nofile] = (struct BoundaryType*)
      malloc((size_t) (MAXBOUNDARIES)*sizeof(struct BoundaryType)); 	
    for(i=0;i<MAXBOUNDARIES;i++) {
      boundaries[nofile][i].created = FALSE; 
      boundaries[nofile][i].nosides = 0;
    }
    if(LoadAbaqusInput(&(data[nofile]),boundaries[nofile],eg.filesin[nofile],TRUE)) 
      Goodbye();
    nomeshes++;
    break;

  case 6:
    if(LoadAbaqusOutput(&(data[nofile]),eg.filesin[nofile],TRUE))
      Goodbye();
    nomeshes++;
    break;

  case 7:
    if(LoadFidapInput(&(data[nofile]),eg.filesin[nofile],TRUE))
      Goodbye();
    boundaries[nofile] = (struct BoundaryType*)
      malloc((size_t) (MAXBOUNDARIES)*sizeof(struct BoundaryType)); 	
    for(i=0;i<MAXBOUNDARIES;i++) {
      boundaries[nofile][i].created = FALSE; 
      boundaries[nofile][i].nosides = 0;
    }
    if(0 && !eg.usenames) data[nofile].boundarynamesexist = data[nofile].bodynamesexist = FALSE;
    ElementsToBoundaryConditions(&(data[nofile]),boundaries[nofile],FALSE,TRUE);
    RenumberBoundaryTypes(&data[nofile],boundaries[nofile],TRUE,0,info);
  
    nomeshes++;
    break;

  case 8:
    boundaries[nofile] = (struct BoundaryType*)
      malloc((size_t) (MAXBOUNDARIES)*sizeof(struct BoundaryType)); 	
    for(i=0;i<MAXBOUNDARIES;i++) {
      boundaries[nofile][i].created = FALSE; 
      boundaries[nofile][i].nosides = 0;
    }
    if (LoadUniversalMesh(&(data[nofile]),boundaries[nofile],eg.filesin[nofile],TRUE))
      Goodbye();
    nomeshes++;
    break;

 case 9:
    boundaries[nofile] = (struct BoundaryType*)
      malloc((size_t) (MAXBOUNDARIES)*sizeof(struct BoundaryType)); 	
    for(i=0;i<MAXBOUNDARIES;i++) {
      boundaries[nofile][i].created = FALSE; 
      boundaries[nofile][i].nosides = 0;
    }
   
    if(LoadComsolMesh(&(data[nofile]),eg.filesin[nofile],info)) 
      Goodbye();
    ElementsToBoundaryConditions(&(data[nofile]),boundaries[nofile],FALSE,TRUE);
    nomeshes++;
    break;

  case 10:
    if(LoadFieldviewInput(&(data[nofile]),eg.filesin[nofile],TRUE))
      Goodbye();
    boundaries[nofile] = (struct BoundaryType*)
      malloc((size_t) (MAXBOUNDARIES)*sizeof(struct BoundaryType)); 	    
    for(i=0;i<MAXBOUNDARIES;i++) {
      boundaries[nofile][i].created = FALSE; 
      boundaries[nofile][i].nosides = 0;
    }
    ElementsToBoundaryConditions(&(data[nofile]),boundaries[nofile],FALSE,TRUE);
    nomeshes++;
    break;

  case 11:
    boundaries[nofile] = (struct BoundaryType*)
      malloc((size_t) (MAXBOUNDARIES)*sizeof(struct BoundaryType)); 	
    for(i=0;i<MAXBOUNDARIES;i++) {
      boundaries[nofile][i].created = FALSE; 
      boundaries[nofile][i].nosides = 0;
    }
    if (LoadTriangleInput(&(data[nofile]),boundaries[nofile],eg.filesin[nofile],TRUE))
      Goodbye();
    nomeshes++;
    break;

  case 12:
    boundaries[nofile] = (struct BoundaryType*)
      malloc((size_t) (MAXBOUNDARIES)*sizeof(struct BoundaryType)); 	
    for(i=0;i<MAXBOUNDARIES;i++) {
      boundaries[nofile][i].created = FALSE; 
      boundaries[nofile][i].nosides = 0;
    }
    if (LoadMeditInput(&(data[nofile]),boundaries[nofile],eg.filesin[nofile],TRUE))
      Goodbye();
    nomeshes++;
    break;

  case 13:
    boundaries[nofile] = (struct BoundaryType*)
      malloc((size_t) (MAXBOUNDARIES)*sizeof(struct BoundaryType)); 	
    for(i=0;i<MAXBOUNDARIES;i++) {
      boundaries[nofile][i].created = FALSE; 
      boundaries[nofile][i].nosides = 0;
    }
    if (LoadGidInput(&(data[nofile]),boundaries[nofile],eg.filesin[nofile],TRUE))
      Goodbye();
    nomeshes++;
    break;

  case 14:
    boundaries[nofile] = (struct BoundaryType*)
      malloc((size_t) (MAXBOUNDARIES)*sizeof(struct BoundaryType)); 	
    for(i=0;i<MAXBOUNDARIES;i++) {
      boundaries[nofile][i].created = FALSE; 
      boundaries[nofile][i].nosides = 0;
    }
    if (LoadGmshInput(&(data[nofile]),boundaries[nofile],eg.filesin[nofile],TRUE))
      Goodbye();
    nomeshes++;
    break;

  case 15: 
    if(info) printf("Partitioned solution is fused on-the-fly therefore no other operations may be performed.\n");
    FuseSolutionElmerPartitioned(eg.filesin[nofile],eg.filesout[nofile],eg.decimals,eg.partjoin,
				 eg.saveinterval[0],eg.saveinterval[1],eg.saveinterval[2],info);
    if(info) printf("Finishing with the fusion of partitioned Elmer solutions\n");
    Goodbye();
    break;

#if 0
  case 16: 
    InitializeKnots(&(data[nofile]));
    if( Easymesh(argc,argv,&data[nofile].noknots,
		 &data[nofile].noelements,&sides)) 
      Goodbye();	
    
    data[nofile].dim = 2;
    data[nofile].coordsystem = COORD_CART2;
    data[nofile].maxnodes = 3;
    
    AllocateKnots(&(data[nofile]));
    boundaries[nofile] = (struct BoundaryType*)
      malloc((size_t) (MAXBOUNDARIES)*sizeof(struct BoundaryType)); 	
    for(i=0;i<MAXBOUNDARIES;i++) {
      boundaries[nofile][i].created = FALSE; 
      boundaries[nofile][i].nosides = 0;
    }
    if(EasymeshCopy(&(data[nofile]),boundaries[nofile]))
      Goodbye();    
    nomeshes++;
    break;
#endif

  case 17:
    boundaries[nofile] = (struct BoundaryType*)
      malloc((size_t) (MAXBOUNDARIES)*sizeof(struct BoundaryType)); 	
    for(i=0;i<MAXBOUNDARIES;i++) {
      boundaries[nofile][i].created = FALSE; 
      boundaries[nofile][i].nosides = 0;
    }
    if (LoadNastranInput(&(data[nofile]),boundaries[nofile],eg.filesin[nofile],TRUE))
      Goodbye();
    nomeshes++;
    break;

  case 18:
    boundaries[nofile] = (struct BoundaryType*)
      malloc((size_t) (MAXBOUNDARIES)*sizeof(struct BoundaryType)); 	
    for(i=0;i<MAXBOUNDARIES;i++) {
      boundaries[nofile][i].created = FALSE; 
      boundaries[nofile][i].nosides = 0;
    }
   
    if(LoadCGsimMesh(&(data[nofile]),eg.filesin[nofile],info))
       Goodbye();
    nomeshes++;
    break;

  case 19:
    boundaries[nofile] = (struct BoundaryType*)
      malloc((size_t) (MAXBOUNDARIES)*sizeof(struct BoundaryType)); 	
    for(i=0;i<MAXBOUNDARIES;i++) {
      boundaries[nofile][i].created = FALSE; 
      boundaries[nofile][i].nosides = 0;
    }
    if (LoadGeoInput(&(data[nofile]),boundaries[nofile],eg.filesin[nofile],TRUE))
      Goodbye();
    nomeshes++;
    break;

  default:
    Instructions();
    Goodbye();
  }  

  nofile++;
  if(nofile < eg.nofilesin) {
    printf("\nElmergrid loading data from another file:\n");
    goto read_another_file;
  }

  /***********************************/


 redoelements:

  printf("\nElmergrid creating and manipulating meshes:\n");
  printf(  "-------------------------------------------\n");
  timer_show();


  if(nogrids > nomeshes && outmethod != 1) { 

    nomeshes = nogrids;
    for(k=0;k<nogrids;k++) {

      CreateCells(&(grids[k]),&(cell[k]),info);  
      CreateKnots(&(grids[k]),cell[k],&(data[k]),0,0);

      boundaries[k] = (struct BoundaryType*)
	malloc((size_t) (MAXBOUNDARIES)*sizeof(struct BoundaryType)); 

      for(j=0;j<MAXBOUNDARIES;j++) {
	boundaries[k][j].created = FALSE;
	boundaries[k][j].nosides = FALSE;
      }

      if(grids[k].noboundaries > 0) {
	for(j=0;j<grids[k].noboundaries;j++) {
	  if(grids[k].boundsolid[j] < 4) {
	    CreateBoundary(cell[k],&(data[k]),&(boundaries[k][j]),
			   grids[k].boundext[j],grids[k].boundint[j],
			   1,grids[k].boundtype[j]);  
	  } 
	  else { 
	    CreatePoints(cell[k],&(data[k]),&(boundaries[k][j]),
			 grids[k].boundext[j],grids[k].boundint[j],
			 grids[k].boundsolid[j],grids[k].boundtype[j]); 	    
	  }
	}
      }
    }
  }

  /* In some formats the dimension for curved 2D meshes seems to be set to 2.
     This should fix the problem for all input types. */
  if( data->dim < 3 ) {
    data->dim = GetCoordinateDimension(data,info);
  }

 
  /* Make the discontinous boundary needed, for example, in poor thermal conduction */
  for(k=0;k<nomeshes;k++) {
    if(!eg.discont) {
      for(j=0;j<grids[k].noboundaries;j++) 
	if(grids[k].boundsolid[j] == 2) {
	  eg.discontbounds[eg.discont] = grids[k].boundtype[j];
	  eg.discont++;	  
	}
    }
    if(eg.discont) {
      for(i=1;i<=eg.discont;i++) 
	SetDiscontinuousBoundary(&(data[k]),boundaries[k],eg.discontbounds[i-1],2,info);
    }
  }


  /* Divide quadrilateral meshes into triangular meshes */
  for(k=0;k<nomeshes;k++) 
    if(nogrids && (eg.triangles || grids[k].triangles == TRUE)) {
      Real criticalangle;
      criticalangle = MAX(eg.triangleangle , grids[k].triangleangle);
      ElementsToTriangles(&data[k],boundaries[k],criticalangle,info);
    }


  /* Make a boundary layer with two different methods */
  if(eg.layers > 0) 
    for(k=0;k<nomeshes;k++) 
      CreateBoundaryLayer(&data[k],boundaries[k],eg.layers,
			  eg.layerbounds, eg.layernumber, eg.layerratios, eg.layerthickness,
			  eg.layerparents, eg.layermove, eg.layereps, info);

  else if(eg.layers < 0) 
    for(k=0;k<nomeshes;k++) 
      CreateBoundaryLayerDivide(&data[k],boundaries[k],abs(eg.layers),
				eg.layerbounds, eg.layernumber, eg.layerratios, eg.layerthickness,
				eg.layerparents, info);

  /* Take up the infor on rotation */
  for(k=0;k<nogrids;k++) 
    if( grids[k].rotatecurve ) {
      eg.rotatecurve = TRUE;
      eg.curvezet = grids[k].curvezet;
      eg.curverad = grids[k].curverad;
      eg.curveangle = grids[k].curveangle;
    }


  if(outmethod != 1 && dim != 2 && eg.dim != 2) { 
    j = MAX(nogrids,1);


    for(k=0;k<j;k++) {
      if(grids[k].dimension == 3 || grids[k].rotate) {

	boundaries[j] = (struct BoundaryType*)
	  malloc((size_t) (MAXBOUNDARIES)*sizeof(struct BoundaryType)); 	
	
	for(i=0;i<MAXBOUNDARIES;i++) 
	  boundaries[j][i].created = FALSE;

	CreateKnotsExtruded(&(data[k]),boundaries[k],&(grids[k]),
			    &(data[j]),boundaries[j],info);

	if(nogrids) {
	  elements3d = MAX(eg.elements3d, grids[k].wantedelems3d);
	  nodes3d = MAX(eg.nodes3d, grids[k].wantednodes3d);

	  if(elements3d) {
	    if( abs(data[j].noelements - elements3d) / (1.0*elements3d) > 0.01 && elementsredone < 5 ) {
	      grids[k].wantedelems *= pow(1.0*elements3d / data[j].noelements, (2.0/3.0));
	      elementsredone++;
	    }
	    else elementsredone = 0;
	  }
	  else if(nodes3d) {
	    if( abs(data[j].noknots - nodes3d) / (1.0*nodes3d) > 0.01 && elementsredone < 5 ) {
	      grids[k].wantedelems *= pow(1.0*nodes3d / data[j].noknots, (2.0/3.0));
	      elementsredone++;
	    }
	    else elementsredone = 0;
	  }

	  if(elementsredone) {
	    nomeshes = 0;
	    for(i=0;i < nogrids;i++) SetElementDivision(&(grids[i]),eg.relh,info);
	    
	    DestroyKnots(&data[j]);
	    DestroyKnots(&data[k]);
	    free(cell[k]);
	    
	    if(info) printf("Iteration %d of elements number targiting %d in 2D\n",
			    elementsredone,grids[k].wantedelems);
	    goto redoelements;
	  }
	}	

	data[k] = data[j];
	boundaries[k] = boundaries[j];
      }
    }
  }

  /* If the original mesh was given in polar coordinates make the transformation into cartesian ones */
  for(k=0;k<nomeshes;k++) {
    if(eg.polar || data[k].coordsystem == COORD_POLAR) {
      if(!eg.polar) eg.polarradius = grids[k].polarradius;
      PolarCoordinates(&data[k],eg.polarradius,info);
    }
  }

  /* If the original mesh was given in cylindrical coordinates make the transformation into cartesian ones */
  for(k=0;k<nomeshes;k++) {
    if(eg.cylinder || data[k].coordsystem == COORD_CYL) {
      CylinderCoordinates(&data[k],info);
    }
  }

  if(1) for(k=0;k<nomeshes;k++) 
    RotateTranslateScale(&data[k],&eg,info);


  /* Rotate may apply to 2d and 3d geometries as well */
  for(k=0;k<nomeshes;k++) 
    if(eg.rotatecurve) 
      CylindricalCoordinateCurve(&data[k],eg.curvezet,eg.curverad,eg.curveangle);

  /* Unite meshes if there are several of them */
  if(eg.unitemeshes) {
    for(k=1;k<nomeshes;k++)
      UniteMeshes(&data[0],&data[k],boundaries[0],boundaries[k],info);
    nomeshes = nogrids = 1;
  }
  
  if(eg.clone[0] || eg.clone[1] || eg.clone[2]) {
    for(k=0;k<nomeshes;k++) {
      CloneMeshes(&data[k],boundaries[k],eg.clone,eg.clonesize,FALSE,info);
      mergeeps = fabs(eg.clonesize[0]+eg.clonesize[1]+eg.clonesize[2]) * 1.0e-8;
      MergeElements(&data[k],boundaries[k],eg.order,eg.corder,mergeeps,TRUE,TRUE);
    }
  }

  if(eg.mirror[0] || eg.mirror[1] || eg.mirror[2]) {
    for(k=0;k<nomeshes;k++) {
      MirrorMeshes(&data[k],boundaries[k],eg.mirror,FALSE,eg.clonesize,eg.mirrorbc,info);
      mergeeps = fabs(eg.clonesize[0]+eg.clonesize[1]+eg.clonesize[2]) * 1.0e-8;
      MergeElements(&data[k],boundaries[k],eg.order,eg.corder,mergeeps,FALSE,TRUE);
    }
  }

  /* Naming convection for the case of several meshes */
  if(nomeshes > 1) {
    strcpy(prefix,eg.filesout[0]);
    for(k=0;k<nomeshes;k++)
      sprintf(eg.filesout[k],"%s%d",prefix,k+1);
  }

  for(k=0;k<nomeshes;k++) {
    if(nogrids && grids[k].reduceordermatmax) {
      eg.reduce = TRUE;
      eg.reducemat1 = grids[k].reduceordermatmin;
      eg.reducemat2 = grids[k].reduceordermatmax;
    }
    if(eg.reduce) 
      ReduceElementOrder(&data[k],eg.reducemat1,eg.reducemat2);
  }

  for(k=0;k<nomeshes;k++) 
    if(eg.increase) IncreaseElementOrder(&data[k],TRUE);
 
  for(k=0;k<nomeshes;k++) {
    if(eg.merge) 
      MergeElements(&data[k],boundaries[k],eg.order,eg.corder,eg.cmerge,FALSE,TRUE);
    else if(eg.order == 3) 
#if PARTMETIS 
      ReorderElementsMetis(&data[k],TRUE);
#else
      printf("Cannot order nodes by Metis as it is not even compiled!\n");
#endif    
    else if(eg.order) 
      ReorderElements(&data[k],boundaries[k],eg.order,eg.corder,TRUE);
    
    if(eg.isoparam) 
      IsoparametricElements(&data[k],boundaries[k],TRUE,info);
  }  
ShHealOper_FillHoles::ShHealOper_FillHoles (const TopoDS_Shape& theShape)
{
  
  Init(theShape);
  InitParameters();
}
Beispiel #25
0
int main(int argc, char *argv[]){



# ifdef UNIX
 static char state[256];
 initstate(1997,state,256);
# else
  Exit_wait(1);
# endif

 Set_comment_char(';');

 StartTime();
 char *cfgfile="Params.dta";
 if(argc>1)cfgfile=argv[1];

 int no_remove=1;
 if(argc>2)if(strstr(argv[2],"new"))no_remove=0;

 Open_param_file(cfgfile);
 int nions,i;


 Read_param("Number of ions: %d",&nions);
 Read_param("Ionisation degree: %d",&i);
 ion_charge=i;

 double imass=1.;
 Set_stop(0);
 if(Read_param("Ion mass: %lf",&imass)){
   printf("Non-symmetric plasma specified!\n");
   non_symm=1;
 }

 char tmpstr[256];

 int sep_cm=0;
 if(Read_param("Center-of-mass for components: %s",tmpstr)){
   if(strstr(tmpstr,"separate")){
     printf("Plasma with separated center of masses specified!\n");
     sep_cm=1;
   }
 }



 Plasma *TheGas;  // allocation of the Gas
 double bdens, bTv;
 int bq;
 int bunch=Read_param("Bunch propagation: %lf, %lf, %d",&bdens,&bTv,&bq);
 if(bunch>0){
   printf("Bunch in plasma specified!\n");
   if(bunch!=3){
     msg_error("Invalid bunch specification!\n");
     exit(1);
   }
   bunch=1;
   bTv=sqrt(3*nions*i*bTv); // converting temperature to velocity
   TheGas=(Plasma *)new PlasmaBunch(bdens,bTv,bq,nions,i,imass);
 }
 else{
   TheGas=new Plasma(nions,i,imass);
   bunch=0;
 }
 Plasma &Gas=*TheGas;

 Gas.non_symm=non_symm;
 Gas.one_center=1-sep_cm;

 char dataname[50];
 Read_param("Data name: %s",dataname);
 strncpy(Gas.dataname,dataname,50);

 char ofile[256], pfile[256]="poten.dat";


 strcat(strcpy(pfile,dataname),".pot");

 Read_param("Output file: %s",ofile);
 if(strstr(ofile,"default")){
   strcpy(ofile,dataname);
   strcat(ofile,".eq");
 }

 Read_param("Log file: %s",logfile);
 if(strstr(logfile,"default")){
   strcpy(logfile,dataname);
   strcat(logfile,".log");
 }



 Parameter *p;
 int np=InitParameters(&p);


 double T,Gamma;

 potspec_t reader;
 reader.read_spec(cfgfile);
 Gas.potential=reader.potential;
 strncpy(Gas.charpot,reader.charpot,50);


 /*
 Read_param("Potential: %s",tmpstr);
 strncpy(Gas.charpot,tmpstr,50);
 if(strstr(tmpstr,"Kelbg"))Gas.potential=PotentialKELBG;
 else if(strstr(tmpstr,"Lennard-Johnes"))Gas.potential=PotentialJONES;
 else if(strstr(tmpstr,"Deutsch"))Gas.potential=PotentialDEUTSCH;
 else if(strstr(tmpstr,"Erf"))Gas.potential=PotentialERF;
 else if(strstr(tmpstr,"Cutoff")){
  if(!strcmp(tmpstr,"Cutoff1")){
    Gas.potential=PotentialCUT1;
  }
  else{
    Gas.potential=PotentialCUT;
    Read_param("Cutoff value*: %lf",&E_cut);
  }
 }
 else if(strstr(tmpstr,"ln")){
  Gas.potential=PotentialLN;
  Read_param("Cutoff value*: %lf",&E_cut);
 }
 else if(strstr(tmpstr,"table")){
  Gas.potential=PotentialTAB;
  Read_param("Potential table file: %s",tmpstr);
  Close_param_file();
  ReadPotential(tmpstr);
  Open_param_file(cfgfile);
 }
 else serror("Unknown potential type specified!\n");


 Read_param("Pauli part: %s",tmpstr);
 if(strstr(tmpstr,"n"))Pauli_part=0;


 double Lambda, Lambda_set;
 Read_param("R0: %s",tmpstr);
 if(strstr(tmpstr,"default"))Lambda_set=0.;
 else Lambda_set=atof(tmpstr);

 double Clam_ep=1.,Clam_ee=1;
 Read_param("e-e R0 coefficient: %lf",&Clam_ee);
 Read_param("e-p R0 coefficient: %lf",&Clam_ep);
 */

 int ask=0;
 Read_param("Dialog: %s",tmpstr);
 if(strstr(tmpstr,"y"))ask=1;

 auto_rf=0;
 Gf=10.;
 Read_param("Random force strength: %s",tmpstr);
 if(strstr(tmpstr,"auto"))auto_rf=1;
 else if(strstr(tmpstr,"fluct"))auto_rf=2;
 if(!sscanf(tmpstr,"%lf",&Gf) && auto_rf==0)serror("Can't read Random force strength\n");



 Read_param("Scale velocities: %s",tmpstr);
 if(strstr(tmpstr,"y"))scale_vel=1;

 Read_param("Delta: %lf",&delta);

 Read_param("Trajectory write interval: %ld",&wr_int);
 if(wr_int<=0)wr_int=-1;

 int new_rec=0;
 long wr_ions=0, wr_enseq=-1;
 Set_stop(0);
 if(Read_param("Ions write interval: %ld",&wr_ions)){
   new_rec=1;
   if(!Read_param("Electrons write sequence: %ld",&wr_enseq))wr_enseq=-1;
 }
 Set_stop(1);


 Read_param("Steps to check equillibrium: %ld",&chk_nsteps);
 Read_param("Steps with random force: %ld",&rf_nsteps);
 Read_param("Check steps with random force: %ld",&tst_nsteps);
 Read_param("Steps in equillibrium: %ld",&eq_nsteps);
 Read_param("Time step in equillibrium: %lf",&eq_dt);

 Read_param("Time step for random force: %lf",&rf_dt0);


 char trfile[256]="trajectory";

 int wr_tr=0;
 Set_stop(0);

 /*int pot_corr=0;
 if(Read_param("Potential correction: %s",tmpstr)){
   if(strstr(tmpstr,"y")){
     pot_corr=1;
     strcat(Gas.charpot," corr.");
   }                                       
 }*/


 if(Read_param("Total energy stability: %lf",&stab_acc))e_stab=1;


 if(Read_param("Positive cutoff: %lf",&E_negcut))neg_cut=1;
 else neg_cut=0;

 if(!Read_param("Random generator *:>",tmpstr))strcpy(tmpstr,"3");
 cList rndlist(tmpstr);

 int nrepeats=1;
 if(!Read_param("Repeats: %d",&nrepeats))nrepeats=1;


 char mdistrfile[256]="r-r.distrib";
 double rr_r0=0., rr_r1=-1.;
 if(Read_param("Write r-r distribution: %s",tmpstr)){
   if(strstr(tmpstr,"y")){
     write_distr=1;
     if(!Read_param("r-r file: %s",mdistrfile)||strstr(mdistrfile,"default")){
       strcpy(mdistrfile,"%s%d.rr");
     }
     if(Read_param("r-r range: %lf, %lf",&rr_r0,&rr_r1)!=2){
       rr_r0=0.;
       rr_r1=-1.;
     }
   }
 }


 if(Read_param("Soft step: %s",tmpstr)){
  if(strstr(tmpstr,"n"))soft_step=0;
 }

 if(Read_param("Soft random force: %s",tmpstr)){
  if(strstr(tmpstr,"y")){
    rf_sw_off=1;
    Set_stop(1);
    Read_param("Switch off steps: %ld",&sw_nsteps);
    Set_stop(0);
  }
  else rf_sw_off=0;
 }

 if(Read_param("Relative step: %s",tmpstr)){
  if(strstr(tmpstr,"y"))rel_step=1;
 }


 if(Read_param("Animation : %s",&tmpstr)){
   if(strstr(tmpstr,"y")){
      if(!Read_param("Film directory: %s",filmdir)||strstr(filmdir,"default")){
       strcpy(filmdir,"film/");
      }
   }
 }

 in_cs=-1.;
 Read_param("Initial cluster size: %lf",&in_cs);

 int restart=0,load_fried=0;
 int new_input=0;
 char inptrj[256];

 if(Read_param("Restart: %s",tmpstr)){
  if(strstr(tmpstr,"y")){
    restart=1;
    if(Read_param("Load Friedemann: %s",tmpstr)){
      if(strstr(tmpstr,"y"))load_fried=1;
    }
    if(Read_param("Input from: %s",inptrj))new_input=1;
  }

 }

 long wtype=0;
 if(Read_param("Trajectory file: %s",&trfile)){
  if(strstr(trfile,"default"))strcpy(trfile,"%s%d.r");



  Set_stop(1);
  wr_tr=1;

  Read_param("In output:>",tmpstr);
  if(strstr(tmpstr,"vel"))wtype|=VEL;
  if(strstr(tmpstr,"coord"))wtype|=COORD;
  if(strstr(tmpstr,"flow"))wtype|=FLOW;
  Set_stop(0);

 }
 else printf("Warning: no trajectory file\n");

 int mc_one=0;
 int mc_diff=0;
 int auto_adjust=1;
 double mc_inistep;

 int no_equilibr=0;
 Set_stop(1);
 if(Read_param("Equilibration procedure: %s",tmpstr)){
   if(strstr(tmpstr,"monte-carlo")){
     Set_stop(1);
     mc_equil=1;
     Read_param("One particle MC-step: %s",tmpstr);
     if(strstr(tmpstr,"y")){
       mc_one=1;
       // rf_dt0/=Gas.n;
     }
     Read_paramn(2,"MC step mode and value: %s %lf",tmpstr, &mc_inistep);
     if(strstr(tmpstr,"auto"))auto_adjust=1;
     else if(strstr(tmpstr,"stable"))auto_adjust=0;
     else serror("Unknown MC step mode.\n");
     Set_stop(0);
     mc_diff=0;
     if(Read_param("MC different temperatures: %s",tmpstr)){
       if(strstr(tmpstr,"y")){
	 if(mc_one)serror("Can use different MC temperatures\n"
			  "only in MC one-particle mode!\n");
	 mc_diff=1;
       }
     }
   }
   else{
     mc_equil=0;
     if(strstr(tmpstr,"off"))no_equilibr=1;
     else if(!strstr(tmpstr,"random-force")){
       serror("Unknown equilibration procedure: %s\n",tmpstr);
     }
   }
 }

 

 Set_stop(0);
 mc_calc=0;
 if(Read_param("Equilibrium calculation: %s",tmpstr)){
   if(strstr(tmpstr,"monte-carlo")){
     Set_stop(1);
     mc_calc=1;
     Read_param("One particle MC-step: %s",tmpstr);
     if(strstr(tmpstr,"y")){
       mc_one=1;
       // rf_dt0/=Gas.n;
     }
     Read_paramn(2,"MC step mode and value: %s %lf",tmpstr, &mc_inistep);
     if(strstr(tmpstr,"auto"))auto_adjust=1;
     else if(strstr(tmpstr,"stable"))auto_adjust=0;
     else serror("Unknown MC step mode.\n");
     Set_stop(0);
     mc_diff=0;
     if(Read_param("MC different temperatures: %s",tmpstr)){
       if(strstr(tmpstr,"y")){
	 if(mc_one)serror("Can use different MC temperatures\n"
			  "only in MC one-particle mode!\n");
	 mc_diff=1;
       }
     }
   }
 }

//# ifdef UNIX

 char out_dirs[250]="./",out_dirl[250]="./";
 if(Read_param("Data output directory: %s",out_dirs)){
   if(out_dirs[strlen(out_dirs)-1]!='/')strcat(out_dirs,"/");
   sprintf(tmpstr,out_dirs,dataname);
   strcpy(out_dirs,tmpstr);
# ifdef UNIX
   if(mkdir(out_dirs,S_IRWXU|S_IRGRP|S_IROTH)){
     if(errno!=EEXIST)serror("Can not create directory: %s.\n%s\n",
			     out_dirs,strerror(errno));
   }
   sprintf(tmpstr,"cp %s %s%s.cfg",cfgfile,out_dirs,dataname);
   //strcat(strcat(tmpstr,dataname),".cfg");
   if(system(tmpstr)==-1)
     printf("\nExec: %s\n",strerror(errno));
# else
   if(_mkdir(out_dirs)){
     if(errno!=EEXIST)serror("Can not create directory: %s.\n%s\n",
			     out_dirs,strerror(errno));
   }
   char cfgfilef[_MAX_PATH], out_dirsf[_MAX_PATH];
   _fullpath(cfgfilef, cfgfile, _MAX_PATH);
   _fullpath(out_dirsf, out_dirs, _MAX_PATH);
   sprintf(tmpstr,"copy %s %s%s.cfg",cfgfilef,out_dirsf,dataname);
   //strcat(strcat(tmpstr,dataname),".cfg");
   if(system(tmpstr)==-1)
     printf("\nExec: %s\n",strerror(errno));
# endif

   


   strcpy(ofile,strcat(strcpy(tmpstr,out_dirs),ofile));
   strcpy(mdistrfile,strcat(strcpy(tmpstr,out_dirs),mdistrfile));
   strcpy(sfile,strcat(strcpy(tmpstr,out_dirs),sfile));
   strcpy(pfile,strcat(strcpy(tmpstr,out_dirs),pfile));
   if(wr_film){
     strcpy(filmdir,strcat(strcpy(tmpstr,out_dirs),ofile));
# ifdef UNIX
     if(mkdir(filmdir,S_IRWXU|S_IRGRP|S_IROTH)){
# else
     if(_mkdir(filmdir)){
# endif
       if(errno!=EEXIST)serror("Can not create directory: %s.\n%s\n",
			       filmdir,strerror(errno) );
     }
     strcat(filmdir,dataname);
   }
 }
 if(Read_param("Process output directory: %s",out_dirl)){
   if(out_dirl[strlen(out_dirl)]!='/')strcat(out_dirl,"/");
   sprintf(tmpstr,out_dirl,dataname);
   strcpy(out_dirl,tmpstr);


# ifdef UNIX
   if(mkdir(out_dirl,S_IRWXU|S_IRGRP|S_IROTH)){
# else
   if(_mkdir(out_dirl)){
# endif 
     if(errno!=EEXIST)serror("Can not create directory: %s.\n%s\n",
			     out_dirl,strerror(errno));
   }


   strcpy(logfile,strcat(strcpy(tmpstr,out_dirl),logfile));
   strcpy(trfile,strcat(strcpy(tmpstr,out_dirl),trfile));
 }

//# endif  // UNIX

 int spwn_trj=0;

 if(Read_param("Spawn trajectories: %s",tmpstr)){
   if(strstr(tmpstr,"y")){
    spwn_trj=1;
    //Read_paramn(1,"Spawn frame: %d",&spwn_frame);
    no_test=1; // no RF test for equilibrartion
   }
 }

 Gas.stable_ions=0;
 if(Read_param("Stable ions: %s",tmpstr)){
   if(strstr(tmpstr,"y")){
    Gas.stable_ions=1;

   }
 }

 int repc_i=0;
 if(!Read_param("Repeat counter start: %d",&repc_i))repc_i=0;

 int irescale=0;
 if(Read_param("Ion velocity rescale: %s",tmpstr)){
  if(strstr(tmpstr,"y"))irescale=1;
  if(strstr(tmpstr,"reset"))irescale=2;
 }

 /*
 int limrescale=0;
 if(Read_param("Rescale on electron temperature reached: %lf  %ld",&limTe,&limstpe)==2){
  limrescale=1;
  limspec=0x2;
  limrescale_switch(0);
 } */

 int limrescale=0;
 int inc_mes=0;

 if(Read_param("Incremental measurement (T0,dT,mes_steps): %lf,%lf,%ld",&incT0,&incdT,&incStp)==3){
   inc_mes=1;
   fixT=incT0;
   limstpe=1;
   limstpi=1;
 }



 Set_stop(1);



 Gas.ini_Te=Gas.ini_Ti=1.;  // by default equal temperatures
 Read_param("Initial velocity distribution: %s",tmpstr);
 if(strstr(tmpstr,"maxwell"))in_distr=MAXWELL;
 else if(strstr(tmpstr,"max_polak"))in_distr=MAXWELL_P;
 else if(strstr(tmpstr,"zero")){
   if(mc_equil){
     in_distr=MAXWELL;
     printf("Warning: setting 'maxwell' initial vel. distribution for MC!\n");
   }
   else in_distr=ZEROVEL;
 }
 else if(strstr(tmpstr,"separate")){
   in_distr=SEPARATE;
   int &ndistr=Gas.idistr;
   int nr;
   char relstr[200];
   for(i=0;i<2;i++){
    if(i==0)nr=  Read_param("Electron velocity distribution: %s  %lf  %s",tmpstr,&Gas.ini_Te,relstr);
    else{
     nr= Read_param("Ion velocity distribution: %s  %lf %s",tmpstr,&Gas.ini_Ti,relstr);
     Gas.edistr=ndistr;
    }
    if(nr<2){
      serror("Can't read velocity distribution parameters!\n");
    }
    if(nr>=2){
      if(strstr(relstr,"abs")){
        if(i==0)Gas.rel_Te=0;
        else Gas.rel_Ti=0;
      }
    }

    if(strstr(tmpstr,"maxwell"))ndistr=MAXWELL;
    else if(strstr(tmpstr,"max_polak"))ndistr=MAXWELL_P;
    else if(strstr(tmpstr,"zero"))ndistr=ZEROVEL;
    else {
     printf("Warning: unknown distribution '%s', setting to 'zero'\n",tmpstr);
     ndistr=ZEROVEL;
    }
   }
 }
 else{
   printf("Warning: unknown distribution '%s', setting to 'zero'\n",tmpstr);
   in_distr=ZEROVEL;
 }

 

 Close_param_file();


 Statistics sT(&Gas.T),sEcoul(&Gas.Ecoul),sEpotent(&Gas.Epotent),sQuant(&Gas.Quant), sEtot(&Gas.Etot);
 Statistics sTi(&Gas.Ti),sTe(&Gas.Te);
 const int nstat=7;
 Statistics *stats[nstat]={&sT,&sEcoul,&sEpotent,&sQuant,&sEtot,&sTi,&sTe};

 SetTableform(GNU);
 if(no_remove){
   no_remove=CheckData(sfile,ofile,dataname,np,p,ask);
 }

 if(restart && !wr_tr && !new_input)serror("No trajectory file specified, cannot restart.\n");
 if(restart && new_input && wr_tr)
   if(!strcmp(trfile,inptrj))
     serror("Equal names for input and output trj-files.\n");


 FILE *f1;
 if(!no_remove || no_remove==2){
  if(!no_remove)f1=Err_fopen(ofile,"wt");
  else f1=Err_fopen(ofile,"at");
  BeginFrame(f1,dataname,np,p);
  fprintf(f1,"%9.9s %9.9s %9.9s %9.9s %9.9s %9.9s %9.9s %9.9s\n",
             "T","Ecoul","Epotent","Equant","dT","dEcoul","dEpotent","dEquant");
  fclose(f1);
 }

 double t=0;

 f1=fopen(logfile,"rt");
 if(f1){
   if(!restart && !no_remove){
     fclose(f1);
     remove(logfile);
   }
   else {// reading 'log' time
     fseek(f1,0,SEEK_END);
     long pos=ftell(f1)-4;
     do{
       fseek(f1,pos,SEEK_SET);
       if(fgetc(f1)=='\n'){
	        fscanf(f1,"%lf",&t);
         //printf("new t: %f\n",t);
	        break;
       }
       pos--;
     }while(pos>=0);
     fclose(f1);
   }
 }


 int ccount=CurrentCount(np,p);
 WriteStatus(!ccount,sfile,dataname,np,p);



 do{

   //Gamma=get_pc(p[0]);
   //T=get_pc(p[1]);



  char ctrfile[256];
  sprintf(ctrfile,trfile,dataname,ccount);
  char ss[100];
  sprintf(ss,"%s%d",dataname,ccount);
  sprintf(distrfile,mdistrfile,dataname,ccount);

  // StatusLine(str,np,p);
  //show_status(440,str);

  long i,n,m,nf=0;

  //Gas.adjustTG(T,Gamma);

  AdjustGas(Gas,p,np);
  T=Gas.par_T;
  Gamma=Gas.par_Gamma;

  double me=0.9109534e-30;
  double qe=1.602e-19;
  double Kb=1.38e-23;
  double unit_t=qe*qe/(4*M_PI*8.854e-12)*sqrt(me);


  // overcoming g++ bug with -O3
  double jojo=Kb*T*1.e4;
  //printf("c2: %e\n",jojo);
  jojo=jojo*jojo*jojo;
  jojo=sqrt(jojo);
  //printf("c21: %e\n",jojo);
  unit_t/=jojo;
  //printf("c3:\n");

  double unit_h=Kb*T*1e4*unit_t;
  double h_qwer=1.0545887e-34;

  reader.calc_lambda(T,Gas.ini_Te,Gas.ini_Ti,Gas.mass);

  /*
  if(!non_symm){
   if(Lambda_set!=0.0){
     Lambda=Lambda_set/unit_l;
     equal_lambda=0;
   }
   else {
     Lambda=0.179*sqrt(T);
     equal_lambda=1;
   }
   Lambda_pauli=0.179*sqrt(T);
   //non_symm=0;
   Lambda_ee=Lambda_pp=Lambda*Clam_ee;
   if(fabs(Clam_ee-1.)>1e-5)equal_lambda=0;
   Lambda_ep=Lambda*Clam_ep;
  }
  else{
   if(Lambda_set!=0.0){
     serror("Can not setup lambda for nonsymmetric plasma.\n");
     //Lambda=Lambda_set/unit_l;
     //Lambda_ep=Lambda*Clam_ep;
     //Lambda_ee=Lambda*Clam_ee;
     //equal_lambda=0;
   }
   else{
     if(strstr(Gas.charpot,"Deutsch")){
       printf("Setting lambda values for Deutsch potential !!!\n");
       Lambda_pauli=h_qwer/(unit_h);
       Lambda=Lambda_pauli/sqrt(2*M_PI);
       double m_ee=0.5, m_pp=0.5*Gas.mass, m_ep=Gas.mass/(1.+Gas.mass);

       Lambda_ee=Lambda/sqrt(m_ee);
       Lambda_pp=Lambda/sqrt(m_pp);
       Lambda_ep=Lambda/sqrt(m_ep);
     }
     else { //if(strstr(Gas.charpot,"Kelbg")){
       printf("Setting lambda values for Kelbg potential !!!\n");

       Lambda_pauli=h_qwer/(unit_h);
       Lambda=Lambda_pauli;
       double m_ee=0.5, m_pp=0.5*Gas.mass, m_ep=Gas.mass/(1.+Gas.mass);
       double t_ep=Gas.ini_Te;
       double t_pp=Gas.ini_Ti;
       double t_ee=Gas.ini_Te;

       Lambda_ee=Lambda/sqrt(2*m_ee*t_ee);
       Lambda_pp=Lambda/sqrt(2*m_pp*t_pp);
       Lambda_ep=Lambda/sqrt(2*m_ep*t_ep);
     }

   }
  } */


  if(rel_step)rf_dtcoeff=1./Gas.Wpe;

  double kk=(1.602e-19)*(1.602e-19)/(4*M_PI*1.38e-23*T*1e4*8.854e-12);



  printf("Simulation parameters:\n");
  printf("Gamma =%f\n"
	 "L=%f=%12e m\n"
	 "lambda=%f=%12e m\n"
	 "1/Wp=%f\n"
	 "Rd=%f\n",Gamma,Gas.L, Gas.L*kk,reader.Lambda,reader.Lambda*kk,1./Gas.Wpe,RDebye);
  printf("Density = %1.2e cm^(-3)\n"
	 "T= %f K\n",Gas.par_density*1e19,T*1e4);

  printf("Time step relations:\n");
  printf("dtrf*Wp= %f, dteq*Wp= %f\n", (rel_step ? rf_dt0 : rf_dt0*Gas.Wpe),
	 (rel_step ? eq_dt : eq_dt*Gas.Wpe));


  double t_inter=RDebye/sqrt(2*getEmax(Gas));


  printf("dtrf/tint= %f, dteq/tint= %f\n", rf_dt0*rf_dtcoeff/t_inter,
	 eq_dt*rf_dtcoeff/t_inter);


  reader.calc_correction(Gas.par_T);
  reader.write_pot(pfile, Gas.L);

  /*
  //if(ccount==1)t/=Gas.Wpe;
  if(pot_corr){
    //Correction(IONION,Gas.potential,Gas.par_T);
    Correction(IONELC,Gas.potential,Gas.par_T);
    Correction(ELCELC,Gas.potential,Gas.par_T);
  }*/

  Statistics rs[nstat];



  int repi=0;
  int repc=repc_i;

  do{ //through nrepeats

    printf("\nStarting calculation #%d...\n",repc);
    flm_count=0;

    if(repc>0){
      repi++;
      sprintf(tmpstr,"%02d",repc);
      if(repi>1){
       distrfile[strlen(distrfile)-2]=0;
       ctrfile[strlen(ctrfile)-2]=0;
      }
      strcat(distrfile,tmpstr);
      strcat(ctrfile,tmpstr);
    }


    if(write_distr){
      DRRee.init(rr_r0,(rr_r1>0 ? rr_r1 : Gas.L/2),400);
      DRRep.init(rr_r0,(rr_r1>0 ? rr_r1 : Gas.L/2),400);
      if(non_symm)DRRpp.init(0,(rr_r1>0 ? rr_r1 : Gas.L/2),400);
    }

    long ftype=wtype;


    if(restart){
      printf("restarting...\n");
      if((mc_equil && spwn_trj) || mc_calc){
        mc_equil=-1;
        MC = new mc_simm(Gas,mc_inistep*Gas.L /*Gas.L/Gas.n*/,0.5,
			 mc_one,mc_diff);
        if(!MC)serror("Cannot allocate MCsimm\n");
        MC->auto_adjust=auto_adjust;
      }
      else mc_equil=0;

      if(!new_input)strcpy(inptrj,ctrfile);

      if(load_fried){
        LoadFriedemann(inptrj,Gas);
        Gas.dt=eq_dt;
        if(rel_step)Gas.dt/=Gas.Wpe;

        if(eq_nsteps<wr_int)eq_nsteps=wr_int;
	m=wr_int;
	n=eq_nsteps/m;
	Gas.ext_force=void_force1;
	wr_tr=0;
	ftype=0;
      }
      else{
	Gas.dt=(rel_step ? eq_dt/Gas.Wpe : eq_dt);
	Trajectory.Check(inptrj,wtype,Gas,wr_int,wr_ions,wr_enseq,new_input);
	if(Trajectory.wtype !=0 && !new_input){
	  Gas.dt=Trajectory.AdjustInterval(Gas.dt);
	}

	long stp;
	if(!new_input){
	  stp=Trajectory.ReloadGas(Gas,1);
	  t=stp*Trajectory.file_dt();
	  nf=(long)(t/Gas.dt/wr_int+0.01);
	}
	else{
	  stp=Trajectory.ReloadGas(Gas,0);
	  t=0;
	  nf=0;
	}
	printf("t= %f, nf= %ld,  %f\n",t,nf,(t/Gas.dt/wr_int));

	//serror("Restart is not yet implemented !\n");
        Gas.ext_force=void_force1;
      }
      //restart=0;
    }
    else{
      rand_init=rndlist.step();
      if(rand_init<0){
        rndlist.rewind();
        rand_init=rndlist.step();
      }

      strcat(distrfile,"e");


      if((mc_equil && (!spwn_trj || (repc==repc_i && spwn_trj))) || mc_calc){
        mc_equil=1;
        MC = new mc_simm(Gas,mc_inistep*Gas.L /*Gas.L/Gas.n*/,0.5,
			 mc_one,mc_diff);
        if(!MC)serror("Cannot allocate MCsimm\n");
        MC->auto_adjust=auto_adjust;
      }

      if(!no_equilibr){
        if(!spwn_trj || (spwn_trj && repc==repc_i)){
          limrescale_switch(0);
          Equillibrium(t,Gas,stats,nstat);
          limrescale_switch(limrescale);
        }
      }
      else{
        Gas.r0=0.05;
        Gas.init_config(in_cs,in_distr);
      }

      distrfile[strlen(distrfile)-1]=0; // deleting 'e'

      if(mc_equil){
       if(spwn_trj){
        Gas.init_vel(in_distr);
       }
       else if(!mc_calc){
	 delete MC;
	 mc_equil=-1;
       }
       else
         mc_equil=1;
      }

      Gas.dt=eq_dt;
      if(rel_step)Gas.dt/=Gas.Wpe;

    }
    if(irescale){
     if(irescale==1)Gas.ivel_scale(1.);
     else Gas.init_vel(in_distr);
    }

    if(eq_nsteps<wr_int)eq_nsteps=wr_int;
    if(wr_int>0){
      n=eq_nsteps/wr_int;
      m=wr_int;
    }
    else if(eq_nsteps>=500){
      n=eq_nsteps/500;
      m=500;
    }
    else{
      n=1;
      m=eq_nsteps;
    }

    if(wr_tr && (!restart || new_input || (restart && ftype==0))){

      //WriteHeader(ctrfile,wtype,Gas,Gamma,T, ss,m);

      // initializing PlasmaRec
      Trajectory.Clear();
      Trajectory.Init(ctrfile,wtype,Gas,wr_int,wr_ions,wr_enseq);
    }
    if(wr_tr && (restart && ftype==0)){
      //WriteStep(ctrfile,wtype,Gas,0);
    }

    Statistics statsl[nstat];

    Trajectory.valid=wr_tr;
    // new cycle

    if(bunch){
      PlasmaBunch *pb=(PlasmaBunch *)&Gas;
      pb->start_bunch();
    }
    for(i=nf;i<n;i++){
      double term_c=1.;
      if(Gas.stable_ions)term_c=(double)Gas.ne/Gas.n;
      printf("Equilibrium calculation: %f%% complete, T= %f Et=%f\n",(i+1)*100./n,Gas.T,Gas.T*3/2*term_c+Gas.Epotent/Gas.n);

      if(StopStatus(sfile,3)){
       	StopStatus(sfile,-1);
        serror("Program interrupted!\n");
      }

      if(mc_equil && spwn_trj){
        mc_equil=1;
        double ratio=MC->get_ratio();
        if(ratio<1e-10)printf("Estimated randomization steps: infinity\n");
        else printf("Estimated randomization steps: %d\n",(int)(Gas.n*Gas.L/MC->dc[1]/ratio));
      }
      MoveIt(t,m,m,Gas,stats,statsl,nstat);


      //if(wr_tr)WriteStep(ctrfile,wtype,Gas,i);
      if(write_distr)WriteDRR(distrfile);
      if(wr_film)WriteFilm(filmdir,Gas);
    }
    if(bunch){
      PlasmaBunch *pb=(PlasmaBunch *)&Gas;
      pb->stop_bunch();
    }

    if(write_distr)WriteDRR(distrfile);

    for(i=0;i<nstat;i++)rs[i]+=*(stats[i]);
    repc++;

    if(new_input)restart=0;
  }while(repc<nrepeats);

  if(spwn_trj)delete MC;

  f1=Err_fopen(ofile,"at");
  MiddleFrame(f1,np,p);
  int gn=Gas.n;
  //fprintf(f1,"%9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f\n",
  //       sT.av()*T,sEcoul.av()/gn,sEpotent.av()/gn,sQuant.av()/gn,
  //       sT.dev()*T,sEcoul.dev()/gn,sEpotent.dev()/gn,sQuant.dev()/gn);

  fprintf(f1,"%9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f\n",
         rs[0].av()*T,rs[1].av()/gn,rs[2].av()/gn,rs[3].av()/gn,
         rs[0].dev()*T,rs[1].dev()/gn,rs[2].dev()/gn,rs[3].dev()/gn);

  fclose(f1);

  ccount=CycleCount(np,p);
  WriteStatus(!ccount,sfile,dataname,np,p);

  restart=0;
  repc=0;
 }while(ccount);
 return 0;
}
static int NewWiFiWinProc(HWND  hWnd, int message, WPARAM wParam, LPARAM lParam)
{
	HDC hdc;
	int id,nc;
	static char keyupFlag=0;

	switch (message)
	{
		case MSG_CREATE:
			wifidhcpflag = gOptions.wifidhcpfunon;
			InitWifiWindow(hWnd);		//add controls
			InitParameters();

			curFocusWnd =0;
			SetFocusChild(WifiWnd[curFocusWnd]);
			UpdateWindow(hWnd,TRUE);
			break;

		case MSG_ERASEBKGND:
			{
				HDC hdc = (HDC)wParam;
				const RECT* clip = (const RECT*)lParam;
				BOOL fGetDC = FALSE;
				RECT rcTemp;
				if(hdc == 0) {
					hdc = GetClientDC(hWnd);
					fGetDC = TRUE;
				}

				if(clip) {
					rcTemp = *clip;
					ScreenToClient(hWnd, &rcTemp.left, &rcTemp.top);
					ScreenToClient(hWnd,&rcTemp.right, &rcTemp.bottom);
					IncludeClipRect(hdc, &rcTemp);
				}

				FillBoxWithBitmap (hdc, 0, 0, gOptions.LCDWidth, 0, &wifibkg);
				if(fGetDC) {
					ReleaseDC (hdc);
				}
				return 0;
			}

		case MSG_PAINT:
			hdc=BeginPaint(hWnd);	
			EndPaint(hWnd,hdc);
			return 0;

		case MSG_KEYUP:
			if(3 == gOptions.TFTKeyLayout){
				keyupFlag=1;
			}
			break;
		case MSG_KEYDOWN:
			SetMenuTimeOut(time(NULL));
			if (3 == gOptions.TFTKeyLayout) {
				if (1==keyupFlag) {
					keyupFlag=0;
				} else {
					break;
				}
			}
			if (gOptions.KeyPadBeep){
				ExKeyBeep();
			}

			if ((LOWORD(wParam)==SCANCODE_ESCAPE)){
				PostMessage(hWnd, MSG_COMMAND, WIFI_EXIT, 0);
			} else 	if (LOWORD(wParam)==SCANCODE_CURSORBLOCKDOWN) {
				char tmpssid[128];
				if (curFocusWnd==0) {
					GetWindowText(WifiWnd[0], tmpssid, sizeof(tmpssid));
					if(tmpssid && strlen(tmpssid)>0) {
						if(hIMEWnd!=HWND_INVALID){
							SendMessage(hIMEWnd,MSG_CLOSE,0,0L);
							hIMEWnd=HWND_INVALID;
						}
						curFocusWnd++;
					}
				} else if (curFocusWnd==1) {
					if(hIMEWnd!=HWND_INVALID){
						SendMessage(hIMEWnd,MSG_CLOSE,0,0L);
						hIMEWnd=HWND_INVALID;
					}
					curFocusWnd++;
				} else if(++curFocusWnd>16) {
					curFocusWnd=0;
				}

				if (wifidhcpflag == 1 && curFocusWnd == 3) {
					curFocusWnd=15;
				}
				if (curFocusWnd == 4 || curFocusWnd == 5 ||curFocusWnd == 6 ){
					curFocusWnd = 7;
				}
				if (curFocusWnd == 8 || curFocusWnd == 9 || curFocusWnd == 10){
					curFocusWnd = 11;
				}
				if (curFocusWnd == 12 || curFocusWnd == 13 || curFocusWnd == 14){
					curFocusWnd = 15;
				}
				SetFocusChild(WifiWnd[curFocusWnd]);		
				return 0;
			} else if (LOWORD(wParam)==SCANCODE_CURSORBLOCKUP){
				char tmpssid[128];
				if(curFocusWnd==0){
					GetWindowText(WifiWnd[0], tmpssid, sizeof(tmpssid));
					if(tmpssid && strlen(tmpssid)>0){
						if(hIMEWnd!=HWND_INVALID){
							SendMessage(hIMEWnd,MSG_CLOSE,0,0L);
							hIMEWnd=HWND_INVALID;
						}
						curFocusWnd--;
					}
				} else if (curFocusWnd==1) {
					if(hIMEWnd!=HWND_INVALID){
						SendMessage(hIMEWnd,MSG_CLOSE,0,0L);
						hIMEWnd=HWND_INVALID;
					}
					curFocusWnd--;
				
				} else if(--curFocusWnd<0){
					curFocusWnd=16;
				}

				if (wifidhcpflag == 1 && curFocusWnd == 14) {
					curFocusWnd= 2;
				}

				if (curFocusWnd == 10|| curFocusWnd == 11|| curFocusWnd == 12 ||curFocusWnd == 13 ){
					curFocusWnd = 7;
				} else if (curFocusWnd == 6|| curFocusWnd == 7|| curFocusWnd == 8 || curFocusWnd == 9){
					curFocusWnd = 3;
				} else if (curFocusWnd == 3 || curFocusWnd == 4 || curFocusWnd == 5){
					curFocusWnd = 2;
				} else if(curFocusWnd == 14){
					curFocusWnd = 11;
				}

				SetFocusChild(WifiWnd[curFocusWnd]);
				return 0;

			} else if(LOWORD(wParam)==SCANCODE_F9 || 
					((gOptions.TFTKeyLayout==0 || gOptions.TFTKeyLayout==4) && (LOWORD(wParam)==SCANCODE_F11))) {
				if((curFocusWnd==0 || curFocusWnd==1) && (gOptions.IMEFunOn==1 && gOptions.TFTKeyLayout!=3))
				{
					T9IMEWindow(hWnd,0,200,gOptions.LCDWidth, gOptions.LCDHeight,gOptions.HzImeOn);
				}
			} else if ((LOWORD(wParam)==SCANCODE_CURSORBLOCKLEFT) || (LOWORD(wParam)==SCANCODE_CURSORBLOCKRIGHT)
				|| ((gOptions.TFTKeyLayout==3) && LOWORD(wParam)==SCANCODE_BACKSPACE)) {

				if ((LOWORD(wParam)==SCANCODE_CURSORBLOCKRIGHT) && gOptions.IMEFunOn==1 
						&& gOptions.TFTKeyLayout==3 && (curFocusWnd==0 || curFocusWnd==1)) {
					T9IMEWindow(hWnd,0,200,gOptions.LCDWidth, gOptions.LCDHeight, 0);
					return 0;
				}

				if(curFocusWnd==2 && ((LOWORD(wParam)==SCANCODE_CURSORBLOCKLEFT || ((gOptions.TFTKeyLayout==3) && LOWORD(wParam)==SCANCODE_BACKSPACE))
					||LOWORD(wParam)==SCANCODE_CURSORBLOCKRIGHT)) {

					int tmpsel = SendMessage(WifiWnd[curFocusWnd], CB_GETCURSEL, 0, 0);		
					if (tmpsel == 0) {
						SendMessage(WifiWnd[curFocusWnd], CB_SETCURSEL, 1, 0);
						dhcpswitch(1);
						UpdateWindow(hWnd,TRUE);
						wifidhcpflag =1;
					} else {
						SendMessage(WifiWnd[curFocusWnd], CB_SETCURSEL, 0, 0);
						dhcpswitch(0);
						UpdateWindow(hWnd,TRUE);
						wifidhcpflag = 0;
					}
				}
				if (curFocusWnd >2 && curFocusWnd<15 && wifidhcpflag ==0) {
					if (LOWORD(wParam)==SCANCODE_CURSORBLOCKLEFT ){
						curFocusWnd --;
						if (curFocusWnd == 2){
							curFocusWnd =14;
						}
					}else if (LOWORD(wParam)==SCANCODE_CURSORBLOCKRIGHT){
						curFocusWnd ++;
						if (curFocusWnd ==15){
							curFocusWnd = 3;
						}
					}
					SetFocusChild(WifiWnd[curFocusWnd]);
				}
				return 0;	
			} else if ((LOWORD(wParam)==SCANCODE_ENTER) || (LOWORD(wParam)==SCANCODE_F10)) {
				char tmpssid[128];
				switch(curFocusWnd)
				{
					case 0:
						GetWindowText(WifiWnd[0], tmpssid, sizeof(tmpssid));
						if(tmpssid && strlen(tmpssid)>0)
							SendMessage(hWnd, MSG_COMMAND, WIFI_SAVE, 0);
						else
							MessageBox1(hWnd ,LoadStrByID(HIT_ERROR0) ,LoadStrByID(HIT_ERR),MB_OK | MB_ICONINFORMATION);
						break;
					case 16:		//exit
						SendMessage(hWnd, MSG_COMMAND, WIFI_EXIT, 0);
						break;
					default:
						SendMessage(hWnd, MSG_COMMAND, WIFI_SAVE, 0);
				}
				return 0;
			} else if(LOWORD(wParam)==SCANCODE_MENU) {
				SendMessage(hWnd, MSG_COMMAND, WIFI_SAVE, 0);
				return 0;
			}
			break;

		case MSG_COMMAND:
			id = LOWORD(wParam);
			nc = HIWORD(wParam);
			if(id==WIFI_SAVE) {
				if(isModified() && SaveNewWiFiSetting(hWnd)) {
					MessageBox1(hWnd ,LoadStrByID(HIT_RIGHT) ,LoadStrByID(HIT_RUN),MB_OK| MB_ICONINFORMATION);
					if(!ismenutimeout) {
						PostMessage(hWnd, MSG_CLOSE, 0, 0);
					}
				} else if(!ismenutimeout) {
					PostMessage(hWnd, MSG_CLOSE, 0, 0);
				}
			} else if (id==WIFI_EXIT) {
				if(isModified() && MessageBox1(hWnd,LoadStrByID(MID_SAVEDATA),LoadStrByID(MID_APPNAME),
					MB_OKCANCEL|MB_ICONQUESTION|MB_BASEDONPARENT)==IDOK) {
					PostMessage(hWnd, MSG_COMMAND, WIFI_SAVE, 0);
				} else if(!ismenutimeout) {
					PostMessage(hWnd, MSG_CLOSE, 0, 0);
				}
			}
			break;

		case MSG_CLOSE:
			if(hIMEWnd!=HWND_INVALID){
				SendMessage(hIMEWnd,MSG_CLOSE,0,0);
				hIMEWnd=HWND_INVALID;
			}

			UnloadBitmap(&wifibkg);
			//MainWindowCleanup(hWnd);
			DestroyMainWindow(hWnd);
			return 0;

	}
	return DefaultMainWinProc(hWnd,message,wParam,lParam);
}
Beispiel #27
0
QSimpleTextItem::QSimpleTextItem(QString sText)
{
    sTEXT = sText;                       //默认文本
    m_rect.setRect(0,0,100,100);         //给背景矩形赋初始值
    InitParameters();
}