Example #1
0
void ControllerWindow::doOpen(const QString &fileName)
{
    static QStringList extensions;
    if (extensions.isEmpty())
    {
        extensions.append("png");
        extensions.append("bmp");
    }
    closeFile();
    QFile modelFile(fileName + "/tris.md2");
    if (!modelFile.exists())
        return;
    modelFile.open(QIODevice::ReadOnly);
    model = Md2Model::loadFromFile(&modelFile);
    if (!model)
        return;
    for (int i = 0; i < 4; i++)
    {
        foreach (QString ext, extensions)
        {
            QFile file(QString("%1/tris%2.%3").arg(fileName).arg(i).arg(ext));
            if (file.exists())
            {
                QImage *img = new QImage(file.fileName());
                if (img)
                {
                    skins.append(img);
                    ui->comboBox->addItem(QString("Skin %1 (%2)").arg(i).arg(ext));
                }
                continue;
            }
        }
    }
Example #2
0
void ModelBaker::exportScene() {
    auto fbxData = FBXWriter::encodeFBX(_rootNode);

    QString bakedModelURL = _bakedModelURL.toString();
    QFile bakedFile(bakedModelURL);

    if (!bakedFile.open(QIODevice::WriteOnly)) {
        handleError("Error opening " + bakedModelURL + " for writing");
        return;
    }

    bakedFile.write(fbxData);

    _outputFiles.push_back(bakedModelURL);

#ifdef HIFI_DUMP_FBX
    {
        FBXToJSON fbxToJSON;
        fbxToJSON << _rootNode;
        QFileInfo modelFile(_bakedModelURL.toString());
        QString outFilename(modelFile.dir().absolutePath() + "/" + modelFile.completeBaseName() + "_FBX.json");
        QFile jsonFile(outFilename);
        if (jsonFile.open(QIODevice::WriteOnly)) {
            jsonFile.write(fbxToJSON.str().c_str(), fbxToJSON.str().length());
            jsonFile.close();
        }
    }
#endif

    qCDebug(model_baking) << "Exported" << _modelURL << "with re-written paths to" << bakedModelURL;
}
Example #3
0
void Model::loadRawModel(std::string fileName) {
    fileName = "Resources/" + fileName;
    std::ifstream modelFile(fileName.c_str());
    char* tt = new char (10);
    while (modelFile.good()) {
        triFace *temp = new triFace;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                modelFile >> tt;
                temp->vertex[i][j] = atof(tt);

                //get bounding box around model
                if (temp->vertex[i][j] > bound->max[j]) {
                    bound->max[j] = temp->vertex[i][j];
                }
                if (temp->vertex[i][j] < bound->min[j]) {
                    bound->min[j] = temp->vertex[i][j];
                }
            }
        }
        faces.push_back(temp);
        modelFile.ignore();
    }
    modelFile.close();
}
Example #4
0
S3DModel* COBJParser::Load(const std::string& modelFileName)
{
	std::string metaFileName = modelFileName.substr(0, modelFileName.find_last_of('.')) + ".lua";

	CFileHandler modelFile(modelFileName);
	CFileHandler metaFile(metaFileName);

	if (!modelFile.FileExists()) {
		throw content_error("[OBJParser] could not find model-file \"" + modelFileName + "\"");
	}
	if (!metaFile.FileExists()) {
		throw content_error("[OBJParser] could not find meta-file \"" + metaFileName + "\"");
	}


	LuaParser metaFileParser(metaFileName, SPRING_VFS_MOD_BASE, SPRING_VFS_ZIP);
	metaFileParser.Execute();

	if (!metaFileParser.IsValid()) {
		throw content_error("[OBJParser] failed to parse meta-file \"" + metaFileName + "\"");
	}

	// get the (root-level) model table
	const LuaTable& modelTable = metaFileParser.GetRoot();

	S3DModel* model = new S3DModel();
		model->name = modelFileName;
		model->type = MODELTYPE_OBJ;
		model->textureType = 0;
		model->numPieces = 0;
		model->radius = modelTable.GetFloat("radius", 0.0f);
		model->height = modelTable.GetFloat("height", 0.0f);
		model->relMidPos = modelTable.GetFloat3("midpos", ZeroVector);
		model->tex1 = modelTable.GetString("tex1", "");
		model->tex2 = modelTable.GetString("tex2", "");
		model->mins = DEF_MIN_SIZE;
		model->maxs = DEF_MAX_SIZE;

	// basic S3O-style texturing
	texturehandlerS3O->LoadS3OTexture(model);

	std::string modelData;
	modelFile.LoadStringData(modelData);

	if (ParseModelData(model, modelData, modelTable)) {
		assert(model->numPieces == modelTable.GetInt("numpieces", 0));
		return model;
	} else {
		delete model;
		throw content_error("[OBJParser] failed to parse model-data \"" + modelFileName + "\"");
	}

	return NULL;
}
Example #5
0
void reProjectAssets::WriteModel(const recondite::ModelData& modelData, const wxString& name) {
	wxFileName modelFile(m_assetsDir);
	modelFile.AppendDir("models");

	modelFile.SetName(name);
	modelFile.SetExt("rmdl");

	rString outputFilePath = modelFile.GetFullPath().c_str().AsChar();
	rOFileStream outputStream(outputFilePath);

	modelData.Write(outputStream);
}
Example #6
0
  Files ModelInModelOutJob::outputFilesImpl() const
  {
    Files outfiles;

    try {
      FileInfo osm(outdir() / toPath("out.osm"), "osm");
      osm.requiredFiles = modelFile().requiredFiles;

      outfiles.append(osm);
    } catch (const std::exception &) {
      //output file cannot be generated yet
    }
    return outfiles;
  }
Example #7
0
        bool generateModels(const std::string & outputFile)
        {
            std::ofstream modelsContent(outputFile, std::ofstream::out);
            modelsContent << "#include \"" << applicationName << ".h\"" << std::endl;
            modelsContent << "namespace webmvcpp" << std::endl;
            modelsContent << "{" << std::endl << std::endl;
            modelsContent << std::endl;

            std::string path = webApplicationPath + "/models";
            DIR *currentDir = opendir(path.c_str());
            if (!currentDir)
                return false;

            while (dirent *entry = readdir(currentDir))
            {
                if (entry->d_type == DT_REG)
                {
                    std::string filePath = path + "/" + entry->d_name;

                    std::ifstream modelFile(filePath);
                    if (!modelFile.is_open())
                        return false;

                    modelsContent << "const char json_" << entry->d_name << "[] = \\" << std::endl;

                    std::string jsonLine;
                    while (std::getline(modelFile, jsonLine)) {
                        if (jsonLine.length() != 0)
                            modelsContent << "    \"" << utils::replace_string(jsonLine, "\"", "\\\"") << "\" \\" << std::endl;
                    }

                    modelsContent << ";" << std::endl;

                    modelsContent << "const json mdl_" << entry->d_name << " = json::parse(" << "json_" << entry->d_name << ");" << std::endl;
                    modelsContent << "gadd_request_model reqModel_" << entry->d_name << "(\"" << entry->d_name << "\", mdl_" << entry->d_name << ");" << std::endl;
                }
            }
            closedir(currentDir);

            modelsContent << std::endl << std::endl << "}";
            modelsContent.close();

            return true;
        }
Example #8
0
bool HmcModule::doLoad()
{

    if(!fileExists(_modelPath))
    {
        Log::error("HMC model file not found");
        return false;
    }

    std::ifstream modelFile(_modelPath);
    CSVReader modelReader(modelFile);

    for(unsigned int i = 0;modelReader.hasNextLine();++i)
    {
        std::vector<std::string> modelLine;
        modelReader.readNextLine(modelLine);

        if(modelLine.size()<2)
            break;

        std::string name = modelLine[0];
        name[0]= toupper(name[0]);
        std::string type  = modelLine[1];

        addParser(name);
        const ObjectTypeTemplate& typeTemplate = newTemplate(name);
        setSpecification(EbmlModule::EBMLElement(i), typeTemplate());

        for(int j =0;j<EbmlModule::numberOfTypeElements;++j)
        {
            if(type == EbmlModule::typeElementAtributes[j])
            {
                setExtension(typeTemplate, getTemplate(EbmlModule::typeElements[j])());
                break;
            }
        }
    }
    return true;
}
Example #9
0
void ModelBaker::exportScene() {
    // save the relative path to this FBX inside our passed output folder
    auto fileName = _modelURL.fileName();
    auto baseName = fileName.left(fileName.lastIndexOf('.'));
    auto bakedFilename = baseName + BAKED_FBX_EXTENSION;

    _bakedModelFilePath = _bakedOutputDir + "/" + bakedFilename;

    auto fbxData = FBXWriter::encodeFBX(_rootNode);

    QFile bakedFile(_bakedModelFilePath);

    if (!bakedFile.open(QIODevice::WriteOnly)) {
        handleError("Error opening " + _bakedModelFilePath + " for writing");
        return;
    }

    bakedFile.write(fbxData);

    _outputFiles.push_back(_bakedModelFilePath);

#ifdef HIFI_DUMP_FBX
    {
        FBXToJSON fbxToJSON;
        fbxToJSON << _rootNode;
        QFileInfo modelFile(_bakedModelFilePath);
        QString outFilename(modelFile.dir().absolutePath() + "/" + modelFile.completeBaseName() + "_FBX.json");
        QFile jsonFile(outFilename);
        if (jsonFile.open(QIODevice::WriteOnly)) {
            jsonFile.write(fbxToJSON.str().c_str(), fbxToJSON.str().length());
            jsonFile.close();
        }
    }
#endif

    qCDebug(model_baking) << "Exported" << _modelURL << "with re-written paths to" << _bakedModelFilePath;
}
Example #10
0
  void ModelToRadJob::startImpl(const boost::shared_ptr<ProcessCreator> &)
  {
    openstudio::path outpath = outdir();
    QWriteLocker l(&m_mutex);
    JobErrors errors;
    errors.result = ruleset::OSResultValue::Success;
    
    try {
      if (!m_model)
      {
        m_model = modelFile();
      }
      if (!m_sql)
      {
        m_sql = sqlFile();
      }

      resetFiles(m_files, m_model);
    } catch (const std::runtime_error &e) {
      errors.result = ruleset::OSResultValue::Fail;
      errors.addError(ErrorType::Error, e.what());
    }

    if (!m_sql || !m_model)
    {
      errors.result = ruleset::OSResultValue::Fail;
      errors.addError(ErrorType::Error, "Unable to find required model or sql file");
    }

    LOG(Info, "ModelToRad starting, filename: " << toString(m_model->fullPath));
    LOG(Info, "ModelToRad starting, outdir: " << toString(outpath));

    l.unlock();

    emitStatusChanged(AdvancedStatus(AdvancedStatusEnum::Starting));

    emitStarted();
    emitStatusChanged(AdvancedStatus(AdvancedStatusEnum::Processing));

    if (errors.result == ruleset::OSResultValue::Fail)
    {
      setErrors(errors);
      return;
    }


    try {
      boost::filesystem::create_directories(outpath);

      //
      // setup
      //
      LOG(Debug, "Working Directory: " + openstudio::toString(outpath));

      // get model
      boost::optional<openstudio::IdfFile> idf = openstudio::IdfFile::load(m_model->fullPath);
      openstudio::model::Model model = openstudio::model::Model(idf.get());

      // load the sql file
      openstudio::SqlFile sqlFile(m_sql->fullPath);

      if (!sqlFile.connectionOpen())
      {
        LOG(Error, "SqlFile connection is not open");
        errors.result = ruleset::OSResultValue::Fail;
        errors.addError(ErrorType::Error, "SqlFile collection is not open");
        setErrors(errors);
        return;
      }

      // set the sql file
      model.setSqlFile(sqlFile);
      if (!model.sqlFile())
      {
        LOG(Error, "SqlFile is not set on model");
        errors.result = ruleset::OSResultValue::Fail;
        errors.addError(ErrorType::Error, "SqlFile is not set on model");
        setErrors(errors);
        return;
      }

      openstudio::radiance::ForwardTranslator ft;
      std::vector<openstudio::path> outfiles = ft.translateModel(outpath, model);
      
      // capture translator errors and warnings?
      //ft.errors();
      //ft.warnings();
      
      Files outfileinfos;

      for (std::vector<openstudio::path>::const_iterator itr = outfiles.begin();
          itr != outfiles.end();
          ++itr)
      {
        FileInfo fi = RunManager_Util::dirFile(*itr);
        LOG(Info, "Output file generated: " << openstudio::toString(fi.fullPath));
        emitOutputFileChanged(fi);
        outfileinfos.append(fi);
      }

      l.relock();

      m_outputfiles = outfileinfos;

      /// Do work here - and be sure to set output files too
    } catch (const std::runtime_error &e) {
      errors.addError(ErrorType::Error, "Error with conversion (runtime_error): " + std::string(e.what()));
      errors.result = ruleset::OSResultValue::Fail;
    }
    catch (const std::exception &e) {
      errors.addError(ErrorType::Error, "Error with conversion: " + std::string(e.what()));
      errors.result = ruleset::OSResultValue::Fail;
    }

    setErrors(errors);
  }
Example #11
0
void ModelBaker::bakeSourceCopy() {
    QFile modelFile(_originalOutputModelPath);
    if (!modelFile.open(QIODevice::ReadOnly)) {
        handleError("Error opening " + _originalOutputModelPath + " for reading");
        return;
    }
    hifi::ByteArray modelData = modelFile.readAll();

    std::vector<hifi::ByteArray> dracoMeshes;
    std::vector<std::vector<hifi::ByteArray>> dracoMaterialLists; // Material order for per-mesh material lookup used by dracoMeshes

    {
        auto serializer = DependencyManager::get<ModelFormatRegistry>()->getSerializerForMediaType(modelData, _modelURL, "");
        if (!serializer) {
            handleError("Could not recognize file type of model file " + _originalOutputModelPath);
            return;
        }
        hifi::VariantHash serializerMapping = _mapping;
        serializerMapping["combineParts"] = true; // set true so that OBJSerializer reads material info from material library
        serializerMapping["deduplicateIndices"] = true; // Draco compression also deduplicates, but we might as well shave it off to save on some earlier processing (currently FBXSerializer only)
        hfm::Model::Pointer loadedModel = serializer->read(modelData, serializerMapping, _modelURL);

        // Temporarily support copying the pre-parsed node from FBXSerializer, for better performance in FBXBaker
        // TODO: Pure HFM baking
        std::shared_ptr<FBXSerializer> fbxSerializer = std::dynamic_pointer_cast<FBXSerializer>(serializer);
        if (fbxSerializer) {
            qCDebug(model_baking) << "Parsing" << _modelURL;
            _rootNode = fbxSerializer->_rootNode;
        }

        baker::Baker baker(loadedModel, serializerMapping, _mappingURL);
        auto config = baker.getConfiguration();
        // Enable compressed draco mesh generation
        config->getJobConfig("BuildDracoMesh")->setEnabled(true);
        // Do not permit potentially lossy modification of joint data meant for runtime
        ((PrepareJointsConfig*)config->getJobConfig("PrepareJoints"))->passthrough = true;
    
        // Begin hfm baking
        baker.run();

        _hfmModel = baker.getHFMModel();
        _materialMapping = baker.getMaterialMapping();
        dracoMeshes = baker.getDracoMeshes();
        dracoMaterialLists = baker.getDracoMaterialLists();
    }

    // Do format-specific baking
    bakeProcessedSource(_hfmModel, dracoMeshes, dracoMaterialLists);

    if (shouldStop()) {
        return;
    }

    if (!_hfmModel->materials.isEmpty()) {
        _materialBaker = QSharedPointer<MaterialBaker>(
            new MaterialBaker(_modelURL.fileName(), true, _bakedOutputDir),
            &MaterialBaker::deleteLater
        );
        _materialBaker->setMaterials(_hfmModel->materials, _modelURL.toString());
        connect(_materialBaker.data(), &MaterialBaker::finished, this, &ModelBaker::handleFinishedMaterialBaker);
        _materialBaker->bake();
    } else {
        bakeMaterialMap();
    }
}
Example #12
0
bool TestRenderer::AddMeshes(const std::wstring& contentRoot, const std::wstring& modelFilename)
{
    static_assert(sizeof(ModelVertex) == sizeof(Vertex), "Make sure structures (and padding) match so we can read directly!");

    FileHandle modelFile(CreateFile((contentRoot + modelFilename).c_str(), GENERIC_READ,
        FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr));
    if (!modelFile.IsValid())
    {
        LogError(L"Failed to open asset file.");
        return false;
    }

    DWORD bytesRead{};
    ModelHeader header{};
    if (!ReadFile(modelFile.Get(), &header, sizeof(header), &bytesRead, nullptr))
    {
        LogError(L"Failed to read file.");
        return false;
    }

    if (header.Signature != header.ExpectedSignature)
    {
        LogError(L"Invalid model file.");
        return false;
    }

    TheScene.reset(new Scene);

    TheScene->VertexCount = header.NumVertices;
    TheScene->IndexCount = header.NumIndices;

    std::unique_ptr<Vertex[]> vertices(new Vertex[header.NumVertices]);
    if (!ReadFile(modelFile.Get(), vertices.get(), header.NumVertices * sizeof(Vertex), &bytesRead, nullptr))
    {
        LogError(L"Failed to read file.");
        return false;
    }

    D3D11_BUFFER_DESC bd {};
    bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    bd.ByteWidth = sizeof(Vertex) * header.NumVertices;
    bd.StructureByteStride = sizeof(Vertex);
    bd.Usage = D3D11_USAGE_DEFAULT;

    D3D11_SUBRESOURCE_DATA init{};
    init.pSysMem = vertices.get();
    init.SysMemPitch = bd.ByteWidth;
    init.SysMemSlicePitch = init.SysMemPitch;

    HRESULT hr = Device->CreateBuffer(&bd, &init, &TheScene->VertexBuffer);
    if (FAILED(hr))
    {
        LogError(L"Failed to read file.");
        return false;
    }

    // Free up memory
    vertices.reset();

    std::unique_ptr<uint32_t[]> indices(new uint32_t[header.NumIndices]);
    if (!ReadFile(modelFile.Get(), indices.get(), header.NumIndices * sizeof(uint32_t), &bytesRead, nullptr))
    {
        LogError(L"Failed to read file.");
        return false;
    }

    bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
    bd.ByteWidth = sizeof(uint32_t) * header.NumIndices;
    bd.StructureByteStride = sizeof(uint32_t);

    init.pSysMem = indices.get();
    init.SysMemPitch = bd.ByteWidth;
    init.SysMemSlicePitch = init.SysMemPitch;

    hr = Device->CreateBuffer(&bd, &init, &TheScene->IndexBuffer);
    if (FAILED(hr))
    {
        LogError(L"Failed to read file.");
        return false;
    }

    // Free up memory
    indices.reset();

    // Load objects
    for (int iObj = 0; iObj < (int)header.NumObjects; ++iObj)
    {
        ModelObject object{};
        if (!ReadFile(modelFile.Get(), &object, sizeof(object), &bytesRead, nullptr))
        {
            LogError(L"Failed to read file.");
            return false;
        }

        std::shared_ptr<Object> obj = std::make_shared<Object>();
        obj->Name = object.Name;
        XMStoreFloat4x4(&obj->World, XMMatrixIdentity());

        for (int iPart = 0; iPart < (int)object.NumParts; ++iPart)
        {
            ModelPart part{};
            if (!ReadFile(modelFile.Get(), &part, sizeof(part), &bytesRead, nullptr))
            {
                LogError(L"Failed to read file.");
                return false;
            }

            Mesh mesh{};
            mesh.StartIndex = part.StartIndex;
            mesh.NumIndices = part.NumIndices;

            if (part.DiffuseTexture[0] != 0)
            {
                std::wstring path = contentRoot + part.DiffuseTexture;
                auto it = CachedTextureMap.find(path);
                if (it == CachedTextureMap.end())
                {
                    if (!LoadTexture(path, &mesh.AlbedoSRV))
                    {
                        LogError(L"Failed to load texture.");
                        return false;
                    }
                    CachedTextureMap[path] = mesh.AlbedoSRV;
                }
                else
                {
                    mesh.AlbedoSRV = it->second;
                }
            }
            if (part.NormalTexture[0] != 0)
            {
                std::wstring path = contentRoot + part.NormalTexture;
                auto it = CachedTextureMap.find(path);
                if (it == CachedTextureMap.end())
                {
                    if (!LoadTexture(path, &mesh.BumpDerivativeSRV))
                    {
                        LogError(L"Failed to load texture.");
                        return false;
                    }
                    CachedTextureMap[path] = mesh.BumpDerivativeSRV;
                }
                else
                {
                    mesh.BumpDerivativeSRV = it->second;
                }
            }
            if (part.SpecularTexture[0] != 0)
            {
                std::wstring path = contentRoot + part.SpecularTexture;
                auto it = CachedTextureMap.find(path);
                if (it == CachedTextureMap.end())
                {
                    if (!LoadTexture(path, &mesh.SpecularSRV))
                    {
                        LogError(L"Failed to load texture.");
                        return false;
                    }
                    CachedTextureMap[path] = mesh.SpecularSRV;
                }
                else
                {
                    mesh.SpecularSRV = it->second;
                }
            }

            obj->Meshes.push_back(mesh);
        }

        TheScene->Objects.push_back(obj);
    }

    return true;
}
Example #13
0
  void ModelInModelOutJob::startImpl(const std::shared_ptr<ProcessCreator> &)
  {
    openstudio::path outpath = outdir(true);

    QWriteLocker l(&m_mutex);
    if (!m_model)
    {
      m_model = modelFile();
      resetFiles(m_files, m_model);
    }

    std::vector<std::shared_ptr<ModelInModelOutJob> > mergedJobs = m_mergedJobs;
    boost::optional<FileInfo> model = m_model;

    LOG(Info, "ModelInModelOut starting, filename: " << toString(m_model->fullPath));
    LOG(Info, "ModelInModelOut starting, outdir: " << toString(outpath));
    LOG(Info, "ModelInModelOut starting, num merged jobs: " << m_mergedJobs.size());

    m_lastrun = QDateTime::currentDateTime();
    JobErrors errors;
    errors.result = ruleset::OSResultValue::Success;
    l.unlock();

    emitStatusChanged(AdvancedStatus(AdvancedStatusEnum::Starting));

    emitStarted();
    emitStatusChanged(AdvancedStatus(AdvancedStatusEnum::Processing));

    try {
      boost::filesystem::create_directories(outpath);

      model::OptionalModel m = model::Model::load(model->fullPath);

      if (!m)
      {
        errors.addError(ErrorType::Error, "Unable to load model: " + toString(model->fullPath));
        errors.result = ruleset::OSResultValue::Fail;
      } else {
        LOG(Info, "ModelInModelOut executing primary job");
        model::Model outmodel = modelToModelRun(*m);

        for (const auto & mergedJob : mergedJobs)
        {
          LOG(Info, "ModelInModelOut executing merged job");
          outmodel = mergedJob->modelToModelRun(outmodel);
        }

        openstudio::path outFile = outpath / toPath("out.osm");
        if (!outmodel.save(outFile,true))
        {
          errors.addError(ErrorType::Error, "Error while writing final output file");
          errors.result = ruleset::OSResultValue::Fail;
        }
      }
    } catch (const std::exception &e) {
      errors.addError(ErrorType::Error, "Error with processing: " + std::string(e.what()));
      errors.result = ruleset::OSResultValue::Fail;
    }

    emitOutputFileChanged(RunManager_Util::dirFile(outpath / openstudio::toPath("out.osm")));
    setErrors(errors);
  }
Example #14
0
int CUserMgr::HandleHeader(CMission* pMission)
{
	ST_CMD_HEADER header = *(ST_CMD_HEADER*)pMission->m_pMissionData;
	CNetUser* pUser = pMission->m_pUser;

	BOOL bFind = TRUE; //该命令是否被处理
	switch (header.usCmd)
	{
	case USER_LOGIN:
		{
			ST_LOGIN_INFO  LoginInfo = *(pStLoginInfo)(pMission->m_pMissionData + HEAD_SIZE);
			std::cout << "login info: " << LoginInfo.szUserNo << ", pwd: " << LoginInfo.szPWD << std::endl;
			
// 			_mapUserLock_.lock();
// 			MAP_USER::iterator itFind = _mapUser_.find(LoginInfo.szUserNo);
// 			if (itFind != _mapUser_.end())
// 			{
// 				//重复登录提醒,
// 				std::string strSendData = "账号已登录";
// 
// 				pUser->SendResponesInfo(USER_RESPONSE_LOGIN, RESULT_LOGIN_FAIL, (char*)strSendData.c_str(), strSendData.length());
// 				_mapUserLock_.unlock();
// 				return 1;
// 			}
// 			_mapUserLock_.unlock();

			#ifdef TEST_MODE
			_mapUserLock_.lock();
			MAP_USER::iterator itFind2 = _mapUser_.find(LoginInfo.szUserNo);
			if (itFind2 == _mapUser_.end())
			{
				_mapUser_.insert(MAP_USER::value_type(LoginInfo.szUserNo, pUser));
			}
			else
			{
				itFind2->second = pUser;
			}
			_mapUserLock_.unlock();

			ST_LOGIN_RESULT stResult;
			ZeroMemory(&stResult, sizeof(stResult));
			stResult.nTeacherId = 100;
			stResult.nUserId = 200;
			std::string strEzs = "1234567890abcdefghijklmnopqrstuvwxyz";
			strncpy(stResult.szEzs, strEzs.c_str(), strEzs.length());
			strncpy(stResult.szUserInfo, LoginInfo.szUserNo, 100);

			char szLoginResult[1024] = { 0 };
			memcpy(szLoginResult, (char*)&stResult, sizeof(stResult));

			pUser->UpdateLogonInfo(LoginInfo.szUserNo, LoginInfo.szPWD);
			pUser->SendResponesInfo(USER_RESPONSE_LOGIN, RESULT_SUCCESS, szLoginResult, sizeof(stResult));
			return 1;
			#endif

//		#ifdef TO_WHTY
		#if 1
			pSCAN_REQ_TASK pTask = NULL;
			if(SysSet.m_nServerMode == 1)
			{
				std::string strAppKey = "SP0000000TEST";
				std::string strAppValue = "63d4311d46714a39-a54cf2b0537a79b6TEST";
				std::string strMsgFormat = "json";
				std::string strMethod = "login111";
				std::string strPwd = LoginInfo.szPWD;
				std::string strUser = LoginInfo.szUserNo;
				std::string strSha1Src = Poco::format("%sappKey%smessageFormat%smethod%spassword%susername%sv1.0%s", strAppValue, strAppKey, strMsgFormat, strMethod, strPwd, strUser, strAppValue);
				Poco::SHA1Engine engine;
				engine.update(strSha1Src);
				std::string strSHA1 = Poco::DigestEngine::digestToHex(engine.digest());
				std::string strSHA1_Up = Poco::toUpper(strSHA1);
				std::string strUriValue = Poco::format("/router?appKey=%s&messageFormat=%s&method=%s&password=%s&sign=%s&username=%s&v=1.0", strAppKey, strMsgFormat, strMethod, strPwd, strSHA1_Up, strUser);

				pTask = new SCAN_REQ_TASK;
				pTask->strUri		= SysSet.m_strBackUri + strUriValue;
				pTask->pUser		= pUser;
				pTask->strMsg		= "login2Ty";
				pTask->strUser		= LoginInfo.szUserNo;
				pTask->strPwd		= LoginInfo.szPWD;
				std::string strLog = Poco::format("天喻登录: src_SHA1 = %s\nSHA1 = %s\nuri = %s", strSha1Src, strSHA1_Up, pTask->strUri);
				g_Log.LogOut(strLog);
			}
			else
			{
				pTask = new SCAN_REQ_TASK;
				pTask->pUser = pUser;
				pTask->strUser = LoginInfo.szUserNo;
				pTask->strPwd = LoginInfo.szPWD;

				switch (SysSet.m_nUseThirdPlatform)
				{
					case 3:		//成都佳发,用的天喻系统,登录方法改变
					case 1:		//武汉天喻
						{
							std::string strAppKey = "SP0000000TEST";
							std::string strAppValue = "63d4311d46714a39-a54cf2b0537a79b6TEST";
							std::string strMsgFormat = "json";
							std::string strMethod = "login111";
							if (SysSet.m_nUseThirdPlatform == 3)
								strMethod = "loginjf";
							std::string strPwd = LoginInfo.szPWD;
							std::string strUser = LoginInfo.szUserNo;
							std::string strSha1Src = Poco::format("%sappKey%smessageFormat%smethod%spassword%susername%sv1.0%s", strAppValue, strAppKey, strMsgFormat, strMethod, strPwd, strUser, strAppValue);
							Poco::SHA1Engine engine;
							engine.update(strSha1Src);
							std::string strSHA1 = Poco::DigestEngine::digestToHex(engine.digest());
							std::string strSHA1_Up = Poco::toUpper(strSHA1);
							std::string strUriValue = Poco::format("/router?appKey=%s&messageFormat=%s&method=%s&password=%s&sign=%s&username=%s&v=1.0", strAppKey, strMsgFormat, strMethod, strPwd, strSHA1_Up, strUser);

							pTask->strUri = SysSet.m_str3PlatformUrl + strUriValue;
							pTask->strMsg = "login2Ty";
						}
						break;
					case 2:		//山西寰烁
						{
							pTask->strUri = SysSet.m_str3PlatformUrl + "?username="******"&password="******"login_SanXi_huanshuo";
						}
						break;
					default:	//默认易考乐学后端平台
						{
							pTask->strUri = SysSet.m_strBackUri + "/login";
							pTask->strMsg = "login";
							char szTmp[200] = { 0 };
							sprintf(szTmp, "username=%s&password=%s", LoginInfo.szUserNo, LoginInfo.szPWD);
							pTask->strRequest = szTmp;
						}
				}

				std::string strLog = Poco::format("登录命令: msg = %s(%s:%s)\nurl = %s", pTask->strMsg, pTask->strUser, pTask->strPwd, pTask->strUri);
				g_Log.LogOut(strLog);
			}
		#else
			pSCAN_REQ_TASK pTask = new SCAN_REQ_TASK;
			pTask->strUri		= SysSet.m_strBackUri + "/login";
			pTask->pUser		= pUser;
			pTask->strMsg		= "login";
			pTask->strUser		= LoginInfo.szUserNo;
			pTask->strPwd		= LoginInfo.szPWD;
			char szTmp[200] = { 0 };
			sprintf(szTmp, "username=%s&password=%s", LoginInfo.szUserNo, LoginInfo.szPWD);
			pTask->strRequest = szTmp;
		#endif
			g_fmScanReq.lock();
			g_lScanReq.push_back(pTask);
			g_fmScanReq.unlock();
		}
		break;
	case USER_LOGIN_4TY:
		{
			ST_LOGIN_INFO4TY  LoginInfo = *(pStLoginInfo4TY)(pMission->m_pMissionData + HEAD_SIZE);
			std::cout << "login info: " << LoginInfo.szUserNo << ", pwd: " << LoginInfo.szPWD << ", platformcode: " << LoginInfo.szPlatformCode <<
				", encryption: " << LoginInfo.szEncryption << ", platformUrl: " << LoginInfo.szPlatformUrl << std::endl;
			std::string strAppKey = "SP0000000TEST";
			std::string strAppValue = "63d4311d46714a39-a54cf2b0537a79b6TEST";
			std::string strMsgFormat = "json";
			std::string strMethod = "login111";
			std::string strPwd = LoginInfo.szPWD;
			std::string strUser = LoginInfo.szUserNo;
			std::string strEncryption = LoginInfo.szEncryption;
			std::string strPlatformCode = LoginInfo.szPlatformCode;
			std::string strPlatformUrl = LoginInfo.szPlatformUrl;
			std::string strSha1Src = Poco::format("%sappKey%sencryption%smessageFormat%smethod%spassword%splatformUrl%splatformcode%susername%sv1.0%s", \
												  strAppValue, strAppKey, strEncryption, strMsgFormat, strMethod, strPwd, strPlatformUrl, strPlatformCode, strUser, strAppValue);
			Poco::SHA1Engine engine;
			engine.update(strSha1Src);
			std::string strSHA1 = Poco::DigestEngine::digestToHex(engine.digest());
			std::string strSHA1_Up = Poco::toUpper(strSHA1);
			std::string strUriValue = Poco::format("/router?appKey=%s&encryption=%s&messageFormat=%s&method=%s&password=%s&platformUrl=%s&platformcode=%s&sign=%s&username=%s&v=1.0",\
												   strAppKey, strEncryption, strMsgFormat, strMethod, strPwd, strPlatformUrl, strPlatformCode, strSHA1_Up, strUser);

			pSCAN_REQ_TASK pTask = new SCAN_REQ_TASK;
			if (SysSet.m_nServerMode == 0)	//非天喻服务器模式,则进入此处为登录第3方天喻平台
				pTask->strUri = SysSet.m_str3PlatformUrl + strUriValue;
			else
				pTask->strUri	= SysSet.m_strBackUri + strUriValue;
			pTask->pUser	= pUser;
			pTask->strMsg	= "login2Ty";
			pTask->strUser	= LoginInfo.szUserNo;
			pTask->strPwd	= LoginInfo.szPWD;
			std::string strLog = Poco::format("天喻登录平台: src_SHA1 = %s\nSHA1 = %s\nuri = %s", strSha1Src, strSHA1_Up, pTask->strUri);
			g_Log.LogOut(strLog);

			g_fmScanReq.lock();
			g_lScanReq.push_back(pTask);
			g_fmScanReq.unlock();
		}
		break;
	case USER_LOGOUT:
		{
			char szData[1024] = { 0 };
			strncpy(szData, pMission->m_pMissionData + HEAD_SIZE, header.uPackSize);
			std::string strUser = szData;

			_mapUserLock_.lock();
			MAP_USER::iterator itFind = _mapUser_.find(strUser);
			if (itFind != _mapUser_.end())
			{
				_mapUser_.erase(itFind);

				std::string strLog = "账号" + strUser + "退出登录";

				pUser->SendResponesInfo(USER_RESPONSE_LOGOUT, RESULT_SUCCESS, (char*)strUser.c_str(), strUser.length());
				g_Log.LogOut(strLog);
			}
			_mapUserLock_.unlock();

		}
		break;
	case USER_GETEXAMINFO:
		{
			ST_EXAM_INFO stExamInfo = *(pStExamInfo)(pMission->m_pMissionData + HEAD_SIZE);
			std::string strEzs = stExamInfo.szEzs;
			int	nUserID = stExamInfo.nUserId;
			std::cout << "获取考试列表: " << pUser->m_Name <<std::endl;

			#ifdef TEST_MODE
			#if 1
			std::string strExamListPath = SysSet.m_strCurrentDir + "\\ServerTestData\\ServerTestData-examlist.txt";
			std::string strJsnData;
			std::ifstream in(strExamListPath);

			if (!in) return false;

			std::string strJsnLine;
			while (!in.eof())
			{
				getline(in, strJsnLine);
				strJsnData.append(strJsnLine);
			}
			in.close();
			
			pUser->SendResponesInfo(USER_RESPONSE_EXAMINFO, RESULT_EXAMINFO_SUCCESS, (char*)strJsnData.c_str(), strJsnData.length());
			return 1;
			#else
			Poco::JSON::Object jsnSubject1;
			jsnSubject1.set("id", 200);
			jsnSubject1.set("name", CMyCodeConvert::Gb2312ToUtf8("语文"));
			jsnSubject1.set("code", 1001);
			jsnSubject1.set("scanTemplateName", "100_200.mod");
			Poco::JSON::Object jsnSubject2;
			jsnSubject2.set("id", 201);
			jsnSubject2.set("name", CMyCodeConvert::Gb2312ToUtf8("数学"));
			jsnSubject2.set("code", 1002);
			jsnSubject2.set("scanTemplateName", "100_201.mod");

			Poco::JSON::Array jsnSubjectArry;
			jsnSubjectArry.add(jsnSubject1);
			jsnSubjectArry.add(jsnSubject2);
			Poco::JSON::Object jsnExamObj;
			jsnExamObj.set("id", 100);
			jsnExamObj.set("name", CMyCodeConvert::Gb2312ToUtf8("高三期末考试"));
			Poco::JSON::Object jsnExamTypeObj;
			jsnExamTypeObj.set("id", 33);
			jsnExamTypeObj.set("name", CMyCodeConvert::Gb2312ToUtf8("期末考试"));
			jsnExamObj.set("examType", jsnExamTypeObj);
			Poco::JSON::Object jsnGrade;
			jsnGrade.set("id", 5);
			jsnGrade.set("name", CMyCodeConvert::Gb2312ToUtf8("高三"));
			jsnGrade.set("aliasName", "");
			jsnExamObj.set("grade", jsnGrade);
			jsnExamObj.set("examSubjects", jsnSubjectArry);
			jsnExamObj.set("state", 1);
			Poco::JSON::Array jsnExamArry;
			jsnExamArry.add(jsnExamObj);

			Poco::JSON::Object jsnResult;
			jsnResult.set("exams", jsnExamArry);

			Poco::JSON::Object jsnStatus;
			jsnStatus.set("success", true);
			jsnResult.set("status", jsnStatus);

			std::stringstream jsnString;
			jsnResult.stringify(jsnString, 0);
			pUser->SendResponesInfo(USER_RESPONSE_EXAMINFO, RESULT_EXAMINFO_SUCCESS, (char*)jsnString.str().c_str(), jsnString.str().length());
			return 1;
			#endif
			#endif

//		#ifdef TO_WHTY
		#if 1
			pSCAN_REQ_TASK pTask = NULL;
			if (SysSet.m_nServerMode == 1)
			{
				std::string strAppKey = "SP0000000TEST";
				std::string strAppValue = "63d4311d46714a39-a54cf2b0537a79b6TEST";
				std::string strMsgFormat = "json";
				std::string strMethod = "examinfo";

				std::string strPersonId;
				std::string strSchoolID;
				std::string strTmp = stExamInfo.szEzs;
				int nPos = strTmp.find("###");
				if (nPos != std::string::npos)
				{
					std::string strEzs = strTmp.substr(0, nPos);
					strSchoolID = strTmp.substr(nPos + 3);
					strPersonId = strEzs;
				}
				else
				{
					strPersonId = stExamInfo.szEzs;
				}
//				std::string strPersonId = stExamInfo.szEzs;
				std::string strSha1Src = Poco::format("%sappKey%smessageFormat%smethod%sperson_id%sv1.0%s", strAppValue, strAppKey, strMsgFormat, strMethod, strPersonId, strAppValue);
				Poco::SHA1Engine engine;
				engine.update(strSha1Src);
				std::string strSHA1 = Poco::DigestEngine::digestToHex(engine.digest());
				std::string strSHA1_Up = Poco::toUpper(strSHA1);
//				std::string strUriValue = Poco::format("/router?appKey=%s&messageFormat=%s&method=%s&person_id=%s&sign=%s&v=1.0", strAppKey, strMsgFormat, strMethod, strPersonId, strSHA1_Up);
				std::string strUriValue;
				if (nPos != std::string::npos)
					strUriValue = Poco::format("/router?appKey=%s&messageFormat=%s&method=%s&person_id=%s&school_id=%s&sign=%s&v=1.0", strAppKey, strMsgFormat, strMethod, strPersonId, strSchoolID, strSHA1_Up);	//2017.6.20添加school_id
				else
					strUriValue = Poco::format("/router?appKey=%s&messageFormat=%s&method=%s&person_id=%s&sign=%s&v=1.0", strAppKey, strMsgFormat, strMethod, strPersonId, strSHA1_Up);

				pTask = new SCAN_REQ_TASK;
				pTask->strUri = SysSet.m_strBackUri + strUriValue;
				pTask->pUser = pUser;
				pTask->strEzs = SysSet.m_strSessionName + strEzs;		//"ezs=" + strEzs;
				pTask->strMsg = "ezs";

				std::string strLog = Poco::format("天喻平台,获取考试列表: src_SHA1 = %s\nSHA1 = %s\nuri = %s", strSha1Src, strSHA1_Up, pTask->strUri);
				g_Log.LogOut(strLog);
			}
			else
			{
				pTask = new SCAN_REQ_TASK;
				std::string strUserID = Poco::format("%d", nUserID);
				if (SysSet.m_nQuYuVersion)
					pTask->strUri = SysSet.m_strBackUri + "/examinfo";
				else
					pTask->strUri = SysSet.m_strBackUri + "/examinfo/" + strUserID;
				pTask->pUser  = pUser;
				pTask->strEzs = SysSet.m_strSessionName + strEzs;		//"ezs=" + strEzs;
				pTask->strMsg = "ezs";
			}
			
		#else
			pSCAN_REQ_TASK pTask = new SCAN_REQ_TASK;
			pTask->strUri = SysSet.m_strBackUri + "/examinfo";
			pTask->pUser  = pUser;
			pTask->strEzs = SysSet.m_strSessionName + strEzs;		//"ezs=" + strEzs;
			pTask->strMsg = "ezs";
		#endif
			g_fmScanReq.lock();
			g_lScanReq.push_back(pTask);
			g_fmScanReq.unlock();
		}
		break;
	case USER_SETMODELINFO:
		{
			ST_MODELINFO stModelInfo = *(pST_MODELINFO)(pMission->m_pMissionData + HEAD_SIZE);
			bool bNeedSend = false;
			char szIndex[50] = { 0 };
			sprintf(szIndex, "%d_%d", stModelInfo.nExamID, stModelInfo.nSubjectID);

			std::cout << "设置考试模板命令: " << szIndex << std::endl;
			std::stringstream ssLog;
			ssLog << "设置考试模板命令: " << szIndex << "\n";

			MAP_MODEL::iterator itFind = _mapModel_.find(szIndex);
			if (itFind == _mapModel_.end())
			{
				bNeedSend = true;
				ssLog << "模板信息映射表中未找到" << szIndex << "的信息,可以发送此模板的信息[Ezs = " << stModelInfo.szEzs << "]\n";
				//g_Log.LogOut(strLog);

				pST_MODELINFO pStModelInfo = new ST_MODELINFO;
				memcpy(pStModelInfo, &stModelInfo, sizeof(stModelInfo));

				pMODELINFO pModelInfo = new MODELINFO;
				pModelInfo->nExamID = stModelInfo.nExamID;
				pModelInfo->nSubjectID = stModelInfo.nSubjectID;
				pModelInfo->strName = stModelInfo.szModelName;
				pModelInfo->strEzs = stModelInfo.szEzs;
				pModelInfo->strElectOmr = stModelInfo.szElectOmr;
				pModelInfo->strMd5 = stModelInfo.szMD5;
				pModelInfo->pUploadModelInfo = pStModelInfo;
				pModelInfo->pUser = pUser;

				_mapModelLock_.lock();
				_mapModel_.insert(MAP_MODEL::value_type(szIndex, pModelInfo));
				_mapModelLock_.unlock();

				ssLog << "添加新的模板信息,等待接收模板文件: " << stModelInfo.szModelName << "\n";
			}
			else
			{
				pMODELINFO pModelInfo = itFind->second;
				try
				{
					Poco::File modelFile(CMyCodeConvert::Gb2312ToUtf8(pModelInfo->strPath));
					if (!modelFile.exists())
						pModelInfo->strMd5 = "";
				}
				catch (Poco::Exception&exc)
				{
				}
				if (pModelInfo->strMd5 != stModelInfo.szMD5)		//文件有修改,需要重新发送
				{
					bNeedSend = true;

					pST_MODELINFO pStModelInfo = new ST_MODELINFO;
					memcpy(pStModelInfo, &stModelInfo, sizeof(stModelInfo));

					SAFE_RELEASE(pModelInfo->pUploadModelInfo);
					pModelInfo->pUploadModelInfo = pStModelInfo;
					pModelInfo->pUser = pUser;

					pModelInfo->nExamID = stModelInfo.nExamID;
					pModelInfo->nSubjectID = stModelInfo.nSubjectID;
					pModelInfo->strName = stModelInfo.szModelName;
					pModelInfo->strEzs = stModelInfo.szEzs;
					pModelInfo->strElectOmr = stModelInfo.szElectOmr;
					pModelInfo->strMd5 = stModelInfo.szMD5;

					ssLog << "模板信息映射表中" << szIndex << "的文件MD5与需要上传的文件MD5信息不一致,可以发送此模板的信息[Ezs = " << pModelInfo->strEzs <<"]";
				}
				else
					std::cout << "文件未修改,不需要重传" << std::endl;
			}

			if (bNeedSend)
			{
				pUser->SendResponesInfo(USER_RESPONSE_MODELINFO, RESULT_SETMODELINFO_SEND, (char*)&stModelInfo, sizeof(stModelInfo));

				
				#ifdef TEST_MODE
				return 1;
				#endif

		#if 0				//需要先解压后提交图片MD5再去后端设置信息
				Poco::JSON::Object jsnModel;
				jsnModel.set("examId", stModelInfo.nExamID);
				jsnModel.set("subjectId", stModelInfo.nSubjectID);
				jsnModel.set("tmplateName", stModelInfo.szModelName);
				jsnModel.set("modelElectOmr", stModelInfo.szElectOmr);

				std::stringstream jsnString;
				jsnModel.stringify(jsnString, 0);

				std::string strEzs = stModelInfo.szEzs;
				pSCAN_REQ_TASK pTask = new SCAN_REQ_TASK;
				pTask->strUri = SysSet.m_strBackUri + "/scanTemplate";
				pTask->pUser = pUser;
				pTask->strEzs = "ezs=" + strEzs;
				pTask->strMsg = "setScanModel";
				pTask->strRequest = jsnString.str();
				g_fmScanReq.lock();
				g_lScanReq.push_back(pTask);
				g_fmScanReq.unlock();
		#endif
			}
			else
				pUser->SendResult(USER_RESPONSE_MODELINFO, RESULT_SETMODELINFO_NO);

			g_Log.LogOut(ssLog.str());
		}
		break;
	case USER_NEED_DOWN_MODEL:
		{
			ST_DOWN_MODEL stModelInfo = *(pST_DOWN_MODEL)(pMission->m_pMissionData + HEAD_SIZE);

			bool bNeedDown = true;
			char szIndex[50] = { 0 };
			sprintf(szIndex, "%d_%d", stModelInfo.nExamID, stModelInfo.nSubjectID);

			std::cout << "请求下载模板命令: " << szIndex << std::endl;
			std::stringstream ssLog;
			ssLog << "请求下载模板命令: " << szIndex << "\n";

			pMODELINFO pModelInfo = NULL;
			MAP_MODEL::iterator itFind = _mapModel_.find(szIndex);
			if (itFind == _mapModel_.end())
			{
				pUser->SendResult(USER_RESPONSE_NEEDDOWN, RESULT_DOWNMODEL_FAIL);
				ssLog << "请求下载的模板文件不存在\n";
				break;
			}
			else
			{
				pModelInfo = itFind->second;
				if (pModelInfo->strMd5 == stModelInfo.szMD5)		//文件未修改,不需要重新下载
					bNeedDown = false;
			}
			if (bNeedDown)
			{
				try
				{
					Poco::File fileModel(CMyCodeConvert::Gb2312ToUtf8(pModelInfo->strPath));
					stModelInfo.nModelSize = static_cast<int>(fileModel.getSize());
					pUser->SendResponesInfo(USER_RESPONSE_NEEDDOWN, RESULT_DOWNMODEL_OK, (char*)&stModelInfo, sizeof(stModelInfo));
					ssLog << "可以正常下载";
				}
				catch (Poco::Exception& exc)
				{
					std::string strLog = "请求下载模板命令(" + std::string(szIndex) + ")-->检测模板文件路径异常: " + exc.displayText();
					std::cout << strLog << std::endl;
					ssLog << strLog;
					pUser->SendResult(USER_RESPONSE_NEEDDOWN, RESULT_DOWNMODEL_FAIL);
				}
			}
			else
			{
				pUser->SendResult(USER_RESPONSE_NEEDDOWN, RESULT_DOWNMODEL_NONEED);
				ssLog << "不需要重新下载模板\n";
			}
			g_Log.LogOut(ssLog.str());
		}
		break;
	case USER_DOWN_MODEL:
		{
			ST_DOWN_MODEL stModelInfo = *(pST_DOWN_MODEL)(pMission->m_pMissionData + HEAD_SIZE);

			std::string strCmdResponse = Poco::format("Get Cmd %d OK", (int)USER_DOWN_MODEL);
			//pUser->SendResponesInfo(USER_RESPONSE_DOWNMODEL, RESULT_SUCCESS, (char*)strCmdResponse.c_str(), strCmdResponse.length());

			bool bNeedDown = true;
			char szIndex[50] = { 0 };
			sprintf(szIndex, "%d_%d", stModelInfo.nExamID, stModelInfo.nSubjectID);

			std::cout << "开始下载考试模板命令: " << szIndex << std::endl;
			std::stringstream ssLog;
			ssLog << "开始下载考试模板命令: " << szIndex << "\n";

			MAP_MODEL::iterator itFind = _mapModel_.find(szIndex);
			if (itFind == _mapModel_.end())
			{
			}
			else
			{
				pMODELINFO pModelInfo = itFind->second;
				
 				std::string strFileData;

				std::ifstream fin(pModelInfo->strPath, std::ifstream::binary);
				if (!fin)
				{
					pUser->SendResult(USER_RESPONSE_DOWNMODEL, RESULT_ERROR_FILEIO);
					return false;
				}
				std::stringstream buffer;
				buffer << fin.rdbuf();
				strFileData = buffer.str();
				fin.close();

				int nLen = strFileData.length();
				std::cout << "模板长度: " << nLen << std::endl;
				ssLog << "模板长度: " << nLen << "\n";
// 				ofstream out("1.mod", std::ios::binary);
// 				std::stringstream buffer2;
// 				buffer2.write(strFileData.c_str(), strFileData.length());
// 				int n = buffer2.str().length();
// 				out << buffer2.str();
// 				out.close();

				pUser->SendResponesInfo(USER_RESPONSE_DOWNMODEL, RESULT_DOWNMODEL_RECV, (char*)strFileData.c_str(), strFileData.length());
				std::cout << "下载考试模板文件完成: " << szIndex << std::endl;
				ssLog << "下载考试模板文件完成: " << szIndex;
				g_Log.LogOut(ssLog.str());
			}
		}
		break;
	case USER_NEED_CREATE_MODEL:
		{
			ST_CREATE_MODEL stModelInfo = *(pST_CREATE_MODEL)(pMission->m_pMissionData + HEAD_SIZE);

			char szIndex[50] = { 0 };
			sprintf(szIndex, "%d_%d", stModelInfo.nExamID, stModelInfo.nSubjectID);

			std::cout << "请求自动创建模板命令: " << szIndex << std::endl;

			_mapModelLock_.lock();
			pMODELINFO pModelInfo = NULL;
			MAP_MODEL::iterator itFind = _mapModel_.find(szIndex);
			if (itFind == _mapModel_.end())		//服务器上没有模板,请求后端提供数据生成模板
			{
				pModelInfo = new MODELINFO;
				pModelInfo->nExamID = stModelInfo.nExamID;
				pModelInfo->nSubjectID = stModelInfo.nSubjectID;

				_mapModel_.insert(MAP_MODEL::value_type(szIndex, pModelInfo));
			}
			_mapModelLock_.unlock();

			pSCAN_REQ_TASK pTask = new SCAN_REQ_TASK;
			pTask->strUri = Poco::format("%s/sheet/data/%d/%d", SysSet.m_strBackUri, stModelInfo.nExamID, stModelInfo.nSubjectID);
			pTask->pUser = pUser;
			pTask->strMsg = "createModel";
			pTask->nExamID = stModelInfo.nExamID;
			pTask->nSubjectID = stModelInfo.nSubjectID;
			pTask->strEzs = stModelInfo.szEzs;
			pTask->strExamName = stModelInfo.szExamName;
			pTask->strSubjectName = stModelInfo.szSubjectName;

			g_fmScanReq.lock();
			g_lScanReq.push_back(pTask);
			g_fmScanReq.unlock();
		}
		break;
	case GET_VERSERVER_ADDR:
		{
			std::stringstream ss;
			ss << SysSet.m_strVerServerIP << ":" << SysSet.m_nVerServerPort;
			std::string strVerAddr = ss.str();
			pUser->SendResponesInfo(RESPONSE_GET_VERSERVER_ADDR, RESULT_SUCCESS, (char*)strVerAddr.c_str(), strVerAddr.length());
			std::cout << "回复版本服务器地址信息:" << strVerAddr << std::endl;
		}
		break;
	case USER_GET_BMK:
		{
			ST_GET_BMK_INFO stGetBmkInfo = *(pStGetBmkInfo)(pMission->m_pMissionData + HEAD_SIZE);

			std::cout << "请求报名库命令: " << stGetBmkInfo.nExamID << "_" << stGetBmkInfo.nSubjectID << std::endl;
			std::string strLog = Poco::format("请求考试的报名库命令: %d_%d", stGetBmkInfo.nExamID, stGetBmkInfo.nSubjectID);
			g_Log.LogOut(strLog);

			std::string strEzs = stGetBmkInfo.szEzs;
			pSCAN_REQ_TASK pTask = new SCAN_REQ_TASK;
			pTask->strUri = SysSet.m_strBackUri + "/getStudents";
			pTask->nExamID = stGetBmkInfo.nExamID;
			pTask->nSubjectID = stGetBmkInfo.nSubjectID;

			char szExamInfo[30] = { 0 };
			sprintf(szExamInfo, "/%d/%d", stGetBmkInfo.nExamID, stGetBmkInfo.nSubjectID);
			pTask->strUri.append(szExamInfo);

			pTask->pUser = pUser;
			pTask->strEzs = SysSet.m_strSessionName + strEzs;		//"ezs=" + strEzs;
			pTask->strMsg = "getBmk";

			Poco::JSON::Object obj;
			obj.set("examId", stGetBmkInfo.nExamID);
			obj.set("subjectId", stGetBmkInfo.nSubjectID);
			stringstream ss;
			obj.stringify(ss, 0);
			pTask->strRequest = ss.str();

			g_fmScanReq.lock();
			g_lScanReq.push_back(pTask);
			g_fmScanReq.unlock();
		}
		break;
	case USER_GET_EXAM_BMK:
		{
			ST_GET_BMK_INFO stGetBmkInfo = *(pStGetBmkInfo)(pMission->m_pMissionData + HEAD_SIZE);

			std::string strCmdResponse = Poco::format("Get Cmd %d OK", (int)USER_GET_EXAM_BMK);
			//pUser->SendResponesInfo(USER_RESPONSE_GET_EXAM_BMK, RESULT_SUCCESS, (char*)strCmdResponse.c_str(), strCmdResponse.length());

			std::cout << "请求考试的报名库命令: " << stGetBmkInfo.nExamID << std::endl;
			std::string strLog = Poco::format("请求考试的报名库命令: %d", stGetBmkInfo.nExamID);
			g_Log.LogOut(strLog);

//			#ifdef _DEBUG	//测试数据,后期要删
			#ifdef TEST_MODE
			std::string strSendData;
			std::string strBmkFileName;
			if (stGetBmkInfo.nExamID == 1354 || stGetBmkInfo.nExamID == 1257 || stGetBmkInfo.nExamID == 1241)
			{
				strBmkFileName = Poco::format("ServerTestData-bmk-%d.txt", stGetBmkInfo.nExamID);
				std::string strExamListPath = SysSet.m_strCurrentDir + "\\ServerTestData\\" + strBmkFileName;
				std::string strJsnData;
				std::ifstream in(strExamListPath);

				if (!in) return false;

				std::string strJsnLine;
				while (!in.eof())
				{
					getline(in, strJsnLine);
					strJsnData.append(strJsnLine);
				}
				in.close();

				Poco::JSON::Parser parser;
				Poco::Dynamic::Var result;
				try
				{
					result = parser.parse(strJsnData);
					Poco::JSON::Object::Ptr object = result.extract<Poco::JSON::Object::Ptr>();
					//++添加考试ID和科目ID到结果信息中
					Poco::JSON::Object objExam;
					objExam.set("examId", stGetBmkInfo.nExamID);
					objExam.set("subjectId", stGetBmkInfo.nSubjectID);
					object->set("examInfo", objExam);
					std::stringstream jsnSnString;
					object->stringify(jsnSnString, 0);
					//--
					strSendData = jsnSnString.str();
				}
				catch (Poco::Exception& exc)
				{
					std::cout << "获取考试[" << stGetBmkInfo.nExamID << "]报名库数据异常\n";
					return false;
				}
			}
			else
			{
				Poco::JSON::Object objBmkTestResult;
				Poco::JSON::Object objStatus;
				objStatus.set("success", true);

				Poco::JSON::Array arryStudent;
				for (int i = 0; i < 100; i++)
				{
					Poco::JSON::Object objStudent;
					std::string strZkzh = Poco::format("%d", 100 + i);
					objStudent.set("zkzh", strZkzh);
					std::string strName = Poco::format("测试%d", i);
					objStudent.set("name", CMyCodeConvert::Gb2312ToUtf8(strName));
					objStudent.set("classRoom", CMyCodeConvert::Gb2312ToUtf8("10001"));
					objStudent.set("school", CMyCodeConvert::Gb2312ToUtf8("一中"));

					Poco::JSON::Array arryScanStatus;
					for (int j = 0; j < 4; j++)
					{
						Poco::JSON::Object objSubStatus;
						objSubStatus.set("subjectID", 590 + j);
						objSubStatus.set("scaned", (j + i) % 2);
						arryScanStatus.add(objSubStatus);
					}
					objStudent.set("scanStatus", arryScanStatus);
					arryStudent.add(objStudent);
				}

				Poco::JSON::Object objExam;
				objExam.set("examId", 402);
				objExam.set("subjectId", 590);
				objBmkTestResult.set("status", objStatus);
				objBmkTestResult.set("students", arryStudent);
				objBmkTestResult.set("examInfo", objExam);
				std::stringstream jsnSnString;
				objBmkTestResult.stringify(jsnSnString, 0);

				strSendData = jsnSnString.str();
			}
			pUser->SendResponesInfo(USER_RESPONSE_GET_EXAM_BMK, RESULT_GET_BMK_SUCCESS, (char*)strSendData.c_str(), strSendData.length());
			break;
			#endif

			std::string strEzs = stGetBmkInfo.szEzs;
			
			pSCAN_REQ_TASK pTask = new SCAN_REQ_TASK;
			pTask->strUri = SysSet.m_strBackUri + "/getStudents";
			pTask->nExamID = stGetBmkInfo.nExamID;
			pTask->nSubjectID = stGetBmkInfo.nSubjectID;
			pTask->nTeacherID = _mapSession_[strEzs].nTeacherID;

			char szExamInfo[30] = { 0 };
			sprintf(szExamInfo, "/%d/%d", stGetBmkInfo.nExamID, stGetBmkInfo.nSubjectID);
			pTask->strUri.append(szExamInfo);

			pTask->pUser = pUser;
			pTask->strEzs = SysSet.m_strSessionName + strEzs;		//"ezs=" + strEzs;
			pTask->strMsg = "getExamBmk";

			Poco::JSON::Object obj;
			obj.set("examId", stGetBmkInfo.nExamID);
			obj.set("subjectId", stGetBmkInfo.nSubjectID);
			obj.set("teacherId", pTask->nTeacherID);
			stringstream ss;
			obj.stringify(ss, 0);
			pTask->strRequest = ss.str();

			g_fmScanReq.lock();
			g_lScanReq.push_back(pTask);
			g_fmScanReq.unlock();
		}
		break;
	case USER_GET_FILE_UPLOAD_ADDR:
		{
			std::cout << "请求不同格式文件服务器地址信息命令: "<< std::endl;
			int nResult = RESULT_GET_FILE_ADDR_SUCCESS;
			if (SysSet.m_strFileAddrs.empty())
				nResult = RESULT_GET_FILE_ADDR_FAIL;
			std::string strVerAddr = SysSet.m_strFileAddrs;
			pUser->SendResponesInfo(USER_RESPONSE_GET_FILE_UPLOAD_ADDR, nResult, (char*)strVerAddr.c_str(), strVerAddr.length());

			std::string strLog = "请求不同格式文件服务器地址信息命令: \n" + strVerAddr;
			g_Log.LogOut(strLog);
		}
		break;
	case USER_NEED_UP_MODEL_PIC:
		{
			std::cout << "请求上传模板图像命令: " << std::endl;
			ST_MODELPIC stModelPic = *(pST_MODELPIC)(pMission->m_pMissionData + HEAD_SIZE);
			int nResult = RESULT_ERROR_UNKNOWN;

			std::string strModelPicPath = Poco::format("%s\\%d\\%d_%d_%d%s", CMyCodeConvert::Gb2312ToUtf8(SysSet.m_strModelSavePath), stModelPic.nExamID, \
													   stModelPic.nExamID, stModelPic.nSubjectID, stModelPic.nIndex, CMyCodeConvert::Gb2312ToUtf8(stModelPic.szExtName));

// 			std::string strModelPicPath = Poco::format("%s\\%d\\%d_%d_%d_#_%s", CMyCodeConvert::Gb2312ToUtf8(SysSet.m_strModelSavePath), stModelPic.nExamID,\
// 												   stModelPic.nExamID, stModelPic.nSubjectID, stModelPic.nIndex, CMyCodeConvert::Gb2312ToUtf8(stModelPic.szPicName));
			std::string strLog;
			try
			{
				Poco::File modelPic(strModelPicPath);
				if (!modelPic.exists())
				{
					nResult = RESULT_UP_MODEL_PIC_SEND;
					strLog = "请求上传模板图像命令 ==> 可以发送模板图片:" + strModelPicPath;
					std::cout << "可以发送模板图片:" << strModelPicPath << std::endl;
				}
				else
				{
					std::string strMd5 = calcFileMd5(strModelPicPath);
					if (strMd5 == stModelPic.szMD5)
					{
						nResult = RESULT_UP_MODEL_PIC_NONEED;
						strLog = "请求上传模板图像命令 ==> 不需要发送模板图片:" + strModelPicPath;
						std::cout << "不需要发送模板图片:" << strModelPicPath << std::endl;
					}
					else
					{
						nResult = RESULT_UP_MODEL_PIC_SEND;
						strLog = "请求上传模板图像命令 ==> 可以发送模板图片:" + strModelPicPath;
						std::cout << "可以发送模板图片:" << strModelPicPath << std::endl;
					}
				}
			}
			catch (Poco::Exception& e)
			{
				strLog = "请求上传模板图像命令 ==> 检测模板图片路径异常:" + e.displayText();
				std::cout << "检测模板图片路径异常: "<< e.displayText() << std::endl;
				nResult = RESULT_UP_MODEL_PIC_SEND;
			}
			
			pUser->SendResponesInfo(USER_RESPONSE_NEED_UP_MODEL_PIC, nResult, (char*)&stModelPic, sizeof(stModelPic));
			g_Log.LogOut(strLog);
		}
		break;
	case USER_GET_MODEL_PIC:
		{
			char szData[1024] = { 0 };
			strncpy(szData, pMission->m_pMissionData + HEAD_SIZE, header.uPackSize);
			std::string strModelPicInfo = szData;
			std::cout << "请求下载模板图像命令: " << strModelPicInfo << std::endl;
			std::stringstream ssLog;
			ssLog<< "请求下载模板图像命令: " << strModelPicInfo << std::endl;

			int nPos = strModelPicInfo.find("_");
			std::string strExamID = strModelPicInfo.substr(0, nPos);
			std::string strSubjectID = strModelPicInfo.substr(nPos + 1);

			std::string strModelPicDir = SysSet.m_strModelSavePath + "\\" + strExamID + "\\";

			std::vector<std::string> vecModelPicName;
			std::vector<std::string> vecModelPicPath;
			std::string strPaperPath = CMyCodeConvert::Gb2312ToUtf8(strModelPicDir);

			try
			{
				Poco::File modlePicDir(strPaperPath);
				if (!modlePicDir.exists())
				{
					pUser->SendResult(USER_RESPONSE_GET_MODEL_PIC, RESULT_GET_MODEL_PIC_NOPIC);
					ssLog << "模板图像不存在";
					g_Log.LogOut(ssLog.str());
					return false;
				}
			}
			catch (Poco::Exception& e)
			{
			}

			Poco::DirectoryIterator it(strPaperPath);
			Poco::DirectoryIterator end;
			while (it != end)
			{
				Poco::Path p(it->path());
				if (it->isFile())
				{
					std::string strName = p.getFileName();
					if (strName.find(strModelPicInfo) != std::string::npos)
					{
						std::string strPicPath = p.toString();
						vecModelPicName.push_back(strName);
						vecModelPicPath.push_back(strPicPath);
					}
				}
				it++;
			}
			if (vecModelPicPath.size() == 0)
			{
				pUser->SendResult(USER_RESPONSE_GET_MODEL_PIC, RESULT_GET_MODEL_PIC_NOPIC);
				ssLog << "模板图像不存在";
				g_Log.LogOut(ssLog.str());
				return false;
			}

			std::string strSendData;
			for (int i = 0; i < vecModelPicPath.size(); i++)
			{
				std::string strFileData;
				std::ifstream fin(CMyCodeConvert::Utf8ToGb2312(vecModelPicPath[i]), std::ifstream::binary);
				if (!fin)
				{
					pUser->SendResult(USER_RESPONSE_GET_MODEL_PIC, RESULT_ERROR_FILEIO);
					ssLog << "读取模板文件失败";
					g_Log.LogOut(ssLog.str());
					return false;
				}
				std::stringstream buffer;
				buffer << fin.rdbuf();
				strFileData = buffer.str();
				fin.close();

				strSendData.append("#_#_#_#_");
				strSendData.append(vecModelPicName[i]);
				strSendData.append("_*_");
				char szLen[20] = { 0 };
				sprintf_s(szLen, "%d", strFileData.length());
				strSendData.append(szLen);
				strSendData.append("_#####_");
				strSendData.append(strFileData);
			}

			pUser->SendResponesInfo(USER_RESPONSE_GET_MODEL_PIC, RESULT_GET_MODEL_PIC_SUCCESS, (char*)strSendData.c_str(), strSendData.length());
			ssLog << "模板文件发送完成";
			g_Log.LogOut(ssLog.str());
		}
		break;
	case USER_CHK_NEW_GUARDEXE:
		{
			char szData[1024] = { 0 };
			strncpy(szData, pMission->m_pMissionData + HEAD_SIZE, header.uPackSize);
			std::string strClientGuardExeMd5 = szData;
			if (_strNewGuardExeMd5_.empty())
			{
				std::cout << "服务器上新守护进程不存在" << std::endl;
				pUser->SendResult(USER_RESPONSE_CHK_NEW_GUARDEXE, RESULT_GET_NEW_GUARDEXE_NOFILE);
			}
			else if (_strNewGuardExeMd5_ == strClientGuardExeMd5)
			{
				std::cout << "客户端上的守护进程和服务器一致,不需要下载" << std::endl;
				pUser->SendResult(USER_RESPONSE_CHK_NEW_GUARDEXE, RESULT_GET_NEW_GUARDEXE_NONEED);
			}
			else
			{
				std::string strGuardExePath = SysSet.m_strNewGuardProcessPath + "EasyTntGuardProcess.exe";
				std::string strFileData;
				std::ifstream fin(strGuardExePath, std::ifstream::binary);
				if (!fin)
				{
					pUser->SendResult(USER_RESPONSE_CHK_NEW_GUARDEXE, RESULT_ERROR_FILEIO);
					g_Log.LogOut("读取新守护进程文件时打开文件失败: " + strGuardExePath);
					return false;
				}
				std::cout << "正在发送新守护进程文件..." << std::endl;
				std::stringstream buffer;
				buffer << fin.rdbuf();
				strFileData = buffer.str();
				fin.close();
				pUser->SendResponesInfo(USER_RESPONSE_CHK_NEW_GUARDEXE, RESULT_GET_NEW_GUARDEXE_SUCCESS, (char*)strFileData.c_str(), strFileData.length());
				g_Log.LogOut("新守护进程文件发送完成");
				std::cout << "新守护进程文件发送完成" << std::endl;
			}
		}
		break;
	case KEEPALIVE_PKG:
		{
			char szData[1024] = { 0 };
			strncpy(szData, pMission->m_pMissionData + HEAD_SIZE, header.uPackSize);
			std::string strEzs = szData;

			MAP_SESSION::iterator itSession = _mapSession_.begin();
			for (; itSession != _mapSession_.end(); itSession++)
			{
				if (itSession->first == strEzs)
				{
					itSession->second.tmStamp.update();
					itSession->second.nChkHeartPkgFailTimes = 0;
					break;
				}
			}
		}
		break;
	default:
		bFind = FALSE;
		break;
	}
	if (bFind)
	{
		return 1;
	}
	return 0;
}
Example #15
0
int DripLine::createFile(const std::string& file) const noexcept
{
  std::ifstream modelFile(FRDM_file, std::ios::binary);

  if (!modelFile)
    {
      std::cerr << "\n"
                << "***ERROR***: " << FRDM_file << " couldn't be opened, does it exist?"
                << "\n"
                << std::endl;
      return 1;
    }

  std::ofstream dripFile(file, std::ios::binary);

  if (!dripFile)
    {
      std::cerr << "\n"
                << "***ERROR***: " << file << " couldn't be opened to write to"
                << "\n"
                << std::endl;
      return 2;
    }

  dripFile << "#  N    Z   drip[MeV]\n"
           << "#------------------" << std::endl;
  dripFile.precision(4);

  // Starting values come from the FRLDM file
  int currentSingleProton   = 7;
  int currentSingleNeutron  = 7;
  int previousSingleNeutron = 8;
  int previousSingleProton  = 0;

  int currentDoubleProton   = 7;
  int currentDoubleNeutron  = 7;
  int previousDoubleNeutron = 8;
  int previousDoubleProton  = 0;

  int nucleonWidth = 4;
  int dripWidth    = 8;

  // Rather than use a vector of Nuclide(216), create a new
  // smaller(56) struct to store the required values and
  // create a vector of these.
  struct isotope
  {
    int A = 0;
    int Z = 0;
    int N = 0;

    double s_n  = 0.0;
    double s_2n = 0.0;
    double s_p  = 0.0;
    double s_2p = 0.0;
    double ME   = 0.0;
  };
  std::vector<isotope> dripNuc;

  std::string dataline;
  while (std::getline(modelFile, dataline))
    {
      if (dataline.empty() || dataline.at(0) == '#')
        {
          continue;
        }

      std::istringstream dripData(dataline);
      std::string dummy;

      dripNuc.emplace_back(isotope());
      auto currentIsotope = std::rbegin(dripNuc);

      dripData >> currentIsotope->A >> currentIsotope->Z >> dummy >> currentIsotope->ME;

      currentIsotope->N = currentIsotope->A - currentIsotope->Z;

      // File is ordered in Z then A, by looping through backwards,
      // we do not need to traverse the entire contents as we can stop
      // once values get too far apart to provide data.
      for (auto otherIsotope = currentIsotope; otherIsotope != std::rend(dripNuc); ++otherIsotope)
        {
          // Depending on the drip line, we can break when differences
          // in N or Z get too larger i.e. 2 for single particle and
          // 3 for double particle lines.
          if ((the_line == LineType::singleneutron && currentIsotope->N - otherIsotope->N >= 2)
              || (the_line == LineType::doubleneutron && currentIsotope->N - otherIsotope->N >= 3)
              || (the_line == LineType::singleproton && currentIsotope->Z - otherIsotope->Z >= 2)
              || (the_line == LineType::doubleproton && currentIsotope->Z - otherIsotope->Z >= 3))
            {
              break;
            }

          if (currentIsotope->A - otherIsotope->A == 1)
            {
              // S(n) = M(Z,N-1) - M(Z,N) + M(0,1)
              if (the_line == LineType::singleneutron && otherIsotope->Z == currentIsotope->Z
                  && currentSingleProton < currentIsotope->Z)
                {
                  currentIsotope->s_n = otherIsotope->ME - currentIsotope->ME + neutron_mass;

                  if (currentIsotope->s_n < 0.0)
                    {
                      dripFile << std::fixed << std::setw(nucleonWidth) << currentIsotope->N << " "
                               << std::setw(nucleonWidth) << currentIsotope->Z << " " << std::setw(dripWidth)
                               << currentIsotope->s_n << "\n"
                               << std::setw(nucleonWidth) << currentIsotope->N << " " << std::setw(nucleonWidth)
                               << currentIsotope->Z + 1 << " " << std::setw(dripWidth) << currentIsotope->s_n
                               << std::endl;

                      ++currentSingleProton;
                    }
                }

              // S(p) = M(Z-1,N) - M(Z,N) + M(1,0)
              if (the_line == LineType::singleproton && otherIsotope->N == currentIsotope->N
                  && currentSingleNeutron < currentIsotope->N)
                {
                  currentIsotope->s_p = otherIsotope->ME - currentIsotope->ME + proton_mass;

                  if (currentIsotope->s_p < 0.0)
                    {
                      if (currentIsotope->N != previousSingleNeutron)
                        {
                          dripFile << std::fixed << std::setw(nucleonWidth) << previousSingleNeutron + 1 << " "
                                   << std::setw(nucleonWidth) << previousSingleProton << " " << std::setw(dripWidth)
                                   << currentIsotope->s_p << std::endl;
                        }

                      dripFile << std::fixed << std::setw(nucleonWidth) << currentIsotope->N << " "
                               << std::setw(nucleonWidth) << currentIsotope->Z << " " << std::setw(dripWidth)
                               << currentIsotope->s_p << std::endl;

                      ++currentSingleNeutron;
                      previousSingleProton  = currentIsotope->Z;
                      previousSingleNeutron = currentIsotope->N;
                    }
                }
            }
          else if (currentIsotope->A - otherIsotope->A == 2)
            {
              // S(2n) = M(Z,N-2) - M(Z,N) + 2*M(0,1)
              if (the_line == LineType::doubleneutron && otherIsotope->Z == currentIsotope->Z
                  && currentDoubleProton < currentIsotope->Z)
                {
                  currentIsotope->s_2n = otherIsotope->ME - currentIsotope->ME + 2.0 * neutron_mass;

                  if (currentIsotope->s_2n < 0.0)
                    {
                      dripFile << std::fixed << std::setw(nucleonWidth) << currentIsotope->N << " "
                               << std::setw(nucleonWidth) << currentIsotope->Z << " " << std::setw(dripWidth)
                               << currentIsotope->s_2n << "\n"
                               << std::setw(nucleonWidth) << currentIsotope->N << " " << std::setw(nucleonWidth)
                               << currentIsotope->Z + 1 << " " << std::setw(dripWidth) << currentIsotope->s_2n
                               << std::endl;

                      ++currentDoubleProton;
                    }
                }

              // S(2p) = M(Z-2,N) - M(Z,N) + 2*M(1,0)
              if (the_line == LineType::doubleproton && otherIsotope->N == currentIsotope->N
                  && currentDoubleNeutron < currentIsotope->N)
                {
                  currentIsotope->s_2p = otherIsotope->ME - currentIsotope->ME + 2.0 * proton_mass;

                  if (currentIsotope->s_2p < 0.0)
                    {
                      if (currentIsotope->N != previousDoubleNeutron)
                        {
                          dripFile << std::fixed << std::setw(nucleonWidth) << previousDoubleNeutron + 1 << " "
                                   << std::setw(nucleonWidth) << previousDoubleProton << " " << std::setw(dripWidth)
                                   << currentIsotope->s_2p << std::endl;
                        }

                      dripFile << std::fixed << std::setw(nucleonWidth) << currentIsotope->N << " "
                               << std::setw(nucleonWidth) << currentIsotope->Z << " " << std::setw(dripWidth)
                               << currentIsotope->s_2p << std::endl;

                      ++currentDoubleNeutron;
                      previousDoubleProton  = currentIsotope->Z;
                      previousDoubleNeutron = currentIsotope->N;
                    }
                }
            }
        }
    }

  modelFile.close();

  dripFile.close();

  return 0;
}
Example #16
0
int main(int argc, char** argv)
{
  bool AddLicenceInformation = true;
#if defined(COMPILE_STORM_MODULES_FOR_RMS)
  AddLicenceInformation = false;
  //* The Appl is static, otherwise it is not deleted upon call to exit().
  //* TODO: checkUsage() must not call exit(), either return a status, or
  //* throw an exception that is caught here.
  //* So that the app can exit gracefully.
  static
  CravaAppl CravaAppl("RMS",
                      "RMS - Seismic inversion module",
                      Appl::NOTRADEMARK,
                      ReleaseInfo::GetRmsMajorMinorVersionNumber(),
                      ReleaseInfo::GetFullVersionNumber(),
                      Appl::RELEASE,
                      FileVersion(0),
                      "SEISMIC_INVERSION",
                      ReleaseInfo::GetLicenseVersion());
  Appl::Instance()->Main(argc, argv);
#endif

  if(0) {
    //test of DEM RPM
    double effective_bulk_modulus2;
    double effective_shear_modulus2;
    double effective_density2;
    DEMTools::DebugTestCalcEffectiveModulus2(effective_bulk_modulus2,
                                             effective_shear_modulus2,
                                             effective_density2);
    double effective_bulk_modulus;
    double effective_shear_modulus;
    double effective_density;
    DEMTools::DebugTestCalcEffectiveModulus4(effective_bulk_modulus,
                                             effective_shear_modulus,
                                             effective_density);
    //float tmp10 = 5.0f;


  }

  if (argc != 2) {
    printf("Usage: %s modelfile\n",argv[0]);
    exit(1);
  }
  LogKit::SetScreenLog(LogKit::L_Low);
  LogKit::StartBuffering();

  Program program( 4,                     // Major version
                   0,                     // Minor version
                   0,                     // Patch number for bug fixes
                   //"",                  // Use empty string "" for release versions
                   " beta",               // Use empty string "" for release versions
                   -1,                    // Validity of licence in days (-1 = infinite)
                   //"NORSAR",            // Who this copy of CRAVA is licensed to
                   "Norsk Regnesentral/Statoil",
                   AddLicenceInformation);

  double wall=0.0, cpu=0.0;
  TimeKit::getTime(wall,cpu);

  try
  {
    XmlModelFile modelFile(argv[1]);
    InputFiles         * inputFiles         = modelFile.getInputFiles();
    ModelSettings      * modelSettings      = modelFile.getModelSettings();
    CommonData         * common_data        = NULL;
    ModelGeneral       * modelGeneral       = NULL;
    ModelAVOStatic     * modelAVOstatic     = NULL;
    ModelGravityStatic * modelGravityStatic = NULL;
    CravaResult        * crava_result       = new CravaResult();
    NRLib::Random::Initialize();

    if (modelFile.getParsingFailed()) {
      LogKit::SetFileLog(IO::FileLog()+IO::SuffixTextFiles(), modelSettings->getLogLevel());
      LogKit::EndBuffering();
      return(1);
    }

    std::string errTxt = inputFiles->addInputPathAndCheckFiles();
    if(errTxt != "") {
      LogKit::WriteHeader("Error opening files");
      LogKit::LogMessage(LogKit::Error, "\n"+errTxt);
      LogKit::LogFormatted(LogKit::Error,"\nAborting\n");
      LogKit::SetFileLog(IO::FileLog()+IO::SuffixTextFiles(), modelSettings->getLogLevel());
      LogKit::EndBuffering();
      return(1);
    }

    /*------------------------------------------------------------
    READ COMMON DATA AND PERFORM ESTIMATION BASED ON INPUT FILES
    AND MODEL SETTINGS
    -------------------------------------------------------------*/

    common_data = new CommonData(modelSettings, inputFiles);
    int n_intervals = common_data->GetMultipleIntervalGrid()->GetNIntervals();
    std::vector<SeismicParametersHolder> seismicParametersIntervals(common_data->GetMultipleIntervalGrid()->GetNIntervals());

    if(modelSettings->getEstimationMode() == false) {
      //Loop over intervals
      for (int i_interval = 0; i_interval < n_intervals; i_interval++) {

        modelGeneral       = NULL;
        modelAVOstatic     = NULL;
        modelGravityStatic = NULL;

        std::string interval_text = "";
        if (n_intervals > 1)
          interval_text = " for interval " + NRLib::ToString(common_data->GetMultipleIntervalGrid()->GetIntervalName(i_interval));
        LogKit::WriteHeader("Setting up model" + interval_text);

        //Priormodell i 3D
        const Simbox * simbox = common_data->GetMultipleIntervalGrid()->GetIntervalSimbox(i_interval);

        //Expectationsgrids. NRLib::Grid to FFTGrid, fills in padding
        LogKit::LogFormatted(LogKit::Low,"\nBackground model..\n");

        seismicParametersIntervals[i_interval].setBackgroundParametersInterval(common_data->GetBackgroundParametersInterval(i_interval),
                                                                               simbox->GetNXpad(),
                                                                               simbox->GetNYpad(),
                                                                               simbox->GetNZpad());

        //Background grids are overwritten in avoinversion
        std::string interval_name = common_data->GetMultipleIntervalGrid()->GetIntervalName(i_interval);
        crava_result->AddBackgroundVp(seismicParametersIntervals[i_interval].GetMeanVp());
        crava_result->AddBackgroundVs(seismicParametersIntervals[i_interval].GetMeanVs());
        crava_result->AddBackgroundRho(seismicParametersIntervals[i_interval].GetMeanRho());
        //Release background grids from common_data.
        common_data->ReleaseBackgroundGrids(i_interval, 0);
        common_data->ReleaseBackgroundGrids(i_interval, 1);
        common_data->ReleaseBackgroundGrids(i_interval, 2);

        //korrelasjonsgrid (2m)
        float corr_grad_I = 0.0f;
        float corr_grad_J = 0.0f;
        common_data->GetCorrGradIJ(corr_grad_I, corr_grad_J, simbox);

        float dt        = static_cast<float>(simbox->getdz());
        float low_cut   = modelSettings->getLowCut();
        int low_int_cut = int(floor(low_cut*(simbox->GetNZpad()*0.001*dt))); // computes the integer which corresponds to the low cut frequency.

        if (!modelSettings->getForwardModeling()) {
          LogKit::LogFormatted(LogKit::Low,"\nCorrelation parameters..\n");
          seismicParametersIntervals[i_interval].setCorrelationParameters(common_data->GetPriorCovEst(),
                                                                          common_data->GetPriorParamCov(i_interval),
                                                                          common_data->GetPriorAutoCov(i_interval),
                                                                          common_data->GetPriorCorrT(i_interval),
                                                                          common_data->GetPriorCorrXY(i_interval),
                                                                          low_int_cut,
                                                                          corr_grad_I,
                                                                          corr_grad_J,
                                                                          simbox->getnx(),
                                                                          simbox->getny(),
                                                                          simbox->getnz(),
                                                                          simbox->GetNXpad(),
                                                                          simbox->GetNYpad(),
                                                                          simbox->GetNZpad(),
                                                                          simbox->getdz());

        }

        //ModelGeneral, modelAVOstatic, modelGravityStatic, (modelTravelTimeStatic?)
        LogKit::LogFormatted(LogKit::Low,"\nStatic models..\n");
        setupStaticModels(modelGeneral,
                          modelAVOstatic,
                          //modelGravityStatic,
                          modelSettings,
                          inputFiles,
                          seismicParametersIntervals[i_interval],
                          common_data,
                          i_interval);

        //Loop over dataset
        //i.   ModelAVODynamic
        //ii.  Inversion
        //iii. Move model one time-step ahead

        //Do not run avoinversion if forward modelleing or estimationmode
        //Syntetic seismic is generated in CravaResult
        if (!modelSettings->getForwardModeling() && !modelSettings->getEstimationMode()) {
          int  eventType;
          int  eventIndex;
          modelGeneral->GetTimeLine()->ReSet();

          double time;
          int time_index = 0;
          bool first     = true;
          while(modelGeneral->GetTimeLine()->GetNextEvent(eventType, eventIndex, time) == true) {
            if (first == false) {
                modelGeneral->AdvanceTime(time_index, seismicParametersIntervals[i_interval], modelSettings);
                time_index++;
            }
            bool failed = false;
            switch(eventType) {
            case TimeLine::AVO : {
              LogKit::LogFormatted(LogKit::Low,"\nAVO inversion, time lapse "+ CommonData::ConvertIntToString(time_index) +"..\n");
              failed = doTimeLapseAVOInversion(modelSettings,
                                                modelGeneral,
                                                modelAVOstatic,
                                                common_data,
                                                seismicParametersIntervals[i_interval],
                                                eventIndex,
                                                i_interval);
              break;
            }
            case TimeLine::TRAVEL_TIME : {
              LogKit::LogFormatted(LogKit::Low,"\nTravel time inversion, time lapse "+ CommonData::ConvertIntToString(time_index) +"..\n");
              //failed = doTimeLapseTravelTimeInversion(modelSettings,
              //                                        modelGeneral,
              //                                        modelTravelTimeStatic,
              //                                        inputFiles,
              //                                        eventIndex,
              //                                        seismicParametersIntervals[i_interval]);
              break;
            }
            case TimeLine::GRAVITY : {
              LogKit::LogFormatted(LogKit::Low,"\nGravimetric inversion, time lapse "+ CommonData::ConvertIntToString(time_index) +"..\n");
              //failed = doTimeLapseGravimetricInversion(modelSettings,
              //                                          modelGeneral,
              //                                          modelGravityStatic,
              //                                          common_data,
              //                                          eventIndex,
              //                                          seismicParametersIntervals[i_interval]);
              break;
            }
            default :
              failed = true;
              break;
            }
            if(failed)
              return(1);

            first = false;
          }
        }

        crava_result->AddBlockedLogs(modelGeneral->GetBlockedWells());
      } //interval_loop
    }
    if (n_intervals == 1)
      crava_result->SetBgBlockedLogs(common_data->GetBgBlockedLogs());

    if (modelSettings->getEstimationMode() == true) {
      LogKit::WriteHeader("Combine Results and Write to Files");
      if (modelSettings->getEstimateBackground() == true && n_intervals == 1 && ((modelSettings->getOutputGridFormat() & IO::CRAVA) > 0)) {
        const Simbox * simbox = common_data->GetMultipleIntervalGrid()->GetIntervalSimbox(0);
        seismicParametersIntervals[0].setBackgroundParametersInterval(common_data->GetBackgroundParametersInterval(0),
                                                                      simbox->GetNXpad(),
                                                                      simbox->GetNYpad(),
                                                                      simbox->GetNZpad());
        crava_result->AddBackgroundVp(seismicParametersIntervals[0].GetMeanVp());
        crava_result->AddBackgroundVs(seismicParametersIntervals[0].GetMeanVs());
        crava_result->AddBackgroundRho(seismicParametersIntervals[0].GetMeanRho());
      }

      crava_result->WriteEstimationResults(modelSettings,
                                           common_data);
    }
    else {
      //Combine interval grids to one grid per parameter
      LogKit::WriteHeader("Combine Results and Write to Files");
      crava_result->CombineResults(modelSettings,
                                   common_data,
                                   seismicParametersIntervals);

      crava_result->WriteResults(modelSettings,
                                 common_data,
                                 seismicParametersIntervals[0]);

      if(modelSettings->getDo4DInversion())
      {

        bool failed;
        if(modelSettings->getDo4DRockPhysicsInversion())
        {
          LogKit::WriteHeader("4D Rock Physics Inversion");
          failed = modelGeneral->Do4DRockPhysicsInversion(modelSettings);

          if(failed)
            return(1);
        }
      }
    }
    if (modelSettings->getDoInversion() && FFTGrid::getMaxAllowedGrids() != FFTGrid::getMaxAllocatedGrids()) {
      //NBNB-PAL: Memory check is bogus at the moment. Include again when 4.0 release is fixed.")
      //LogKit::LogFormatted(LogKit::Warning,"\nWARNING: A memory requirement inconsistency has been detected:");
      //LogKit::LogFormatted(LogKit::Warning,"\n            Maximum number of grids requested  :  %2d",FFTGrid::getMaxAllowedGrids());
      //LogKit::LogFormatted(LogKit::Warning,"\n            Maximum number of grids allocated  :  %2d",FFTGrid::getMaxAllocatedGrids());
      //TaskList::addTask("The memory usage estimate failed. Please send your XML-model file and the logFile.txt\n    to the CRAVA developers.");
    }

    Timings::setTimeTotal(wall,cpu);
    Timings::reportAll(LogKit::Medium);

    TaskList::viewAllTasks(modelSettings->getTaskFileFlag());

    delete modelAVOstatic;
    delete modelGeneral;
    delete common_data;
    delete crava_result;
    crava_result            = NULL;
    delete modelSettings;
    modelSettings           = NULL;
    delete inputFiles;
    inputFiles              = NULL;

    Timings::reportTotal();
    LogKit::LogFormatted(LogKit::Low,"\n*** CRAVA closing  ***\n");
    LogKit::LogFormatted(LogKit::Low,"\n*** CRAVA finished ***\n");
    //
    // The exit(0) is needed to get the gprof output file gmon.out ...
    //
    exit(0);
  }
  catch (std::bad_alloc& ba) {
    std::cerr << "Out of memory: " << ba.what() << std::endl;
    std::string error_message = std::string("Out of memory: ") + ba.what() + "\n";
    LogKit::LogMessage(LogKit::Error, error_message);
  }

#if defined(COMPILE_STORM_MODULES_FOR_RMS)
  Feature& feature = FEATURE_INVERSION_EXE;
  LicenseSystem::Instance()->CheckIn(&feature);
#endif

  LogKit::EndLog(); //Debug messages may occur when variables go out of scope above, so this must be the final call.
  return(0);
}