// main function
int main(int argc, char const *argv[])
{
    try {
        // read the neural network description file
        std::string networkFile = argv[1];
        std::string weightFile = argv[2];
        std::string outputFile = argv[3];
        printf("Reading network from '%s'... ", networkFile.c_str());
        fflush(stdout);
        rapidjson::Document layerDoc;
        rapidjson::Document weightDoc;
        readJsonFile(&layerDoc, networkFile);
        readJsonFile(&weightDoc, weightFile);
        printf("done.\n");
        printf("\n");

        printf("loadDict..." );
        fflush(stdout);
        std::unordered_map<std::string, int> _wordDict;
        loadDict(&weightDoc, &_wordDict);
        printf("done.\n");
        printf("\n");

        printf("output parameter to %s...", outputFile.c_str());
        fflush(stdout);
        outputWeight(&layerDoc, &weightDoc, &_wordDict, outputFile);
        printf("finished.\n");
    }
    catch (const std::exception &e) {
        printf("FAILED: %s\n", e.what());
        return 2;
    }

    return 0;
}
Esempio n. 2
0
void showGameDialog(){
    if(dialog == 0 && combo == 0){
        dialog = new QDialog;
        QGridLayout* layout = new QGridLayout(dialog);
        combo = new QComboBox(dialog);
        QPushButton* accept = new QPushButton("Accept", dialog);
        dialog->connect(accept, &QPushButton::clicked, dialog, &acceptFunc);
        QPushButton* cancel = new QPushButton("Cancel", dialog);
        dialog->connect(cancel, &QPushButton::clicked, dialog, &QDialog::close);
        layout->addWidget(combo, 0, 0, 1, 2);
        layout->addWidget(accept, 1, 0);
        layout->addWidget(cancel, 1, 1);
        dialog->setLayout(layout);
    }
    combo->clear();
    gameDirs = getSubDirectories("games/");
    QStringList games;
    for(std::string s : gameDirs){
        rapidjson::Document doc;
        if(readJsonFile("games/"+s+"/gameInfo.json", doc)){
            games << doc["name"].GetString();
        } else {
            games << s.c_str();
        }
    }
    combo->addItems(games);
    dialog->exec();
}
Esempio n. 3
0
void Pulsars::restoreDefaults(void)
{
	restoreDefaultConfigIni();
	restoreDefaultJsonFile();
	readJsonFile();
	readSettingsFromConfig();
}
void restoreState(NeuralNetwork<TDevice> *nn, optimizers::lmOptimizer<TDevice> *optimizer, std::string *infoRows)
{
    rapidjson::Document jsonDoc;
    readJsonFile(&jsonDoc, Configuration::instance().continueFile());

    // extract info rows
    if (!jsonDoc.HasMember("info_rows"))
        throw std::runtime_error("Missing value 'info_rows'");
    *infoRows = jsonDoc["info_rows"].GetString();
    boost::replace_all(*infoRows, ";;;", "\n");

    // extract the state of the optimizer
    optimizer->importState(jsonDoc);
}
Esempio n. 5
0
bool World::loadFromFile(std::string filename){
    rapidjson::Document doc;
    if(readJsonFile(filename, doc)){
        rapidjson::Value& objects = doc["objects"];
        for (rapidjson::SizeType i = 0; i < objects.Size(); i++) {
            if(!worldObjectExists(objects[i]["type"].GetString())){
                Logger::warning << "World Object \"" << objects[i]["type"].GetString() << "\" doesn't exist, skipping." << std::endl;
                continue;
            }
            WorldObject* o = getWorldObject(objects[i]["type"].GetString())->clone();
            o->initFromJson(this, objects[i]);
            if (objects[i].HasMember("id"))
                idObjectMap[objects[i]["id"].GetString()] = o;
            addObject(o);
        }
        Logger::info << "Level loaded" << std::endl;
    }
}
Esempio n. 6
0
void Pulsars::reloadCatalog(void)
{
	bool hasSelection = false;
	StelObjectMgr* objMgr = GETSTELMODULE(StelObjectMgr);
	// Whether any pulsar are selected? Save the current selection...
	const QList<StelObjectP> selectedObject = objMgr->getSelectedObject("Pulsar");
	if (!selectedObject.isEmpty())
	{
		// ... unselect current pulsar.
		hasSelection = true;
		objMgr->unSelect();
	}

	readJsonFile();

	if (hasSelection)
	{
		// Restore selection...
		objMgr->setSelectedObject(selectedObject);
	}
}
Esempio n. 7
0
/*
 Init our module
*/
void Novae::init()
{
	try
	{
		StelFileMgr::makeSureDirExistsAndIsWritable(StelFileMgr::getUserDir()+"/modules/Novae");

		// If no settings in the main config file, create with defaults
		if (!conf->childGroups().contains("Novae"))
		{
			qDebug() << "Novae: no Novae section exists in main config file - creating with defaults";
			restoreDefaultConfigIni();
		}

		// populate settings from main config file.
		readSettingsFromConfig();

		novaeJsonPath = StelFileMgr::findFile("modules/Novae", (StelFileMgr::Flags)(StelFileMgr::Directory|StelFileMgr::Writable)) + "/novae.json";
		if (novaeJsonPath.isEmpty())
			return;

		texPointer = StelApp::getInstance().getTextureManager().createTexture(StelFileMgr::getInstallationDir()+"/textures/pointeur2.png");
		addAction("actionShow_Novae_ConfigDialog", N_("Bright Novae"), N_("Bright Novae configuration window"), configDialog, "visible");
	}
	catch (std::runtime_error &e)
	{
		qWarning() << "Novae: init error:" << e.what();
		return;
	}

	// A timer for hiding alert messages
	messageTimer = new QTimer(this);
	messageTimer->setSingleShot(true);   // recurring check for update
	messageTimer->setInterval(9000);      // 6 seconds should be enough time
	messageTimer->stop();
	connect(messageTimer, SIGNAL(timeout()), this, SLOT(messageTimeout()));

	// If the json file does not already exist, create it from the resource in the Qt resource
	if(QFileInfo(novaeJsonPath).exists())
	{
		if (!checkJsonFileFormat() || getJsonFileVersion()<CATALOG_FORMAT_VERSION)
		{
			restoreDefaultJsonFile();
		}
	}
	else
	{
		qDebug() << "Novae: novae.json does not exist - copying default file to" << QDir::toNativeSeparators(novaeJsonPath);
		restoreDefaultJsonFile();
	}

	qDebug() << "Novae: loading catalog file:" << QDir::toNativeSeparators(novaeJsonPath);

	readJsonFile();

	// Set up download manager and the update schedule
	downloadMgr = new QNetworkAccessManager(this);
	connect(downloadMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(updateDownloadComplete(QNetworkReply*)));
	updateState = CompleteNoUpdates;
	updateTimer = new QTimer(this);
	updateTimer->setSingleShot(false);   // recurring check for update
	updateTimer->setInterval(13000);     // check once every 13 seconds to see if it is time for an update
	connect(updateTimer, SIGNAL(timeout()), this, SLOT(checkForUpdate()));
	updateTimer->start();

	GETSTELMODULE(StelObjectMgr)->registerStelObjectMgr(this);
}
Esempio n. 8
0
 void VideoStructure::setNewJsonDocument( QByteArray const & json_document )
 {
     readJsonFile( json_document );
 }
Esempio n. 9
0
/*
 Init our module
*/
void Quasars::init()
{
	upgradeConfigIni();

	try
	{
		StelFileMgr::makeSureDirExistsAndIsWritable(StelFileMgr::getUserDir()+"/modules/Quasars");

		// If no settings in the main config file, create with defaults
		if (!conf->childGroups().contains("Quasars"))
		{
			qDebug() << "Quasars: no Quasars section exists in main config file - creating with defaults";
			restoreDefaultConfigIni();
		}

		// populate settings from main config file.
		readSettingsFromConfig();

		catalogJsonPath = StelFileMgr::findFile("modules/Quasars", (StelFileMgr::Flags)(StelFileMgr::Directory|StelFileMgr::Writable)) + "/quasars.json";
		if (catalogJsonPath.isEmpty())
			return;

		texPointer = StelApp::getInstance().getTextureManager().createTexture(StelFileMgr::getInstallationDir()+"/textures/pointeur2.png");
		Quasar::markerTexture = StelApp::getInstance().getTextureManager().createTexture(":/Quasars/quasar.png");

		// key bindings and other actions
		addAction("actionShow_Quasars", N_("Quasars"), N_("Show quasars"), "quasarsVisible", "Ctrl+Alt+Q");
		addAction("actionShow_Quasars_ConfigDialog", N_("Quasars"), N_("Quasars configuration window"), configDialog, "visible");

		GlowIcon = new QPixmap(":/graphicGui/glow32x32.png");
		OnIcon = new QPixmap(":/Quasars/btQuasars-on.png");
		OffIcon = new QPixmap(":/Quasars/btQuasars-off.png");

		setFlagShowQuasars(getEnableAtStartup());
		setFlagShowQuasarsButton(flagShowQuasarsButton);
	}
	catch (std::runtime_error &e)
	{
		qWarning() << "Quasars: init error:" << e.what();
		return;
	}

	// A timer for hiding alert messages
	messageTimer = new QTimer(this);
	messageTimer->setSingleShot(true);   // recurring check for update
	messageTimer->setInterval(9000);      // 6 seconds should be enough time
	messageTimer->stop();
	connect(messageTimer, SIGNAL(timeout()), this, SLOT(messageTimeout()));

	// If the json file does not already exist, create it from the resource in the Qt resource
	if(QFileInfo(catalogJsonPath).exists())
	{
		if (!checkJsonFileFormat() || getJsonFileFormatVersion()<CATALOG_FORMAT_VERSION)
		{
			restoreDefaultJsonFile();
		}
	}
	else
	{
		qDebug() << "Quasars: quasars.json does not exist - copying default file to" << QDir::toNativeSeparators(catalogJsonPath);
		restoreDefaultJsonFile();
	}

	qDebug() << "Quasars: loading catalog file:" << QDir::toNativeSeparators(catalogJsonPath);

	readJsonFile();

	// Set up download manager and the update schedule
	downloadMgr = new QNetworkAccessManager(this);
	connect(downloadMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(updateDownloadComplete(QNetworkReply*)));
	updateState = CompleteNoUpdates;
	updateTimer = new QTimer(this);
	updateTimer->setSingleShot(false);   // recurring check for update
	updateTimer->setInterval(13000);     // check once every 13 seconds to see if it is time for an update
	connect(updateTimer, SIGNAL(timeout()), this, SLOT(checkForUpdate()));
	updateTimer->start();

	GETSTELMODULE(StelObjectMgr)->registerStelObjectMgr(this);
}
Esempio n. 10
0
void ReleaseDialog::release()
{
    QString pwd = lineedit_pwd->text();
    QString name = lineedit_name->text();
    if(pwd.isEmpty() || name.isEmpty() || name.size() > 16)
    {
        QString prompt;
        prompt = QString("必须设置加密密码\n填写版本信息。");
        if(name.size() > 16)
            prompt = QString("版本信息不能超过16个字符。");
        QMessageBox box(QMessageBox::Information, "提示", prompt);
        box.setStandardButtons(QMessageBox::Ok);
        box.setButtonText(QMessageBox::Ok, "确定");
        box.exec();
        return;
    }

    ////name 最大16个字符



    if(!setFilePath())
        return;

    QDateTime start,end;
    getDateTime(start, end);
    QString jsonfilePath = getReadFilePath(start, end);

    ///读JSON下载资源
    readJsonFile(jsonfilePath);

    ///打包
    QStringList fileNames = getCurrentDirFiles(releasePath);
    QString destPath  = QCoreApplication::applicationDirPath();
    destPath.append("/ZIP/");
    QDir dir(destPath);
    if(!dir.exists())
        dir.mkpath(destPath);
    QString destName = currentDate.toString("yyyy-MM-dd_hh_mm_ss");
    destName.append(".zip");
    destPath.append(destName);

    QFile destFile(destPath);
    if(destFile.exists())
    {
    }

    zipFile zf;
    QByteArray dest = destPath.toLocal8Bit();
    zf = zipOpen(dest.data(), APPEND_STATUS_CREATE);


    if (zf == NULL)
    {
        return;
    }

//   LOKI_ON_BLOCK_EXIT(zipClose, zf, (const char *)NULL);
   for (int i=0; i<fileNames.size(); i++)
   {
       QString tempStr = fileNames.at(i);
       QString path = releasePath;
       path.remove("music");
       QString temprel = path;
       QString deststr = tempStr.remove(temprel);
       if (!ZipAddFile(zf, deststr, fileNames.at(i),  pwd,  true)) //"default_yqc"
       {
           continue;
       }
   }

   int errclose = zipClose(zf, NULL);
   if (errclose != ZIP_OK)
       qDebug() << " zipClose ret : " << errclose;

   ///上传打包文件
   QString url;
   CurlUpload *curlUpload = new CurlUpload();
   bool ok = curlUpload->uploadYQDyun(destName, destPath, url);

   qDebug() << " upload yun : ok : " << ok;
   qDebug() << " zip name " << destName;
   qDebug() << " url " << url;
   /// post 表格数据
   QDateTime time = QDateTime::currentDateTime();
   QString timeStr = time.toString("yyyy-MM-dd-hh-mm-ss");
   int version = time.toTime_t();
   QString postStr = QString("name=%1&url=%2&time=%3&remark=%4&version=%5")
                            .arg(name)
                            .arg(url)
                            .arg(timeStr)
                            .arg(pwd)
                            .arg(version);


   CurlUpload *curlDownlaod = new CurlUpload();
   curlDownlaod->postJson(postStr);

   return;
}
Esempio n. 11
0
bool Model::loadCollada(std::string filename){
    //Load the collada xml file
    rapidxml::file<> xmlFile(filename.c_str());
    rapidxml::xml_document<> doc;
    doc.parse<0>(xmlFile.data());
    
    bool zup = std::string(doc.first_node()->first_node("asset")->first_node("up_axis")->value()) == "Z_UP";
    
    //Load textures
    rapidxml::xml_node<> *images = doc.first_node()->first_node("library_images");
    if(images->first_node("image") == 0){
        Logger::error << "Couldn't load model: file contains no texture data." << std::endl;
        return false;
    }
    std::map<std::string, unsigned int> textures;
    for(rapidxml::xml_node<> *image = images->first_node("image"); image != 0; image = image->next_sibling("image")){
        textures.insert(std::pair<std::string, unsigned int>(image->first_attribute("id")->value(), loadTextureFromPNG(filename.substr(0, filename.find_last_of("\\/")+1) + image->first_node("init_from")->value())));
    }
    
    
    //Load effects
    //TODO: only supports common profiles using phong techniques
    rapidxml::xml_node<> *effectsNode = doc.first_node()->first_node("library_effects");
    if(effectsNode->first_node("effect") == 0){
        Logger::error << "Couldn't load model: file contains no effects data." << std::endl;
        return false;
    }
    std::map<std::string, Material> effects;
    for(rapidxml::xml_node<> *effect = effectsNode->first_node("effect"); effect != 0; effect = effect->next_sibling("effect")){
        rapidxml::xml_node<> *profile = effect->first_node("profile_COMMON");
        if(profile != 0){
            rapidxml::xml_node<> *technique = profile->first_node("technique");
            Material mat;
            rapidxml::xml_node<> *phong = technique->first_node("phong");
            if(phong != 0){                
                if(phong->first_node("emission") != 0){
                    mat.emission = getVec4(phong->first_node("emission")->first_node("color"));
                }
                if(phong->first_node("ambient") != 0){
                    mat.ambient = getVec4(phong->first_node("ambient")->first_node("color"));
                }
                if(phong->first_node("diffuse") != 0){
                    if(phong->first_node("diffuse")->first_node("color") != 0){
                        mat.diffuse = getVec4(phong->first_node("diffuse")->first_node("color"));
                    }
                    if(phong->first_node("diffuse")->first_node("texture") != 0){
                        mat.diffuseTexture = textures.at(searchByAttribute(profile, "sid", 
                                searchByAttribute(profile, "sid", phong->first_node("diffuse")->first_node("texture")->first_attribute("texture")->value(), "newparam")
                                ->first_node("sampler2D")->first_node("source")->value()
                                , "newparam")->first_node("surface")->first_node("init_from")->value());
                    }
                }
                if(phong->first_node("specular") != 0){
                    if(phong->first_node("specular")->first_node("color") != 0){
                        mat.specular = getVec4(phong->first_node("specular")->first_node("color"));
                    }
                    if(phong->first_node("specular")->first_node("texture") != 0){
                        mat.specularTexture = textures.at(searchByAttribute(profile, "sid", 
                                searchByAttribute(profile, "sid", phong->first_node("specular")->first_node("texture")->first_attribute("texture")->value(), "newparam")
                                ->first_node("sampler2D")->first_node("source")->value()
                                , "newparam")->first_node("surface")->first_node("init_from")->value());
                    }
                }
                if(phong->first_node("shininess") != 0){
                    mat.shininess = std::stof(phong->first_node("shininess")->first_node("float")->value());
                }
            } else {
                Logger::error << "Couldn't load model: material doesn't use the phong technique." << std::endl;
                return false;
            }
            if(technique->first_node("extra") != 0 && technique->first_node("extra")->first_node("technique")->first_node("bump") != 0){
                mat.bumpmapTexture = textures.at(searchByAttribute(profile, "sid", 
                                searchByAttribute(profile, "sid", technique->first_node("extra")->first_node("technique")->first_node("bump")->first_node("texture")->first_attribute("texture")->value(), "newparam")
                                ->first_node("sampler2D")->first_node("source")->value()
                                , "newparam")->first_node("surface")->first_node("init_from")->value());
            }
            effects.insert(std::pair<std::string, Material>(effect->first_attribute("id")->value(), mat));
        } else {
            Logger::error << "Couldn't load model: material doesn't have a profile_COMMON tag." << std::endl;
            return false;
        }
    }
    
    
    //Load materials
    //TODO: make them overridable (collada spec))
    rapidxml::xml_node<> *materialsNode = doc.first_node()->first_node("library_materials");
    if(materialsNode->first_node("material") == 0){
        Logger::error << "Couldn't load model: file contains no material data." << std::endl;
        return false;
    }
    std::map<std::string, Material> materials;
    for(rapidxml::xml_node<> *material = materialsNode->first_node("material"); material != 0; material = material->next_sibling("material")){
        materials.insert(std::pair<std::string, Material>(material->first_attribute("id")->value(), effects.at(std::string(material->first_node("instance_effect")->first_attribute("url")->value()).substr(1))));
    }
    
    
    //Load geometry
    std::map<std::string, Mesh> meshes;
    rapidxml::xml_node<> *geometries = doc.first_node()->first_node("library_geometries");
    if(geometries->first_node("geometry") == 0){
        Logger::error << "Couldn't load model: file contains no geometry data." << std::endl;
        return false;
    }
    for(rapidxml::xml_node<> *geometry = geometries->first_node("geometry"); geometry != 0; geometry = geometry->next_sibling("geometry")){
        Mesh mesh;        
        rapidxml::xml_node<> *meshNode = geometry->first_node("mesh");
        if(meshNode == 0){
            Logger::error << "Couldn't load model: The loader can only load geometry of type \"mesh\" (geometry with name: " << geometry->first_attribute("name")->value() << ")." << std::endl;
            return false;
        }
        if(meshNode->first_node("polylist") == 0){
            Logger::error << "Couldn't load model: The loader can only load meshes that use polylists. (geometry with name: " << geometry->first_attribute("name")->value() << ")." << std::endl;
            return false;
        }
        
        //TODO: allow for multiple data types
        //<name, <stride, data>>
        std::map<std::string, std::pair<unsigned int, std::vector<float>>> sources;
        GLenum dataType;
        for(rapidxml::xml_node<> *source = meshNode->first_node("source"); source != 0; source = source->next_sibling("source")){
            std::vector<float> container;
            dataType = readData(&container, source);
            if(dataType == GL_NONE){
                return false;
            }
            sources.insert(std::pair<std::string, std::pair<unsigned int, std::vector<float>>>(source->first_attribute("id")->value(), std::pair<unsigned int, std::vector<float>>(std::stoi(source->first_node("technique_common")->first_node("accessor")->first_attribute("stride")->value()), container)));
        }
        
        //TODO: same data vertex merging (aka indexing)
        for(rapidxml::xml_node<> *polylist = meshNode->first_node("polylist"); polylist != 0; polylist = polylist->next_sibling("polylist")){
            std::vector<float> openglData;
            std::vector<unsigned int> indices;
            std::vector<std::string> tempContainer;
            std::vector<int> colladaIndices;        
            split(polylist->first_node("p")->value(), " ", &tempContainer);
            for(std::string s : tempContainer){
                colladaIndices.push_back(std::stoi(s));
            }
            std::vector<float> vertexData;
            float vertexOffset;
            float vertexStride;
            std::vector<float> normalData;
            float normalOffset;
            float normalStride;
            std::vector<float> uvData;
            float uvOffset;
            float uvStride;
            
            std::pair<unsigned int, std::vector<float>> pair;
            for(rapidxml::xml_node<> *input = polylist->first_node("input"); input != 0; input = input->next_sibling("input")){
                std::string semantic(input->first_attribute("semantic")->value());
                if(semantic == "VERTEX"){
                    pair = sources.at(std::string(meshNode->first_node("vertices")->first_node("input")->first_attribute("source")->value()).substr(1));
                    vertexData = pair.second;
                    vertexOffset = std::stoi(input->first_attribute("offset")->value());
                    vertexStride = pair.first;
                } else if(semantic == "NORMAL"){
                    pair = sources.at(std::string(input->first_attribute("source")->value()).substr(1));
                    normalData = pair.second;
                    normalOffset = std::stoi(input->first_attribute("offset")->value());
                    normalStride = pair.first;
                } else if(semantic == "TEXCOORD"){
                    pair = sources.at(std::string(input->first_attribute("source")->value()).substr(1));
                    uvData = pair.second;
                    uvOffset = std::stoi(input->first_attribute("offset")->value());
                    uvStride = pair.first;
                } else {
                    Logger::error << "Unknown input semantic: " << semantic << std::endl;
                    return 0;
                }
            }            
            PolyGroup poly;
            poly.elements = std::stoi(polylist->first_attribute("count")->value())*3;
            
            //Generate vertices
            for(unsigned int i = 0; i < poly.elements; i++){
                openglData.push_back(vertexData.at(colladaIndices.at(i*3+vertexOffset)*vertexStride));
                if(zup){
                    openglData.push_back(vertexData.at(colladaIndices.at(i*3+vertexOffset)*vertexStride+2));
                    openglData.push_back(-vertexData.at(colladaIndices.at(i*3+vertexOffset)*vertexStride+1));
                } else {
                    openglData.push_back(vertexData.at(colladaIndices.at(i*3+vertexOffset)*vertexStride+1));
                    openglData.push_back(vertexData.at(colladaIndices.at(i*3+vertexOffset)*vertexStride+2));
                }

                openglData.push_back(normalData.at(colladaIndices.at(i*3+normalOffset)*normalStride));
                if(zup){
                    openglData.push_back(normalData.at(colladaIndices.at(i*3+normalOffset)*normalStride+2));
                    openglData.push_back(-normalData.at(colladaIndices.at(i*3+normalOffset)*normalStride+1));
                } else {
                    openglData.push_back(normalData.at(colladaIndices.at(i*3+normalOffset)*normalStride+1));
                    openglData.push_back(normalData.at(colladaIndices.at(i*3+normalOffset)*normalStride+2));
                }

                openglData.push_back(uvData.at(colladaIndices.at(i*3+uvOffset)*uvStride));
                //collada stores the uv data the other way around. how silly.
                openglData.push_back(1.0f - uvData.at(colladaIndices.at(i*3+uvOffset)*uvStride+1));

                //temp index
                indices.push_back(i);
            }
            poly.vaoid = sendToOpengl(openglData, indices);
            poly.material = materials.at(polylist->first_attribute("material")->value());
            mesh.addPolyGroup(poly);
        }
        meshes.insert(std::pair<std::string, Mesh>(geometry->first_attribute("id")->value(), mesh));
        //this->meshes.insert(std::pair<std::string, std::pair<glm::mat4, Mesh>>(std::string(geometry->first_attribute("id")->value()).substr(1), std::pair<glm::mat4, Mesh>(glm::mat4(1.0f), mesh)));
    }
    
    //Load scene
    rapidxml::xml_node<> *scenes = doc.first_node()->first_node("library_visual_scenes");
    if(scenes->first_node("visual_scene") == 0){
        Logger::error << "Couldn't load model: file contains no scene data." << std::endl;
        return false;
    } else {
        rapidxml::xml_node<> *scene = scenes->first_node("visual_scene");
        for(rapidxml::xml_node<> *node = scene->first_node("node"); node != 0; node = node->next_sibling("node")){
            if(node->first_node("instance_geometry") != 0){
                std::vector<float> matrix;
                std::vector<std::string> tempContainer;
                glm::mat4 mat4 = glm::mat4(1.0f);
                if(node->first_node("matrix") == 0){
                    split(node->first_node("translate")->value(), " ", &tempContainer);
                    mat4 = glm::translate(mat4, glm::vec3(std::stof(tempContainer[0]), std::stof(tempContainer[2]), -std::stof(tempContainer[1])));
                    tempContainer.clear();
                    split(searchByAttribute(node, "sid", "rotationX", "rotate")->value(), " ", &tempContainer);
                    mat4 = glm::rotate(mat4, glm::radians(std::stof(tempContainer[3])), glm::vec3(1.0f, 0.0f, 0.0f));
                    tempContainer.clear();
                    split(searchByAttribute(node, "sid", "rotationZ", "rotate")->value(), " ", &tempContainer);
                    mat4 = glm::rotate(mat4, glm::radians(std::stof(tempContainer[3])), glm::vec3(0.0f, 1.0f, 0.0f));
                    tempContainer.clear();
                    split(searchByAttribute(node, "sid", "rotationY", "rotate")->value(), " ", &tempContainer);
                    mat4 = glm::rotate(mat4, glm::radians(std::stof(tempContainer[3])), glm::vec3(0.0f, 0.0f, -1.0f));
                    tempContainer.clear();
                    split(node->first_node("scale")->value(), " ", &tempContainer);
                    mat4 = glm::scale(mat4, glm::vec3(std::stof(tempContainer[0]), std::stof(tempContainer[2]), std::stof(tempContainer[1])));
                    //mat4 = glm::mat4(1.0f);
                } else {
                    split(node->first_node("matrix")->value(), " ", &tempContainer);
                    for(std::string s : tempContainer){
                        matrix.push_back(std::stof(s));
                    }
                    glm::mat4 mat4 = glm::make_mat4(matrix.data());
                    if(std::string(doc.first_node()->first_node("asset")->first_node("up_axis")->value()) == "Z_UP"){
                        mat4 = convertToRightHandedCoords(mat4);
                    }
                }
                this->meshes.insert(std::pair<std::string,std::pair<glm::mat4, Mesh>>(
                        node->first_attribute("id")->value(),
                        std::pair<glm::mat4, Mesh>(
                            mat4,
                            meshes.at(std::string(node->first_node("instance_geometry")->first_attribute("url")->value()).substr(1)))));
            }
        }
    }
    rapidjson::Document animDoc;
    if(readJsonFile(filename.substr(0, filename.find_last_of("/")+1) + "animation.json", animDoc)){
        rapidxml::xml_node<> *animations = doc.first_node()->first_node("library_animations");
        if(animations->first_node("animation") != 0){
            std::map<std::string, std::vector< std::pair<float, glm::vec3> > > locationKeyframes;
            std::map<std::string, std::vector< std::pair<float, glm::vec3> > > rotationKeyframes;
            for(rapidxml::xml_node<> *animNode = animations->first_node("animation"); animNode != 0; animNode = animNode->next_sibling("animation")){
                std::vector<float> inputContainer;
                readData(&inputContainer, searchByAttribute(
                        animNode,
                        "id",
                        std::string(searchByAttribute(
                            animNode->first_node("sampler"),
                            "semantic",
                            "INPUT",
                            "input"
                        )->first_attribute("source")->value()).substr(1),
                        "source"));
                std::vector<float> outputContainer;
                readData(&outputContainer, searchByAttribute(
                        animNode,
                        "id",
                        std::string(searchByAttribute(
                            animNode->first_node("sampler"),
                            "semantic",
                            "OUTPUT",
                            "input"
                        )->first_attribute("source")->value()).substr(1),
                        "source"));/*
                std::vector< std::pair<float, glm::vec3> > keyframes;
                for(int i = 0; i < inputContainer.size(); i++){
                    keyframes.push_back(std::pair<float, glm::vec3>(inputContainer.at(i), outputContainer.at(i)));
                }*/
                std::string target = animNode->first_node("channel")->first_attribute("target")->value();
                std::string meshName = target.substr(0, target.find_first_of("/"));
                if(target.substr(target.find_first_of("/")+1, target.find_first_of(".")-target.find_first_of("/")-2) == "rotation"){
                    if(!rotationKeyframes.count(meshName)){
                        rotationKeyframes.insert(std::pair<std::string, std::vector< std::pair<float, glm::vec3> > >(meshName, std::vector< std::pair<float, glm::vec3> >()));
                    }
                    for(int i = 0; i < inputContainer.size(); i++){
                        if(rotationKeyframes.at(meshName).size() <= i){
                            rotationKeyframes.at(meshName).push_back(std::pair<float, glm::vec3>(inputContainer.at(i), glm::vec3(0.0f, 0.0f, 0.0f)));
                        }
                        if(target.substr(target.find_first_of("/")+1, target.find_first_of(".")-target.find_first_of("/")-1) == "rotationX"){
                            rotationKeyframes.at(meshName).at(i).second.x = outputContainer.at(i);
                        } else if(target.substr(target.find_first_of("/")+1, target.find_first_of(".")-target.find_first_of("/")-1) == "rotationY"){
                            rotationKeyframes.at(meshName).at(i).second.y = outputContainer.at(i);
                        } else if(target.substr(target.find_first_of("/")+1, target.find_first_of(".")-target.find_first_of("/")-1) == "rotationZ"){
                            rotationKeyframes.at(meshName).at(i).second.z = outputContainer.at(i);
                        }
                    }
                } else if(target.substr(target.find_first_of("/")+1, target.find_first_of(".")) == "location"){
                    if(locationKeyframes.count(meshName)){
                        locationKeyframes.insert(std::pair<std::string, std::vector< std::pair<float, glm::vec3> > >(meshName, std::vector< std::pair<float, glm::vec3> >()));
                    }
                    for(int i = 0; i < inputContainer.size(); i++){
                        if(locationKeyframes.at(meshName).size() <= i){
                            locationKeyframes.at(meshName).push_back(std::pair<float, glm::vec3>(inputContainer.at(i), glm::vec3(0.0f, 0.0f, 0.0f)));
                        }
                        if(target.substr(target.find_first_of(".")+1) == "X"){
                            locationKeyframes.at(meshName).at(i).second.x = outputContainer.at(i);
                        } else if(target.substr(target.find_first_of(".")+1) == "Y"){
                            locationKeyframes.at(meshName).at(i).second.y = outputContainer.at(i);
                        } else if(target.substr(target.find_first_of(".")+1) == "Z"){
                            locationKeyframes.at(meshName).at(i).second.z = outputContainer.at(i);
                        }
                    }
                } else {
                    Logger::info << "unknown animation target: " << target << std::endl;
                }
            }
            for (rapidjson::SizeType i = 0; i < animDoc.Size(); i++) {
                Animation animation;
                rapidjson::Value& animjson = animDoc[i];
                animation.mesh = animjson["mesh"].GetString();
                int start = animjson["startKeyframe"].GetInt();
                int end = animjson["endKeyframe"].GetInt();
                for(int j = start; j <= end; j++){
                    glm::mat4 mat4 = this->meshes.at(animation.mesh).first;
                    glm::vec3 rotation = rotationKeyframes.count(animation.mesh) ? rotationKeyframes.at(animation.mesh).at(j).second : glm::vec3(0.0f, 0.0f, 0.0f);
                    glm::vec3 translation = locationKeyframes.count(animation.mesh) ? locationKeyframes.at(animation.mesh).at(j).second : glm::vec3(0.0f, 0.0f, 0.0f);
                    if(zup){
                        mat4 = glm::translate(mat4, glm::vec3(translation.x, translation.z, -translation.y));
                        mat4 = glm::rotate(mat4, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f));
                        mat4 = glm::rotate(mat4, glm::radians(rotation.z), glm::vec3(0.0f, 1.0f, 0.0f));
                        mat4 = glm::rotate(mat4, glm::radians(rotation.y), glm::vec3(0.0f, 0.0f, -1.0f));
                    } else {
                        mat4 = glm::translate(mat4, glm::vec3(translation.x, translation.y, translation.z));
                        mat4 = glm::rotate(mat4, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f));
                        mat4 = glm::rotate(mat4, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f));
                        mat4 = glm::rotate(mat4, glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f));
                    }
                    animation.keyframes.push_back(std::make_pair(rotationKeyframes.at(animation.mesh).at(j).first, mat4));
                }
                this->animations.insert(std::make_pair(animjson["name"].GetString(), animation));
            }
        }
    }
    return true;
}
/*
 Init our module
*/
void Exoplanets::init()
{
	try
	{
		StelFileMgr::makeSureDirExistsAndIsWritable(StelFileMgr::getUserDir()+"/modules/Exoplanets");

		// If no settings in the main config file, create with defaults
		if (!conf->childGroups().contains("Exoplanets"))
		{
			qDebug() << "Exoplanets::init no Exoplanets section exists in main config file - creating with defaults";
			restoreDefaultConfigIni();
		}

		// populate settings from main config file.
		readSettingsFromConfig();

		jsonCatalogPath = StelFileMgr::findFile("modules/Exoplanets", (StelFileMgr::Flags)(StelFileMgr::Directory|StelFileMgr::Writable)) + "/exoplanets.json";

		// key bindings and other actions
		StelGui* gui = dynamic_cast<StelGui*>(StelApp::getInstance().getGui());

		GlowIcon = new QPixmap(":/graphicsGui/glow32x32.png");
		OnIcon = new QPixmap(":/Exoplanets/btExoplanets-on.png");
		OffIcon = new QPixmap(":/Exoplanets/btExoplanets-off.png");

		gui->getGuiAction("actionShow_Exoplanets")->setChecked(flagShowExoplanets);
		toolbarButton = new StelButton(NULL, *OnIcon, *OffIcon, *GlowIcon, gui->getGuiAction("actionShow_Exoplanets"));
		gui->getButtonBar()->addButton(toolbarButton, "065-pluginsGroup");

		connect(gui->getGuiAction("actionShow_Exoplanets_ConfigDialog"), SIGNAL(toggled(bool)), exoplanetsConfigDialog, SLOT(setVisible(bool)));
		connect(exoplanetsConfigDialog, SIGNAL(visibleChanged(bool)), gui->getGuiAction("actionShow_Exoplanets_ConfigDialog"), SLOT(setChecked(bool)));
		connect(gui->getGuiAction("actionShow_Exoplanets"), SIGNAL(toggled(bool)), this, SLOT(setFlagShowExoplanets(bool)));
	}
	catch (std::runtime_error &e)
	{
		qWarning() << "Exoplanets::init error: " << e.what();
		return;
	}

	// A timer for hiding alert messages
	messageTimer = new QTimer(this);
	messageTimer->setSingleShot(true);   // recurring check for update
	messageTimer->setInterval(9000);      // 6 seconds should be enough time
	messageTimer->stop();
	connect(messageTimer, SIGNAL(timeout()), this, SLOT(messageTimeout()));

	// If the json file does not already exist, create it from the resource in the Qt resource
	if(QFileInfo(jsonCatalogPath).exists())
	{
		if (getJsonFileVersion() < CATALOG_FORMAT_VERSION)
		{
			restoreDefaultJsonFile();
		}
	}
	else
	{
		qDebug() << "Exoplanets::init catalog.json does not exist - copying default file to " << jsonCatalogPath;
		restoreDefaultJsonFile();
	}

	qDebug() << "Exoplanets::init using catalog.json file: " << jsonCatalogPath;

	readJsonFile();

	// Set up download manager and the update schedule
	downloadMgr = new QNetworkAccessManager(this);
	connect(downloadMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(updateDownloadComplete(QNetworkReply*)));
	updateState = CompleteNoUpdates;
	updateTimer = new QTimer(this);
	updateTimer->setSingleShot(false);   // recurring check for update
	updateTimer->setInterval(13000);     // check once every 13 seconds to see if it is time for an update
	connect(updateTimer, SIGNAL(timeout()), this, SLOT(checkForUpdate()));
	updateTimer->start();

	GETSTELMODULE(StelObjectMgr)->registerStelObjectMgr(this);
}
Esempio n. 13
0
/*
 Init our module
*/
void Supernovae::init()
{
	try
	{
		StelFileMgr::makeSureDirExistsAndIsWritable(StelFileMgr::getUserDir()+"/modules/Supernovae");

		// If no settings in the main config file, create with defaults
		if (!conf->childGroups().contains("Supernovae"))
		{
			qDebug() << "Supernovae::init no Supernovae section exists in main config file - creating with defaults";
			restoreDefaultConfigIni();
		}

		// populate settings from main config file.
		readSettingsFromConfig();

		sneJsonPath = StelFileMgr::findFile("modules/Supernovae", (StelFileMgr::Flags)(StelFileMgr::Directory|StelFileMgr::Writable)) + "/supernovae.json";
		// key bindings and other actions
		StelGui* gui = dynamic_cast<StelGui*>(StelApp::getInstance().getGui());

		connect(gui->getGuiAction("actionShow_Supernovae_ConfigDialog"), SIGNAL(toggled(bool)), configDialog, SLOT(setVisible(bool)));
		connect(configDialog, SIGNAL(visibleChanged(bool)), gui->getGuiAction("actionShow_Supernovae_ConfigDialog"), SLOT(setChecked(bool)));
	}
	catch (std::runtime_error &e)
	{
		qWarning() << "Supernovas::init error: " << e.what();
		return;
	}

	// A timer for hiding alert messages
	messageTimer = new QTimer(this);
	messageTimer->setSingleShot(true);   // recurring check for update
	messageTimer->setInterval(9000);      // 6 seconds should be enough time
	messageTimer->stop();
	connect(messageTimer, SIGNAL(timeout()), this, SLOT(messageTimeout()));

	// If the json file does not already exist, create it from the resource in the Qt resource
	if(QFileInfo(sneJsonPath).exists())
	{
		if (!checkJsonFileFormat() || getJsonFileVersion()<CATALOG_FORMAT_VERSION)
		{
			restoreDefaultJsonFile();
		}
	}
	else
	{
		qDebug() << "Supernovae::init supernovae.json does not exist - copying default file to " << QDir::toNativeSeparators(sneJsonPath);
		restoreDefaultJsonFile();
	}

	qDebug() << "Supernovae::init using file: " << QDir::toNativeSeparators(sneJsonPath);

	readJsonFile();

	// Set up download manager and the update schedule
	downloadMgr = new QNetworkAccessManager(this);
	connect(downloadMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(updateDownloadComplete(QNetworkReply*)));
	updateState = CompleteNoUpdates;
	updateTimer = new QTimer(this);
	updateTimer->setSingleShot(false);   // recurring check for update
	updateTimer->setInterval(13000);     // check once every 13 seconds to see if it is time for an update
	connect(updateTimer, SIGNAL(timeout()), this, SLOT(checkForUpdate()));
	updateTimer->start();

	GETSTELMODULE(StelObjectMgr)->registerStelObjectMgr(this);
}
Esempio n. 14
0
void ReleaseDialog::release()
{
    setTitle("发布版本");
    QString pwd = lineedit_pwd->text();
    QString name = lineedit_name->text();
    if(pwd.isEmpty() || name.isEmpty() || name.size() > 16)
    {
        QString prompt;
        prompt = QString("必须设置加密密码\n填写版本信息。");
        if(name.size() > 16)
            prompt = QString("版本信息不能超过16个字符。");
        QMessageBox box(QMessageBox::Information, "提示", prompt);
        box.setStandardButtons(QMessageBox::Ok);
        box.setButtonText(QMessageBox::Ok, "确定");
        box.exec();
        return;
    }

    ////name 最大16个字符
    if(!setFilePath())
    {
        QMessageBox::information(NULL, "提示", "文件路径设置失败!");
        return;
    }

    bar->setHidden(false);

    QDateTime start,end;
    getDateTime(start, end);
    QString jsonfilePath = getReadFilePath(start, end);

    this->setCursor(Qt::WaitCursor);
    ///读JSON下载资源
    readJsonFile(jsonfilePath);

    ///打包
    QStringList fileNames = getCurrentDirFiles(releasePath);
    QString destPath  = QCoreApplication::applicationDirPath();
    destPath.append("/ZIP/");
    QDir dir(destPath);
    if(!dir.exists())
        dir.mkpath(destPath);
    QString destName = currentDate.toString("yyyy-MM-dd_hh_mm_ss");
    destName.append(".zip");
    destPath.append(destName);

    QFile destFile(destPath);
    if(destFile.exists())
    {
    }

    zipFile zf;
    QByteArray dest = destPath.toLocal8Bit();
    zf = zipOpen(dest.data(), APPEND_STATUS_CREATE);


    if (zf == NULL)
    {
        QMessageBox::information(NULL, "提示", "打开压缩文件失败!");
        return;
    }

   label_title->setText("压缩文件……");
//   LOKI_ON_BLOCK_EXIT(zipClose, zf, (const char *)NULL);
   for (int i=0; i<fileNames.size(); i++)
   {
       QString tempStr = fileNames.at(i);
       QString path = releasePath;
       path.remove("music");
       QString temprel = path;
       QString deststr = tempStr.remove(temprel);
       if (!ZipAddFile(zf, deststr, fileNames.at(i),  pwd,  true)) //"default_yqc"
       {
           continue;
       }
   }

   int errclose = zipClose(zf, NULL);
   if (errclose != ZIP_OK)
       qDebug() << " zipClose ret : " << errclose;


   label_title->setText("上传压缩包……");

   QFile file(destPath);
   qDebug() << " size " << file.size();
   if(file.size()/1024/1024 >= 1024)
   {
        QMessageBox::information(this, "提示", "上传文件大小必须小于1G!");
        return;
   }
   ///上传打包文件
//   QString url;
//   CurlUpload *curlUpload = new CurlUpload();
//   bool ok = curlUpload->uploadYQDyun(destName, destPath, url);


//   if(!ok)
//   {
//       url = "";
//       label_title->setText("上传失败");
//       label_title->setStyleSheet("color:rgb(255, 0, 0);");
//   }
//   else
//   {
//       label_title->setText("上传成功");
//       label_title->setStyleSheet("color:rgb(0, 255, 0);");
//   }

//   qDebug() << " upload yun : ok : " << ok;
//   qDebug() << " zip name " << destName;
//   qDebug() << " url " << url;
//   /// post 表格数据
   QDateTime time = QDateTime::currentDateTime();
   QString timeStr = time.toString("yyyy-MM-dd-hh-mm-ss");
   int version = time.toTime_t(); ///时间戳
//   QString postStr = QString("name=%1&url=%2&time=%3&remark=%4&version=%5")
//                            .arg(name)
//                            .arg(url)
//                            .arg(timeStr)
//                            .arg(pwd)
//                            .arg(version);


//   CurlUpload *curlDownlaod = new CurlUpload();
//   curlDownlaod->postJson(postStr);


   _yun.name = name;
   _yun.timeStr = timeStr;
   _yun.pwd = pwd;
   _yun.version = QString::number(version);

   this->setCursor(Qt::ArrowCursor);
//   return;

   ////
   ///线程上传
   retSize = "-2";
   Thread *workerThread = new Thread(this, 4);
   connect(workerThread, &Thread::resultYun, this, &ReleaseDialog::uploadsuccess);
   connect(workerThread, &Thread::start_upload, this, &ReleaseDialog::timeStart);
   connect(workerThread, &Thread::finished, workerThread, &QObject::deleteLater);
   workerThread->setUploadYun(destName, destPath, &retSize);
   workerThread->start();
   startValue = true;
}
Esempio n. 15
0
void Pulsars::downloadComplete(QNetworkReply *reply)
{
	if (reply == Q_NULLPTR)
		return;

	disconnect(networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(downloadComplete(QNetworkReply*)));

	#if QT_VERSION < 0x050600
	int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
	if (statusCode == 301 || statusCode == 302 || statusCode == 307)
	{
		QUrl rawUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
		QUrl redirectUrl(rawUrl.toString(QUrl::RemoveQuery));
		qDebug() << "[Pulsars] The query has been redirected to" << redirectUrl.toString();
		updateUrl = redirectUrl.toString();
		conf->setValue("Pulsars/url", updateUrl);
		reply->deleteLater();
		downloadReply = Q_NULLPTR;
		startDownload(redirectUrl.toString());
		return;
	}
	#endif

	deleteDownloadProgressBar();

	if (reply->error() || reply->bytesAvailable()==0)
	{
		qWarning() << "[Pulsars] Download error: While trying to access"
			   << reply->url().toString()
			   << "the following error occured:"
			   << reply->errorString();

		reply->deleteLater();
		downloadReply = Q_NULLPTR;
		return;
	}

	// download completed successfully.
	try
	{
		QString jsonFilePath = StelFileMgr::findFile("modules/Pulsars", StelFileMgr::Flags(StelFileMgr::Writable|StelFileMgr::Directory)) + "/pulsars.json";
		QFile jsonFile(jsonFilePath);
		if (jsonFile.exists())
			jsonFile.remove();

		if (jsonFile.open(QIODevice::WriteOnly | QIODevice::Text))
		{
			jsonFile.write(reply->readAll());
			jsonFile.close();
		}

		updateState = Pulsars::CompleteUpdates;

		lastUpdate = QDateTime::currentDateTime();
		conf->setValue("Pulsars/last_update", lastUpdate.toString(Qt::ISODate));
	}
	catch (std::runtime_error &e)
	{
		qWarning() << "[Pulsars] Cannot write JSON data to file:" << e.what();
		updateState = Pulsars::DownloadError;
	}

	emit(updateStateChanged(updateState));
	emit(jsonUpdateComplete());

	reply->deleteLater();
	downloadReply = Q_NULLPTR;

	readJsonFile();
}