Exemple #1
0
void Importer::importSceneFile(const QFileInfo& file, const QString& targetFileName)
{
	QFile sceneFile(file.absoluteFilePath());
	if (!sceneFile.open(QIODevice::ReadOnly))
	{
		m_errorLog << QObject::tr("Error opening file %1").arg(sceneFile.fileName());
		return;
	}
	QDomDocument root;
	root.setContent(&sceneFile);
	sceneFile.close();
	QFileInfo target(m_targetResourcePath, targetFileName);
	if( !target.absoluteDir().exists() )
		m_targetResourcePath.mkpath(target.absolutePath());

	if (!sceneFile.copy(target.absoluteFilePath()))
	{
		CopyJob job(file, target);
		if (!m_filesToOverwrite.contains(job) && !m_alreadyCopied.contains(job))
			m_filesToOverwrite.append(job);	
	}
	else
		m_alreadyCopied.append(CopyJob(file, target));
	importEffectElement(root.documentElement());
	importMaterialElement(root.documentElement());
	importGeometrieElement(root.documentElement());	
	importSceneElement(root.documentElement());
}
Exemple #2
0
void Scene::Parse(std::string sceneFilename)
{
	BeganParsing();

	std::ifstream sceneFile(sceneFilename.c_str());

	// Die if we couldn't find the file
	if (sceneFile.fail())
	{
		printf("Scene::Parse - Could not find input scene file '%s'\n", sceneFilename.c_str());
		exit(1);
	}

	char line[1024];
	while (!sceneFile.eof())
	{
		sceneFile.getline(line, 1023);
		std::stringstream ss;
		ss.str(line);
		std::string command;
		ss >> command;

		if (command == "Camera")
		{
			float ex, ey, ez, ux, uy, uz, lx, ly, lz, f, a;
			ss >> ex >> ey >> ez >> ux >> uy >> uz >> lx >> ly >> lz >> f >> a;
			Pnt3f eye(ex, ey, ez);
			Vec3f up(ux, uy, uz);
			Pnt3f lookAt(lx, ly, lz);
			ParsedCamera(eye, up, lookAt, f, a);
		}
		else if (command == "Output")
/*
* public:
*/
ScenePointer SceneLoader::loadScene(const QString &filePath) const {
  QFile sceneFile(filePath);

  sceneFile.open(QIODevice::ReadOnly);
  if (!sceneFile.isOpen()) {
    std::cerr << "Unable to open file at path '" << filePath.toUtf8().constData() << "'" << std::endl;
    return ScenePointer(NULL);
  }

  QDomDocument document;
  QString errorMessge;
  int errorLine, errorColumn;

  if (!document.setContent(&sceneFile, &errorMessge, &errorLine, &errorColumn)) {
    std::cerr << "XML parsing error at line " << errorLine << ", column " << errorColumn << ": " << errorMessge.toUtf8().constData() << std::endl;
    return ScenePointer(NULL);    
  }

  QDomElement rootElement = document.documentElement();
  ScenePointer scene = readScene(rootElement);
  if (scene == NULL) {
    std::cerr << "Failed scene file parsing, check scene format" << std::endl;
  }

  return scene;
}
Exemple #4
0
void Scene::Parse(std::string sceneFilename)
{
	BeganParsing();

	std::ifstream sceneFile(sceneFilename.c_str());
	char line[1024];
	while (!sceneFile.eof())
	{
		sceneFile.getline(line, 1023);
		std::stringstream ss;
		ss.str(line);
		std::string command;
		ss >> command;

		if (command == "Camera")
		{
			float ex, ey, ez, ux, uy, uz, lx, ly, lz, f, a;
			ss >> ex >> ey >> ez >> ux >> uy >> uz >> lx >> ly >> lz >> f >> a;
			STPoint3 eye(ex, ey, ez);
			STVector3 up(ux, uy, uz);
			STPoint3 lookAt(lx, ly, lz);
			ParsedCamera(eye, up, lookAt, f, a);
		}
		else
		if (command == "Output")
Exemple #5
0
int main(int argv, char **argc) {

	Scene *scene = new Scene();

	std::ifstream sceneFile("scene.txt");

	if (!sceneFile)
		return 123;

	std::string s((std::istreambuf_iterator<char>(sceneFile)), std::istreambuf_iterator<char>());

	JsonGroup json(s);
	JsonArray objects(json.at("objects").Array());
	JsonArray lights(json.at("lights").Array());
	JsonGroup camera(json.at("camera").Group());

	Camera cam = Camera(Vector3D(camera.at("position").Array().at(0).Float(), camera.at("position").Array().at(1).Float(), camera.at("position").Array().at(2).Float()), Vector3D(camera.at("target").Array().at(0).Float(), camera.at("target").Array().at(1).Float(), camera.at("target").Array().at(2).Float()), camera.at("roll").Float());

	for (int i = 0; i < objects.size(); i++){
		JsonGroup object = objects.at(i).Group();

		if (object.at("type").String().compare("sphere") == 0){
			scene->add(new SphereObject(Vector3D(object.at("position").Array().at(0).Float(), object.at("position").Array().at(1).Float(), object.at("position").Array().at(2).Float()),
				object.at("radius").Float(), Color(object.at("color").Array().at(0).Integer(), object.at("color").Array().at(1).Integer(), object.at("color").Array().at(2).Integer()), object.at("reflection").Float(), object.at("refraction").Float(), object.at("ior").Float()));
		}

		if (object.at("type").String().compare("plane") == 0){
			scene->add(new PlaneObject(Vector3D(object.at("position").Array().at(0).Float(), object.at("position").Array().at(1).Float(), object.at("position").Array().at(2).Float()),
				Vector3D(object.at("normal").Array().at(0).Float(), object.at("normal").Array().at(1).Float(), object.at("normal").Array().at(2).Float()),
				Color(object.at("color").Array().at(0).Array().at(0).Integer(), object.at("color").Array().at(0).Array().at(1).Integer(), object.at("color").Array().at(0).Array().at(2).Integer()),
				Color(object.at("color").Array().at(1).Array().at(0).Integer(), object.at("color").Array().at(1).Array().at(1).Integer(), object.at("color").Array().at(1).Array().at(2).Integer()), object.at("reflection").Float(), object.at("refraction").Float(), object.at("ior").Float()));
		}

		if (object.at("type").String().compare("triangle") == 0){
			scene->add(new TriangleObject(Vector3D(object.at("vertices").Array().at(0).Array().at(0).Integer(), object.at("vertices").Array().at(0).Array().at(1).Integer(), object.at("vertices").Array().at(0).Array().at(2).Integer()),
				Vector3D(object.at("vertices").Array().at(1).Array().at(0).Integer(), object.at("vertices").Array().at(1).Array().at(1).Integer(), object.at("vertices").Array().at(1).Array().at(2).Integer()),
				Vector3D(object.at("vertices").Array().at(2).Array().at(0).Integer(), object.at("vertices").Array().at(2).Array().at(1).Integer(), object.at("vertices").Array().at(2).Array().at(2).Integer()),
				Color(object.at("color").Array().at(0).Integer(), object.at("color").Array().at(1).Integer(), object.at("color").Array().at(2).Integer()), object.at("reflection").Float(), object.at("refraction").Float(), object.at("ior").Float()));
		}
	}

	for (int i = 0; i < lights.size(); i++){
		JsonGroup light = lights.at(i).Group();

		if (light.at("type").String().compare("point") == 0){
			scene->add(new PointLight(Vector3D(light.at("position").Array().at(0).Float(), light.at("position").Array().at(1).Float(), light.at("position").Array().at(2).Float())));
		}

		if (light.at("type").String().compare("direction") == 0){
			scene->add(new DirectionLight(Vector3D(light.at("direction").Array().at(0).Float(), light.at("direction").Array().at(1).Float(), light.at("direction").Array().at(2).Float())));
		}
	}

    Renderer *renderer = new Renderer();
	PixelBuffer *buffer = renderer->render(scene, &cam, camera.at("resolution").Array().at(0).Integer(), camera.at("resolution").Array().at(1).Integer(), camera.at("raydepth").Integer());
	//buffer->savePPM("test.ppm");
	buffer->saveBMP("image.bmp");
    return 0;
}
Exemple #6
0
void Scene::ReadObjFile(const char* fileName)
{
    posSize[ROBOT_ROT] = 2*Pi;
    posSize[ROBOT_ARM0] = posSize[ROBOT_ARM1] = Pi/2.;
    negSize[ROBOT_ROT] = 0;
    negSize[ROBOT_ARM0] = negSize[ROBOT_ARM1] = -Pi/2.;
    posSize[ROBOT_X] = posSize[ROBOT_Z] = negSize[ROBOT_X] = negSize[ROBOT_Z] = 0;
    posSize[BALL_X] = posSize[BALL_Y] = posSize[BALL_Z] = 0;
    negSize[BALL_X] = negSize[BALL_Y] = negSize[BALL_Z] = 0;

    std::ifstream sceneFile(fileName);
    while(!sceneFile.eof())
    {
        Point p;
        std::array<int, 3> triangle;

        switch(sceneFile.get())
        {
        case 'v':
            sceneFile >> p[0] >> p[1] >> p[2];
            staticScene.points.push_back(p);

            if(p[X] > posSize[ROBOT_X])
                posSize[ROBOT_X] = p[X];
            else if(p[X] < negSize[ROBOT_X])
                negSize[ROBOT_X] = p[X];

            if(p[Z] > posSize[ROBOT_Z])
                posSize[ROBOT_Z] = p[Z];
            else if(p[Z] < negSize[ROBOT_Z])
                negSize[ROBOT_Z] = p[Z];
            break;
        case 'f':
            sceneFile >> triangle[0] >> triangle[1] >> triangle[2];
            triangle -= 1;
            staticScene.triangles.push_back(triangle);
            break;
        case '\n':
            break;
        default:
            sceneFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }

    maxSize=0;
    for(auto x : posSize)
        maxSize = std::max(maxSize, x);
    for(auto x : negSize)
        maxSize = std::max(maxSize, -x);
}
void GameControllerAttachment::sceneFileConfig()
{
	QDomDocument sceneFile(m_sceneFile->sceneFileDom());
	QDomElement pathNode(sceneFile.documentElement().firstChildElement("EnginePath"));
	// Create a wizard for the configuration of the directories
	QWizard wizard;
	PathPage* page = new PathPage(&wizard);	
	page->setDirectories( 
		pathNode.attribute("mediapath"), 
		pathNode.attribute("scriptpath")
	);
	wizard.addPage(page);
	if (wizard.exec() == QDialog::Accepted)
	{
		pathNode.setAttribute("mediapath", wizard.field("mediadir").toString());
		pathNode.setAttribute("scriptpath", wizard.field("scriptdir").toString());
	}
}
Exemple #8
0
bool TupFileManager::save(const QString &fileName, TupProject *project)
{
    #ifdef K_DEBUG
        QString msg = "TupFileManager::save() - Saving file -> " + fileName;
            #ifdef Q_OS_WIN32
                qWarning() << msg;
            #else
                tWarning() << msg;
        #endif
    #endif

	/* 
    int indexPath = fileName.lastIndexOf(QDir::separator());
    int indexFile = fileName.length() - indexPath;
    QString name = fileName.right(indexFile - 1);
    int indexDot = name.lastIndexOf(".");
    name = name.left(indexDot);
    */
	
	QFileInfo info(fileName);
	QString name = info.baseName();	
    QString oldDirName = CACHE_DIR + project->projectName();
    QDir projectDir(oldDirName);

    if (name.compare(project->projectName()) != 0) {
        project->setProjectName(name);
        projectDir.setPath(CACHE_DIR + name);    
        project->library()->updatePaths(CACHE_DIR + name);
        if (!projectDir.exists()) {
            if (projectDir.rename(oldDirName, projectDir.path())) {
                #ifdef K_DEBUG
                    QString msg = "TupFileManager::save() - Directory renamed to -> " + projectDir.path(); 
                    #ifdef Q_OS_WIN32
                        qWarning() << msg;
                    #else
                        tWarning() << msg;
                    #endif
                #endif
            } else {
                // SQA: Check if these lines are really needed
                if (! projectDir.mkdir(projectDir.path())) {
                    #ifdef K_DEBUG
                        QString msg = "TupFileManager::save() - Error: Can't create path -> " + projectDir.path();
                        #ifdef Q_OS_WIN32
                            qDebug() << msg;
                        #else
                            tError() << msg;
                        #endif
                    #endif
                    return false;
                } else {
                    #ifdef K_DEBUG
                        QString msg = "TupFileManager::save() - Directory was created successfully -> " + projectDir.path();
                        #ifdef Q_OS_WIN32
                            qWarning() << msg;
                        #else
                            tWarning() << msg;
                        #endif
                    #endif
                }
            }
        }
    } else {
        if (!projectDir.exists()) {
            if (! projectDir.mkdir(projectDir.path())) {
                #ifdef K_DEBUG
                    QString msg = "TupFileManager::save() - Error: Can't create path -> " + projectDir.path();
                    #ifdef Q_OS_WIN32
                        qDebug() << msg;
                    #else
                        tError() << msg;
                    #endif
                #endif
                return false;
            } else {
                #ifdef K_DEBUG
                    QString msg = "TupFileManager::save() - Directory was created successfully -> " + projectDir.path();
                    #ifdef Q_OS_WIN32
                        qWarning() << msg;
                    #else
                        tWarning() << msg;
                    #endif
                #endif
            }
        }
    }

    {
     // Save project
     QFile projectFile(projectDir.path() + QDir::separator() + "project.tpp");

     if (projectFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
         QTextStream ts(&projectFile);
         QDomDocument doc;
         project->setProjectName(name);
         doc.appendChild(project->toXml(doc));
         ts << doc.toString();
         projectFile.close();
     } else {
         #ifdef K_DEBUG
             QString msg = "TupFileManager::save() - Error: Can't create file -> " + projectDir.path() + QDir::separator() + "project.tpp";
             #ifdef Q_OS_WIN32
                 qDebug() << msg;
             #else
                 tError() << msg;
             #endif
         #endif
     }
    }

    // Save scenes
    {
     int index = 0;
     int totalScenes = project->scenes().size();
     for (int i = 0; i < totalScenes; i++) {
          TupScene *scene = project->scenes().at(i);
          QDomDocument doc;
          doc.appendChild(scene->toXml(doc));
          QString scenePath = projectDir.path() + QDir::separator() + "scene" + QString::number(index) + ".tps";
          QFile sceneFile(scenePath);

          if (sceneFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
              QTextStream st(&sceneFile);
              st << doc.toString();
              index += 1;
              sceneFile.close();
          } else {
              #ifdef K_DEBUG
                  QString msg = "TupFileManager::save() - Error: Can't create file -> " + scenePath;
                  #ifdef Q_OS_WIN32
                      qDebug() << msg;
                  #else
                      tError() << msg;
                  #endif
              #endif
          }
     }
    }

    {
     // Save library
     QFile lbr(projectDir.path() + QDir::separator() + "library.tpl");

     if (lbr.open(QIODevice::WriteOnly | QIODevice::Text)) {
         QTextStream ts(&lbr);

         QDomDocument doc;
         doc.appendChild(project->library()->toXml(doc));

         ts << doc.toString();
         lbr.close();
     } else {
         #ifdef K_DEBUG
             QString msg = "TupFileManager::save() - Error: Can't create file -> " + projectDir.path() + QDir::separator() + "library.tpl";
             #ifdef Q_OS_WIN32
                 qDebug() << msg;
             #else
                 tError() << msg;
             #endif
         #endif
     }
    }

    TupPackageHandler packageHandler;
    bool ok = packageHandler.makePackage(projectDir.path(), fileName);

    if (ok) {
        #ifdef K_DEBUG
            QString msg = "TupFileManager::save() - Project saved in -> " + fileName;
            #ifdef Q_OS_WIN32
                qWarning() << msg;
            #else
                tWarning() << msg;
            #endif
        #endif
    } else {
        #ifdef K_DEBUG
            QString msg = "TupFileManager::save() - Error: Project couldn't be saved in -> " + fileName;
            #ifdef Q_OS_WIN32
                qDebug() << msg;
            #else
                tError() << msg;
            #endif
        #endif
    }

    return ok;
}
Exemple #9
0
int main(int argc, char** argv)
{
	float scale = 0.1f;
	float scaleTexV = -1.f;

	std::vector<Object> objects;
	std::ifstream inputFile(argv[1]);
	if (!inputFile.is_open())
	{
		printf("Failed to open %s", argv[1]);
		return -1;
	}

	if (argc != 3)
	{
		printf("Missing scene name");
		return -1;
	}
	std::string sceneName = argv[2];

	char line[1024];
	std::vector<Vec3> positions;
	std::vector<Vec3> normals;
	std::vector<Vec2> texcoords;

	Object* pActiveObj = nullptr;
	SubObject* pActiveSubObject = nullptr;

	int lineNum = 0;
	while (inputFile.getline(line, 1024))
	{
		++lineNum;

		char* context = nullptr;
		char* tok = strtok_s(line, " ", &context);
		if (!tok)
			continue;

		if (strcmp(tok, "v") == 0)
		{
			// Position
			Vec3 pos;
			pos.x = scale * (float)atof(strtok_s(nullptr, " ", &context));
			pos.y = scale * (float)atof(strtok_s(nullptr, " ", &context));
			pos.z = scale * (float)atof(strtok_s(nullptr, " ", &context));
			positions.push_back(pos);
		}
		else if (strcmp(tok, "vn") == 0)
		{
			// Normal
			Vec3 norm;
			norm.x = (float)atof(strtok_s(nullptr, " ", &context));
			norm.y = (float)atof(strtok_s(nullptr, " ", &context));
			norm.z = (float)atof(strtok_s(nullptr, " ", &context));
			normals.push_back(norm);
		}
		else if (strcmp(tok, "vt") == 0)
		{
			// Tex coord
			Vec2 uv;
			uv.x = (float)atof(strtok_s(nullptr, " ", &context));
			uv.y = (float)atof(strtok_s(nullptr, " ", &context)) * scaleTexV;
			texcoords.push_back(uv);
		}
		else if (strcmp(tok, "f") == 0)
		{
			// Face
			Vertex faceVerts[4];
			int numVerts = 0;

			while (context[0] != 0)
			{
				Vertex& rVert = faceVerts[numVerts];
				rVert.pos = atoi(strtok_s(nullptr, "/ ", &context)) - 1;
				rVert.uv = atoi(strtok_s(nullptr, "/ ", &context)) - 1;
				rVert.norm = atoi(strtok_s(nullptr, "/ ", &context)) - 1;

				++numVerts;
			}

			if (numVerts == 3)
			{
				pActiveSubObject->verts.push_back(faceVerts[0]);
				pActiveSubObject->verts.push_back(faceVerts[1]);
				pActiveSubObject->verts.push_back(faceVerts[2]);
			}
			else if (numVerts == 4)
			{
				pActiveSubObject->verts.push_back(faceVerts[0]);
				pActiveSubObject->verts.push_back(faceVerts[1]);
				pActiveSubObject->verts.push_back(faceVerts[2]);
				pActiveSubObject->verts.push_back(faceVerts[0]);
				pActiveSubObject->verts.push_back(faceVerts[2]);
				pActiveSubObject->verts.push_back(faceVerts[3]);
			}
			else
			{
				assert(false);
			}
		}
		else if (strcmp(tok, "g") == 0)
		{
			objects.emplace_back();
			pActiveObj = &objects.back();

			pActiveObj->name = strtok_s(nullptr, " ", &context);
		}
		else if (strcmp(tok, "usemtl") == 0)
		{
			pActiveObj->subobjects.emplace_back();
			pActiveSubObject = &pActiveObj->subobjects.back();

			pActiveSubObject->material = strtok_s(nullptr, " ", &context);
		}
	}

	Json::StyledStreamWriter jsonWriter;

	Json::Value jSceneRoot(Json::objectValue);

	// Camera
	{
		Json::Value jCamera(Json::objectValue);

		Json::Value jPos(Json::arrayValue);
		jPos[0] = 0.f;
		jPos[1] = 5.f;
		jPos[2] = 0.f;
		jCamera["position"] = jPos;

		Json::Value jRot(Json::arrayValue);
		jRot[0] = 0.f;
		jRot[1] = 0.f;
		jRot[2] = 0.f;
		jCamera["rotation"] = jRot;

		jSceneRoot["camera"] = jCamera;
	}

	jSceneRoot["sky"] = "cloudy";
	jSceneRoot["lights"] = Json::Value(Json::arrayValue);
	Json::Value& jSceneObjects = jSceneRoot["objects"] = Json::Value(Json::arrayValue);

	int numObjects = (int)objects.size();
	for (int i = 0; i < numObjects; ++i)
	{
		const Object& obj = objects[i];

		Vec3 minExtents = { FLT_MAX, FLT_MAX, FLT_MAX };
		Vec3 maxExtents = { -FLT_MAX, -FLT_MAX, -FLT_MAX };
		char str[256];

		for (unsigned int n = 0; n < obj.subobjects.size(); ++n)
		{
			const SubObject& subobj = obj.subobjects[n];
			for (unsigned int k = 0; k < subobj.verts.size(); ++k)
			{
				const Vertex& vert = subobj.verts[k];
				const Vec3& pos = positions[vert.pos];
				minExtents.x = min(minExtents.x, pos.x);
				minExtents.y = min(minExtents.y, pos.y);
				minExtents.z = min(minExtents.z, pos.z);
				maxExtents.x = max(maxExtents.x, pos.x);
				maxExtents.y = max(maxExtents.y, pos.y);
				maxExtents.z = max(maxExtents.z, pos.z);
			}
		}

		Vec3 center = { (maxExtents.x + minExtents.x) * 0.5f, minExtents.y, (maxExtents.z + minExtents.z) * 0.5f };

		std::string objFilename = "output/" + obj.name + ".obj";
		createDirectoryTreeForFile(objFilename);

		std::ofstream objFile(objFilename);
		assert(objFile.is_open());

		int posCount = 0;
		int uvCount = 0;
		int normCount = 0;

		for (unsigned int n = 0; n < obj.subobjects.size(); ++n)
		{
			const SubObject& subobj = obj.subobjects[n];

			// Build the obj file
			int posStart = INT_MAX;
			int posEnd = 0;
			int uvStart = INT_MAX;
			int uvEnd = 0;
			int normStart = INT_MAX;
			int normEnd = 0;

			for (unsigned int k = 0; k < subobj.verts.size(); ++k)
			{
				const Vertex& vert = subobj.verts[k];

				posStart = min(posStart, vert.pos);
				posEnd = max(posEnd, vert.pos);
				uvStart = min(uvStart, vert.uv);
				uvEnd = max(uvEnd, vert.uv);
				normStart = min(normStart, vert.norm);
				normEnd = max(normEnd, vert.norm);
			}

			// write positions
			for (int k = posStart; k <= posEnd; ++k)
			{
				const Vec3& pos = positions[k];
				sprintf_s(str, "v %f %f %f\n", (pos.x - center.x), (pos.y - center.y), (pos.z - center.z));
				objFile.write(str, strlen(str));
			}

			// write uvs
			for (int k = uvStart; k <= uvEnd; ++k)
			{
				const Vec2& uv = texcoords[k];
				sprintf_s(str, "vt %f %f\n", uv.x, uv.y);
				objFile.write(str, strlen(str));
			}

			// write normals
			for (int k = normStart; k <= normEnd; ++k)
			{
				const Vec3& normal = normals[k];
				sprintf_s(str, "vn %f %f %f\n", normal.x, normal.y, normal.z);
				objFile.write(str, strlen(str));
			}

			// write material to use for this subobject
			std::string materialName = sceneName + "/" + subobj.material;
			sprintf_s(str, "usemtl %s\n", materialName.c_str());
			objFile.write(str, strlen(str));

			// write faces
			for (unsigned int k = 0; k < subobj.verts.size(); k += 3)
			{
				const Vertex& vert1 = subobj.verts[k + 0];
				const Vertex& vert2 = subobj.verts[k + 1];
				const Vertex& vert3 = subobj.verts[k + 2];
				sprintf_s(str, "f %d/%d/%d %d/%d/%d %d/%d/%d\n",
					posCount + (vert1.pos - posStart + 1), uvCount + (vert1.uv - uvStart + 1), normCount + (vert1.norm - normStart + 1),
					posCount + (vert2.pos - posStart + 1), uvCount + (vert2.uv - uvStart + 1), normCount + (vert2.norm - normStart + 1),
					posCount + (vert3.pos - posStart + 1), uvCount + (vert3.uv - uvStart + 1), normCount + (vert3.norm - normStart + 1));
				objFile.write(str, strlen(str));
			}

			posCount += (posEnd - posStart) + 1;
			uvCount += (uvEnd - uvStart) + 1;
			normCount += (normEnd - normStart) + 1;
		}

		objFile.close();

		// Add instance to scene
		Json::Value& jObj = jSceneObjects.append(Json::objectValue);
		jObj["model"] = sceneName + "/" + obj.name;

		Json::Value& jPos = jObj["position"] = Json::arrayValue;
		jPos[0] = center.x; jPos[1] = center.y; jPos[2] = center.z;

		Json::Value& jRot = jObj["rotation"] = Json::arrayValue;
		jRot[0] = 0.f; jRot[1] = 0.f; jRot[2] = 0.f;

		Json::Value& jScale = jObj["scale"] = Json::arrayValue;
		jScale[0] = 1.f; jScale[1] = 1.f; jScale[2] = 1.f;
	}

	std::ofstream sceneFile("output/" + sceneName + ".scene");
	jsonWriter.write(sceneFile, jSceneRoot);
}
void loadScene(std::string fileName, std::vector<glm::vec4> &positions, std::vector<glm::vec4> &colors, std::vector<int> &modelSize, glm::vec4 &eye, glm::vec4 &lookAt, glm::vec4 &up, glm::vec4 &lrtb, float &N, float &F)
{
    std::ifstream sceneFile(fileName.c_str());

    for(int k=0;k<3;k++)
    {
		std::vector<glm::vec4> modelPositions;

		float Sx, Sy, Sz, Rx, Ry, Rz, Tx, Ty, Tz;
		std::string modelName;	
		sceneFile >> modelName;
		std::ifstream model(modelName.c_str());
		
		int numOfCoordinates = 0;

		while(1)
		{
			float v1, v2, v3, c1, c2, c3, c4;
			model >> v1;
			model >> v2;
			model >> v3;

			model >> c1;
			model >> c2;
			model >> c3;
			model >> c4;

			if(model.eof()) 
				break;

			glm::vec4 newPosition(v1, v2, v3, 1.0);
			glm::vec4 newColor(c1, c2, c3, c4);
			modelPositions.push_back(newPosition);
			colors.push_back(newColor);
			numOfCoordinates++;
	 	}
	 	model.close();

		sceneFile >> Sx;
		sceneFile >> Sy;
		sceneFile >> Sz;

		sceneFile >> Rx;
		sceneFile >> Ry;
		sceneFile >> Rz;
	
		sceneFile >> Tx;
		sceneFile >> Ty;
		sceneFile >> Tz;
	
		glm::mat4 rotationMatrix, translationMatrix, scaleMatrix, transformMatrix; 

		translationMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(Tx,Ty,Tz));
		rotationMatrix = glm::rotate(glm::mat4(1.0f), Rx, glm::vec3(1.0f,0.0f,0.0f));
	  	rotationMatrix = glm::rotate(rotationMatrix, Ry, glm::vec3(0.0f,1.0f,0.0f));
	  	rotationMatrix = glm::rotate(rotationMatrix, Rz, glm::vec3(0.0f,0.0f,1.0f));
		scaleMatrix = glm::scale(glm::mat4(1.0f),glm::vec3(Sx,Sy,Sz));
		transformMatrix = translationMatrix*rotationMatrix*scaleMatrix;
		
		for(int j=0; j<numOfCoordinates; j++)
		{
			glm::vec4 newPos=transformMatrix*modelPositions[j];
			positions.push_back(newPos);
		}

		modelSize.push_back(numOfCoordinates);

    }
    sceneFile >> eye[0];
    sceneFile >> eye[1];
    sceneFile >> eye[2];
    eye[3] = 1.0f;
    
    sceneFile >> lookAt[0];
    sceneFile >> lookAt[1];
    sceneFile >> lookAt[2];
    lookAt[3] = 1.0f;
    
    sceneFile >> up[0];
    sceneFile >> up[1];
    sceneFile >> up[2];
    up[3] = 1.0f;
    
    sceneFile >> lrtb[0];
    sceneFile >> lrtb[1];
    sceneFile >> lrtb[2];
    sceneFile >> lrtb[3];
    sceneFile >> N;
    sceneFile >> F;

    sceneFile.close();

}
Exemple #11
0
// Carrega uma cena a partir de uma descrição em arquivo
// texto (e.g, cena-simples.txt)
Scene Scene::fromFile(string fileName) {
    cout << "Carregando arquivo: " << fileName << endl;
    Scene* newScene = new Scene();
    ifstream sceneFile(fileName.c_str());

    // variáveis temporárias para leitura de arquivo
    string line;
    double doubleValues[9];
    string temp;
    stringstream iss;

    //-----------------------------------------------------------------
    // lendo a CÂMERA
    getline(sceneFile, line);
    iss << line;
    iss >> doubleValues[0] >> doubleValues[1] >> doubleValues[2];
    newScene->camera.eye = Vector3(doubleValues);
    iss.clear();

    getline(sceneFile, line);
    iss << line;
    iss >> doubleValues[0] >> doubleValues[1] >> doubleValues[2];
    newScene->camera.target = Vector3(doubleValues);
    iss.clear();

    getline(sceneFile, line);
    iss << line;
    iss >> doubleValues[0] >> doubleValues[1] >> doubleValues[2];
    newScene->camera.up = Vector3(doubleValues);
    iss.clear();

    //-----------------------------------------------------------------
    // lendo as FONTES DE LUZ
    getline(sceneFile, line);
    iss << line;
    iss >> (newScene->numLights);
    cout << "newScene->numLights: " << newScene->numLights << endl;
    newScene->lights = new Light[newScene->numLights];
    iss.clear();

    for (int i = 0; i < newScene->numLights; i++) {
        newScene->lights[i] = Light();
        // posição
        getline(sceneFile, line);
        iss << line;
        iss >> doubleValues[0] >> doubleValues[1] >> doubleValues[2] >> doubleValues[3] >> doubleValues[4] >> doubleValues[5] >> doubleValues[6] >> doubleValues[7] >> doubleValues[8];
        iss.clear();
        newScene->lights[i].position = Vector3(doubleValues[0], doubleValues[1], doubleValues[2]);
        // cor
        newScene->lights[i].color = Vector3(doubleValues[3], doubleValues[4], doubleValues[5]);
        // atenuação
        newScene->lights[i].constantAttenuation = doubleValues[6];
        newScene->lights[i].linearAttenuation = doubleValues[7];
        newScene->lights[i].quadraticAttenuation = doubleValues[8];
    }

    //-----------------------------------------------------------------
    // lendo os PIGMENTOS
    getline(sceneFile, line);
    iss << line;
    iss >> (newScene->numPygments);
    cout << "newScene->numPygments: " << newScene->numPygments << endl;
    newScene->pygments = new Pygment[newScene->numPygments];
    iss.clear();

    // ASSUMINDO SOLID
    for(int i = 0; i < newScene->numPygments; i++) {
        newScene->pygments[i] = Pygment();
        // tipo ("solid", "checker", "texmap") e cor
        getline(sceneFile, line);
        iss << line;
        iss >> temp;
        newScene->pygments[i].type = temp;
        // cor
        iss >> doubleValues[0] >> doubleValues[1] >> doubleValues[2];
        iss.clear();
        newScene->pygments[i].color1 = Vector3(doubleValues[0], doubleValues[1], doubleValues[2]);
    }


    //-----------------------------------------------------------------
    // lendo os MATERIAIS
    getline(sceneFile, line);
    iss << line;
    iss >> newScene->numMaterials;
    cout << "newScene->numMaterials: " << newScene->numMaterials << endl;
    newScene->materials = new Material[newScene->numMaterials];
    iss.clear();

    for (int i = 0; i < newScene->numMaterials; i++) {
        newScene->materials[i] = Material();
        // coeficientes
        getline(sceneFile, line);
        iss << line;
        iss >> doubleValues[0] >> doubleValues[1] >> doubleValues[2] >> doubleValues[3] >> doubleValues[4] >> doubleValues[5] >> doubleValues[6];
        newScene->materials[i].ambientCoefficient = doubleValues[0];
        newScene->materials[i].diffuseCoefficient = doubleValues[1];
        newScene->materials[i].specularCoefficient = doubleValues[2];
        newScene->materials[i].specularExponent = doubleValues[3];
        newScene->materials[i].reflectionCoefficient = doubleValues[4];
        newScene->materials[i].transmissionCoefficient = doubleValues[5];
        newScene->materials[i].snellCoefficient = doubleValues[6];
        iss.clear();
    }


    //-----------------------------------------------------------------
    // lendo os OBJETOS DA CENA
    getline(sceneFile, line);
    iss << line;
    iss >> newScene->numObjs;
    newScene->objects = new Object[newScene->numObjs];
    iss.clear();

    for (int i = 0; i < newScene->numObjs; i++) {
        newScene->objects[i] = Object();
        // índices de pigmento e acabamento
        getline(sceneFile, line);
        iss << line;
        int pygmentIndex;
        int materialIndex;
        iss >> pygmentIndex >> materialIndex;

        newScene->objects[i].pygment = &(newScene->pygments[pygmentIndex]);
        newScene->objects[i].material = &(newScene->materials[materialIndex]);

        // tipo de objeto
        iss >> newScene->objects[i].type;

        // ASSUMINDO "sphere": posição e raio
        iss >> doubleValues[0] >> doubleValues[1] >> doubleValues[2] >> doubleValues[3];
        newScene->objects[i].position = Vector3(doubleValues[0], doubleValues[1], doubleValues[2]);
        newScene->objects[i].radius = doubleValues[3];
        iss.clear();
    }


    // Calcula a base ortonormal da câmera
    newScene->camera.calculateBase();


    newScene->printDebugInfo();

    return *newScene;
}