<commit_before>/*****************************************************************************************
 *                                                                                *
 * OpenSpace                                                                             *
 *                                                                                *
 * Copyright (c) 2014-2018                                                               *
 *                                                                                *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this  *
 * software and associated documentation files (the "Software"), to deal in the Software *
 * without restriction, including without limitation the rights to use, copy, modify,    *
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to    *
 * permit persons to whom the Software is furnished to do so, subject to the following   *
 * conditions:                                                                           *
 *                                                                                *
 * The above copyright notice and this permission notice shall be included in all copies *
 * or substantial portions of the Software.                                              *
 *                                                                                *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *
 ****************************************************************************************/

#include <modules/base/rendering/renderableplane.h>

#include <modules/base/basemodule.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/util/updatestructures.h>

#include <ghoul/filesystem/filesystem.h>
#include <ghoul/io/texture/texturereader.h>
#include <ghoul/misc/defer.h>
#include <ghoul/opengl/programobject.h>
#include <ghoul/opengl/texture.h>
#include <ghoul/opengl/textureunit.h>

namespace {
    constexpr const char* ProgramName = "Plane";

    enum BlendMode {
        BlendModeNormal = 0,
        BlendModeAdditive
    };

    const openspace::properties::Property::PropertyInfo BillboardInfo = {
        "Billboard",
        "Billboard mode",
        "This value specifies whether the plane is a billboard, which means that it is "
        "always facing the camera. If this is false, it can be oriented using other "
        "transformations."
    };

    const openspace::properties::Property::PropertyInfo SizeInfo = {
        "Size",
        "Size (in meters)",
        "This value specifies the size of the plane in meters."
    };

    const openspace::properties::Property::PropertyInfo BlendModeInfo = {
        "BlendMode",
        "Blending Mode",
        "This determines the blending mode that is applied to this plane."
    };
} // namespace

namespace openspace {

documentation::Documentation RenderablePlane::Documentation() {
    using namespace documentation;
    return {
        "Renderable Plane",
        "base_renderable_plane",
        {
            {
                SizeInfo.identifier,
                new DoubleVerifier,
                Optional::No,
                SizeInfo.description
            },
            {
                BillboardInfo.identifier,
                new BoolVerifier,
                Optional::Yes,
                BillboardInfo.description
            },
            {
                BlendModeInfo.identifier,
                new StringInListVerifier({ "Normal", "Additive" }),
                Optional::Yes,
                BlendModeInfo.description, // + " The default value is 'Normal'.",
            }
        }
    };
}

RenderablePlane::RenderablePlane(const ghoul::Dictionary& dictionary)
    : Renderable(dictionary)
    , _billboard(BillboardInfo, false)
    , _size(SizeInfo, 10.f, 0.f, 1e25f)
    , _blendMode(BlendModeInfo, properties::OptionProperty::DisplayType::Dropdown)
{
    documentation::testSpecificationAndThrow(
        Documentation(),
        dictionary,
        "RenderablePlane"
    );

    addProperty(_opacity);
    registerUpdateRenderBinFromOpacity();

    _size = static_cast<float>(dictionary.value<double>(SizeInfo.identifier));

    if (dictionary.hasKey(BillboardInfo.identifier)) {
        _billboard = dictionary.value<bool>(BillboardInfo.identifier);
    }

    _blendMode.addOptions({
        { BlendModeNormal, "Normal" },
        { BlendModeAdditive, "Additive"}
    });
    _blendMode.onChange([&]() {
        switch (_blendMode) {
            case BlendModeNormal:
                setRenderBin(Renderable::RenderBin::Opaque);
                break;
            case BlendModeAdditive:
                setRenderBin(Renderable::RenderBin::Transparent);
                break;
            default:
                throw ghoul::MissingCaseException();
        }
    });

    if (dictionary.hasKey(BlendModeInfo.identifier)) {
        const std::string v = dictionary.value<std::string>(BlendModeInfo.identifier);
        if (v == "Normal") {
            _blendMode = BlendModeNormal;
        }
        else if (v == "Additive") {
            _blendMode = BlendModeAdditive;
        }
    }

    addProperty(_billboard);

    addProperty(_size);
    _size.onChange([this](){ _planeIsDirty = true; });

    setBoundingSphere(_size);
}

bool RenderablePlane::isReady() const {
    return _shader != nullptr;
}

void RenderablePlane::initializeGL() {
    glGenVertexArrays(1, &_quad); // generate array
    glGenBuffers(1, &_vertexPositionBuffer); // generate buffer
    createPlane();

    _shader = BaseModule::ProgramObjectManager.requestProgramObject(
        ProgramName,
        []() -> std::unique_ptr<ghoul::opengl::ProgramObject> {
            return OsEng.renderEngine().buildRenderProgram(
                ProgramName,
                absPath("${MODULE_BASE}/shaders/plane_vs.glsl"),
                absPath("${MODULE_BASE}/shaders/plane_fs.glsl")
            );
        }
    );
}

void RenderablePlane::deinitializeGL() {
    glDeleteVertexArrays(1, &_quad);
    _quad = 0;

    glDeleteBuffers(1, &_vertexPositionBuffer);
    _vertexPositionBuffer = 0;

    BaseModule::ProgramObjectManager.releaseProgramObject(
        ProgramName,
        [](ghoul::opengl::ProgramObject* p) {
            OsEng.renderEngine().removeRenderProgram(p);
        }
    );
    _shader = nullptr;
}

void RenderablePlane::render(const RenderData& data, RendererTasks&) {
    _shader->activate();

    _shader->setUniform("opacity", _opacity);

    // Model transform and view transform needs to be in double precision
    const glm::dmat4 rotationTransform = _billboard ?
        glm::inverse(glm::dmat4(data.camera.viewRotationMatrix())) :
        glm::dmat4(data.modelTransform.rotation);

    const glm::dmat4 modelTransform =
        glm::translate(glm::dmat4(1.0), data.modelTransform.translation) *
        rotationTransform *
        glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)) *
        glm::dmat4(1.0);
    const glm::dmat4 modelViewTransform =
        data.camera.combinedViewMatrix() * modelTransform;

    _shader->setUniform("modelViewProjectionTransform",
        data.camera.projectionMatrix() * glm::mat4(modelViewTransform));

    _shader->setUniform("modelViewTransform",
        glm::mat4(data.camera.combinedViewMatrix() * glm::dmat4(modelViewTransform)));

    ghoul::opengl::TextureUnit unit;
    unit.activate();
    bindTexture();
    defer { unbindTexture(); };

    _shader->setUniform("texture1", unit);

    bool usingFramebufferRenderer = OsEng.renderEngine().rendererImplementation() ==
                                    RenderEngine::RendererImplementation::Framebuffer;

    bool usingABufferRenderer = OsEng.renderEngine().rendererImplementation() ==
                                RenderEngine::RendererImplementation::ABuffer;

    if (usingABufferRenderer) {
        _shader->setUniform("additiveBlending", _blendMode == BlendModeAdditive);
    }

    bool additiveBlending = (_blendMode == BlendModeAdditive) && usingFramebufferRenderer;
    if (additiveBlending) {
        glDepthMask(false);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE);
    }

    glBindVertexArray(_quad);
    glDrawArrays(GL_TRIANGLES, 0, 6);

    if (additiveBlending) {
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glDepthMask(true);
    }

    _shader->deactivate();
}

void RenderablePlane::bindTexture() {}

void RenderablePlane::unbindTexture() {}

void RenderablePlane::update(const UpdateData&) {
    if (_shader->isDirty()) {
        _shader->rebuildFromFile();
    }

    if (_planeIsDirty) {
        createPlane();
    }
}

void RenderablePlane::createPlane() {
    const GLfloat size = _size;
    const GLfloat vertexData[] = {
        //      x      y     z     w     s     t
        -size, -size, 0.f, 0.f, 0.f, 0.f,
        size, size, 0.f, 0.f, 1.f, 1.f,
        -size, size, 0.f, 0.f, 0.f, 1.f,
        -size, -size, 0.f, 0.f, 0.f, 0.f,
        size, -size, 0.f, 0.f, 1.f, 0.f,
        size, size, 0.f, 0.f, 1.f, 1.f,
    };

    glBindVertexArray(_quad);
    glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, nullptr);

    glEnableVertexAttribArray(1);
    glVertexAttribPointer(
        1,
        2,
        GL_FLOAT,
        GL_FALSE,
        sizeof(GLfloat) * 6,
        reinterpret_cast<void*>(sizeof(GLfloat) * 4)
    );
}

} // namespace openspace
<commit_msg>Fixed RenderablePlane billboard orientation in dome. (#620)<commit_after>/*****************************************************************************************
 *                                                                                *
 * OpenSpace                                                                             *
 *                                                                                *
 * Copyright (c) 2014-2018                                                               *
 *                                                                                *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this  *
 * software and associated documentation files (the "Software"), to deal in the Software *
 * without restriction, including without limitation the rights to use, copy, modify,    *
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to    *
 * permit persons to whom the Software is furnished to do so, subject to the following   *
 * conditions:                                                                           *
 *                                                                                *
 * The above copyright notice and this permission notice shall be included in all copies *
 * or substantial portions of the Software.                                              *
 *                                                                                *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *
 ****************************************************************************************/

#include <modules/base/rendering/renderableplane.h>

#include <modules/base/basemodule.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/util/updatestructures.h>

#include <ghoul/filesystem/filesystem.h>
#include <ghoul/io/texture/texturereader.h>
#include <ghoul/misc/defer.h>
#include <ghoul/opengl/programobject.h>
#include <ghoul/opengl/texture.h>
#include <ghoul/opengl/textureunit.h>
#include <ghoul/glm.h>
#include <glm/gtx/string_cast.hpp>

namespace {
    constexpr const char* ProgramName = "Plane";

    enum BlendMode {
        BlendModeNormal = 0,
        BlendModeAdditive
    };

    const openspace::properties::Property::PropertyInfo BillboardInfo = {
        "Billboard",
        "Billboard mode",
        "This value specifies whether the plane is a billboard, which means that it is "
        "always facing the camera. If this is false, it can be oriented using other "
        "transformations."
    };

    const openspace::properties::Property::PropertyInfo SizeInfo = {
        "Size",
        "Size (in meters)",
        "This value specifies the size of the plane in meters."
    };

    const openspace::properties::Property::PropertyInfo BlendModeInfo = {
        "BlendMode",
        "Blending Mode",
        "This determines the blending mode that is applied to this plane."
    };
} // namespace

namespace openspace {

documentation::Documentation RenderablePlane::Documentation() {
    using namespace documentation;
    return {
        "Renderable Plane",
        "base_renderable_plane",
        {
            {
                SizeInfo.identifier,
                new DoubleVerifier,
                Optional::No,
                SizeInfo.description
            },
            {
                BillboardInfo.identifier,
                new BoolVerifier,
                Optional::Yes,
                BillboardInfo.description
            },
            {
                BlendModeInfo.identifier,
                new StringInListVerifier({ "Normal", "Additive" }),
                Optional::Yes,
                BlendModeInfo.description, // + " The default value is 'Normal'.",
            }
        }
    };
}

RenderablePlane::RenderablePlane(const ghoul::Dictionary& dictionary)
    : Renderable(dictionary)
    , _billboard(BillboardInfo, false)
    , _size(SizeInfo, 10.f, 0.f, 1e25f)
    , _blendMode(BlendModeInfo, properties::OptionProperty::DisplayType::Dropdown)
{
    documentation::testSpecificationAndThrow(
        Documentation(),
        dictionary,
        "RenderablePlane"
    );

    addProperty(_opacity);
    registerUpdateRenderBinFromOpacity();

    _size = static_cast<float>(dictionary.value<double>(SizeInfo.identifier));

    if (dictionary.hasKey(BillboardInfo.identifier)) {
        _billboard = dictionary.value<bool>(BillboardInfo.identifier);
    }

    _blendMode.addOptions({
        { BlendModeNormal, "Normal" },
        { BlendModeAdditive, "Additive"}
    });
    _blendMode.onChange([&]() {
        switch (_blendMode) {
            case BlendModeNormal:
                setRenderBin(Renderable::RenderBin::Opaque);
                break;
            case BlendModeAdditive:
                setRenderBin(Renderable::RenderBin::Transparent);
                break;
            default:
                throw ghoul::MissingCaseException();
        }
    });

    if (dictionary.hasKey(BlendModeInfo.identifier)) {
        const std::string v = dictionary.value<std::string>(BlendModeInfo.identifier);
        if (v == "Normal") {
            _blendMode = BlendModeNormal;
        }
        else if (v == "Additive") {
            _blendMode = BlendModeAdditive;
        }
    }

    addProperty(_billboard);

    addProperty(_size);
    _size.onChange([this](){ _planeIsDirty = true; });

    setBoundingSphere(_size);
}

bool RenderablePlane::isReady() const {
    return _shader != nullptr;
}

void RenderablePlane::initializeGL() {
    glGenVertexArrays(1, &_quad); // generate array
    glGenBuffers(1, &_vertexPositionBuffer); // generate buffer
    createPlane();

    _shader = BaseModule::ProgramObjectManager.requestProgramObject(
        ProgramName,
        []() -> std::unique_ptr<ghoul::opengl::ProgramObject> {
            return OsEng.renderEngine().buildRenderProgram(
                ProgramName,
                absPath("${MODULE_BASE}/shaders/plane_vs.glsl"),
                absPath("${MODULE_BASE}/shaders/plane_fs.glsl")
            );
        }
    );
}

void RenderablePlane::deinitializeGL() {
    glDeleteVertexArrays(1, &_quad);
    _quad = 0;

    glDeleteBuffers(1, &_vertexPositionBuffer);
    _vertexPositionBuffer = 0;

    BaseModule::ProgramObjectManager.releaseProgramObject(
        ProgramName,
        [](ghoul::opengl::ProgramObject* p) {
            OsEng.renderEngine().removeRenderProgram(p);
        }
    );
    _shader = nullptr;
}

void RenderablePlane::render(const RenderData& data, RendererTasks&) {
    _shader->activate();

    _shader->setUniform("opacity", _opacity);

    glm::dvec3 objectPositionWorld = glm::dvec3(
        glm::translate(
            glm::dmat4(1.0),
            data.modelTransform.translation) * glm::dvec4(0.0, 0.0, 0.0, 1.0)
    );

    glm::dvec3 normal = glm::normalize(data.camera.positionVec3() - objectPositionWorld);
    glm::dvec3 newRight = glm::normalize(
        glm::cross(data.camera.lookUpVectorWorldSpace(), normal)
    );
    glm::dvec3 newUp = glm::cross(normal, newRight);

    glm::dmat4 cameraOrientedRotation;
    cameraOrientedRotation[0] = glm::dvec4(newRight, 0.0);
    cameraOrientedRotation[1] = glm::dvec4(newUp, 0.0);
    cameraOrientedRotation[2] = glm::dvec4(normal, 0.0);

    const glm::dmat4 rotationTransform = _billboard ?
        cameraOrientedRotation :
        glm::dmat4(data.modelTransform.rotation);

    const glm::dmat4 modelTransform =
        glm::translate(glm::dmat4(1.0), data.modelTransform.translation) *
        rotationTransform *
        glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)) *
        glm::dmat4(1.0);
    const glm::dmat4 modelViewTransform =
        data.camera.combinedViewMatrix() * modelTransform;

    _shader->setUniform("modelViewProjectionTransform",
        data.camera.projectionMatrix() * glm::mat4(modelViewTransform));

    _shader->setUniform("modelViewTransform",
        glm::mat4(data.camera.combinedViewMatrix() * glm::dmat4(modelViewTransform)));

    ghoul::opengl::TextureUnit unit;
    unit.activate();
    bindTexture();
    defer { unbindTexture(); };

    _shader->setUniform("texture1", unit);

    bool usingFramebufferRenderer = OsEng.renderEngine().rendererImplementation() ==
                                    RenderEngine::RendererImplementation::Framebuffer;

    bool usingABufferRenderer = OsEng.renderEngine().rendererImplementation() ==
                                RenderEngine::RendererImplementation::ABuffer;

    if (usingABufferRenderer) {
        _shader->setUniform("additiveBlending", _blendMode == BlendModeAdditive);
    }

    bool additiveBlending = (_blendMode == BlendModeAdditive) && usingFramebufferRenderer;
    if (additiveBlending) {
        glDepthMask(false);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE);
    }

    glBindVertexArray(_quad);
    glDrawArrays(GL_TRIANGLES, 0, 6);

    if (additiveBlending) {
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glDepthMask(true);
    }

    _shader->deactivate();
}

void RenderablePlane::bindTexture() {}

void RenderablePlane::unbindTexture() {}

void RenderablePlane::update(const UpdateData&) {
    if (_shader->isDirty()) {
        _shader->rebuildFromFile();
    }

    if (_planeIsDirty) {
        createPlane();
    }
}

void RenderablePlane::createPlane() {
    const GLfloat size = _size;
    const GLfloat vertexData[] = {
        //      x      y     z     w     s     t
        -size, -size, 0.f, 0.f, 0.f, 0.f,
        size, size, 0.f, 0.f, 1.f, 1.f,
        -size, size, 0.f, 0.f, 0.f, 1.f,
        -size, -size, 0.f, 0.f, 0.f, 0.f,
        size, -size, 0.f, 0.f, 1.f, 0.f,
        size, size, 0.f, 0.f, 1.f, 1.f,
    };

    glBindVertexArray(_quad);
    glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, nullptr);

    glEnableVertexAttribArray(1);
    glVertexAttribPointer(
        1,
        2,
        GL_FLOAT,
        GL_FALSE,
        sizeof(GLfloat) * 6,
        reinterpret_cast<void*>(sizeof(GLfloat) * 4)
    );
}

} // namespace openspace
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/common/adapters/adapter_manager.h"

#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/util/util.h"

namespace apollo {
namespace common {
namespace adapter {

AdapterManager::AdapterManager() {}

void AdapterManager::Observe() {
  for (const auto observe : instance()->observers_) {
    observe();
  }
}

bool AdapterManager::Initialized() {
  return instance()->initialized_;
}

void AdapterManager::Reset() {
  instance()->initialized_ = false;
  instance()->observers_.clear();
}

void AdapterManager::Init(const std::string &adapter_config_filename) {
  // Parse config file
  AdapterManagerConfig configs;
  CHECK(util::GetProtoFromFile(adapter_config_filename, &configs))
      << "Unable to parse adapter config file " << adapter_config_filename;
  AINFO << "Init AdapterManger config:" << configs.DebugString();
  Init(configs);
}

void AdapterManager::Init(const AdapterManagerConfig &configs) {
  if (Initialized()) {
    return;
  }

  instance()->initialized_ = true;
  if (configs.is_ros()) {
    instance()->node_handle_.reset(new ros::NodeHandle());
  }

  for (const auto &config : configs.config()) {
    switch (config.type()) {
      case AdapterConfig::POINT_CLOUD:
        EnablePointCloud(FLAGS_pointcloud_topic, config.mode(),
                         config.message_history_limit());
        break;
      case AdapterConfig::GPS:
        EnableGps(FLAGS_gps_topic, config.mode(),
                  config.message_history_limit());
        break;
      case AdapterConfig::IMU:
        EnableImu(FLAGS_imu_topic, config.mode(),
                  config.message_history_limit());
        break;
      case AdapterConfig::CHASSIS:
        EnableChassis(FLAGS_chassis_topic, config.mode(),
                      config.message_history_limit());
        break;
      case AdapterConfig::LOCALIZATION:
        EnableLocalization(FLAGS_localization_topic, config.mode(),
                           config.message_history_limit());
        break;
      case AdapterConfig::PERCEPTION_OBSTACLES:
        EnablePerceptionObstacles(FLAGS_perception_obstacle_topic,
                                  config.mode(),
                                  config.message_history_limit());
        break;
      case AdapterConfig::TRAFFIC_LIGHT_DETECTION:
        EnableTrafficLightDetection(FLAGS_traffic_light_detection_topic,
                                    config.mode(),
                                    config.message_history_limit());
      case AdapterConfig::PAD:
        EnablePad(FLAGS_pad_topic, config.mode(),
                  config.message_history_limit());
        break;
      case AdapterConfig::CONTROL_COMMAND:
        EnableControlCommand(FLAGS_control_command_topic, config.mode(),
                             config.message_history_limit());
        break;
      case AdapterConfig::ROUTING_REQUEST:
        EnableRoutingRequest(FLAGS_routing_request_topic, config.mode(),
                             config.message_history_limit());
        break;
      case AdapterConfig::ROUTING_RESPONSE:
        EnableRoutingResponse(FLAGS_routing_response_topic, config.mode(),
                              config.message_history_limit());
        break;
      case AdapterConfig::PLANNING_TRAJECTORY:
        EnablePlanning(FLAGS_planning_trajectory_topic, config.mode(),
                       config.message_history_limit());
        break;
      case AdapterConfig::PREDICTION:
        EnablePrediction(FLAGS_prediction_topic, config.mode(),
                         config.message_history_limit());
        break;
      case AdapterConfig::MONITOR:
        EnableMonitor(FLAGS_monitor_topic, config.mode(),
                      config.message_history_limit());
        break;
      case AdapterConfig::CHASSIS_DETAIL:
        EnableChassisDetail(FLAGS_chassis_detail_topic, config.mode(),
                            config.message_history_limit());
        break;
      case AdapterConfig::RELATIVE_ODOMETRY:
        EnableRelativeOdometry(FLAGS_relative_odometry_topic, config.mode(),
                               config.message_history_limit());
        break;
      case AdapterConfig::INS_STAT:
        EnableInsStat(FLAGS_ins_stat_topic, config.mode(),
                      config.message_history_limit());
        break;
      case AdapterConfig::INS_STATUS:
        EnableInsStat(FLAGS_ins_status_topic, config.mode(),
                      config.message_history_limit());
        break;
      case AdapterConfig::GNSS_STATUS:
        EnableInsStat(FLAGS_gnss_status_topic, config.mode(),
                      config.message_history_limit());
        break;
      case AdapterConfig::HMI_COMMAND:
        EnableHMICommand(FLAGS_hmi_command_topic, config.mode(),
                         config.message_history_limit());
        break;
      case AdapterConfig::MOBILEYE:
        EnableMobileye(FLAGS_mobileye_topic, config.mode(),
                       config.message_history_limit());
        break;
      case AdapterConfig::DELPHIESR:
        EnableDelphiESR(FLAGS_delphi_esr_topic, config.mode(),
                        config.message_history_limit());
        break;
      case AdapterConfig::COMPRESSED_IMAGE:
        EnableCompressedImage(FLAGS_compressed_image_topic, config.mode(),
                              config.message_history_limit());
        break;
      case AdapterConfig::HMI_STATUS:
        EnableHMIStatus(FLAGS_hmi_status_topic, config.mode(),
                        config.message_history_limit());
        break;
      default:
        AERROR << "Unknown adapter config type!";
        break;
    }
  }
}

}  // namespace adapter
}  // namespace common
}  // namespace apollo
<commit_msg>Common: Fix switch case fall through.<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/common/adapters/adapter_manager.h"

#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/util/util.h"

namespace apollo {
namespace common {
namespace adapter {

AdapterManager::AdapterManager() {}

void AdapterManager::Observe() {
  for (const auto observe : instance()->observers_) {
    observe();
  }
}

bool AdapterManager::Initialized() {
  return instance()->initialized_;
}

void AdapterManager::Reset() {
  instance()->initialized_ = false;
  instance()->observers_.clear();
}

void AdapterManager::Init(const std::string &adapter_config_filename) {
  // Parse config file
  AdapterManagerConfig configs;
  CHECK(util::GetProtoFromFile(adapter_config_filename, &configs))
      << "Unable to parse adapter config file " << adapter_config_filename;
  AINFO << "Init AdapterManger config:" << configs.DebugString();
  Init(configs);
}

void AdapterManager::Init(const AdapterManagerConfig &configs) {
  if (Initialized()) {
    return;
  }

  instance()->initialized_ = true;
  if (configs.is_ros()) {
    instance()->node_handle_.reset(new ros::NodeHandle());
  }

  for (const auto &config : configs.config()) {
    switch (config.type()) {
      case AdapterConfig::POINT_CLOUD:
        EnablePointCloud(FLAGS_pointcloud_topic, config.mode(),
                         config.message_history_limit());
        break;
      case AdapterConfig::GPS:
        EnableGps(FLAGS_gps_topic, config.mode(),
                  config.message_history_limit());
        break;
      case AdapterConfig::IMU:
        EnableImu(FLAGS_imu_topic, config.mode(),
                  config.message_history_limit());
        break;
      case AdapterConfig::CHASSIS:
        EnableChassis(FLAGS_chassis_topic, config.mode(),
                      config.message_history_limit());
        break;
      case AdapterConfig::LOCALIZATION:
        EnableLocalization(FLAGS_localization_topic, config.mode(),
                           config.message_history_limit());
        break;
      case AdapterConfig::PERCEPTION_OBSTACLES:
        EnablePerceptionObstacles(FLAGS_perception_obstacle_topic,
                                  config.mode(),
                                  config.message_history_limit());
        break;
      case AdapterConfig::TRAFFIC_LIGHT_DETECTION:
        EnableTrafficLightDetection(FLAGS_traffic_light_detection_topic,
                                    config.mode(),
                                    config.message_history_limit());
        break;
      case AdapterConfig::PAD:
        EnablePad(FLAGS_pad_topic, config.mode(),
                  config.message_history_limit());
        break;
      case AdapterConfig::CONTROL_COMMAND:
        EnableControlCommand(FLAGS_control_command_topic, config.mode(),
                             config.message_history_limit());
        break;
      case AdapterConfig::ROUTING_REQUEST:
        EnableRoutingRequest(FLAGS_routing_request_topic, config.mode(),
                             config.message_history_limit());
        break;
      case AdapterConfig::ROUTING_RESPONSE:
        EnableRoutingResponse(FLAGS_routing_response_topic, config.mode(),
                              config.message_history_limit());
        break;
      case AdapterConfig::PLANNING_TRAJECTORY:
        EnablePlanning(FLAGS_planning_trajectory_topic, config.mode(),
                       config.message_history_limit());
        break;
      case AdapterConfig::PREDICTION:
        EnablePrediction(FLAGS_prediction_topic, config.mode(),
                         config.message_history_limit());
        break;
      case AdapterConfig::MONITOR:
        EnableMonitor(FLAGS_monitor_topic, config.mode(),
                      config.message_history_limit());
        break;
      case AdapterConfig::CHASSIS_DETAIL:
        EnableChassisDetail(FLAGS_chassis_detail_topic, config.mode(),
                            config.message_history_limit());
        break;
      case AdapterConfig::RELATIVE_ODOMETRY:
        EnableRelativeOdometry(FLAGS_relative_odometry_topic, config.mode(),
                               config.message_history_limit());
        break;
      case AdapterConfig::INS_STAT:
        EnableInsStat(FLAGS_ins_stat_topic, config.mode(),
                      config.message_history_limit());
        break;
      case AdapterConfig::INS_STATUS:
        EnableInsStat(FLAGS_ins_status_topic, config.mode(),
                      config.message_history_limit());
        break;
      case AdapterConfig::GNSS_STATUS:
        EnableInsStat(FLAGS_gnss_status_topic, config.mode(),
                      config.message_history_limit());
        break;
      case AdapterConfig::HMI_COMMAND:
        EnableHMICommand(FLAGS_hmi_command_topic, config.mode(),
                         config.message_history_limit());
        break;
      case AdapterConfig::MOBILEYE:
        EnableMobileye(FLAGS_mobileye_topic, config.mode(),
                       config.message_history_limit());
        break;
      case AdapterConfig::DELPHIESR:
        EnableDelphiESR(FLAGS_delphi_esr_topic, config.mode(),
                        config.message_history_limit());
        break;
      case AdapterConfig::COMPRESSED_IMAGE:
        EnableCompressedImage(FLAGS_compressed_image_topic, config.mode(),
                              config.message_history_limit());
        break;
      case AdapterConfig::HMI_STATUS:
        EnableHMIStatus(FLAGS_hmi_status_topic, config.mode(),
                        config.message_history_limit());
        break;
      default:
        AERROR << "Unknown adapter config type!";
        break;
    }
  }
}

}  // namespace adapter
}  // namespace common
}  // namespace apollo
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                          License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "precomp.hpp"
#include "fast_score.hpp"

using namespace cv;

Ptr<Feature2D> Feature2D::create( const string& feature2DType )
{
    return Algorithm::create<Feature2D>("Feature2D." + feature2DType);
}

/////////////////////// AlgorithmInfo for various detector & descriptors ////////////////////////////

/* NOTE!!!
   All the AlgorithmInfo-related stuff should be in the same file as initModule_features2d().
   Otherwise, linker may throw away some seemingly unused stuff.
*/

CV_INIT_ALGORITHM(BRISK, "Feature2D.BRISK",
                   obj.info()->addParam(obj, "thres", obj.threshold);
                   obj.info()->addParam(obj, "octaves", obj.octaves));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(BriefDescriptorExtractor, "Feature2D.BRIEF",
                  obj.info()->addParam(obj, "bytes", obj.bytes_));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(FastFeatureDetector, "Feature2D.FAST",
                  obj.info()->addParam(obj, "threshold", obj.threshold);
                  obj.info()->addParam(obj, "nonmaxSuppression", obj.nonmaxSuppression));

CV_INIT_ALGORITHM(FastFeatureDetector2, "Feature2D.FASTX",
                  obj.info()->addParam(obj, "threshold", obj.threshold);
                  obj.info()->addParam(obj, "nonmaxSuppression", obj.nonmaxSuppression);
                  obj.info()->addParam(obj, "type", obj.type));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(StarDetector, "Feature2D.STAR",
                  obj.info()->addParam(obj, "maxSize", obj.maxSize);
                  obj.info()->addParam(obj, "responseThreshold", obj.responseThreshold);
                  obj.info()->addParam(obj, "lineThresholdProjected", obj.lineThresholdProjected);
                  obj.info()->addParam(obj, "lineThresholdBinarized", obj.lineThresholdBinarized);
                  obj.info()->addParam(obj, "suppressNonmaxSize", obj.suppressNonmaxSize));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(MSER, "Feature2D.MSER",
                  obj.info()->addParam(obj, "delta", obj.delta);
                  obj.info()->addParam(obj, "minArea", obj.minArea);
                  obj.info()->addParam(obj, "maxArea", obj.maxArea);
                  obj.info()->addParam(obj, "maxVariation", obj.maxVariation);
                  obj.info()->addParam(obj, "minDiversity", obj.minDiversity);
                  obj.info()->addParam(obj, "maxEvolution", obj.maxEvolution);
                  obj.info()->addParam(obj, "areaThreshold", obj.areaThreshold);
                  obj.info()->addParam(obj, "minMargin", obj.minMargin);
                  obj.info()->addParam(obj, "edgeBlurSize", obj.edgeBlurSize));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(ORB, "Feature2D.ORB",
                  obj.info()->addParam(obj, "nFeatures", obj.nfeatures);
                  obj.info()->addParam(obj, "scaleFactor", obj.scaleFactor);
                  obj.info()->addParam(obj, "nLevels", obj.nlevels);
                  obj.info()->addParam(obj, "firstLevel", obj.firstLevel);
                  obj.info()->addParam(obj, "edgeThreshold", obj.edgeThreshold);
                  obj.info()->addParam(obj, "patchSize", obj.patchSize);
                  obj.info()->addParam(obj, "WTA_K", obj.WTA_K);
                  obj.info()->addParam(obj, "scoreType", obj.scoreType));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(FREAK, "Feature2D.FREAK",
                  obj.info()->addParam(obj, "orientationNormalized", obj.orientationNormalized);
                  obj.info()->addParam(obj, "scaleNormalized", obj.scaleNormalized);
                  obj.info()->addParam(obj, "patternScale", obj.patternScale);
                  obj.info()->addParam(obj, "nbOctave", obj.nOctaves));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(GFTTDetector, "Feature2D.GFTT",
                  obj.info()->addParam(obj, "nfeatures", obj.nfeatures);
                  obj.info()->addParam(obj, "qualityLevel", obj.qualityLevel);
                  obj.info()->addParam(obj, "minDistance", obj.minDistance);
                  obj.info()->addParam(obj, "useHarrisDetector", obj.useHarrisDetector);
                  obj.info()->addParam(obj, "k", obj.k));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(SimpleBlobDetector, "Feature2D.SimpleBlob",
                  obj.info()->addParam(obj, "thresholdStep",    obj.params.thresholdStep);
                  obj.info()->addParam(obj, "minThreshold",     obj.params.minThreshold);
                  obj.info()->addParam(obj, "maxThreshold",     obj.params.maxThreshold);
                  obj.info()->addParam_(obj, "minRepeatability", ParamType<size_t>::type, &obj.params.minRepeatability, false, 0, 0);
                  obj.info()->addParam(obj, "minDistBetweenBlobs", obj.params.minDistBetweenBlobs);
                  obj.info()->addParam(obj, "filterByColor",    obj.params.filterByColor);
                  obj.info()->addParam(obj, "blobColor",        obj.params.blobColor);
                  obj.info()->addParam(obj, "filterByArea",     obj.params.filterByArea);
                  obj.info()->addParam(obj, "maxArea",          obj.params.maxArea);
                  obj.info()->addParam(obj, "filterByCircularity", obj.params.filterByCircularity);
                  obj.info()->addParam(obj, "maxCircularity",   obj.params.maxCircularity);
                  obj.info()->addParam(obj, "filterByInertia",  obj.params.filterByInertia);
                  obj.info()->addParam(obj, "maxInertiaRatio",  obj.params.maxInertiaRatio);
                  obj.info()->addParam(obj, "filterByConvexity", obj.params.filterByConvexity);
                  obj.info()->addParam(obj, "maxConvexity",     obj.params.maxConvexity);
                  );

///////////////////////////////////////////////////////////////////////////////////////////////////////////

class CV_EXPORTS HarrisDetector : public GFTTDetector
{
public:
    HarrisDetector( int maxCorners=1000, double qualityLevel=0.01, double minDistance=1,
                    int blockSize=3, bool useHarrisDetector=true, double k=0.04 );
    AlgorithmInfo* info() const;
};

inline HarrisDetector::HarrisDetector( int _maxCorners, double _qualityLevel, double _minDistance,
                    int _blockSize, bool _useHarrisDetector, double _k )
    : GFTTDetector( _maxCorners, _qualityLevel, _minDistance, _blockSize, _useHarrisDetector, _k ) {}

CV_INIT_ALGORITHM(HarrisDetector, "Feature2D.HARRIS",
                  obj.info()->addParam(obj, "nfeatures", obj.nfeatures);
                  obj.info()->addParam(obj, "qualityLevel", obj.qualityLevel);
                  obj.info()->addParam(obj, "minDistance", obj.minDistance);
                  obj.info()->addParam(obj, "useHarrisDetector", obj.useHarrisDetector);
                  obj.info()->addParam(obj, "k", obj.k));

////////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(DenseFeatureDetector, "Feature2D.Dense",
                  obj.info()->addParam(obj, "initFeatureScale", obj.initFeatureScale);
                  obj.info()->addParam(obj, "featureScaleLevels", obj.featureScaleLevels);
                  obj.info()->addParam(obj, "featureScaleMul", obj.featureScaleMul);
                  obj.info()->addParam(obj, "initXyStep", obj.initXyStep);
                  obj.info()->addParam(obj, "initImgBound", obj.initImgBound);
                  obj.info()->addParam(obj, "varyXyStepWithScale", obj.varyXyStepWithScale);
                  obj.info()->addParam(obj, "varyImgBoundWithScale", obj.varyImgBoundWithScale));

CV_INIT_ALGORITHM(GridAdaptedFeatureDetector, "Feature2D.Grid",
                  obj.info()->addParam(obj, "detector", obj.detector);
                  obj.info()->addParam(obj, "maxTotalKeypoints", obj.maxTotalKeypoints);
                  obj.info()->addParam(obj, "gridRows", obj.gridRows);
                  obj.info()->addParam(obj, "gridCols", obj.gridCols));

////////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(BFMatcher, "DescriptorMatcher.BFMatcher",
                  obj.info()->addParam(obj, "normType", obj.normType);
                  obj.info()->addParam(obj, "crossCheck", obj.crossCheck));

CV_INIT_ALGORITHM(FlannBasedMatcher, "DescriptorMatcher.FlannBasedMatcher",);

///////////////////////////////////////////////////////////////////////////////////////////////////////////

bool cv::initModule_features2d(void)
{
    bool all = true;
    all &= !BriefDescriptorExtractor_info_auto.name().empty();
    all &= !BRISK_info_auto.name().empty();
    all &= !FastFeatureDetector_info_auto.name().empty();
    all &= !FastFeatureDetector2_info_auto.name().empty();
    all &= !StarDetector_info_auto.name().empty();
    all &= !MSER_info_auto.name().empty();
    all &= !FREAK_info_auto.name().empty();
    all &= !ORB_info_auto.name().empty();
    all &= !GFTTDetector_info_auto.name().empty();
    all &= !HarrisDetector_info_auto.name().empty();
    all &= !DenseFeatureDetector_info_auto.name().empty();
    all &= !GridAdaptedFeatureDetector_info_auto.name().empty();
    all &= !BFMatcher_info_auto.name().empty();
    all &= !FlannBasedMatcher_info_auto.name().empty();

    return all;
}
<commit_msg>The next attempt to fix a build error on Mac.<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                          License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "precomp.hpp"
#include "fast_score.hpp"

using namespace cv;

Ptr<Feature2D> Feature2D::create( const string& feature2DType )
{
    return Algorithm::create<Feature2D>("Feature2D." + feature2DType);
}

/////////////////////// AlgorithmInfo for various detector & descriptors ////////////////////////////

/* NOTE!!!
   All the AlgorithmInfo-related stuff should be in the same file as initModule_features2d().
   Otherwise, linker may throw away some seemingly unused stuff.
*/

CV_INIT_ALGORITHM(BRISK, "Feature2D.BRISK",
                   obj.info()->addParam(obj, "thres", obj.threshold);
                   obj.info()->addParam(obj, "octaves", obj.octaves));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(BriefDescriptorExtractor, "Feature2D.BRIEF",
                  obj.info()->addParam(obj, "bytes", obj.bytes_));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(FastFeatureDetector, "Feature2D.FAST",
                  obj.info()->addParam(obj, "threshold", obj.threshold);
                  obj.info()->addParam(obj, "nonmaxSuppression", obj.nonmaxSuppression));

CV_INIT_ALGORITHM(FastFeatureDetector2, "Feature2D.FASTX",
                  obj.info()->addParam(obj, "threshold", obj.threshold);
                  obj.info()->addParam(obj, "nonmaxSuppression", obj.nonmaxSuppression);
                  obj.info()->addParam(obj, "type", obj.type));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(StarDetector, "Feature2D.STAR",
                  obj.info()->addParam(obj, "maxSize", obj.maxSize);
                  obj.info()->addParam(obj, "responseThreshold", obj.responseThreshold);
                  obj.info()->addParam(obj, "lineThresholdProjected", obj.lineThresholdProjected);
                  obj.info()->addParam(obj, "lineThresholdBinarized", obj.lineThresholdBinarized);
                  obj.info()->addParam(obj, "suppressNonmaxSize", obj.suppressNonmaxSize));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(MSER, "Feature2D.MSER",
                  obj.info()->addParam(obj, "delta", obj.delta);
                  obj.info()->addParam(obj, "minArea", obj.minArea);
                  obj.info()->addParam(obj, "maxArea", obj.maxArea);
                  obj.info()->addParam(obj, "maxVariation", obj.maxVariation);
                  obj.info()->addParam(obj, "minDiversity", obj.minDiversity);
                  obj.info()->addParam(obj, "maxEvolution", obj.maxEvolution);
                  obj.info()->addParam(obj, "areaThreshold", obj.areaThreshold);
                  obj.info()->addParam(obj, "minMargin", obj.minMargin);
                  obj.info()->addParam(obj, "edgeBlurSize", obj.edgeBlurSize));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(ORB, "Feature2D.ORB",
                  obj.info()->addParam(obj, "nFeatures", obj.nfeatures);
                  obj.info()->addParam(obj, "scaleFactor", obj.scaleFactor);
                  obj.info()->addParam(obj, "nLevels", obj.nlevels);
                  obj.info()->addParam(obj, "firstLevel", obj.firstLevel);
                  obj.info()->addParam(obj, "edgeThreshold", obj.edgeThreshold);
                  obj.info()->addParam(obj, "patchSize", obj.patchSize);
                  obj.info()->addParam(obj, "WTA_K", obj.WTA_K);
                  obj.info()->addParam(obj, "scoreType", obj.scoreType));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(FREAK, "Feature2D.FREAK",
                  obj.info()->addParam(obj, "orientationNormalized", obj.orientationNormalized);
                  obj.info()->addParam(obj, "scaleNormalized", obj.scaleNormalized);
                  obj.info()->addParam(obj, "patternScale", obj.patternScale);
                  obj.info()->addParam(obj, "nbOctave", obj.nOctaves));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(GFTTDetector, "Feature2D.GFTT",
                  obj.info()->addParam(obj, "nfeatures", obj.nfeatures);
                  obj.info()->addParam(obj, "qualityLevel", obj.qualityLevel);
                  obj.info()->addParam(obj, "minDistance", obj.minDistance);
                  obj.info()->addParam(obj, "useHarrisDetector", obj.useHarrisDetector);
                  obj.info()->addParam(obj, "k", obj.k));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(SimpleBlobDetector, "Feature2D.SimpleBlob",
                  obj.info()->addParam(obj, "thresholdStep",    obj.params.thresholdStep);
                  obj.info()->addParam(obj, "minThreshold",     obj.params.minThreshold);
                  obj.info()->addParam(obj, "maxThreshold",     obj.params.maxThreshold);
                  obj.info()->addParam_(obj, "minRepeatability", (sizeof(size_t) == sizeof(uint64))?Param::UINT64 : Param::UNSIGNED_INT, &obj.params.minRepeatability, false, 0, 0);
                  obj.info()->addParam(obj, "minDistBetweenBlobs", obj.params.minDistBetweenBlobs);
                  obj.info()->addParam(obj, "filterByColor",    obj.params.filterByColor);
                  obj.info()->addParam(obj, "blobColor",        obj.params.blobColor);
                  obj.info()->addParam(obj, "filterByArea",     obj.params.filterByArea);
                  obj.info()->addParam(obj, "maxArea",          obj.params.maxArea);
                  obj.info()->addParam(obj, "filterByCircularity", obj.params.filterByCircularity);
                  obj.info()->addParam(obj, "maxCircularity",   obj.params.maxCircularity);
                  obj.info()->addParam(obj, "filterByInertia",  obj.params.filterByInertia);
                  obj.info()->addParam(obj, "maxInertiaRatio",  obj.params.maxInertiaRatio);
                  obj.info()->addParam(obj, "filterByConvexity", obj.params.filterByConvexity);
                  obj.info()->addParam(obj, "maxConvexity",     obj.params.maxConvexity);
                  );

///////////////////////////////////////////////////////////////////////////////////////////////////////////

class CV_EXPORTS HarrisDetector : public GFTTDetector
{
public:
    HarrisDetector( int maxCorners=1000, double qualityLevel=0.01, double minDistance=1,
                    int blockSize=3, bool useHarrisDetector=true, double k=0.04 );
    AlgorithmInfo* info() const;
};

inline HarrisDetector::HarrisDetector( int _maxCorners, double _qualityLevel, double _minDistance,
                    int _blockSize, bool _useHarrisDetector, double _k )
    : GFTTDetector( _maxCorners, _qualityLevel, _minDistance, _blockSize, _useHarrisDetector, _k ) {}

CV_INIT_ALGORITHM(HarrisDetector, "Feature2D.HARRIS",
                  obj.info()->addParam(obj, "nfeatures", obj.nfeatures);
                  obj.info()->addParam(obj, "qualityLevel", obj.qualityLevel);
                  obj.info()->addParam(obj, "minDistance", obj.minDistance);
                  obj.info()->addParam(obj, "useHarrisDetector", obj.useHarrisDetector);
                  obj.info()->addParam(obj, "k", obj.k));

////////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(DenseFeatureDetector, "Feature2D.Dense",
                  obj.info()->addParam(obj, "initFeatureScale", obj.initFeatureScale);
                  obj.info()->addParam(obj, "featureScaleLevels", obj.featureScaleLevels);
                  obj.info()->addParam(obj, "featureScaleMul", obj.featureScaleMul);
                  obj.info()->addParam(obj, "initXyStep", obj.initXyStep);
                  obj.info()->addParam(obj, "initImgBound", obj.initImgBound);
                  obj.info()->addParam(obj, "varyXyStepWithScale", obj.varyXyStepWithScale);
                  obj.info()->addParam(obj, "varyImgBoundWithScale", obj.varyImgBoundWithScale));

CV_INIT_ALGORITHM(GridAdaptedFeatureDetector, "Feature2D.Grid",
                  obj.info()->addParam(obj, "detector", obj.detector);
                  obj.info()->addParam(obj, "maxTotalKeypoints", obj.maxTotalKeypoints);
                  obj.info()->addParam(obj, "gridRows", obj.gridRows);
                  obj.info()->addParam(obj, "gridCols", obj.gridCols));

////////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(BFMatcher, "DescriptorMatcher.BFMatcher",
                  obj.info()->addParam(obj, "normType", obj.normType);
                  obj.info()->addParam(obj, "crossCheck", obj.crossCheck));

CV_INIT_ALGORITHM(FlannBasedMatcher, "DescriptorMatcher.FlannBasedMatcher",);

///////////////////////////////////////////////////////////////////////////////////////////////////////////

bool cv::initModule_features2d(void)
{
    bool all = true;
    all &= !BriefDescriptorExtractor_info_auto.name().empty();
    all &= !BRISK_info_auto.name().empty();
    all &= !FastFeatureDetector_info_auto.name().empty();
    all &= !FastFeatureDetector2_info_auto.name().empty();
    all &= !StarDetector_info_auto.name().empty();
    all &= !MSER_info_auto.name().empty();
    all &= !FREAK_info_auto.name().empty();
    all &= !ORB_info_auto.name().empty();
    all &= !GFTTDetector_info_auto.name().empty();
    all &= !HarrisDetector_info_auto.name().empty();
    all &= !DenseFeatureDetector_info_auto.name().empty();
    all &= !GridAdaptedFeatureDetector_info_auto.name().empty();
    all &= !BFMatcher_info_auto.name().empty();
    all &= !FlannBasedMatcher_info_auto.name().empty();

    return all;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2007-2017 Content Management AG
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "Launch.hxx"
#include "spawn/UidGid.hxx"
#include "system/Error.hxx"
#include "util/PrintException.hxx"

#include "util/Compiler.h"

#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

gcc_noreturn
static void
RunLogger(const char *command, UniqueSocketDescriptor &&fd)
{
    fd.CheckDuplicate(FileDescriptor(STDIN_FILENO));

    execl("/bin/sh", "sh", "-c", command, nullptr);
    fprintf(stderr, "failed to execute %s: %s\n",
            command, strerror(errno));
    _exit(EXIT_FAILURE);
}

LogProcess
LaunchLogger(const char *command,
             const UidGid *user)
{
    LogProcess p;
    UniqueSocketDescriptor server_fd;

    if (!UniqueSocketDescriptor::CreateSocketPair(AF_LOCAL, SOCK_SEQPACKET, 0,
                                                  server_fd, p.fd))
        throw MakeErrno("socketpair() failed");

    /* we need an unidirectional socket only */
    p.fd.ShutdownRead();
    server_fd.ShutdownWrite();

    p.pid = fork();
    if (p.pid < 0)
        throw MakeErrno("fork() failed");

    if (p.pid == 0) {
        try {
            if (user != nullptr)
                user->Apply();

            RunLogger(command, std::move(server_fd));
        } catch (...) {
            PrintException(std::current_exception());
            _exit(EXIT_FAILURE);
        }
    }

    return p;
}
<commit_msg>access_log/Launch: pass SocketDescriptor to RunLogger()<commit_after>/*
 * Copyright 2007-2017 Content Management AG
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "Launch.hxx"
#include "spawn/UidGid.hxx"
#include "system/Error.hxx"
#include "util/PrintException.hxx"

#include "util/Compiler.h"

#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

gcc_noreturn
static void
RunLogger(const char *command, SocketDescriptor fd)
{
    fd.CheckDuplicate(FileDescriptor(STDIN_FILENO));

    execl("/bin/sh", "sh", "-c", command, nullptr);
    fprintf(stderr, "failed to execute %s: %s\n",
            command, strerror(errno));
    _exit(EXIT_FAILURE);
}

LogProcess
LaunchLogger(const char *command,
             const UidGid *user)
{
    LogProcess p;
    UniqueSocketDescriptor server_fd;

    if (!UniqueSocketDescriptor::CreateSocketPair(AF_LOCAL, SOCK_SEQPACKET, 0,
                                                  server_fd, p.fd))
        throw MakeErrno("socketpair() failed");

    /* we need an unidirectional socket only */
    p.fd.ShutdownRead();
    server_fd.ShutdownWrite();

    p.pid = fork();
    if (p.pid < 0)
        throw MakeErrno("fork() failed");

    if (p.pid == 0) {
        try {
            if (user != nullptr)
                user->Apply();

            RunLogger(command, server_fd);
        } catch (...) {
            PrintException(std::current_exception());
            _exit(EXIT_FAILURE);
        }
    }

    return p;
}
<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id: memory.cc,v 1.40 2005/04/10 19:42:48 sshwarts Exp $
/////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2001  MandrakeSoft S.A.
//
//    MandrakeSoft S.A.
//    43, rue d'Aboukir
//    75002 Paris - France
//    http://www.linux-mandrake.com/
//    http://www.mandrakesoft.com/
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

#include "iodev/iodev.h"
#define LOG_THIS BX_MEM_THIS

#if BX_PROVIDE_CPU_MEMORY

  void BX_CPP_AttrRegparmN(3)
BX_MEM_C::writePhysicalPage(BX_CPU_C *cpu, Bit32u addr, unsigned len, void *data)
{
  Bit8u *data_ptr;
  Bit32u a20addr;

  // Note: accesses should always be contained within a single page now.

#if BX_SUPPORT_IODEBUG
  bx_iodebug_c::mem_write(cpu, addr, len, data);
#endif

  a20addr = A20ADDR(addr);
  struct memory_handler_struct *memory_handler = memory_handlers[a20addr >> 20];
  while (memory_handler) {
	  if (memory_handler->begin <= a20addr &&
		memory_handler->end >= a20addr &&
	  	memory_handler->write_handler(a20addr, len, data, memory_handler->write_param))
		  return;
	  memory_handler = memory_handler->next;
  }

  BX_INSTR_PHY_WRITE(cpu->which_cpu(), a20addr, len);

#if BX_DEBUGGER
  // (mch) Check for physical write break points, TODO
  // (bbd) Each breakpoint should have an associated CPU#, TODO
  for (int i = 0; i < num_write_watchpoints; i++)
        if (write_watchpoint[i] == a20addr) {
	      BX_CPU(0)->watchpoint = a20addr;
              BX_CPU(0)->break_point = BREAK_POINT_WRITE;
              break;
        }
#endif

#if BX_SUPPORT_ICACHE
  if (a20addr < BX_MEM_THIS len)
    pageWriteStampTable.decWriteStamp(a20addr);
#endif

#if BX_SUPPORT_APIC
    bx_generic_apic_c *local_apic = &cpu->local_apic;
    bx_generic_apic_c *ioapic = bx_devices.ioapic;
    if (local_apic->is_selected (a20addr, len)) {
      local_apic->write (a20addr, (Bit32u *)data, len);
      return;
    }
    if (ioapic->is_selected (a20addr, len)) {
      ioapic->write (a20addr, (Bit32u *)data, len);
      return;
    }
#endif

  if ( (a20addr + len) <= BX_MEM_THIS len ) {
    // all of data is within limits of physical memory
    if ( (a20addr & 0xfff80000) != 0x00080000 ) {
      if (len == 4) {
        WriteHostDWordToLittleEndian(&vector[a20addr], *(Bit32u*)data);
        BX_DBG_DIRTY_PAGE(a20addr >> 12);
        return;
      }
      if (len == 2) {
        WriteHostWordToLittleEndian(&vector[a20addr], *(Bit16u*)data);
        BX_DBG_DIRTY_PAGE(a20addr >> 12);
        return;
      }
      if (len == 1) {
        * ((Bit8u *) (&vector[a20addr])) = * (Bit8u *) data;
        BX_DBG_DIRTY_PAGE(a20addr >> 12);
        return;
      }
      // len == other, just fall thru to special cases handling
      }

#ifdef BX_LITTLE_ENDIAN
  data_ptr = (Bit8u *) data;
#else // BX_BIG_ENDIAN
  data_ptr = (Bit8u *) data + (len - 1);
#endif

write_one:
    if ( (a20addr & 0xfff80000) != 0x00080000 ) {
      // addr *not* in range 00080000 .. 000FFFFF
      vector[a20addr] = *data_ptr;
      BX_DBG_DIRTY_PAGE(a20addr >> 12);
inc_one:
      if (len == 1) return;
      len--;
      a20addr++;
#ifdef BX_LITTLE_ENDIAN
      data_ptr++;
#else // BX_BIG_ENDIAN
      data_ptr--;
#endif
      goto write_one;
    }

    // addr in range 00080000 .. 000FFFFF

    if (a20addr <= 0x0009ffff) {
      // regular memory 80000 .. 9FFFF
      vector[a20addr] = *data_ptr;
      BX_DBG_DIRTY_PAGE(a20addr >> 12);
      goto inc_one;
    }
    // adapter ROM     C0000 .. DFFFF
    // ROM BIOS memory E0000 .. FFFFF
#if BX_SUPPORT_PCI == 0
    // ignore write to ROM
#else
    // Write Based on 440fx Programming
    if ( bx_options.Oi440FXSupport->get () &&
          ((a20addr & 0xfffc0000) == 0x000c0000) )
    {
      switch (DEV_pci_wr_memtype(a20addr & 0xFC000)) {
        case 0x1:   // Writes to ShadowRAM
          BX_DEBUG(("Writing to ShadowRAM: address %08x, data %02x", (unsigned) a20addr, *data_ptr));
          vector[a20addr] = *data_ptr;
          BX_DBG_DIRTY_PAGE(a20addr >> 12);
          goto inc_one;

        case 0x0:   // Writes to ROM, Inhibit
          BX_DEBUG(("Write to ROM ignored: address %08x, data %02x", (unsigned) a20addr, *data_ptr));
          goto inc_one;

        default:
          BX_PANIC(("writePhysicalPage: default case"));
          goto inc_one;
        }
      }
#endif
    goto inc_one;
  }
  else {
    // some or all of data is outside limits of physical memory

#ifdef BX_LITTLE_ENDIAN
    data_ptr = (Bit8u *) data;
#else // BX_BIG_ENDIAN
    data_ptr = (Bit8u *) data + (len - 1);
#endif

    for (unsigned i = 0; i < len; i++) {
      if (a20addr < BX_MEM_THIS len) {
        vector[a20addr] = *data_ptr;
        BX_DBG_DIRTY_PAGE(a20addr >> 12);
      }
      // otherwise ignore byte, since it overruns memory
      addr++;
      a20addr = (addr);
#ifdef BX_LITTLE_ENDIAN
      data_ptr++;
#else // BX_BIG_ENDIAN
      data_ptr--;
#endif
    }
    return;
  }
}

  void BX_CPP_AttrRegparmN(3)
BX_MEM_C::readPhysicalPage(BX_CPU_C *cpu, Bit32u addr, unsigned len, void *data)
{
  Bit8u *data_ptr;
  Bit32u a20addr;

#if BX_SUPPORT_IODEBUG
  bx_iodebug_c::mem_read(cpu, addr, len, data);
#endif

  a20addr = A20ADDR(addr);
  struct memory_handler_struct *memory_handler = memory_handlers[a20addr >> 20];
  while (memory_handler) {
	  if (memory_handler->begin <= a20addr &&
		memory_handler->end >= a20addr &&
	  	memory_handler->read_handler(a20addr, len, data, memory_handler->read_param))
		  return;
	  memory_handler = memory_handler->next;
  }

  BX_INSTR_PHY_READ(cpu->which_cpu(), a20addr, len);

#if BX_DEBUGGER
  // (mch) Check for physical read break points, TODO
  // (bbd) Each breakpoint should have an associated CPU#, TODO
  for (int i = 0; i < num_read_watchpoints; i++)
        if (read_watchpoint[i] == a20addr) {
	      BX_CPU(0)->watchpoint = a20addr;
              BX_CPU(0)->break_point = BREAK_POINT_READ;
              break;
        }
#endif

#if BX_SUPPORT_APIC
  bx_generic_apic_c *local_apic = &cpu->local_apic;
  bx_generic_apic_c *ioapic = bx_devices.ioapic;
    if (local_apic->is_selected (addr, len)) {
      local_apic->read (addr, data, len);
      return;
    }
    if (ioapic->is_selected (addr, len)) {
      ioapic->read (addr, data, len);
      return;
    }
#endif

  if ( (a20addr + len) <= BX_MEM_THIS len ) {
    // all of data is within limits of physical memory
    if ( (a20addr & 0xfff80000) != 0x00080000 ) {
      if (len == 4) {
        ReadHostDWordFromLittleEndian(&vector[a20addr], * (Bit32u*) data);
        return;
      }
      if (len == 2) {
        ReadHostWordFromLittleEndian(&vector[a20addr], * (Bit16u*) data);
        return;
      }
      if (len == 1) {
        * (Bit8u *) data =  * ((Bit8u *) (&vector[a20addr]));
        return;
      }
      // len == 3 case can just fall thru to special cases handling
    }

#ifdef BX_LITTLE_ENDIAN
    data_ptr = (Bit8u *) data;
#else // BX_BIG_ENDIAN
    data_ptr = (Bit8u *) data + (len - 1);
#endif

read_one:
    if ( (a20addr & 0xfff80000) != 0x00080000 ) {
      // addr *not* in range 00080000 .. 000FFFFF
      *data_ptr = vector[a20addr];
inc_one:
      if (len == 1) return;
      len--;
      a20addr++;
#ifdef BX_LITTLE_ENDIAN
      data_ptr++;
#else // BX_BIG_ENDIAN
      data_ptr--;
#endif
      goto read_one;
    }

    // addr in range 00080000 .. 000FFFFF
#if BX_SUPPORT_PCI
    if ( bx_options.Oi440FXSupport->get () &&
          ((a20addr & 0xfffc0000) == 0x000c0000) )
    {
      switch (DEV_pci_rd_memtype (a20addr)) {
        case 0x0:  // Read from ROM
          *data_ptr = rom[a20addr - 0xc0000];
          goto inc_one;
        case 0x1:  // Read from ShadowRAM
          *data_ptr = vector[a20addr];
          goto inc_one;
        default:
          BX_PANIC(("readPhysicalPage: default case"));
      }
      goto inc_one;
    }
    else
#endif  // #if BX_SUPPORT_PCI
    {
      if ( (a20addr & 0xfffc0000) == 0x000c0000 ) {
        *data_ptr = rom[a20addr - 0xc0000];
      }
      else
      {
        *data_ptr = vector[a20addr];
      }
      goto inc_one;
    }
  }
  else
  {  // some or all of data is outside limits of physical memory

#ifdef BX_LITTLE_ENDIAN
    data_ptr = (Bit8u *) data;
#else // BX_BIG_ENDIAN
    data_ptr = (Bit8u *) data + (len - 1);
#endif

    for (unsigned i = 0; i < len; i++) {
      if (a20addr < BX_MEM_THIS len)
        *data_ptr = vector[a20addr];
      else if (a20addr >= 0xfffe0000)
        *data_ptr = rom[a20addr & 0x3ffff];
      else
        *data_ptr = 0xff;
      addr++;
      a20addr = (addr);
#ifdef BX_LITTLE_ENDIAN
      data_ptr++;
#else // BX_BIG_ENDIAN
      data_ptr--;
#endif
    }
    return;
  }
}

#endif // #if BX_PROVIDE_CPU_MEMORY
<commit_msg>- make debugger watchpoints in device memory work again (SF patch #1309763 by   Nickolai Zeldovich)<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id: memory.cc,v 1.41 2005/10/01 09:52:35 vruppert Exp $
/////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2001  MandrakeSoft S.A.
//
//    MandrakeSoft S.A.
//    43, rue d'Aboukir
//    75002 Paris - France
//    http://www.linux-mandrake.com/
//    http://www.mandrakesoft.com/
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

#include "iodev/iodev.h"
#define LOG_THIS BX_MEM_THIS

#if BX_PROVIDE_CPU_MEMORY

  void BX_CPP_AttrRegparmN(3)
BX_MEM_C::writePhysicalPage(BX_CPU_C *cpu, Bit32u addr, unsigned len, void *data)
{
  Bit8u *data_ptr;
  Bit32u a20addr;

  // Note: accesses should always be contained within a single page now.

#if BX_SUPPORT_IODEBUG
  bx_iodebug_c::mem_write(cpu, addr, len, data);
#endif

  a20addr = A20ADDR(addr);
  BX_INSTR_PHY_WRITE(cpu->which_cpu(), a20addr, len);

#if BX_DEBUGGER
  // (mch) Check for physical write break points, TODO
  // (bbd) Each breakpoint should have an associated CPU#, TODO
  for (int i = 0; i < num_write_watchpoints; i++)
        if (write_watchpoint[i] == a20addr) {
	      BX_CPU(0)->watchpoint = a20addr;
              BX_CPU(0)->break_point = BREAK_POINT_WRITE;
              break;
        }
#endif

  struct memory_handler_struct *memory_handler = memory_handlers[a20addr >> 20];
  while (memory_handler) {
	  if (memory_handler->begin <= a20addr &&
		memory_handler->end >= a20addr &&
	  	memory_handler->write_handler(a20addr, len, data, memory_handler->write_param))
		  return;
	  memory_handler = memory_handler->next;
  }

#if BX_SUPPORT_ICACHE
  if (a20addr < BX_MEM_THIS len)
    pageWriteStampTable.decWriteStamp(a20addr);
#endif

#if BX_SUPPORT_APIC
    bx_generic_apic_c *local_apic = &cpu->local_apic;
    bx_generic_apic_c *ioapic = bx_devices.ioapic;
    if (local_apic->is_selected (a20addr, len)) {
      local_apic->write (a20addr, (Bit32u *)data, len);
      return;
    }
    if (ioapic->is_selected (a20addr, len)) {
      ioapic->write (a20addr, (Bit32u *)data, len);
      return;
    }
#endif

  if ( (a20addr + len) <= BX_MEM_THIS len ) {
    // all of data is within limits of physical memory
    if ( (a20addr & 0xfff80000) != 0x00080000 ) {
      if (len == 4) {
        WriteHostDWordToLittleEndian(&vector[a20addr], *(Bit32u*)data);
        BX_DBG_DIRTY_PAGE(a20addr >> 12);
        return;
      }
      if (len == 2) {
        WriteHostWordToLittleEndian(&vector[a20addr], *(Bit16u*)data);
        BX_DBG_DIRTY_PAGE(a20addr >> 12);
        return;
      }
      if (len == 1) {
        * ((Bit8u *) (&vector[a20addr])) = * (Bit8u *) data;
        BX_DBG_DIRTY_PAGE(a20addr >> 12);
        return;
      }
      // len == other, just fall thru to special cases handling
      }

#ifdef BX_LITTLE_ENDIAN
  data_ptr = (Bit8u *) data;
#else // BX_BIG_ENDIAN
  data_ptr = (Bit8u *) data + (len - 1);
#endif

write_one:
    if ( (a20addr & 0xfff80000) != 0x00080000 ) {
      // addr *not* in range 00080000 .. 000FFFFF
      vector[a20addr] = *data_ptr;
      BX_DBG_DIRTY_PAGE(a20addr >> 12);
inc_one:
      if (len == 1) return;
      len--;
      a20addr++;
#ifdef BX_LITTLE_ENDIAN
      data_ptr++;
#else // BX_BIG_ENDIAN
      data_ptr--;
#endif
      goto write_one;
    }

    // addr in range 00080000 .. 000FFFFF

    if (a20addr <= 0x0009ffff) {
      // regular memory 80000 .. 9FFFF
      vector[a20addr] = *data_ptr;
      BX_DBG_DIRTY_PAGE(a20addr >> 12);
      goto inc_one;
    }
    // adapter ROM     C0000 .. DFFFF
    // ROM BIOS memory E0000 .. FFFFF
#if BX_SUPPORT_PCI == 0
    // ignore write to ROM
#else
    // Write Based on 440fx Programming
    if ( bx_options.Oi440FXSupport->get () &&
          ((a20addr & 0xfffc0000) == 0x000c0000) )
    {
      switch (DEV_pci_wr_memtype(a20addr & 0xFC000)) {
        case 0x1:   // Writes to ShadowRAM
          BX_DEBUG(("Writing to ShadowRAM: address %08x, data %02x", (unsigned) a20addr, *data_ptr));
          vector[a20addr] = *data_ptr;
          BX_DBG_DIRTY_PAGE(a20addr >> 12);
          goto inc_one;

        case 0x0:   // Writes to ROM, Inhibit
          BX_DEBUG(("Write to ROM ignored: address %08x, data %02x", (unsigned) a20addr, *data_ptr));
          goto inc_one;

        default:
          BX_PANIC(("writePhysicalPage: default case"));
          goto inc_one;
        }
      }
#endif
    goto inc_one;
  }
  else {
    // some or all of data is outside limits of physical memory

#ifdef BX_LITTLE_ENDIAN
    data_ptr = (Bit8u *) data;
#else // BX_BIG_ENDIAN
    data_ptr = (Bit8u *) data + (len - 1);
#endif

    for (unsigned i = 0; i < len; i++) {
      if (a20addr < BX_MEM_THIS len) {
        vector[a20addr] = *data_ptr;
        BX_DBG_DIRTY_PAGE(a20addr >> 12);
      }
      // otherwise ignore byte, since it overruns memory
      addr++;
      a20addr = (addr);
#ifdef BX_LITTLE_ENDIAN
      data_ptr++;
#else // BX_BIG_ENDIAN
      data_ptr--;
#endif
    }
    return;
  }
}

  void BX_CPP_AttrRegparmN(3)
BX_MEM_C::readPhysicalPage(BX_CPU_C *cpu, Bit32u addr, unsigned len, void *data)
{
  Bit8u *data_ptr;
  Bit32u a20addr;

#if BX_SUPPORT_IODEBUG
  bx_iodebug_c::mem_read(cpu, addr, len, data);
#endif

  a20addr = A20ADDR(addr);
  BX_INSTR_PHY_READ(cpu->which_cpu(), a20addr, len);

#if BX_DEBUGGER
  // (mch) Check for physical read break points, TODO
  // (bbd) Each breakpoint should have an associated CPU#, TODO
  for (int i = 0; i < num_read_watchpoints; i++)
        if (read_watchpoint[i] == a20addr) {
	      BX_CPU(0)->watchpoint = a20addr;
              BX_CPU(0)->break_point = BREAK_POINT_READ;
              break;
        }
#endif

  struct memory_handler_struct *memory_handler = memory_handlers[a20addr >> 20];
  while (memory_handler) {
	  if (memory_handler->begin <= a20addr &&
		memory_handler->end >= a20addr &&
	  	memory_handler->read_handler(a20addr, len, data, memory_handler->read_param))
		  return;
	  memory_handler = memory_handler->next;
  }

#if BX_SUPPORT_APIC
  bx_generic_apic_c *local_apic = &cpu->local_apic;
  bx_generic_apic_c *ioapic = bx_devices.ioapic;
    if (local_apic->is_selected (addr, len)) {
      local_apic->read (addr, data, len);
      return;
    }
    if (ioapic->is_selected (addr, len)) {
      ioapic->read (addr, data, len);
      return;
    }
#endif

  if ( (a20addr + len) <= BX_MEM_THIS len ) {
    // all of data is within limits of physical memory
    if ( (a20addr & 0xfff80000) != 0x00080000 ) {
      if (len == 4) {
        ReadHostDWordFromLittleEndian(&vector[a20addr], * (Bit32u*) data);
        return;
      }
      if (len == 2) {
        ReadHostWordFromLittleEndian(&vector[a20addr], * (Bit16u*) data);
        return;
      }
      if (len == 1) {
        * (Bit8u *) data =  * ((Bit8u *) (&vector[a20addr]));
        return;
      }
      // len == 3 case can just fall thru to special cases handling
    }

#ifdef BX_LITTLE_ENDIAN
    data_ptr = (Bit8u *) data;
#else // BX_BIG_ENDIAN
    data_ptr = (Bit8u *) data + (len - 1);
#endif

read_one:
    if ( (a20addr & 0xfff80000) != 0x00080000 ) {
      // addr *not* in range 00080000 .. 000FFFFF
      *data_ptr = vector[a20addr];
inc_one:
      if (len == 1) return;
      len--;
      a20addr++;
#ifdef BX_LITTLE_ENDIAN
      data_ptr++;
#else // BX_BIG_ENDIAN
      data_ptr--;
#endif
      goto read_one;
    }

    // addr in range 00080000 .. 000FFFFF
#if BX_SUPPORT_PCI
    if ( bx_options.Oi440FXSupport->get () &&
          ((a20addr & 0xfffc0000) == 0x000c0000) )
    {
      switch (DEV_pci_rd_memtype (a20addr)) {
        case 0x0:  // Read from ROM
          *data_ptr = rom[a20addr - 0xc0000];
          goto inc_one;
        case 0x1:  // Read from ShadowRAM
          *data_ptr = vector[a20addr];
          goto inc_one;
        default:
          BX_PANIC(("readPhysicalPage: default case"));
      }
      goto inc_one;
    }
    else
#endif  // #if BX_SUPPORT_PCI
    {
      if ( (a20addr & 0xfffc0000) == 0x000c0000 ) {
        *data_ptr = rom[a20addr - 0xc0000];
      }
      else
      {
        *data_ptr = vector[a20addr];
      }
      goto inc_one;
    }
  }
  else
  {  // some or all of data is outside limits of physical memory

#ifdef BX_LITTLE_ENDIAN
    data_ptr = (Bit8u *) data;
#else // BX_BIG_ENDIAN
    data_ptr = (Bit8u *) data + (len - 1);
#endif

    for (unsigned i = 0; i < len; i++) {
      if (a20addr < BX_MEM_THIS len)
        *data_ptr = vector[a20addr];
      else if (a20addr >= 0xfffe0000)
        *data_ptr = rom[a20addr & 0x3ffff];
      else
        *data_ptr = 0xff;
      addr++;
      a20addr = (addr);
#ifdef BX_LITTLE_ENDIAN
      data_ptr++;
#else // BX_BIG_ENDIAN
      data_ptr--;
#endif
    }
    return;
  }
}

#endif // #if BX_PROVIDE_CPU_MEMORY
<|endoftext|>