Exemplo n.º 1
0
void toResultTableView::clearData()
{
    // Note that destroying data model effectively "clears" QTableView
    if (Model && running())
        Model->stop();
    freeModel();
} // clearData
Exemplo n.º 2
0
toResultTableView::~toResultTableView()
{
    if (Model && running())
        Model->stop();
    freeModel();
    Registry.remove(Utils::ptr2str(this).c_str());
}
/* copyModel - Copy all the contents from one model to another */
void copyModel(Model *dst_m, Model *src_m) {
  int u, i;
  assert(src_m&&dst_m);
  //assert(src_m->uu<=dst_m->uu); /* Take into account the elimination of unreachable states */
  assert(src_m->ffm[0]->ii==dst_m->ffm[0]->ii);

  if(src_m->uu != dst_m->uu){
    freeModel(dst_m);
    dst_m = allocModel(src_m->ffm[0]->ii, src_m->uu);
    for(i = 0; i < src_m->ffm[0]->ii; i ++){
      switch((src_m->ffm[0])->ft[i]){
      case FT_CONTINUOUS:
	defineContFeat(dst_m, i, ((struct ContFI*)((src_m->ffm[0])->fi[i]))->initialSigma);
	break;
      case FT_RADIAL:
	defineRadialFeat(dst_m, i);
	break;
      case FT_DISCRETE:
	defineDiscreteFeat(dst_m, i);
	break;
      default:break;
      }
    }
  }
  
  copyHMM(dst_m->hmm, src_m->hmm);
  for (u = 0; u<src_m->uu; u++) copyFFM(dst_m->ffm[u], src_m->ffm[u]);
}
Exemplo n.º 4
0
void ResourceManager::unloadResources() {
	for (auto model = models_.begin(); model != models_.end(); model++) {
    freeModel(model->second);
	}
  for (auto texture = textures_.begin(); texture != textures_.end(); texture++) {
    freeTexture(texture->second);
  }
  for (auto shader = shaders_.begin(); shader != shaders_.end(); shader++) {
    delete (shader->second);
  }

  models_.clear();
  textures_.clear();
  shaders_.clear();
}
Exemplo n.º 5
0
ModelWidget::~ModelWidget() {
	freeModel(_model);
}
Exemplo n.º 6
0
void BoostCart::GlobalRegression(const vector<Mat_<int> >& lbf, const Mat_<double>& shape_residual) {
  Config& c = Config::GetInstance();
  const int landmark_n = c.landmark_n;
  const int n = lbf.size();
  const int m = K; // true size of local binary feature
  const int f = m*carts[0].leafNum; // full size of local binary feature
  vector<int> idx;
  // prepare linear regression X, Y
  struct feature_node** X = (struct feature_node**)malloc(n*sizeof(struct feature_node*));
  double** Y = (double**)malloc(2 * landmark_n*sizeof(double*));
  for (int i = 0; i < n; i++) {
    X[i] = (struct feature_node*)malloc((m + 1)*sizeof(struct feature_node));
    for (int j = 0; j < m; j++) {
      X[i][j].index = lbf[i](0, j) + 1; // index starts from 1
      X[i][j].value = 1.;
    }
    X[i][m].index = -1;
    X[i][m].value = -1.;
  }
  for (int i = 0; i < landmark_n; i++) {
    Y[2 * i] = (double*)malloc(n*sizeof(double));
    Y[2 * i + 1] = (double*)malloc(n*sizeof(double));
    for (int j = 0; j < n; j++) {
      Y[2 * i][j] = shape_residual(j, 2 * i);
      Y[2 * i + 1][j] = shape_residual(j, 2 * i + 1);
    }
  }
  // train every landmark
  struct problem prob;
  struct parameter param;
  prob.l = n;
  prob.n = f;
  prob.x = X;
  prob.bias = -1;
  param.solver_type = L2R_L2LOSS_SVR_DUAL;
  param.C = 1. / n;
  param.p = 0;
  param.eps = 0.0001;

  #pragma omp parallel for
  for (int i = 0; i < landmark_n; i++) {
    struct problem prob_ = prob;
    prob_.y = Y[2 * i];
    check_parameter(&prob_, &param);
    struct model *model = train(&prob_, &param);
    for (int j = 0; j < f; j++) w(j, 2 * i) = get_decfun_coef(model, j + 1, 0);
    freeModel(model);

    prob_.y = Y[2 * i + 1];
    check_parameter(&prob_, &param);
    model = train(&prob_, &param);
    for (int j = 0; j < f; j++) w(j, 2 * i + 1) = get_decfun_coef(model, j + 1, 0);
    freeModel(model);
  }

  // free
  for (int i = 0; i < n; i++) free(X[i]);
  for (int i = 0; i < 2 * landmark_n; i++) free(Y[i]);
  free(X);
  free(Y);
}
Exemplo n.º 7
0
int main(int argc, char **argv) {
	int flag;
	const char* filename = NULL;

	// retrieve the options
	while(1) {
		static struct option long_options[] = {
			{"help", no_argument, &flagHelp, 1},
			{"no-counter-examples", no_argument, &flagNoCounterExample, 1},
			{"no-generalization", no_argument, &flagNoGeneralization, 1},
			{"expand-relations", no_argument, &flagExpandRelation, 1},
			{"no-color", no_argument, &flagNoColor, 1},
			{0, 0, 0, 0}
		};
		/* getopt_long stores the option index here. */
		int option_index = 0;

		flag = getopt_long (argc, argv, "vh", long_options, &option_index);

		/* Detect the end of the options. */
		if (flag == -1) {
			break;
		}

		switch(flag) {
			case 0:
				// all long option set flags, they will be checked after
				break;
			case 'v':
				// each occurence of a v add a verbosity level
				++flagVerbose;
				break;
			case 'h':
				flagHelp = 1;
				break;
			case '?':
				/* getopt_long already printed an error message. */
				break;
			default:
				abort ();
		}
	}

	if (optind < argc) {
		filename = argv[optind];
	}
	else if(!flagHelp) {
		output(LERROR, "An example file must be passed as an argument. Re run with --help for more informations.\n");
		return 1;
	}
	else {
		output(L0, PROG_NAME " is a programs that aims to find similarities in objects of same type.\n");
		output(L0, "Usage: " PROG_NAME " --help\n");
		output(L0, "       " PROG_NAME " <example-file-path>\n\n");
		output(L0, "--help                  Print the options that can be given to the program\n");
		output(L0, "--expand-relations      On solution objects that contains relations, print the object linked instead of writing its name\n");
		output(L0, "--no-generalization     Skip the generalization step of the solutions generation.\n");
		output(L0, "--no-counter-examples   Prevent the use of counter-exemples to reduce the solutions.\n");
		output(L0, "--no-color              Disable the colored output.\n");
		output(L0, "-v                      Set the verbosity level. 4 levels are available (up to -vvvv)\n");

		return 0;
	}

	setOutputImportance(flagVerbose);

	// if the user ask for no color or the output streams (whether stdout or stderr) aren't terminals, remove colors
	if(flagNoColor || !isatty(fileno(stdout)) || !isatty(fileno(stderr))) {
		enableColors(0);
	}

	size_t includePosition;
	char* c = getIncludeFile(filename, &includePosition);

	if(c == NULL) {
		output(LERROR, "The loading of the configuration file failed. The configuration must be linked in the example file (example file loaded: %s).\n", filename);
	}
	else {
		output(L1, "%sLoading configuration file: %s%s\n", SBDEFAULT, c, SDEFAULT);
		Model* m = loadConfigFile(c);

		if(m == NULL) {
			output(LERROR, "Configuration file parsing: failed\n");
			free(c);
			return 1;
		}

		output(L1, "%sLoading examples file: %s%s\n", SBDEFAULT, filename, SDEFAULT);

		Examples* e = loadExampleFile(filename, m, includePosition);

		if(e == NULL) {
			output(LERROR, "Example file parsing: failed\n");
			free(c);
			freeModel(m);
			return 1;
		}

		output(L1, "%sGenerating all combinations...%s\n", SBDEFAULT, SDEFAULT);

		Solution* s = genAllCombi(m, e);

		output(L1, "%sAdding relations...%s\n", SBDEFAULT, SDEFAULT);

		genAllRelations(s, e, m);

		if(!flagNoGeneralization) {
			output(L1, "%sGeneralization...%s\n", SBDEFAULT, SDEFAULT);
			genGeneralization(m, s);
		}

		if(!flagNoCounterExample) {
			output(L1, "%sChecking counter-examples...%s\n", SBDEFAULT, SDEFAULT);
			genCounterExamples(m, e, s);
		}

		output(L1, "%sSolutions:%s\n", SBDEFAULT, SDEFAULT);
		
		genOutput(s, m, flagExpandRelation);

		free(c);
		freeModel(m);
		freeExamples(e);
		freeSolution(s);
	}

	return 0;
}
Exemplo n.º 8
0
void toResultTableView::querySub(QSharedPointer<toConnectionSubLoan> &con, const QString &sql, toQueryParams const& param)
{
    setSqlAndParams(sql, param);

    TLOG(7, toDecorator, __HERE__) << "Query from toResultTableView::querySub :" << sql << std::endl;
    try
    {
        if (Model && running())
            Model->stop();
        freeModel();

        readAllAct->setEnabled(true);
        Ready = false;
        Finished = false;
        Working->setText(tr("Please wait..."));
        Working->hide();

        // sets visible true but won't show if parent is hidden
        QTimer t(this);
        t.singleShot(300, Working, SLOT(forceShow()));

        toEventQuery *query = new toEventQuery(this
                                               , con
                                               , sql
                                               , param
                                               , toEventQuery::READ_FIRST
                                               //, Statistics
                                              );

        toResultModel *model = allocModel(query);
        setModel(model);

        connect(Model, SIGNAL(done()), this, SLOT(slotHandleDone()));
        connect(Model, SIGNAL(modelReset()), this, SLOT(slotHandleReset()));
        connect(Model,
                SIGNAL(firstResult(const toConnection::exception &, bool)),
                this,
                SLOT(slotHandleFirst(const toConnection::exception &, bool)));
        setSortingEnabled(true);
        query->start();
    }
    catch (const toConnection::exception &str)
    {
        emit firstResult(toResult::sql(), str, true);
        emit done();
        slotHandleDone();
        Utils::toStatusMessage(str);
    }
    catch (const QString &str)
    {
        emit firstResult(toResult::sql(), str, true);
        emit done();
        slotHandleDone();
        Utils::toStatusMessage(str);
    }

    verticalHeader()->setVisible(false);
    verticalHeader()->setDefaultSectionSize(QFontMetrics(QFont()).height() + 4);

    horizontalHeader()->setHighlightSections(false);

    // when a new model is created the column sizes are lost
    ColumnsResized = false;
}
Exemplo n.º 9
0
int main(int argc, char **argv)
{
    MODEL *psModel;
    const int width = 640, height = 480;
    SDL_Event event;
    GLfloat angle = 0.0f;
    const float aspect = (float)width / (float)height;
    bool quit = false;
    float dimension = 0.0f;
    int i;
    char path[PATH_MAX];

    parse_args(argc, argv);

    /* Initialize SDL */
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0)
    {
        fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }
    atexit(SDL_Quit);

    psModel = readModel(input, SDL_GetTicks());
    strcpy(path, texPath);
    strcat(path, psModel->texPath);
    psModel->pixmap = readPixmap(path);

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    /* Initialize the display */
    screen = SDL_SetVideoMode(width, height, 0, SDL_OPENGL|SDL_ANYFORMAT);
    if (screen == NULL)
    {
        fprintf(stderr, "Couldn't initialize display: %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }

    printf("OpenGL version: %s\n", glGetString(GL_VERSION));
    printf("OpenGL renderer: %s\n", glGetString(GL_RENDERER));
    printf("OpenGL vendor: %s\n", glGetString(GL_VENDOR));

    resizeWindow(width, height);
    glEnable(GL_TEXTURE_2D);
    glDisable(GL_FOG);
    glDisable(GL_LIGHTING);
    glEnable(GL_BLEND);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
    glClearDepth(1.0f);
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45.0f, aspect, 0.1f, 500.0f);
    glMatrixMode(GL_MODELVIEW);

    prepareModel(psModel);
    for (i = 0; i < psModel->meshes; i++)
    {
        int j;
        MESH *psMesh = &psModel->mesh[i];

        for (j = 0; j < psMesh->vertices * 3; j++)
        {
            dimension = MAX(fabs(psMesh->vertexArray[j]), dimension);
        }
    }

    /* Find model size */

    while (!quit)
    {
        now = SDL_GetTicks();
        while (SDL_PollEvent(&event))
        {
            SDL_keysym *keysym = &event.key.keysym;

            switch (event.type)
            {
            case SDL_VIDEORESIZE:
                resizeWindow(event.resize.w, event.resize.h);
                break;
            case SDL_QUIT:
                quit = true;
                break;
            case SDL_KEYDOWN:
                switch (keysym->sym)
                {
                case SDLK_F1:
                    glEnable(GL_CULL_FACE);
                    printf("Culling enabled.\n");
                    break;
                case SDLK_F2:
                    glDisable(GL_CULL_FACE);
                    printf("Culling disabled.\n");
                    break;
                case SDLK_F3:
                    glDisable(GL_TEXTURE_2D);
                    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
                    printf("Wireframe mode.\n");
                    break;
                case SDLK_F4:
                    glEnable(GL_TEXTURE_2D);
                    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
                    printf("Texturing mode.\n");
                    break;
                case SDLK_ESCAPE:
                    quit = true;
                    break;
                case SDLK_KP_PLUS:
                case SDLK_PLUS:
                    for (i = 0; i < psModel->meshes; i++)
                    {
                        MESH *psMesh = &psModel->mesh[i];

                        if (!psMesh->teamColours)
                        {
                            continue;
                        }

                        if (psMesh->currentTextureArray < 7)
                        {
                            psMesh->currentTextureArray++;
                        }
                        else
                        {
                            psMesh->currentTextureArray = 0;
                        }
                    }
                    break;
                default:
                    break;
                }
                break;
            }
        }

        glLoadIdentity();
        glTranslatef(0.0f, -30.0f, -50.0f + -(dimension * 2.0f));;
        glRotatef(angle, 0, 1, 0);
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
        drawModel(psModel, now);
        SDL_GL_SwapBuffers();
        SDL_Delay(10);
        angle += 0.1;
        if (angle > 360.0f)
        {
            angle = 0.0f;
        }
    }

    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    freeModel(psModel);

    return 0;
}
Exemplo n.º 10
0
WZMOpenGLWidget::~WZMOpenGLWidget()
{
	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
	freeModel(psModel);
}
Exemplo n.º 11
0
MODEL *QWzmViewer::loadPIE(QString inputFile)
{
	const bool swapYZ = false;
	const bool reverseWinding = false;
	const bool invertUV = false;
	const bool assumeAnimation = false;
	int num, x, y, z, levels, level, pieVersion;
	char s[200];
	QByteArray inFile = inputFile.toAscii();
	const char *input = inFile.constData();
	MODEL *psModel = NULL;
	FILE *fp = fopen(input, "r");

	if (!fp)
	{
		qWarning("Cannot open \"%s\" for reading: %s", input, strerror(errno));
		return NULL;
	}

	num = fscanf(fp, "PIE %d\n", &pieVersion);
	if (num != 1)
	{
		qWarning("Bad PIE file %s\n", input);
		fclose(fp);
		freeModel(psModel);
		return NULL;
	}

	num = fscanf(fp, "TYPE %x\n", &x); // ignore
	if (num != 1)
	{
		qWarning("Bad TYPE directive in %s\n", input);
		fclose(fp);
		freeModel(psModel);
		return NULL;
	}

	num = fscanf(fp, "TEXTURE %d %s %d %d\n", &z, s, &x, &y);
	if (num != 4)
	{
		qWarning("Bad TEXTURE directive in %s\n", input);
		fclose(fp);
		freeModel(psModel);
		return NULL;
	}

	num = fscanf(fp, "LEVELS %d\n", &levels);
	if (num != 1)
	{
		qWarning("Bad LEVELS directive in %s\n", input);
		fclose(fp);
		freeModel(psModel);
		return NULL;
	}

	psModel = createModel(levels, 0);
	if (!psModel)
	{
		qFatal("Out of memory");
		fclose(fp);
		exit(EXIT_FAILURE);
	}
	strcpy(psModel->texPath, s);

	for (level = 0; level < levels; level++)
	{
		MESH *psMesh = &psModel->mesh[level];
		int j, points, faces, facesWZM, faceCount, pointsWZM, pointCount, textureArrays = 1;
		WZ_FACE *faceList;
		WZ_POSITION *posList;

		num = fscanf(fp, "\nLEVEL %d\n", &x);
		if (num != 1 || level + 1 != x)
		{
			qWarning("Bad LEVEL directive in %s, was %d should be %d.\n", input, x, level + 1);
			fclose(fp);
			freeModel(psModel);
			return NULL;
		}

		num = fscanf(fp, "POINTS %d\n", &points);
		if (num != 1)
		{
			qWarning("Bad POINTS directive in %s, level %d.\n", input, level);
			fclose(fp);
			freeModel(psModel);
			return NULL;
		}
		posList = (WZ_POSITION*)malloc(sizeof(WZ_POSITION) * points);
		for (j = 0; j < points; j++)
		{
			if (swapYZ)
			{
				num = fscanf(fp, "%f %f %f\n", &posList[j].x, &posList[j].z, &posList[j].y);
			}
			else
			{
				num = fscanf(fp, "%f %f %f\n", &posList[j].x, &posList[j].y, &posList[j].z);
			}
			if (num != 3)
			{
				qWarning("Bad POINTS entry level %d, number %d\n", level, j);
				fclose(fp);
				freeModel(psModel);
				return NULL;
			}
		}

		num = fscanf(fp, "POLYGONS %d", &faces);
		if (num != 1)
		{
			qWarning("Bad POLYGONS directive in %s, level %d.\n", input, level);
			fclose(fp);
			freeModel(psModel);
			return NULL;
		}
		facesWZM = faces;	// for starters
		faceList = (WZ_FACE*)malloc(sizeof(WZ_FACE) * faces);
		pointsWZM = 0;
		for (j = 0; j < faces; ++j)
		{
			int k;
			unsigned int flags;

			num = fscanf(fp, "\n%x", &flags);
			if (num != 1)
			{
				qWarning("Bad POLYGONS texture flag entry level %d, number %d\n", level, j);
				fclose(fp);
				freeModel(psModel);
				return NULL;
			}
			if (!(flags & iV_IMD_TEX))
			{
				qWarning("Bad texture flag entry level %d, number %d - no texture flag!\n", level, j);
				fclose(fp);
				freeModel(psModel);
				return NULL;
			}

			if (flags & iV_IMD_XNOCUL)
			{
				faceList[j].cull = true;
				facesWZM++;	// must add additional face that is faced in the opposite direction
			}
			else
			{
				faceList[j].cull = false;
			}

			num = fscanf(fp, "%u", &faceList[j].vertices);
			if (num != 1 || faceList[j].vertices < 0)
			{
				qWarning("Bad POLYGONS vertices entry level %d, number %d\n", level, j);
				fclose(fp);
				freeModel(psModel);
				return NULL;
			}
			assert(faceList[j].vertices <= MAX_POLYGON_SIZE); // larger polygons not supported
			assert(faceList[j].vertices >= VERTICES_PER_TRIANGLE); // points and lines not supported
			if (faceList[j].vertices > VERTICES_PER_TRIANGLE)
			{
				// since they are triangle fans already, we get to do easy tessellation
				facesWZM += (faceList[j].vertices - VERTICES_PER_TRIANGLE);
				if (faceList[j].cull)
				{
					facesWZM += (faceList[j].vertices - VERTICES_PER_TRIANGLE); // double the number of extra faces needed
				}
			}
			pointsWZM += faceList[j].vertices;

			// Read in vertex indices and texture coordinates
			for (k = 0; k < faceList[j].vertices; k++)
			{
				num = fscanf(fp, "%d", &faceList[j].index[k]);
				if (num != 1)
				{
					qWarning("Bad vertex position entry level %d, number %d\n", level, j);
					fclose(fp);
					freeModel(psModel);
					return NULL;
				}
			}
			if (flags & iV_IMD_TEXANIM)
			{
				num = fscanf(fp, "%d %d %f %f", &faceList[j].frames, &faceList[j].rate, &faceList[j].width, &faceList[j].height);
				if (num != 4)
				{
					qWarning("Bad texture animation entry level %d, number %d.\n", level, j);
					fclose(fp);
					freeModel(psModel);
					return NULL;
				}
				if (faceList[j].frames <= 1)
				{
					qWarning("Level %d, polygon %d has a single animation frame. That makes no sense.\n", level, j);
				}
				if (textureArrays < faceList[j].frames)
				{
					textureArrays = faceList[j].frames;
				}
			}
			else
			{
				faceList[j].frames = 0;
				faceList[j].rate = 0;
				faceList[j].width = 0;
				faceList[j].height = 0;
			}
			for (k = 0; k < faceList[j].vertices; k++)
			{
				num = fscanf(fp, "%f %f", &faceList[j].texCoord[k][0], &faceList[j].texCoord[k][1]);
				if (num != 2)
				{
					qWarning("Bad texture coordinate entry level %d, number %d\n", level, j);
					fclose(fp);
					freeModel(psModel);
					return NULL;
				}
			}
		}
		if (textureArrays == 8 && !assumeAnimation)	// guesswork
		{
			psMesh->teamColours = true;
		}
		else
		{
			psMesh->teamColours = false;
		}

		// Calculate position list. Since positions hold texture coordinates in WZM, unlike in Warzone,
		// we need to use some black magic to transfer them over here.
		pointCount = 0;
		psMesh->vertices = pointsWZM;
		psMesh->faces = facesWZM;
		psMesh->vertexArray = (GLfloat*)malloc(sizeof(GLfloat) * psMesh->vertices * VERTICES_PER_TRIANGLE);
		psMesh->indexArray = (GLuint*)malloc(sizeof(GLuint) * psMesh->vertices * VERTICES_PER_TRIANGLE);
		psMesh->textureArrays = textureArrays;
		for (j = 0; j < textureArrays; j++)
		{
			psMesh->textureArray[j] = (GLfloat*)malloc(sizeof(GLfloat) * psMesh->vertices * 2);
		}

		for (z = 0, j = 0; j < faces; j++)
		{
			for (int k = 0; k < faceList[j].vertices; k++, pointCount++)
			{
				int pos = faceList[j].index[k];

				// Generate new position
				psMesh->vertexArray[z++] = posList[pos].x;
				psMesh->vertexArray[z++] = posList[pos].y;
				psMesh->vertexArray[z++] = posList[pos].z;

				// Use the new position
				faceList[j].index[k] = pointCount;
			}
		}

		// Handle texture animation or team colours. In either case, add multiple texture arrays.
		for (z = 0; z < textureArrays; z++)
		{
			for (x = 0, j = 0; j < faces; j++)
			{
				for (int k = 0; k < faceList[j].vertices; k++)
				{
					double u;
					double v;
					// Fix for division by zero in pie 2
					int framesPerLine = OLD_TEXTURE_SIZE_FIX;

					if (pieVersion == 3)
					{
						if(faceList[j].width != 0)
						{
							framesPerLine = 1/ faceList[j].width;
						}
						else
						{
							// Fix for division by zero in pie 3
							framesPerLine = 1;
						}
					}
					else if (faceList[j].width != 0) // else pieVersion ==2
					{
						framesPerLine = OLD_TEXTURE_SIZE_FIX / faceList[j].width;
					}

					int frameH = z % framesPerLine;

					/*
					 * This works because wrap around is only permitted if you start the animation at the
					 * left border of the texture. What a horrible hack this was.
					 * Note: It is done the same way in the Warzone source.
					 */
					int frameV = z / framesPerLine;
					double width = faceList[j].texCoord[k][0] + faceList[j].width * frameH;
					double height = faceList[j].texCoord[k][1] + faceList[j].height * frameV;

					if (pieVersion == 2)
					{
						u = width / OLD_TEXTURE_SIZE_FIX;
						v = height / OLD_TEXTURE_SIZE_FIX;
					}
					else if (pieVersion == 3)
					{
						u = width;
						v = height;
					}

					if (invertUV)
					{
						v = 1.0f - v;
					}
					psMesh->textureArray[z][x++] = u;
					psMesh->textureArray[z][x++] = v;
				}
			}
		}

		faceCount = 0;

		for (z = 0, j = 0; j < faces; j++)
		{
			int k, key, previous;

			key = faceList[j].index[0];
			previous = faceList[j].index[2];
			faceCount++;
			if (reverseWinding || faceList[j].cull)
			{
				GLuint *v = &psMesh->indexArray[z];

				z += 3;
				v[0] = key;
				v[1] = previous;
				v[2] = faceList[j].index[1];
			}
			if (!reverseWinding || faceList[j].cull)
			{
				GLuint *v = &psMesh->indexArray[z];

				z += 3;
				v[0] = key;
				v[2] = previous;
				v[1] = faceList[j].index[1];
			}

			// Generate triangles from the Warzone triangle fans (PIEs, get it?)
			for (k = VERTICES_PER_TRIANGLE; k < faceList[j].vertices; k++)
			{
				if (reverseWinding || faceList[j].cull)
				{
					GLuint *v = &psMesh->indexArray[z];

					z += 3;
					v[0] = key;
					v[2] = previous;
					v[1] = faceList[j].index[k];
				}
				if (!reverseWinding || faceList[j].cull)
				{
					GLuint *v = &psMesh->indexArray[z];

					z += 3;
					v[0] = key;
					v[1] = previous;
					v[2] = faceList[j].index[k];
				}
				previous = faceList[j].index[k];
			}
		}

		// We only handle texture animation here, so leave bone heap animation out of it for now.
		if (textureArrays == 1 || (textureArrays == 8 && !assumeAnimation))
		{
			psMesh->frames = 0;
		}
		else
		{
			psMesh->frames = textureArrays;
			psMesh->frameArray = (FRAME*)malloc(sizeof(FRAME) * psMesh->frames);
			for (j = 0; j < textureArrays; j++)
			{
				FRAME *psFrame = &psMesh->frameArray[j];

				psFrame->timeSlice = (float)faceList[j].rate;
				psFrame->textureArray = j;
				psFrame->translation.x = 0;
				psFrame->translation.y = 0;
				psFrame->translation.z = 0;
				psFrame->rotation.x = 0;
				psFrame->rotation.y = 0;
				psFrame->rotation.z = 0;
			}
		}

		num = fscanf(fp, "\nCONNECTORS %d", &psMesh->connectors);
		if (num == 1 && psMesh->connectors > 0)
		{
			psMesh->connectorArray = (CONNECTOR *)malloc(sizeof(CONNECTOR) * psMesh->connectors);

			for (j = 0; j < psMesh->connectors; j++)
			{
				CONNECTOR *conn = &psMesh->connectorArray[j];
				GLfloat a, b, c;

				num = fscanf(fp, "\n%f %f %f", &a, &b, &c);
				if (num != 3)
				{
					qWarning("Bad CONNECTORS directive in %s entry level %d, number %d\n", input, level, j);
					fclose(fp);
					freeModel(psModel);
					return NULL;
				}
				conn->pos.x = a;
				conn->pos.y = b;
				conn->pos.z = c;
				conn->type = 0;	// generic type of connector, only type supported in PIE
			}
		}

		free(faceList);
		free(posList);
	}
	fclose(fp);
	return psModel;
}
Exemplo n.º 12
0
MODEL *readModel(const char *filename, int now)
{
	FILE *fp = fopen(filename, "r");
	int num, x, meshes, mesh, version;
	char s[200];
	MODEL *psModel;

	if (!fp)
	{
		fprintf(stderr, "Cannot open \"%s\" for reading: %s", filename, strerror(errno));
		return NULL;
	}

	num = fscanf(fp, "WZM %d\n", &version);
	if (num != 1)
	{
		fprintf(stderr, "Bad WZM file or wrong version: %s\n", filename);
		fclose(fp);
		return NULL;
	}
	if (version != 1 && version != 2)
	{
		fprintf(stderr, "Bad WZM version %d in %s\n", version, filename);
		fclose(fp);
		return NULL;
	}

	num = fscanf(fp, "TEXTURE %s\n", s);
	if (num != 1)
	{
		fprintf(stderr, "Bad TEXTURE directive in %s\n", filename);
		fclose(fp);
		return NULL;
	}

	num = fscanf(fp, "MESHES %d", &meshes);
	if (num != 1)
	{
		fprintf(stderr, "Bad MESHES directive in %s\n", filename);
		fclose(fp);
		return NULL;
	}
	psModel = createModel(meshes, now);
	strcpy(psModel->texPath, s);

	for (mesh = 0; mesh < meshes; mesh++)
	{
		MESH *psMesh = &psModel->mesh[mesh];
		int j;

		num = fscanf(fp, "\nMESH %s\n", s);
		if (num != 1)
		{
			fprintf(stderr, "Bad MESH directive in %s, was \"%s\".\n", filename, s);
			fclose(fp);
			freeModel(psModel);
			return NULL;
		}

		num = fscanf(fp, "TEAMCOLOURS %d\n", &x);
		if (num != 1 || x > 1 || x < 0)
		{
			fprintf(stderr, "Bad TEAMCOLOURS directive in %s, mesh %d.\n", filename, mesh);
			fclose(fp);
			freeModel(psModel);
			return NULL;
		}
		psMesh->teamColours = x;

		num = fscanf(fp, "VERTICES %d\n", &x);
		if (num != 1 || x < 0)
		{
			fprintf(stderr, "Bad VERTICES directive in %s, mesh %d.\n", filename, mesh);
			fclose(fp);
			freeModel(psModel);
			return NULL;
		}
		psMesh->vertices = x;
		psMesh->vertexArray = malloc(sizeof(GLfloat) * x * 3);

		num = fscanf(fp, "FACES %d\n", &x);
		if (num != 1)
		{
			fprintf(stderr, "Bad VERTICES directive in %s, mesh %d.\n", filename, mesh);
			fclose(fp);
			freeModel(psModel);
			return NULL;
		}
		psMesh->faces = x;
		psMesh->indexArray = malloc(sizeof(GLuint) * x * 3);

		num = fscanf(fp, "VERTEXARRAY");
		if (num == EOF)
		{
			fprintf(stderr, "No VERTEXARRAY directive in %s, mesh %d.\n", filename, mesh);
			fclose(fp);
			freeModel(psModel);
			return NULL;
		}

		for (j = 0; j < psMesh->vertices; j++)
		{
			GLfloat *v = &psMesh->vertexArray[j * 3];

			num = fscanf(fp, "%f %f %f\n", &v[0], &v[1], &v[2]);
			if (num != 3)
			{
				fprintf(stderr, "Bad VERTEXARRAY entry mesh %d, number %d\n", mesh, j);
				fclose(fp);
				freeModel(psModel);
				return NULL;
			}
		}

		num = fscanf(fp, "TEXTUREARRAYS %d", &x);
		if (num != 1 || x < 0)
		{
			fprintf(stderr, "Bad TEXTUREARRAYS directive in %s, mesh %d.\n", filename, mesh);
			fclose(fp);
			freeModel(psModel);
			return NULL;
		}
		psMesh->textureArrays = x;
		for (j = 0; j < psMesh->textureArrays; j++)
		{
			int k;

			num = fscanf(fp, "\nTEXTUREARRAY %d", &x);
			if (num != 1 || x < 0 || x != j)
			{
				fprintf(stderr, "Bad TEXTUREARRAY directive in %s, mesh %d, array %d.\n", filename, mesh, j);
				fclose(fp);
				freeModel(psModel);
				return NULL;
			}
			psMesh->textureArray[j] = malloc(sizeof(GLfloat) * psMesh->vertices * 2);
			for (k = 0; k < psMesh->vertices; k++)
			{
				GLfloat *v = &psMesh->textureArray[j][k * 2];

				num = fscanf(fp, "\n%f %f", &v[0], &v[1]);
				if (num != 2)
				{
					fprintf(stderr, "Bad TEXTUREARRAY entry mesh %d, array %d, number %d\n", mesh, j, k);
					fclose(fp);
					freeModel(psModel);
					return NULL;
				}
			}
		}

		num = fscanf(fp, "\nINDEXARRAY");
		if (num == EOF)
		{
			fprintf(stderr, "No INDEXARRAY directive in %s, mesh %d.\n", filename, mesh);
			fclose(fp);
			freeModel(psModel);
			return NULL;
		}

		for (j = 0; j < psMesh->faces; j++)
		{
			GLuint *v = &psMesh->indexArray[j * 3];

			num = fscanf(fp, "\n%u %u %u", &v[0], &v[1], &v[2]);
			if (num != 3)
			{
				fprintf(stderr, "Bad INDEXARRAY entry in mesh %d, number %d\n", mesh, j);
				fclose(fp);
				freeModel(psModel);
				return NULL;
			}
		}

		// Read animation frames
		num = fscanf(fp, "\nFRAMES %d", &psMesh->frames);
		if (num != 1 || psMesh->frames < 0)
		{
			fprintf(stderr, "Bad FRAMES directive in mesh %d\n", mesh);
			fclose(fp);
			freeModel(psModel);
			return NULL;
		}
		if (psMesh->frames)
		{
			psMesh->frameArray = malloc(sizeof(FRAME) * psMesh->frames);
		}
		for (j = 0; j < psMesh->frames; j++)
		{
			FRAME *psFrame = &psMesh->frameArray[j];

			num = fscanf(fp, "\n%f %d %f %f %f %f %f %f", &psFrame->timeSlice, &psFrame->textureArray,
						 &psFrame->translation.x, &psFrame->translation.y, &psFrame->translation.z,
						 &psFrame->rotation.x, &psFrame->rotation.y, &psFrame->rotation.z);
			if (num != 8)
			{
				fprintf(stderr, "Bad FRAMES entry in mesh %d, number %d\n", mesh, j);
				fclose(fp);
				freeModel(psModel);
				return NULL;
			}
		}

		// Read connectors
		num = fscanf(fp, "\nCONNECTORS %d", &psMesh->connectors);
		if (num != 1 || psMesh->connectors < 0)
		{
			fprintf(stderr, "Bad CONNECTORS directive in mesh %d\n", mesh);
			fclose(fp);
			freeModel(psModel);
			return NULL;
		}
		if (psMesh->connectors)
		{
			psMesh->connectorArray = malloc(sizeof(CONNECTOR) * psMesh->connectors);
		}
		for (j = 0; j < psMesh->connectors; j++)
		{
			CONNECTOR *conn = &psMesh->connectorArray[j];
			int angle, angler1, angler2;

			if (version == 1)
			{
				num = fscanf(fp, "\n%f %f %f %d", &conn->pos.x, &conn->pos.y, &conn->pos.z, &conn->type);
			}
			else if (version == 2)
			{
				num = fscanf(fp, "\n%s %f %f %f %d %d %d", s, &conn->pos.x, &conn->pos.y, &conn->pos.z, &angle, &angler1, &angler2);
				conn->type = 0;	// TODO
			}
			if (num != 4)
			{
				fprintf(stderr, "Bad CONNECTORS entry in mesh %d, number %d\n", mesh, j);
				fclose(fp);
				freeModel(psModel);
				return NULL;
			}
		}
	}

	return psModel;
}
Exemplo n.º 13
0
void QWzmViewer::actionOpen()
{
	static QString lastDir; // Convenience HACK to remember last succesful directory a model was loaded from.
	filename = QFileDialog::getOpenFileName(this, tr("Choose a PIE or WZM file"), lastDir, tr("All Compatible (*.wzm *.pie);;WZM models (*.wzm);;PIE models (*.pie)"));
	if (!filename.isEmpty())
	{
		QFileInfo theFile(filename);
		MODEL *tmpModel = NULL;

		if (theFile.completeSuffix().compare(QString("wzm"), Qt::CaseInsensitive) == 0)
		{
			tmpModel = readModel(filename.toAscii().constData(), 0);
		}
		else if (theFile.completeSuffix().compare(QString("pie"), Qt::CaseInsensitive) == 0)
		{
			tmpModel = loadPIE(filename);
		}
		else
		{
			return;
		}

		if (tmpModel)
		{

			QFileInfo texPath(theFile.absoluteDir(), tmpModel->texPath);

			// Try to find texture automatically
			if (!texPath.exists())
			{
				texPath.setFile(QString("../../data/base/texpages/"), tmpModel->texPath);
				if (!texPath.exists())
				{
					texPath.setFile(QFileDialog::getExistingDirectory(this, tr("Specify texture directory"), QString::null), tmpModel->texPath);
					if (!texPath.exists())
					{
						QMessageBox::warning(this, tr("Oops..."), "Could not find texture", QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton);
						freeModel(tmpModel);
						return;
					}
				}
			}
			if (psModel)
			{
				freeModel(psModel);
			}
			psModel = tmpModel;
			setModel(texPath);
			ui->actionSave->setEnabled(true);
			lastDir = theFile.absolutePath();
			fileNameLabel->setText(theFile.fileName());
			fileNameLabel->setToolTip(filename);
		}
		else
		{
			qWarning("Failed to create model!");

			ui->statusBar->showMessage(tr("Failed to create model!"), 3000);
		}
	}
}
Exemplo n.º 14
0
int main(int argc, char **argv) {
	TypePosition orderstart=1, orderend=10;
	char option[256], inputFileName[SIZE_BUFFER_CHAR], outputFileName[SIZE_BUFFER_CHAR], bufferOutput[SIZE_BUFFER_CHAR], *table, 
	outputFormat = 'r', typeDec = 'l', typeAlphabet = '?', typeCalc = 'g', type = 't';
	TypeSetOfSequences *set, seq;
	TypeAlignment aln, atmp;
	int fixed = 0;
	double threshold = 0.001, tmin = 1E-20, tmax=0.1, tstep = 0.00001, qmin = -25, qmax = -3, qprec = 0.5;
	double thre;
	TypeNumber n;
	TypeDistance distA, distB;
	TypePosition l, tot, lmax = 50;
	TypeSuffixTree *suffixTree;
	TypeMarkovModel *model;
	TypeCodeScheme *scheme;
/*	TypeDistFunction *distfunc[MAX_FUNC]=
	{computeProba, computeKullbackLeiber1, computePham, computeCommon, computeCommonBis, computeGillesPham, computeMatchesBis, computeMatches, computeAlex, computeAlexBis};
*/		
	FILE *fi, *fo;
	int i = 1, typeDist = 0;

	for(i=0; i<256; i++)
		option[i] = 0;
	for(i=1; i<argc && *(argv[i]) == '-'; i++) {
		int j;
		for(j=1; argv[i][j] != '\0'; j++)
			option[argv[i][j]] = 1;
		if(option['f']) {
			option['f'] = 0;
			if((i+1)<argc && sscanf(argv[i+1], "%c", &outputFormat) == 1)
				i++;
		}
		if(option['s']) {
			option['s'] = 0;
			if((i+1)<argc && sscanf(argv[i+1], "%c", &typeAlphabet) == 1)
				i++;
		}
		if(option['c']) {
			option['c'] = 0;
			if((i+1)<argc && sscanf(argv[i+1], "%c", &typeCalc) == 1)
				i++;
		}
		if(option['m']) {
			option['m'] = 0;
			if((i+1)<argc && sscanf(argv[i+1], "%lf", &tmin) == 1)
				i++;
			if(typeDist >= MAX_FUNC)
				typeDist = 0;
		}
		if(option['t']) {
			option['t'] = 0;
			if((i+1)<argc && sscanf(argv[i+1], "%lf", &threshold) == 1)
				i++;
		}
		if(option['y']) {
			option['y'] = 0;
			if((i+1)<argc && sscanf(argv[i+1], "%c", &type) == 1)
				i++;
		}
	if(option['h']) {
			printf("%s\n", HELPMESSAGE);
			exitProg(ExitOk, NULL);
		}
	}
	if (i>=argc || sscanf(argv[i++], "%s", inputFileName) != 1) exitProg(ErrorArgument, HELPMESSAGE);
	if (i>=argc || sscanf(argv[i++], "%s", outputFileName) != 1) exitProg(ErrorArgument, HELPMESSAGE);

	switch(typeAlphabet) {
		case 'd':
			table = (char*) monmalloc((strlen(DNA)+1)*sizeof(char));
			strcpy(table, DNA);
			break;
		case 'r':
			table = (char*) monmalloc((strlen(RNA)+1)*sizeof(char));
			strcpy(table, RNA);
			break;
		case 'p':
			table = (char*) monmalloc((strlen(PRO)+1)*sizeof(char));
			strcpy(table, PRO);
			break;
		case '?':
		default:
			table = (char*) monmalloc(sizeof(char));
			table[0] = '\0';
	}
	if(fi = fopen(inputFileName, "r")) {
		aln = readAlignement(fi, table, typeAlphabet == '?');
		switch(typeAlphabet) {
			case 'd':
			case 'r':
				aln.ambiguity = getXNAAmbiguity();
				break;
			case 'p':
				aln.ambiguity = getProteinAmbiguity();
				break;
			case '?':
			default:
				aln.ambiguity.number = 0;
		}
		aln.cardinal -= aln.ambiguity.number;
		fclose(fi);
	} else {
		exitProg(ErrorReading, inputFileName);
	}
	fixAlignmentAmbiguity(&aln);
	set=toSequences(&aln);

	if(!(fo = fopen(outputFileName, "w")))
		exitProg(ErrorWriting, outputFileName);
	distA = computeWholeDistancePairAln(aln, computeNorm1Aln);
	scheme = (TypeCodeScheme*) monmalloc(sizeof(TypeCodeScheme));
	scheme->suffixTree = getSuffixTree(set);
	scheme->code = (TypePosition*) monmalloc(scheme->suffixTree->size*sizeof(TypePosition));
	scheme->buffSize = INC_SIZE_CODE;
	scheme->lengthCode = (TypePosition*) monmalloc(scheme->buffSize*sizeof(TypePosition));
	if(type == 't') {
		int l;
		model = estimateMarkovModel(set);
//		for(thre=tmin; thre<=tmax; thre *= 10.0) {
		for(l=tmin; l<=-1; l++) {
			double t;
			int k;
			thre = pow(10.0, (double) l);
			for(k=0; k<10; k++) {
//			for(t=thre; t<thre*10; t+=thre) {
				double corr, sc;
				TypeSetOfSequences *dec;
				t = ((double)k+1.)*thre;
				scheme->cardCode = 0;
				buildCodeThreshold(t, scheme->suffixTree->root, 0, 1., model, scheme);
//printLengthDistribution(stdout, scheme->lengthCode,scheme->cardCode);
				dec = getDecodedFromScheme(scheme);
//printf("cardinal dec = %ld\n", dec->cardinal);
				distB = computeWholeDistanceDec(dec);
				corr = computeCorrelation(distA, distB);
				monfree((void*)distB.table);
				sc = score(dec);
				printf("%lE\t%lf\t%.2lf\n", t, corr, sc);
				fprintf(fo, "%lE\t%lf\t%.2lf\n", t, corr, sc);
				for(n=0; n<dec->number; n++)
					monfree((void*) dec->sequence[n]);
				monfree((void*) dec->sequence);
				monfree((void*) dec->size);
				monfree((void*) dec);
			}
		}
		fprintf(stdout, "\n\n%.4lE\n\n", findMode(set, qmin, qmax, qprec, scheme, model));
		freeModel(model);
	} else {
		for(l = lmax; l>=1; l--) {
			double corr;
			TypeSetOfSequences *dec;
			scheme->cardCode = 0;
			buildCodeLength(l, scheme->suffixTree->root, 0, scheme);
//printLengthDistribution(stdout, scheme->lengthCode,scheme->cardCode);
			dec = getDecodedFromScheme(scheme);
//printf("cardinal dec = %ld\n", dec->cardinal);
			distB = computeWholeDistanceDec(dec);
			corr = computeCorrelation(distA, distB);
			monfree((void*)distB.table);
			fprintf(fo, "%ld\t%lf\n", l, corr);
			fprintf(stdout, "%ld\t%lf\n", l, corr);
			for(n=0; n<dec->number; n++)
				monfree((void*) dec->sequence[n]);
			monfree((void*) dec->sequence);
			monfree((void*) dec->size);
			monfree((void*) dec);
		}
	}
		
	freeScheme(scheme);
	monfree((void*)distA.table);
	fprintf(stdout, "\n\n%ld\n\n", totalLength(*set));
	monfree((void*)set->size);
	for(n=0; n<set->number; n++)
		monfree((void*)set->sequence[n]);
	monfree((void*)set->sequence);
	monfree((void*)set);
	fclose(fo);
/*	sprintf(bufferOutput, "%s_Ali.nex", outputFileName);
	if(!(fo = fopen(bufferOutput, "w")))
		exitProg(ErrorWriting, bufferOutput);
	printDistanceNexus(fo, distA);
	fclose(fo);
	sprintf(bufferOutput, "%s_New.nex", outputFileName);
	if(!(fo = fopen(bufferOutput, "w")))
		exitProg(ErrorWriting, bufferOutput);
	printDistanceNexus(fo, distB);
	fclose(fo);
*/
;
	exitProg(ExitOk,NULL);
	return 0;
}
void freeOptimizer(emb_optimizer optim)
{
	freeModel(myModel);
	return;
}
Exemplo n.º 16
0
int main(int argc, char **argv) {		
	TypePosition orderstart=1, orderend=10, length = 10;
	char option[256], inputFileName[SIZE_BUFFER_CHAR], outputFileName[SIZE_BUFFER_CHAR], bufferOutput[SIZE_BUFFER_CHAR], *table, 
	outputFormat = 'r', typeDec = 'l', typeAlphabet = 'd', typeCalc = 'g';
	TypeSetOfSequences set;
	int fixed = 0, flagThre = 1;
	double threshold = 0.001, tmin = -25, tmax = -3, tprec = 0.5;
/*	TypeDistFunction *distfunc[MAX_FUNC]=
	{computeProba, computeKullbackLeiber1, computePham, computeCommon, computeCommonBis, computeGillesPham, computeMatchesBis, computeMatches, computeAlex, computeAlexBis};
*/		
	FILE *fi, *fo;
	int i = 1, typeDist = 0;

	for(i=0; i<256; i++)
		option[i] = 0;
	for(i=1; i<argc && *(argv[i]) == '-'; i++) {
		int j;
		for(j=1; argv[i][j] != '\0'; j++)
			option[argv[i][j]] = 1;
		if(option['f']) {
			option['f'] = 0;
			if((i+1)<argc && sscanf(argv[i+1], "%c", &outputFormat) == 1)
				i++;
		}
		if(option['s']) {
			option['s'] = 0;
			if((i+1)<argc && sscanf(argv[i+1], "%c", &typeAlphabet) == 1)
				i++;
		}
		if(option['c']) {
			option['c'] = 0;
			if((i+1)<argc && sscanf(argv[i+1], "%c", &typeCalc) == 1)
				i++;
		}
		if(option['m']) {
			option['m'] = 0;
			if((i+1)<argc && sscanf(argv[i+1], "%d", &typeDist) == 1)
				i++;
			if(typeDist >= MAX_FUNC)
				typeDist = 0;
		}
		if(option['t']) {
			option['t'] = 0;
			if((i+1)<argc && sscanf(argv[i+1], "%lf", &threshold) == 1)
				i++;
			flagThre = 1;
		}
		if(option['l']) {
			option['l'] = 0;
			if((i+1)<argc && sscanf(argv[i+1], "%ld", &length) == 1)
				i++;
			flagThre = 0;
		}
		if(option['h']) {
			printf("%s\n", HELPMESSAGE);
			exitProg(ExitOk, NULL);
		}
	}
	if (i>=argc || sscanf(argv[i++], "%s", inputFileName) != 1) exitProg(ErrorArgument, HELPMESSAGE);
	if (i>=argc || sscanf(argv[i++], "%s", outputFileName) != 1) exitProg(ErrorArgument, HELPMESSAGE);

	switch(typeAlphabet) {
		case 'd':
			table = (char*) monmalloc((strlen(DNA)+1)*sizeof(char));
			strcpy(table, DNA);
			break;
		case 'r':
			table = (char*) monmalloc((strlen(RNA)+1)*sizeof(char));
			strcpy(table, RNA);
			break;
		case 'p':
			table = (char*) monmalloc((strlen(PRO)+1)*sizeof(char));
			strcpy(table, PRO);
			break;
		case '?':
		default:
			table = (char*) monmalloc(sizeof(char));
			table[0] = '\0';
	}
	if(fi = fopen(inputFileName, "r")) {
		set = readSequencesFasta(fi, table, typeAlphabet == '?');
		switch(typeAlphabet) {
			case 'd':
			case 'r':
				set.ambiguity = getXNAAmbiguity();
				break;
			case 'p':
				set.ambiguity = getProteinAmbiguity();
				break;
			case '?':
			default:
				set.ambiguity.number = 0;
		}
		set.cardinal -= set.ambiguity.number;
		fclose(fi);
	} else {
		exitProg(ErrorReading, inputFileName);
	}
	
	if(fo = fopen(outputFileName, "w")) {
		TypeSetOfSequences *dec;
		TypeDistance dist;
		double tmid, t, smax, tres, sc,  scl, scr;
		TypeNumber n;
		TypeCodeScheme *scheme;
		TypeMarkovModel *model;

		fixSequencesAmbiguity(&set);
		scheme = (TypeCodeScheme*) monmalloc(sizeof(TypeCodeScheme));
		scheme->suffixTree = getSuffixTree(&set);
		scheme->code = (TypePosition*) monmalloc(scheme->suffixTree->size*sizeof(TypePosition));
		scheme->buffSize = INC_SIZE_CODE;
		scheme->lengthCode = (TypePosition*) monmalloc(scheme->buffSize*sizeof(TypePosition));
		model = estimateMarkovModel(&set);
		while((tmax-tmin)>4*tprec) {
			tmid = (tmax+tmin)/2.;
			scheme->cardCode = 0;
			buildCodeThreshold(exp(tmid-3.*tprec/2.), scheme->suffixTree->root, 0, 1., model, scheme);
			dec = getDecodedFromScheme(scheme);
			scl = score(dec);
			for(n=0; n<dec->number; n++)
				monfree((void*) dec->sequence[n]);
			monfree((void*) dec->sequence);
			monfree((void*) dec->size);
			monfree((void*) dec);
			scheme->cardCode = 0;
			buildCodeThreshold(exp(tmid+3.*tprec/2.), scheme->suffixTree->root, 0, 1., model, scheme);
			dec = getDecodedFromScheme(scheme);
			scr = score(dec);
			for(n=0; n<dec->number; n++)
				monfree((void*) dec->sequence[n]);
			monfree((void*) dec->sequence);
			monfree((void*) dec->size);
				monfree((void*) dec);
			if(scl>scr)
				tmax = tmid+3.*tprec/2.;
			else
				tmin = tmid-3.*tprec/2.;
		}
		if(scl>scr) {
			smax = scl;
			tres = exp(tmid-3.*tprec/2.);
		} else {
			smax = scr;
			tres = exp(tmid+3.*tprec/2.);
		}
		scheme->cardCode = 0;
		buildCodeThreshold(exp(tmid), scheme->suffixTree->root, 0, 1., model, scheme);
		dec = getDecodedFromScheme(scheme);
		sc = score(dec);
		for(n=0; n<dec->number; n++)
			monfree((void*) dec->sequence[n]);
		monfree((void*) dec->sequence);
		monfree((void*) dec->size);
		monfree((void*) dec);
		if(sc>smax) {
			smax = scl;
			tres = exp(tmid);
		}
printf("%.4lE\t%lf\n", tres, smax);
		scheme->cardCode = 0;
		buildCodeThreshold(tres, scheme->suffixTree->root, 0, 1., model, scheme);
		dec = getDecodedFromScheme(scheme);
		freeModel(model);
		freeScheme(scheme);
		dist = computeWholeDistanceDec(dec);
		switch(outputFormat) {
			case 't':
				printDistanceTable(fo, dist);
				break;
			case 'r':
				printDistanceRaw(fo, dist);
				break;
			case 'p':
				printDistancePhylip(fo, dist);
				break;
			case 'n':
				printDistanceNexus(fo, dist);
		}
		fclose(fo);
	} else {
		exitProg(ErrorWriting, outputFileName);
	}
	exitProg(ExitOk,NULL);
	return 0;
}
Exemplo n.º 17
0
void myKeyHandler(unsigned char ch, int x, int y)
{
  int i;
  static int subdiv=0;
  struct point_t *slice;
  struct point_t *linecur;
  struct point_t *cur;
  struct point_t *new_points;

  struct slice_t *cur_slice,*cur2_slice;
  struct point_t *cur2;
  struct point_t points[5];
  double a,b,c;

  GLfloat v1[3],v2[3],v3[3];

  double deginc;

  //  struct slice_t *cur_slice;

  switch(ch)
    {
    case 'q':
      endSubdiv(0);
      break;

    case 'z':
      mode=(~mode)&1;
      printf("%s\n",mode?"3D mode":"2D mode");
      switch(mode)
	{
	case 0:
	  resetCamera();
	  break;
	case 1:
	  reset3DCamera();
	  break;
	}
      break;

    case 'k':
      /* test phong stuff */
      cur_slice = slices;
      cur2_slice = slices->n;
      //while(cur_slice!=NULL)
	{
	  cur = cur_slice->line;
	  cur2 = cur2_slice->line;
	  //while(cur->n!=NULL)
	    {
	      /* right vertex */
	      add_vec(&(cur->nx),&(cur->n->nx),&(points[0].nx));
	      normalize(&(points[0].nx));
	      sub_vec(&(cur->n->x),&(cur->x),v1);
	      v1[0] /= 2; v1[1] /= 2; v1[2] /= 2;
	      add_vec(&(cur->x),v1,&(points[0].x));
	      
	      /* top vertex */
	      add_vec(&(cur->nx),&(cur2->nx),&(points[1].nx));
	      normalize(&(points[1].nx));
	      sub_vec(&(cur2->x),&(cur->x),v1);
	      v1[0] /= 2; v1[1] /= 2; v1[2] /= 2;
	      add_vec(&(cur->x),v1,&(points[1].x));
	      
	      /* left vertex */
	      add_vec(&(cur2->nx),&(cur2->n->nx),&(points[2].nx));
	      normalize(&(points[2].nx));
	      sub_vec(&(cur2->n->x),&(cur2->x),v1);
	      v1[0] /= 2; v1[1] /= 2; v1[2] /= 2;
	      add_vec(&(cur2->x),v1,&(points[2].x));
	      
	      /* bottom vertex */
	      add_vec(&(cur2->n->nx),&(cur->n->nx),&(points[3].nx));
	      normalize(&(points[3].nx));
	      sub_vec(&(cur->n->x),&(cur2->n->x),v1);
	      v1[0] /= 2; v1[1] /= 2; v1[2] /= 2;
	      add_vec(&(cur2->n->x),v1,&(points[3].x));
	      
	      /* center vertex */
	      add_vec(&(points[0].nx),&(points[1].nx),v1);
	      add_vec(&(points[2].nx),&(points[3].nx),v2);
	      add_vec(v1,v2,&(points[4].nx));
	      normalize(&(points[4].nx));
	      sub_vec(&(points[3].x),&(cur2->n->x),v1);
	      sub_vec(&(points[2].x),&(cur2->n->x),v2);
	      add_vec(v1,v2,v3);
	      normalize(v3);
	      a=sqrt(v1[0]*v1[0]+v1[1]*v1[1]+v1[2]*v1[2]);
	      b=sqrt(v2[0]*v2[0]+v2[1]*v2[1]+v2[2]*v2[2]);
	      c=sqrt(a*a+b*b);
	      v3[0] *= c; v3[1] *= c; v3[2] *= c;
	      add_vec(&(cur2->n->x),v3,&(points[4].x));

	      printf("v2[0]=%f,v2[1]=%f,v2[2]=%f\nv3[0]=%f,v3[1]=%f,v3[2]=%f\n",v2[0],v2[1],v2[2],v3[0],v3[1],v3[2]);

	      for(i=0; i<5; i++)
		printf("points[%d]->x=%f,points[%d]->y=%f,points[%d]->z=%f\n",
		       i,points[i].x,i,points[i].y,i,points[i].z);
	      printf("cur->x=%f,cur->y=%f,cur->z=%f\ncur->n->x=%f,cur->n->y=%f,cur->n->z=%f\n",
		     cur->x,cur->y,cur->z,cur->n->x,cur->n->y,cur->n->z);
	      printf("cur2->x=%f,cur2->y=%f,cur2->z=%f\ncur2->n->x=%f,cur2->n->y=%f,cur2->n->z=%f\n",
		     cur2->x,cur2->y,cur2->z,cur2->n->x,cur2->n->y,cur2->n->z);

	      cur = cur->n;
	      cur2 = cur2->n;
	    }

	  cur_slice = cur_slice->n;
	  cur2_slice = cur2_slice->n != NULL ? cur2_slice->n : slices; /* circle around */
	}
      break;

    case 'n':
      normals=(~normals)&1;
      printf("Normal mode %s\n",normals?"on":"off");
      break;

    case 'e':
      solid=(~solid)&1;
      printf("%s\n",solid?"Solid mode":"Wireframe mode");
      switch(solid)
	{
	case 0:
	  glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
	  break;
	case 1:
	  glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
	  break;
	}
      break;

    case 'r':
      faces=(~faces)&1;
      printf("%s\n",faces?"Faces mode":"Control points mode");
      break;

    case 'w': /* calculate initial 3d object */
      if(num<5)
	printf("There must be at least 5 control points.\n");
      else if(!mode)
	{
	  mode=(~mode)&1;
	  printf("%s\n",mode?"3D mode":"2D mode");
	  switch(mode)
	    {
	    case 0:
	      resetCamera();
	      break;
	    case 1:
	      reset3DCamera();
	      break;
	    }
	  freeModel();
	  subdiv_v = 0;
	  subdiv_h = NUMSLICES;

	  /* the radius of the circle for each of the points is x */
	  for(i=0;i<subdiv_h;i++)
	    {
	      ALLOC_POINT(slice);
	      cur=slice;

	      linecur=line;
	      while(linecur!=NULL)
		{
		  cur->z = linecur->x*sin(DEGINC*i);
		  cur->x = linecur->x*cos(DEGINC*i);
		  cur->y = linecur->y;

		  linecur = linecur->n;
		  if(linecur!=NULL)
		    {
		      ALLOC_POINT(cur->n);
		      cur = cur->n;
		    }
		}

	      addSlice(slice);
	    }
	}

      recompute_normals();

      break;
     
    case 's': /* horizontal subdivision */

      if(!mode || slices==NULL) break;

      /* backup the original slice */
      new_points = duplicate_slice(slices->line);
      freeModel();

      subdiv_h<<=1;
      subdiv++;
      printf("Horizontal subdivision level %d\n",subdiv);
     
      deginc = 2*M_PI/subdiv_h;

      for(i=0;i<subdiv_h;i++)
	{
	  ALLOC_POINT(slice);
	  cur=slice;

	  linecur=new_points;
	  while(linecur!=NULL)
	    {
	      cur->z = linecur->x*sin(deginc*i);
	      cur->x = linecur->x*cos(deginc*i);
	      cur->y = linecur->y;

	      linecur = linecur->n;
	      if(linecur!=NULL)
		{
		  ALLOC_POINT(cur->n);
		  cur = cur->n;
		}
	    }

	  addSlice(slice);
	}

      recompute_normals();

      break;

    case 'a': /* vertical subdivision */

      if(!mode || slices==NULL) break;
      cur_slice=slices;
      
      subdiv_v++;
      printf("Vertical subdivision level %d\n",subdiv_v);
            
      linecur = cur_slice->line;
      /* calc the first point */
      cur = new_points = calc_point(linecur,linecur,linecur->n,linecur->n->n);
      
      /* calc middle and last points */
      while(linecur->n->n!=NULL)
	{
	  if(linecur->n->n->n!=NULL) /* middle points */
	    cur->n = calc_point(linecur,linecur->n,linecur->n->n,linecur->n->n->n);
	  else
	    cur->n = calc_point(linecur,linecur->n,linecur->n->n,linecur->n->n);
	  cur = cur->n;
	  linecur = linecur->n;
	}
      
      interleave(cur_slice->line,new_points);
      
      new_points = duplicate_slice(cur_slice->line);
      
      deginc = 2*M_PI/subdiv_h;

      freeModel();

      for(i=0;i<subdiv_h;i++)
	{
	  ALLOC_POINT(slice);
	  cur=slice;

	  linecur=new_points;
	  while(linecur!=NULL)
	    {
	      cur->z = linecur->x*sin(deginc*i);
	      cur->x = linecur->x*cos(deginc*i);
	      cur->y = linecur->y;

	      linecur = linecur->n;
	      if(linecur!=NULL)
		{
		  ALLOC_POINT(cur->n);
		  cur = cur->n;
		}
	    }
	  
	  addSlice(slice);
	}

      recompute_normals();

	break;

    case 'd':
      shading=(~shading)&1;
      printf("%s shading\n",shading?"Phong":"Gouraud");
      break;

    case '<':
      if(mode)
	{
	  glMatrixMode(GL_MODELVIEW);
	  glRotatef(1,0.0,1.0,0.0);
	}
      break;
    case '>':
      if(mode)
	{
	  glMatrixMode(GL_MODELVIEW);
	  glRotatef(-1,0.0,1.0,0.0);
	}
      break;

    default:
      /* Unrecognized keypress */
      return;
    }
  
  glutPostRedisplay();
  
  return;
}