void BenchmarkRunnerThread::run()
{
    auto_release_ptr<XMLFileBenchmarkListener> xmlfile_listener(
        create_xmlfile_benchmark_listener());

    const string xmlfile_name = "benchmark." + get_time_stamp_string() + ".xml";
    const filesystem::path xmlfile_path =
          filesystem::path(Application::get_tests_root_path())
        / "unit benchmarks"
        / "results"
        / xmlfile_name;

    if (!xmlfile_listener->open(xmlfile_path.string().c_str()))
    {
        emit signal_cannot_create_benchmark_file();
        return;
    }

    BenchmarkResult result;
    result.add_listener(xmlfile_listener.get());

    const filesystem::path old_current_path =
        Application::change_current_directory_to_tests_root_path();

    BenchmarkSuiteRepository::instance().run(result);

    filesystem::current_path(old_current_path);

    emit signal_finished();
}
void RenderingManager::archive_frame_to_disk()
{
    RENDERER_LOG_INFO("archiving frame to disk...");

    const filesystem::path autosave_path =
          filesystem::path(Application::get_root_path())
        / "images" / "autosave";

    m_project->get_frame()->archive(autosave_path.string().c_str());
}
bool ReadTexturesFromFile(const filesystem::path& lights_path, const filesystem::path& base_path, ID3D11Device* device, std::vector<TextureIdentifier>* textures) {
  nlohmann::json json_textures;

  bool load_ok = Core::ReadJsonFile(lights_path, &json_textures);
  if (!load_ok) {
    DXFW_TRACE(__FILE__, __LINE__, false, "Error reading textures file from %s", lights_path.string());
    return false;
  }

  return ReadTexturesFromJson(json_textures, base_path, device, textures);
}
void BenchmarkWindow::reload_benchmarks()
{
    const filesystem::path benchmarks_path =
          filesystem::path(Application::get_tests_root_path())
        / "unit benchmarks/results/";

    m_benchmark_aggregator.clear();
    m_benchmark_aggregator.scan_directory(benchmarks_path.string().c_str());

    populate_benchmarks_treeview();
}
Exemple #5
0
int main(int argc, const char* argv[])
{
    SuperLogger logger;
    Application::check_installation(logger);

    CommandLineHandler cl;
    cl.parse(argc, argv, logger);

    // Initialize the renderer's logger.
    global_logger().add_target(&logger.get_log_target());

    // Retrieve the input file path.
    const string& input_filepath = cl.m_filename.value();

    // Construct the schema file path.
    const filesystem::path schema_filepath =
          filesystem::path(Application::get_root_path())
        / "schemas"
        / "project.xsd";

    // Read the input project from disk.
    // Note: it is crucial that we read mesh files as well, so that we can collect
    // material slots declared by objects. Material slots are required by the project
    // file updater, for instance when migrating projects from rev. 7 to rev. 8.
    ProjectFileReader reader;
    auto_release_ptr<Project> project(
        reader.read(
            input_filepath.c_str(),
            schema_filepath.string().c_str(),
            ProjectFileReader::OmitProjectFileUpdate));

    // Bail out if the project couldn't be loaded.
    if (project.get() == 0)
        return 1;

    // Update the project file to the desired revision.
    ProjectFileUpdater updater;
    if (cl.m_to_revision.is_set())
        updater.update(project.ref(), cl.m_to_revision.value());
    else updater.update(project.ref());

    // Write the project back to disk.
    const bool success =
        ProjectFileWriter::write(
            project.ref(),
            project->get_path(),
            ProjectFileWriter::OmitWritingGeometryFiles | ProjectFileWriter::OmitBringingAssets);

    return success ? 0 : 1;
}
Exemple #6
0
int main(int argc, const char* argv[])
{
    SuperLogger logger;
    Application::check_installation(logger);

    CommandLineHandler cl;
    cl.parse(argc, argv, logger);

    // Initialize the renderer's logger.
    global_logger().add_target(&logger.get_log_target());

    // Retrieve the command line arguments.
    const string& input_filepath = cl.m_filenames.values()[0];
    const string& output_filepath = cl.m_filenames.values()[1];
    const FluffParams params(cl);

    // Construct the schema file path.
    const filesystem::path schema_filepath =
          filesystem::path(Application::get_root_path())
        / "schemas"
        / "project.xsd";

    // Read the input project from disk.
    ProjectFileReader reader;
    auto_release_ptr<Project> project(
        reader.read(
            input_filepath.c_str(),
            schema_filepath.string().c_str()));

    // Bail out if the project couldn't be loaded.
    if (project.get() == 0)
        return 1;

    // Fluffify the project.
    make_fluffy(project.ref(), params);

    // Write the project back to disk.
    const bool success =
        ProjectFileWriter::write(
            project.ref(),
            output_filepath.c_str());

    return success ? 0 : 1;
}
Exemple #7
0
inline std::string convert_to_string( const filesystem::path& path )
{
    return convert_to_string( path.string() );
}
Exemple #8
0
string EngineInit::getRelativePath(
    filesystem::path p, filesystem::path root = filesystem::current_path()) {
  return p.string().substr(root.string().length());
}
Exemple #9
0
Media::Media(const filesystem::path& path) : m_path{path}, m_uid{hexEncode(md5(path.string()))} {
}
void MaterialCollectionItem::slot_import_disney()
{
#ifdef APPLESEED_WITH_DISNEY_MATERIAL
    QString filepath =
        get_open_filename(
            0,
            "Import...",
            "Disney Material (*.dmt);;All Files (*.*)",
            m_editor_context.m_settings,
            SETTINGS_FILE_DIALOG_PROJECTS);

    if (!filepath.isEmpty())
    {
        filepath = QDir::toNativeSeparators(filepath);

        const filesystem::path root_path(Application::get_root_path());
        const filesystem::path schema_file_path = root_path / "schemas" / "settings.xsd";

        SettingsFileReader reader(global_logger());
        ParamArray parameters;
        const bool success =
            reader.read(
                filepath.toStdString().c_str(),
                schema_file_path.string().c_str(),
                parameters);

        if (!success)
        {
            show_error_message_box(
                "Importing Error",
                "Failed to import the Disney Material file " + filepath.toStdString());
            return;
        }

        string name = parameters.get("__name");
        const string model = parameters.get("__model");
        parameters.strings().remove("__name");
        parameters.strings().remove("__model");

        if (model != "disney_material")
        {
            show_error_message_box(
                "Importing Error",
                "Material model " + model + " is not supported.");
            return;
        }

        // If there is already a material with the same name, rename the imported material.
        for (const_each<MaterialContainer> i = m_parent.materials(); i; ++i)
        {
            if (strcmp(i->get_name(), name.c_str()) == 0)
            {
                name = make_unique_name(name, m_parent.materials());
                break;
            }
        }

        auto_release_ptr<Material> material =
            DisneyMaterialFactory().create(name.c_str(), parameters);
        Material* material_ptr = material.get();

        add_item(material_ptr);

        EntityTraits<Material>::insert_entity(material, m_parent);
        m_editor_context.m_project_builder.notify_project_modification();

        m_editor_context.m_project_explorer.select_entity(material_ptr->get_uid());
    }
#endif
}
Exemple #11
0
IRendererController::Status MasterRenderer::initialize_and_render_frame_sequence()
{
    assert(m_project.get_scene());
    assert(m_project.get_frame());

    // Reset the abort switch.
    if (m_abort_switch)
        m_abort_switch->clear();

#ifdef WITH_OSL

    // Create the error handler.
    OIIOErrorHandler error_handler;

    // While debugging, we want all possible outputs.
#ifndef NDEBUG
    error_handler.verbosity(OIIO::ErrorHandler::VERBOSE);
#endif

    const size_t texture_cache_size =
        m_params.get_optional<size_t>("texture_cache_size",  256 * 1024 * 1024);

    // If the texture cache size changes, we have to recreate the texture system.
    if (texture_cache_size != m_texture_cache_size)
    {
        m_texture_cache_size = texture_cache_size;
        m_texture_system.reset();
    }

    // Create the OIIO texture system, if needed.
    if (!m_texture_system)
    {
        m_texture_system.reset(
            OIIO::TextureSystem::create(false),
            bind(&OIIO::TextureSystem::destroy, _1));
    }

    // Set the texture system mem limit.
    m_texture_system->attribute("max_memory_MB", static_cast<float>(m_texture_cache_size / 1024));

    std::string search_paths;

    // Skip search paths for builtin projects.
    if (m_project.search_paths().has_root_path())
    {
        // Setup texture / shader search paths.
        // In OIIO / OSL, the path priorities are the opposite of appleseed,
        // so we copy the paths in reverse order.

        const filesystem::path root_path = m_project.search_paths().get_root_path();

        if (!m_project.search_paths().empty())
        {
            for (size_t i = 0, e = m_project.search_paths().size(); i != e; ++i)
            {
                filesystem::path p(m_project.search_paths()[e - 1 - i]);

                if (p.is_relative())
                   p = root_path / p;

                search_paths.append(p.string());
                search_paths.append(";");
            }
        }

        search_paths.append(root_path.string());
    }

    if (!search_paths.empty())
        m_texture_system->attribute("searchpath", search_paths);

    // TODO: set other texture system options here.

    // Create our renderer services.
    RendererServices services(m_project, *m_texture_system);

    // Create our OSL shading system.
    boost::shared_ptr<OSL::ShadingSystem> shading_system(
        OSL::ShadingSystem::create(
            &services,
            m_texture_system.get(),
            &error_handler),
            bind(&destroy_osl_shading_system, _1, m_texture_system.get()));

    if (!search_paths.empty())
        shading_system->attribute("searchpath:shader", search_paths);

    shading_system->attribute("lockgeom", 1);
    shading_system->attribute("colorspace", "Linear");
    shading_system->attribute("commonspace", "world");

    // This array needs to be kept in sync with the ShadingRay::Type enumeration.
    static const char* ray_type_labels[] =
    {
        "camera",
        "light",
        "shadow",
        "probe",
        "diffuse",
        "glossy",
        "specular"
    };

    shading_system->attribute(
        "raytypes",
        OSL::TypeDesc(
            OSL::TypeDesc::STRING,
            sizeof(ray_type_labels) / sizeof(ray_type_labels[0])),
        ray_type_labels);

#ifndef NDEBUG
    // While debugging, we want all possible outputs.
    shading_system->attribute("debug", 1);
    shading_system->attribute("statistics:level", 1);
    shading_system->attribute("compile_report", 1);
    shading_system->attribute("countlayerexecs", 1);
    shading_system->attribute("clearmemory", 1);
#endif

    register_closures(*shading_system);

#endif  // WITH_OSL

    // We start by binding entities inputs. This must be done before creating/updating the trace context.
    if (!bind_scene_entities_inputs())
        return IRendererController::AbortRendering;

    m_project.create_aov_images();
    m_project.update_trace_context();

    const Scene& scene = *m_project.get_scene();

    Frame& frame = *m_project.get_frame();
    frame.print_settings();

    const TraceContext& trace_context = m_project.get_trace_context();

    // Create the texture store.
    TextureStore texture_store(scene, m_params.child("texture_store"));

    // Create the light sampler.
    LightSampler light_sampler(scene, m_params.child("light_sampler"));

    // Create the shading engine.
    ShadingEngine shading_engine(m_params.child("shading_engine"));

    //
    // Create a lighting engine factory.
    //

    auto_ptr<IPassCallback> pass_callback;
    auto_ptr<ILightingEngineFactory> lighting_engine_factory;
    {
        const string value = m_params.get_required<string>("lighting_engine", "pt");

        if (value == "drt")
        {
            lighting_engine_factory.reset(
                new DRTLightingEngineFactory(
                    light_sampler,
                    m_params.child("drt")));    // todo: change to "drt_lighting_engine" -- or?
        }
        else if (value == "pt")
        {
            lighting_engine_factory.reset(
                new PTLightingEngineFactory(
                    light_sampler,
                    m_params.child("pt")));     // todo: change to "pt_lighting_engine" -- or?
        }
        else if (value == "sppm")
        {
            const SPPMParameters params(m_params.child("sppm"));

            SPPMPassCallback* sppm_pass_callback =
                new SPPMPassCallback(
                    scene,
                    light_sampler,
                    trace_context,
                    texture_store,
#ifdef WITH_OSL
                    *shading_system,
#endif
                    params);
            pass_callback.reset(sppm_pass_callback);

            lighting_engine_factory.reset(
                new SPPMLightingEngineFactory(
                    *sppm_pass_callback,
                    light_sampler,
                    params));
        }
        else
        {
            RENDERER_LOG_ERROR(
                "invalid value for \"lighting_engine\" parameter: \"%s\".",
                value.c_str());

            return IRendererController::AbortRendering;
        }
    }

    //
    // Create a sample renderer factory.
    //

    auto_ptr<ISampleRendererFactory> sample_renderer_factory;
    {
        const string value = m_params.get_required<string>("sample_renderer", "generic");

        if (value == "generic")
        {
            sample_renderer_factory.reset(
                new GenericSampleRendererFactory(
                    scene,
                    frame,
                    trace_context,
                    texture_store,
                    lighting_engine_factory.get(),
                    shading_engine,
#ifdef WITH_OSL
                    *shading_system,
#endif
                    m_params.child("generic_sample_renderer")));
        }
        else if (value == "blank")
        {
            sample_renderer_factory.reset(new BlankSampleRendererFactory());
        }
        else if (value == "debug")
        {
            sample_renderer_factory.reset(new DebugSampleRendererFactory());
        }
        else
        {
            RENDERER_LOG_ERROR(
                "invalid value for \"sample_renderer\" parameter: \"%s\".",
                value.c_str());

            return IRendererController::AbortRendering;
        }
    }

    //
    // Create a sample generator factory.
    //

    auto_ptr<ISampleGeneratorFactory> sample_generator_factory;
    {
        const string value = m_params.get_optional<string>("sample_generator", "");

        if (value == "generic")
        {
            sample_generator_factory.reset(
                new GenericSampleGeneratorFactory(
                    frame,
                    sample_renderer_factory.get()));
        }
        else if (value == "lighttracing")
        {
            sample_generator_factory.reset(
                new LightTracingSampleGeneratorFactory(
                    scene,
                    frame,
                    trace_context,
                    texture_store,
                    light_sampler,
#ifdef WITH_OSL
                    *shading_system,
#endif
                    m_params.child("lighttracing_sample_generator")));
        }
        else if (!value.empty())
        {
            RENDERER_LOG_ERROR(
                "invalid value for \"sample_generator\" parameter: \"%s\".",
                value.c_str());

            return IRendererController::AbortRendering;
        }
    }

    //
    // Create a pixel renderer factory.
    //

    auto_ptr<IPixelRendererFactory> pixel_renderer_factory;
    {
        const string value = m_params.get_optional<string>("pixel_renderer", "");

        if (value == "uniform")
        {
            pixel_renderer_factory.reset(
                new UniformPixelRendererFactory(
                    sample_renderer_factory.get(),
                    m_params.child("uniform_pixel_renderer")));
        }
        else if (value == "adaptive")
        {
            pixel_renderer_factory.reset(
                new AdaptivePixelRendererFactory(
                    frame,
                    sample_renderer_factory.get(),
                    m_params.child("adaptive_pixel_renderer")));
        }
        else if (!value.empty())
        {
            RENDERER_LOG_ERROR(
                "invalid value for \"pixel_renderer\" parameter: \"%s\".",
                value.c_str());

            return IRendererController::AbortRendering;
        }
    }

    //
    // Create a shading result framebuffer factory.
    //

    auto_ptr<IShadingResultFrameBufferFactory> shading_result_framebuffer_factory;
    {
        const string value =
            m_params.get_optional<string>("shading_result_framebuffer", "ephemeral");

        if (value == "ephemeral")
        {
            shading_result_framebuffer_factory.reset(
                new EphemeralShadingResultFrameBufferFactory());
        }
        else if (value == "permanent")
        {
            shading_result_framebuffer_factory.reset(
                new PermanentShadingResultFrameBufferFactory(frame));
        }
        else if (!value.empty())
        {
            RENDERER_LOG_ERROR(
                "invalid value for \"shading_result_framebuffer\" parameter: \"%s\".",
                value.c_str());

            return IRendererController::AbortRendering;
        }
    }

    //
    // Create a tile renderer factory.
    //

    auto_ptr<ITileRendererFactory> tile_renderer_factory;
    {
        const string value = m_params.get_optional<string>("tile_renderer", "");

        if (value == "generic")
        {
            tile_renderer_factory.reset(
                new GenericTileRendererFactory(
                    frame,
                    pixel_renderer_factory.get(),
                    shading_result_framebuffer_factory.get(),
                    m_params.child("generic_tile_renderer")));
        }
        else if (value == "blank")
        {
            tile_renderer_factory.reset(new BlankTileRendererFactory());
        }
        else if (value == "debug")
        {
            tile_renderer_factory.reset(new DebugTileRendererFactory());
        }
        else if (!value.empty())
        {
            RENDERER_LOG_ERROR(
                "invalid value for \"tile_renderer\" parameter: \"%s\".",
                value.c_str());

            return IRendererController::AbortRendering;
        }
    }

    //
    // Create a frame renderer.
    //

    auto_release_ptr<IFrameRenderer> frame_renderer;
    {
        const string value = m_params.get_required<string>("frame_renderer", "generic");

        if (value == "generic")
        {
            ParamArray params = m_params.child("generic_frame_renderer");
            copy_param(params, m_params, "rendering_threads");

            frame_renderer.reset(
                GenericFrameRendererFactory::create(
                    frame,
                    tile_renderer_factory.get(),
                    m_tile_callback_factory,
                    pass_callback.get(),
                    params));
        }
        else if (value == "progressive")
        {
            ParamArray params = m_params.child("progressive_frame_renderer");
            copy_param(params, m_params, "rendering_threads");

            frame_renderer.reset(
                ProgressiveFrameRendererFactory::create(
                    m_project,
                    sample_generator_factory.get(),
                    m_tile_callback_factory,
                    params));
        }
        else
        {
            RENDERER_LOG_ERROR(
                "invalid value for \"frame_renderer\" parameter: \"%s\".",
                value.c_str());

            return IRendererController::AbortRendering;
        }
    }

    // Execute the main rendering loop.
    const IRendererController::Status status =
        render_frame_sequence(
            frame_renderer.get()
#ifdef WITH_OSL
            , *shading_system
#endif
            );

    // Print texture store performance statistics.
    RENDERER_LOG_DEBUG("%s", texture_store.get_statistics().to_string().c_str());

    return status;
}
Exemple #12
0
void 
Scene::load(const filesystem::path &file)
{
  size_t i;
  std::string message;

  if(!filesystem::exists(file))
    throw std::runtime_error(std::string("File does not exists:") + file.string());

  this->collada = new DAE;

  message = "Start loading COLLADA DOM from ";
  message += file.string();
  this->scene_graph.printStatusMessage(message); 
  this->dae_file_name = file;

  // load with full path 
  domCOLLADA *dom = this->collada->open(file.string());
  if(!dom)
    {
      delete this->collada;	
      throw std::runtime_error(std::string("Error loading the COLLADA file ") 
			  + file.string() 
			  + ". Make sure it is COLLADA 1.4 or greater");
    }

  this->scene_graph.printStatusMessage("Begin conditioning");

  //if(kmzcleanup(this->collada, true))
  //  std::cout << "  kmzcleanup complete\n";
  int res = 0;

  this->scene_graph.printStatusMessage("  triangulating");
  res = triangulate(this->collada);
	if(res)
  {
    std::ostringstream os;
    os << "  triangulation returns error " << res << std::ends;
    this->scene_graph.printStatusMessage(os.str());
  }
  else
    this->scene_graph.printStatusMessage(std::string("  triangulation complete"));
/*
  this->scene_graph.printStatusMessage(std::string("  deindexing"));
  res = deindex(this->collada);
	if(res)
  {
    std::ostringstream os;
    os << "  deindexer returns error " << res << std::ends;
    this->scene_graph.printStatusMessage(os.str());
  }
  else
    this->scene_graph.printStatusMessage(std::string("  deindexing complete"));
*/
  this->scene_graph.printStatusMessage(std::string("Finish conditioning."));

  // Need to get the asset tag which will determine what vector x y or z is up.  Typically y or z. 
  domAssetRef asset = dom->getAsset();
  this->scene_graph.printStatusMessage(std::string("File information:"));
  const domAsset::domContributor_Array &contributors = asset->getContributor_array();
  for(i = 0; i < contributors.getCount(); ++i)
  {
    domAsset::domContributorRef c = contributors.get(i);
    this->scene_graph.printStatusMessage(std::string("  author:") + c->getAuthor()->getCharData());
    this->scene_graph.printStatusMessage(std::string("  authoring tool:") + c->getAuthoring_tool()->getCharData());
  }
  if(asset->getCreated())
    this->scene_graph.printStatusMessage(std::string("  created: ") + asset->getCreated()->getCharData());
  if(asset->getModified())
    this->scene_graph.printStatusMessage(std::string("  modified: ") + asset->getModified()->getCharData());
  if(asset->getUnit())
  {
    std::ostringstream os;
    os << "  units: " << asset->getUnit()->getMeter() << " meter (" << asset->getUnit()->getAttribute("name") << ")";
    os << std::ends;
    this->scene_graph.printStatusMessage(os.str());
  }
  if(asset->getUp_axis())
    {
      domAsset::domUp_axis *up = dom->getAsset()->getUp_axis();
      if(up)
        this->up_axis = up->getValue();
      switch(this->up_axis)
        {
        case UPAXISTYPE_X_UP:
          this->scene_graph.printStatusMessage(std::string("  X axis is UP axis.")); 
          break; 

        case UPAXISTYPE_Y_UP:
          this->scene_graph.printStatusMessage(std::string("  Y axis is UP axis.")); 
          break;

        case UPAXISTYPE_Z_UP:
          this->scene_graph.printStatusMessage(std::string("  Z axis is UP axis.")); 
          break; 

        default:
          break; 
        }
  	}

  this->scene_graph.printStatusMessage("Building libraries");
 	
  // Load the image for the default texture.

  const Image::ImageID image_key = {"default", ""};
  bool inserted;
  Image::ImageList::iterator img_iter;
  tie(img_iter, inserted) = this->scene_graph.all_images.insert(std::make_pair(image_key, Image()));

  Image &img = img_iter->second;
  img.image = IMG_Load("default.tga");
  if(!img.image)
  {
    scene_graph.all_images.erase(image_key);
    this->scene_graph.printStatusMessage("Can not load default.tga for the default texture.");
  }

  this->scene_graph.printStatusMessage("  Load image libraries");
  const domLibrary_images_Array &ia = dom->getLibrary_images_array();
	for(i = 0; i < ia.getCount(); ++i)
		this->readImageLibrary(ia[i]);

  this->scene_graph.printStatusMessage("  Load effect libraries");
  const domLibrary_effects_Array &ea = dom->getLibrary_effects_array();
	for(i = 0; i < ea.getCount(); i++)
		this->readEffectLibrary(ea[i]);

  this->scene_graph.printStatusMessage("  Load material libraries");
  const domLibrary_materials_Array &ma = dom->getLibrary_materials_array();
	for(i = 0; i < ma.getCount(); i++)
		this->readMaterialLibrary(ma[i]);

  this->scene_graph.printStatusMessage("  Load animation libraries");
  const domLibrary_animations_Array &aa = dom->getLibrary_animations_array();
	for(i = 0; i < aa.getCount(); i++)
		this->readAnimationLibrary(aa[i]);

	// Find the scene we want
	domCOLLADA::domSceneRef domScene = dom->getScene();
	daeElement* defaultScene = NULL;
	if (domScene)
		if (domScene->getInstance_visual_scene())
			if (domScene->getInstance_visual_scene())
				defaultScene = domScene->getInstance_visual_scene()->getUrl().getElement();
	if(defaultScene)
		this->readScene((domVisual_scene*)defaultScene);

	// If no lights were loaded, we need to make one so the scene won't be totally black
	if(this->scene_graph.all_lights.empty())
	{
		// new Light  
		this->scene_graph.printStatusMessage("Scene: no lights were loaded. Creating a default light");
    const Light::LightID light_key = 
      {"no_light_in_scene_default_light", dom->getDocumentURI()->getURI()};
    bool inserted;
    Light::LightList::iterator light;
    tie(light, inserted) = scene_graph.all_lights.insert(std::make_pair(light_key, Light()));
    Light &default_light = light->second;
		default_light.type = Light::DIRECTIONAL;
		default_light.color = Color4f(1, 1, 1, 1);

		// new Node
		this->scene_graph.printStatusMessage("Scene: no instance_light found creating a node with an instance");
    this->scene_graph.insertNode(this->scene_graph.root,
                                 "no_light_in_scene_default_node",
                                 "no_light_in_scene_default_node",
                                 "NONE");
    // Read node transformations
    Node &current_node = *this->scene_graph.all_nodes.find("no_light_in_scene_default_node");

    current_node.transformations.push_back(Transformation());
    Transformation &transform = 
      current_node.transformations.at(current_node.transformations.size() - 1);
		transform.type = Transformation::Translate; 
		const Vector3 trans(-40.0, 40.0, 0.0);
    transform.transform = Transform3::translation(trans);

		// new InstanceLight
    InstanceLight instance_light;
    instance_light.abstract_light_ref = light->first;
    current_node.instance_lights.push_back(instance_light);
    this->scene_graph.light_nodes.push_back("no_light_in_scene_default_node"); 
  }

  if(!this->scene_graph.all_cameras.empty())
  {
    // Search for the first camera node
    Node::NodeMap &all_nodes = this->scene_graph.all_nodes;
    for(int n = 0; n < all_nodes.size(); ++n)
    {
      Node *node = all_nodes.getAtIndex(n);
      if(node->instance_cameras.size() > 0)
      {
        this->scene_graph.active_camera_info = std::make_pair(node, &(node->instance_cameras[0]));
        break;
      }
    }
  }
  else
	{
		this->scene_graph.printStatusMessage( "Scene: create a default camera and it is the first camera to use");
		// new Camera
    const Camera::CameraID camera_key = 
      {"no_camera_in_scene_default_camera", dom->getDocumentURI()->getURI()};

	  // Make the camera
    bool inserted;
    Camera::CameraList::iterator camera;
    tie(camera, inserted) = this->scene_graph.all_cameras.insert(std::make_pair(camera_key, Camera()));
    Camera &default_camera = camera->second;
    default_camera.Xfov = 45.0f;
    default_camera.Yfov = 45.0f;

		this->scene_graph.printStatusMessage( "Scene: creating a node with an instance of default camera");
		// new Node
    this->scene_graph.insertNode(this->scene_graph.root,
                                 "no_camera_in_scene_default_node",
                                 "no_camera_in_scene_default_node",
                                 "NONE");
    // Read node transformations
    Node &current_node = *this->scene_graph.all_nodes.find("no_camera_in_scene_default_node");

    // Calculate approximate bounding box for the model
    Vector3 max(0,0,0);
    Vector3 min(0,0,0);
    for(Geometry::GeometryList::const_iterator g = this->scene_graph.all_geometries.begin();
      g != this->scene_graph.all_geometries.end(); ++g)
    {
      // Points are stored as x/y/z tripples within this array
      for(Geometry::PointList::const_iterator p = g->second.points.begin();
        p != g->second.points.end(); ++p)
      {
        // X
        if(*p > max.getX())
          max.setX(*p);
        else if(*p < min.getX())
          min.setX(*p);
        // Y
        ++p;
        if(*p > max.getY())
          max.setY(*p);
        else if(*p < min.getY())
          min.setY(*p);
        // Z
        ++p;
        if(*p > max.getZ())
          max.setZ(*p);
        else if(*p < min.getZ())
          min.setZ(*p);
      }
    }

    default_camera.ZNear = 1.0f;
		default_camera.ZFar = 1000.0f;

    current_node.transformations.push_back(Transformation());
    Transformation &transform = 
      current_node.transformations.at(current_node.transformations.size() - 1);
    transform.type = Transformation::LookAt;
    const Point3 eyePos(max.getX() * 0.5f, max.getY() * 0.5f, max.getZ() * 0.5f);
    const Point3 lookAtPos(min.getX(), min.getY(), min.getZ());
    Vector3 upVec;
    upVec.setY(0);
		if(this->up_axis == UPAXISTYPE_Z_UP)
    {
      upVec.setX(0);
      upVec.setZ(1.0f);
    }
		else if(this->up_axis == UPAXISTYPE_X_UP)
    {
      upVec.setX(1.0f);
      upVec.setZ(0);
    }
    // Store transformation
    transform.matrix = inverse(Matrix4::lookAt(eyePos, lookAtPos, upVec));
    current_node.local_matrix *= transform.matrix;

    // new InstanceCamera
    InstanceCamera instance_camera;
    instance_camera.abstract_camera_ref = camera->first;
    current_node.instance_cameras.push_back(instance_camera);
    this->scene_graph.active_camera_info = std::make_pair(&current_node,
      &(current_node.instance_cameras.at(current_node.instance_cameras.size() - 1)));
	}

  this->scene_graph.printStatusMessage(std::string("COLLADA_DOM runtime database initialized from ") + file.filename().string());
}
void process_data(const filesystem::path & in_fname_path)
{
    filesystem::path out_fname_path(in_fname_path);
    
    string out_fname_str(out_fname_path.filename().string());
    const char * str_to_replace = "input_";
    size_t pos = out_fname_str.find(str_to_replace);
    size_t len = strlen(str_to_replace);
    out_fname_str.replace(pos, len,"output_");
    out_fname_path.remove_filename();
    out_fname_path /= out_fname_str;
    
    std::ifstream in_file(in_fname_path.string(),ios_base::binary);
    std::ofstream out_file(out_fname_path.string(),ios_base::binary);
    
    try {
        if(!in_file.is_open()||!out_file.is_open())
            throw runtime_error("Error:Unable to open file");
    } catch (runtime_error& e) {
        cerr << e.what() << endl;
        return;
    }
    
    TypeMap type_map;
    map<uint32_t, uint32_t> bufferUsedBytesMap;
    uint32_t lastSecond = UINT32_MAX;
    
    while (1) {
        binary_reader::market_message msg(in_file);
        
        if(in_file.eof())
            break;
        
        const uint32_t type = msg.type();
        const uint32_t time = msg.time();
        
        if(lastSecond!=time)
        {
            bufferUsedBytesMap.clear();
            lastSecond = time;
        }
        
        const uint32_t msgBytes = msg.msg_len() + sizeof(uint32_t)*3;
        
        if((bufferUsedBytesMap[type] + msgBytes) > kBufferSize)
            continue;
        
        bufferUsedBytesMap[type]+=msgBytes;
        
        ++type_map[type][time];
        
    }
    
    TypeMap::const_iterator type_iter;
    
    for(type_iter = type_map.begin();type_iter != type_map.end(); ++type_iter)
    {
        const uint32_t type = type_iter->first;
        const TimeMap& sec_map = type_iter->second;
        
        uint32_t cnt = 0;
        uint32_t secs = 0;
        
        TimeMap::const_iterator sec_iter;
        
        for(sec_iter = sec_map.begin();sec_iter != sec_map.end(); ++sec_iter)
        {
            cnt += sec_iter->second;
            secs++;
        }
        
        out_file.write( reinterpret_cast< const char * >( &type), sizeof(type));
        const double avg = cnt/static_cast<double>(secs);
        out_file.write( reinterpret_cast<const char * >( &avg), sizeof(avg));
    }
    
}