<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 <cstdio>
#include <iostream>
#include <fstream>
#include "gflags/gflags.h"

#include "modules/common/configs/config_gflags.h"
#include "modules/common/log.h"
#include "modules/map/hdmap/hdmap_common.h"
#include "modules/map/hdmap/hdmap_impl.h"
#include "modules/map/proto/map_geometry.pb.h"

DEFINE_bool(xy_to_sl, false, "calculate xy to sl");
DEFINE_bool(sl_to_xy, false, "calculate sl to xy");
DEFINE_bool(xy_to_lane, false, "calculate xy to lane");
DEFINE_bool(lane_to_lane, false, "calculate lane to lane");
DEFINE_bool(lane_width, false, "calculate lane width");
DEFINE_string(print_map, "", "print the map");
DEFINE_string(print_map_bin, "", "print the map binary");
DEFINE_string(overlap, "", "get overlap information");
DEFINE_string(lane_info, "", "print lane info");
DEFINE_string(signal_info, "", "print signal info");
DEFINE_double(x, 0.0, "x");
DEFINE_double(y, 0.0, "y");
DEFINE_string(lane, "", "lane_id");
DEFINE_string(from_lane, "", "from_lane");
DEFINE_string(to_lane, "", "to_lane");
DEFINE_double(s, 0.0, "s");
DEFINE_double(l, 0.0, "l");

namespace apollo {
namespace tools {

class MapUtil {
 public:
  explicit MapUtil(const std::string &map_filename) : _map_client(nullptr) {
    _map_client.reset(new apollo::hdmap::HDMapImpl());
    _map_client->load_map_from_file(map_filename);
  }

  static ::apollo::hdmap::Id create_id(const std::string &id) {
    ::apollo::hdmap::Id hdmap_id;
    hdmap_id.set_id(id);
    return hdmap_id;
  }

  const ::apollo::hdmap::OverlapInfo *get_overlap(
      const std::string &overlap_id) {
    ::apollo::hdmap::Id id;
    id.set_id(overlap_id);
    auto ret = _map_client->get_overlap_by_id(id);
    if (ret == nullptr) {
      fprintf(stderr, "failed to find overlap[%s]\n", overlap_id.c_str());
    }
    return ret.get();
  }

  const ::apollo::hdmap::SignalInfo *get_signal(const std::string &signal_id) {
    ::apollo::hdmap::Id id;
    id.set_id(signal_id);
    auto ret = _map_client->get_signal_by_id(id);
    if (ret == nullptr) {
      fprintf(stderr, "failed to find overlap[%s]\n", signal_id.c_str());
    }
    return ret.get();
  }

  const ::apollo::hdmap::LaneInfo *get_lane(const std::string &lane_id) {
    ::apollo::hdmap::Id id;
    id.set_id(lane_id);
    auto ret = _map_client->get_lane_by_id(id);
    if (ret == nullptr) {
      fprintf(stderr, "failed to find lane[%s]\n", lane_id.c_str());
    }
    return ret.get();
  }

  int point_to_sl(const ::apollo::common::PointENU &point,
                  std::string *lane_id, double *s, double *l) {
    QUIT_IF(lane_id == nullptr, -1, ERROR, "arg lane id is null");
    QUIT_IF(s == nullptr, -2, ERROR, "arg s is null");
    QUIT_IF(l == nullptr, -3, ERROR, "arg l is null");
    ::apollo::hdmap::LaneInfoConstPtr lane = nullptr;
    int ret = _map_client->get_nearest_lane(point, &lane, s, l);
    QUIT_IF(ret != 0, -4, ERROR, "get_nearest_lane failed with ret[%d]", ret);
    QUIT_IF(lane == nullptr, -5, ERROR, "lane is null");
    *lane_id = lane->id().id();
    return 0;
  }

  int sl_to_point(const std::string &lane_id, const double s,
                  const double l, ::apollo::common::PointENU *point,
                  double *heading) {
    QUIT_IF(point == nullptr, -1, ERROR, "arg point is null");
    QUIT_IF(heading == nullptr, -2, ERROR, "arg heading is null");
    ::apollo::hdmap::Id id;
    id.set_id(lane_id);
    const ::apollo::hdmap::LaneInfo* lane_info_ptr
        = _map_client->get_lane_by_id(id).get();
    QUIT_IF(lane_info_ptr == nullptr, -3,
            ERROR, "get_smooth_point_from_lane[%s] failed",
            lane_id.c_str());
    *point = lane_info_ptr->get_smooth_point(s);
    return 0;
  }

  int lane_projection(const ::apollo::common::math::Vec2d &vec2d,
                      const std::string &lane_id,
                      double *s, double *l) {
    QUIT_IF(s == nullptr, -1, ERROR, "arg s is nullptr");
    const ::apollo::hdmap::LaneInfo *lane =
        _map_client->get_lane_by_id(create_id(lane_id)).get();
    QUIT_IF(lane == nullptr, -2, ERROR, "get_lane_by_id[%s] failed",
            lane_id.c_str());
    bool ret = lane->get_projection(vec2d, s, l);
    QUIT_IF(!ret, -3, ERROR,
            "lane[%s] get projection for point[%f, %f] failed",
            lane_id.c_str(),
            vec2d.x(), vec2d.y());
    return 0;
  }
  const ::apollo::hdmap::HDMapImpl *get_map_client() const {
    return _map_client.get();
  }

 private:
  std::unique_ptr<apollo::hdmap::HDMapImpl> _map_client;
};

}  // namespace tools
}  // namespace apollo

std::ostream &operator<<(
    std::ostream &os,
    const ::google::protobuf::RepeatedPtrField<::apollo::hdmap::Id> &ids) {
  for (int i = 0; i < ids.size(); ++i) {
    os << ids.Get(i).id();
    if (i != ids.size() - 1) {
      os << ", ";
    }
  }
  return os;
}

int main(int argc, char *argv[]) {
  google::ParseCommandLineFlags(&argc, &argv, true);
  std::string map_file = FLAGS_map_file_path;
  ::apollo::tools::MapUtil map_util(FLAGS_map_file_path);

  if (FLAGS_xy_to_sl) {
    double x = FLAGS_x;
    double y = FLAGS_y;
    ::apollo::common::PointENU point;
    point.set_x(x);
    point.set_y(y);
    point.set_z(0);
    std::string lane_id;
    double s = 0.0;
    double l = 0.0;
    map_util.point_to_sl(point, &lane_id, &s, &l);
    double heading = 0.0;
    map_util.sl_to_point(lane_id, s, l, &point, &heading);
    printf("lane_id[%s], s[%f], l[%f], heading[%f]\n",
           lane_id.c_str(), s, l, heading);
  }
  if (FLAGS_sl_to_xy) {
    ::apollo::common::PointENU point;
    double heading = 0.0;
    map_util.sl_to_point(FLAGS_lane, FLAGS_s, FLAGS_l, &point, &heading);
    printf("x[%f] y[%f], heading[%f]\n", point.x(), point.y(), heading);
  }
  if (FLAGS_xy_to_lane) {
    ::apollo::common::math::Vec2d vec2d(FLAGS_x, FLAGS_y);
    double s = 0.0;
    double l = 0.0;
    int ret = map_util.lane_projection(vec2d, FLAGS_lane, &s, &l);
    if (ret != 0) {
      printf("lane_projection for x[%f], y[%f], lane_id[%s] failed\n",
             FLAGS_x, FLAGS_y, FLAGS_lane.c_str());
      return -1;
    }
    printf("lane[%s] s[%f], l[%f]\n", FLAGS_lane.c_str(), s, l);
  }
  if (FLAGS_lane_to_lane) {
    ::apollo::common::PointENU point;
    double heading = 0.0;
    map_util.sl_to_point(FLAGS_from_lane, FLAGS_s, 0.0, &point, &heading);
    double target_s = 0.0;
    double target_l = 0.0;
    ::apollo::common::math::Vec2d vec2d(point.x(), point.y());
    int ret = map_util.lane_projection(vec2d, FLAGS_to_lane,
                                       &target_s, &target_l);
    if (ret != 0) {
      printf("lane_projection for lane[%s], s[%f] to lane_id[%s] failed\n",
             FLAGS_from_lane.c_str(), FLAGS_s, FLAGS_to_lane.c_str());
      return -1;
    }
    printf("lane[%s] s[%f], l[%f]\n", FLAGS_to_lane.c_str(),
           target_s, target_l);
  }
  if (FLAGS_lane_width) {
    auto lane_ptr = map_util.get_lane(FLAGS_lane);
    double left_width = 0.0;
    double right_width = 0.0;
    lane_ptr->get_width(FLAGS_s, &left_width, &right_width);
    printf("lane[%s] s[%f]: left_width[%f], right_width[%f], total_width[%f]\n",
           FLAGS_lane.c_str(), FLAGS_s, left_width, right_width,
           left_width + right_width);
  }
  if (!FLAGS_lane_info.empty()) {
    const auto *lane_ptr = map_util.get_lane(FLAGS_lane_info);
    const auto &lane = lane_ptr->lane();

    ::apollo::common::PointENU start_point;
    double start_heading = 0.0;
    map_util.sl_to_point(FLAGS_lane_info, 0, 0, &start_point, &start_heading);

    ::apollo::common::PointENU end_point;
    double end_heading = 0.0;
    map_util.sl_to_point(FLAGS_lane_info, lane_ptr->total_length(), 0,
                         &end_point, &end_heading);

    std::cout << "lane[" << FLAGS_lane_info
              << "] length[" << lane_ptr->total_length()
              << "] type[" << Lane_LaneType_Name(lane.type())
              << "] turn[" << Lane_LaneTurn_Name(lane.turn())
              // << "] left_boundary["
              // << LaneBoundary_Type_Name(lane.left_boundary().type())
              // << "] right_boundary["
              // << LaneBoundary_Type_Name(lane.right_boundary().type())
              << "] speed_limit[" << lane.speed_limit()
              << "] predecessor[" << lane.predecessor_id()
              << "] successor[" << lane.successor_id()
              << "] left_forward[" << lane.left_neighbor_forward_lane_id()
              << "] right_forward[" << lane.right_neighbor_forward_lane_id()
              << "] left_reverse[" << lane.left_neighbor_reverse_lane_id()
              << "] right_reverse[" << lane.right_neighbor_reverse_lane_id()
              << "] overlap[" << lane.overlap_id()
              // << "] crosswalk[" << lane.crosswalk_id()
              // << "] yield_sign[" << lane.yield_sign_id()
               << "] stop_sign num:[" << lane_ptr->stop_signs().size()
              << "]"
              << " start point(x,y,heading):" << start_point.x() << ","
              << start_point.y() << "," << start_heading
              << " end point(x,y,heading):" << end_point.x() << ","
              << end_point.y() << "," << end_heading
              << std::endl;
  }
  if (!FLAGS_overlap.empty()) {
    const auto *overlap_ptr = map_util.get_overlap(FLAGS_overlap);
    if (overlap_ptr != nullptr) {
      std::cout << "overlap[" << overlap_ptr->id().id()
                << "] info[" << overlap_ptr->overlap().DebugString()
                << "]" << std::endl;
    }
  }
  if (!FLAGS_signal_info.empty()) {
    const auto *signal_ptr = map_util.get_signal(FLAGS_signal_info);
    if (signal_ptr) {
      std::cout << "signal[" << FLAGS_signal_info << "] info["
                << signal_ptr->signal().DebugString() << "]" << std::endl;
    }
  }
  if (!FLAGS_print_map.empty()) {
    //const auto *map_client = map_util.get_map_client();
    std::ofstream ofs(FLAGS_print_map);
    // TODO(yifei) map api is not available
    //ofs << map_client->_map.DebugString();
    ofs.close();
  }
  if (!FLAGS_print_map_bin.empty()) {
    // const auto *map_client = map_util.get_map_client();
    std::ofstream ofs(FLAGS_print_map_bin);
    std::string map_str;
    // TODO(yifei) map api is not available
    // map_client->_map.SerializeToString(&map_str);
    // ofs << map_str;
    ofs.close();
  }
  if (!FLAGS_sl_to_xy
      && !FLAGS_xy_to_sl
      && !FLAGS_xy_to_lane
      && !FLAGS_lane_to_lane
      && !FLAGS_lane_width
      && FLAGS_print_map.empty()
      && FLAGS_print_map_bin.empty()
      && FLAGS_lane_info.empty()
      && FLAGS_signal_info.empty()
      && FLAGS_overlap.empty()) {
    std::cout << "usage: --map_file" << std::endl;
    std::cout << "usage: --print_map" << std::endl;
    std::cout << "usage: --print_map_bin" << std::endl;
    std::cout << "usage: --xy_to_sl --x --y" << std::endl;
    std::cout << "usage: --sl_to_xy --lane --s --l" << std::endl;
    std::cout << "usage: --xy_to_lane --x --y --lane" << std::endl;
    std::cout << "usage: --lane_to_lane --from_lane --s --to_lane" << std::endl;
    std::cout << "usage: --lane_width --lane --s" << std::endl;
    std::cout << "usage: --lane_info" << std::endl;
    std::cout << "usage: --signal_info" << std::endl;
    std::cout << "usage: --overlap" << std::endl;
  }
  return 0;
}
<commit_msg>map: add dump text map in map_xysl tool.<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 <cstdio>
#include <iostream>
#include <fstream>
#include "gflags/gflags.h"

#include "modules/common/configs/config_gflags.h"
#include "modules/common/log.h"
#include "modules/common/util/file.h"
#include "modules/map/hdmap/hdmap_common.h"
#include "modules/map/hdmap/hdmap_impl.h"
#include "modules/map/proto/map_geometry.pb.h"

DEFINE_bool(xy_to_sl, false, "calculate xy to sl");
DEFINE_bool(sl_to_xy, false, "calculate sl to xy");
DEFINE_bool(xy_to_lane, false, "calculate xy to lane");
DEFINE_bool(lane_to_lane, false, "calculate lane to lane");
DEFINE_bool(lane_width, false, "calculate lane width");
DEFINE_string(dump_txt_map, "", "text file name for dumping map");
DEFINE_string(dump_bin_map, "", "binary file name for dumping map");
DEFINE_string(overlap, "", "get overlap information");
DEFINE_string(lane_info, "", "print lane info");
DEFINE_string(signal_info, "", "print signal info");
DEFINE_double(x, 0.0, "x");
DEFINE_double(y, 0.0, "y");
DEFINE_string(lane, "", "lane_id");
DEFINE_string(from_lane, "", "from_lane");
DEFINE_string(to_lane, "", "to_lane");
DEFINE_double(s, 0.0, "s");
DEFINE_double(l, 0.0, "l");

namespace apollo {
namespace tools {

class MapUtil {
 public:
  explicit MapUtil(const std::string &map_filename) : _map_client(nullptr) {
    _map_client.reset(new apollo::hdmap::HDMapImpl());
    _map_client->load_map_from_file(map_filename);
  }

  static ::apollo::hdmap::Id create_id(const std::string &id) {
    ::apollo::hdmap::Id hdmap_id;
    hdmap_id.set_id(id);
    return hdmap_id;
  }

  const ::apollo::hdmap::OverlapInfo *get_overlap(
      const std::string &overlap_id) {
    ::apollo::hdmap::Id id;
    id.set_id(overlap_id);
    auto ret = _map_client->get_overlap_by_id(id);
    if (ret == nullptr) {
      fprintf(stderr, "failed to find overlap[%s]\n", overlap_id.c_str());
    }
    return ret.get();
  }

  const ::apollo::hdmap::SignalInfo *get_signal(const std::string &signal_id) {
    ::apollo::hdmap::Id id;
    id.set_id(signal_id);
    auto ret = _map_client->get_signal_by_id(id);
    if (ret == nullptr) {
      fprintf(stderr, "failed to find overlap[%s]\n", signal_id.c_str());
    }
    return ret.get();
  }

  const ::apollo::hdmap::LaneInfo *get_lane(const std::string &lane_id) {
    ::apollo::hdmap::Id id;
    id.set_id(lane_id);
    auto ret = _map_client->get_lane_by_id(id);
    if (ret == nullptr) {
      fprintf(stderr, "failed to find lane[%s]\n", lane_id.c_str());
    }
    return ret.get();
  }

  int point_to_sl(const ::apollo::common::PointENU &point,
                  std::string *lane_id, double *s, double *l) {
    QUIT_IF(lane_id == nullptr, -1, ERROR, "arg lane id is null");
    QUIT_IF(s == nullptr, -2, ERROR, "arg s is null");
    QUIT_IF(l == nullptr, -3, ERROR, "arg l is null");
    ::apollo::hdmap::LaneInfoConstPtr lane = nullptr;
    int ret = _map_client->get_nearest_lane(point, &lane, s, l);
    QUIT_IF(ret != 0, -4, ERROR, "get_nearest_lane failed with ret[%d]", ret);
    QUIT_IF(lane == nullptr, -5, ERROR, "lane is null");
    *lane_id = lane->id().id();
    return 0;
  }

  int sl_to_point(const std::string &lane_id, const double s,
                  const double l, ::apollo::common::PointENU *point,
                  double *heading) {
    QUIT_IF(point == nullptr, -1, ERROR, "arg point is null");
    QUIT_IF(heading == nullptr, -2, ERROR, "arg heading is null");
    ::apollo::hdmap::Id id;
    id.set_id(lane_id);
    const ::apollo::hdmap::LaneInfo* lane_info_ptr
        = _map_client->get_lane_by_id(id).get();
    QUIT_IF(lane_info_ptr == nullptr, -3,
            ERROR, "get_smooth_point_from_lane[%s] failed",
            lane_id.c_str());
    *point = lane_info_ptr->get_smooth_point(s);
    return 0;
  }

  int lane_projection(const ::apollo::common::math::Vec2d &vec2d,
                      const std::string &lane_id,
                      double *s, double *l) {
    QUIT_IF(s == nullptr, -1, ERROR, "arg s is nullptr");
    const ::apollo::hdmap::LaneInfo *lane =
        _map_client->get_lane_by_id(create_id(lane_id)).get();
    QUIT_IF(lane == nullptr, -2, ERROR, "get_lane_by_id[%s] failed",
            lane_id.c_str());
    bool ret = lane->get_projection(vec2d, s, l);
    QUIT_IF(!ret, -3, ERROR,
            "lane[%s] get projection for point[%f, %f] failed",
            lane_id.c_str(),
            vec2d.x(), vec2d.y());
    return 0;
  }
  const ::apollo::hdmap::HDMapImpl *get_map_client() const {
    return _map_client.get();
  }

 private:
  std::unique_ptr<apollo::hdmap::HDMapImpl> _map_client;
};

}  // namespace tools
}  // namespace apollo

std::ostream &operator<<(
    std::ostream &os,
    const ::google::protobuf::RepeatedPtrField<::apollo::hdmap::Id> &ids) {
  for (int i = 0; i < ids.size(); ++i) {
    os << ids.Get(i).id();
    if (i != ids.size() - 1) {
      os << ", ";
    }
  }
  return os;
}

int main(int argc, char *argv[]) {
  google::ParseCommandLineFlags(&argc, &argv, true);
  std::string map_file = FLAGS_map_file_path;
  ::apollo::tools::MapUtil map_util(FLAGS_map_file_path);

  if (FLAGS_xy_to_sl) {
    double x = FLAGS_x;
    double y = FLAGS_y;
    ::apollo::common::PointENU point;
    point.set_x(x);
    point.set_y(y);
    point.set_z(0);
    std::string lane_id;
    double s = 0.0;
    double l = 0.0;
    map_util.point_to_sl(point, &lane_id, &s, &l);
    double heading = 0.0;
    map_util.sl_to_point(lane_id, s, l, &point, &heading);
    printf("lane_id[%s], s[%f], l[%f], heading[%f]\n",
           lane_id.c_str(), s, l, heading);
  }
  if (FLAGS_sl_to_xy) {
    ::apollo::common::PointENU point;
    double heading = 0.0;
    map_util.sl_to_point(FLAGS_lane, FLAGS_s, FLAGS_l, &point, &heading);
    printf("x[%f] y[%f], heading[%f]\n", point.x(), point.y(), heading);
  }
  if (FLAGS_xy_to_lane) {
    ::apollo::common::math::Vec2d vec2d(FLAGS_x, FLAGS_y);
    double s = 0.0;
    double l = 0.0;
    int ret = map_util.lane_projection(vec2d, FLAGS_lane, &s, &l);
    if (ret != 0) {
      printf("lane_projection for x[%f], y[%f], lane_id[%s] failed\n",
             FLAGS_x, FLAGS_y, FLAGS_lane.c_str());
      return -1;
    }
    printf("lane[%s] s[%f], l[%f]\n", FLAGS_lane.c_str(), s, l);
  }
  if (FLAGS_lane_to_lane) {
    ::apollo::common::PointENU point;
    double heading = 0.0;
    map_util.sl_to_point(FLAGS_from_lane, FLAGS_s, 0.0, &point, &heading);
    double target_s = 0.0;
    double target_l = 0.0;
    ::apollo::common::math::Vec2d vec2d(point.x(), point.y());
    int ret = map_util.lane_projection(vec2d, FLAGS_to_lane,
                                       &target_s, &target_l);
    if (ret != 0) {
      printf("lane_projection for lane[%s], s[%f] to lane_id[%s] failed\n",
             FLAGS_from_lane.c_str(), FLAGS_s, FLAGS_to_lane.c_str());
      return -1;
    }
    printf("lane[%s] s[%f], l[%f]\n", FLAGS_to_lane.c_str(),
           target_s, target_l);
  }
  if (FLAGS_lane_width) {
    auto lane_ptr = map_util.get_lane(FLAGS_lane);
    double left_width = 0.0;
    double right_width = 0.0;
    lane_ptr->get_width(FLAGS_s, &left_width, &right_width);
    printf("lane[%s] s[%f]: left_width[%f], right_width[%f], total_width[%f]\n",
           FLAGS_lane.c_str(), FLAGS_s, left_width, right_width,
           left_width + right_width);
  }
  if (!FLAGS_lane_info.empty()) {
    const auto *lane_ptr = map_util.get_lane(FLAGS_lane_info);
    const auto &lane = lane_ptr->lane();

    ::apollo::common::PointENU start_point;
    double start_heading = 0.0;
    map_util.sl_to_point(FLAGS_lane_info, 0, 0, &start_point, &start_heading);

    ::apollo::common::PointENU end_point;
    double end_heading = 0.0;
    map_util.sl_to_point(FLAGS_lane_info, lane_ptr->total_length(), 0,
                         &end_point, &end_heading);

    std::cout << "lane[" << FLAGS_lane_info
              << "] length[" << lane_ptr->total_length()
              << "] type[" << Lane_LaneType_Name(lane.type())
              << "] turn[" << Lane_LaneTurn_Name(lane.turn())
              // << "] left_boundary["
              // << LaneBoundary_Type_Name(lane.left_boundary().type())
              // << "] right_boundary["
              // << LaneBoundary_Type_Name(lane.right_boundary().type())
              << "] speed_limit[" << lane.speed_limit()
              << "] predecessor[" << lane.predecessor_id()
              << "] successor[" << lane.successor_id()
              << "] left_forward[" << lane.left_neighbor_forward_lane_id()
              << "] right_forward[" << lane.right_neighbor_forward_lane_id()
              << "] left_reverse[" << lane.left_neighbor_reverse_lane_id()
              << "] right_reverse[" << lane.right_neighbor_reverse_lane_id()
              << "] overlap[" << lane.overlap_id()
              // << "] crosswalk[" << lane.crosswalk_id()
              // << "] yield_sign[" << lane.yield_sign_id()
               << "] stop_sign num:[" << lane_ptr->stop_signs().size()
              << "]"
              << " start point(x,y,heading):" << start_point.x() << ","
              << start_point.y() << "," << start_heading
              << " end point(x,y,heading):" << end_point.x() << ","
              << end_point.y() << "," << end_heading
              << std::endl;
  }
  if (!FLAGS_overlap.empty()) {
    const auto *overlap_ptr = map_util.get_overlap(FLAGS_overlap);
    if (overlap_ptr != nullptr) {
      std::cout << "overlap[" << overlap_ptr->id().id()
                << "] info[" << overlap_ptr->overlap().DebugString()
                << "]" << std::endl;
    }
  }
  if (!FLAGS_signal_info.empty()) {
    const auto *signal_ptr = map_util.get_signal(FLAGS_signal_info);
    if (signal_ptr) {
      std::cout << "signal[" << FLAGS_signal_info << "] info["
                << signal_ptr->signal().DebugString() << "]" << std::endl;
    }
  }
  if (!FLAGS_dump_txt_map.empty()) {
    apollo::hdmap::Map map;
    apollo::common::util::GetProtoFromFile(FLAGS_map_file_path, &map);

    std::ofstream ofs(FLAGS_dump_txt_map);
    ofs << map.DebugString();
    ofs.close();
  }
  if (!FLAGS_dump_bin_map.empty()) {
    apollo::hdmap::Map map;
    apollo::common::util::GetProtoFromFile(FLAGS_map_file_path, &map);

    std::ofstream ofs(FLAGS_dump_bin_map);
    std::string map_str;
    map.SerializeToString(&map_str);
    ofs << map_str;
    ofs.close();
  }
  if (!FLAGS_sl_to_xy
      && !FLAGS_xy_to_sl
      && !FLAGS_xy_to_lane
      && !FLAGS_lane_to_lane
      && !FLAGS_lane_width
      && FLAGS_dump_txt_map.empty()
      && FLAGS_dump_bin_map.empty()
      && FLAGS_lane_info.empty()
      && FLAGS_signal_info.empty()
      && FLAGS_overlap.empty()) {
    std::cout << "usage: --map_file" << std::endl;
    std::cout << "usage: --dump_txt_map" << std::endl;
    std::cout << "usage: --dump_bin_map" << std::endl;
    std::cout << "usage: --xy_to_sl --x --y" << std::endl;
    std::cout << "usage: --sl_to_xy --lane --s --l" << std::endl;
    std::cout << "usage: --xy_to_lane --x --y --lane" << std::endl;
    std::cout << "usage: --lane_to_lane --from_lane --s --to_lane" << std::endl;
    std::cout << "usage: --lane_width --lane --s" << std::endl;
    std::cout << "usage: --lane_info" << std::endl;
    std::cout << "usage: --signal_info" << std::endl;
    std::cout << "usage: --overlap" << std::endl;
  }
  return 0;
}
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2009 Torus Knot Software Ltd

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 "OgreOSXWindow.h"
#include "OgreOSXCGLContext.h"
#include "OgreRoot.h"
#include "OgreGLRenderSystem.h"
#include "OgreImageCodec.h"
#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreGLPixelFormat.h"

#include <OpenGL/gl.h>
#define GL_EXT_texture_env_combine 1
#include <OpenGL/glext.h>
#include <OpenGL/glu.h>

namespace Ogre
{

//-------------------------------------------------------------------------------------------------//
OSXWindow::OSXWindow() : mCGLContext(NULL)
{
}

//-------------------------------------------------------------------------------------------------//
OSXWindow::~OSXWindow()
{
}

//-------------------------------------------------------------------------------------------------//
void OSXWindow::copyContentsToMemory(const PixelBox &dst, FrameBuffer buffer)
{
	if ((dst.left < 0) || (dst.right > mWidth) ||
		(dst.top < 0) || (dst.bottom > mHeight) ||
		(dst.front != 0) || (dst.back != 1))
	{
		OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
					"Invalid box.",
					"OSXWindow::copyContentsToMemory" );
	}

	if (buffer == FB_AUTO)
	{
		buffer = mIsFullScreen? FB_FRONT : FB_BACK;
	}

	GLenum format = Ogre::GLPixelUtil::getGLOriginFormat(dst.format);
	GLenum type = Ogre::GLPixelUtil::getGLOriginDataType(dst.format);

	if ((format == GL_NONE) || (type == 0))
	{
		OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
					"Unsupported format.",
					"OSXWindow::copyContentsToMemory" );
	}

	if((dst.getWidth()*Ogre::PixelUtil::getNumElemBytes(dst.format)) & 3)
	{
		// Standard alignment of 4 is not right
		glPixelStorei(GL_PACK_ALIGNMENT, 1);
	}

	glReadBuffer((buffer == FB_FRONT)? GL_FRONT : GL_BACK);
	glReadPixels((GLint)dst.left, (GLint)dst.top,
				 (GLsizei)dst.getWidth(), (GLsizei)dst.getHeight(),
				 format, type, dst.data);

	glPixelStorei(GL_PACK_ALIGNMENT, 4);

	//vertical flip
	{
		size_t rowSpan = dst.getWidth() * PixelUtil::getNumElemBytes(dst.format);
		size_t height = dst.getHeight();
		uchar *tmpData = new uchar[rowSpan * height];
		uchar *srcRow = (uchar *)dst.data, *tmpRow = tmpData + (height - 1) * rowSpan;

		while (tmpRow >= tmpData)
		{
			memcpy(tmpRow, srcRow, rowSpan);
			srcRow += rowSpan;
			tmpRow -= rowSpan;
		}
		memcpy(dst.data, tmpData, rowSpan * height);

		delete [] tmpData;
	}
}

#if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
uint32 OSXWindow::bitDepthFromDisplayMode(CGDisplayModeRef mode)
{
    uint32 depth = 0;
    CFStringRef pixEnc = CGDisplayModeCopyPixelEncoding(mode);
    if(CFStringCompare(pixEnc, CFSTR(IO32BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)
        depth = 32;
    else if(CFStringCompare(pixEnc, CFSTR(IO16BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)
        depth = 16;
    else if(CFStringCompare(pixEnc, CFSTR(IO8BitIndexedPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)
        depth = 8;

    return depth;
}
#endif

//-------------------------------------------------------------------------------------------------//
void OSXWindow::createCGLFullscreen(unsigned int width, unsigned int height, unsigned int depth, unsigned int fsaa, CGLContextObj sharedContext)
{
    // Find the best match to what was requested
    boolean_t exactMatch = 0;
    int reqWidth, reqHeight, reqDepth;
#if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6

    // Get a copy of the current display mode
    CGDisplayModeRef displayMode = CGDisplayCopyDisplayMode(kCGDirectMainDisplay);

    // Loop through all display modes to determine the closest match.
    // CGDisplayBestModeForParameters is deprecated on 10.6 so we will emulate it's behavior
    // Try to find a mode with the requested depth and equal or greater dimensions first.
    // If no match is found, try to find a mode with greater depth and same or greater dimensions.
    // If still no match is found, just use the current mode.
    CFArrayRef allModes = CGDisplayCopyAllDisplayModes(kCGDirectMainDisplay, NULL);
    for(int i = 0; i < CFArrayGetCount(allModes); i++)
    {
        CGDisplayModeRef mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(allModes, i);
        String modeString = StringConverter::toString(CGDisplayModeGetWidth(mode)) + String(" x ") +
            StringConverter::toString(CGDisplayModeGetHeight(mode)) + String(" @ ") +
            StringConverter::toString(bitDepthFromDisplayMode(mode)) + "bpp.";

        LogManager::getSingleton().logMessage(modeString);
        if(bitDepthFromDisplayMode(mode) != depth)
            continue;

        if((CGDisplayModeGetWidth(mode) >= width) && (CGDisplayModeGetHeight(mode) >= height))
        {
            displayMode = mode;
            exactMatch = 1;
            break;
        }
    }

    // No depth match was found
    if(!exactMatch)
    {
        for(int i = 0; i < CFArrayGetCount(allModes); i++)
        {
            CGDisplayModeRef mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(allModes, i);
            if(bitDepthFromDisplayMode(mode) >= depth)
                continue;

            if((CGDisplayModeGetWidth(mode) >= width) && (CGDisplayModeGetHeight(mode) >= height))
            {
                displayMode = mode;
                exactMatch = 1;
                break;
            }
        }
    }

    reqWidth = CGDisplayModeGetWidth(displayMode);
    reqHeight = CGDisplayModeGetHeight(displayMode);
    reqDepth = bitDepthFromDisplayMode(displayMode);
#else
    CFDictionaryRef displayMode = CGDisplayBestModeForParameters(kCGDirectMainDisplay, depth, width, height, &exactMatch);
    const void *value = NULL;

    value = CFDictionaryGetValue(displayMode, kCGDisplayWidth);
    CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &reqWidth);

    value = CFDictionaryGetValue(displayMode, kCGDisplayHeight);
    CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &reqHeight);

    value = CFDictionaryGetValue(displayMode, kCGDisplayBitsPerPixel);
    CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &reqDepth);
#endif

    if(!exactMatch)
    {
        // TODO: Report the size difference
        // That mode is not available, using the closest match
        String request = StringConverter::toString(width) + String(" x ") + StringConverter::toString(height) + String(" @ ") +
            StringConverter::toString(depth) + "bpp. ";

        String received = StringConverter::toString(reqWidth) + String(" x ") +
            StringConverter::toString(reqHeight) + String(" @ ") +
            StringConverter::toString(reqDepth) + "bpp. ";

        LogManager::getSingleton().logMessage(String("RenderSystem Warning:  You requested a fullscreen mode of ") + request +
            String(" This mode is not available and you will receive the closest match.  The best display mode for the parameters requested is: ")
            + received);
    }

    // Do the fancy display fading
    CGDisplayFadeReservationToken reservationToken;
    CGAcquireDisplayFadeReservation(kCGMaxDisplayReservationInterval,
                                        &reservationToken);
    CGDisplayFade(reservationToken,
                  0.5,
                  kCGDisplayBlendNormal,
                  kCGDisplayBlendSolidColor,
                  0.0, 0.0, 0.0,
                  true);

    // Grab the main display and save it for later.
    // You could render to any display, but picking what display
    // to render to could be interesting.
    CGDisplayCapture(kCGDirectMainDisplay);

    // Switch to the correct resolution
#if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
    CGDisplaySetDisplayMode(kCGDirectMainDisplay, displayMode, NULL);
#else
    CGDisplaySwitchToMode(kCGDirectMainDisplay, displayMode);
#endif

    // Get a pixel format that best matches what we are looking for
    CGLPixelFormatAttribute attribs[] = {
        kCGLPFADoubleBuffer,
        kCGLPFAAlphaSize,     (CGLPixelFormatAttribute)8,
        kCGLPFADepthSize,     (CGLPixelFormatAttribute)reqDepth,
        kCGLPFAStencilSize,   (CGLPixelFormatAttribute)8,
        kCGLPFASampleBuffers, (CGLPixelFormatAttribute)0,
        kCGLPFASamples,       (CGLPixelFormatAttribute)0,
        kCGLPFAFullScreen,
        kCGLPFASingleRenderer,
        kCGLPFAAccelerated,
        kCGLPFADisplayMask,   (CGLPixelFormatAttribute)CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay),
        (CGLPixelFormatAttribute)0
    };

    // Set up FSAA if it was requested
    if(fsaa > 1)
    {
            // turn on kCGLPFASampleBuffers
            attribs[8] = (CGLPixelFormatAttribute)1;
            // set the samples for kCGLPFASamples
            attribs[10] = (CGLPixelFormatAttribute)fsaa;
    }

    CGLError err;
    CGLPixelFormatObj pixelFormatObj;
#if (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4)
    GLint numPixelFormats = 0;
    err = CGLChoosePixelFormat(attribs, &pixelFormatObj, &numPixelFormats);
#else
    long numPixelFormats = 0;
    err = CGLChoosePixelFormat(attribs, &pixelFormatObj, &numPixelFormats);
#endif
    if(err != 0)
    {
        CGReleaseAllDisplays();
        OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, String("CGL Error: " + String(CGLErrorString(err))), "OSXWindow::createCGLFullscreen");
    }

    // Create the CGLcontext from our pixel format, share it with the sharedContext passed in
    err = CGLCreateContext(pixelFormatObj, sharedContext, &mCGLContext);
    if(err != 0)
    {
        CGReleaseAllDisplays();
        OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, String("CGL Error: " + String(CGLErrorString(err))), "OSXWindow::createCGLFullscreen");
    }

    // Once we have the context we can destroy the pixel format
    // In order to share contexts you must keep a pointer to the context object around
    // Our context class will now manage the life of the pixelFormatObj
    //CGLDestroyPixelFormat(pixelFormatObj);

    // Set the context to full screen
#if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
    CGLSetFullScreenOnDisplay(mCGLContext, CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay));
#else
    CGLSetFullScreen(mCGLContext);
#endif

    // Set the context as current
    CGLSetCurrentContext(mCGLContext);

    // This synchronizes CGL with the vertical retrace
    // Apple docs suggest that OpenGL blocks rendering calls when waiting for
    // a vertical retrace anyhow.
#if (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4)
    GLint swapInterval = 1;
    CGLSetParameter(mCGLContext, kCGLCPSwapInterval, &swapInterval);
#else
    long swapInterval = 1;
    CGLSetParameter(mCGLContext, kCGLCPSwapInterval, &swapInterval);
#endif

    // Give a copy of our context to the rendersystem
    mContext = new OSXCGLContext(mCGLContext, pixelFormatObj);

    // Let everyone know we are fullscreen now
    mIsFullScreen = true;

    // Set some other variables.  Just in case we got a different value from CGDisplayBestModeForParameters than we requested
    mWidth = reqWidth;
    mHeight = reqHeight;
    mColourDepth = reqDepth;

    CGDisplayFade(reservationToken,
              2.0,
              kCGDisplayBlendSolidColor,
              kCGDisplayBlendNormal,
              0.0, 0.0, 0.0,
              false);
    CGReleaseDisplayFadeReservation(reservationToken);
}

//-------------------------------------------------------------------------------------------------//
void OSXWindow::destroyCGLFullscreen(void)
{
	CGReleaseAllDisplays();
}

//-------------------------------------------------------------------------------------------------//
void OSXWindow::swapCGLBuffers(void)
{
	CGLFlushDrawable(mCGLContext);
	CGLContextObj curCtx = CGLGetCurrentContext();
	if(curCtx != mCGLContext)
	{
		CGLSetCurrentContext(mCGLContext);
#if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
        CGLSetFullScreenOnDisplay(mCGLContext, CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay));
#else
        CGLSetFullScreen(mCGLContext);
#endif
	}
}

}
<commit_msg>OS X: When targeting 10.6 only - Fixed an issue with old framebuffer contents being displayed when using non-native resolution full screen contexts. Also fixed a crash when switching resolutions.  Added some error checking to the full screen context creation.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2009 Torus Knot Software Ltd

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 "OgreOSXWindow.h"
#include "OgreOSXCGLContext.h"
#include "OgreRoot.h"
#include "OgreGLRenderSystem.h"
#include "OgreImageCodec.h"
#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreGLPixelFormat.h"

#include <OpenGL/gl.h>
#define GL_EXT_texture_env_combine 1
#include <OpenGL/glext.h>
#include <OpenGL/glu.h>

namespace Ogre
{

//-------------------------------------------------------------------------------------------------//
OSXWindow::OSXWindow() : mCGLContext(NULL)
{
}

//-------------------------------------------------------------------------------------------------//
OSXWindow::~OSXWindow()
{
}

//-------------------------------------------------------------------------------------------------//
void OSXWindow::copyContentsToMemory(const PixelBox &dst, FrameBuffer buffer)
{
	if ((dst.left < 0) || (dst.right > mWidth) ||
		(dst.top < 0) || (dst.bottom > mHeight) ||
		(dst.front != 0) || (dst.back != 1))
	{
		OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
					"Invalid box.",
					"OSXWindow::copyContentsToMemory" );
	}

	if (buffer == FB_AUTO)
	{
		buffer = mIsFullScreen? FB_FRONT : FB_BACK;
	}

	GLenum format = Ogre::GLPixelUtil::getGLOriginFormat(dst.format);
	GLenum type = Ogre::GLPixelUtil::getGLOriginDataType(dst.format);

	if ((format == GL_NONE) || (type == 0))
	{
		OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
					"Unsupported format.",
					"OSXWindow::copyContentsToMemory" );
	}

	if((dst.getWidth()*Ogre::PixelUtil::getNumElemBytes(dst.format)) & 3)
	{
		// Standard alignment of 4 is not right
		glPixelStorei(GL_PACK_ALIGNMENT, 1);
	}

	glReadBuffer((buffer == FB_FRONT)? GL_FRONT : GL_BACK);
	glReadPixels((GLint)dst.left, (GLint)dst.top,
				 (GLsizei)dst.getWidth(), (GLsizei)dst.getHeight(),
				 format, type, dst.data);

	glPixelStorei(GL_PACK_ALIGNMENT, 4);

	//vertical flip
	{
		size_t rowSpan = dst.getWidth() * PixelUtil::getNumElemBytes(dst.format);
		size_t height = dst.getHeight();
		uchar *tmpData = new uchar[rowSpan * height];
		uchar *srcRow = (uchar *)dst.data, *tmpRow = tmpData + (height - 1) * rowSpan;

		while (tmpRow >= tmpData)
		{
			memcpy(tmpRow, srcRow, rowSpan);
			srcRow += rowSpan;
			tmpRow -= rowSpan;
		}
		memcpy(dst.data, tmpData, rowSpan * height);

		delete [] tmpData;
	}
}

#if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
uint32 OSXWindow::bitDepthFromDisplayMode(CGDisplayModeRef mode)
{
    uint32 depth = 0;
    CFStringRef pixEnc = CGDisplayModeCopyPixelEncoding(mode);
    if(CFStringCompare(pixEnc, CFSTR(IO32BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)
        depth = 32;
    else if(CFStringCompare(pixEnc, CFSTR(IO16BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)
        depth = 16;
    else if(CFStringCompare(pixEnc, CFSTR(IO8BitIndexedPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)
        depth = 8;

    return depth;
}
#endif

//-------------------------------------------------------------------------------------------------//
void OSXWindow::createCGLFullscreen(unsigned int width, unsigned int height, unsigned int depth, unsigned int fsaa, CGLContextObj sharedContext)
{
    // Find the best match to what was requested
    boolean_t exactMatch = 0;
    int reqWidth, reqHeight, reqDepth;
    CGLError err;
    CGError cgErr;
#if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6

    // Get a copy of the current display mode
    CGDisplayModeRef displayMode = CGDisplayCopyDisplayMode(kCGDirectMainDisplay);

    // Loop through all display modes to determine the closest match.
    // CGDisplayBestModeForParameters is deprecated on 10.6 so we will emulate it's behavior
    // Try to find a mode with the requested depth and equal or greater dimensions first.
    // If no match is found, try to find a mode with greater depth and same or greater dimensions.
    // If still no match is found, just use the current mode.
    CFArrayRef allModes = CGDisplayCopyAllDisplayModes(kCGDirectMainDisplay, NULL);
    for(int i = 0; i < CFArrayGetCount(allModes); i++)
    {
        CGDisplayModeRef mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(allModes, i);
        String modeString = StringConverter::toString(CGDisplayModeGetWidth(mode)) + String(" x ") +
            StringConverter::toString(CGDisplayModeGetHeight(mode)) + String(" @ ") +
            StringConverter::toString(bitDepthFromDisplayMode(mode)) + "bpp.";

//        LogManager::getSingleton().logMessage(modeString);
        if(bitDepthFromDisplayMode(mode) != depth)
            continue;

        if((CGDisplayModeGetWidth(mode) == width) && (CGDisplayModeGetHeight(mode) == height))
        {
            displayMode = mode;
            exactMatch = 1;
            break;
        }
    }

    // No depth match was found
    if(!exactMatch)
    {
        for(int i = 0; i < CFArrayGetCount(allModes); i++)
        {
            CGDisplayModeRef mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(allModes, i);
            if(bitDepthFromDisplayMode(mode) >= depth)
                continue;

            if((CGDisplayModeGetWidth(mode) >= width) && (CGDisplayModeGetHeight(mode) >= height))
            {
                displayMode = mode;
                exactMatch = 1;
                break;
            }
        }
    }

    reqWidth = CGDisplayModeGetWidth(displayMode);
    reqHeight = CGDisplayModeGetHeight(displayMode);
    reqDepth = bitDepthFromDisplayMode(displayMode);
#else
    CFDictionaryRef displayMode = CGDisplayBestModeForParameters(kCGDirectMainDisplay, depth, width, height, &exactMatch);
    const void *value = NULL;

    value = CFDictionaryGetValue(displayMode, kCGDisplayWidth);
    CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &reqWidth);

    value = CFDictionaryGetValue(displayMode, kCGDisplayHeight);
    CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &reqHeight);

    value = CFDictionaryGetValue(displayMode, kCGDisplayBitsPerPixel);
    CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &reqDepth);
#endif

    if(!exactMatch)
    {
        // TODO: Report the size difference
        // That mode is not available, using the closest match
        String request = StringConverter::toString(width) + String(" x ") + StringConverter::toString(height) + String(" @ ") +
            StringConverter::toString(depth) + "bpp. ";

        String received = StringConverter::toString(reqWidth) + String(" x ") +
            StringConverter::toString(reqHeight) + String(" @ ") +
            StringConverter::toString(reqDepth) + "bpp. ";

        LogManager::getSingleton().logMessage(String("RenderSystem Warning:  You requested a fullscreen mode of ") + request +
            String(" This mode is not available and you will receive the closest match.  The best display mode for the parameters requested is: ")
            + received);
    }

    // Do the fancy display fading
    CGDisplayFadeReservationToken reservationToken;
    CGAcquireDisplayFadeReservation(kCGMaxDisplayReservationInterval,
                                        &reservationToken);
    CGDisplayFade(reservationToken,
                  0.5,
                  kCGDisplayBlendNormal,
                  kCGDisplayBlendSolidColor,
                  0.0, 0.0, 0.0,
                  true);

    // Grab the main display and save it for later.
    // You could render to any display, but picking what display
    // to render to could be interesting.
    CGDisplayCapture(kCGDirectMainDisplay);

    // Switch to the correct resolution
#if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
    cgErr = CGDisplaySetDisplayMode(kCGDirectMainDisplay, displayMode, NULL);
    if(cgErr != 0)
    {
        CGReleaseAllDisplays();
        OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, String("CG Error: " + StringConverter::toString((int)err)), "OSXWindow::createCGLFullscreen");
    }
#else
    CGDisplaySwitchToMode(kCGDirectMainDisplay, displayMode);
#endif

    // Get a pixel format that best matches what we are looking for
    CGLPixelFormatAttribute attribs[] = {
        kCGLPFADoubleBuffer,
        kCGLPFAAlphaSize,     (CGLPixelFormatAttribute)8,
        kCGLPFADepthSize,     (CGLPixelFormatAttribute)reqDepth,
        kCGLPFAStencilSize,   (CGLPixelFormatAttribute)8,
        kCGLPFASampleBuffers, (CGLPixelFormatAttribute)0,
        kCGLPFASamples,       (CGLPixelFormatAttribute)0,
        kCGLPFAFullScreen,
        kCGLPFASingleRenderer,
        kCGLPFAAccelerated,
        kCGLPFADisplayMask,   (CGLPixelFormatAttribute)CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay),
        (CGLPixelFormatAttribute)0
    };

    // Set up FSAA if it was requested
    if(fsaa > 1)
    {
            // turn on kCGLPFASampleBuffers
            attribs[8] = (CGLPixelFormatAttribute)1;
            // set the samples for kCGLPFASamples
            attribs[10] = (CGLPixelFormatAttribute)fsaa;
    }

    CGLPixelFormatObj pixelFormatObj;
#if (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4)
    GLint numPixelFormats = 0;
    err = CGLChoosePixelFormat(attribs, &pixelFormatObj, &numPixelFormats);
#else
    long numPixelFormats = 0;
    err = CGLChoosePixelFormat(attribs, &pixelFormatObj, &numPixelFormats);
#endif
    if(err != 0)
    {
        CGReleaseAllDisplays();
        OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, String("CGL Error: " + String(CGLErrorString(err))), "OSXWindow::createCGLFullscreen");
    }

    // Create the CGLcontext from our pixel format, share it with the sharedContext passed in
    err = CGLCreateContext(pixelFormatObj, sharedContext, &mCGLContext);
    if(err != 0)
    {
        CGReleaseAllDisplays();
        OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, String("CGL Error: " + String(CGLErrorString(err))), "OSXWindow::createCGLFullscreen");
    }

    // Set the context to full screen
#if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
    err = CGLSetFullScreenOnDisplay(mCGLContext, CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay));
    if(err != 0)
    {
        CGReleaseAllDisplays();
        OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, String("CGL Error: " + String(CGLErrorString(err))), "OSXWindow::createCGLFullscreen");
    }
#else
    CGLSetFullScreen(mCGLContext);
#endif

    // Set the context as current
    err = CGLSetCurrentContext(mCGLContext);
    if(err != 0)
    {
        CGReleaseAllDisplays();
        OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, String("CGL Error: " + String(CGLErrorString(err))), "OSXWindow::createCGLFullscreen");
    }

    // This synchronizes CGL with the vertical retrace
    // Apple docs suggest that OpenGL blocks rendering calls when waiting for
    // a vertical retrace anyhow.
#if (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4)
    GLint swapInterval = 1;
    CGLSetParameter(mCGLContext, kCGLCPSwapInterval, &swapInterval);
#else
    long swapInterval = 1;
    CGLSetParameter(mCGLContext, kCGLCPSwapInterval, &swapInterval);
#endif

    // Give a copy of our context to the rendersystem
    mContext = new OSXCGLContext(mCGLContext, pixelFormatObj);

    // Once we have the context we can destroy the pixel format
    // In order to share contexts you must keep a pointer to the context object around
    // Our context class will now manage the life of the pixelFormatObj
    CGLDestroyPixelFormat(pixelFormatObj);

    // Let everyone know we are fullscreen now
    mIsFullScreen = true;

    // Set some other variables.  Just in case we got a different value from CGDisplayBestModeForParameters than we requested
    mWidth = reqWidth;
    mHeight = reqHeight;
    mColourDepth = reqDepth;

    CGDisplayFade(reservationToken,
              2.0,
              kCGDisplayBlendSolidColor,
              kCGDisplayBlendNormal,
              0.0, 0.0, 0.0,
              false);
    CGReleaseDisplayFadeReservation(reservationToken);
}

//-------------------------------------------------------------------------------------------------//
void OSXWindow::destroyCGLFullscreen(void)
{
	CGReleaseAllDisplays();
    if(mCGLContext)
    {
        CGLDestroyContext(mCGLContext);
        mCGLContext = 0;
    }
}

//-------------------------------------------------------------------------------------------------//
void OSXWindow::swapCGLBuffers(void)
{
	CGLFlushDrawable(mCGLContext);
	CGLContextObj curCtx = CGLGetCurrentContext();
	if(curCtx != mCGLContext)
	{
		CGLSetCurrentContext(mCGLContext);
#if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
        CGLSetFullScreenOnDisplay(mCGLContext, CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay));
#else
        CGLSetFullScreen(mCGLContext);
#endif
	}
}

}
<|endoftext|>


<commit_before>#define HUE_STEP 1
#define VALUE_STEP 5
#define PERIOD_STEP 3

#define LETTERS_LAYER 0
#define BACKGROUND_LAYER 1

#include "Effects.h"
#include "effects/Effect.cpp"
#include "effects/RandomOn.cpp"
#include "effects/Counter.cpp"
#include "effects/BasicTyping.cpp"
#include "effects/SolidColor.cpp"
#include "effects/SolidFade.cpp"
#include "effects/RandomFade.cpp"
#include "effects/RandomLetters.cpp"
#include "effects/RainbowLetter.cpp"
#include "effects/RainbowSegment.cpp"

const uint16_t CYCLE_TIME = 5;

Effects::Effects(){
  for(uint8_t i=0; i<LAYER_COUNT; i++){
    colorEffect[i] = &solidColor;
    cColorEffect[i] = SOLID_COLORS;
  }
  cTextEffect = BASIC_TYPING;
  textEffect = &basicTyping;
  this -> reset();
}

void Effects::run(Sign &sign){
  unsigned long time = millis();
  if(time - lastRun < CYCLE_TIME){ return; }
  lastRun = time;
  sign.textChanged = false;

  textEffect -> run(sign, 0);

  for(uint8_t i=0; i<LAYER_COUNT; i++){
    colorEffect[i] -> run(sign, i);
  }
}

void Effects::pushChar(char character){

  switch(character){
    case '2':
      curLayer = LETTERS_LAYER;
      Serial.println("Layer 2: Letters");
      Serial1.print("\nLayer 2: Letters");
      return;
    case '1':
      curLayer = BACKGROUND_LAYER;
      Serial.println("Layer 1: Background");
      Serial1.print("\nLayer 1: Background");
      return;
  }

  if( textEffect -> pushChar(character, 0) ){ return; }
  if( colorEffect[curLayer] -> pushChar(character, curLayer) ){ return; }

  int32_t val = 0;
  switch(character){
    case 'R':
      Serial1.print("\nRESET");
      this -> reset(); break;

    case '<': val = this -> prevTextEffect(); break;
    case '>': val = this -> nextTextEffect(); break;

    case 'l': val = this -> prevColorEffect(curLayer); break;
    case 'h': val = this -> nextColorEffect(curLayer); break;

  }
  Serial.print(character);
  Serial.print(": ");
  Serial.print(val);
  Serial.println(" ");
}

// Called when new letters pushed to sign
void Effects::signWasUpdated(Sign &sign){
  this -> run(sign);
  textEffect -> signWasUpdated(sign);
  for(uint8_t i=0; i<LAYER_COUNT; i++){
    colorEffect[i] -> signWasUpdated(sign);
  }
}

void Effects::reset(){
  curLayer = 0;
  lastRun = 0;
  textEffect -> reset();
  for(uint8_t i=1; i<LAYER_COUNT; i++){
    colorEffect[i] -> reset();
  }
}

uint8_t Effects::nextTextEffect(){
  cTextEffect++;
  cTextEffect = cTextEffect % TEXT_EFFECTS_COUNT;
  this -> updateTextEffect();
  return cTextEffect;
}

uint8_t Effects::prevTextEffect(){
  cTextEffect--;
  cTextEffect = cTextEffect % TEXT_EFFECTS_COUNT;
  this -> updateTextEffect();
  return cTextEffect;
}

void Effects::updateTextEffect(){
  String desc;
  switch(cTextEffect){
    case RANDOM_ON:
      textEffect = &randomOn;
      desc = "Random Segs,\nkeys:[]kjor";
      break;
    case BASIC_TYPING:
      textEffect = &basicTyping;
      desc = "Basic Typing";
      break;
    case COUNTER:
      textEffect = &counter;
      desc = "Counter\nkeys:[]kj";
      break;
    case RANDOM_LETTERS:
      textEffect = &randomLetters;
      desc = "Random Letters\nkeys:kj";
      break;
    default:
      textEffect = &nullEffect;
      desc = "ERROR";
  }
  Serial.println(desc);
  Serial1.print('\n');
  Serial1.print(desc);
}

uint8_t Effects::nextColorEffect(uint8_t ci){
  cColorEffect[ci]++;
  cColorEffect[ci] = cColorEffect[ci] % COLOR_EFFECTS_COUNT;
  this -> updateColorEffect(ci);
  return cColorEffect[ci];
}
uint8_t Effects::prevColorEffect(uint8_t ci){
  if(cColorEffect[ci] == 0){
    cColorEffect[ci] = COLOR_EFFECTS_COUNT - 1;
  }else{
    cColorEffect[ci]--;
    cColorEffect[ci] = cColorEffect[ci] % COLOR_EFFECTS_COUNT;
  }
  this -> updateColorEffect(ci);
  return cColorEffect[ci];
}

void Effects::updateColorEffect(uint8_t ci){
  String desc;
  switch(cColorEffect[ci]){
    case SOLID_COLORS:
      colorEffect[ci] = &solidColor;
      desc = "Solid Color\nKeys:cCvVbB";
      break;
    case RANDOM_FADE:
      colorEffect[ci] = &randomFade;
      desc = "Random Fade\nKeys:cCvVbBfsFS";
      break;
    case SOLID_FADE:
      colorEffect[ci] = &solidFade;
      desc = "Solid Fade\nKeys:cCvVbBfs";
      break;
    case RAINBOW_LETTER:
      colorEffect[ci] = &rainbowLetter;
      desc = "Rainbow Letter\nKeys:cCvVbBrefsd";
      break;
    case RAINBOW_SEGMENT:
      colorEffect[ci] = &rainbowSegment;
      desc = "Rainbow Segment\nKeys:cCvVbBrefsd";
      break;
  }
  Serial.println(desc);
  Serial1.print('\n');
  Serial1.print(desc);
}

<commit_msg>Switch text effect change to ,/.<commit_after>#define HUE_STEP 1
#define VALUE_STEP 5
#define PERIOD_STEP 3

#define LETTERS_LAYER 0
#define BACKGROUND_LAYER 1

#include "Effects.h"
#include "effects/Effect.cpp"
#include "effects/RandomOn.cpp"
#include "effects/Counter.cpp"
#include "effects/BasicTyping.cpp"
#include "effects/SolidColor.cpp"
#include "effects/SolidFade.cpp"
#include "effects/RandomFade.cpp"
#include "effects/RandomLetters.cpp"
#include "effects/RainbowLetter.cpp"
#include "effects/RainbowSegment.cpp"

const uint16_t CYCLE_TIME = 5;

Effects::Effects(){
  for(uint8_t i=0; i<LAYER_COUNT; i++){
    colorEffect[i] = &solidColor;
    cColorEffect[i] = SOLID_COLORS;
  }
  cTextEffect = BASIC_TYPING;
  textEffect = &basicTyping;
  this -> reset();
}

void Effects::run(Sign &sign){
  unsigned long time = millis();
  if(time - lastRun < CYCLE_TIME){ return; }
  lastRun = time;
  sign.textChanged = false;

  textEffect -> run(sign, 0);

  for(uint8_t i=0; i<LAYER_COUNT; i++){
    colorEffect[i] -> run(sign, i);
  }
}

void Effects::pushChar(char character){

  switch(character){
    case '2':
      curLayer = LETTERS_LAYER;
      Serial.println("Layer 2: Letters");
      Serial1.print("\nLayer 2: Letters");
      return;
    case '1':
      curLayer = BACKGROUND_LAYER;
      Serial.println("Layer 1: Background");
      Serial1.print("\nLayer 1: Background");
      return;
  }

  if( textEffect -> pushChar(character, 0) ){ return; }
  if( colorEffect[curLayer] -> pushChar(character, curLayer) ){ return; }

  int32_t val = 0;
  switch(character){
    case 'R':
      Serial1.print("\nRESET");
      this -> reset(); break;

    case '.': val = this -> prevTextEffect(); break;
    case ',': val = this -> nextTextEffect(); break;

    case 'l': val = this -> prevColorEffect(curLayer); break;
    case 'h': val = this -> nextColorEffect(curLayer); break;

  }
  Serial.print(character);
  Serial.print(": ");
  Serial.print(val);
  Serial.println(" ");
}

// Called when new letters pushed to sign
void Effects::signWasUpdated(Sign &sign){
  this -> run(sign);
  textEffect -> signWasUpdated(sign);
  for(uint8_t i=0; i<LAYER_COUNT; i++){
    colorEffect[i] -> signWasUpdated(sign);
  }
}

void Effects::reset(){
  curLayer = 0;
  lastRun = 0;
  textEffect -> reset();
  for(uint8_t i=1; i<LAYER_COUNT; i++){
    colorEffect[i] -> reset();
  }
}

uint8_t Effects::nextTextEffect(){
  cTextEffect++;
  cTextEffect = cTextEffect % TEXT_EFFECTS_COUNT;
  this -> updateTextEffect();
  return cTextEffect;
}

uint8_t Effects::prevTextEffect(){
  cTextEffect--;
  cTextEffect = cTextEffect % TEXT_EFFECTS_COUNT;
  this -> updateTextEffect();
  return cTextEffect;
}

void Effects::updateTextEffect(){
  String desc;
  switch(cTextEffect){
    case RANDOM_ON:
      textEffect = &randomOn;
      desc = "Random Segs,\nkeys:[]kjor";
      break;
    case BASIC_TYPING:
      textEffect = &basicTyping;
      desc = "Basic Typing";
      break;
    case COUNTER:
      textEffect = &counter;
      desc = "Counter\nkeys:[]kj";
      break;
    case RANDOM_LETTERS:
      textEffect = &randomLetters;
      desc = "Random Letters\nkeys:kj";
      break;
    default:
      textEffect = &nullEffect;
      desc = "ERROR";
  }
  Serial.println(desc);
  Serial1.print('\n');
  Serial1.print(desc);
}

uint8_t Effects::nextColorEffect(uint8_t ci){
  cColorEffect[ci]++;
  cColorEffect[ci] = cColorEffect[ci] % COLOR_EFFECTS_COUNT;
  this -> updateColorEffect(ci);
  return cColorEffect[ci];
}
uint8_t Effects::prevColorEffect(uint8_t ci){
  if(cColorEffect[ci] == 0){
    cColorEffect[ci] = COLOR_EFFECTS_COUNT - 1;
  }else{
    cColorEffect[ci]--;
    cColorEffect[ci] = cColorEffect[ci] % COLOR_EFFECTS_COUNT;
  }
  this -> updateColorEffect(ci);
  return cColorEffect[ci];
}

void Effects::updateColorEffect(uint8_t ci){
  String desc;
  switch(cColorEffect[ci]){
    case SOLID_COLORS:
      colorEffect[ci] = &solidColor;
      desc = "Solid Color\nKeys:cCvVbB";
      break;
    case RANDOM_FADE:
      colorEffect[ci] = &randomFade;
      desc = "Random Fade\nKeys:cCvVbBfsFS";
      break;
    case SOLID_FADE:
      colorEffect[ci] = &solidFade;
      desc = "Solid Fade\nKeys:cCvVbBfs";
      break;
    case RAINBOW_LETTER:
      colorEffect[ci] = &rainbowLetter;
      desc = "Rainbow Letter\nKeys:cCvVbBrefsd";
      break;
    case RAINBOW_SEGMENT:
      colorEffect[ci] = &rainbowSegment;
      desc = "Rainbow Segment\nKeys:cCvVbBrefsd";
      break;
  }
  Serial.println(desc);
  Serial1.print('\n');
  Serial1.print(desc);
}

<|endoftext|>


<commit_before>/**
 * @file   Mesh.cpp
 * @author Sebastian Maisch <sebastian.maisch@googlemail.com>
 * @date   2017.03.24
 *
 * @brief  Implementation of the Mesh class.
 */

#include "Mesh.h"
#include "gfx/vk/LogicalDevice.h"
#include "gfx/vk/memory/MemoryGroup.h"
#include "gfx/Texture2D.h"
#include <glm/gtc/matrix_inverse.hpp>
#include <glm/gtc/type_ptr.hpp>

namespace vku::gfx {

    Mesh::Mesh(std::shared_ptr<const MeshInfo> meshInfo, const LogicalDevice* device,
        vk::MemoryPropertyFlags memoryFlags, const std::vector<std::uint32_t>& queueFamilyIndices) :
        device_{ device },
        meshInfo_{ meshInfo },
        memoryGroup_{ std::make_unique<MemoryGroup>(device, memoryFlags) },
        vertexBuffer_{ nullptr, 0 },
        indexBuffer_{ nullptr, 0 },
        materialBuffer_{ nullptr, 0, 0 }
    {
        CreateMaterials(queueFamilyIndices);
    }

    Mesh::Mesh(std::shared_ptr<const MeshInfo> meshInfo, const LogicalDevice* device,
        MemoryGroup& memoryGroup, const std::vector<std::uint32_t>& queueFamilyIndices) :
        device_{ device },
        meshInfo_{ meshInfo },
        vertexBuffer_{ nullptr, 0 },
        indexBuffer_{ nullptr, 0 },
        materialBuffer_{ nullptr, 0, 0 }
    {
        CreateMaterials(queueFamilyIndices);
    }

    Mesh::Mesh(Mesh&& rhs) noexcept :
        device_{ std::move(rhs.device_) },
        meshInfo_{ std::move(rhs.meshInfo_) },
        memoryGroup_{ std::move(rhs.memoryGroup_) },
        vertexBuffer_{ std::move(rhs.vertexBuffer_) },
        indexBuffer_{ std::move(rhs.indexBuffer_) },
        materialBuffer_{ std::move(rhs.materialBuffer_) },
        materials_{ std::move(rhs.materials_) },
        textureSampler_{ std::move(rhs.textureSampler_) },
        descriptorPool_{ std::move(rhs.descriptorPool_) },
        descriptorSetLayout_{ std::move(rhs.descriptorSetLayout_) },
        materialDescriptorSets_{ std::move(rhs.materialDescriptorSets_) },
        vertexMaterialData_{ std::move(rhs.vertexMaterialData_) }
    {
        rhs.textureSampler_ = vk::Sampler();
        rhs.descriptorPool_ = vk::DescriptorPool();
        rhs.descriptorSetLayout_ = vk::DescriptorSetLayout();
    }

    Mesh& Mesh::operator=(Mesh&& rhs) noexcept
    {
        this->~Mesh();
        device_ = std::move(rhs.device_);
        meshInfo_ = std::move(rhs.meshInfo_);
        memoryGroup_ = std::move(rhs.memoryGroup_);
        vertexBuffer_ = std::move(rhs.vertexBuffer_);
        indexBuffer_ = std::move(rhs.indexBuffer_);
        materialBuffer_ = std::move(rhs.materialBuffer_);
        materials_ = std::move(rhs.materials_);
        textureSampler_ = std::move(rhs.textureSampler_);
        descriptorPool_ = std::move(rhs.descriptorPool_);
        descriptorSetLayout_ = std::move(rhs.descriptorSetLayout_);
        materialDescriptorSets_ = std::move(rhs.materialDescriptorSets_);
        vertexMaterialData_ = std::move(rhs.vertexMaterialData_);
        rhs.textureSampler_ = vk::Sampler();
        rhs.descriptorPool_ = vk::DescriptorPool();
        rhs.descriptorSetLayout_ = vk::DescriptorSetLayout();
        return *this;
    }

    Mesh::~Mesh()
    {
        if (descriptorPool_) device_->GetDevice().destroyDescriptorPool(descriptorPool_);
        descriptorPool_ = vk::DescriptorPool();
        if (descriptorSetLayout_) device_->GetDevice().destroyDescriptorSetLayout(descriptorSetLayout_);
        descriptorSetLayout_ = vk::DescriptorSetLayout();
        if (textureSampler_) device_->GetDevice().destroySampler(textureSampler_);
        textureSampler_ = vk::Sampler();
    }

    void Mesh::CreateMaterials(const std::vector<std::uint32_t>& queueFamilyIndices)
    {
        vk::SamplerCreateInfo samplerCreateInfo{ vk::SamplerCreateFlags(), vk::Filter::eLinear, vk::Filter::eLinear,
            vk::SamplerMipmapMode::eNearest, vk::SamplerAddressMode::eRepeat, vk::SamplerAddressMode::eRepeat,
            vk::SamplerAddressMode::eRepeat };
        textureSampler_ = device_->GetDevice().createSampler(samplerCreateInfo);

        auto numMaterials = meshInfo_->GetMaterials().size();
        std::vector<vk::DescriptorPoolSize> poolSizes;
        poolSizes.emplace_back(vk::DescriptorType::eUniformBuffer, static_cast<std::uint32_t>(numMaterials));
        poolSizes.emplace_back(vk::DescriptorType::eCombinedImageSampler, static_cast<std::uint32_t>(numMaterials * 2));

        vk::DescriptorPoolCreateInfo descriptorPoolInfo{ vk::DescriptorPoolCreateFlags(), static_cast<std::uint32_t>(numMaterials * 3),
            static_cast<std::uint32_t>(poolSizes.size()), poolSizes.data() };

        descriptorPool_ = device_->GetDevice().createDescriptorPool(descriptorPoolInfo);

        // Shared descriptor set layout
        std::vector<vk::DescriptorSetLayoutBinding> setLayoutBindings;
        // Binding 0: UBO
        setLayoutBindings.emplace_back(0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eFragment);
        // Binding 1: Diffuse map
        setLayoutBindings.emplace_back(1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment);
        // Binding 1: Bump map
        setLayoutBindings.emplace_back(2, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment);

        vk::DescriptorSetLayoutCreateInfo descriptorLayoutCreateInfo{ vk::DescriptorSetLayoutCreateFlags(),
            static_cast<std::uint32_t>(setLayoutBindings.size()), setLayoutBindings.data() };

        descriptorSetLayout_ = device_->GetDevice().createDescriptorSetLayout(descriptorLayoutCreateInfo);

        materials_.reserve(numMaterials);
        for (std::size_t i = 0; i < numMaterials; ++i) {
            const auto& mat = meshInfo_->GetMaterials()[i];
            materials_.emplace_back(&mat, device_, *memoryGroup_, queueFamilyIndices);
        }

        // {
        //     vk::PipelineLayoutCreateInfo pipelineLayoutInfo{ vk::PipelineLayoutCreateFlags(),
        //         static_cast<std::uint32_t>(vkDescriptorSetLayouts_.size()), vkDescriptorSetLayouts_.data(), 0, nullptr };
        //     vkPipelineLayout_ = device.GetDevice().createPipelineLayout(pipelineLayoutInfo);
        // }

        // {
        //     std::vector<vk::DescriptorSetLayout> descSetLayouts; descSetLayouts.resize(numUBOBuffers + 1);
        //     descSetLayouts[0] = descSetLayout;
        //     for (auto i = 0U; i < numUBOBuffers; ++i) descSetLayouts[i + 1] = vkDescriptorSetLayouts_[1];
        //     vk::DescriptorSetAllocateInfo descSetAllocInfo{ vkUBODescriptorPool_, static_cast<std::uint32_t>(descSetLayouts.size()), descSetLayouts.data() };
        //     vkUBOSamplerDescritorSets_ = device.GetDevice().allocateDescriptorSets(descSetAllocInfo);
        // }
    }

    void Mesh::CreateDescriptorSets()
    {
        std::vector<vk::DescriptorSetLayout> descSetLayouts; descSetLayouts.resize(materials_.size());
        std::vector<vk::WriteDescriptorSet> descSetWrites; descSetWrites.reserve(materials_.size());
        std::vector<vk::DescriptorBufferInfo> descBufferInfos; descBufferInfos.reserve(materials_.size());
        std::vector<vk::DescriptorImageInfo> descImageInfos; descImageInfos.reserve(materials_.size() * 2);

        for (std::size_t i = 0; i < materials_.size(); ++i) {
            descSetLayouts[i] = descriptorSetLayout_;
        }

        vk::DescriptorSetAllocateInfo descSetAllocInfo{ descriptorPool_, static_cast<std::uint32_t>(descSetLayouts.size()), descSetLayouts.data() };
        materialDescriptorSets_ = device_->GetDevice().allocateDescriptorSets(descSetAllocInfo);

        auto uboOffset = static_cast<std::uint32_t>(std::get<1>(materialBuffer_));
        auto materialBufferSize = static_cast<std::uint32_t>(std::get<2>(materialBuffer_));
        for (std::size_t i = 0; i < materials_.size(); ++i) {
            auto materialBufferOffset = uboOffset + materialBufferSize * i;
            descBufferInfos.emplace_back(std::get<0>(materialBuffer_)->GetBuffer(), materialBufferOffset, materialBufferSize);
            descSetWrites.emplace_back(materialDescriptorSets_[i], 0, static_cast<std::uint32_t>(i), 1,
                vk::DescriptorType::eUniformBuffer, nullptr, &descBufferInfos[i]);

            if (materials_[i].diffuseTexture_) {
                descImageInfos.emplace_back(textureSampler_, materials_[i].diffuseTexture_->GetTexture().GetImageView(), vk::ImageLayout::eShaderReadOnlyOptimal);
                descSetWrites.emplace_back(materialDescriptorSets_[i], 1, static_cast<std::uint32_t>(i), 1, vk::DescriptorType::eCombinedImageSampler, &descImageInfos[2 * i + 0]);
            }
            else {
                descSetWrites.emplace_back(materialDescriptorSets_[i], 1, static_cast<std::uint32_t>(i), 0, vk::DescriptorType::eCombinedImageSampler, nullptr);
            }

            if (materials_[i].bumpMap_) {
                vk::DescriptorImageInfo descImageInfo{ textureSampler_, materials_[i].bumpMap_->GetTexture().GetImageView(), vk::ImageLayout::eShaderReadOnlyOptimal };
                descSetWrites.emplace_back(materialDescriptorSets_[i], 2, static_cast<std::uint32_t>(i), 1, vk::DescriptorType::eCombinedImageSampler, &descImageInfos[2 * i + 1]);
            }
            else {
                descSetWrites.emplace_back(materialDescriptorSets_[i], 2, static_cast<std::uint32_t>(i), 0, vk::DescriptorType::eCombinedImageSampler, nullptr);
            }
        }

        device_->GetDevice().updateDescriptorSets(descSetWrites, nullptr);
    }

    void Mesh::UploadMeshData(QueuedDeviceTransfer& transfer)
    {
        assert(memoryGroup_);
        memoryGroup_->FinalizeDeviceGroup();
        memoryGroup_->TransferData(transfer);
        vertexMaterialData_.clear();
    }

    void Mesh::BindBuffersToCommandBuffer(vk::CommandBuffer cmdBuffer) const
    {
        cmdBuffer.bindVertexBuffers(0, 1, vertexBuffer_.first->GetBufferPtr(), &vertexBuffer_.second);
        cmdBuffer.bindIndexBuffer(indexBuffer_.first->GetBuffer(), indexBuffer_.second, vk::IndexType::eUint32);
    }

    void Mesh::DrawMesh(vk::CommandBuffer cmdBuffer, vk::PipelineLayout pipelineLayout, const glm::mat4& worldMatrix) const
    {
        auto meshWorld = meshInfo_->GetRootTransform() * worldMatrix;
        // TODO: add depth sorting here...
        DrawMeshNode(cmdBuffer, pipelineLayout, meshInfo_->GetRootNode(), meshWorld);

        // TODO: use submeshes and materials and the scene nodes...
        // need:
        // - for each submesh: 2 texture descriptors
        // - for each scene mesh node: uniform buffer?
        // - uniform buffer for all materials[array] (via template)
        // - push constant for world matrix
        // - push constant for material index .. or "VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC"
        // cmdBuffer.drawIndexed(static_cast<std::uint32_t>(meshInfo_->GetIndices().size()), 1, 0, 0, 0);
    }

    void Mesh::DrawMeshNode(vk::CommandBuffer cmdBuffer, vk::PipelineLayout pipelineLayout,
        const SceneMeshNode* node, const glm::mat4& worldMatrix) const
    {
        auto nodeWorld = node->GetLocalTransform() * worldMatrix;
        for (unsigned int i = 0; i < node->GetNumberOfSubMeshes(); ++i) DrawSubMesh(cmdBuffer, pipelineLayout, meshInfo_->GetSubMesh(node->GetSubMeshID(i)), nodeWorld);
        for (unsigned int i = 0; i < node->GetNumberOfNodes(); ++i) DrawMeshNode(cmdBuffer, pipelineLayout, node->GetChild(i), nodeWorld);
    }

    void Mesh::DrawSubMesh(vk::CommandBuffer cmdBuffer, vk::PipelineLayout pipelineLayout, const SubMesh* subMesh, const glm::mat4& worldMatrix) const
    {
        auto worldMat = worldMatrix;
        auto normalMat = glm::inverseTranspose(glm::mat3(worldMatrix));
        auto& mat = materials_[subMesh->GetMaterialID()];
        auto& matDescSets = materialDescriptorSets_[subMesh->GetMaterialID()];

        // bind material ubo.
        cmdBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipelineLayout, 0, materialDescriptorSets_, nullptr);
        cmdBuffer.pushConstants(pipelineLayout, vk::ShaderStageFlagBits::eVertex, 0, vk::ArrayProxy<const float>(16, glm::value_ptr(worldMat)));
        cmdBuffer.pushConstants(pipelineLayout, vk::ShaderStageFlagBits::eVertex, 16, vk::ArrayProxy<const float>(9, glm::value_ptr(normalMat)));
        cmdBuffer.drawIndexed(static_cast<std::uint32_t>(subMesh->GetNumberOfIndices()), 1, static_cast<std::uint32_t>(subMesh->GetIndexOffset()), 0, 0);
    }

    void Mesh::SetVertexBuffer(const DeviceBuffer* vtxBuffer, std::size_t offset)
    {
        vertexBuffer_.first = vtxBuffer;
        vertexBuffer_.second = offset;
    }

    void Mesh::SetIndexBuffer(const DeviceBuffer* idxBuffer, std::size_t offset)
    {
        indexBuffer_.first = idxBuffer;
        indexBuffer_.second = offset;
    }

    void Mesh::SetMaterialBuffer(const DeviceBuffer* matBuffer, std::size_t offset, std::size_t elementSize)
    {
        materialBuffer_ = std::make_tuple(matBuffer, offset, elementSize);
    }
}
<commit_msg>Some fixes for mesh rendering.<commit_after>/**
 * @file   Mesh.cpp
 * @author Sebastian Maisch <sebastian.maisch@googlemail.com>
 * @date   2017.03.24
 *
 * @brief  Implementation of the Mesh class.
 */

#include "Mesh.h"
#include "gfx/vk/LogicalDevice.h"
#include "gfx/vk/memory/MemoryGroup.h"
#include "gfx/Texture2D.h"
#include <glm/gtc/matrix_inverse.hpp>
#include <glm/gtc/type_ptr.hpp>

namespace vku::gfx {

    Mesh::Mesh(std::shared_ptr<const MeshInfo> meshInfo, const LogicalDevice* device,
        vk::MemoryPropertyFlags memoryFlags, const std::vector<std::uint32_t>& queueFamilyIndices) :
        device_{ device },
        meshInfo_{ meshInfo },
        memoryGroup_{ std::make_unique<MemoryGroup>(device, memoryFlags) },
        vertexBuffer_{ nullptr, 0 },
        indexBuffer_{ nullptr, 0 },
        materialBuffer_{ nullptr, 0, 0 }
    {
        CreateMaterials(queueFamilyIndices);
    }

    Mesh::Mesh(std::shared_ptr<const MeshInfo> meshInfo, const LogicalDevice* device,
        MemoryGroup& memoryGroup, const std::vector<std::uint32_t>& queueFamilyIndices) :
        device_{ device },
        meshInfo_{ meshInfo },
        vertexBuffer_{ nullptr, 0 },
        indexBuffer_{ nullptr, 0 },
        materialBuffer_{ nullptr, 0, 0 }
    {
        CreateMaterials(queueFamilyIndices);
    }

    Mesh::Mesh(Mesh&& rhs) noexcept :
        device_{ std::move(rhs.device_) },
        meshInfo_{ std::move(rhs.meshInfo_) },
        memoryGroup_{ std::move(rhs.memoryGroup_) },
        vertexBuffer_{ std::move(rhs.vertexBuffer_) },
        indexBuffer_{ std::move(rhs.indexBuffer_) },
        materialBuffer_{ std::move(rhs.materialBuffer_) },
        materials_{ std::move(rhs.materials_) },
        textureSampler_{ std::move(rhs.textureSampler_) },
        descriptorPool_{ std::move(rhs.descriptorPool_) },
        descriptorSetLayout_{ std::move(rhs.descriptorSetLayout_) },
        materialDescriptorSets_{ std::move(rhs.materialDescriptorSets_) },
        vertexMaterialData_{ std::move(rhs.vertexMaterialData_) }
    {
        rhs.textureSampler_ = vk::Sampler();
        rhs.descriptorPool_ = vk::DescriptorPool();
        rhs.descriptorSetLayout_ = vk::DescriptorSetLayout();
    }

    Mesh& Mesh::operator=(Mesh&& rhs) noexcept
    {
        this->~Mesh();
        device_ = std::move(rhs.device_);
        meshInfo_ = std::move(rhs.meshInfo_);
        memoryGroup_ = std::move(rhs.memoryGroup_);
        vertexBuffer_ = std::move(rhs.vertexBuffer_);
        indexBuffer_ = std::move(rhs.indexBuffer_);
        materialBuffer_ = std::move(rhs.materialBuffer_);
        materials_ = std::move(rhs.materials_);
        textureSampler_ = std::move(rhs.textureSampler_);
        descriptorPool_ = std::move(rhs.descriptorPool_);
        descriptorSetLayout_ = std::move(rhs.descriptorSetLayout_);
        materialDescriptorSets_ = std::move(rhs.materialDescriptorSets_);
        vertexMaterialData_ = std::move(rhs.vertexMaterialData_);
        rhs.textureSampler_ = vk::Sampler();
        rhs.descriptorPool_ = vk::DescriptorPool();
        rhs.descriptorSetLayout_ = vk::DescriptorSetLayout();
        return *this;
    }

    Mesh::~Mesh()
    {
        if (descriptorPool_) device_->GetDevice().destroyDescriptorPool(descriptorPool_);
        descriptorPool_ = vk::DescriptorPool();
        if (descriptorSetLayout_) device_->GetDevice().destroyDescriptorSetLayout(descriptorSetLayout_);
        descriptorSetLayout_ = vk::DescriptorSetLayout();
        if (textureSampler_) device_->GetDevice().destroySampler(textureSampler_);
        textureSampler_ = vk::Sampler();
    }

    void Mesh::CreateMaterials(const std::vector<std::uint32_t>& queueFamilyIndices)
    {
        vk::SamplerCreateInfo samplerCreateInfo{ vk::SamplerCreateFlags(), vk::Filter::eLinear, vk::Filter::eLinear,
            vk::SamplerMipmapMode::eNearest, vk::SamplerAddressMode::eRepeat, vk::SamplerAddressMode::eRepeat,
            vk::SamplerAddressMode::eRepeat };
        textureSampler_ = device_->GetDevice().createSampler(samplerCreateInfo);

        auto numMaterials = meshInfo_->GetMaterials().size();
        std::vector<vk::DescriptorPoolSize> poolSizes;
        poolSizes.emplace_back(vk::DescriptorType::eUniformBuffer, static_cast<std::uint32_t>(numMaterials));
        poolSizes.emplace_back(vk::DescriptorType::eCombinedImageSampler, static_cast<std::uint32_t>(numMaterials * 2));

        vk::DescriptorPoolCreateInfo descriptorPoolInfo{ vk::DescriptorPoolCreateFlags(), static_cast<std::uint32_t>(numMaterials * 3),
            static_cast<std::uint32_t>(poolSizes.size()), poolSizes.data() };

        descriptorPool_ = device_->GetDevice().createDescriptorPool(descriptorPoolInfo);

        // Shared descriptor set layout
        std::vector<vk::DescriptorSetLayoutBinding> setLayoutBindings;
        // Binding 0: UBO
        setLayoutBindings.emplace_back(0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eFragment);
        // Binding 1: Diffuse map
        setLayoutBindings.emplace_back(1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment);
        // Binding 1: Bump map
        setLayoutBindings.emplace_back(2, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment);

        vk::DescriptorSetLayoutCreateInfo descriptorLayoutCreateInfo{ vk::DescriptorSetLayoutCreateFlags(),
            static_cast<std::uint32_t>(setLayoutBindings.size()), setLayoutBindings.data() };

        descriptorSetLayout_ = device_->GetDevice().createDescriptorSetLayout(descriptorLayoutCreateInfo);

        materials_.reserve(numMaterials);
        for (std::size_t i = 0; i < numMaterials; ++i) {
            const auto& mat = meshInfo_->GetMaterials()[i];
            materials_.emplace_back(&mat, device_, *memoryGroup_, queueFamilyIndices);
        }

        // {
        //     vk::PipelineLayoutCreateInfo pipelineLayoutInfo{ vk::PipelineLayoutCreateFlags(),
        //         static_cast<std::uint32_t>(vkDescriptorSetLayouts_.size()), vkDescriptorSetLayouts_.data(), 0, nullptr };
        //     vkPipelineLayout_ = device.GetDevice().createPipelineLayout(pipelineLayoutInfo);
        // }

        // {
        //     std::vector<vk::DescriptorSetLayout> descSetLayouts; descSetLayouts.resize(numUBOBuffers + 1);
        //     descSetLayouts[0] = descSetLayout;
        //     for (auto i = 0U; i < numUBOBuffers; ++i) descSetLayouts[i + 1] = vkDescriptorSetLayouts_[1];
        //     vk::DescriptorSetAllocateInfo descSetAllocInfo{ vkUBODescriptorPool_, static_cast<std::uint32_t>(descSetLayouts.size()), descSetLayouts.data() };
        //     vkUBOSamplerDescritorSets_ = device.GetDevice().allocateDescriptorSets(descSetAllocInfo);
        // }
    }

    void Mesh::CreateDescriptorSets()
    {
        std::vector<vk::DescriptorSetLayout> descSetLayouts; descSetLayouts.resize(materials_.size());
        std::vector<vk::WriteDescriptorSet> descSetWrites; descSetWrites.reserve(materials_.size());
        std::vector<vk::DescriptorBufferInfo> descBufferInfos; descBufferInfos.reserve(materials_.size());
        std::vector<vk::DescriptorImageInfo> descImageInfos; descImageInfos.reserve(materials_.size() * 2);

        for (std::size_t i = 0; i < materials_.size(); ++i) {
            descSetLayouts[i] = descriptorSetLayout_;
        }

        vk::DescriptorSetAllocateInfo descSetAllocInfo{ descriptorPool_, static_cast<std::uint32_t>(descSetLayouts.size()), descSetLayouts.data() };
        materialDescriptorSets_ = device_->GetDevice().allocateDescriptorSets(descSetAllocInfo);

        auto uboOffset = static_cast<std::uint32_t>(std::get<1>(materialBuffer_));
        auto materialBufferSize = static_cast<std::uint32_t>(std::get<2>(materialBuffer_));
        for (std::size_t i = 0; i < materials_.size(); ++i) {
            auto materialBufferOffset = uboOffset + materialBufferSize * i;
            descBufferInfos.emplace_back(std::get<0>(materialBuffer_)->GetBuffer(), materialBufferOffset, materialBufferSize);
            descSetWrites.emplace_back(materialDescriptorSets_[i], 0, static_cast<std::uint32_t>(i), 1,
                vk::DescriptorType::eUniformBuffer, nullptr, &descBufferInfos[i]);

            if (materials_[i].diffuseTexture_) {
                descImageInfos.emplace_back(textureSampler_, materials_[i].diffuseTexture_->GetTexture().GetImageView(), vk::ImageLayout::eShaderReadOnlyOptimal);
            }
            else {
                descImageInfos.emplace_back(vk::Sampler(), vk::ImageView(), vk::ImageLayout::eShaderReadOnlyOptimal);
                // descSetWrites.emplace_back(materialDescriptorSets_[i], 1, static_cast<std::uint32_t>(i), 0, vk::DescriptorType::eCombinedImageSampler, nullptr);
            }
            descSetWrites.emplace_back(materialDescriptorSets_[i], 1, static_cast<std::uint32_t>(i), 1, vk::DescriptorType::eCombinedImageSampler, &descImageInfos[2 * i + 0]);

            if (materials_[i].bumpMap_) {
                descImageInfos.emplace_back(textureSampler_, materials_[i].bumpMap_->GetTexture().GetImageView(), vk::ImageLayout::eShaderReadOnlyOptimal);
            }
            else {
                descImageInfos.emplace_back(vk::Sampler(), vk::ImageView(), vk::ImageLayout::eShaderReadOnlyOptimal);
                // descSetWrites.emplace_back(materialDescriptorSets_[i], 2, static_cast<std::uint32_t>(i), 0, vk::DescriptorType::eCombinedImageSampler, nullptr);
            }
            descSetWrites.emplace_back(materialDescriptorSets_[i], 2, static_cast<std::uint32_t>(i), 1, vk::DescriptorType::eCombinedImageSampler, &descImageInfos[2 * i + 1]);
        }

        device_->GetDevice().updateDescriptorSets(descSetWrites, nullptr);
    }

    void Mesh::UploadMeshData(QueuedDeviceTransfer& transfer)
    {
        assert(memoryGroup_);
        memoryGroup_->FinalizeDeviceGroup();
        memoryGroup_->TransferData(transfer);
        vertexMaterialData_.clear();
    }

    void Mesh::BindBuffersToCommandBuffer(vk::CommandBuffer cmdBuffer) const
    {
        cmdBuffer.bindVertexBuffers(0, 1, vertexBuffer_.first->GetBufferPtr(), &vertexBuffer_.second);
        cmdBuffer.bindIndexBuffer(indexBuffer_.first->GetBuffer(), indexBuffer_.second, vk::IndexType::eUint32);
    }

    void Mesh::DrawMesh(vk::CommandBuffer cmdBuffer, vk::PipelineLayout pipelineLayout, const glm::mat4& worldMatrix) const
    {
        auto meshWorld = meshInfo_->GetRootTransform() * worldMatrix;
        // TODO: add depth sorting here...
        DrawMeshNode(cmdBuffer, pipelineLayout, meshInfo_->GetRootNode(), meshWorld);

        // TODO: use submeshes and materials and the scene nodes...
        // need:
        // - for each submesh: 2 texture descriptors
        // - for each scene mesh node: uniform buffer?
        // - uniform buffer for all materials[array] (via template)
        // - push constant for world matrix
        // - push constant for material index .. or "VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC"
        // cmdBuffer.drawIndexed(static_cast<std::uint32_t>(meshInfo_->GetIndices().size()), 1, 0, 0, 0);
    }

    void Mesh::DrawMeshNode(vk::CommandBuffer cmdBuffer, vk::PipelineLayout pipelineLayout,
        const SceneMeshNode* node, const glm::mat4& worldMatrix) const
    {
        auto nodeWorld = node->GetLocalTransform() * worldMatrix;
        for (unsigned int i = 0; i < node->GetNumberOfSubMeshes(); ++i) DrawSubMesh(cmdBuffer, pipelineLayout, meshInfo_->GetSubMesh(node->GetSubMeshID(i)), nodeWorld);
        for (unsigned int i = 0; i < node->GetNumberOfNodes(); ++i) DrawMeshNode(cmdBuffer, pipelineLayout, node->GetChild(i), nodeWorld);
    }

    void Mesh::DrawSubMesh(vk::CommandBuffer cmdBuffer, vk::PipelineLayout pipelineLayout, const SubMesh* subMesh, const glm::mat4& worldMatrix) const
    {
        auto worldMat = worldMatrix;
        auto normalMat = glm::inverseTranspose(glm::mat3(worldMatrix));
        auto& mat = materials_[subMesh->GetMaterialID()];
        auto& matDescSets = materialDescriptorSets_[subMesh->GetMaterialID()];

        // bind material ubo.
        cmdBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipelineLayout, 0, materialDescriptorSets_, nullptr);
        cmdBuffer.pushConstants(pipelineLayout, vk::ShaderStageFlagBits::eVertex, 0, vk::ArrayProxy<const float>(16, glm::value_ptr(worldMat)));
        cmdBuffer.pushConstants(pipelineLayout, vk::ShaderStageFlagBits::eVertex, 16, vk::ArrayProxy<const float>(9, glm::value_ptr(normalMat)));
        cmdBuffer.drawIndexed(static_cast<std::uint32_t>(subMesh->GetNumberOfIndices()), 1, static_cast<std::uint32_t>(subMesh->GetIndexOffset()), 0, 0);
    }

    void Mesh::SetVertexBuffer(const DeviceBuffer* vtxBuffer, std::size_t offset)
    {
        vertexBuffer_.first = vtxBuffer;
        vertexBuffer_.second = offset;
    }

    void Mesh::SetIndexBuffer(const DeviceBuffer* idxBuffer, std::size_t offset)
    {
        indexBuffer_.first = idxBuffer;
        indexBuffer_.second = offset;
    }

    void Mesh::SetMaterialBuffer(const DeviceBuffer* matBuffer, std::size_t offset, std::size_t elementSize)
    {
        materialBuffer_ = std::make_tuple(matBuffer, offset, elementSize);
    }
}
<|endoftext|>