repo_id
stringlengths 19
138
| file_path
stringlengths 32
200
| content
stringlengths 1
12.9M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/replay/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
py_binary(
name = "replay_file",
srcs = ["replay_file.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//modules/tools/common:message_manager",
"//modules/tools/common:proto_utils",
],
)
install(
name = "install",
py_dest = "tools/replay",
targets = [
":replay_file",
],
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/routing/road_show.py
|
#!/usr/bin/env python3
###############################################################################
# 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.
###############################################################################
"""Show road."""
import sys
import matplotlib.pyplot as plt
import modules.tools.common.proto_utils as proto_utils
import modules.tools.routing.util as util
g_color = [
'navy', 'c', 'cornflowerblue', 'gold', 'darkorange', 'darkviolet',
'aquamarine', 'firebrick', 'limegreen'
]
def draw_line(line_segment, color):
"""
:param line_segment:
:return: none
"""
px, py = proto_utils.flatten(line_segment.point, ['x', 'y'])
px, py = downsample_array(px), downsample_array(py)
plt.gca().plot(px, py, lw=10, alpha=0.8, color=color)
return px[len(px) // 2], py[len(py) // 2]
def draw_arc(arc):
"""
:param arc: proto obj
:return: none
"""
xy = (arc.center.x, arc.center.y)
start = 0
end = 0
if arc.start_angle < arc.end_angle:
start = arc.start_angle / math.pi * 180
end = arc.end_angle / math.pi * 180
else:
end = arc.start_angle / math.pi * 180
start = arc.end_angle / math.pi * 180
pac = mpatches.Arc(
xy, arc.radius * 2, arc.radius * 2, angle=0, theta1=start, theta2=end)
plt.gca().add_patch(pac)
def downsample_array(array):
"""down sample given array"""
skip = 5
result = array[::skip]
result.append(array[-1])
return result
def draw_boundary(line_segment):
"""
:param line_segment:
:return:
"""
px, py = proto_utils.flatten(line_segment.point, ['x', 'y'])
px, py = downsample_array(px), downsample_array(py)
plt.gca().plot(px, py, 'k')
def draw_id(x, y, id_string):
"""Draw id_string on (x, y)"""
plt.annotate(
id_string,
xy=(x, y),
xytext=(40, -40),
textcoords='offset points',
ha='right',
va='bottom',
bbox=dict(boxstyle='round,pad=0.5', fc='green', alpha=0.5),
arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))
def get_road_index_of_lane(lane_id, road_lane_set):
"""Get road index of lane"""
for i, lane_set in enumerate(road_lane_set):
if lane_id in lane_set:
return i
return -1
def draw_map(drivemap):
""" draw map from mapfile"""
print('Map info:')
print('\tVersion:\t', end=' ')
print(drivemap.header.version)
print('\tDate:\t', end=' ')
print(drivemap.header.date)
print('\tDistrict:\t', end=' ')
print(drivemap.header.district)
road_lane_set = []
for road in drivemap.road:
lanes = []
for sec in road.section:
lanes.extend(proto_utils.flatten(sec.lane_id, 'id'))
road_lane_set.append(lanes)
for lane in drivemap.lane:
for curve in lane.central_curve.segment:
if curve.HasField('line_segment'):
road_idx = get_road_index_of_lane(lane.id.id, road_lane_set)
if road_idx == -1:
print('Failed to get road index of lane')
sys.exit(-1)
center_x, center_y = draw_line(curve.line_segment,
g_color[road_idx % len(g_color)])
draw_id(center_x, center_y, str(road_idx))
# break
# if curve.HasField('arc'):
# draw_arc(curve.arc)
for curve in lane.left_boundary.curve.segment:
if curve.HasField('line_segment'):
draw_boundary(curve.line_segment)
for curve in lane.right_boundary.curve.segment:
if curve.HasField('line_segment'):
draw_boundary(curve.line_segment)
# break
return drivemap
if __name__ == "__main__":
print("Reading map data")
map_dir = util.get_map_dir(sys.argv)
base_map = util.get_mapdata(map_dir)
print("Done reading map data")
plt.subplots()
draw_map(base_map)
plt.axis('equal')
plt.show()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/routing/debug_route.py
|
#!/usr/bin/env python3
###############################################################################
# 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.
###############################################################################
import itertools
import os
import sys
import gflags
import matplotlib.pyplot as plt
import modules.tools.routing.debug_topo as debug_topo
import modules.routing.proto.topo_graph_pb2 as topo_graph_pb2
import modules.tools.routing.util as util
color_iter = itertools.cycle(
['navy', 'c', 'cornflowerblue', 'gold', 'darkorange'])
def read_route(route_file_name):
"""Read route result text file"""
fin = open(route_file_name)
route = []
for line in fin:
lane = {}
items = line.strip().split(',')
lane['id'] = items[0]
lane['is virtual'] = int(items[1])
lane['start s'] = float(items[2])
lane['end s'] = float(items[3])
route.append(lane)
return route
def plot_route(lanes, central_curve_dict):
"""Plot route result"""
plt.close()
plt.figure()
for lane in lanes:
lane_id = lane['id']
if lane['is virtual']:
color = 'red'
else:
color = 'green'
mid_pt = debug_topo.plot_central_curve_with_s_range(
central_curve_dict[lane_id],
lane['start s'],
lane['end s'],
color=color)
debug_topo.draw_id(mid_pt, lane_id, 'y')
plt.gca().set_aspect(1)
plt.title('Routing result')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.draw()
def print_help_command():
"""Print command help information.
Print help information of command.
Args:
"""
print('type in command: [q] [r]')
print(' q exit')
print(' r plot route result')
print(' r_map plot route result with map')
if __name__ == '__main__':
map_dir = util.get_map_dir(sys.argv)
graph = util.get_topodata(map_dir)
base_map = util.get_mapdata(map_dir)
route = util.get_routingdata()
central_curves = {}
for nd in graph.node:
central_curves[nd.lane_id] = nd.central_curve
plt.ion()
while 1:
print_help_command()
print('cmd>', end=' ')
instruction = raw_input()
argv = instruction.strip(' ').split(' ')
if len(argv) == 1:
if argv[0] == 'q':
sys.exit(0)
elif argv[0] == 'r':
plot_route(route, central_curves)
elif argv[0] == 'r_map':
plot_route(route, central_curves)
util.draw_map(plt.gca(), base_map)
else:
print('[ERROR] wrong command')
continue
else:
print('[ERROR] wrong arguments')
continue
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/routing/debug_passage_region.py
|
#!/usr/bin/env python3
###############################################################################
# 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.
###############################################################################
import itertools
import sys
import matplotlib.pyplot as plt
import modules.tools.common.proto_utils as proto_utils
import modules.tools.routing.debug_topo as debug_topo
from modules.common_msgs.routing_msgs.routing_pb2 import RoutingResponse
from modules.routing.proto.topo_graph_pb2 import Graph
color_iter = itertools.cycle(
['navy', 'c', 'cornflowerblue', 'gold', 'darkorange'])
g_central_curve_dict = {}
g_center_point_dict = {}
def get_center_of_passage_region(region):
"""Get center of passage region center curve"""
center_points = [g_center_point_dict[seg.id] for seg in region.segment]
return center_points[len(center_points) // 2]
def plot_region(region, color):
"Plot passage region"
for seg in region.segment:
center_pt = debug_topo.plot_central_curve_with_s_range(
g_central_curve_dict[seg.id], seg.start_s, seg.end_s, color=color)
debug_topo.draw_id(center_pt, seg.id, 'r')
g_center_point_dict[seg.id] = center_pt
print('Plot lane id: %s, start s: %f, end s: %f' % (seg.id, seg.start_s,
seg.end_s))
def plot_lane_change(lane_change, passage_regions):
"""Plot lane change information"""
st_idx = lane_change.start_passage_region_index
ed_idx = lane_change.end_passage_region_index
from_pt = get_center_of_passage_region(passage_regions[st_idx])
to_pt = get_center_of_passage_region(passage_regions[ed_idx])
plt.gca().annotate(
"",
xy=(to_pt[0], to_pt[1]),
xytext=(from_pt[0], from_pt[1]),
arrowprops=dict(
facecolor='blue', edgecolor='none', alpha=0.7, shrink=0.05))
def plot_road(road):
"""Plot road"""
for region in road.passage_region:
plot_region(region, 'green')
for lane_change in road.lane_change_info:
plot_lane_change(lane_change, road.passage_region)
def plot_junction(junction):
"""Plot junction"""
plot_region(junction.passage_region, 'red')
def plot_result(routing_result, central_curve_dict):
"""Plot routing result"""
plt.close()
plt.figure()
for way in routing_result.route:
if way.HasField("road_info"):
plot_road(way.road_info)
else:
plot_junction(way.junction_info)
plt.gca().set_aspect(1)
plt.title('Passage region')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.draw()
def print_help():
"""Print help information.
Print help information of usage.
Args:
"""
print('usage:')
print(' python debug_topo.py file_path, then', end=' ')
print_help_command()
def print_help_command():
"""Print command help information.
Print help information of command.
Args:
"""
print('type in command: [q] [r]')
print(' q exit')
print(' p plot passage region')
if __name__ == '__main__':
if len(sys.argv) != 3:
print_help()
sys.exit(0)
print('Please wait for loading data...')
topo_graph_file = sys.argv[1]
graph = proto_utils.get_pb_from_bin_file(topo_graph_file, Graph())
g_central_curve_dict = {nd.lane_id: nd.central_curve for nd in graph.node}
plt.ion()
while 1:
print_help_command()
print('cmd>', end=' ')
instruction = raw_input()
argv = instruction.strip(' ').split(' ')
if len(argv) == 1:
if argv[0] == 'q':
sys.exit(0)
elif argv[0] == 'p':
routing_result_file = sys.argv[2]
result = proto_utils.get_pb_from_bin_file(routing_result_file,
RoutingResponse())
plot_result(result, g_central_curve_dict)
else:
print('[ERROR] wrong command')
continue
else:
print('[ERROR] wrong arguments')
continue
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/routing/util.py
|
#!/usr/bin/env python3
###############################################################################
# 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.
###############################################################################
import os
import sys
import gflags
import matplotlib.pyplot as plt
import modules.tools.common.proto_utils as proto_utils
import modules.common_msgs.map_msgs.map_pb2 as map_pb2
import modules.routing.proto.topo_graph_pb2 as topo_graph_pb2
import modules.common_msgs.routing_msgs.routing_pb2 as routing_pb2
from pathlib import Path
FLAGS = gflags.FLAGS
gflags.DEFINE_string('map_dir', 'modules/map/data/demo', 'map directory')
def check_file(file_path, origin_apollo_path):
file_wrapper = Path(file_path)
if not file_wrapper.exists():
file_wrapper = Path(origin_apollo_path)
if not file_wrapper.exists():
print("Can not find {}, exit".format(str(file_wrapper)))
exit(-1)
return str(file_wrapper)
def get_map_dir(argv):
sys.argv.insert(1, '--undefok')
flagfile = os.path.normpath(
os.path.join(
os.path.dirname(__file__), '../../common/data',
'global_flagfile.txt'))
flagfile = check_file(flagfile, "/apollo/modules/common/data/global_flagfile.txt")
sys.argv.insert(2, '--flagfile=' + flagfile)
argv = FLAGS(sys.argv)
mapdir = os.path.normpath(
os.path.join(os.path.dirname(__file__), '../../../', FLAGS.map_dir))
print("Map dir: %s " % FLAGS.map_dir)
return mapdir
def get_mapdata(map_dir):
print('Please wait for loading map data...')
map_data_path = os.path.join(map_dir, 'base_map.bin')
print('File: %s' % map_data_path)
return proto_utils.get_pb_from_bin_file(map_data_path, map_pb2.Map())
def get_topodata(map_dir):
print('Please wait for loading routing topo data...')
topo_data_path = os.path.join(map_dir, 'routing_map.bin')
print("File: %s" % topo_data_path)
return proto_utils.get_pb_from_bin_file(topo_data_path, topo_graph_pb2.Graph())
def get_routingdata():
print('Please wait for loading route response data...')
log_dir = os.path.normpath(
os.path.join('/apollo/data/log'))
route_data_path = os.path.join(log_dir, 'passage_region_debug.bin')
print("File: %s" % route_data_path)
return proto_utils.get_pb_from_text_file(route_data_path, routing_pb2.RoutingResponse())
def onclick(event):
"""Event function when mouse left button is clicked"""
print('\nClick captured! x=%f\ty=%f' % (event.xdata, event.ydata))
print('cmd>')
def downsample_array(array, step=5):
"""Down sample given array"""
result = array[::step]
result.append(array[-1])
return result
def draw_boundary(ax, line_segment):
"""
:param line_segment:
:return:
"""
px = [float(p.x) for p in line_segment.point]
py = [float(p.y) for p in line_segment.point]
px = downsample_array(px)
py = downsample_array(py)
ax.plot(px, py, 'k', lw=0.4)
def draw_map(ax, mapfile):
"""Draw map from mapfile"""
for lane in mapfile.lane:
for curve in lane.left_boundary.curve.segment:
if curve.HasField('line_segment'):
draw_boundary(ax, curve.line_segment)
for curve in lane.right_boundary.curve.segment:
if curve.HasField('line_segment'):
draw_boundary(ax, curve.line_segment)
plt.draw()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/routing/debug_topo.py
|
#!/usr/bin/env python3
###############################################################################
# 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.
###############################################################################
import itertools
import math
import sys
import matplotlib.pyplot as plt
import modules.tools.common.proto_utils as proto_utils
import modules.routing.proto.topo_graph_pb2 as topo_graph_pb2
import modules.tools.routing.util as util
color_iter = itertools.cycle(
['navy', 'c', 'cornflowerblue', 'gold', 'darkorange'])
def calculate_s(px, py):
"""Calculate s array based on x and y arrays"""
dis = 0.0
ps = [dis]
for i in range(len(px) - 1):
gap = math.sqrt(pow(px[i + 1] - px[i], 2) + pow(py[i + 1] - py[i], 2))
dis = dis + gap
ps.append(dis)
return ps
def draw_line(line, color):
"""draw line, return x array and y array"""
px, py = proto_utils.flatten(line.point, ['x', 'y'])
px, py = util.downsample_array(px), util.downsample_array(py)
plt.gca().plot(px, py, color=color, lw=3, alpha=0.8)
return px, py
def draw_arc(arc):
"""draw arc"""
xy = (arc.center.x, arc.center.y)
start = 0
end = 0
if arc.start_angle < arc.end_angle:
start = arc.start_angle / math.pi * 180
end = arc.end_angle / math.pi * 180
else:
end = arc.start_angle / math.pi * 180
start = arc.end_angle / math.pi * 180
pac = mpatches.Arc(
xy, arc.radius * 2, arc.radius * 2, angle=0, theta1=start, theta2=end)
plt.gca().add_patch(pac)
def draw_id(coordinate, id_string, color):
"""draw id"""
x = coordinate[0]
y = coordinate[1]
plt.annotate(
id_string,
xy=(x, y),
xytext=(30, 30),
textcoords='offset points',
bbox=dict(boxstyle='round,pad=0.5', fc=color, alpha=0.5),
arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'),
horizontalalignment='right',
verticalalignment='bottom')
def plot_central_curve_with_s_range(central_curve, start_s, end_s, color):
"""plot topology graph node with given start and end s, return middle point"""
node_x = []
node_y = []
for curve in central_curve.segment:
px, py = proto_utils.flatten(curve.line_segment.point, ['x', 'y'])
node_x.extend(px)
node_y.extend(py)
start_plot_index = 0
end_plot_index = len(node_x)
node_s = calculate_s(node_x, node_y)
for i in range(len(node_s)):
if node_s[i] >= start_s:
start_plot_index = i
break
for i in range(len(node_s) - 1, -1, -1):
if node_s[i] <= end_s:
end_plot_index = i + 1
break
plt.gca().plot(
node_x[start_plot_index:end_plot_index],
node_y[start_plot_index:end_plot_index],
color=color,
lw=3,
alpha=0.8)
mid_index = (start_plot_index + end_plot_index) // 2
return [node_x[mid_index], node_y[mid_index]]
def plot_central_curve(central_curve, color):
"""plot topology graph node, return node middle point"""
node_x = []
node_y = []
for curve in central_curve.segment:
if curve.HasField('line_segment'):
px, py = draw_line(curve.line_segment, color)
node_x = node_x + px
node_y = node_y + py
# if curve.HasField('arc'):
# draw_arc(curve.arc)
return [node_x[len(node_x) // 2], node_y[len(node_y) // 2]]
def plot_node(node, plot_id, color):
"""plot topology graph node"""
print('length of %s: %f' % (node.lane_id, node.length))
mid_pt = plot_central_curve(node.central_curve, color)
if 'l' in plot_id:
draw_id(mid_pt, node.lane_id, 'green')
if 'r' in plot_id:
draw_id(mid_pt, node.road_id, 'red')
return mid_pt
def plot_edge(edge, midddle_point_map):
"""plot topology graph edge"""
if edge.direction_type == topo_graph_pb2.Edge.FORWARD:
return
# if lane change is allowed, draw an arrow from lane with from_id to lane with to_id
from_id = edge.from_lane_id
from_pt = midddle_point_map[from_id]
to_id = edge.to_lane_id
to_pt = midddle_point_map[to_id]
plt.gca().annotate(
"",
xy=(to_pt[0], to_pt[1]),
xytext=(from_pt[0], from_pt[1]),
arrowprops=dict(arrowstyle="->", connectionstyle="arc3"))
def plot_all(graph, plot_id=''):
"""plot topology graph"""
plt.close()
fig = plt.figure()
fig.canvas.mpl_connect('button_press_event', util.onclick)
lane_middle_point_map = {}
for i, (nd, color) in enumerate(zip(graph.node, color_iter)):
nd_mid_pt = plot_node(nd, plot_id, color)
lane_middle_point_map[nd.lane_id] = nd_mid_pt
for i, eg in enumerate(graph.edge):
plot_edge(eg, lane_middle_point_map)
plt.gca().set_aspect(1)
plt.title('Routing topology graph')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.draw()
def plot_id(graph, lane_id):
"""plot topology graph"""
plt.close()
fig = plt.figure()
fig.canvas.mpl_connect('button_press_event', util.onclick)
lane_middle_point_map = {}
plot_ids = [lane_id]
for eg in graph.edge:
if eg.from_lane_id == lane_id:
plot_ids.append(eg.to_lane_id)
for i, (nd, color) in enumerate(zip(graph.node, color_iter)):
if nd.lane_id in plot_ids:
nd_mid_pt = plot_node(nd, 'l', color)
lane_middle_point_map[nd.lane_id] = nd_mid_pt
for i, eg in enumerate(graph.edge):
if eg.from_lane_id == lane_id:
plot_edge(eg, lane_middle_point_map)
plt.gca().set_aspect(1)
plt.title('Routing topology graph')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.draw()
def print_help_command():
"""Print command help information.
Print help information of command.
Args:
"""
print('type in command: [q] [a] [i lane_id]')
print(' q exit')
print(' a plot all topology')
print(' a_id plot all topology with lane id')
print(' a_rid plot all topology with road id')
print(' i lane_id plot lanes could be reached from lane with lane_id')
print(' i_map lane_id plot lanes could be reached from lane with lane_id, with map')
if __name__ == '__main__':
map_dir = util.get_map_dir(sys.argv)
graph = util.get_topodata(map_dir)
base_map = util.get_mapdata(map_dir)
print("district: %s" % graph.hdmap_district)
print("version: %s" % graph.hdmap_version)
plt.ion()
while 1:
print_help_command()
print('cmd>', end=' ')
instruction = raw_input()
argv = instruction.strip(' ').split(' ')
if len(argv) == 1:
if argv[0] == 'q':
sys.exit(0)
elif argv[0] == 'a':
plot_all(graph)
elif argv[0] == 'a_id':
plot_all(graph, 'l')
elif argv[0] == 'a_rid':
plot_all(graph, 'r')
else:
print('[ERROR] wrong command')
continue
if len(argv) == 2:
if argv[0] == 'i':
plot_id(graph, argv[1])
elif argv[0] == 'i_map':
plot_id(graph, argv[1])
util.draw_map(plt.gca(), base_map)
else:
print('[ERROR] wrong command')
continue
else:
print('[ERROR] wrong arguments')
continue
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/routing/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary", "py_library")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
install(
name = "install",
py_dest = "tools/routing",
targets = [
":debug_passage_region",
":debug_route",
":road_show",
],
)
py_binary(
name = "debug_passage_region",
srcs = ["debug_passage_region.py"],
deps = [
":debug_topo",
"//modules/common_msgs/routing_msgs:routing_py_pb2",
"//modules/routing/proto:topo_graph_py_pb2",
"//modules/tools/common:proto_utils",
],
)
py_binary(
name = "debug_route",
srcs = ["debug_route.py"],
deps = [
":debug_topo",
":util",
"//modules/routing/proto:topo_graph_py_pb2",
"//modules/tools/common:proto_utils",
],
)
py_library(
name = "debug_topo",
srcs = ["debug_topo.py"],
deps = [
":util",
"//modules/routing/proto:topo_graph_py_pb2",
"//modules/tools/common:proto_utils",
],
)
py_binary(
name = "road_show",
srcs = ["road_show.py"],
deps = [
":util",
"//modules/tools/common:proto_utils",
],
)
py_library(
name = "util",
srcs = ["util.py"],
deps = [
"//modules/common_msgs/map_msgs:map_py_pb2",
"//modules/common_msgs/routing_msgs:routing_py_pb2",
"//modules/routing/proto:topo_graph_py_pb2",
"//modules/tools/common:proto_utils",
],
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/perception/garage_perception.bash
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2020 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.
###############################################################################
cd "$(dirname "${BASH_SOURCE[0]}")"
source "/apollo/scripts/apollo_base.sh"
/apollo/bazel-bin/modules/tools/perception/replay_perception garage_*.json
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/perception/extend_prediction.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2019 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.
###############################################################################
"""
print received prediction message
"""
import argparse
import math
import sys
import numpy
import modules.tools.common.proto_utils as proto_utils
from modules.common_msgs.prediction_msgs.prediction_obstacle_pb2 import PredictionObstacles
def distance(p1, p2):
"""distance between two trajectory points"""
return math.sqrt((p1.y - p2.y)**2 + (p1.x - p2.x)**2)
def get_trajectory_length(trajectory):
"""get_trajectory_length"""
total = 0.0
for i in range(1, len(trajectory.trajectory_point)):
total += distance(trajectory.trajectory_point[i - 1].path_point,
trajectory.trajectory_point[i].path_point)
return total
def extend_prediction(prediction, min_length, min_time):
"""extend prediction"""
for obstacle in prediction.prediction_obstacle:
i = 0
for trajectory in obstacle.trajectory:
points = trajectory.trajectory_point
point_num = len(points)
trajectory_length = get_trajectory_length(trajectory)
sys.stderr.write("obstacle_id :%s trajectory_id: %s length: %s\n" % (
obstacle.perception_obstacle.id, i, trajectory_length))
i += 1
if trajectory_length < min_length:
second_last = points[point_num - 2]
last_point = points[point_num - 1]
x_diff = last_point.path_point.x - second_last.path_point.x
y_diff = last_point.path_point.y - second_last.path_point.y
t_diff = last_point.path_point.theta - second_last.path_point.theta
delta_diff = math.sqrt(x_diff ** 2 + y_diff ** 2)
cur_len = trajectory_length
while cur_len < min_length and abs(cur_len) > 0.000001:
last_point.path_point.x += x_diff
last_point.path_point.y += y_diff
last_point.path_point.theta += t_diff
p = points.add()
p.CopyFrom(last_point)
last_point = p
cur_len += delta_diff
return prediction
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="extend prediction trajectory")
parser.add_argument("prediction", action="store",
type=str, help="set the prediction file")
parser.add_argument("-p", "--period", action="store", type=float, default=10.0,
help="set the prediction period")
parser.add_argument("-d", "--distance", action="store", type=float, default=70.0,
help="set the prediction distance")
args = parser.parse_args()
prediction_data = proto_utils.get_pb_from_file(
args.prediction, PredictionObstacles())
extended_prediction = extend_prediction(
prediction_data, args.distance, args.period)
print(extended_prediction)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/perception/garage_onroad_vehicle_3.json
|
{
"id": 3,
"position": [586376.36731545243, 4140677.2173802247, 0.0],
"theta": 1.1659045405098132,
"length": 4,
"width": 2,
"height": 1,
"speed": 8.0,
"tracking_time": 1.0,
"type": "VEHICLE",
"trace": [
[586392.84003, 4140673.01232, 0.0],
[586391.48345350777, 4140673.3586190776, 0.0],
[586389.93308037391, 4140673.7543894518, 0.0],
[586388.38270724006, 4140674.1501598256, 0.0],
[586386.83233410609, 4140674.5459302, 0.0],
[586385.28196097224, 4140674.941700574, 0.0],
[586383.92538448, 4140675.2879996509, 0.0],
[586382.37501134619, 4140675.6837700251, 0.0],
[586380.82463821233, 4140676.0795403994, 0.0],
[586379.27426507848, 4140676.4753107731, 0.0],
[586377.72389194451, 4140676.8710811473, 0.0],
[586376.36731545243, 4140677.2173802247, 0.0],
[586374.81694231846, 4140677.6131505985, 0.0],
[586373.26656918461, 4140678.0089209727, 0.0],
[586371.71619605075, 4140678.4046913465, 0.0],
[586370.1658229169, 4140678.8004617207, 0.0],
[586368.8092464247, 4140679.1467607981, 0.0],
[586367.25887329085, 4140679.5425311718, 0.0],
[586365.708500157, 4140679.938301546, 0.0],
[586364.158127023, 4140680.3340719203, 0.0],
[586362.60775388917, 4140680.729842294, 0.0],
[586361.05738075532, 4140681.1256126682, 0.0],
[586359.70080426312, 4140681.4719117456, 0.0],
[586358.15043112927, 4140681.8676821194, 0.0],
[586356.60005799541, 4140682.2634524936, 0.0],
[586355.04968486144, 4140682.6592228673, 0.0],
[586353.49931172759, 4140683.0549932416, 0.0],
[586352.14273523539, 4140683.4012923189, 0.0],
[586350.59236210154, 4140683.7970626927, 0.0],
[586349.04198896769, 4140684.1928330669, 0.0],
[586347.569402928, 4140684.6569425897, 0.0],
[586346.34040037962, 4140685.3234600914, 0.0],
[586345.30744645279, 4140686.0166505864, 0.0],
[586344.29222947382, 4140686.9242762327, 0.0],
[586343.56665382232, 4140688.0126865744, 0.0],
[586342.949612425, 4140689.1510837893, 0.0],
[586342.55869757663, 4140690.3676857753, 0.0],
[586342.55462259543, 4140691.4767941991, 0.0],
[586342.6637494904, 4140692.8428249569, 0.0],
[586342.99203702353, 4140694.4008130711, 0.0],
[586343.35804034967, 4140695.9494921896, 0.0],
[586343.75255533273, 4140697.4911341346, 0.0],
[586344.16637783637, 4140699.0280107288, 0.0],
[586344.537075054, 4140700.3706546258, 0.0],
[586344.962295973, 4140701.904718264, 0.0],
[586345.38318794768, 4140703.4398507774, 0.0],
[586345.80090989673, 4140704.9757669368, 0.0],
[586346.21787014115, 4140706.5118733062, 0.0],
[586346.58354364219, 4140707.8557630088, 0.0],
[586347.00225746073, 4140709.3914409908, 0.0],
[586347.42124613957, 4140710.9270518012, 0.0],
[586347.83999702206, 4140712.4627208482, 0.0],
[586348.25850161957, 4140713.9984501684, 0.0],
[586348.62461901968, 4140715.3422314571, 0.0],
[586349.04308792681, 4140716.8779694913, 0.0],
[586349.4616301487, 4140718.4136895789, 0.0],
[586349.88020279026, 4140719.9494022224, 0.0],
[586350.2987647875, 4140721.4851174741, 0.0],
[586350.66498962464, 4140722.8288724585, 0.0],
[586351.08352311642, 4140724.3645946868, 0.0],
[586351.502057768, 4140725.9003166305, 0.0],
[586351.92059813277, 4140727.4360371758, 0.0],
[586352.33914143045, 4140728.9717570036, 0.0],
[586352.75768457341, 4140730.507476869, 0.0],
[586353.12390853534, 4140731.8512320668, 0.0],
[586353.54244935873, 4140733.3869525003, 0.0],
[586353.96099008131, 4140734.9226729581, 0.0],
[586354.37953121448, 4140736.4583933158, 0.0],
[586354.798072612, 4140737.9941136083, 0.0],
[586355.16429637477, 4140739.3378688549, 0.0],
[586355.582837717, 4140740.8735891613, 0.0],
[586356.00137897744, 4140742.4093094873, 0.0],
[586356.41992021643, 4140743.9450298189, 0.0],
[586356.8384614815, 4140745.4807501445, 0.0],
[586357.20468510769, 4140746.8245054241, 0.0],
[586357.62322640244, 4140748.3602257422, 0.0],
[586358.04176769149, 4140749.8959460612, 0.0],
[586358.46030897368, 4140751.4316663826, 0.0],
[586358.8788502533, 4140752.9673867039, 0.0],
[586359.245073874, 4140754.3111419855, 0.0],
[586359.66361515666, 4140755.8468623064, 0.0],
[586360.08215644024, 4140757.3825826268, 0.0],
[586360.50069772359, 4140758.9183029477, 0.0],
[586360.91923900647, 4140760.4540232685, 0.0],
[586361.337780289, 4140761.9897435894, 0.0],
[586361.70400391135, 4140763.33349887, 0.0],
[586362.122545194, 4140764.8692191909, 0.0],
[586362.54108647688, 4140766.4049395118, 0.0],
[586362.95962775976, 4140767.9406598327, 0.0],
[586363.37816904252, 4140769.4763801536, 0.0],
[586363.74439266487, 4140770.8201354346, 0.0],
[586364.16293394763, 4140772.3558557555, 0.0],
[586364.5814752304, 4140773.8915760764, 0.0],
[586365.00001651316, 4140775.4272963973, 0.0],
[586365.418557796, 4140776.9630167182, 0.0],
[586365.78478141839, 4140778.3067719988, 0.0],
[586366.20332270127, 4140779.8424923196, 0.0],
[586366.621863984, 4140781.3782126405, 0.0],
[586367.0404052668, 4140782.9139329614, 0.0],
[586367.45894654957, 4140784.4496532823, 0.0]
]
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/perception/garage_onroad_static_4.json
|
{
"id": 1,
"position": [586347.42124613957, 4140710.9270518012, 0.0],
"theta": 1.1659045405098132,
"length": 4,
"width": 2,
"height": 1,
"speed": 0.0,
"tracking_time": 1.0,
"type": "UNKNOWN_UNMOVABLE"
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/perception/empty_prediction.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2019 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.
###############################################################################
"""
this module creates a node and fake prediction data based
on json configurations
"""
import argparse
import math
import time
import numpy
import simplejson
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3 import cyber_time
from modules.common_msgs.prediction_msgs.prediction_obstacle_pb2 import PredictionObstacles
def prediction_publisher(prediction_channel, rate):
"""publisher"""
cyber.init()
node = cyber.Node("prediction")
writer = node.create_writer(prediction_channel, PredictionObstacles)
sleep_time = 1.0 / rate
seq_num = 1
while not cyber.is_shutdown():
prediction = PredictionObstacles()
prediction.header.sequence_num = seq_num
prediction.header.timestamp_sec = cyber_time.Time.now().to_sec()
prediction.header.module_name = "prediction"
print(str(prediction))
writer.write(prediction)
seq_num += 1
time.sleep(sleep_time)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="create empty prediction message",
prog="replay_prediction.py")
parser.add_argument("-c", "--channel", action="store", type=str, default="/apollo/prediction",
help="set the prediction channel")
parser.add_argument("-r", "--rate", action="store", type=int, default=10,
help="set the prediction channel publish time duration")
args = parser.parse_args()
prediction_publisher(args.channel, args.rate)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/perception/print_perception.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2019 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.
###############################################################################
"""
print received perception message
"""
import argparse
from cyber.python.cyber_py3 import cyber
from modules.common_msgs.perception_msgs.perception_obstacle_pb2 import PerceptionObstacles
def receiver(data):
"""receiver"""
print(data)
def perception_receiver(perception_channel):
"""publisher"""
cyber.init()
node = cyber.Node("perception")
node.create_reader(perception_channel, PerceptionObstacles, receiver)
node.spin()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="create fake perception obstacles",
prog="print_perception.py")
parser.add_argument("-c", "--channel", action="store", type=str,
default="/apollo/perception/obstacles",
help="set the perception channel")
args = parser.parse_args()
perception_receiver(args.channel)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/perception/garage_offroad_static_1.json
|
{
"id": 1,
"position": [-1855.5, -2961.51, 0],
"theta": 1.1659045405098132,
"length": 4,
"width": 2,
"height": 1,
"speed": 0.0,
"tracking_time": 1.0,
"type": "UNKNOWN_UNMOVABLE"
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/perception/garage_cross_vehicle_2.json
|
{
"id": 2,
"position": [-1868.59, -2990.91, 0.0],
"theta": 1.1659045405098132,
"length": 4,
"width": 2,
"height": 1,
"speed": 8.0,
"tracking_time": 1.0,
"type": "VEHICLE",
"trace": [[-1868.59, -2990.91, 0.0],
[-1845.16, -2994.59, 0.0],
[-1850.16, -3000.0, 0.0]]
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/perception/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "garage_config",
srcs = glob(["*.json"]) + ["garage_perception.bash"],
)
py_binary(
name = "empty_prediction",
srcs = ["empty_prediction.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:cyber_time",
"//modules/common_msgs/prediction_msgs:prediction_obstacle_py_pb2",
],
)
py_binary(
name = "extend_prediction",
srcs = ["extend_prediction.py"],
deps = [
"//modules/common_msgs/prediction_msgs:prediction_obstacle_py_pb2",
"//modules/tools/common:proto_utils",
],
)
py_binary(
name = "print_perception",
srcs = ["print_perception.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//modules/common_msgs/perception_msgs:perception_obstacle_py_pb2",
],
)
py_binary(
name = "replay_perception",
srcs = ["replay_perception.py"],
data = [":garage_config"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:cyber_time",
"//modules/common_msgs/basic_msgs:geometry_py_pb2",
"//modules/common_msgs/perception_msgs:perception_obstacle_py_pb2",
],
)
install(
name = "install",
data_dest = "tools/perception",
py_dest = "tools/perception",
targets = [
":empty_prediction",
":extend_prediction",
":print_perception",
":replay_perception"
]
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/perception/replay_perception.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2019 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.
###############################################################################
"""
This module creates a node and fake perception data based
on json configurations
"""
import argparse
import math
import time
import simplejson
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3 import cyber_time
from modules.common_msgs.basic_msgs.geometry_pb2 import Point3D
from modules.common_msgs.perception_msgs.perception_obstacle_pb2 import PerceptionObstacle
from modules.common_msgs.perception_msgs.perception_obstacle_pb2 import PerceptionObstacles
_s_seq_num = 0
_s_delta_t = 0.1
_s_epsilon = 1e-8
def get_seq_num():
"""
Return the sequence number
"""
global _s_seq_num
_s_seq_num += 1
return _s_seq_num
def get_velocity(theta, speed):
"""
Get velocity from theta and speed
"""
point = Point3D()
point.x = math.cos(theta) * speed
point.y = math.sin(theta) * speed
point.z = 0.0
return point
def generate_polygon(point, heading, length, width):
"""
Generate polygon
"""
points = []
half_l = length / 2.0
half_w = width / 2.0
sin_h = math.sin(heading)
cos_h = math.cos(heading)
vectors = [(half_l * cos_h - half_w * sin_h,
half_l * sin_h + half_w * cos_h),
(-half_l * cos_h - half_w * sin_h,
- half_l * sin_h + half_w * cos_h),
(-half_l * cos_h + half_w * sin_h,
- half_l * sin_h - half_w * cos_h),
(half_l * cos_h + half_w * sin_h,
half_l * sin_h - half_w * cos_h)]
for x, y in vectors:
p = Point3D()
p.x = point.x + x
p.y = point.y + y
p.z = point.z
points.append(p)
return points
def load_descrptions(files):
"""
Load description files
"""
objects = []
for file in files:
with open(file, 'r') as fp:
obstacles = simplejson.loads(fp.read())
# Multiple obstacle in one file saves as a list[obstacles]
if isinstance(obstacles, list):
for obstacle in obstacles:
trace = obstacle.get('trace', [])
for i in range(1, len(trace)):
if same_point(trace[i], trace[i - 1]):
print('same trace point found in obstacle: %s' % obstacle["id"])
return None
objects.append(obstacle)
else: # Default case. handles only one obstacle
obstacle = obstacles
trace = obstacle.get('trace', [])
for i in range(1, len(trace)):
if same_point(trace[i], trace[i - 1]):
print('same trace point found in obstacle: %s' % obstacle["id"])
return None
objects.append(obstacle)
return objects
def get_point(a, b, ratio):
"""
Get point from a to b with ratio
"""
p = Point3D()
p.x = a[0] + ratio * (b[0] - a[0])
p.y = a[1] + ratio * (b[1] - a[1])
p.z = a[2] + ratio * (b[2] - a[2])
return p
def init_perception(description):
"""
Create perception from description
"""
perception = PerceptionObstacle()
perception.id = description["id"]
perception.position.x = description["position"][0]
perception.position.y = description["position"][1]
perception.position.z = description["position"][2]
perception.theta = description["theta"]
perception.velocity.CopyFrom(get_velocity(
description["theta"], description["speed"]))
perception.length = description["length"]
perception.width = description["width"]
perception.height = description["height"]
perception.polygon_point.extend(generate_polygon(perception.position,
perception.theta,
perception.length,
perception.width))
perception.tracking_time = description["tracking_time"]
perception.type = PerceptionObstacle.Type.Value(description["type"])
perception.timestamp = cyber_time.Time.now().to_sec()
return perception
def same_point(a, b):
"""
Test if a and b are the same point
"""
return math.fabs(b[0] - a[0]) < _s_epsilon and \
math.fabs(b[1] - a[1]) < _s_epsilon
def inner_product(a, b):
"""
Get the a, b inner product
"""
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def cross_product(a, b):
"""
Cross product
"""
return a[0] * b[1] - a[1] * b[0]
def distance(a, b):
"""
Return distance between a and b
"""
return math.sqrt((b[0] - a[0])**2 + (b[1] - a[1])**2 + (b[2] - a[2])**2)
def is_within(a, b, c):
"""
Check if c is in [a, b]
"""
if b < a:
b, a = a, b
return a - _s_epsilon < c < b + _s_epsilon
def on_segment(a, b, c):
"""
Test if c is in line segment a-b
"""
ab = (b[0] - a[0], b[1] - a[1], b[2] - a[2])
ac = (c[0] - a[0], c[1] - a[1], c[2] - a[2])
if math.fabs(cross_product(ac, ab)) > _s_epsilon:
return False
return is_within(a[0], b[0], c[0]) and is_within(a[1], b[1], c[1]) \
and is_within(a[2], b[2], c[2])
def linear_project_perception(description, prev_perception):
"""
Get perception from linear projection of description
"""
perception = PerceptionObstacle()
perception = prev_perception
perception.timestamp = cyber_time.Time.now().to_sec()
if "trace" not in description:
return perception
trace = description["trace"]
prev_point = (prev_perception.position.x, prev_perception.position.y,
prev_perception.position.z)
delta_s = description["speed"] * _s_delta_t
for i in range(1, len(trace)):
if on_segment(trace[i - 1], trace[i], prev_point):
dist = distance(trace[i - 1], trace[i])
delta_s += distance(trace[i - 1], prev_point)
while dist < delta_s:
delta_s -= dist
i += 1
if i < len(trace):
dist = distance(trace[i - 1], trace[i])
else:
return init_perception(description)
ratio = delta_s / dist
perception.position.CopyFrom(
get_point(trace[i - 1], trace[i], ratio))
perception.theta = math.atan2(trace[i][1] - trace[i - 1][1],
trace[i][0] - trace[i - 1][0])
perception.velocity.CopyFrom(get_velocity(perception.theta, description["speed"]))
perception.ClearField("polygon_point")
perception.polygon_point.extend(generate_polygon(perception.position, perception.theta,
perception.length, perception.width))
return perception
return perception
def generate_perception(perception_description, prev_perception):
"""
Generate perception data
"""
perceptions = PerceptionObstacles()
perceptions.header.sequence_num = get_seq_num()
perceptions.header.module_name = "perception"
perceptions.header.timestamp_sec = cyber_time.Time.now().to_sec()
if not perception_description:
return perceptions
if prev_perception is None:
for description in perception_description:
p = perceptions.perception_obstacle.add()
p.CopyFrom(init_perception(description))
return perceptions
# Linear projection
description_dict = {desc["id"]: desc for desc in perception_description}
for obstacle in prev_perception.perception_obstacle:
description = description_dict[obstacle.id]
next_obstacle = linear_project_perception(description, obstacle)
perceptions.perception_obstacle.add().CopyFrom(next_obstacle)
return perceptions
def perception_publisher(perception_channel, files, period):
"""
Publisher
"""
cyber.init()
node = cyber.Node("perception")
writer = node.create_writer(perception_channel, PerceptionObstacles)
perception_description = load_descrptions(files)
sleep_time = float(period) # 10Hz
global _s_delta_t
_s_delta_t = sleep_time
perception = None
while not cyber.is_shutdown():
perception = generate_perception(perception_description, perception)
print(str(perception))
writer.write(perception)
time.sleep(sleep_time)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="create fake perception obstacles",
prog="replay_perception.py")
parser.add_argument("files", action="store", type=str, nargs="*",
help="obstacle description files")
parser.add_argument("-c", "--channel", action="store", type=str,
default="/apollo/perception/obstacles",
help="set the perception channel")
parser.add_argument("-p", "--period", action="store", type=float, default=0.1,
help="set the perception channel publish time duration")
args = parser.parse_args()
perception_publisher(args.channel, args.files, args.period)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/localization/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
py_binary(
name = "evaluate_compare",
srcs = ["evaluate_compare.py"],
)
install(
name = "install",
py_dest = "tools/localization",
targets = [
":evaluate_compare",
]
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/localization/evaluate_compare.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 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.
###############################################################################
import math
import os
import sys
import numpy
def get_stat2_from_data(data):
"""Find the max number of continuous frames when position error is lager
than 30cm, 20cm and 10cm
Arguments:
data: error array
Returns:
stat: array of max number of continuous frames
"""
max_con_frame_num_10 = 0
max_con_frame_num_20 = 0
max_con_frame_num_30 = 0
tem_con_frame_num_10 = 0
tem_con_frame_num_20 = 0
tem_con_frame_num_30 = 0
for d in data:
if d > 0.1:
tem_con_frame_num_10 += 1
if d > 0.2:
tem_con_frame_num_20 += 1
if d > 0.3:
tem_con_frame_num_30 += 1
else:
if tem_con_frame_num_30 > max_con_frame_num_30:
max_con_frame_num_30 = tem_con_frame_num_30
tem_con_frame_num_30 = 0
else:
if tem_con_frame_num_20 > max_con_frame_num_20:
max_con_frame_num_20 = tem_con_frame_num_20
tem_con_frame_num_20 = 0
else:
if tem_con_frame_num_10 > max_con_frame_num_10:
max_con_frame_num_10 = tem_con_frame_num_10
tem_con_frame_num_10 = 0
stat = [max_con_frame_num_10, max_con_frame_num_20, max_con_frame_num_30]
return stat
def get_angle_stat2_from_data(data):
"""Find the max number of continuous frames when yaw error is lager
than 1.0d, 0.6d and 0.3d
Arguments:
data: error array
Returns:
stat: array of max number of continuous frames
"""
max_con_frame_num_1_0 = 0
max_con_frame_num_0_6 = 0
max_con_frame_num_0_3 = 0
tem_con_frame_num_1_0 = 0
tem_con_frame_num_0_6 = 0
tem_con_frame_num_0_3 = 0
for d in data:
if(d > 0.3):
tem_con_frame_num_0_3 += 1
if(d > 0.6):
tem_con_frame_num_0_6 += 1
if(d > 1.0):
tem_con_frame_num_1_0 += 1
else:
if tem_con_frame_num_1_0 > max_con_frame_num_1_0:
max_con_frame_num_1_0 = tem_con_frame_num_1_0
tem_con_frame_num_1_0 = 0
else:
if tem_con_frame_num_0_6 > max_con_frame_num_0_6:
max_con_frame_num_0_6 = tem_con_frame_num_0_6
tem_con_frame_num_0_6 = 0
else:
if tem_con_frame_num_0_3 > max_con_frame_num_0_3:
max_con_frame_num_0_3 = tem_con_frame_num_0_3
tem_con_frame_num_0_3 = 0
stat = [max_con_frame_num_1_0, max_con_frame_num_0_6, max_con_frame_num_0_3]
return stat
def get_stat_from_data(data):
if len(data) == 0:
print("No statistics data!")
return []
num_data = numpy.array(data)
sum1 = num_data.sum()
sum2 = (num_data * num_data).sum()
mean = sum1 / len(data)
std = math.sqrt(sum2 / len(data) - mean * mean)
mx = num_data.max()
count_less_than_30 = 0.0
count_less_than_20 = 0.0
count_less_than_10 = 0.0
for d in data:
if d < 0.3:
count_less_than_30 += 1.0
if d < 0.2:
count_less_than_20 += 1.0
if d < 0.1:
count_less_than_10 += 1.0
count_less_than_30 /= float(len(data))
count_less_than_20 /= float(len(data))
count_less_than_10 /= float(len(data))
stat = [mean, std, mx, count_less_than_30,
count_less_than_20, count_less_than_10]
return stat
def get_angle_stat_from_data(data):
if len(data) == 0:
print("No statistics data!")
return []
num_data = numpy.array(data)
sum1 = num_data.sum()
sum2 = (num_data * num_data).sum()
mean = sum1 / len(data)
std = math.sqrt(sum2 / len(data) - mean * mean)
mx = num_data.max()
count_less_than_1 = 0.0
count_less_than_06 = 0.0
count_less_than_03 = 0.0
for d in data:
if d < 1.0:
count_less_than_1 += 1.0
if d < 0.6:
count_less_than_06 += 1.0
if d < 0.3:
count_less_than_03 += 1.0
count_less_than_1 /= float(len(data))
count_less_than_06 /= float(len(data))
count_less_than_03 /= float(len(data))
stat = [mean, std, mx, count_less_than_1,
count_less_than_06, count_less_than_03]
return stat
def parse_file(filename, type):
with open(filename, 'r') as fp:
lines = fp.readlines()
print('%d frames' % len(lines))
error = []
error_lon = []
error_lat = []
error_alt = []
error_roll = []
error_pitch = []
error_yaw = []
for line in lines:
s = line.split()
if (len(s) > 7):
# error.append(float(s[6]))
error_lon.append(float(s[2]))
error_lat.append(float(s[3]))
error_alt.append(float(s[4]))
error_roll.append(float(s[5]))
error_pitch.append(float(s[6]))
error_yaw.append(float(s[7]))
x = float(s[2])
y = float(s[3])
error.append(math.sqrt(x * x + y * y))
# print "%f %f %f" % (error[-1], error_lon[-1], error_lat[-1])
if type == "all":
print_distance_error(error, error_lon, error_lat, error_alt)
print_angle_error(error_roll, error_pitch, error_yaw)
elif type == "distance_only":
print_distance_error(error, error_lon, error_lat, error_alt)
elif type == "angle_only":
print_angle_error(error_roll, error_pitch, error_yaw)
else:
print_distance_error(error, error_lon, error_lat, error_alt)
print_angle_error(error_roll, error_pitch, error_yaw)
def print_distance_error(error, error_lon, error_lat, error_alt):
print('criteria : mean std max < 30cm < 20cm < 10cm con_frames(>30cm)')
result = get_stat_from_data(error)
if len(result) != 6:
return
res = get_stat2_from_data(error)
print('error : %06f %06f %06f %06f %06f %06f %06d' %
(result[0], result[1], result[2],
result[3], result[4], result[5], res[2]))
result = get_stat_from_data(error_lon)
res = get_stat2_from_data(error_lon)
print('error lon: %06f %06f %06f %06f %06f %06f %06d' %
(result[0], result[1], result[2],
result[3], result[4], result[5], res[2]))
result = get_stat_from_data(error_lat)
res = get_stat2_from_data(error_lat)
print('error lat: %06f %06f %06f %06f %06f %06f %06d' %
(result[0], result[1], result[2],
result[3], result[4], result[5], res[2]))
result = get_stat_from_data(error_alt)
res = get_stat2_from_data(error_alt)
print('error alt: %06f %06f %06f %06f %06f %06f %06d' %
(result[0], result[1], result[2],
result[3], result[4], result[5], res[2]))
def print_angle_error(error_roll, error_pitch, error_yaw):
print('criteria : mean std max < 1.0d < 0.6d < 0.3d con_frames(>1.0d)')
result = get_angle_stat_from_data(error_roll)
if len(result) != 6:
return
res = get_angle_stat2_from_data(error_roll)
print("error rol: %06f %06f %06f %06f %06f %06f %06d" %
(result[0], result[1], result[2],
result[3], result[4], result[5], res[0]))
result = get_angle_stat_from_data(error_pitch)
res = get_angle_stat2_from_data(error_pitch)
print("error pit: %06f %06f %06f %06f %06f %06f %06d" %
(result[0], result[1], result[2],
result[3], result[4], result[5], res[0]))
result = get_angle_stat_from_data(error_yaw)
res = get_angle_stat2_from_data(error_yaw)
print("error yaw: %06f %06f %06f %06f %06f %06f %06d" %
(result[0], result[1], result[2],
result[3], result[4], result[5], res[0]))
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: %s [evaluation file] [evaluation type]' % argv[0])
sys.exit(0)
elif not os.path.isfile(sys.argv[1]):
print('File does not exist')
elif len(sys.argv) < 3:
parse_file(sys.argv[1], 'all')
else:
parse_file(sys.argv[1], sys.argv[2])
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/extract_static_data.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2019 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.
###############################################################################
"""
This is a tool to etract useful information from already extracted sensor data,
mainly for camera lidar calibration.
"""
from datetime import datetime
from shutil import copyfile
import argparse
import cv2
import os
import six
import sys
from google.protobuf import text_format
import numpy as np
from cyber.python.cyber_py3.record import RecordReader
from cyber.proto import record_pb2
from modules.tools.sensor_calibration.configuration_yaml_generator import ConfigYaml
from modules.tools.sensor_calibration.data_file_object import TimestampFileObject, OdometryFileObject
from modules.tools.sensor_calibration.proto import extractor_config_pb2
CYBER_PATH = os.environ['CYBER_PATH']
CYBER_RECORD_HEADER_LENGTH = 2048
Z_FILL_LEN = 4
Z_DEFAULT_LEN = 5
def mkdir_p(path):
if not os.path.isdir(path):
os.makedirs(path)
else:
print('folder {} exists'.format(path))
def get_subfolder_list(d):
"""list the 1st-level directories under the root directory
ignore hidden folders"""
return [f for f in os.listdir(d) if not f.startswith('.') and
os.path.isdir(os.path.join(d, f))]
def sort_files_by_timestamp(in_path, out_path,
timestamp_filename,
extension='.png'):
"""sort files by timestamp"""
ts_file = os.path.join(in_path, timestamp_filename)
out_ts_file = os.path.join(out_path, timestamp_filename)
ts_map = np.loadtxt(ts_file)
sorted_ids = np.argsort(ts_map[:, 1])
ts_map = ts_map[sorted_ids]
# sorted_ts = np.vstack((np.arange(sorted_ids), ts_map[:,1])).T
# np.savetxt(out_ts_file, ts_map, sorted_ts)
ts_obj = TimestampFileObject(file_path=out_ts_file)
ts_obj.save_to_file(ts_map[:, 1])
if extension == '.png' or extension == '.pcd':
for i, idx in enumerate(ts_map[:, 0]):
in_file_name = os.path.join(in_path, ("%06d" % (idx + 1)) + extension)
out_file_name = os.path.join(out_path, ("%06d" % (i + 1)) + extension)
copyfile(in_file_name, out_file_name)
elif extension == 'odometry':
tmp_file = os.path.join(in_path, 'odometry')
in_odm = OdometryFileObject(file_path=tmp_file,
operation='read',
file_type='binary')
data = in_odm.load_file()
sorted_data = []
for idx in ts_map[:, 0]:
d = data[idx]
sorted_data.append(d)
tmp_file = os.path.join(out_path, 'odometry')
out_odm = OdometryFileObject(file_path=tmp_file,
operation='write',
file_type='binary')
out_odm.save_to_file(sorted_data)
def find_nearest(array, value):
idx = np.searchsorted(array, value, side="left")
if idx > 0 and (idx == len(array) or
math.fabs(value - array[idx-1]) < math.fabs(value - array[idx])):
return idx-1
else:
return idx
def find_synchronized_timestamp_index(query_ts, source_ts, max_threshold=1.0):
# for each element in query, find the nearest element in source,
# if the distance < max_threshold
ts1 = query_ts
ts2 = source_ts
if len(ts1) == 0 or len(ts2) == 0:
return {}
nearest_index_map = {}
start = 0
for i in range(len(ts1)):
if start >= len(ts2):
break
min_ts_diff = max_threshold
min_j = -1
for j in range(start, len(ts2)):
ts_diff = ts2[j] - ts1[i]
if abs(ts_diff) < min_ts_diff:
min_j = j
min_ts_diff = abs(ts_diff)
if ts_diff >= 0:
# the rest ts2 > ts1, no need to loop ts2 anymore
break
if min_j > 0: # find valid nearest index in ts2
start = min_j # reset start for case i++
nearest_index_map[i] = min_j
# for i, j in nearest_index_map.items():
# print([i, j, query_ts[i], source_ts[j]])
return nearest_index_map
def get_difference_score_between_images(path, file_indexes,
suffix=".png", thumbnail_size=32):
image_sum = np.zeros(len(file_indexes), dtype=np.float32)
image_diff = np.zeros(len(file_indexes), dtype=np.float32)
image_thumbnails = []
for c, idx in enumerate(file_indexes):
image_file = os.path.join(path, str(int(idx)).zfill(Z_DEFAULT_LEN) + suffix)
image = cv2.imread(image_file)
image_thumbnails.append(cv2.resize(image,
(thumbnail_size, thumbnail_size), interpolation=cv2.INTER_AREA))
image_sum[c] = np.sum(image_thumbnails[-1])
image_diff[0] = np.finfo(float).max
for c in range(len(file_indexes)-1, 0, -1):
image_diff[c] = np.sum(cv2.absdiff(image_thumbnails[c], image_thumbnails[c-1]))
image_diff[c] = image_diff[c] / image_sum[c]
# print("image_diff is: ")
# for i in range(len(image_diff)):
# print([i, image_diff[i], image_sum[i]])
return image_diff
def get_distance_by_odometry(data, i, j):
# calculate x-y plane distance
return np.linalg.norm(data[i, -3:-1] - data[j, -3:-1])
def check_static_by_odometry(data, index, check_range=40,
movable_threshold=0.01):
start_idx = np.maximum(index - check_range, 0)
end_idx = np.minimum(index + check_range, data.shape[0]-1)
# skip if start and end index are too nearby.
if end_idx - start_idx < 2 * check_range:
return False
# calculate x-y plane distance
distance = get_distance_by_odometry(data, start_idx, end_idx)
# print("distance is %d %d %f" % (start_idx, end_idx,distance))
return distance < movable_threshold
def select_static_image_pcd(path, min_distance=5, stop_times=5,
wait_time=3, check_range=50,
image_static_diff_threshold=0.005,
output_folder_name='camera-lidar-pairs',
image_suffix='.jpg', pcd_suffix='.pcd'):
"""
select pairs of images and pcds, odometry information may
come from /apollolocalization/pose as well
"""
subfolders = [x for x in get_subfolder_list(
path) if '_apollo_sensor_' in x or '_localization_pose' in x]
lidar_subfolder = [x for x in subfolders if '_PointCloud2' in x]
odometry_subfolder = [x for x in subfolders if'_odometry' in x or '_localization_pose' in x]
camera_subfolders = [x for x in subfolders if'_image' in x]
if len(lidar_subfolder) is not 1 or \
len(odometry_subfolder) is not 1:
raise ValueError('only one main lidar and one Odometry'
'sensor is needed for sensor calibration')
lidar_subfolder = lidar_subfolder[0]
odometry_subfolder = odometry_subfolder[0]
# load timestamp dictionary
timestamp_dict = {}
for f in subfolders:
f_abs_path = os.path.join(path, f)
ts_file = os.path.join(f_abs_path, 'timestamps')
ts_map = np.loadtxt(ts_file)
timestamp_dict[f] = ts_map
# load odometry binary file
odometry_file = os.path.join(path, odometry_subfolder, 'odometry')
in_odm = OdometryFileObject(file_path=odometry_file,
operation='read',
file_type='binary')
odometry_data = np.array(in_odm.load_file())
for camera in camera_subfolders:
print("working on sensor message: {}".format(camera))
camera_gps_nearest_pairs = \
find_synchronized_timestamp_index(
timestamp_dict[camera][:, 1],
timestamp_dict[odometry_subfolder][:, 1],
max_threshold=0.2)
camera_lidar_nearest_pairs = \
find_synchronized_timestamp_index(
timestamp_dict[camera][:, 1],
timestamp_dict[lidar_subfolder][:, 1],
max_threshold=0.5)
# clean camera-lidar paris not exist in both dictionary
del_ids = []
for key in camera_lidar_nearest_pairs:
if key not in camera_gps_nearest_pairs:
del_ids.append(key)
for key in del_ids:
del camera_lidar_nearest_pairs[key]
camera_folder_path = os.path.join(path, camera)
print('foder: {}'.format(camera_folder_path))
camera_diff = get_difference_score_between_images(
camera_folder_path, timestamp_dict[camera][:, 0], suffix=image_suffix)
valid_image_indexes = [x for x, v in enumerate(camera_diff)
if v <= image_static_diff_threshold]
valid_images = (timestamp_dict[camera][valid_image_indexes, 0]).astype(int)
# generate valid camera frame
candidate_idx = []
last_idx = -1
last_odometry_idx = -1
for i in valid_images:
if i in camera_lidar_nearest_pairs:
odometry_idx = camera_gps_nearest_pairs[i]
# not static considering odometry motion.
if not check_static_by_odometry(odometry_data,
odometry_idx, check_range=check_range):
continue
if last_idx is -1:
last_idx = i
last_odometry_idx = odometry_idx
candidate_idx.append(i)
continue
time_interval = timestamp_dict[camera][i, 1] - timestamp_dict[camera][last_idx, 1]
odomerty_interval = \
get_distance_by_odometry(odometry_data, odometry_idx, last_odometry_idx)
# timestamp interval > wait_time and odometry_interval > min_distance`
if time_interval < wait_time or \
odomerty_interval < min_distance:
continue
candidate_idx.append(i)
last_idx = i
last_odometry_idx = odometry_idx
# print(odometry_data[odometry_idx])
# print(odometry_data[last_odometry_idx])
# print([i, odomerty_interval])
# check candidate number and select best stop according to camera_diff score
print("all valid static image index: ", candidate_idx)
if len(candidate_idx) < stop_times:
raise ValueError('not enough stops detected,'
'thus no sufficient data for camera-lidar calibration')
elif len(candidate_idx) > stop_times:
tmp_diff = camera_diff[candidate_idx]
tmp_idx = np.argsort(tmp_diff)[:stop_times]
candidate_idx = [candidate_idx[x] for x in tmp_idx]
candidate_idx.sort()
# save files
image_idx = candidate_idx
print("selected best static image index: ", image_idx)
lidar_idx = [camera_lidar_nearest_pairs[x] for x in image_idx]
output_path = os.path.join(camera_folder_path, output_folder_name)
mkdir_p(output_path)
for count, i in enumerate(image_idx):
# save images
in_file = os.path.join(camera_folder_path, str(
int(i)).zfill(Z_DEFAULT_LEN) + image_suffix)
out_file = os.path.join(output_path, str(
int(count)).zfill(Z_FILL_LEN) + '_00' + image_suffix)
copyfile(in_file, out_file)
j = camera_lidar_nearest_pairs[i]
# save pcd
in_file = os.path.join(path, lidar_subfolder, str(
int(j)).zfill(Z_DEFAULT_LEN) + pcd_suffix)
out_file = os.path.join(output_path, str(
int(count)).zfill(Z_FILL_LEN) + '_00' + pcd_suffix)
copyfile(in_file, out_file)
print("generate image-lidar-pair:[%d, %d]" % (i, j))
return camera_subfolders, lidar_subfolder
def main2():
for str in ['_apollo_sensor_lidar16_front_center_PointCloud2',
'_apollo_sensor_lidar16_rear_left_PointCloud2',
'_apollo_sensor_lidar16_rear_right_PointCloud2',
'_apollo_sensor_lidar128_PointCloud2']:
# _apollo_sensor_lidar128_PointCloud2'
in_path = '/apollo/data/Lidar_GNSS_Calibration-2019-07-12-15-25/' + str
out_path = os.path.join(in_path, 'new')
mkdir_p(out_path)
timestamp_filename = 'timestamps.txt'
extension = '.pcd'
sort_files_by_timestamp(in_path, out_path, timestamp_filename, extension=extension)
in_path = '/apollo/data/Lidar_GNSS_Calibration-2019-07-12-15-25/_apollo_sensor_gnss_odometry'
out_path = os.path.join(in_path, 'new')
mkdir_p(out_path)
timestamp_filename = 'timestamps.txt'
extension = 'odometry'
sort_files_by_timestamp(in_path, out_path, timestamp_filename, extension=extension)
def main():
if CYBER_PATH is None:
print('Error: environment variable CYBER_PATH was not found, '
'set environment first.')
sys.exit(1)
os.chdir(CYBER_PATH)
parser = argparse.ArgumentParser(
description='A tool to extract useful data information for camera-to-lidar calibration.')
parser.add_argument("-i", "--workspace_path", action="store", default="", required=True,
dest='workspace',
help="Specify the worksapce where storing extracted sensor messages")
args = parser.parse_args()
select_static_image_pcd(path=args.workspace, min_distance=5, stop_times=5,
wait_time=3, check_range=50,
image_static_diff_threshold=0.005)
if __name__ == '__main__':
main()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/configuration_yaml_generator.py
|
#!/usr/bin/env python3
###############################################################################
# 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.
###############################################################################
import os
import shutil
import yaml
from google.protobuf import text_format
from modules.dreamview.proto import preprocess_table_pb2
from modules.tools.common.proto_utils import get_pb_from_text_file
ROOT_DIR = '/apollo/modules/tools/sensor_calibration'
class ConfigYaml(object):
"""generate yaml configuration for next-step calibration service.
automatically generate calibration configuration yaml file. help user to
input the initial extrinsics values or path(lidar, camera), intrinsics path(camera),
sensor name if needs changes.
"""
def __init__(self, supported_calibrations=['lidar_to_gnss', 'camera_to_lidar']):
self._task_name = 'unknown'
self._supported_tasks = supported_calibrations
self._source_sensor = ''
self._table_info = preprocess_table_pb2.PreprocessTable()
print('calibration service now support: {}'.format(self._supported_tasks))
def load_sample_yaml_file(self, task_name, sample_file=None):
if sample_file is None:
sample_file = os.path.join(ROOT_DIR, 'config', task_name + '_sample_config.yaml')
try:
with open(sample_file, 'r') as f:
data = yaml.safe_load(f)
except IOError:
raise ValueError(
'cannot open the sample configure yaml file at {}'.format(sample_file))
return data
def _generate_lidar_to_gnss_calibration_yaml(self, in_data, lidar_folder_name, gnss_folder_name):
in_data['sensor_files_directory'] = os.path.join(
'.', lidar_folder_name, "")
in_data['odometry_file'] = os.path.join(
'.', gnss_folder_name, 'odometry')
for lidar_config in self._table_info.lidar_config:
if lidar_config.sensor_name == self._source_sensor:
in_data['transform']['translation']['x'] = round(
lidar_config.translation.x, 4)
in_data['transform']["translation"]["y"] = round(
lidar_config.translation.y, 4)
in_data['transform']["translation"]["z"] = round(
lidar_config.translation.z, 4)
return in_data
def _generate_camera_init_param_yaml(self, root_path, in_data):
init_param_folder = os.path.join(
ROOT_DIR, 'config/init_params')
out_param_folder = os.path.join(root_path, 'init_params')
if os.path.exists(out_param_folder):
print('folder: %s exists' % out_param_folder)
else:
print('create folder: %s' % out_param_folder)
os.makedirs(out_param_folder)
camera_config = self._table_info.camera_config
# copy sample intrinsic yaml file to correct location
# wait for user input about intrinsics
sample_intrinsic_yaml = os.path.join(
init_param_folder, 'sample_intrinsics.yaml')
intrinsic_data = self.load_sample_yaml_file(self._task_name,
sample_file=sample_intrinsic_yaml)
for iter, data in enumerate(camera_config.D):
intrinsic_data['D'][iter] = data
for iter, data in enumerate(camera_config.K):
intrinsic_data['K'][iter] = data
# dump the intrinsic yaml data
out_intrinsic_yaml = os.path.join(out_param_folder,
in_data['source_sensor'] + '_intrinsics.yaml')
try:
with open(out_intrinsic_yaml, 'w') as f:
yaml.safe_dump(intrinsic_data, f)
except IOError:
raise ValueError('cannot generate the task config yaml '
'file at {}'.format(out_intrinsic_yaml))
# load extrinsics sample yaml, rename source sensor and destination sensor
sample_extrinsic_yaml = os.path.join(
init_param_folder, 'sample_extrinsics.yaml')
extrinsic_data = self.load_sample_yaml_file(self._task_name,
sample_file=sample_extrinsic_yaml)
# set up the source_sensor(camera name) to dest sensor(lidar name)
extrinsic_data['header']['frame_id'] = in_data['destination_sensor']
extrinsic_data['child_frame_id'] = in_data['source_sensor']
extrinsic_data['transform']['translation']['x'] = round(
camera_config.translation.x, 4)
extrinsic_data['transform']["translation"]["y"] = round(
camera_config.translation.y, 4)
extrinsic_data['transform']["translation"]["z"] = round(
camera_config.translation.z, 4)
# dump the extrinsic yaml data
out_extrinsic_yaml = os.path.join(out_param_folder, in_data['source_sensor']
+ '_' + in_data['destination_sensor'] + '_extrinsics.yaml')
try:
with open(out_extrinsic_yaml, 'w') as f:
yaml.safe_dump(extrinsic_data, f)
except IOError:
raise ValueError('cannot generate the task config yaml '
'file at {}'.format(out_extrinsic_yaml))
def _generate_camera_to_lidar_calibration_yaml(self, in_data):
in_data['intrinsic'] = os.path.join('.', 'init_params',
in_data['source_sensor'] + '_intrinsics.yaml')
in_data['extrinsic'] = os.path.join('.', 'init_params', in_data['source_sensor']
+ '_' + in_data['destination_sensor'] + '_extrinsics.yaml')
return in_data
def get_task_name(self):
if self._task_name == 'unknown':
raise ValueError('have not set the task name, the valid task names'
'are: {}'.format(self._supported_tasks))
return self._task_name
def generate_task_config_yaml(self, task_name, source_sensor, dest_sensor,
source_folder, dest_folder, out_config_file,
in_config_file=None):
self._task_name = task_name
self._source_sensor = source_sensor
out_data = self.load_sample_yaml_file(
task_name=task_name, sample_file=in_config_file)
out_data['source_sensor'] = source_sensor
out_data['destination_sensor'] = dest_sensor
if task_name not in self._supported_tasks:
raise ValueError('does not support the calibration task: {}'.format(
task_name))
user_config = os.path.join(ROOT_DIR, 'config',
task_name + '_user.config')
if os.path.exists(user_config):
try:
get_pb_from_text_file(user_config, self._table_info)
except text_format.ParseError:
print(f'Error: Cannot parse {user_config} as text proto')
if self._task_name == 'lidar_to_gnss':
out_data = self._generate_lidar_to_gnss_calibration_yaml(
out_data, source_folder, dest_folder)
elif self._task_name == 'camera_to_lidar':
if source_folder != dest_folder:
raise ValueError(
'camera frame and lidar frame should be in same folder')
out_root_path = os.path.dirname(out_config_file)
self._generate_camera_init_param_yaml(out_root_path, out_data)
out_data = self._generate_camera_to_lidar_calibration_yaml(
out_data)
print(out_data)
try:
with open(out_config_file, 'w') as f:
yaml.safe_dump(out_data, f)
except IOError:
raise ValueError(
'cannot generate the task config yaml file at {}'.format(out_config_file))
return True
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/odom_publisher.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2020 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.
###############################################################################
import argparse
import atexit
import logging
import os
import sys
import time
#from common.logger import Logger
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3 import cyber_time
from modules.common_msgs.localization_msgs import localization_pb2
from modules.common_msgs.localization_msgs import gps_pb2
class OdomPublisher(object):
def __init__(self, node):
self.localization = localization_pb2.LocalizationEstimate()
self.gps_odom_pub = node.create_writer('/apollo/sensor/gnss/odometry', gps_pb2.Gps)
self.sequence_num = 0
self.terminating = False
self.position_x = 0
self.position_y = 0
self.position_z = 0
self.orientation_x = 0
self.orientation_y = 0
self.orientation_z = 0
self.orientation_w = 0
self.linear_velocity_x = 0
self.linear_velocity_y = 0
self.linear_velocity_z = 0
def localization_callback(self, data):
"""
New message received
"""
self.localization.CopyFrom(data)
self.position_x = self.localization.pose.position.x
self.position_y = self.localization.pose.position.y
self.position_z = self.localization.pose.position.z
self.orientation_x = self.localization.pose.orientation.qx
self.orientation_y = self.localization.pose.orientation.qy
self.orientation_z = self.localization.pose.orientation.qz
self.orientation_w = self.localization.pose.orientation.qw
self.linear_velocity_x = self.localization.pose.linear_velocity.x
self.linear_velocity_y = self.localization.pose.linear_velocity.y
self.linear_velocity_z = self.localization.pose.linear_velocity.z
def publish_odom(self):
odom = gps_pb2.Gps()
now = cyber_time.Time.now().to_sec()
odom.header.timestamp_sec = now
odom.header.module_name = "odometry"
odom.header.sequence_num = self.sequence_num
self.sequence_num = self.sequence_num + 1
odom.localization.position.x = self.position_x
odom.localization.position.y = self.position_y
odom.localization.position.z = self.position_z
odom.localization.orientation.qx = self.orientation_x
odom.localization.orientation.qy = self.orientation_y
odom.localization.orientation.qz = self.orientation_z
odom.localization.orientation.qw = self.orientation_w
odom.localization.linear_velocity.x = self.linear_velocity_x
odom.localization.linear_velocity.y = self.linear_velocity_y
odom.localization.linear_velocity.z = self.linear_velocity_z
#self.logger.info("%s"%odom)
self.gps_odom_pub.write(odom)
def shutdown(self):
"""
shutdown rosnode
"""
self.terminating = True
#self.logger.info("Shutting Down...")
time.sleep(0.2)
def main():
"""
Main rosnode
"""
node = cyber.Node('odom_publisher')
odom = OdomPublisher(node)
node.create_reader('/apollo/localization/pose', localization_pb2.LocalizationEstimate, odom.localization_callback)
while not cyber.is_shutdown():
now = cyber_time.Time.now().to_sec()
odom.publish_odom()
sleep_time = 0.01 - (cyber_time.Time.now().to_sec() - now)
if sleep_time > 0:
time.sleep(sleep_time)
if __name__ == '__main__':
cyber.init()
main()
cyber.shutdown()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/extract_data.sh
|
#! /usr/bin/env bash
###############################################################################
# Copyright 2020 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.
###############################################################################
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd -P)"
TARGET_DIR="${TOP_DIR}/output/sensor_calibration"
TEMPLATE_DIR="${TOP_DIR}/modules/tools/sensor_calibration/template"
DEFAULT_RECORD_DIR="${TOP_DIR}/data/bag"
TASK=""
VALID_TASKS=("lidar_to_gnss" "camera_to_lidar")
RECORD_FILES=()
RECORD_DIRS=()
function join_by() {
local d=$1
shift
echo -n "$1"
shift
printf "%s" "${@/#/$d}"
}
function print_usage() {
echo "Usage:
./extract_data.sh -t [ $(join_by ' | ' ${VALID_TASKS[@]}) ] -f <path/to/record/file> -d <path/to/record/dir>
eg.
./extract_data.sh -t lidar_to_gnss -f xxx/yyy.record.00000 -f xxx/yyy.record.00001
or
./extract_data.sh -t camera_to_lidar -d xxx -c front_6mm
"
}
function parse_args() {
# read options
while getopts ':t:c:f:d:' flag; do
case "${flag}" in
t)
TASK="${OPTARG}"
;;
f)
RECORD_FILES+=("${OPTARG}")
;;
d)
RECORD_DIRS+=("${OPTARG}")
;;
*)
print_usage
exit 1
;;
esac
done
if [[ " ${VALID_TASKS[@]} " =~ " ${TASK} " ]]; then
TARGET_DIR="${TARGET_DIR}/${TASK}"
TEMPLATE_DIR="${TEMPLATE_DIR}/${TASK}"
else
print_usage
exit 1
fi
}
function check_target_dir() {
if [[ ! -d "${TARGET_DIR}" ]]; then
mkdir -p ${TARGET_DIR}
elif [[ ! -z "$(ls -A ${TARGET_DIR})" ]]; then
rm -rf ${TARGET_DIR}/*
fi
cp -R ${TEMPLATE_DIR}/* ${TARGET_DIR}
}
# Since pypcd installed via `pip install` only works with python2.7,
# we can only install it this way
function _install_pypcd() {
git clone https://github.com/DanielPollithy/pypcd
pushd pypcd >/dev/null
sudo make install
popd >/dev/null
sudo rm -rf pypcd
}
function _get_latest() {
local parent_dir=$1
local latest=$(ls -lt ${parent_dir} | grep -v '_s' |
grep -m1 '^d' | awk '{print $NF}')
if [[ -z "${latest}" ]]; then
echo "There is no reord directories in ${parent_dir}!"
exit 1
else
echo "${parent_dir}/${latest}"
fi
}
function get_records() {
if [[ ${#RECORD_FILES[*]} -eq 0 && ${#RECORD_DIRS[*]} -eq 0 ]]; then
RECORD_DIRS+=($(_get_latest ${DEFAULT_RECORD_DIR}))
fi
local tmp_file="${TARGET_DIR}/tmp.txt"
for file in "${RECORD_FILES[@]}"; do
if [[ -f "${file}" ]]; then
if [[ "${file}" == *"record"* ]]; then
echo -e ' record_path: "'$(readlink -f ${file})'"\n' >>"${tmp_file}"
sed -i "/# records can be specified as a list/r ${tmp_file}" "${TARGET_DIR}/${TASK}.config"
else
echo "The input file ${file} is not a record!"
exit 1
fi
else
echo "File ${file} doesn't exist!"
exit 1
fi
done
rm -f ${tmp_file}
for dir in "${RECORD_DIRS[@]}"; do
if [[ -d "${dir}" ]]; then
if [[ -z "$(ls ${dir} | grep record)" ]]; then
echo "There is no reord file in ${dir}!"
exit 1
fi
echo -e ' record_path: "'$(readlink -f ${dir})'"\n' >>"${tmp_file}"
sed -i "/# or, records can be loaded from a directory/r ${tmp_file}" "${TARGET_DIR}/${TASK}.config"
else
echo "Directory ${dir} doesn't exist!"
exit 1
fi
done
rm -f ${tmp_file}
}
function install_if_not_exist() {
while [[ $# -gt 0 ]]; do
local pkg=$1
shift
pip show --files "${pkg}" >/dev/null
if [[ $? -ne 0 ]]; then
if [[ "${pkg}" == "pypcd" ]]; then
_install_pypcd
else
sudo pip install --no-cache-dir "${pkg}"
fi
fi
done
}
function update_lidar_config() {
local record
local lidar_channels
local tmp_file="${TARGET_DIR}/tmp.txt"
local channel_template="${TEMPLATE_DIR}/channel_template.txt"
local extraction_rate="5"
if [[ ${#RECORD_FILES[*]} -ne 0 ]]; then
record="$(readlink -f ${RECORD_FILES[0]})"
else
record="$(readlink -f ${RECORD_DIRS[0]})/$(ls ${RECORD_DIRS[0]} | grep -m1 record)"
fi
lidar_channels=($(cyber_recorder info ${record} | awk '{print $1}' |
grep "PointCloud2" | grep -v "fusion" | grep -v "compensator"))
if [ "${#lidar_channels[*]}" -eq 0 ]; then
echo "There is no PointCloud messages in ${record}, please check your record!"
exit 1
fi
sed -i "s|__RATE__|${extraction_rate}|g" "${channel_template}"
for channel in "${lidar_channels[@]}"; do
sed -i "s|__NAME__|${channel}|g" "${channel_template}"
cat "${channel_template}" >>"${tmp_file}"
sed -i "s|${channel}|__NAME__|g" "${channel_template}"
done
sed -i "s|${extraction_rate}|__RATE__|g" "${channel_template}"
sed -i "/# channel of mulitple lidars/{n;N;N;N;N;d}" "${TARGET_DIR}/lidar_to_gnss.config"
sed -i "/# channel of mulitple lidars/r ${tmp_file}" "${TARGET_DIR}/lidar_to_gnss.config"
rm -f ${tmp_file}
}
function update_camera_config() {
local channel_template="${TEMPLATE_DIR}/channel_template.txt"
local extraction_rate=5
if [[ ${#RECORD_FILES[*]} -ne 0 ]]; then
record="$(readlink -f ${RECORD_FILES[0]})"
else
record="$(readlink -f ${RECORD_DIRS[0]})/$(ls ${RECORD_DIRS[0]} | grep -m1 record)"
fi
camera_channels=($(cyber_recorder info ${record} | grep "image" | grep -v "compressed" | awk '$2>0{print $1}'))
if [ "${#camera_channels[*]}" -ne 1 ]; then
echo "There should be only one camera channel in ${record}, please check your record!"
exit 1
fi
sed -i "s|__RATE__|${extraction_rate}|g" "${channel_template}"
sed -i "s|__NAME__|${camera_channels[0]}|g" "${channel_template}"
sed -i "/# channel of camera image channels/{n;N;N;N;N;d}" "${TARGET_DIR}/camera_to_lidar.config"
sed -i "/# channel of camera image channels/r ${channel_template}" "${TARGET_DIR}/camera_to_lidar.config"
sed -i "s|${extraction_rate}|__RATE__|g" "${channel_template}"
sed -i "s|${camera_channels[0]}|__NAME__|g" "${channel_template}"
}
function main() {
parse_args "$@"
check_target_dir
get_records
if [[ "${TASK}" == "lidar_to_gnss" ]]; then
update_lidar_config
fi
if [[ "${TASK}" == "camera_to_lidar" ]]; then
update_camera_config
fi
install_if_not_exist "pyyaml" "pypcd"
set -e
local extract_data_bin="/opt/apollo/neo/packages/tools-dev/latest/sensor_calibration/extract_data"
if [[ ! -f "${extract_data_bin}" ]];then
extract_data_bin="${TOP_DIR}/bazel-bin/modules/tools/sensor_calibration/extract_data"
fi
if [[ -f "${extract_data_bin}" ]]; then
"${extract_data_bin}" --config "${TARGET_DIR}/${TASK}.config"
else
bazel run //modules/tools/sensor_calibration:extract_data \
-- --config "${TARGET_DIR}/${TASK}.config"
fi
rm -f ${TARGET_DIR}/records/*
}
main "$@"
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/sanity_check.py
|
#!/usr/bin/env python
###############################################################################
# Copyright 2020 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.
###############################################################################
"""
This is a tool to sanity check the output files of extract_data.py
"""
import os
import yaml
from absl import app
from absl import flags
from absl import logging
import modules.tools.common.file_utils as file_utils
flags.DEFINE_string('input_folder', '', 'The folder stores extracted messages')
def missing_config_file(path):
sample_config_files = []
for (dirpath, _, filenames) in os.walk(path):
for filename in filenames:
if filename == 'sample_config.yaml':
end_file = os.path.join(dirpath, filename)
sample_config_files.append(end_file)
if (len(sample_config_files) == 0):
return True, []
return False, sample_config_files
def missing_calibration_task(sample_config_files):
for sample_config_file in sample_config_files:
print(sample_config_file)
with open(sample_config_file, 'r') as f:
data = yaml.safe_load(f)
if not ('calibration_task' in data):
return True
return False
def file_type_exist(file_dir, file_type):
files = os.listdir(file_dir)
for k in range(len(files)):
files[k] = os.path.splitext(files[k])[1]
if file_type in files:
return True
return False
def list_to_str(data):
if isinstance(data, list):
return data[0]
else:
return data
def missing_lidar_gnss_file(lidar_gnss_config):
with open(lidar_gnss_config, 'r') as f:
data = yaml.safe_load(f)
yaml_dir = os.path.dirname(lidar_gnss_config)
odometry_dir = os.path.join(yaml_dir, data['odometry_file'])
point_cloud_dir = os.path.join(yaml_dir,
list_to_str(data['sensor_files_directory']))
logging.info(
f"odometry_dir:{odometry_dir} , point_cloud_dir: {point_cloud_dir}")
if not os.access(odometry_dir, os.F_OK):
logging.info('odometry file does not exist')
return True
if not file_type_exist(point_cloud_dir, '.pcd'):
logging.info('pcd file does not exist')
return True
return False
def missing_camera_lidar_file(camera_lidar_configs):
with open(camera_lidar_configs, 'r') as f:
data = yaml.safe_load(f)
yaml_dir = os.path.dirname(camera_lidar_configs)
camera_lidar_pairs_dir = os.path.join(yaml_dir, data['data_path'])
extrinsics_yaml_dir = os.path.join(yaml_dir, data['extrinsic'])
intrinsics_yaml_dir = os.path.join(yaml_dir, data['intrinsic'])
jpg_flag = file_type_exist(camera_lidar_pairs_dir, '.jpg')
pcd_flag = file_type_exist(camera_lidar_pairs_dir, '.pcd')
if not (jpg_flag and pcd_flag):
logging.info('camera_lidar_pairs data error')
return True
if not os.access(extrinsics_yaml_dir, os.F_OK):
logging.info('extrinsics_yaml file does not exist')
return True
if not os.access(intrinsics_yaml_dir, os.F_OK):
logging.info('intrinsics_yaml file does not exist')
return True
return False
def missing_calibration_data_file(sample_config_files):
lidar_file_flag = False
camera_file_flag = False
for sample_config_file in sample_config_files:
with open(sample_config_file, 'r') as f:
data = yaml.safe_load(f)
if data['calibration_task'] == 'lidar_to_gnss':
if (missing_lidar_gnss_file(sample_config_file)):
lidar_file_flag = True
if data['calibration_task'] == 'camera_to_lidar':
if (missing_camera_lidar_file(sample_config_file)):
camera_file_flag = True
return lidar_file_flag, camera_file_flag
def is_oversize_file(path):
dir_size = file_utils.getInputDirDataSize(path)
if dir_size == 0:
logging.error('The input dir is empty!')
return True
if dir_size >= 5 * 1024 * 1024 * 1024:
logging.error('The record file is oversize!')
return True
return False
def sanity_check(input_folder):
err_msg = None
lidar_gnss_flag = False
camera_lidar_flag = False
if is_oversize_file(input_folder):
err_msg = "The input file is oversize(1G)!"
config_flag, config_files = missing_config_file(input_folder)
if config_flag:
err_msg = "Missing sample_config.yaml!"
if missing_calibration_task(config_files):
err_msg = "The sample_config.yaml file miss calibration_task config!"
lidar_gnss_flag, camera_lidar_flag = missing_calibration_data_file(
config_files)
if lidar_gnss_flag and not camera_lidar_flag:
err_msg = "Missing Lidar_gnss files!"
elif not lidar_gnss_flag and camera_lidar_flag:
err_msg = "Missing camera_lidar files!"
elif lidar_gnss_flag and camera_lidar_flag:
err_msg = "Missing lidar_gnss and camera_lidar files!"
else:
info_msg = f"{input_folder} Passed sanity check."
logging.info(info_msg)
return True, info_msg
logging.error(err_msg)
return False, err_msg
def main(argv):
sanity_check(input_folder=flags.FLAGS.input_folder)
if __name__ == "__main__":
app.run(main)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/extract_data.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2019 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.
###############################################################################
"""
This is a tool to extract useful information from given record files. It does
self-check the validity of the uploaded data and able to inform developer's when
the data is not qualified, and reduce the size of uploaded data significantly.
"""
from datetime import datetime
import os
import shutil
import six
import sys
import time
import yaml
from absl import app
from absl import flags
from google.protobuf import text_format
import numpy as np
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3.record import RecordReader
from cyber.proto import record_pb2
from modules.dreamview.proto import preprocess_table_pb2
from modules.tools.common.proto_utils import get_pb_from_text_file
from modules.tools.sensor_calibration.configuration_yaml_generator import ConfigYaml
from modules.tools.sensor_calibration.extract_static_data import get_subfolder_list, select_static_image_pcd
from modules.tools.sensor_calibration.proto import extractor_config_pb2
from modules.tools.sensor_calibration.sanity_check import sanity_check
from modules.tools.sensor_calibration.sensor_msg_extractor import GpsParser, ImageParser, PointCloudParser, PoseParser, ContiRadarParser
SMALL_TOPICS = [
'/apollo/canbus/chassis',
'/apollo/canbus/chassis_detail',
'/apollo/control',
'/apollo/control/pad',
'/apollo/drive_event',
'/apollo/guardian',
'/apollo/hmi/status',
'/apollo/localization/pose',
'/apollo/localization/msf_gnss',
'/apollo/localization/msf_lidar',
'/apollo/localization/msf_status',
'/apollo/monitor',
'/apollo/monitor/system_status',
'/apollo/navigation',
'/apollo/perception/obstacles',
'/apollo/perception/traffic_light',
'/apollo/planning',
'/apollo/prediction',
'/apollo/relative_map',
'/apollo/routing_request',
'/apollo/routing_response',
'/apollo/routing_response_history',
'/apollo/sensor/conti_radar',
'/apollo/sensor/delphi_esr',
'/apollo/sensor/gnss/best_pose',
'/apollo/sensor/gnss/corrected_imu',
'/apollo/sensor/gnss/gnss_status',
'/apollo/sensor/gnss/imu',
'/apollo/sensor/gnss/ins_stat',
'/apollo/sensor/gnss/odometry',
'/apollo/sensor/gnss/raw_data',
'/apollo/sensor/gnss/rtk_eph',
'/apollo/sensor/gnss/rtk_obs',
'/apollo/sensor/gnss/heading',
'/apollo/sensor/mobileye',
'/tf',
'/tf_static',
]
flags.DEFINE_string('config', '',
'protobuf text format configuration file abosolute path')
flags.DEFINE_string('root_dir', '/apollo/modules/tools/sensor_calibration',
'program root dir')
FLAGS = flags.FLAGS
class Extractor(object):
def __init__(self):
self.node = cyber.Node("sensor_calibration_preprocessor")
self.writer = self.node.create_writer("/apollo/dreamview/progress",
preprocess_table_pb2.Progress, 6)
self.config = extractor_config_pb2.DataExtractionConfig()
self.progress = preprocess_table_pb2.Progress()
self.progress.percentage = 0.0
self.progress.log_string = "Preprocessing in progress..."
self.progress.status = preprocess_table_pb2.Status.UNKNOWN
try:
get_pb_from_text_file(FLAGS.config, self.config)
except text_format.ParseError:
print(f'Error: Cannot parse {FLAGS.config} as text proto')
self.records = []
for r in self.config.records.record_path:
self.records.append(str(r))
self.start_timestamp = -1
self.end_timestamp = -1
if self.config.io_config.start_timestamp == "FLOAT_MIN":
self.start_timestamp = np.finfo(np.float32).min
else:
self.start_timestamp = np.float32(
self.config.io_config.start_timestamp)
if self.config.io_config.end_timestamp == "FLOAT_MAX":
self.end_timestamp = np.finfo(np.float32).max
else:
self.end_timestamp = np.float32(
self.config.io_config.end_timestamp)
@staticmethod
def process_dir(path, operation):
"""Create or remove directory."""
try:
if operation == 'create':
if os.path.exists(path):
print(f'folder: {path} exists')
else:
print(f'create folder: {path}')
os.makedirs(path)
elif operation == 'remove':
os.remove(path)
else:
print(
f'Error! Unsupported operation {operation} for directory.')
return False
except OSError as e:
print(f'Failed to {operation} directory: {path}. '
f'Error: {six.text_type(e)}')
return False
return True
@staticmethod
def get_sensor_channel_list(record_file):
"""Get the channel list of sensors for calibration."""
record_reader = RecordReader(record_file)
return set(channel_name
for channel_name in record_reader.get_channellist()
if 'sensor' in channel_name
or '/localization/pose' in channel_name)
@staticmethod
def validate_channel_list(channels, dictionary):
ret = True
for channel in channels:
if channel not in dictionary:
print(f'ERROR: channel {channel} does not exist in '
'record sensor channels')
ret = False
return ret
@staticmethod
def in_range(v, s, e):
return True if v >= s and v <= e else False
@staticmethod
def build_parser(channel, output_path):
parser = None
if channel.endswith("/image"):
parser = ImageParser(output_path=output_path, instance_saving=True)
elif channel.endswith("/PointCloud2"):
parser = PointCloudParser(output_path=output_path,
instance_saving=True)
elif channel.endswith("/gnss/odometry"):
parser = GpsParser(output_path=output_path, instance_saving=False)
elif channel.endswith("/localization/pose"):
parser = PoseParser(output_path=output_path, instance_saving=False)
elif channel.startswith("/apollo/sensor/radar"):
parser = ContiRadarParser(output_path=output_path,
instance_saving=True)
else:
raise ValueError(f"Not Support this channel type: {channel}")
return parser
def print_and_publish(self,
str,
status=preprocess_table_pb2.Status.UNKNOWN):
"""status: 0 for success, 1 for fail, 2 for unknown"""
print(str)
self.progress.log_string = str
self.progress.status = status
self.writer.write(self.progress)
time.sleep(0.5)
def extract_data(self, record_files, output_path, channels,
extraction_rates):
"""
Extract the desired channel messages if channel_list is specified.
Otherwise extract all sensor calibration messages according to
extraction rate, 10% by default.
"""
# all records have identical sensor channels.
sensor_channels = self.get_sensor_channel_list(record_files[0])
if (len(channels) > 0
and not self.validate_channel_list(channels, sensor_channels)):
print('The input channel list is invalid.')
return False
# Extract all the sensor channels if channel_list is empty(no input arguments).
print(sensor_channels)
if len(channels) == 0:
channels = sensor_channels
# Declare logging variables
process_channel_success_num = len(channels)
process_channel_failure_num = 0
process_msg_failure_num = 0
channel_success = {}
channel_occur_time = {}
channel_output_path = {}
# channel_messages = {}
channel_parsers = {}
channel_message_number = {}
channel_processed_msg_num = {}
for channel in channels:
channel_success[channel] = True
channel_occur_time[channel] = -1
topic_name = channel.replace('/', '_')
channel_output_path[channel] = os.path.join(
output_path, topic_name)
self.process_dir(channel_output_path[channel], operation='create')
channel_parsers[channel] =\
self.build_parser(channel, channel_output_path[channel])
channel_message_number[channel] = 0
for record_file in record_files:
record_reader = RecordReader(record_file)
channel_message_number[
channel] += record_reader.get_messagenumber(channel)
channel_message_number[channel] = channel_message_number[
channel] // extraction_rates[channel]
channel_message_number_total = 0
for num in channel_message_number.values():
channel_message_number_total += num
channel_processed_msg_num = 0
# if channel in SMALL_TOPICS:
# channel_messages[channel] = list()
for record_file in record_files:
record_reader = RecordReader(record_file)
for msg in record_reader.read_messages():
if msg.topic in channels:
# Only care about messages in certain time intervals
msg_timestamp_sec = msg.timestamp / 1e9
if not self.in_range(msg_timestamp_sec,
self.start_timestamp,
self.end_timestamp):
continue
channel_occur_time[msg.topic] += 1
# Extract the topic according to extraction_rate
if channel_occur_time[msg.topic] % extraction_rates[
msg.topic] != 0:
continue
ret = channel_parsers[msg.topic].parse_sensor_message(msg)
channel_processed_msg_num += 1
self.progress.percentage = channel_processed_msg_num / \
channel_message_number_total * 90.0
# Calculate parsing statistics
if not ret:
process_msg_failure_num += 1
if channel_success[msg.topic]:
channel_success[msg.topic] = False
process_channel_failure_num += 1
process_channel_success_num -= 1
log_string = (
'Failed to extract data from channel: '
f'{msg.topic} in record {record_file}')
print(log_string)
self.progress.log_string = log_string
self.writer.write(self.progress)
# traverse the dict, if any channel topic stored as a list
# then save the list as a summary file, mostly binary file
for channel, parser in channel_parsers.items():
self.save_combined_messages_info(parser, channel)
# Logging statics about channel extraction
self.print_and_publish(
(f"Extracted sensor channel number {len(channels)} "
f"from record files: {' '.join(record_files)}"))
self.print_and_publish(
(f'Successfully processed {process_channel_success_num} channels, '
f'and {process_channel_failure_num} was failed.'))
if process_msg_failure_num > 0:
self.print_and_publish(
f'Channel extraction failure number is {process_msg_failure_num}.',
preprocess_table_pb2.Status.FAIL)
return True
@staticmethod
def save_combined_messages_info(parser, channel):
if not parser.save_messages_to_file():
raise ValueError(
f"cannot save combined messages into single file for : {channel}"
)
if not parser.save_timestamps_to_file():
raise ValueError(f"cannot save tiemstamp info for {channel}")
@staticmethod
def generate_compressed_file(input_path,
input_name,
output_path,
compressed_file='sensor_data'):
"""
Compress data extraction directory as a single tar.gz archive
"""
cwd_path = os.getcwd()
os.chdir(input_path)
shutil.make_archive(base_name=os.path.join(output_path,
compressed_file),
format='gztar',
root_dir=input_path,
base_dir=input_name)
os.chdir(cwd_path)
@staticmethod
def generate_extraction_rate_dict(channels,
large_topic_extraction_rate,
small_topic_extraction_rate=1):
"""
Default extraction rate for small topics is 1, which means no sampling
"""
# Validate extration_rate, and set it as an integer.
if large_topic_extraction_rate < 1.0 or small_topic_extraction_rate < 1.0:
raise ValueError(
"Extraction rate must be a number no less than 1.")
large_topic_extraction_rate = np.floor(large_topic_extraction_rate)
small_topic_extraction_rate = np.floor(small_topic_extraction_rate)
rates = {}
for channel in channels:
if channel in SMALL_TOPICS:
rates[channel] = small_topic_extraction_rate
else:
rates[channel] = large_topic_extraction_rate
return rates
@staticmethod
def validate_record(record_file):
"""Validate the record file."""
# Check the validity of a cyber record file according to header info.
record_reader = RecordReader(record_file)
header_msg = record_reader.get_headerstring()
header = record_pb2.Header()
header.ParseFromString(header_msg)
print(f"header is {header}")
if not header.is_complete:
print(f'Record file: {record_file} is not completed.')
return False
if header.size == 0:
print(f'Record file: {record_file}. size is 0.')
return False
if header.major_version != 1 and header.minor_version != 0:
print(
f'Record file: {record_file}. version [{header.major_version}: '
f'{header.minor_version}] is wrong.')
return False
if header.begin_time >= header.end_time:
print(
f'Record file: {record_file}. begin time [{header.begin_time}] '
f'is equal or larger than end time [{header.end_time}].')
return False
if header.message_number < 1 or header.channel_number < 1:
print(
f'Record file: {record_file}. [message:channel] number '
f'[{header.message_number}:{header.channel_number}] is invalid.'
)
return False
# There should be at least one sensor channel
sensor_channels = Extractor.get_sensor_channel_list(record_file)
if len(sensor_channels) < 1:
print(f'Record file: {record_file}. cannot find sensor channels.')
return False
return True
def validate_record_files(self, kword='.record.'):
# load file list from directory if needs
file_abs_paths = []
if not isinstance(self.records, list):
raise ValueError("Record files must be in a list")
records = self.records
if len(records) == 1 and os.path.isdir(records[0]):
print(f'Load cyber records from: {records[0]}')
for f in sorted(os.listdir(records[0])):
if kword in f:
file_abs_path = os.path.join(records[0], f)
if Extractor.validate_record(file_abs_path):
file_abs_paths.append(file_abs_path)
else:
print(f'Invalid record file: {file_abs_path}')
else:
for f in records:
if not os.path.isfile(f):
raise ValueError("Input cyber record does not exist "
f"or not a regular file: {f}")
if Extractor.validate_record(f):
file_abs_paths.append(f)
else:
print(f'Invalid record file: {f}')
if len(file_abs_paths) < 1:
raise ValueError("All the input record files are invalid")
# Validate all record files have the same sensor topics
first_record_file = file_abs_paths[0]
default_sensor_channels = Extractor.get_sensor_channel_list(
first_record_file)
for i, f in enumerate(file_abs_paths[1:]):
sensor_channels = Extractor.get_sensor_channel_list(f)
if sensor_channels != default_sensor_channels:
print(
f'Default sensor channel list in {first_record_file} is: ')
print(default_sensor_channels)
print(f'but sensor channel list in {file_abs_paths[i]} is: ')
print(sensor_channels)
raise ValueError(
"The record files should contain the same channel list")
return file_abs_paths
def parse_channel_config(self):
channel_list = set()
extraction_rate_dict = dict()
for channel in self.config.channels.channel:
if channel.name in channel_list:
raise ValueError(
f"Duplicated channel config for : {channel.name}")
else:
channel_list.add(channel.name)
extraction_rate_dict[channel.name] = channel.extraction_rate
return channel_list, extraction_rate_dict
@staticmethod
def get_substring(str, prefix, suffix):
"""return substring, eclusive prefix or suffix"""
str_p = str.rfind(prefix) + len(prefix)
end_p = str.rfind(suffix)
return str[str_p:end_p]
def reorganize_extracted_data(self,
tmp_data_path,
remove_input_data_cache=False):
root_path = os.path.dirname(os.path.normpath(tmp_data_path))
output_path = None
config_yaml = ConfigYaml()
task_name = self.config.io_config.task_name
if task_name == 'lidar_to_gnss':
subfolders = [
x for x in get_subfolder_list(tmp_data_path)
if '_apollo_sensor_' in x or '_localization_pose' in x
]
odometry_subfolders = [
x for x in subfolders if '_odometry' in x or '_pose' in x
]
lidar_subfolders = [x for x in subfolders if '_PointCloud2' in x]
print(lidar_subfolders)
print(odometry_subfolders)
if len(lidar_subfolders) == 0 or len(odometry_subfolders) != 1:
raise ValueError(('one odometry and more than 0 lidar(s)'
'sensor are needed for sensor calibration'))
odometry_subfolder = odometry_subfolders[0]
yaml_list = []
gnss_name = 'novatel'
multi_lidar_out_path = os.path.join(
root_path, 'multi_lidar_to_gnss_calibration')
output_path = multi_lidar_out_path
for lidar in lidar_subfolders:
# get the lidar name from folder name string
lidar_name = Extractor.get_substring(str=lidar,
prefix='_apollo_sensor_',
suffix='_PointCloud2')
# reorganize folder structure: each lidar has its raw data,
# corresponding odometry and configuration yaml file
if not Extractor.process_dir(multi_lidar_out_path, 'create'):
raise ValueError(
f'Failed to create directory: {multi_lidar_out_path}')
lidar_in_path = os.path.join(tmp_data_path, lidar)
lidar_out_path = os.path.join(multi_lidar_out_path, lidar)
if not os.path.exists(lidar_out_path):
shutil.copytree(lidar_in_path, lidar_out_path)
odometry_in_path = os.path.join(tmp_data_path,
odometry_subfolder)
odometry_out_path = os.path.join(multi_lidar_out_path,
odometry_subfolder)
if not os.path.exists(odometry_out_path):
shutil.copytree(odometry_in_path, odometry_out_path)
generated_config_yaml = os.path.join(
tmp_data_path, lidar_name + '_' + 'sample_config.yaml')
config_yaml.generate_task_config_yaml(
task_name=task_name,
source_sensor=lidar_name,
dest_sensor=gnss_name,
source_folder=lidar,
dest_folder=odometry_subfolder,
out_config_file=generated_config_yaml)
print(f'lidar {lidar_name} calibration data and configuration'
' are generated.')
yaml_list.append(generated_config_yaml)
out_data = {
'calibration_task': task_name,
'destination_sensor': gnss_name,
'odometry_file': odometry_subfolder + '/odometry'
}
sensor_files_directory_list = []
source_sensor_list = []
transform_list = []
for i in range(len(yaml_list)):
with open(yaml_list[i], 'r') as f:
data = yaml.safe_load(f)
sensor_files_directory_list.append(
data['sensor_files_directory'])
source_sensor_list.append(data['source_sensor'])
transform_list.append(data['transform'])
out_data['sensor_files_directory'] = sensor_files_directory_list
out_data['source_sensor'] = source_sensor_list
out_data['transform'] = transform_list
out_data['main_sensor'] = source_sensor_list[0]
table = preprocess_table_pb2.PreprocessTable()
user_config = os.path.join(FLAGS.root_dir, 'config',
'lidar_to_gnss_user.config')
if os.path.exists(user_config):
try:
get_pb_from_text_file(user_config, table)
except text_format.ParseError:
print(f'Error: Cannot parse {user_config} as text proto')
if table.HasField("main_sensor"):
out_data['main_sensor'] = table.main_sensor
multi_lidar_yaml = os.path.join(multi_lidar_out_path,
'sample_config.yaml')
with open(multi_lidar_yaml, 'w') as f:
yaml.safe_dump(out_data, f)
elif task_name == 'camera_to_lidar':
# data selection.
pair_data_folder_name = 'camera-lidar-pairs'
cameras, lidar = select_static_image_pcd(
path=tmp_data_path,
min_distance=5,
stop_times=4,
wait_time=3,
check_range=50,
image_static_diff_threshold=0.005,
output_folder_name=pair_data_folder_name,
image_suffix='.jpg',
pcd_suffix='.pcd')
lidar_name = Extractor.get_substring(str=lidar,
prefix='_apollo_sensor_',
suffix='_PointCloud2')
for camera in cameras:
camera_name = Extractor.get_substring(str=camera,
prefix='_apollo_sensor_',
suffix='_image')
out_path = os.path.join(
root_path,
camera_name + '_to_' + lidar_name + '_calibration')
output_path = out_path
if not Extractor.process_dir(out_path, 'create'):
raise ValueError(f'Failed to create directory: {out_path}')
# reorganize folder structure: each camera has its images,
# corresponding lidar pointclouds, camera initial extrinsics,
# intrinsics, and configuration yaml file
in_pair_data_path = os.path.join(tmp_data_path, camera,
pair_data_folder_name)
out_pair_data_path = os.path.join(out_path,
pair_data_folder_name)
shutil.copytree(in_pair_data_path, out_pair_data_path)
generated_config_yaml = os.path.join(out_path,
'sample_config.yaml')
config_yaml.generate_task_config_yaml(
task_name=task_name,
source_sensor=camera_name,
dest_sensor=lidar_name,
source_folder=None,
dest_folder=None,
out_config_file=generated_config_yaml)
elif task_name == 'radar_to_gnss':
print('not ready. stay tuned')
else:
raise ValueError(
f'Unsupported data extraction task for {task_name}')
if remove_input_data_cache:
print(f'removing the cache at {tmp_data_path}')
os.system(f'rm -rf {tmp_data_path}')
return output_path
def sanity_check_path(self, path):
"""Sanity check wrapper"""
result, log_str = sanity_check(path)
if result is True:
self.progress.percentage = 100.0
self.progress.status = preprocess_table_pb2.Status.SUCCESS
else:
self.progress.status = preprocess_table_pb2.Status.FAIL
self.progress.log_string = log_str
self.writer.write(self.progress)
time.sleep(0.5)
def create_tmp_directory(self):
"""Create directory to save the extracted data use time now() as folder name"""
output_relative_path = self.config.io_config.task_name + datetime.now(
).strftime("-%Y-%m-%d-%H-%M") + '/tmp/'
output_abs_path = os.path.join(self.config.io_config.output_path,
output_relative_path)
ret = self.process_dir(output_abs_path, 'create')
if not ret:
raise ValueError(
f'Failed to create extrated data directory: {output_abs_path}')
return output_abs_path
def main(argv):
"""Main function"""
cyber.init("data_extractor")
extractor = Extractor()
valid_record_list = extractor.validate_record_files(kword='.record.')
channels, extraction_rates = extractor.parse_channel_config()
print(f'parsing the following channels: {channels}')
output_tmp_path = extractor.create_tmp_directory()
extractor.extract_data(valid_record_list, output_tmp_path, channels,
extraction_rates)
output_abs_path = extractor.reorganize_extracted_data(
tmp_data_path=output_tmp_path, remove_input_data_cache=True)
print('Data extraction is completed successfully!')
extractor.sanity_check_path(output_abs_path)
cyber.shutdown()
sys.exit(0)
if __name__ == '__main__':
# root_path = '/apollo/data/extracted_data/MKZ5-2019-05-15/lidar_to_gnss-2019-11-25-11-02/tmp'
# task_name = 'lidar_to_gnss'
# root_path = '/apollo/data/extracted_data/udevl002-2019-06-14/camera_to_lidar-2019-11-26-19-49/tmp'
# task_name = 'camera_to_lidar'
# reorganize_extracted_data(tmp_data_path=root_path, task_name=task_name)
app.run(main)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary", "py_library")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
install(
name = "install",
data = ["runtime_files"],
data_dest = "tools/sensor_calibration",
py_dest = "tools/sensor_calibration",
targets = [
":extract_data",
":extract_static_data",
":ins_stat_publisher",
":odom_publisher",
":sanity_check",
],
deps = ["//modules/tools/sensor_calibration/config:install"]
)
filegroup(
name = "runtime_files",
srcs = glob([
#"config/**",
"template/**",
"*.py",
"*.sh",
]),
)
py_library(
name = "configuration_yaml_generator",
srcs = ["configuration_yaml_generator.py"],
deps = [
"//modules/dreamview/proto:preprocess_table_py_pb2",
"//modules/tools/common:proto_utils",
],
)
py_library(
name = "data_file_object",
srcs = ["data_file_object.py"],
)
py_binary(
name = "extract_data",
srcs = ["extract_data.py"],
data = [":runtime_files"],
deps = [
":configuration_yaml_generator",
":extract_static_data",
":sanity_check",
":sensor_msg_extractor",
"//cyber/proto:record_py_pb2",
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:record",
"//modules/dreamview/proto:preprocess_table_py_pb2",
"//modules/tools/common:proto_utils",
"//modules/tools/sensor_calibration/proto:extractor_config_py_pb2",
],
)
py_binary(
name = "extract_static_data",
srcs = ["extract_static_data.py"],
data = [":runtime_files"],
deps = [
":configuration_yaml_generator",
":data_file_object",
"//cyber/proto:record_py_pb2",
"//cyber/python/cyber_py3:record",
"//modules/tools/sensor_calibration/proto:extractor_config_py_pb2",
],
)
py_binary(
name = "ins_stat_publisher",
srcs = ["ins_stat_publisher.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:cyber_time",
"//modules/common_msgs/sensor_msgs:ins_py_pb2",
],
)
py_binary(
name = "odom_publisher",
srcs = ["odom_publisher.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:cyber_time",
"//modules/common_msgs/localization_msgs:gps_py_pb2",
"//modules/common_msgs/localization_msgs:localization_py_pb2",
],
)
py_library(
name = "sensor_msg_extractor",
srcs = ["sensor_msg_extractor.py"],
deps = [
":data_file_object",
"//modules/common_msgs/sensor_msgs:conti_radar_py_pb2",
"//modules/common_msgs/sensor_msgs:pointcloud_py_pb2",
"//modules/common_msgs/sensor_msgs:sensor_image_py_pb2",
"//modules/common_msgs/localization_msgs:gps_py_pb2",
"//modules/common_msgs/localization_msgs:localization_py_pb2",
],
)
py_binary(
name = "sanity_check",
srcs = ["sanity_check.py"],
deps = [
"//modules/tools/common:file_utils",
],
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/ins_stat_publisher.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2020 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.
###############################################################################
import argparse
import atexit
import logging
import os
import sys
import time
#from common.logger import Logger
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3 import cyber_time
from modules.common_msgs.sensor_msgs import ins_pb2
class InsStat(object):
def __init__(self,node):
self.insstat_pub = node.create_writer('/apollo/sensor/gnss/ins_stat', ins_pb2.InsStat)
self.sequence_num = 0
self.terminating = False
def publish_statmsg(self):
insstat = ins_pb2.InsStat()
now = cyber_time.Time.now().to_sec()
insstat.header.timestamp_sec = now
insstat.header.module_name = "ins_stat"
insstat.header.sequence_num = self.sequence_num
self.sequence_num = self.sequence_num + 1
insstat.ins_status = 3
insstat.pos_type = 56
#self.logger.info("%s"%insstat)
self.insstat_pub.write(insstat)
def shutdown(self):
"""
shutdown rosnode
"""
self.terminating = True
#self.logger.info("Shutting Down...")
time.sleep(0.2)
def main():
"""
Main rosnode
"""
node=cyber.Node('ins_stat_publisher')
ins_stat = InsStat(node)
while not cyber.is_shutdown():
now = cyber_time.Time.now().to_sec()
ins_stat.publish_statmsg()
sleep_time = 0.5 - (cyber_time.Time.now().to_sec() - now)
if sleep_time > 0:
time.sleep(sleep_time)
if __name__ == '__main__':
cyber.init()
main()
cyber.shutdown()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/data_file_object.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2019 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.
###############################################################################
"""
This is a bunch of classes to manage cyber record channel FileIO.
"""
import os
import sys
import struct
import numpy as np
class FileObject(object):
"""Wrapper for file object"""
# Initializing file object
def __init__(self, file_path, operation='write', file_type='binary'):
if operation != 'write' and operation != 'read':
raise ValueError("Unsupported file operation: %s" % operation)
if file_type != 'binary' and file_type != 'txt':
raise ValueError("Unsupported file type: %s" % file_type)
operator = 'w' if operation == 'write' else 'r'
operator += 'b' if file_type == 'binary' else ''
try:
self._file_object = open(file_path, operator)
except IOError:
raise ValueError("Cannot open file: {}".format(file_path))
# Safely close file
def __del__(self):
self._file_object.close()
def file_object(self):
return self._file_object
def save_to_file(self, data):
raise NotImplementedError
class TimestampFileObject(FileObject):
"""class to handle sensor timestamp for each Apollo sensor channel"""
def __init__(self, file_path, operation='write', file_type='txt'):
super(TimestampFileObject, self).__init__(file_path,
operation, file_type)
def save_to_file(self, data):
if not isinstance(data, list) and not isinstance(data, np.ndarray):
raise ValueError("timestamps must be in a list")
for i, ts in enumerate(data):
self._file_object.write("%05d %.6f\n" % (i + 1, ts))
class OdometryFileObject(FileObject):
"""class to handle gnss/odometry topic"""
def load_file(self):
struct_len = struct.calcsize('i')
data_size = struct.Struct('i').unpack(self._file_object.read(struct.calcsize('i')))[0]
s0 = struct.Struct('d')
s1 = struct.Struct('I')
s2 = struct.Struct('7d')
data = np.zeros((data_size, 9), dtype='float64')
# , int32, float64, float64, float64, float64, float64, float64, float64')
for d in data:
#d[0] = s0.unpack_from(self._file_object.read(s0.size))[0]
d[0] = s0.unpack(self._file_object.read(s0.size))[0]
d[1] = s1.unpack_from(self._file_object.read(s1.size))[0]
d[2:] = np.array(s2.unpack_from(self._file_object.read(s2.size)))
return data.tolist()
def save_to_file(self, data):
"""
odometry data: total 9 elements
[
double timestamp
int32 postion_type
double qw, qx, qy, qz
double x, y, z
]
"""
if not isinstance(data, list):
raise ValueError("Odometry data must be in a list")
data_size = len(data)
self._file_object.write(struct.pack('I', data_size))
# have to pack separate, to avoid struct padding, now 8+4+7*8 = 68 bytes
# TODO (yuanfan / gchen-Apollo): follow protobuf across tools.
s0 = struct.Struct('d')
s1 = struct.Struct('I')
s2 = struct.Struct('7d')
for d in data:
# print(d[0])
self._file_object.write(s0.pack(d[0]))
self._file_object.write(s1.pack(d[1]))
pack_d = s2.pack(d[2], d[3], d[4], d[5], d[6], d[7], d[8])
self._file_object.write(pack_d)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/sensor_msg_extractor.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2019 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.
###############################################################################
"""
This is a bunch of classes to manage cyber record channel extractor.
"""
import os
import struct
import sys
import cv2
import numpy as np
from pypcd import pypcd
from modules.tools.sensor_calibration.data_file_object import TimestampFileObject, OdometryFileObject
from modules.common_msgs.sensor_msgs import conti_radar_pb2
from modules.common_msgs.sensor_msgs import sensor_image_pb2
from modules.common_msgs.sensor_msgs import pointcloud_pb2
from modules.common_msgs.localization_msgs import gps_pb2
from modules.common_msgs.localization_msgs import localization_pb2
class SensorMessageParser(object):
"""Wrapper for cyber channel message extractor"""
# Initializing extractor
def __init__(self, output_path, instance_saving=True):
"""
instance_saving:
True for large channel message, e.g., Camera/lidar/Radar;
False for small channel message, e.g., GNSS topics
"""
self._msg_parser = None
self._timestamps = []
self._proto_parser = None
self._init_parser()
self._parsed_data = None
self._output_path = output_path
self._timestamp_file = os.path.join(self._output_path, "timestamps")
self._instance_saving = instance_saving
# initializing msg and proto parser
def _init_parser(self):
raise NotImplementedError
def parse_sensor_message(self, msg):
raise NotImplementedError
def save_messages_to_file(self):
return True
def get_msg_count(self):
return len(self._timestamps)
def get_timestamps(self):
return self._timestamps
def save_timestamps_to_file(self):
timestamp_file_obj = TimestampFileObject(self._timestamp_file,
operation='write',
file_type='txt')
timestamp_file_obj.save_to_file(self._timestamps)
return True
class GpsParser(SensorMessageParser):
"""
class to parse GNSS odometry channel.
saving this small topic as a whole.
"""
def __init__(self, output_path, instance_saving=False):
super(GpsParser, self).__init__(output_path, instance_saving)
if not self._instance_saving:
self._parsed_data = []
self._odomotry_output_file = os.path.join(self._output_path, "odometry")
def _init_parser(self):
self._msg_parser = gps_pb2.Gps()
def parse_sensor_message(self, msg):
""" parse Gps information from GNSS odometry channel"""
gps = self._msg_parser
gps.ParseFromString(msg.message)
# all double, except point_type is int32
ts = gps.header.timestamp_sec
self._timestamps.append(ts)
point_type = 56
qw = gps.localization.orientation.qw
qx = gps.localization.orientation.qx
qy = gps.localization.orientation.qy
qz = gps.localization.orientation.qz
x = gps.localization.position.x
y = gps.localization.position.y
z = gps.localization.position.z
# save 9 values as a tuple, for eaisier struct packing during storage
if self._instance_saving:
raise ValueError("Gps odometry should be saved in a file")
else:
self._parsed_data.append((ts, point_type, qw, qx, qy, qz, x, y, z))
return True
def save_messages_to_file(self):
"""save list of parsed Odometry messages to file"""
odometry_file_obj = OdometryFileObject(file_path=self._odomotry_output_file,
operation='write',
file_type='binary')
odometry_file_obj.save_to_file(self._parsed_data)
return True
class PoseParser(GpsParser):
"""
inherit similar data saver and data structure from GpsParser
save the ego-localization information same as odometry
"""
def _init_parser(self):
self._msg_parser = localization_pb2.LocalizationEstimate()
def parse_sensor_message(self, msg):
""" parse localization information from localization estimate channel"""
loc_est = self._msg_parser
loc_est.ParseFromString(msg.message)
# all double, except point_type is int32
ts = loc_est.header.timestamp_sec
self._timestamps.append(ts)
point_type = 56
qw = loc_est.pose.orientation.qw
qx = loc_est.pose.orientation.qx
qy = loc_est.pose.orientation.qy
qz = loc_est.pose.orientation.qz
x = loc_est.pose.position.x
y = loc_est.pose.position.y
z = loc_est.pose.position.z
# save 9 values as a tuple, for eaisier struct packing during storage
if self._instance_saving:
raise ValueError("localization--pseudo odometry-- should be saved in a file")
else:
self._parsed_data.append((ts, point_type, qw, qx, qy, qz, x, y, z))
return True
class PointCloudParser(SensorMessageParser):
"""
class to parse apollo/$(lidar)/PointCloud2 channels.
saving separately each parsed msg
"""
def __init__(self, output_path, instance_saving=True, suffix='.pcd'):
super(PointCloudParser, self).__init__(output_path, instance_saving)
self._suffix = suffix
def convert_xyzit_pb_to_array(self, xyz_i_t, data_type):
arr = np.zeros(len(xyz_i_t), dtype=data_type)
for i, point in enumerate(xyz_i_t):
# change timestamp to timestamp_sec
arr[i] = (point.x, point.y, point.z,
point.intensity, point.timestamp/1e9)
return arr
def make_xyzit_point_cloud(self, xyz_i_t):
"""
Make a pointcloud object from PointXYZIT message, as Pointcloud.proto.
message PointXYZIT {
optional float x = 1 [default = nan];
optional float y = 2 [default = nan];
optional float z = 3 [default = nan];
optional uint32 intensity = 4 [default = 0];
optional uint64 timestamp = 5 [default = 0];
}
"""
md = {'version': .7,
'fields': ['x', 'y', 'z', 'intensity', 'timestamp'],
'count': [1, 1, 1, 1, 1],
'width': len(xyz_i_t),
'height': 1,
'viewpoint': [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0],
'points': len(xyz_i_t),
'type': ['F', 'F', 'F', 'U', 'F'],
'size': [4, 4, 4, 4, 8],
'data': 'binary_compressed'}
typenames = []
for t, s in zip(md['type'], md['size']):
np_type = pypcd.pcd_type_to_numpy_type[(t, s)]
typenames.append(np_type)
np_dtype = np.dtype(list(zip(md['fields'], typenames)))
pc_data = self.convert_xyzit_pb_to_array(xyz_i_t, data_type=np_dtype)
pc = pypcd.PointCloud(md, pc_data)
return pc
def save_pointcloud_meta_to_file(self, pc_meta, pcd_file):
pypcd.save_point_cloud_bin_compressed(pc_meta, pcd_file)
def _init_parser(self):
self._msg_parser = pointcloud_pb2.PointCloud()
def parse_sensor_message(self, msg):
"""
Transform protobuf PointXYZIT to standard PCL bin_compressed_file(*.pcd).
"""
pointcloud = self._msg_parser
pointcloud.ParseFromString(msg.message)
self._timestamps.append(pointcloud.measurement_time)
# self._timestamps.append(pointcloud.header.timestamp_sec)
self._parsed_data = self.make_xyzit_point_cloud(pointcloud.point)
if self._instance_saving:
file_name = "%05d" % self.get_msg_count() + self._suffix
output_file = os.path.join(self._output_path, file_name)
self.save_pointcloud_meta_to_file(pc_meta=self._parsed_data, pcd_file=output_file)
else:
raise ValueError("not implement multiple message concatenation for PointCloud2 topic")
# TODO(gchen-Apollo): add saint check
return True
class ImageParser(SensorMessageParser):
"""
class to parse apollo/$(camera)/image channels.
saving separately each parsed msg
"""
def __init__(self, output_path, instance_saving=True, suffix='.jpg'):
super(ImageParser, self).__init__(output_path, instance_saving)
self._suffix = suffix
def _init_parser(self):
self._msg_parser = sensor_image_pb2.Image()
def parse_sensor_message(self, msg):
image = self._msg_parser
image.ParseFromString(msg.message)
self._timestamps.append(image.header.timestamp_sec)
# Save image according to cyber format, defined in sensor camera proto.
# height = 4, image height, that is, number of rows.
# width = 5, image width, that is, number of columns.
# encoding = 6, as string, type is 'rgb8', 'bgr8' or 'gray'.
# step = 7, full row length in bytes.
# data = 8, actual matrix data in bytes, size is (step * rows).
# type = CV_8UC1 if image step is equal to width as gray, CV_8UC3
# if step * 3 is equal to width.
if image.encoding == 'rgb8' or image.encoding == 'bgr8':
if image.step != image.width * 3:
print('Image.step %d does not equal to Image.width %d * 3 for color image.'
% (image.step, image.width))
return False
elif image.encoding == 'gray' or image.encoding == 'y':
if image.step != image.width:
print('Image.step %d does not equal to Image.width %d or gray image.'
% (image.step, image.width))
return False
else:
print('Unsupported image encoding type: %s.' % image.encoding)
return False
channel_num = image.step // image.width
self._parsed_data = np.fromstring(image.data, dtype=np.uint8).reshape(
(image.height, image.width, channel_num))
if self._instance_saving:
file_name = "%05d" % self.get_msg_count() + self._suffix
output_file = os.path.join(self._output_path, file_name)
self.save_image_mat_to_file(image_file=output_file)
else:
raise ValueError("not implement multiple message concatenation for Image topic")
return True
def save_image_mat_to_file(self, image_file):
# Save image in BGR oder
image_mat = self._parsed_data
if self._msg_parser.encoding == 'rgb8':
cv2.imwrite(image_file, cv2.cvtColor(image_mat, cv2.COLOR_RGB2BGR))
else:
cv2.imwrite(image_file, image_mat)
class ContiRadarParser(SensorMessageParser):
"""
class to parse apollo/sensor/radar/$(position) channels.
saving separately each parsed msg
"""
def __init__(self, output_path, instance_saving=True, suffix='.pcd'):
super(ContiRadarParser, self).__init__(output_path, instance_saving)
self._suffix = suffix
def convert_contiobs_pb_to_array(self, obs, data_type):
arr = np.zeros(len(obs), dtype=data_type)
for i, ob in enumerate(obs):
# change timestamp to timestamp_sec
# z value is 0
# now using x, y, z, and t. later more information will be added
arr[i] = (ob.longitude_dist, ob.lateral_dist, 0, ob.header.timestamp_sec)
return arr
def make_contidata_point_cloud(self, contiobs):
"""
Make a pointcloud object from contiradar message, as conti_radar.proto.
message ContiRadarObs {
// x axis ^
// | longitude_dist
// |
// |
// |
// lateral_dist |
// y axis |
// <----------------
// ooooooooooooo //radar front surface
optional apollo.common.Header header = 1;
// longitude distance to the radar; (+) = forward; unit = m
optional double longitude_dist = 4;
// lateral distance to the radar; (+) = left; unit = m
optional double lateral_dist = 5;
.......
}
"""
md = {'version': .7,
'fields': ['x', 'y', 'z', 'timestamp'],
'count': [1, 1, 1, 1],
'width': len(contiobs),
'height': 1,
'viewpoint': [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0],
'points': len(contiobs),
'type': ['F', 'F', 'F', 'F'],
'size': [4, 4, 4, 8],
'data': 'binary'}
typenames = []
for t, s in zip(md['type'], md['size']):
np_type = pypcd.pcd_type_to_numpy_type[(t, s)]
typenames.append(np_type)
np_dtype = np.dtype(list(zip(md['fields'], typenames)))
pc_data = self.convert_contiobs_pb_to_array(contiobs, data_type=np_dtype)
pc = pypcd.PointCloud(md, pc_data)
return pc
def save_pointcloud_meta_to_file(self, pc_meta, pcd_file):
pypcd.save_point_cloud_bin(pc_meta, pcd_file)
def _init_parser(self):
self._msg_parser = conti_radar_pb2.ContiRadar()
def parse_sensor_message(self, msg):
"""
Transform protobuf radar message to standard PCL bin_file(*.pcd).
"""
radar_data = self._msg_parser
radar_data.ParseFromString(msg.message)
self._timestamps.append(radar_data.header.timestamp_sec)
# self._timestamps.append(pointcloud.header.timestamp_sec)
self._parsed_data = self.make_contidata_point_cloud(radar_data.contiobs)
if self._instance_saving:
file_name = "%05d" % self.get_msg_count() + self._suffix
output_file = os.path.join(self._output_path, file_name)
self.save_pointcloud_meta_to_file(pc_meta=self._parsed_data, pcd_file=output_file)
else:
raise ValueError("not implement multiple message concatenation for COontiRadar topic")
# TODO(gchen-Apollo): add saint check
return True
| 0
|
apollo_public_repos/apollo/modules/tools/sensor_calibration
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/proto/extractor_config.proto
|
/******************************************************************************
* Copyright 2019 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.
*****************************************************************************/
// data extractor configuration
syntax = "proto2";
message IoConfig {
required string task_name = 1 [default = "tmp"];
required string output_path = 2 [default = "extracted_data"];
optional string start_timestamp = 3 [default = "FLOAT_MIN"];
optional string end_timestamp = 4 [default = "FLOAT_MAX"];
optional string main_sensor = 5;
};
message ChannelConfig {
optional string description = 1 [default = ""];
required string name = 2;
required uint32 extraction_rate = 3 [default = 1];
};
message Channels {
repeated ChannelConfig channel = 1;
};
message Records {
repeated string record_path = 1;
};
message DataExtractionConfig {
required IoConfig io_config = 1;
required Channels channels = 2;
required Records records = 3;
};
| 0
|
apollo_public_repos/apollo/modules/tools/sensor_calibration
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/proto/BUILD
|
## Auto generated by `proto_build_generator.py`
load("@rules_proto//proto:defs.bzl", "proto_library")
load("@rules_cc//cc:defs.bzl", "cc_proto_library")
load("//tools:python_rules.bzl", "py_proto_library")
package(default_visibility = ["//visibility:public"])
cc_proto_library(
name = "extractor_config_cc_proto",
deps = [
":extractor_config_proto",
],
)
proto_library(
name = "extractor_config_proto",
srcs = ["extractor_config.proto"],
)
py_proto_library(
name = "extractor_config_py_pb2",
deps = [
":extractor_config_proto",
],
)
| 0
|
apollo_public_repos/apollo/modules/tools/sensor_calibration
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/config/camera_to_lidar_sample_config.yaml
|
# calibration from camera to lidar.
calibration_task: "camera_to_lidar"
source_sensor: camera_head_left
destination_sensor: velodyne64
# beam number of the lidar sensor. For example, Velodyne-128 has 128 beams, Velodyne-16 has 16 beams
beams: 64 # will change to velodyne lidar model later
# relative path of camera intrinsic and initial extrinsic YAML files.
intrinsic: "./init_params/camera_head_left_intrinsics.yaml"
extrinsic: "./init_params/camera_head_left_to_velodyne64_extrinsics.yaml"
# relative path of camera-lidar data pair for calibrations.
data_path: "./camera-lidar-pairs"
#save result params:
| 0
|
apollo_public_repos/apollo/modules/tools/sensor_calibration
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/config/camera_to_lidar_calibration.config
|
# data extraction configuration for multi-camera to lidar calibration
# must includes:
# at least 1 camera image channel
# lidar 128 point cloud channel
# GNSS Gps/odometry channel
io_config: {
# task name now only support "camera_to_lidar, lidar_to_gnss"
task_name: "camera_to_lidar"
output_path: "/apollo/data/extracted_data"
# start_timestamp: "FLOAT_MIN"
# end_timestamp: "FLOAT_MAX"
# start_timestamp: "1553901009.071362291"
# end_timestamp: "1553901012.01"
}
records: {
# records can be specified as a list
record_path: "/apollo/data/bag/test/20190325185008.record.00001"
record_path: "/apollo/data/bag/test/20190325185008.record.00002"
record_path: "/apollo/data/bag/test/20190325185008.record.00003"
# or, records can be loaded from a directory
#record_path: "/apollo/data/bag/test/"
}
channels: {
# channel of camera image channels
channel: {
description: "front camera 6mm"
name: "/apollo/sensor/camera/front_6mm/image"
extraction_rate: 5
}
channel: {
description: "front camera 12mm"
name: "/apollo/sensor/camera/front_12mm/image"
extraction_rate: 5
}
channel: {
description: "front camera fisheye"
name: "/apollo/sensor/camera/front_fisheye/image"
extraction_rate: 5
}
# channel: {
# description: "left camera fisheye"
# name: "/apollo/sensor/camera/left_fisheye/image"
# extraction_rate: 5
# }
# channel: {
# description: "right camera fisheye"
# name: "/apollo/sensor/camera/right_fisheye/image"
# extraction_rate: 5
# }
# channel: {
# description: "rear camera 6mm"
# name: "/apollo/sensor/camera/rear_6mm_fisheye/image"
# extraction_rate: 5
# }
# channel of 128-beam lidar
channel: {
description: "lidar 128 point cloud"
name: "/apollo/sensor/lidar128/PointCloud2"
extraction_rate: 5
}
# channel of GNSS odometry
channel: {
description: "GNSS odometry"
name: "/apollo/sensor/gnss/odometry"
extraction_rate: 1
}
}
| 0
|
apollo_public_repos/apollo/modules/tools/sensor_calibration
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/config/lidar_to_gnss_sample_config.yaml
|
#LiDAR-to-GNSS calibration data service configurations
#Sensor names: calibrate the source_sensor in destination_sensor coordinate
calibration_task: "lidar_to_gnss"
source_sensor: "velodyne128"
destination_sensor: "novatel"
#for lidar-gnss. use odometry message and lidar message.
#provide the local file directory( relevant to this config file), for the sensor message storage.
odometry_file: "./_sensor_novatel_Odometry/odometry"
sensor_files_directory: "./_sensor_velodyne64_VelodyneScan/"
#initial calibration paramters, including translation and raotation, to project a point in source
#source_sensor coordinate to destination_sensor coordinate. translation is in meter. rotation is in quaternion
transform:
translation:
x: 0.0
y: 0.0
z: 0.0
rotation:
x: 0.0
y: 0.0
z: 0.7071
w: 0.7071
| 0
|
apollo_public_repos/apollo/modules/tools/sensor_calibration
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/config/BUILD
|
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "runtime_files",
srcs = glob([
"*.yaml",
"*.config",
"init_params/*"
]),
)
install(
name = "install",
data = [":runtime_files"],
data_dest = "tools/sensor_calibration/config",
deps = ["//modules/tools/sensor_calibration/config/init_params:install"]
)
| 0
|
apollo_public_repos/apollo/modules/tools/sensor_calibration
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/config/lidar_to_GNSS_calibration.config
|
# data extraction configuration for multi-lidar to GNSS Gps calibration
# must includes:
# at least 1 lidar pointcloud2 channel
# GNSS Gps/odometry channel
io_config: {
# task name now only support "camera_to_lidar, lidar_to_gnss"
task_name: "lidar_to_gnss"
output_path: "/apollo/data/extracted_data"
# start_timestamp: "FLOAT_MIN"
# end_timestamp: "FLOAT_MAX"
# start_timestamp: "1553901009.071362291"
# end_timestamp: "1553901012.01"
}
records: {
# records can be specified as a list
record_path: "/apollo/data/bag/test/20190325185008.record.00001"
record_path: "/apollo/data/bag/test/20190325185008.record.00002"
record_path: "/apollo/data/bag/test/20190325185008.record.00003"
# or, records can be loaded from a directory
#record_path: "/apollo/data/bag/test/"
}
channels: {
# channel of mulitple lidars
channel: {
description: "lidar 128 point cloud"
name: "/apollo/sensor/lidar128/PointCloud2"
extraction_rate: 5
}
channel: {
description: "lidar 16 rear left point cloud"
name: "/apollo/sensor/lidar16/rear/left/PointCloud2"
extraction_rate: 5
}
channel: {
description: "lidar 16 rear right point cloud"
name: "/apollo/sensor/lidar16/rear/right/PointCloud2"
extraction_rate: 5
}
channel: {
description: "lidar 16 front center point cloud"
name: "/apollo/sensor/lidar16/front/center/PointCloud2"
extraction_rate: 5
}
# channel: {
# description: "lidar 16 front up point cloud"
# name: "/apollo/sensor/lidar16/front/up/PointCloud2"
# extraction_rate: 5
# }
# channel of GNSS odometry
channel: {
description: "GNSS odometry"
name: "/apollo/sensor/gnss/odometry"
extraction_rate: 1
}
}
| 0
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/config
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/config/init_params/sample_intrinsics.yaml
|
header:
seq: 0
stamp:
secs: 0
nsecs: 0
frame_id: ''
#change image resolution if needs
height: 1080
width: 1920
# change the distortion_model and R if needs.
# change D and K for sure.
distortion_model: plumb_bob
D: [-0.5467789805057404, 0.2729182152572299, -0.0019514549064445735, -0.0004166085741949163, 0.0]
K: [1998.5484365316602, 0.0, 917.7422426747606, 0.0, 1990.2872857509276, 567.1297837900606, 0.0, 0.0, 1.0]
R: [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]
binning_x: 0
binning_y: 0
roi:
x_offset: 0
y_offset: 0
height: 0
width: 0
do_rectify: False
| 0
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/config
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/config/init_params/sample_extrinsics.yaml
|
header:
frame_id: velodyne64
stamp:
nsecs: 0
secs: 0
seq: 0
child_frame_id: camera_head_left
transform:
rotation:
x: -0.5
y: 0.5
z: -0.5
w: 0.5
translation:
x: 0
y: 0
z: 0
| 0
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/config
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/config/init_params/BUILD
|
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "runtime_files",
srcs = glob([
"*",
]),
)
install(
name = "install",
data = [":runtime_files"],
data_dest = "tools/sensor_calibration/config/init_parms"
)
| 0
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/template
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/template/camera_to_lidar/channel_template.txt
|
channel: {
name: "__NAME__"
extraction_rate: __RATE__
}
| 0
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/template
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/template/camera_to_lidar/camera_to_lidar.config
|
# data extraction configuration for multi-camera to lidar calibration
# must includes:
# at least 1 camera image channel
# lidar 16 point cloud channel
# GNSS Gps/odometry channel
io_config: {
task_name: "camera_to_lidar"
output_path: "/apollo/output/sensor_calibration/camera_to_lidar/extracted_data"
# start_timestamp: "FLOAT_MIN"
# end_timestamp: "FLOAT_MAX"
# start_timestamp: "1553901009.071362291"
# end_timestamp: "1553901012.01"
}
records: {
# records can be specified as a list
#record_path: "/apollo/data/bag/test/20190325185008.record.00001"
#record_path: "/apollo/data/bag/test/20190325185008.record.00002"
#record_path: "/apollo/data/bag/test/20190325185008.record.00003"
# or, records can be loaded from a directory
# record_path: "/apollo/output/sensor_calibration/camera_to_lidar/records"
}
channels: {
# channel of camera image channels
channel: {
description: "front camera 6mm"
name: "/apollo/sensor/camera/front_6mm/image"
extraction_rate: 5
}
# channel of 16-beam lidar
channel: {
description: "lidar 16 point cloud"
name: "/apollo/sensor/lidar16/PointCloud2"
extraction_rate: 5
}
# channel of localization pose odometry
channel: {
description: "GNSS odometry"
name: "/apollo/localization/pose"
extraction_rate: 1
}
}
| 0
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/template/camera_to_lidar
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/template/camera_to_lidar/extracted_data/readme.txt
|
output_path
| 0
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/template/camera_to_lidar
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/template/camera_to_lidar/records/readme.txt
|
record_path
| 0
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/template
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/template/lidar_to_gnss/channel_template.txt
|
channel: {
name: "__NAME__"
extraction_rate: __RATE__
}
| 0
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/template
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/template/lidar_to_gnss/lidar_to_gnss.config
|
# data extraction configuration for multi-lidar to GNSS Gps calibration
# must includes:
# at least 1 lidar pointcloud2 channel
# GNSS Gps/odometry channel
io_config: {
# task name now only support "camera_to_lidar, lidar_to_gnss"
task_name: "lidar_to_gnss"
output_path: "/apollo/output/sensor_calibration/lidar_to_gnss/extracted_data"
# start_timestamp: "FLOAT_MIN"
# end_timestamp: "FLOAT_MAX"
# start_timestamp: "1553901009.071362291"
# end_timestamp: "1553901012.01"
}
records: {
# records can be specified as a list
#record_path: "/apollo/data/bag/test/20190325185008.record.00001"
#record_path: "/apollo/data/bag/test/20190325185008.record.00002"
#record_path: "/apollo/data/bag/test/20190325185008.record.00003"
# or, records can be loaded from a directory
#record_path: "/apollo/output/sensor_calibration/lidar_to_gnss/records"
}
channels: {
# channel of mulitple lidars
channel: {
description: "lidar 16 front up point cloud"
name: "/apollo/sensor/lidar16/PointCloud2"
extraction_rate: 5
}
# channel of GNSS odometry
channel: {
description: "localization pose"
name: "/apollo/localization/pose"
extraction_rate: 1
}
}
| 0
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/template/lidar_to_gnss
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/template/lidar_to_gnss/extracted_data/readme.txt
|
output_path
| 0
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/template/lidar_to_gnss
|
apollo_public_repos/apollo/modules/tools/sensor_calibration/template/lidar_to_gnss/records/readme.txt
|
record_path
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/main.cc
|
/******************************************************************************
* Copyright 2018 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 <QtGui/QOffscreenSurface>
#include <QtGui/QOpenGLFunctions>
#include <QtWidgets/QApplication>
#include "modules/tools/visualizer/main_window.h"
int main(int argc, char* argv[]) {
QApplication a(argc, argv);
int major, minor;
{
QOffscreenSurface surf;
surf.create();
QOpenGLContext ctx;
ctx.create();
ctx.makeCurrent(&surf);
std::stringstream strStreamObj;
strStreamObj << (const char*)ctx.functions()->glGetString(
GL_SHADING_LANGUAGE_VERSION);
double version;
strStreamObj >> version;
major = static_cast<int>(version);
minor = static_cast<int>(version * 10.0 - major * 10);
if (major < 3 && minor < 3) {
std::cout << "Shading Language Version ( " << version
<< ") is much lower than 3.3" << std::endl;
return -1;
}
}
QSurfaceFormat format;
format.setVersion(major, minor);
format.setRenderableType(QSurfaceFormat::RenderableType::OpenGL);
format.setSwapBehavior(QSurfaceFormat::SwapBehavior::DoubleBuffer);
QSurfaceFormat::setDefaultFormat(format);
a.setStyleSheet(
"QSplitter::handle {"
" background: lightGray;"
" border-radius: 2px; "
"}");
apollo::cyber::Init(argv[0]);
MainWindow w;
auto topologyCallback =
[&w](const apollo::cyber::proto::ChangeMsg& change_msg) {
w.TopologyChanged(change_msg);
};
auto channelManager =
apollo::cyber::service_discovery::TopologyManager::Instance()
->channel_manager();
channelManager->AddChangeListener(topologyCallback);
std::vector<apollo::cyber::proto::RoleAttributes> role_attr_vec;
channelManager->GetWriters(&role_attr_vec);
for (auto& role_attr : role_attr_vec) {
w.AddNewWriter(role_attr);
}
w.show();
return a.exec();
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/video_images_dialog.h
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#pragma once
#include <QtWidgets/QDialog>
namespace Ui {
class VideoImagesDialog;
}
class VideoImagesDialog : public QDialog {
Q_OBJECT
public:
explicit VideoImagesDialog(QWidget *parent = nullptr);
~VideoImagesDialog();
int count(void) const;
private:
Ui::VideoImagesDialog *ui;
};
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/renderable_object.cc
|
/******************************************************************************
* Copyright 2018 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/tools/visualizer/renderable_object.h"
#include <iostream>
std::shared_ptr<QOpenGLShaderProgram> RenderableObject::NullRenderableObj;
std::shared_ptr<QOpenGLShaderProgram> RenderableObject::CreateShaderProgram(
const QString& vertexShaderFileName, const QString& fragShaderFileName) {
std::shared_ptr<QOpenGLShaderProgram> shaderProg(new QOpenGLShaderProgram());
if (shaderProg != nullptr) {
shaderProg->addShaderFromSourceFile(QOpenGLShader::Vertex,
vertexShaderFileName);
shaderProg->addShaderFromSourceFile(QOpenGLShader::Fragment,
fragShaderFileName);
if (!shaderProg->link()) {
std::cerr << "----cannot link shader programm, log:("
<< shaderProg->log().toStdString() << ")\n";
shaderProg.reset();
}
}
return shaderProg;
}
RenderableObject::RenderableObject(
int vertexCount, int vertexElementCount,
const std::shared_ptr<QOpenGLShaderProgram>& shaderProgram)
: QOpenGLFunctions(),
is_init_(false),
is_renderable_(true),
vertex_count_(vertexCount),
vertex_element_count_(vertexElementCount),
shader_program_(shaderProgram),
vao_(),
vbo_(QOpenGLBuffer::VertexBuffer) {}
RenderableObject::~RenderableObject() { Destroy(); }
void RenderableObject::Destroy(void) {
if (is_init_) {
is_renderable_ = false;
is_init_ = false;
shader_program_.reset();
vbo_.destroy();
vao_.destroy();
}
}
bool RenderableObject::Init(
std::shared_ptr<QOpenGLShaderProgram>& shaderProgram) {
if (is_init_) {
return true;
}
if (vertex_count() < 1) {
return false;
}
if (vertex_element_count() < 1) {
return false;
}
if (shaderProgram != nullptr) {
shader_program_ = shaderProgram;
}
if (shader_program_ == nullptr) {
return false;
}
initializeOpenGLFunctions();
if (!vao_.create()) {
return false;
}
vao_.bind();
if (!vbo_.create()) {
vao_.destroy();
return false;
}
vbo_.setUsagePattern(QOpenGLBuffer::StaticDraw);
vbo_.bind();
vbo_.allocate(VertexBufferSize());
GLfloat* pBuffer = static_cast<GLfloat*>(vbo_.map(QOpenGLBuffer::WriteOnly));
bool ret = FillVertexBuffer(pBuffer);
vbo_.unmap();
if (!ret) {
return ret;
}
SetupAllAttrPointer();
vbo_.release();
vao_.release();
is_init_ = true;
return true;
}
void RenderableObject::Render(const QMatrix4x4* mvp) {
if (is_init_) {
if (is_renderable()) {
shader_program_->bind();
if (mvp) {
shader_program_->setUniformValue("mvp", *mvp);
}
SetupExtraUniforms();
vao_.bind();
Draw();
vao_.release();
shader_program_->release();
}
} else {
std::cerr << "Please initialize the object" << std::endl;
}
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/abstract_camera.h
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#pragma once
#include <QtGui/QMatrix4x4>
class AbstractCamera {
public:
enum class CameraMode { PerspectiveMode, OrthoMode };
static const QVector3D UP;
static float Radians(float degrees) {
return degrees * static_cast<float>(0.01745329251994329576923690768489);
}
static float Degrees(float radians) {
return radians * static_cast<float>(57.295779513082320876798154814105);
}
static QMatrix4x4 YawPitchRoll(float yawInDegrees, float picthInDegrees,
float rollInDegrees);
AbstractCamera(void);
virtual ~AbstractCamera() {}
virtual void UpdateWorld(void) = 0; // update modelview
CameraMode camera_mode(void) const { return camera_mode_; }
void set_camera_mode(CameraMode cm) { camera_mode_ = cm; }
const QMatrix4x4& projection_matrix(void) const { return projection_mat_; }
const QMatrix4x4& model_view_matrix(void) const { return model_view_mat_; }
float near_plane_height(void) const { return near_plane_height_; }
float near_plane_width(void) const { return near_plane_width_; }
void set_near_plane_height(const float npHeight) {
near_plane_height_ = npHeight;
}
void set_near_plane_width(const float npWidth) {
near_plane_width_ = npWidth;
}
float fov(void) const { return fov_; }
void set_fov(const float fovInDegrees) { fov_ = fovInDegrees; }
float near_plane(void) const { return near_plane_; }
void set_near_plane(float n) { near_plane_ = n; }
float far_plane(void) const { return far_plane_; }
void set_far_plane(float f) { far_plane_ = f; }
void SetUpProjection(float fovInDegrees, float nearPlaneWidth,
float nearPlaneHeight, float near = 0.1f,
float far = 1000.f) {
fov_ = fovInDegrees;
near_plane_width_ = nearPlaneWidth;
near_plane_height_ = nearPlaneHeight;
near_plane_ = near;
far_plane_ = far;
}
float x(void) const { return position_[0]; }
float y(void) const { return position_[1]; }
float z(void) const { return position_[2]; }
void set_x(float x) { position_[0] = x; }
void set_y(float y) { position_[1] = y; }
void set_z(float z) { position_[2] = z; }
const QVector3D& position(void) const { return position_; }
void set_position(const QVector3D& pos) { position_ = pos; }
void set_position(float x, float y, float z) {
position_.setX(x);
position_.setY(y);
position_.setZ(z);
}
float yaw(void) const { return attitude_[0]; }
void set_yaw(float yInDegrees) { attitude_[0] = yInDegrees; }
float pitch(void) const { return attitude_[1]; }
void set_pitch(float pInDegrees) { attitude_[1] = pInDegrees; }
float roll(void) const { return attitude_[2]; }
void set_roll(float rInDegrees) { attitude_[2] = rInDegrees; }
const QVector3D& attitude(void) const { return attitude_; }
void SetAttitude(float yawInDegrees, float pitchInDegrees,
float rollInDegrees) {
attitude_[0] = yawInDegrees;
attitude_[1] = pitchInDegrees;
attitude_[2] = rollInDegrees;
}
const QVector3D& look(void) const { return look_; }
void UpdateProjection(void) {
projection_mat_.setToIdentity();
if (camera_mode() == CameraMode::PerspectiveMode) {
projection_mat_.perspective(fov_, near_plane_width_ / near_plane_height_,
near_plane_, far_plane_);
} else {
projection_mat_.ortho(-near_plane_width_ / 2.0f, near_plane_width_ / 2.0f,
-near_plane_height_ / 2.0f,
near_plane_height_ / 2.0f, 0.0f, 0.0f);
}
}
void Update(void) {
UpdateWorld();
UpdateProjection();
}
protected:
CameraMode camera_mode_;
float fov_; // in degrees
float near_plane_width_;
float near_plane_height_;
float near_plane_; // in look direction
float far_plane_; // in look direction
QVector3D position_; // x, y, z
QVector3D attitude_; // 0:yaw, 1:pitch, 2:roll , in degrees
QVector3D look_;
QVector3D up_;
QVector3D right_;
QMatrix4x4 projection_mat_;
QMatrix4x4 model_view_mat_;
};
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/radarpoints.h
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#pragma once
#include <QtGui/QColor>
#include <memory>
#include <string>
#include "modules/common_msgs/sensor_msgs/radar.pb.h"
#include "modules/tools/visualizer/renderable_object.h"
class QOpenGLShaderProgram;
class RadarPoints : public RenderableObject {
/* struct Point{
* GLfloat x, // raw data from radar
* GLfloat y,
* GLfloat r
* };
*/
public:
explicit RadarPoints(
const std::shared_ptr<QOpenGLShaderProgram>& shaderProgram = nullptr);
~RadarPoints(void) {
if (buffer_) {
delete[] buffer_;
buffer_ = nullptr;
}
}
virtual GLenum GetPrimitiveType(void) const { return GL_POINTS; }
void SetupExtraUniforms(void) {
shader_program_->setUniformValue("color", color_);
}
GLfloat red(void) const { return color_.x(); }
GLfloat green(void) const { return color_.y(); }
GLfloat blue(void) const { return color_.z(); }
const QVector3D& color(void) const { return color_; }
void set_color(const QRgb& rgb) { set_color(QColor(rgb)); }
void set_color(const QColor& color) {
color_.setX(static_cast<float>(color.redF()));
color_.setY(static_cast<float>(color.greenF()));
color_.setZ(static_cast<float>(color.blueF()));
}
bool FillData(
const std::shared_ptr<const apollo::drivers::RadarObstacles>& pData);
protected:
bool FillVertexBuffer(GLfloat* pBuffer) override;
private:
QVector3D color_; // r, g, b
GLfloat* buffer_;
};
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/channel_reader.h
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#pragma once
#include <memory>
#include <string>
#include "cyber/cyber.h"
class MainWindow;
template <typename T>
using CyberChannelCallback = std::function<void(const std::shared_ptr<T>&)>;
template <typename T>
class CyberChannReader {
public:
CyberChannReader(void) : channel_callback_(nullptr), channel_node_(nullptr) {}
~CyberChannReader() { CloseChannel(); }
void CloseChannel(void) {
if (channel_reader_ != nullptr) {
channel_reader_.reset();
}
if (channel_node_ != nullptr) {
channel_node_.reset();
}
}
bool InstallCallbackAndOpen(CyberChannelCallback<T> channelCallback,
const std::string& channelName,
const std::string& nodeName) {
return InstallCallback(channelCallback) &&
OpenChannel(channelName, nodeName);
}
bool InstallCallback(CyberChannelCallback<T> channelCallback) {
if (channelCallback != nullptr) {
channel_callback_ = channelCallback;
return true;
} else {
std::cerr << "Parameter readerCallback is null" << std::endl;
return false;
}
}
bool OpenChannel(const std::string& channelName,
const std::string& nodeName) {
if (channelName.empty() || nodeName.empty()) {
std::cerr << "Channel Name or Node Name must be not empty" << std::endl;
return false;
}
if (channel_node_ != nullptr || channel_reader_ != nullptr ||
!channel_callback_) {
return false;
}
return CreateChannel(channelName, nodeName);
}
const std::string& NodeName(void) const { return channel_node_->Name(); }
private:
bool CreateChannel(const std::string& channelName,
const std::string& nodeName) {
if (channel_node_ == nullptr) {
channel_node_ = apollo::cyber::CreateNode(nodeName);
if (channel_node_ == nullptr) {
return false;
}
}
channel_reader_ =
channel_node_->CreateReader<T>(channelName, channel_callback_);
if (channel_reader_ == nullptr) {
std::cout << "----------Creat reader failed---------" << std::endl;
return false;
}
return true;
}
CyberChannelCallback<T> channel_callback_;
std::shared_ptr<apollo::cyber::Reader<T>> channel_reader_;
std::shared_ptr<apollo::cyber::Node> channel_node_;
};
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/plane.cc
|
/******************************************************************************
* Copyright 2018 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/tools/visualizer/plane.h"
std::shared_ptr<Texture> Plane::NullTextureObj;
Plane::Plane(const std::shared_ptr<Texture>& t)
: RenderableObject(4, 4), texture_id_(0), texture_(t) {}
bool Plane::FillVertexBuffer(GLfloat* pBuffer) {
if (texture_ == nullptr || !texture_->isDirty()) {
return false;
}
glGenTextures(1, &texture_id_);
glBindTexture(GL_TEXTURE_2D, texture_id_);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, texture_->width(),
texture_->height(), 0, texture_->texture_format(),
GL_UNSIGNED_BYTE, texture_->data());
glBindTexture(GL_TEXTURE_2D, 0);
texture_->removeDirty();
pBuffer[0] = -1.0f;
pBuffer[1] = -1.0f;
pBuffer[2] = 0.0f;
pBuffer[3] = 0.0f;
pBuffer[4] = 1.0f;
pBuffer[5] = -1.0f;
pBuffer[6] = 1.0f;
pBuffer[7] = 0.0f;
pBuffer[8] = 1.0f;
pBuffer[9] = 1.0f;
pBuffer[10] = 1.0f;
pBuffer[11] = 1.0f;
pBuffer[12] = -1.0f;
pBuffer[13] = 1.0f;
pBuffer[14] = 0.0f;
pBuffer[15] = 1.0f;
return true;
}
void Plane::SetupAllAttrPointer(void) {
glEnableVertexAttribArray(0);
glVertexAttribPointer(
0, 2, GL_FLOAT, GL_FALSE,
static_cast<int>(sizeof(GLfloat)) * vertex_element_count(), 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(
1, 2, GL_FLOAT, GL_FALSE,
static_cast<int>(sizeof(GLfloat)) * vertex_element_count(),
reinterpret_cast<void*>(sizeof(GLfloat) * 2));
}
void Plane::Draw(void) {
if (texture_->data()) {
if (texture_->isSizeChanged()) {
glGenTextures(1, &texture_id_);
glBindTexture(GL_TEXTURE_2D, texture_id_);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, texture_->width(),
texture_->height(), 0, texture_->texture_format(),
GL_UNSIGNED_BYTE, texture_->data());
glBindTexture(GL_TEXTURE_2D, 0);
texture_->removeDirty();
} else if (texture_->isDirty()) {
glBindTexture(GL_TEXTURE_2D, texture_id_);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, texture_->width(),
texture_->height(), texture_->texture_format(),
GL_UNSIGNED_BYTE, texture_->data());
glBindTexture(GL_TEXTURE_2D, 0);
texture_->removeDirty();
}
}
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture_id_);
RenderableObject::Draw();
glBindTexture(GL_TEXTURE_2D, 0);
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/treewidget.h
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#pragma once
#include <QtWidgets/QTreeWidget>
class TreeWidget : public QTreeWidget {
Q_OBJECT
public:
explicit TreeWidget(QWidget *parent = nullptr);
~TreeWidget() {}
signals:
void visibilityChanged(bool);
protected:
void resizeEvent(QResizeEvent *);
bool event(QEvent *e);
};
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/main_window.h
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#pragma once
#include <QtCore/QMutex>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenu>
#include <map>
#include <memory>
#include <string>
#include "modules/common_msgs/sensor_msgs/pointcloud.pb.h"
#include "modules/common_msgs/sensor_msgs/radar.pb.h"
#include "modules/common_msgs/sensor_msgs/sensor_image.pb.h"
#include "modules/tools/visualizer/channel_reader.h"
#include "modules/tools/visualizer/msg_dialog.h"
class FixedAspectRatioWidget;
class Texture;
class Grid;
class QAction;
class QComboBox;
class QTreeWidgetItem;
class QOpenGLShaderProgram;
class QCheckBox;
class QColorDialog;
class VideoImagesDialog;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget* parent = nullptr);
~MainWindow();
void TopologyChanged(const apollo::cyber::proto::ChangeMsg& change_msg);
void AddNewWriter(const apollo::cyber::proto::RoleAttributes& role);
protected:
void resizeEvent(QResizeEvent*) override;
private slots: // NOLINT
void ActionAddGrid(void);
void ActionOpenPointCloud(void);
void PlayRenderableObject(bool);
void ChangePointCloudChannel(void);
void ActionOpenImage(void);
void PlayVideoImage(bool b);
void ChangeVideoImgChannel(void);
void SelectCurrentTreeItem(FixedAspectRatioWidget*);
void ActionDelVideoImage(void);
void CloseVideoImgViewer(bool b);
void UpdateActions(void);
void EnableGrid(bool b);
void EditGridColor(QTreeWidgetItem* item, int column);
void ChangeGridCellCountBySize(int v);
void ActionOpenImages(void);
void AddVideoImages(void);
void ActionOpenRadarChannel(void);
void openRadarChannel(bool b);
void EnableRadarPoints(bool b);
void ChangeRadarChannel(void);
void showMessage(void);
void PlayPause(void);
private:
struct VideoImgProxy;
struct RadarData;
void PointCloudReaderCallback(
const std::shared_ptr<const apollo::drivers::PointCloud>& pdata);
void ImageReaderCallback(
const std::shared_ptr<const apollo::drivers::Image>& imgData,
VideoImgProxy* proxy);
void ImageReaderCallback(
const std::shared_ptr<const apollo::drivers::CompressedImage>& imgData,
VideoImgProxy* proxy);
void InsertAllChannelNames(void);
VideoImgProxy* AddVideoImgViewer(void);
void DoDeleteVideoImg(VideoImgProxy*);
void DoPlayVideoImage(bool, VideoImgProxy*);
void calculateWH(void);
RadarData* createRadarData(void);
void DoOpenRadarChannel(bool b, RadarData* radarProxy);
void RadarRenderCallback(
const std::shared_ptr<const apollo::drivers::RadarObstacles>& rawData,
RadarData* radar);
Ui::MainWindow* ui_;
MessageDialog* msg_dialog_;
VideoImagesDialog* open_images_dialog_;
QTreeWidgetItem* all_channel_root_;
Grid* grid_;
QCheckBox* enable_grid_checkBox_;
QTreeWidgetItem* grid_root_item_;
QTreeWidgetItem* pointcloud_top_item_;
QComboBox* pointcloud_comboBox_;
QPushButton* pointcloud_button_;
CyberChannReader<apollo::drivers::PointCloud>* pointcloud_channel_Reader_;
QMutex pointcloud_reader_mutex_;
QMenu right_menu_;
std::shared_ptr<QOpenGLShaderProgram> pointcloud_shader_;
std::shared_ptr<QOpenGLShaderProgram> grid_shader_;
std::shared_ptr<QOpenGLShaderProgram> radar_points_shader_;
QList<VideoImgProxy*> video_image_viewer_list_;
QList<VideoImgProxy*> closed_video_image_viewer_list_;
QList<RadarData*> radarData_list_;
QList<RadarData*> closed_radarData_list_;
std::map<std::string, std::string> _channelName2TypeMap;
};
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/fixedaspectratiowidget.cc
|
/******************************************************************************
* Copyright 2018 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/tools/visualizer/fixedaspectratiowidget.h"
#include <QtGui/QContextMenuEvent>
#include <QtGui/QPainter>
#include <QtWidgets/QMenu>
#include <QtWidgets/QStyleOption>
FixedAspectRatioWidget::FixedAspectRatioWidget(QWidget* parent, int index)
: QWidget(parent), index_(index), refresh_timer_(this), viewer_() {
viewer_.setParent(this);
viewer_.setGeometry(geometry());
refresh_timer_.setObjectName(tr("_refreshTimer"));
refresh_timer_.setInterval(40);
connect(&refresh_timer_, SIGNAL(timeout()), &viewer_, SLOT(repaint()));
setAutoFillBackground(true);
}
void FixedAspectRatioWidget::StartOrStopUpdate(bool b) {
if (viewer_.is_init_) {
if (b) {
refresh_timer_.start();
} else {
refresh_timer_.stop();
}
}
}
void FixedAspectRatioWidget::SetupDynamicTexture(
const std::shared_ptr<Texture>& textureObj) {
if (textureObj == nullptr) {
viewer_.default_image_->setSizeChanged();
viewer_.plane_.set_texture(viewer_.default_image_);
} else {
viewer_.plane_.set_texture(textureObj);
}
}
void FixedAspectRatioWidget::mouseDoubleClickEvent(QMouseEvent* event) {
if (event->button() == Qt::LeftButton) {
emit focusOnThis(this);
QWidget::mouseDoubleClickEvent(event);
}
}
void FixedAspectRatioWidget::contextMenuEvent(QContextMenuEvent* event) {
emit focusOnThis(this);
QMenu m;
m.addActions(actions());
m.exec(event->globalPos());
m.clear();
QWidget::contextMenuEvent(event);
}
void FixedAspectRatioWidget::resizeEvent(QResizeEvent* revent) {
QSize size = revent->size();
{
double aspect = static_cast<double>(viewer_.plane_.texWidth()) /
static_cast<double>(viewer_.plane_.texHeight());
int wc = 4;
int hc = 9;
if (aspect == 4.0 / 3.0) {
wc = 2;
hc = 3;
} else if (aspect == 16.0 / 10.0) {
wc = 4;
hc = 10;
}
int w = size.width();
int h = size.height();
int tmpH = w >> wc;
w = tmpH << wc;
size.setWidth(w);
tmpH *= hc;
if (tmpH <= h) {
size.setHeight(tmpH);
} else {
tmpH = h / hc;
h = tmpH * hc;
size.setHeight(h);
size.setWidth(tmpH << wc);
}
}
viewer_.setGeometry((revent->size().width() - size.width()) / 2,
(revent->size().height() - size.height()) / 2,
size.width(), size.height());
QWidget::resizeEvent(revent);
}
void FixedAspectRatioWidget::paintEvent(QPaintEvent* event) {
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
QWidget::paintEvent(event);
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/pointcloud.h
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#pragma once
#include <memory>
#include "modules/common_msgs/sensor_msgs/pointcloud.pb.h"
#include "modules/tools/visualizer/renderable_object.h"
class QOpenGLShaderProgram;
class PointCloud : public RenderableObject {
public:
explicit PointCloud(int pointCount = 1, int vertex_element_count = 3,
const std::shared_ptr<QOpenGLShaderProgram>&
shaderProgram = NullRenderableObj);
~PointCloud(void);
virtual GLenum GetPrimitiveType(void) const { return GL_POINTS; }
bool FillData(
const std::shared_ptr<const apollo::drivers::PointCloud>& pData);
private:
virtual bool FillVertexBuffer(GLfloat* vertexBuffer);
GLfloat* buffer_;
};
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/abstract_camera.cc
|
/******************************************************************************
* Copyright 2018 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/tools/visualizer/abstract_camera.h"
#include <cmath>
const QVector3D AbstractCamera::UP{0.0f, 1.0f, 0.0f};
QMatrix4x4 AbstractCamera::YawPitchRoll(float yaw, float pitch, float roll) {
yaw = Radians(yaw);
pitch = Radians(pitch);
roll = Radians(roll);
register float tmpCy = std::cos(yaw);
register float tmpSy = std::sin(yaw);
register float tmpCp = std::cos(pitch);
register float tmpSp = std::sin(pitch);
register float tmpCr = std::cos(roll);
register float tmpSr = std::sin(roll);
QMatrix4x4 Result;
Result(0, 0) = tmpCy * tmpCr + tmpSy * tmpSp * tmpSr;
Result(1, 0) = tmpSr * tmpCp;
Result(2, 0) = -tmpSy * tmpCr + tmpCy * tmpSp * tmpSr;
Result(3, 0) = 0.0f;
Result(0, 1) = -tmpCy * tmpSr + tmpSy * tmpSp * tmpCr;
Result(1, 1) = tmpCr * tmpCp;
Result(2, 1) = tmpSr * tmpSy + tmpCy * tmpSp * tmpCr;
Result(3, 1) = 0.0f;
Result(0, 2) = tmpSy * tmpCp;
Result(1, 2) = -tmpSp;
Result(2, 2) = tmpCy * tmpCp;
Result(3, 2) = 0.0f;
Result(0, 3) = 0.0f;
Result(1, 3) = 0.0f;
Result(2, 3) = 0.0f;
Result(3, 3) = 1.0f;
return Result;
}
AbstractCamera::AbstractCamera()
: camera_mode_(CameraMode::PerspectiveMode),
fov_(45.0f),
near_plane_width_(1.0f),
near_plane_height_(1.0f),
near_plane_(0.1f),
far_plane_(1000.0f),
position_(0.0f, 0.0f, 0.0f),
attitude_(),
look_(0.0f, 0.0f, 1.0f),
up_(UP),
right_(1.0f, 0.0f, 0.0f),
projection_mat_(),
model_view_mat_() {}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/plane.h
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#pragma once
#include <memory>
#include "modules/tools/visualizer/renderable_object.h"
#include "modules/tools/visualizer/texture.h"
class Plane : public RenderableObject {
/*
* struct Vertex
* {
* GLfloat _vert[2];
* GLfloat _texCoor[2];
* };
*
*/
public:
static std::shared_ptr<Texture> NullTextureObj;
explicit Plane(const std::shared_ptr<Texture>& t = NullTextureObj);
virtual ~Plane(void) { texture_.reset(); }
void set_texture(const std::shared_ptr<Texture>& t) {
if (t != texture_) {
texture_ = t;
}
}
GLenum GetPrimitiveType(void) const override { return GL_QUADS; }
GLsizei texWidth(void) const { return texture_->width(); }
GLsizei texHeight(void) const { return texture_->height(); }
protected:
bool FillVertexBuffer(GLfloat* pBuffer) override;
void Draw(void) override;
void SetupAllAttrPointer(void) override;
private:
GLuint texture_id_;
std::shared_ptr<Texture> texture_;
};
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/radarpoints.cc
|
/******************************************************************************
* Copyright 2018 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 "radarpoints.h"
#include <cmath>
#include <iostream>
RadarPoints::RadarPoints(
const std::shared_ptr<QOpenGLShaderProgram>& shaderProgram)
: RenderableObject(1, 3, shaderProgram),
color_(1.0f, 0.0f, 0.0f),
buffer_(nullptr) {}
bool RadarPoints::FillData(
const std::shared_ptr<const apollo::drivers::RadarObstacles>& rawData) {
bool ret = false;
set_vertex_count(rawData->radar_obstacle_size());
buffer_ = new GLfloat[vertex_count() * vertex_element_count()];
if (buffer_) {
GLfloat* ptr = buffer_;
const ::google::protobuf::Map<::google::protobuf::int32,
apollo::drivers::RadarObstacle>&
radarObstacles = rawData->radar_obstacle();
for (::google::protobuf::Map<::google::protobuf::int32,
apollo::drivers::RadarObstacle>::const_iterator
iter = radarObstacles.cbegin();
iter != radarObstacles.cend(); ++iter, ptr += vertex_element_count()) {
const apollo::common::Point2D& position =
iter->second.absolute_position();
ptr[0] = static_cast<float>(position.x());
ptr[1] = static_cast<float>(position.y());
ptr[2] = std::pow(10.0f, static_cast<float>(iter->second.rcs() / 20.0));
} // end for
ret = true;
}
return ret;
}
bool RadarPoints::FillVertexBuffer(GLfloat* pBuffer) {
if (buffer_ && pBuffer) {
memcpy(pBuffer, buffer_, VertexBufferSize());
delete[] buffer_;
buffer_ = nullptr;
return true;
} else {
std::cout << "---Error!!! cannot upload data to Graphics Card----"
<< std::endl;
return false;
}
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/msg_dialog.cc
|
/******************************************************************************
* Copyright 2018 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/tools/visualizer/msg_dialog.h"
#include "modules/tools/visualizer/ui_msg_dialog.h"
MessageDialog::MessageDialog(QWidget *parent)
: QDialog(parent), ui_(new Ui::MessageDialog) {
ui_->setupUi(this);
}
MessageDialog::~MessageDialog() { delete ui_; }
void MessageDialog::setMessage(const QString &msg) {
ui_->msgLabel->setText(msg);
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/pointcloud.cc
|
/******************************************************************************
* Copyright 2018 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/tools/visualizer/pointcloud.h"
#include <iostream>
PointCloud::PointCloud(
int pointCount, int vertexElementCount,
const std::shared_ptr<QOpenGLShaderProgram>& shaderProgram)
: RenderableObject(pointCount, vertexElementCount, shaderProgram),
buffer_(nullptr) {}
PointCloud::~PointCloud(void) {
if (buffer_) {
delete[] buffer_;
buffer_ = nullptr;
}
}
bool PointCloud::FillVertexBuffer(GLfloat* pBuffer) {
if (buffer_ && pBuffer) {
memcpy(pBuffer, buffer_, VertexBufferSize());
delete[] buffer_;
buffer_ = nullptr;
return true;
} else {
std::cout << "---Error!!! cannot upload data to Graphics Card----"
<< std::endl;
return false;
}
}
bool PointCloud::FillData(
const std::shared_ptr<const apollo::drivers::PointCloud>& pdata) {
assert(vertex_count() == pdata->point_size());
buffer_ = new GLfloat[vertex_count() * vertex_element_count()];
if (buffer_) {
GLfloat* tmp = buffer_;
for (int i = 0; i < vertex_count(); ++i, tmp += vertex_element_count()) {
const apollo::drivers::PointXYZIT& point = pdata->point(i);
tmp[0] = point.x();
tmp[1] = point.z();
tmp[2] = -point.y();
tmp[3] = static_cast<float>(point.intensity());
}
return true;
}
return false;
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/grid.h
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#pragma once
#include <QtGui/QColor>
#include "modules/tools/visualizer/renderable_object.h"
class Grid : public RenderableObject {
public:
explicit Grid(int cellCountBySide = 1);
~Grid() {}
GLenum GetPrimitiveType(void) const { return GL_LINES; }
void SetupExtraUniforms(void) {
QVector3D color;
color.setX(static_cast<float>(grid_color_.redF()));
color.setY(static_cast<float>(grid_color_.greenF()));
color.setZ(static_cast<float>(grid_color_.blueF()));
shader_program_->setUniformValue("color", color);
}
int red(void) const { return grid_color_.red(); }
int green(void) const { return grid_color_.green(); }
int blue(void) const { return grid_color_.blue(); }
const QColor& grid_color(void) const { return grid_color_; }
void set_grid_color(const QColor& color) { grid_color_ = color; }
void SetCellCount(int cellCount) {
set_vertex_count(((cellCount << 1) + 2) * vertex_element_count());
}
int CellCount(void) const {
return (vertex_count() / vertex_element_count() - 2) >> 1;
}
protected:
virtual bool FillVertexBuffer(GLfloat* pBuffer);
private:
QColor grid_color_;
};
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/texture.cc
|
/******************************************************************************
* Copyright 2018 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/tools/visualizer/texture.h"
#include <iostream>
Texture::Texture()
: is_size_changed_(false),
is_dirty_(false),
texture_format_(0),
image_width_(0),
image_height_(0),
data_size_(0),
data_(nullptr) {}
bool Texture::UpdateData(const QImage& img) {
if (data_size_ < img.byteCount()) {
if (!data_) {
delete[] data_;
}
data_ = new GLubyte[img.byteCount()];
if (data_ == nullptr) {
data_size_ = 0;
return false;
}
data_size_ = img.byteCount();
is_size_changed_ = true;
}
image_height_ = img.height();
image_width_ = img.width();
memcpy(data_, img.bits(), img.byteCount());
is_dirty_ = true;
texture_format_ = GL_RGBA;
return true;
}
bool Texture::UpdateData(
const std::shared_ptr<const apollo::drivers::Image>& imgData) {
std::size_t imgSize = imgData->width() * imgData->height() * 3;
if (static_cast<std::size_t>(data_size_) < imgSize) {
if (!data_) {
delete[] data_;
}
data_ = new GLubyte[imgSize];
if (data_ == nullptr) {
data_size_ = 0;
return false;
}
data_size_ = static_cast<GLsizei>(imgSize);
is_size_changed_ = true;
}
texture_format_ = GL_RGB;
if (imgData->encoding() == std::string("yuyv")) {
const GLubyte* src =
reinterpret_cast<const GLubyte*>(imgData->data().c_str());
GLubyte* dst = data_;
for (std::size_t i = 0; i < imgData->data().size(); i += 4) {
int y = 298 * (src[i] - 16);
int u = src[i + 1] - 128;
int u1 = 516 * u;
int v = src[i + 3] - 128;
int v1 = 208 * v;
u *= 100;
v *= 409;
#define CLAMP(v) static_cast<GLubyte>((v) > 255 ? 255 : ((v) < 0 ? 0 : v))
*dst++ = CLAMP((y + v + 128) >> 8);
*dst++ = CLAMP((y - u - v1 + 128) >> 8);
*dst++ = CLAMP((y + u1 + 128) >> 8);
y = 298 * (src[i + 2] - 16);
*dst++ = CLAMP((y + v + 128) >> 8);
*dst++ = CLAMP((y - u - v1 + 128) >> 8);
*dst++ = CLAMP((y + u1 + 128) >> 8);
#undef CLAMP
}
} else if (imgData->encoding() == std::string("rgb8")) {
memcpy(data_, imgData->data().c_str(), imgSize);
} else if (imgData->encoding() == std::string("bgr8")) {
memcpy(data_, imgData->data().c_str(), imgSize);
texture_format_ = GL_BGR;
} else {
memset(data_, 0, imgSize);
std::cerr << "Cannot support this format (" << imgData->encoding()
<< ") image" << std::endl;
}
is_dirty_ = true;
image_height_ = imgData->height();
image_width_ = imgData->width();
return true;
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/scene_camera_dialog.cc
|
/******************************************************************************
* Copyright 2018 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/tools/visualizer/scene_camera_dialog.h"
#include <QtGui/QVector3D>
#include "modules/tools/visualizer/ui_scene_camera_dialog.h"
SceneCameraDialog::SceneCameraDialog(QWidget* parent)
: QDialog(parent), ui(new Ui::SceneCameraDialog) {
ui->setupUi(this);
ui->cameraX->setEnabled(false);
ui->cameraY->setEnabled(false);
ui->cameraZ->setEnabled(false);
connect(ui->resetButton, SIGNAL(clicked()), this, SIGNAL(resetcamera()));
connect(ui->cameraTypeComboBox, SIGNAL(currentIndexChanged(int)), this,
SLOT(onCameraTypeChanged(int)));
connect(ui->cameraX, SIGNAL(valueChanged(double)), this,
SIGNAL(xValueChanged(double)));
connect(ui->cameraY, SIGNAL(valueChanged(double)), this,
SIGNAL(yValueChanged(double)));
connect(ui->cameraZ, SIGNAL(valueChanged(double)), this,
SIGNAL(zValueChanged(double)));
connect(ui->cameraYaw, SIGNAL(valueChanged(double)), this,
SIGNAL(yawValueChanged(double)));
connect(ui->cameraPitch, SIGNAL(valueChanged(double)), this,
SIGNAL(pitchValueChanged(double)));
connect(ui->cameraRoll, SIGNAL(valueChanged(double)), this,
SIGNAL(rollValueChanged(double)));
connect(ui->stepSlider, SIGNAL(valueChanged(int)), this,
SLOT(OnStepSlideChanged(int)));
}
SceneCameraDialog::~SceneCameraDialog() { delete ui; }
void SceneCameraDialog::updateCameraAttitude(const QVector3D& attitude) {
ui->cameraYaw->setValue(attitude.x());
ui->cameraPitch->setValue(attitude.y());
ui->cameraRoll->setValue(attitude.z());
}
void SceneCameraDialog::updateCameraPos(const QVector3D& pos) {
ui->cameraX->setValue(pos.x());
ui->cameraY->setValue(pos.y());
ui->cameraZ->setValue(pos.z());
}
void SceneCameraDialog::OnStepSlideChanged(int v) {
const float step =
static_cast<float>(v) / static_cast<float>(ui->stepSlider->maximum());
emit sensitivityChanged(step);
ui->cameraX->setSingleStep(step);
ui->cameraY->setSingleStep(step);
ui->cameraZ->setSingleStep(step);
ui->cameraYaw->setSingleStep(step);
ui->cameraPitch->setSingleStep(step);
ui->cameraRoll->setSingleStep(step);
}
void SceneCameraDialog::onCameraTypeChanged(int index) {
emit cameraTypeChanged(index);
ui->cameraX->setEnabled(index);
ui->cameraY->setEnabled(index);
ui->cameraZ->setEnabled(index);
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/target_camera.h
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#pragma once
#include "modules/tools/visualizer/abstract_camera.h"
class TargetCamera : public AbstractCamera {
public:
TargetCamera();
virtual void UpdateWorld();
const QVector3D& target_pos(void) const { return target_pos_; }
void set_target_pos(float x, float y, float z) {
target_pos_.setX(x);
target_pos_.setY(y);
target_pos_.setZ(z);
distance_ = position_.distanceToPoint(target_pos_);
}
void set_target_pos(const QVector3D& tgt) {
target_pos_ = tgt;
distance_ = position_.distanceToPoint(target_pos_);
}
float distance(void) const { return distance_; }
void set_distance(float distance) {
if (distance < 0.0f) {
distance = 0.0f;
}
distance_ = distance;
}
void Rotate(float xRotateDegrees, float yRotateDegrees,
float zRotateDegrees) {
SetAttitude(yRotateDegrees, xRotateDegrees, zRotateDegrees);
}
private:
QVector3D target_pos_;
float distance_;
};
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/video_image_viewer.cc
|
/******************************************************************************
* Copyright 2018 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/tools/visualizer/video_image_viewer.h"
#include <iostream>
VideoImgViewer::VideoImgViewer(QWidget* parent)
: QOpenGLWidget(parent),
QOpenGLFunctions(),
is_init_(false),
mvp_id_(),
plane_(),
ortho_camera_(),
default_image_(nullptr),
video_image_shader_prog_(nullptr) {}
VideoImgViewer::~VideoImgViewer() {
if (is_init_) {
is_init_ = false;
makeCurrent();
plane_.Destroy();
video_image_shader_prog_->destroyed();
video_image_shader_prog_.reset();
default_image_.reset();
doneCurrent();
}
}
void VideoImgViewer::initializeGL() {
initializeOpenGLFunctions();
glPointSize(1.0f);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
QImage noImage;
if (!noImage.load(tr(":/images/no_image.png"))) {
std::cout << "--------can not load the default texture------------"
<< std::endl;
return;
}
default_image_ = std::make_shared<Texture>();
if (default_image_ == nullptr || !default_image_->UpdateData(noImage)) {
std::cout << "--------can not create the default texture------------"
<< std::endl;
return;
}
video_image_shader_prog_ = RenderableObject::CreateShaderProgram(
tr(":/shaders/video_image_plane.vert"),
tr(":/shaders/video_image_plane.frag"));
if (video_image_shader_prog_ == nullptr) {
return;
}
plane_.set_texture(default_image_);
if (!plane_.Init(video_image_shader_prog_)) {
return;
}
ortho_camera_.set_near_plane_width(GLfloat(width()));
ortho_camera_.set_near_plane_height(GLfloat(height()));
ortho_camera_.set_fov(static_cast<float>(height()));
ortho_camera_.set_camera_mode(AbstractCamera::CameraMode::OrthoMode);
ortho_camera_.set_position(0.0f, 0.0f, 0.0f);
ortho_camera_.UpdateWorld();
ortho_camera_.UpdateProjection();
QMatrix4x4 mvp =
ortho_camera_.projection_matrix() * ortho_camera_.model_view_matrix();
video_image_shader_prog_->bind();
video_image_shader_prog_->setUniformValue(mvp_id_, mvp);
video_image_shader_prog_->release();
is_init_ = true;
}
void VideoImgViewer::resizeGL(int width, int height) {
glViewport(0, 0, (GLsizei)width, (GLsizei)height);
if (is_init_) {
ortho_camera_.set_fov(static_cast<float>(height));
ortho_camera_.set_near_plane_width(GLfloat(width));
ortho_camera_.set_near_plane_height(GLfloat(height));
ortho_camera_.UpdateProjection();
QMatrix4x4 mvp =
ortho_camera_.projection_matrix() * ortho_camera_.model_view_matrix();
video_image_shader_prog_->bind();
video_image_shader_prog_->setUniformValue(mvp_id_, mvp);
video_image_shader_prog_->release();
}
}
void VideoImgViewer::paintGL() {
if (is_init_) {
plane_.Render();
}
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/free_camera.cc
|
/******************************************************************************
* Copyright 2018 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/tools/visualizer/free_camera.h"
FreeCamera::FreeCamera(void)
: AbstractCamera(), translation_(0.0, 0.0f, 0.0f) {}
void FreeCamera::UpdateWorld(void) {
QMatrix4x4 R = YawPitchRoll(attitude_[0], attitude_[1], attitude_[2]);
position_ += translation_;
translation_.setX(0.0f);
translation_.setY(0.0f);
translation_.setZ(0.0f);
look_ = QVector3D(R * QVector4D(0.0f, 0.0f, 1.0f, 0.0f));
up_ = QVector3D(R * QVector4D(0.0f, 1.0f, 0.0f, 0.0f));
right_ = QVector3D::crossProduct(look_, up_);
QVector3D tgt = position_ + look_;
model_view_mat_.setToIdentity();
model_view_mat_.lookAt(position_, tgt, up_);
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/fixedaspectratiowidget.h
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#pragma once
#include <QtCore/QTimer>
#include <memory>
#include "modules/tools/visualizer/video_image_viewer.h"
class FixedAspectRatioWidget : public QWidget {
Q_OBJECT
public:
explicit FixedAspectRatioWidget(QWidget *parent = nullptr, int index = 0);
bool is_init(void) const { return viewer_.is_init_; }
void SetupDynamicTexture(const std::shared_ptr<Texture> &textureObj);
void set_index(int i) { index_ = i; }
int index(void) const { return index_; }
void StartOrStopUpdate(bool b);
int innerHeight(void) { return viewer_.plane_.texHeight(); }
signals:
void focusOnThis(FixedAspectRatioWidget *);
protected:
void mouseDoubleClickEvent(QMouseEvent *event) override;
void contextMenuEvent(QContextMenuEvent *) override;
void resizeEvent(QResizeEvent *) override;
void paintEvent(QPaintEvent *event) override;
private:
int index_;
QTimer refresh_timer_;
VideoImgViewer viewer_;
};
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/video_images_dialog.cc
|
/******************************************************************************
* Copyright 2018 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/tools/visualizer/video_images_dialog.h"
#include "modules/tools/visualizer/ui_video_images_dialog.h"
VideoImagesDialog::VideoImagesDialog(QWidget *parent)
: QDialog(parent), ui(new Ui::VideoImagesDialog) {
ui->setupUi(this);
}
VideoImagesDialog::~VideoImagesDialog() { delete ui; }
int VideoImagesDialog::count(void) const { return ui->spinBox->value(); }
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/scene_viewer.h
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#pragma once
#include <QtWidgets/QOpenGLWidget>
#include <map>
#include <memory>
#include <string>
#include "modules/tools/visualizer/free_camera.h"
#include "modules/tools/visualizer/plane.h"
#include "modules/tools/visualizer/target_camera.h"
class QTimer;
class SceneCameraDialog;
class SceneViewer : public QOpenGLWidget, protected QOpenGLFunctions {
Q_OBJECT
public:
enum CameraType {
TARGET,
FREE,
};
explicit SceneViewer(QWidget* parent = nullptr);
~SceneViewer();
bool is_init(void) const { return is_init_; }
bool IsFreeCamera(void) const { return current_cameraPtr_ == &free_camera_; }
bool AddTempRenderableObj(const std::string& tmpObjGroupName,
RenderableObject* renderObj);
bool AddPermanentRenderObj(RenderableObject* obj) {
if (obj && obj->haveShaderProgram() && is_init_) {
permanent_renderable_obj_list_.append(obj);
return true;
} else {
return false;
}
}
void setTempObjGroupEnabled(const std::string& tmpObjGroupName, bool b);
const QVector3D& CameraPos(void) const {
return current_cameraPtr_->position();
}
const QVector3D& CamerAttitude(void) const {
return current_cameraPtr_->attitude();
}
float sensitivity(void) const { return sensitivity_; }
void AddNewShaderProg(
const std::string& shaderProgName,
const std::shared_ptr<QOpenGLShaderProgram>& newShaderProg);
std::shared_ptr<QOpenGLShaderProgram> FindShaderProg(
const std::string& shaderProgName) {
if (managed_shader_prog_.find(shaderProgName) !=
managed_shader_prog_.end()) {
return managed_shader_prog_[shaderProgName];
} else {
return std::shared_ptr<QOpenGLShaderProgram>();
}
}
signals: // NOLINT
void CameraPosChanged(const QVector3D& pos);
void CameraAttitudeChanged(const QVector3D& attitude);
public slots: // NOLINT
void ChangeCameraType(int index);
// void ChangeCameraMode(int index);
void ResetCameraPosAttitude(void);
void UpdateCameraX(double x);
void UpdateCameraY(double Y);
void UpdateCameraZ(double Z);
void UpdateCameraYaw(double yawInDegrees);
void UpdateCameraPitch(double pitchInDegrees);
void UpdateCameraRoll(double rollInDegrees);
void set_sensitivity(float s) { sensitivity_ = s; }
protected:
void initializeGL() override;
void resizeGL(int w, int h) override;
void paintGL() override;
void enterEvent(QEvent* event) override;
void leaveEvent(QEvent* event) override;
void mousePressEvent(QMouseEvent* mouseEvent) override;
void mouseMoveEvent(QMouseEvent* mouseEvent) override;
void mouseReleaseEvent(QMouseEvent* event) override;
void wheelEvent(QWheelEvent* event) override;
private:
void UpdateCameraWorld(void);
void UpdateAllShaderProgMVP(const QMatrix4x4& mvp);
bool is_init_;
bool right_key_is_moved_;
float sensitivity_;
QTimer* refreshTimer_;
QPoint left_key_last_pos_;
float right_key_last_y_;
SceneCameraDialog* camera_dialog_;
AbstractCamera* current_cameraPtr_;
FreeCamera free_camera_;
TargetCamera target_camera_;
std::map<const std::string, std::shared_ptr<QOpenGLShaderProgram>>
managed_shader_prog_;
struct TempRenderableObjGroup;
std::map<const std::string, TempRenderableObjGroup*> tmp_renderable_obj_list_;
QList<RenderableObject*> permanent_renderable_obj_list_;
};
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/treewidget.cc
|
/******************************************************************************
* Copyright 2018 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/tools/visualizer/treewidget.h"
#include <QtGui/QResizeEvent>
TreeWidget::TreeWidget(QWidget *parent) : QTreeWidget(parent) {}
void TreeWidget::resizeEvent(QResizeEvent *event) {
QTreeWidget::resizeEvent(event);
int cw = width() / columnCount();
for (int i = 0; i < columnCount(); ++i) {
setColumnWidth(i, cw);
}
}
bool TreeWidget::event(QEvent *e) {
bool b = QTreeWidget::event(e);
if (e->type() == QEvent::Hide) {
emit visibilityChanged(false);
}
if (e->type() == QEvent::Show) {
emit visibilityChanged(true);
}
return b;
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/grid.cc
|
/******************************************************************************
* Copyright 2018 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/tools/visualizer/grid.h"
Grid::Grid(int cellCountBySide)
: RenderableObject((cellCountBySide << 2) + 4, 2),
grid_color_(128, 128, 128) {}
bool Grid::FillVertexBuffer(GLfloat* pBuffer) {
float x = static_cast<float>(CellCount()) / 2.0f;
float z;
for (z = -x; z <= x; ++z) {
*pBuffer++ = -x;
*pBuffer++ = z;
*pBuffer++ = x;
*pBuffer++ = z;
}
z = x;
for (x = -z; x <= z; ++x) {
*pBuffer++ = x;
*pBuffer++ = -z;
*pBuffer++ = x;
*pBuffer++ = z;
}
return true;
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/texture.h
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#pragma once
#include <QtGui/QImage>
#include <QtGui/QOpenGLBuffer>
#include <memory>
#include "modules/common_msgs/sensor_msgs/sensor_image.pb.h"
class Texture {
public:
Texture(void);
~Texture() {
if (data_) {
delete[] data_;
data_ = nullptr;
}
}
bool isSizeChanged(void) const { return is_size_changed_; }
bool isDirty(void) const { return is_dirty_; }
void removeDirty(void) { is_size_changed_ = is_dirty_ = false; }
void setDirty(void) { is_dirty_ = true; }
void setSizeChanged(void) { is_size_changed_ = is_dirty_ = true; }
GLsizei width(void) const { return image_width_; }
GLsizei height(void) const { return image_height_; }
GLenum texture_format(void) const { return texture_format_; }
GLsizei data_size(void) const { return data_size_; }
bool UpdateData(const QImage& img);
bool UpdateData(const std::shared_ptr<const apollo::drivers::Image>&);
const GLubyte* data(void) const { return data_; }
private:
struct {
int : 30;
bool is_size_changed_ : 1;
bool is_dirty_ : 1;
};
GLenum texture_format_;
GLsizei image_width_;
GLsizei image_height_;
GLsizei data_size_;
GLubyte* data_;
};
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_binary")
load("//third_party/qt5:qt.bzl", "qt_cc_library")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
install(
name = "install",
runtime_dest = "tools/bin",
targets = [
":cyber_visualizer",
],
deps = [
"//cyber:install",
],
)
cc_binary(
name = "cyber_visualizer",
copts = [
"-Iexternal/qt",
],
includes = [
".",
],
linkopts = [
"-pthread",
],
linkstatic = True,
deps = [
":visualizer_lib",
"@fastrtps",
"@qt//:qt_core",
"@qt//:qt_gui",
"@qt//:qt_opengl",
"@qt//:qt_widgets",
],
)
# TODO(all): Extract the large library to thin pieces.
qt_cc_library(
name = "visualizer_lib",
srcs = glob(
["*.cc"],
),
hdrs = glob([
"*.h",
]),
copts = [
"-Iexternal/qt",
],
includes = [
".",
],
linkstatic = False,
res = glob([
"*.qrc",
]),
uis = glob([
"uis/*.ui",
]),
deps = [
"//cyber",
"//modules/common_msgs/sensor_msgs:pointcloud_cc_proto",
"//modules/common_msgs/sensor_msgs:radar_cc_proto",
"//modules/common_msgs/sensor_msgs:sensor_image_cc_proto",
"@qt//:qt_core",
"@qt//:qt_gui",
"@qt//:qt_opengl",
"@qt//:qt_widgets",
],
)
# TODO(all): Disable linter temporarily as the generated ui files should be
# excluded from check. But we should also check the .h and .cc files, if they
# are extracted to their own cc_libraries. See the TODO above.
# cpplint()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/target_camera.cc
|
/******************************************************************************
* Copyright 2018 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/tools/visualizer/target_camera.h"
TargetCamera::TargetCamera()
: AbstractCamera(), target_pos_(0.0, 0.0, 0.0), distance_(10.0) {}
void TargetCamera::UpdateWorld() {
QMatrix4x4 R = YawPitchRoll(yaw(), pitch(), roll());
QVector3D T{0, 0, distance_};
T = QVector3D(R * QVector4D(T, 0.0f));
position_ = target_pos_ + T;
look_ = target_pos_ - position_;
look_.normalize();
up_ = QVector3D(R * QVector4D(UP, 0.0f));
right_ = QVector3D::crossProduct(look_, up_);
model_view_mat_.setToIdentity();
model_view_mat_.lookAt(position_, target_pos_, up_);
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/renderable_object.h
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#pragma once
#include <QtGui/QOpenGLBuffer>
#include <QtGui/QOpenGLFunctions>
#include <QtGui/QOpenGLShaderProgram>
#include <QtGui/QOpenGLVertexArrayObject>
#include <memory>
class RenderableObject : protected QOpenGLFunctions {
public:
static std::shared_ptr<QOpenGLShaderProgram> NullRenderableObj;
static std::shared_ptr<QOpenGLShaderProgram> CreateShaderProgram(
const QString& vertexShaderFileName, const QString& fragShaderFileName);
explicit RenderableObject(int vertex_count = 1, int vertex_element_count = 3,
const std::shared_ptr<QOpenGLShaderProgram>&
shaderProgram = NullRenderableObj);
virtual ~RenderableObject(void);
virtual GLenum GetPrimitiveType(void) const = 0;
virtual void SetupExtraUniforms(void) {}
bool is_renderable(void) const { return is_renderable_; }
void set_is_renderable(bool b) { is_renderable_ = b; }
int vertex_count(void) const { return vertex_count_; }
void set_vertex_count(int vertexCount) { vertex_count_ = vertexCount; }
int vertex_element_count(void) const { return vertex_element_count_; }
void set_vertex_element_count(int vertexElementCount) {
vertex_element_count_ = vertexElementCount;
}
int VertexBufferSize(void) const {
return vertex_count() * vertex_element_count() *
static_cast<int>(sizeof(GLfloat));
}
void set_shader_program(
const std::shared_ptr<QOpenGLShaderProgram>& shaderProgram) {
shader_program_ = shaderProgram;
}
bool haveShaderProgram(void) { return shader_program_ != nullptr; }
bool Init(
std::shared_ptr<QOpenGLShaderProgram>& shaderProgram =
NullRenderableObj); // initial vao, vbo and call fillVertexBuffer
void Destroy(void);
void Render(const QMatrix4x4* mvp = nullptr);
protected:
virtual bool FillVertexBuffer(GLfloat* pBuffer) = 0;
virtual void Draw(void) {
glDrawArrays(GetPrimitiveType(), 0, vertex_count());
}
virtual void SetupAllAttrPointer(void) {
glEnableVertexAttribArray(0);
glVertexAttribPointer(
0, vertex_element_count(), GL_FLOAT, GL_FALSE,
static_cast<int>(sizeof(GLfloat)) * vertex_element_count(), 0);
}
bool is_init_;
bool is_renderable_;
int vertex_count_;
int vertex_element_count_;
std::shared_ptr<QOpenGLShaderProgram> shader_program_;
QOpenGLVertexArrayObject vao_;
QOpenGLBuffer vbo_;
};
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/main_window.cc
|
/******************************************************************************
* Copyright 2018 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 <QtWidgets/QCheckBox>
#include <QtWidgets/QColorDialog>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpinBox>
#include "modules/tools/visualizer/fixedaspectratiowidget.h"
#include "modules/tools/visualizer/grid.h"
#include "modules/tools/visualizer/main_window.h"
#include "modules/tools/visualizer/pointcloud.h"
#include "modules/tools/visualizer/radarpoints.h"
#include "modules/tools/visualizer/ui_main_window.h"
#include "modules/tools/visualizer/video_images_dialog.h"
namespace {
const char* globalTreeItemStyle = "margin-right:10px";
const char* aboutMessage =
"Cyber_Visualizer\n"
"\n"
"One Visualization Tool for Presenting Cyber Channel Data\n"
"\n"
"F5 Play | Pause\n"
"\n"
"Main View PointCloud view\n"
"All Views have right button Menu";
const char* licenseMessage =
"Copyright 2018 The Apollo Authors. All Rights Reserved.\n"
"\n"
"Licensed under the Apache License, Version 2.0 (the \"License\");\n"
"you may not use this file except in compliance with the License.\n"
"You may obtain a copy of the License at\n"
"\n"
"http://www.apache.org/licenses/LICENSE-2.0\n"
"\n"
"Unless required by applicable law or agreed to in writing, software\n"
"distributed under the License is distributed on an \"AS IS\" BASIS,\n"
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n"
"See the License for the specific language governing permissions and\n"
"limitations under the License.\n";
const char* pcTempObjGroupName = "pointcloud";
const char* pcVertexPath = ":/shaders/pointcloud.vert";
const char* pcFragPath = ":/shaders/grid_pointcloud.frag";
const char* gridVertexPath = ":/shaders/grid.vert";
const char* gridFragPath = ":/shaders/grid_pointcloud.frag";
const char* radarVertexPath = ":/shaders/radarpoints.vert";
const char* radarFragPath = ":/shaders/radarpoints.frag";
const std::string CompressedImageType("apollo.drivers.CompressedImage");
} // namespace
#define MEMBER_OFFSET(StructType, Member) \
(size_t)( \
reinterpret_cast<char*>(&(reinterpret_cast<StructType*>(1)->Member)) - \
1)
#define StructPtrByMemberPtr(MemberPtr, StructType, Member) \
reinterpret_cast<StructType*>(reinterpret_cast<char*>(MemberPtr) - \
MEMBER_OFFSET(StructType, Member))
struct MainWindow::VideoImgProxy {
FixedAspectRatioWidget video_image_viewer_;
QTreeWidgetItem root_item_;
QTreeWidgetItem channel_name_item_;
QTreeWidgetItem action_item_;
QComboBox channel_name_combobox_;
QPushButton action_item_button_;
QMutex reader_mutex_;
std::shared_ptr<Texture> dynamic_texture_;
bool isCompressedImage_;
union {
CyberChannReader<apollo::drivers::Image>* image_reader_;
CyberChannReader<apollo::drivers::CompressedImage>*
compressed_image_reader_;
};
VideoImgProxy()
: video_image_viewer_(),
root_item_(),
channel_name_item_(),
action_item_(),
channel_name_combobox_(),
action_item_button_(),
reader_mutex_(),
dynamic_texture_(),
isCompressedImage_(false),
image_reader_(nullptr) {}
void deleteReader(void) {
if (image_reader_) {
if (isCompressedImage_) {
delete compressed_image_reader_;
} else {
delete image_reader_;
}
image_reader_ = nullptr;
isCompressedImage_ = false;
}
}
void CloseChannel(void) {
if (isCompressedImage_) {
compressed_image_reader_->CloseChannel();
} else {
image_reader_->CloseChannel();
}
}
~VideoImgProxy(void) {
dynamic_texture_.reset();
deleteReader();
}
};
struct MainWindow::RadarData {
QTreeWidgetItem root_item_;
QTreeWidgetItem channel_name_item_;
QTreeWidgetItem action_item_;
QComboBox channel_name_combobox_;
QPushButton action_item_button_;
QCheckBox enable_checkBox_;
QMutex reader_mutex_;
CyberChannReader<apollo::drivers::RadarObstacles>* channel_reader_;
RadarData(void)
: root_item_(),
channel_name_item_(),
action_item_(),
channel_name_combobox_(),
action_item_button_(),
enable_checkBox_(),
reader_mutex_(),
channel_reader_(nullptr) {}
~RadarData(void) {
if (channel_reader_) {
delete channel_reader_;
channel_reader_ = nullptr;
}
}
};
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent),
ui_(new Ui::MainWindow),
msg_dialog_(new MessageDialog),
open_images_dialog_(nullptr),
grid_(nullptr),
enable_grid_checkBox_(nullptr),
grid_root_item_(nullptr),
pointcloud_top_item_(nullptr),
pointcloud_comboBox_(new QComboBox),
pointcloud_button_(new QPushButton),
pointcloud_channel_Reader_(nullptr),
pointcloud_reader_mutex_(),
pointcloud_shader_(nullptr),
grid_shader_(nullptr),
radar_points_shader_(nullptr),
video_image_viewer_list_(),
closed_video_image_viewer_list_(),
radarData_list_(),
closed_radarData_list_(),
_channelName2TypeMap() {
ui_->setupUi(this);
ui_->videoImageGridLayout->setContentsMargins(2, 2, 2, 2);
ui_->videoImageWidget->setVisible(false);
ui_->mainToolBar->addAction(ui_->actionAddGrid);
ui_->mainToolBar->addAction(ui_->actionPointCloud);
ui_->mainToolBar->addSeparator();
ui_->mainToolBar->addAction(ui_->actionOpenImage);
ui_->mainToolBar->addAction(ui_->actionOpenImages);
ui_->mainToolBar->addAction(ui_->actionDelImage);
ui_->mainToolBar->addSeparator();
ui_->mainToolBar->addAction(ui_->actionPlay);
ui_->mainToolBar->addAction(ui_->actionPause);
pointcloud_reader_mutex_.lock();
{
QStringList tmp;
tmp << "ChannelNames"
<< " ";
all_channel_root_ = new QTreeWidgetItem(tmp);
ui_->treeWidget->addTopLevelItem(all_channel_root_);
}
connect(ui_->actionAbout, SIGNAL(triggered(bool)), this, SLOT(showMessage()));
connect(ui_->actionLicense, SIGNAL(triggered(bool)), this,
SLOT(showMessage()));
pointcloud_button_->setCheckable(true);
pointcloud_button_->setStyleSheet(globalTreeItemStyle);
pointcloud_comboBox_->setStyleSheet(globalTreeItemStyle);
connect(pointcloud_button_, SIGNAL(clicked(bool)), this,
SLOT(PlayRenderableObject(bool)));
connect(pointcloud_comboBox_, SIGNAL(currentIndexChanged(int)), this,
SLOT(ChangePointCloudChannel()));
connect(ui_->treeWidget, SIGNAL(itemSelectionChanged()), this,
SLOT(UpdateActions()));
connect(ui_->treeWidget, SIGNAL(visibilityChanged(bool)), ui_->actionGlobal,
SLOT(setChecked(bool)));
connect(ui_->actionPlay, SIGNAL(triggered(bool)), this, SLOT(PlayPause()));
connect(ui_->actionPause, SIGNAL(triggered(bool)), this, SLOT(PlayPause()));
}
MainWindow::~MainWindow() {
for (VideoImgProxy* item : video_image_viewer_list_) {
item->reader_mutex_.unlock();
}
for (VideoImgProxy* item : closed_video_image_viewer_list_) {
item->reader_mutex_.unlock();
}
for (RadarData* item : radarData_list_) {
item->reader_mutex_.unlock();
}
for (RadarData* item : closed_radarData_list_) {
item->reader_mutex_.unlock();
}
pointcloud_reader_mutex_.unlock();
if (pointcloud_channel_Reader_) {
delete pointcloud_channel_Reader_;
pointcloud_channel_Reader_ = nullptr;
}
for (VideoImgProxy* item : video_image_viewer_list_) {
delete item;
}
for (VideoImgProxy* item : closed_video_image_viewer_list_) {
delete item;
}
for (RadarData* item : radarData_list_) {
delete item;
}
for (RadarData* item : closed_radarData_list_) {
delete item;
}
delete ui_;
delete msg_dialog_;
}
void MainWindow::calculateWH(void) {
int count = video_image_viewer_list_.count();
if (count > 0) {
QSize wh;
wh.setWidth(ui_->sceneWidget->width() - count * 2 + 2);
wh.setHeight(50);
wh.setWidth(wh.width() / count);
int index = 0;
for (VideoImgProxy* p : video_image_viewer_list_) {
p->video_image_viewer_.setMinimumSize(wh);
ui_->videoImageGridLayout->removeWidget(&p->video_image_viewer_);
ui_->videoImageGridLayout->addWidget(&p->video_image_viewer_, index / 3,
index % 3, 1, 1);
++index;
}
ui_->videoImageWidget->adjustSize();
}
}
MainWindow::VideoImgProxy* MainWindow::AddVideoImgViewer() {
std::shared_ptr<Texture> tex(new Texture);
if (tex == nullptr) {
return nullptr;
}
VideoImgProxy* ret = new VideoImgProxy();
if (ret) {
int index = video_image_viewer_list_.count();
ret->video_image_viewer_.set_index(index);
ret->video_image_viewer_.setStyleSheet("background-color:black;");
ret->video_image_viewer_.setVisible(false);
QString imgName = tr("Camera%1").arg(index);
ret->root_item_.setHidden(true);
ret->root_item_.setText(0, imgName);
ret->root_item_.setText(1, "");
ret->channel_name_item_.setText(0, "ChannelName");
ret->action_item_.setText(0, "Action");
ret->action_item_button_.setObjectName(tr("pushButton%1").arg(index));
ret->action_item_button_.setText("Play");
ret->action_item_button_.setCheckable(true);
ret->action_item_button_.setStyleSheet(globalTreeItemStyle);
ret->channel_name_combobox_.setObjectName(tr("comboBox%1").arg(index));
ret->channel_name_combobox_.setStyleSheet(globalTreeItemStyle);
ret->root_item_.addChild(&ret->channel_name_item_);
ret->root_item_.addChild(&ret->action_item_);
ret->dynamic_texture_ = tex;
ret->video_image_viewer_.SetupDynamicTexture(tex);
ret->video_image_viewer_.setSizePolicy(QSizePolicy::Preferred,
QSizePolicy::Preferred);
ret->video_image_viewer_.addAction(ui_->actionDelImage);
ret->reader_mutex_.lock();
}
return ret;
}
MainWindow::RadarData* MainWindow::createRadarData(void) {
RadarData* ret = new RadarData();
if (ret) {
int index = radarData_list_.count();
QString radarName = tr("Radar%1").arg(index);
ret->root_item_.setHidden(true);
ret->root_item_.setText(0, radarName);
ret->channel_name_item_.setText(0, "ChannelName");
ret->action_item_.setText(0, "Action");
ret->enable_checkBox_.setChecked(true);
ret->action_item_button_.setText("Play");
ret->action_item_button_.setCheckable(true);
ret->action_item_button_.setStyleSheet(globalTreeItemStyle);
ret->channel_name_combobox_.setObjectName(tr("comboBox%1").arg(index));
ret->channel_name_combobox_.setStyleSheet(globalTreeItemStyle);
ret->root_item_.addChild(&ret->channel_name_item_);
ret->root_item_.addChild(&ret->action_item_);
ret->reader_mutex_.lock();
}
return ret;
}
void MainWindow::EnableGrid(bool b) { grid_->set_is_renderable(b); }
void MainWindow::ActionAddGrid(void) {
if (grid_shader_ == nullptr) {
grid_shader_ = RenderableObject::CreateShaderProgram(tr(gridVertexPath),
tr(gridFragPath));
if (grid_shader_ != nullptr) {
ui_->sceneWidget->AddNewShaderProg("grid", grid_shader_);
}
}
if (grid_root_item_ == nullptr) {
QTreeWidgetItem* colorChild = nullptr;
QTreeWidgetItem* cellCountChild = nullptr;
QSpinBox* spinbox = nullptr;
grid_ = new Grid(6);
if (grid_ == nullptr) {
goto _ret1;
}
if (grid_shader_ == nullptr) {
goto _ret2;
}
enable_grid_checkBox_ = new QCheckBox(ui_->treeWidget);
if (enable_grid_checkBox_ == nullptr) {
goto _ret2;
}
grid_root_item_ = new QTreeWidgetItem(ui_->treeWidget);
if (grid_root_item_ == nullptr) {
goto _ret3;
}
colorChild = new QTreeWidgetItem(grid_root_item_);
if (colorChild == nullptr) {
goto _ret4;
}
grid_root_item_->addChild(colorChild);
colorChild->setText(0, "Color");
colorChild->setText(1, tr("%1;%2;%3")
.arg(grid_->red())
.arg(grid_->green())
.arg(grid_->blue()));
spinbox = new QSpinBox(ui_->treeWidget);
if (spinbox == nullptr) {
goto _ret5;
}
spinbox->setMinimum(1);
spinbox->setMaximum(100);
spinbox->setSingleStep(1);
spinbox->setValue(grid_->CellCount());
spinbox->setStyleSheet(globalTreeItemStyle);
cellCountChild = new QTreeWidgetItem(grid_root_item_);
if (cellCountChild == nullptr) {
goto _ret6;
}
grid_root_item_->addChild(cellCountChild);
cellCountChild->setText(0, "CellCount");
grid_->set_shader_program(grid_shader_);
if (!ui_->sceneWidget->AddPermanentRenderObj(grid_)) {
goto _ret7;
}
enable_grid_checkBox_->setText("Enable");
enable_grid_checkBox_->setChecked(true);
grid_root_item_->setText(0, "Grid");
grid_root_item_->setText(1, "");
ui_->treeWidget->addTopLevelItem(grid_root_item_);
ui_->treeWidget->setItemWidget(grid_root_item_, 1, enable_grid_checkBox_);
ui_->treeWidget->setItemWidget(cellCountChild, 1, spinbox);
connect(enable_grid_checkBox_, SIGNAL(clicked(bool)), this,
SLOT(EnableGrid(bool)));
connect(ui_->treeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)),
this, SLOT(EditGridColor(QTreeWidgetItem*, int)));
connect(spinbox, SIGNAL(valueChanged(int)), this,
SLOT(ChangeGridCellCountBySize(int)));
return;
_ret7:
delete cellCountChild;
_ret6:
delete spinbox;
_ret5:
delete colorChild;
_ret4:
delete grid_root_item_;
_ret3:
delete enable_grid_checkBox_;
_ret2:
delete grid_;
_ret1:
QMessageBox::warning(this, tr("Error"),
tr("There is no enough memory for creating Grid!!!"),
QMessageBox::Ok);
return;
}
}
void MainWindow::ChangeGridCellCountBySize(int v) {
grid_->Destroy();
grid_->set_shader_program(grid_shader_);
grid_->SetCellCount(v);
grid_->set_is_renderable(true);
}
void MainWindow::EditGridColor(QTreeWidgetItem* item, int column) {
if (column && item != nullptr && grid_root_item_ != nullptr &&
item == grid_root_item_->child(0)) {
QStringList rgb = item->text(1).split(';');
QColor color(rgb.at(0).toInt(), rgb.at(1).toInt(), rgb.at(2).toInt());
color = QColorDialog::getColor(color, nullptr, tr("set grid color"));
if (color.isValid()) {
QString str =
tr("%1;%2;%3").arg(color.red()).arg(color.green()).arg(color.blue());
item->setText(1, str);
grid_->set_grid_color(color);
}
}
}
void MainWindow::EnableRadarPoints(bool b) {
QCheckBox* obj = static_cast<QCheckBox*>(sender());
RadarData* r = StructPtrByMemberPtr(obj, RadarData, enable_checkBox_);
ui_->sceneWidget->setTempObjGroupEnabled(r->root_item_.text(0).toStdString(),
b);
}
void MainWindow::ActionOpenRadarChannel(void) {
if (radar_points_shader_ == nullptr) {
radar_points_shader_ = RenderableObject::CreateShaderProgram(
tr(radarVertexPath), tr(radarFragPath));
if (radar_points_shader_ != nullptr) {
ui_->sceneWidget->AddNewShaderProg("radarpoints", radar_points_shader_);
} else {
QMessageBox::warning(
this, tr("NO Shader"),
tr("There is no suitable shader for Radar Points!!!"),
QMessageBox::Ok);
return;
}
}
RadarData* radarProxy;
if (closed_radarData_list_.empty()) {
radarProxy = createRadarData();
if (radarProxy == nullptr) {
QMessageBox::warning(this, tr("No Enough Memory"),
tr("There is no enough memory!!!\nCannot add new "
"image or video channel!"),
QMessageBox::Ok);
return;
}
ui_->treeWidget->addTopLevelItem(&radarProxy->root_item_);
ui_->treeWidget->setItemWidget(&radarProxy->root_item_, 1,
&radarProxy->enable_checkBox_);
ui_->treeWidget->setItemWidget(&radarProxy->channel_name_item_, 1,
&radarProxy->channel_name_combobox_);
ui_->treeWidget->setItemWidget(&radarProxy->action_item_, 1,
&radarProxy->action_item_button_);
for (int i = 0; i < all_channel_root_->childCount(); ++i) {
QTreeWidgetItem* child = all_channel_root_->child(i);
QString channel = child->text(0);
if (channel.contains("radar")) {
radarProxy->channel_name_combobox_.addItem(channel);
}
}
} else {
radarProxy = closed_radarData_list_.takeFirst();
}
connect(&radarProxy->action_item_button_, SIGNAL(clicked(bool)), this,
SLOT(openRadarChannel(bool)));
connect(&radarProxy->enable_checkBox_, SIGNAL(clicked(bool)), this,
SLOT(EnableRadarPoints(bool)));
connect(&radarProxy->channel_name_combobox_, SIGNAL(currentIndexChanged(int)),
this, SLOT(ChangeRadarChannel()));
radarData_list_.append(radarProxy);
radarProxy->root_item_.setHidden(false);
ui_->treeWidget->setVisible(true);
ui_->actionGlobal->setChecked(true);
}
void MainWindow::openRadarChannel(bool b) {
QPushButton* obj = static_cast<QPushButton*>(QObject::sender());
RadarData* theVideoImg =
StructPtrByMemberPtr(obj, RadarData, action_item_button_);
DoOpenRadarChannel(b, theVideoImg);
}
void MainWindow::DoOpenRadarChannel(bool b, RadarData* radarProxy) {
if (b) {
if (radarProxy->channel_name_combobox_.currentText().isEmpty()) {
QMessageBox::warning(
this, tr("Setup Channel Name"),
tr("Channel Name cannot be empty!!!\nPlease select one!"),
QMessageBox::Ok);
radarProxy->action_item_button_.setChecked(false);
return;
}
if (!radarProxy->channel_reader_) {
radarProxy->channel_reader_ =
new CyberChannReader<apollo::drivers::RadarObstacles>();
if (!radarProxy->channel_reader_) {
QMessageBox::warning(this, tr("Create cyber Channel Reader"),
tr("There is no enough memory!!!\nCannot create "
"cyber channel reader!"),
QMessageBox::Ok);
return;
}
auto radarcallback =
[this, radarProxy](
const std::shared_ptr<apollo::drivers::RadarObstacles>& pdata) {
this->RadarRenderCallback(pdata, radarProxy);
};
std::string nodeName("Visualizer-");
nodeName.append(radarProxy->root_item_.text(0).toStdString());
if (!radarProxy->channel_reader_->InstallCallbackAndOpen(
radarcallback,
radarProxy->channel_name_combobox_.currentText().toStdString(),
nodeName)) {
QMessageBox::warning(
this, tr("Setup Channel Callback"),
tr("Channel Callback cannot be installed!!!\nPlease check it!"),
QMessageBox::Ok);
delete radarProxy->channel_reader_;
radarProxy->channel_reader_ = nullptr;
radarProxy->action_item_button_.setChecked(false);
return;
}
}
radarProxy->root_item_.setToolTip(
0, radarProxy->channel_name_combobox_.currentText());
radarProxy->action_item_button_.setText("Stop");
radarProxy->channel_name_combobox_.setEnabled(false);
radarProxy->reader_mutex_.unlock();
} else {
if (!radarProxy->channel_name_combobox_.isEnabled()) {
radarProxy->reader_mutex_.lock();
radarProxy->action_item_button_.setText("Play");
radarProxy->channel_name_combobox_.setEnabled(true);
}
}
ui_->treeWidget->setCurrentItem(nullptr);
ui_->treeWidget->clearFocus();
}
void MainWindow::RadarRenderCallback(
const std::shared_ptr<const apollo::drivers::RadarObstacles>& rawData,
RadarData* radar) {
radar->reader_mutex_.lock();
radar->reader_mutex_.unlock();
std::cout << "-------MainWindow::RadarRenderCallback()-------" << std::endl;
if (rawData != nullptr) {
RadarPoints* r = new RadarPoints(radar_points_shader_);
if (r) {
if (!r->FillData(rawData) ||
!ui_->sceneWidget->AddTempRenderableObj(
radar->root_item_.text(0).toStdString(), r)) {
delete r;
}
} else {
std::cerr << "cannot create RadarPoints Renderable Object" << std::endl;
}
}
}
void MainWindow::ActionOpenPointCloud(void) {
if (pointcloud_shader_ == nullptr) {
pointcloud_shader_ =
RenderableObject::CreateShaderProgram(tr(pcVertexPath), tr(pcFragPath));
if (pointcloud_shader_ != nullptr) {
ui_->sceneWidget->AddNewShaderProg("pointcloud", pointcloud_shader_);
} else {
QMessageBox::warning(this, tr("NO Shader"),
tr("There is no suitable shader for Pointcloud!!!"),
QMessageBox::Ok);
return;
}
}
if (pointcloud_top_item_ == nullptr) {
pointcloud_top_item_ = new QTreeWidgetItem(ui_->treeWidget);
if (pointcloud_top_item_ == nullptr) {
return;
}
pointcloud_top_item_->setText(0, "PointCloud2");
pointcloud_top_item_->setText(1, "");
QTreeWidgetItem* item = new QTreeWidgetItem(pointcloud_top_item_);
if (item == nullptr) {
QMessageBox::warning(this, tr("NO Enough Memory"),
tr("Cannot create tree item for channel name!!!"),
QMessageBox::Ok);
return;
}
item->setText(0, "ChannelName");
ui_->treeWidget->setItemWidget(item, 1, pointcloud_comboBox_);
item = new QTreeWidgetItem(pointcloud_top_item_);
if (item == nullptr) {
QMessageBox::warning(this, tr("NO Enough Memory"),
tr("Cannot create tree item for channel Action!!!"),
QMessageBox::Ok);
return;
}
item->setText(0, "Action");
pointcloud_button_->setText("Play");
ui_->treeWidget->setItemWidget(item, 1, pointcloud_button_);
ui_->treeWidget->setVisible(true);
ui_->actionGlobal->setChecked(true);
}
}
void MainWindow::ActionOpenImages(void) {
if (open_images_dialog_ == nullptr) {
open_images_dialog_ = new VideoImagesDialog(this);
if (open_images_dialog_ == nullptr) {
QMessageBox::warning(this, tr("No Enough Memory"),
tr("There is no enough memory!!!"), QMessageBox::Ok);
return;
} else {
connect(open_images_dialog_, SIGNAL(accepted()), this,
SLOT(AddVideoImages()));
}
}
open_images_dialog_->show();
}
void MainWindow::AddVideoImages(void) {
int count = open_images_dialog_->count();
while (count) {
ActionOpenImage();
--count;
}
}
void MainWindow::ActionOpenImage(void) {
VideoImgProxy* videoImgProxy;
if (closed_video_image_viewer_list_.empty()) {
videoImgProxy = AddVideoImgViewer();
if (videoImgProxy == nullptr) {
QMessageBox::warning(this, tr("No Enough Memory"),
tr("There is no enough memory!!!\nCannot add new "
"image or video channel!"),
QMessageBox::Ok);
return;
}
videoImgProxy->video_image_viewer_.setParent(ui_->videoImageWidget);
ui_->treeWidget->addTopLevelItem(&videoImgProxy->root_item_);
ui_->treeWidget->setItemWidget(&videoImgProxy->channel_name_item_, 1,
&videoImgProxy->channel_name_combobox_);
ui_->treeWidget->setItemWidget(&videoImgProxy->action_item_, 1,
&videoImgProxy->action_item_button_);
for (int i = 0; i < all_channel_root_->childCount(); ++i) {
QTreeWidgetItem* child = all_channel_root_->child(i);
QString channel = child->text(0);
if (channel.contains("camera")) {
videoImgProxy->channel_name_combobox_.addItem(channel);
}
}
} else {
videoImgProxy = closed_video_image_viewer_list_.takeFirst();
}
connect(&videoImgProxy->action_item_button_, SIGNAL(clicked(bool)), this,
SLOT(PlayVideoImage(bool)));
connect(&videoImgProxy->channel_name_combobox_,
SIGNAL(currentIndexChanged(int)), this,
SLOT(ChangeVideoImgChannel()));
connect(&videoImgProxy->video_image_viewer_,
SIGNAL(focusOnThis(FixedAspectRatioWidget*)), this,
SLOT(SelectCurrentTreeItem(FixedAspectRatioWidget*)));
video_image_viewer_list_.append(videoImgProxy);
videoImgProxy->video_image_viewer_.setVisible(true);
calculateWH();
videoImgProxy->video_image_viewer_.StartOrStopUpdate(true);
videoImgProxy->root_item_.setHidden(false);
ui_->videoImageWidget->setVisible(true);
ui_->treeWidget->setVisible(true);
ui_->actionGlobal->setChecked(true);
repaint();
}
void MainWindow::ActionDelVideoImage(void) {
QTreeWidgetItem* topItem = ui_->treeWidget->currentItem();
VideoImgProxy* proxy =
StructPtrByMemberPtr(topItem, VideoImgProxy, root_item_);
DoDeleteVideoImg(proxy);
ui_->actionDelImage->setEnabled(false);
}
void MainWindow::CloseVideoImgViewer(bool b) {
if (!b) {
VideoImgViewer* dock = static_cast<VideoImgViewer*>(sender());
DoDeleteVideoImg(
StructPtrByMemberPtr(dock, VideoImgProxy, video_image_viewer_));
}
}
void MainWindow::DoDeleteVideoImg(VideoImgProxy* proxy) {
disconnect(&proxy->action_item_button_, SIGNAL(clicked(bool)), this,
SLOT(PlayVideoImage(bool)));
disconnect(&proxy->channel_name_combobox_, SIGNAL(currentIndexChanged(int)),
this, SLOT(ChangeVideoImgChannel()));
disconnect(&proxy->video_image_viewer_,
SIGNAL(focusOnThis(FixedAspectRatioWidget*)), this,
SLOT(SelectCurrentTreeItem(FixedAspectRatioWidget*)));
proxy->action_item_button_.setChecked(false);
DoPlayVideoImage(false, proxy);
proxy->video_image_viewer_.StartOrStopUpdate(false);
proxy->root_item_.setHidden(true);
proxy->video_image_viewer_.setVisible(false);
ui_->videoImageGridLayout->removeWidget(&proxy->video_image_viewer_);
video_image_viewer_list_.removeOne(proxy);
closed_video_image_viewer_list_.append(proxy);
if (video_image_viewer_list_.count()) {
calculateWH();
} else {
ui_->videoImageWidget->setVisible(false);
}
}
void MainWindow::UpdateActions(void) {
QTreeWidgetItem* item = ui_->treeWidget->currentItem();
ui_->actionDelImage->setEnabled(false);
if (item) {
if (!item->parent() && item != pointcloud_top_item_ &&
item != all_channel_root_ && item != grid_root_item_) {
ui_->actionDelImage->setEnabled(true);
}
}
}
void MainWindow::PointCloudReaderCallback(
const std::shared_ptr<const apollo::drivers::PointCloud>& pdata) {
pointcloud_reader_mutex_.lock();
pointcloud_reader_mutex_.unlock();
PointCloud* pc = new PointCloud(pdata->point_size(), 4, pointcloud_shader_);
if (pc) {
if (!pc->FillData(pdata) ||
!ui_->sceneWidget->AddTempRenderableObj(pcTempObjGroupName, pc)) {
delete pc;
}
} else {
std::cerr << "-----Cannot create PointCloud----------" << std::endl;
}
}
void MainWindow::PlayRenderableObject(bool b) {
if (b) {
if (pointcloud_comboBox_->currentText().isEmpty()) {
QMessageBox::warning(
this, tr("Setup Channel Name"),
tr("Channel Name cannot be empty!!!\nPlease Select it!"),
QMessageBox::Ok);
pointcloud_button_->setChecked(false);
return;
}
if (!pointcloud_channel_Reader_) {
pointcloud_channel_Reader_ =
new CyberChannReader<apollo::drivers::PointCloud>();
if (!pointcloud_channel_Reader_) {
QMessageBox::warning(this, tr("Create Cyber Channel Reader"),
tr("There is no enough memory!!!\nCannot create "
"cyber channel reader!"),
QMessageBox::Ok);
pointcloud_button_->setChecked(false);
return;
}
auto pointCallback =
[this](const std::shared_ptr<apollo::drivers::PointCloud>& pdata) {
this->PointCloudReaderCallback(pdata);
};
std::string nodeName("Visualizer-");
nodeName.append(pointcloud_top_item_->text(0).toStdString());
if (!pointcloud_channel_Reader_->InstallCallbackAndOpen(
pointCallback, pointcloud_comboBox_->currentText().toStdString(),
nodeName)) {
QMessageBox::warning(
this, tr("Setup Channel Callback"),
tr("Channel Callback cannot be installed!!!\nPlease check it!"),
QMessageBox::Ok);
delete pointcloud_channel_Reader_;
pointcloud_channel_Reader_ = nullptr;
pointcloud_button_->setChecked(false);
return;
}
}
ui_->sceneWidget->setToolTip(pointcloud_comboBox_->currentText());
pointcloud_top_item_->setToolTip(0, pointcloud_comboBox_->currentText());
pointcloud_comboBox_->setEnabled(false);
pointcloud_button_->setText(tr("Stop"));
pointcloud_reader_mutex_.unlock();
} else {
if (!pointcloud_comboBox_->isEnabled()) {
pointcloud_reader_mutex_.lock();
pointcloud_comboBox_->setEnabled(true);
pointcloud_button_->setText(tr("Show"));
}
}
ui_->treeWidget->setCurrentItem(nullptr);
ui_->treeWidget->clearFocus();
}
void MainWindow::ImageReaderCallback(
const std::shared_ptr<const apollo::drivers::Image>& imgData,
VideoImgProxy* theVideoImgProxy) {
theVideoImgProxy->reader_mutex_.lock();
if (theVideoImgProxy->dynamic_texture_ != nullptr && imgData != nullptr) {
if (theVideoImgProxy->dynamic_texture_->UpdateData(imgData)) {
theVideoImgProxy->video_image_viewer_.SetupDynamicTexture(
theVideoImgProxy->dynamic_texture_);
} else {
std::cerr << "--------Cannot update dynamic Texture Data--------"
<< std::endl;
}
} else {
std::cerr
<< "----Dynamic Texture is nullptr or apollo.drivers.Image is nullptr"
<< std::endl;
}
theVideoImgProxy->reader_mutex_.unlock();
}
void MainWindow::ImageReaderCallback(
const std::shared_ptr<const apollo::drivers::CompressedImage>& imgData,
VideoImgProxy* theVideoImgProxy) {
theVideoImgProxy->reader_mutex_.lock();
if (theVideoImgProxy->dynamic_texture_ != nullptr && imgData != nullptr) {
QImage img;
const std::string& data = imgData->data();
if (img.loadFromData(reinterpret_cast<const unsigned char*>(data.c_str()),
static_cast<int>(data.size()))) {
if (theVideoImgProxy->dynamic_texture_->UpdateData(img)) {
theVideoImgProxy->video_image_viewer_.SetupDynamicTexture(
theVideoImgProxy->dynamic_texture_);
} else {
std::cerr << "--------Cannot update dynamic Texture Data--------"
<< std::endl;
}
} else {
std::cerr
<< "-----------Cannot load compressed image from data with QImage"
<< std::endl;
}
} else {
std::cerr
<< "----Dynamic Texture is nullptr or apollo.drivers.Image is nullptr"
<< std::endl;
}
theVideoImgProxy->reader_mutex_.unlock();
}
void MainWindow::PlayVideoImage(bool b) {
QPushButton* obj = static_cast<QPushButton*>(QObject::sender());
VideoImgProxy* theVideoImg =
StructPtrByMemberPtr(obj, VideoImgProxy, action_item_button_);
DoPlayVideoImage(b, theVideoImg);
}
void MainWindow::DoPlayVideoImage(bool b, VideoImgProxy* theVideoImg) {
if (b) {
if (theVideoImg->channel_name_combobox_.currentText().isEmpty()) {
QMessageBox::warning(
this, tr("Setup Channel Name"),
tr("Channel Name cannot be empty!!!\nPlease select one!"),
QMessageBox::Ok);
theVideoImg->action_item_button_.setChecked(false);
return;
}
const std::string channelName =
theVideoImg->channel_name_combobox_.currentText().toStdString();
if (_channelName2TypeMap[channelName] == CompressedImageType)
theVideoImg->isCompressedImage_ = true;
if (!theVideoImg->image_reader_) {
if (theVideoImg->isCompressedImage_) {
theVideoImg->compressed_image_reader_ =
new CyberChannReader<apollo::drivers::CompressedImage>();
} else {
theVideoImg->image_reader_ =
new CyberChannReader<apollo::drivers::Image>();
}
if (!theVideoImg->image_reader_) {
QMessageBox::warning(this, tr("Create cyber Channel Reader"),
tr("There is no enough memory!!!\nCannot create "
"cyber channel reader!"),
QMessageBox::Ok);
return;
}
std::string nodeName("Visualizer-");
nodeName.append(theVideoImg->root_item_.text(0).toStdString());
bool ret = false;
if (theVideoImg->isCompressedImage_) {
auto videoCallback =
[this, theVideoImg](
const std::shared_ptr<apollo::drivers::CompressedImage>&
pdata) { this->ImageReaderCallback(pdata, theVideoImg); };
ret = theVideoImg->compressed_image_reader_->InstallCallbackAndOpen(
videoCallback, channelName, nodeName);
} else {
auto videoCallback =
[this, theVideoImg](
const std::shared_ptr<apollo::drivers::Image>& pdata) {
this->ImageReaderCallback(pdata, theVideoImg);
};
ret = theVideoImg->image_reader_->InstallCallbackAndOpen(
videoCallback, channelName, nodeName);
}
if (!ret) {
QMessageBox::warning(
this, tr("Setup Channel Callback"),
tr("Channel Callback cannot be installed!!!\nPlease check it!"),
QMessageBox::Ok);
theVideoImg->deleteReader();
theVideoImg->action_item_button_.setChecked(false);
return;
}
}
theVideoImg->root_item_.setToolTip(
0, theVideoImg->channel_name_combobox_.currentText());
theVideoImg->video_image_viewer_.setToolTip(
theVideoImg->channel_name_combobox_.currentText());
theVideoImg->action_item_button_.setText("Stop");
theVideoImg->channel_name_combobox_.setEnabled(false);
theVideoImg->reader_mutex_.unlock();
} else {
if (!theVideoImg->channel_name_combobox_.isEnabled()) {
theVideoImg->reader_mutex_.lock();
theVideoImg->action_item_button_.setText("Play");
theVideoImg->channel_name_combobox_.setEnabled(true);
}
}
ui_->treeWidget->setCurrentItem(nullptr);
ui_->treeWidget->clearFocus();
}
void MainWindow::ChangePointCloudChannel() {
if (pointcloud_channel_Reader_ != nullptr) {
pointcloud_channel_Reader_->CloseChannel();
std::string nodeName("Visualizer-");
nodeName.append(pointcloud_top_item_->text(0).toStdString());
pointcloud_channel_Reader_->OpenChannel(
pointcloud_comboBox_->currentText().toStdString(), nodeName);
}
}
void MainWindow::ChangeVideoImgChannel() {
QComboBox* obj = static_cast<QComboBox*>(QObject::sender());
VideoImgProxy* theVideoImg =
StructPtrByMemberPtr(obj, VideoImgProxy, channel_name_combobox_);
if (theVideoImg->image_reader_ != nullptr) {
theVideoImg->deleteReader();
}
}
void MainWindow::ChangeRadarChannel(void) {
QComboBox* obj = static_cast<QComboBox*>(QObject::sender());
RadarData* radar =
StructPtrByMemberPtr(obj, RadarData, channel_name_combobox_);
if (radar->channel_reader_ != nullptr) {
radar->channel_reader_->CloseChannel();
std::string nodeName("Visualizer-");
nodeName.append(radar->root_item_.text(0).toStdString());
radar->channel_reader_->OpenChannel(obj->currentText().toStdString(),
nodeName);
}
}
void MainWindow::SelectCurrentTreeItem(FixedAspectRatioWidget* dock) {
if (dock) {
VideoImgProxy* theVideoImg =
StructPtrByMemberPtr(dock, VideoImgProxy, video_image_viewer_);
theVideoImg->root_item_.setExpanded(true);
if (ui_->treeWidget->currentItem() == &theVideoImg->root_item_) {
ui_->actionDelImage->setEnabled(true);
} else {
ui_->treeWidget->setCurrentItem(&theVideoImg->root_item_);
}
ui_->treeWidget->setFocus();
}
}
void MainWindow::TopologyChanged(
const apollo::cyber::proto::ChangeMsg& changeMsg) {
if (apollo::cyber::proto::ChangeType::CHANGE_CHANNEL ==
changeMsg.change_type() &&
apollo::cyber::proto::RoleType::ROLE_WRITER == changeMsg.role_type() &&
apollo::cyber::proto::OperateType::OPT_JOIN == changeMsg.operate_type()) {
AddNewWriter(changeMsg.role_attr());
}
}
void MainWindow::AddNewWriter(
const apollo::cyber::proto::RoleAttributes& role) {
const std::string& channelName = role.channel_name();
if (_channelName2TypeMap.find(channelName) != _channelName2TypeMap.end()) {
return;
}
const std::string& msgTypeName = role.message_type();
_channelName2TypeMap[channelName] = msgTypeName;
QTreeWidgetItem* child = new QTreeWidgetItem();
if (child == nullptr) {
QMessageBox::warning(this, tr("Error"), tr("No Enough for New Channel!!!"),
QMessageBox::Ok);
return;
}
QString str(channelName.c_str());
child->setText(0, str);
child->setToolTip(0, str);
bool b = true;
for (int i = 0; i < all_channel_root_->childCount(); ++i) {
if (str < all_channel_root_->child(i)->text(0)) {
all_channel_root_->insertChild(i, child);
b = false;
}
}
if (b) {
all_channel_root_->addChild(child);
}
ui_->treeWidget->setRootIsDecorated(true);
QString msgType(msgTypeName.c_str());
if (msgType.contains("camera", Qt::CaseInsensitive)) {
for (VideoImgProxy* item : video_image_viewer_list_) {
item->channel_name_combobox_.addItem(str);
}
for (VideoImgProxy* item : closed_video_image_viewer_list_) {
item->channel_name_combobox_.addItem(str);
}
}
if (msgType.contains("pointcloud", Qt::CaseInsensitive)) {
pointcloud_comboBox_->addItem(str);
}
if (msgType.contains("radar", Qt::CaseInsensitive)) {
for (RadarData* item : radarData_list_) {
item->channel_name_combobox_.addItem(str);
}
for (RadarData* item : closed_radarData_list_) {
item->channel_name_combobox_.addItem(str);
}
}
}
void MainWindow::PlayPause(void) {
QObject* obj = QObject::sender();
bool b = true;
if (obj == ui_->actionPause) {
b = false;
}
if (pointcloud_top_item_) {
pointcloud_button_->setChecked(b);
PlayRenderableObject(b);
}
for (VideoImgProxy* p : video_image_viewer_list_) {
p->action_item_button_.setChecked(b);
DoPlayVideoImage(b, p);
}
for (RadarData* item : radarData_list_) {
item->action_item_button_.setChecked(b);
DoOpenRadarChannel(b, item);
}
}
void MainWindow::resizeEvent(QResizeEvent* event) {
QMainWindow::resizeEvent(event);
calculateWH();
}
void MainWindow::showMessage() {
QObject* obj = QObject::sender();
if (obj == ui_->actionAbout) {
msg_dialog_->setWindowTitle(tr("About"));
msg_dialog_->setMessage(aboutMessage);
goto showMsgLabel;
}
if (obj == ui_->actionLicense) {
msg_dialog_->setWindowTitle(tr("License"));
msg_dialog_->setMessage(licenseMessage);
showMsgLabel:
msg_dialog_->adjustSize();
msg_dialog_->show();
}
}
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/msg_dialog.h
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#pragma once
#include <QtWidgets/QDialog>
namespace Ui {
class MessageDialog;
}
class MessageDialog : public QDialog {
Q_OBJECT
public:
explicit MessageDialog(QWidget* parent = nullptr);
~MessageDialog();
void setMessage(const QString& msg);
void setMessage(const char* msg) { setMessage(QString(msg)); }
private:
Ui::MessageDialog* ui_;
};
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/free_camera.h
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#pragma once
#include "modules/tools/visualizer/abstract_camera.h"
class FreeCamera : public AbstractCamera {
public:
FreeCamera(void);
~FreeCamera() {}
// After calling the function updateWorld
// the translation become zero vector
virtual void UpdateWorld(void);
const QVector3D& tanslation(void) { return translation_; }
void set_translation(const QVector3D& t) { translation_ = t; }
void Walk(const float dt) { translation_ += (look_ * dt); }
void Starfe(const float dt) { translation_ += (right_ * dt); }
void Lift(const float dt) { translation_ += (up_ * dt); }
private:
QVector3D translation_;
};
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/video_image_viewer.h
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#pragma once
#include <QtWidgets/QOpenGLWidget>
#include <memory>
#include "modules/tools/visualizer/free_camera.h"
#include "modules/tools/visualizer/plane.h"
class Texture;
class FixedAspectRatioWidget;
class VideoImgViewer : public QOpenGLWidget, protected QOpenGLFunctions {
public:
explicit VideoImgViewer(QWidget* parent = nullptr);
~VideoImgViewer();
protected:
void initializeGL() override;
void resizeGL(int w, int h) override;
void paintGL() override;
private:
bool is_init_;
int mvp_id_;
Plane plane_;
FreeCamera ortho_camera_;
std::shared_ptr<Texture> default_image_;
std::shared_ptr<QOpenGLShaderProgram> video_image_shader_prog_;
friend class FixedAspectRatioWidget;
};
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/scene_camera_dialog.h
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#pragma once
#include <QtWidgets/QDialog>
namespace Ui {
class SceneCameraDialog;
}
class QVector3D;
class SceneCameraDialog : public QDialog {
Q_OBJECT
public:
explicit SceneCameraDialog(QWidget *parent = nullptr);
~SceneCameraDialog();
signals:
void resetcamera();
void sensitivityChanged(float);
void cameraTypeChanged(int);
void xValueChanged(double);
void yValueChanged(double);
void zValueChanged(double);
void yawValueChanged(double);
void pitchValueChanged(double);
void rollValueChanged(double);
public slots: // NOLINT
void updateCameraAttitude(const QVector3D &);
void updateCameraPos(const QVector3D &);
private slots: // NOLINT
void OnStepSlideChanged(int v);
void onCameraTypeChanged(int);
private:
Ui::SceneCameraDialog *ui;
};
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/res.qrc
|
<RCC>
<qresource prefix="/">
<file>images/app.ico</file>
<file>images/closeimage.png</file>
<file>images/grid.png</file>
<file>images/image.png</file>
<file>images/images.png</file>
<file>images/no_image.png</file>
<file>images/pause.png</file>
<file>images/play.png</file>
<file>images/pointcloud.png</file>
<file>shaders/grid.vert</file>
<file>shaders/grid_pointcloud.frag</file>
<file>shaders/pointcloud.vert</file>
<file>shaders/video_image_plane.frag</file>
<file>shaders/video_image_plane.vert</file>
<file>shaders/radarpoints.frag</file>
<file>shaders/radarpoints.vert</file>
</qresource>
</RCC>
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/visualizer/scene_viewer.cc
|
/******************************************************************************
* Copyright 2018 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/tools/visualizer/scene_viewer.h"
#include <QtCore/QTimer>
#include <QtGui/QWheelEvent>
#include <QtWidgets/QMessageBox>
#include "modules/tools/visualizer/scene_camera_dialog.h"
struct SceneViewer::TempRenderableObjGroup {
bool isEnabled_;
QList<RenderableObject *> objGroupList_;
TempRenderableObjGroup(void) : isEnabled_(true), objGroupList_() {}
~TempRenderableObjGroup(void) {
while (!objGroupList_.isEmpty()) {
delete objGroupList_.takeFirst();
}
objGroupList_.clear();
}
bool isEmpty(void) const { return objGroupList_.isEmpty(); }
bool isEnabled(void) const { return isEnabled_; }
void append(RenderableObject *obj) { objGroupList_.append(obj); }
RenderableObject *takeFirst(void) { return objGroupList_.takeFirst(); }
RenderableObject *takeLast(void) { return objGroupList_.takeLast(); }
};
SceneViewer::SceneViewer(QWidget *parent)
: QOpenGLWidget(parent),
QOpenGLFunctions(),
is_init_(false),
right_key_is_moved_(false),
sensitivity_(0.08f),
refreshTimer_(nullptr),
left_key_last_pos_(),
right_key_last_y_(0),
camera_dialog_(nullptr),
current_cameraPtr_(nullptr),
free_camera_(),
target_camera_(),
managed_shader_prog_(),
tmp_renderable_obj_list_(),
permanent_renderable_obj_list_() {
current_cameraPtr_ = &target_camera_;
}
SceneViewer::~SceneViewer() {
if (is_init_) {
is_init_ = false;
refreshTimer_->stop();
delete refreshTimer_;
makeCurrent();
auto iter = managed_shader_prog_.begin();
for (; iter != managed_shader_prog_.end(); ++iter) {
iter->second->destroyed();
iter->second.reset();
}
managed_shader_prog_.clear();
for (auto &iter : tmp_renderable_obj_list_) {
delete iter.second;
}
tmp_renderable_obj_list_.clear();
while (!permanent_renderable_obj_list_.isEmpty()) {
delete permanent_renderable_obj_list_.takeFirst();
}
doneCurrent();
}
}
void SceneViewer::setTempObjGroupEnabled(const std::string &tmpObjGroupName,
bool b) {
auto iter = tmp_renderable_obj_list_.find(tmpObjGroupName);
if (iter != tmp_renderable_obj_list_.cend()) {
iter->second->isEnabled_ = b;
}
}
bool SceneViewer::AddTempRenderableObj(const std::string &tmpObjGroupName,
RenderableObject *renderObj) {
bool ret = false;
if (renderObj && renderObj->haveShaderProgram() && is_init_) {
auto iter = tmp_renderable_obj_list_.find(tmpObjGroupName);
if (iter == tmp_renderable_obj_list_.cend()) {
TempRenderableObjGroup *objGroup = new TempRenderableObjGroup();
if (objGroup) {
objGroup->append(renderObj);
tmp_renderable_obj_list_.insert(
std::make_pair(tmpObjGroupName, objGroup));
ret = true;
}
} else {
iter->second->objGroupList_.append(renderObj);
ret = true;
}
}
return ret;
}
void SceneViewer::AddNewShaderProg(
const std::string &shaderProgName,
const std::shared_ptr<QOpenGLShaderProgram> &newShaderProg) {
if (newShaderProg == nullptr) {
return;
}
auto iter = managed_shader_prog_.find(shaderProgName);
if (iter != managed_shader_prog_.end()) {
iter->second.reset();
}
QMatrix4x4 mvp = current_cameraPtr_->projection_matrix() *
current_cameraPtr_->model_view_matrix();
newShaderProg->bind();
newShaderProg->setUniformValue("mvp", mvp);
newShaderProg->release();
managed_shader_prog_[shaderProgName] = newShaderProg;
}
void SceneViewer::initializeGL() {
initializeOpenGLFunctions();
glPointSize(1.0f);
glEnable(GL_PROGRAM_POINT_SIZE);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
refreshTimer_ = new QTimer(this);
if (!refreshTimer_) {
return;
}
refreshTimer_->setObjectName(tr("_refreshTimer"));
refreshTimer_->setInterval(40);
refreshTimer_->start();
connect(refreshTimer_, SIGNAL(timeout()), this, SLOT(repaint()));
free_camera_.SetUpProjection(45.0f, GLfloat(width()), GLfloat(height()));
target_camera_.SetUpProjection(45.0f, GLfloat(width()), GLfloat(height()));
ResetCameraPosAttitude();
is_init_ = true;
}
void SceneViewer::resizeGL(int width, int height) {
glViewport(0, 0, (GLsizei)width, (GLsizei)height);
if (is_init_) {
free_camera_.set_near_plane_width(GLfloat(width));
free_camera_.set_near_plane_height(GLfloat(height));
free_camera_.UpdateProjection();
target_camera_.set_near_plane_width(GLfloat(width));
target_camera_.set_near_plane_height(GLfloat(height));
target_camera_.UpdateProjection();
QMatrix4x4 mvp = current_cameraPtr_->projection_matrix() *
current_cameraPtr_->model_view_matrix();
UpdateAllShaderProgMVP(mvp);
}
}
void SceneViewer::paintGL() {
if (is_init_) {
for (RenderableObject *item : permanent_renderable_obj_list_) {
if (item->Init()) {
item->Render();
}
}
for (auto &iter : tmp_renderable_obj_list_) {
if (!iter.second->isEmpty()) {
RenderableObject *lastItem = nullptr;
if (iter.second->isEnabled()) {
lastItem = iter.second->takeLast();
if (lastItem->Init()) {
lastItem->Render();
}
}
while (!iter.second->isEmpty()) {
delete iter.second->takeFirst();
}
if (lastItem) {
iter.second->append(lastItem);
}
}
}
}
}
void SceneViewer::ChangeCameraType(int index) {
if (index < TARGET || index > FREE) {
return;
}
if (index == FREE) {
current_cameraPtr_ = &free_camera_;
} else {
current_cameraPtr_ = &target_camera_;
}
ResetCameraPosAttitude();
}
void SceneViewer::ResetCameraPosAttitude(void) {
free_camera_.set_position(0.0f, 48.0f, -48.0f);
free_camera_.SetAttitude(0.0f, 45.0f, 0.0f);
target_camera_.set_position(-21.0f, 21.0f, 0.0f);
target_camera_.Rotate(-45.0f, -90.0f, 0.0f);
target_camera_.set_target_pos(0.0f, 0.0f, 0.0f);
emit CameraPosChanged(current_cameraPtr_->position());
emit CameraAttitudeChanged(current_cameraPtr_->attitude());
UpdateCameraWorld();
}
void SceneViewer::UpdateCameraX(double x) {
free_camera_.set_x(static_cast<float>(x));
target_camera_.set_x(static_cast<float>(x));
UpdateCameraWorld();
}
void SceneViewer::UpdateCameraY(double y) {
free_camera_.set_y(static_cast<float>(y));
target_camera_.set_y(static_cast<float>(y));
UpdateCameraWorld();
}
void SceneViewer::UpdateCameraZ(double z) {
free_camera_.set_z(static_cast<float>(z));
target_camera_.set_y(static_cast<float>(z));
UpdateCameraWorld();
}
void SceneViewer::UpdateCameraYaw(double yawInDegrees) {
if (yawInDegrees > 360.0) {
yawInDegrees -= 360.0;
}
if (yawInDegrees < -360.0) {
yawInDegrees += 360.0;
}
free_camera_.set_yaw(static_cast<float>(yawInDegrees));
target_camera_.set_yaw(static_cast<float>(yawInDegrees));
UpdateCameraWorld();
}
void SceneViewer::UpdateCameraPitch(double pitchInDegrees) {
if (pitchInDegrees > 90.0) {
pitchInDegrees = 90.0;
}
if (pitchInDegrees < -90.0) {
pitchInDegrees = -90.0;
}
free_camera_.set_pitch(static_cast<float>(pitchInDegrees));
target_camera_.set_pitch(static_cast<float>(pitchInDegrees));
UpdateCameraWorld();
}
void SceneViewer::UpdateCameraRoll(double rollInDegrees) {
if (rollInDegrees > 360.0) {
rollInDegrees -= 360.0;
}
if (rollInDegrees < -360.0) {
rollInDegrees += 360.0;
}
free_camera_.set_roll(static_cast<float>(rollInDegrees));
free_camera_.set_roll(static_cast<float>(rollInDegrees));
UpdateCameraWorld();
}
void SceneViewer::UpdateCameraWorld(void) {
free_camera_.UpdateWorld();
target_camera_.UpdateWorld();
QMatrix4x4 mvp = current_cameraPtr_->projection_matrix() *
current_cameraPtr_->model_view_matrix();
UpdateAllShaderProgMVP(mvp);
update();
}
void SceneViewer::UpdateAllShaderProgMVP(const QMatrix4x4 &mvp) {
for (auto iter = managed_shader_prog_.begin();
iter != managed_shader_prog_.end(); ++iter) {
iter->second->bind();
iter->second->setUniformValue("mvp", mvp);
iter->second->release();
}
}
void SceneViewer::enterEvent(QEvent *event) {
setCursor(Qt::SizeAllCursor);
QOpenGLWidget::enterEvent(event);
}
void SceneViewer::leaveEvent(QEvent *event) {
unsetCursor();
QOpenGLWidget::leaveEvent(event);
}
void SceneViewer::mousePressEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton) {
left_key_last_pos_ = QCursor::pos();
} else if (event->button() == Qt::RightButton) {
right_key_is_moved_ = false;
right_key_last_y_ = static_cast<float>(QCursor::pos().y());
}
QOpenGLWidget::mousePressEvent(event);
}
void SceneViewer::mouseMoveEvent(QMouseEvent *mouseEvent) {
if (mouseEvent->buttons() == Qt::LeftButton) {
QPoint tmp = QCursor::pos();
QPoint dd = tmp - left_key_last_pos_;
left_key_last_pos_ = tmp;
float x = static_cast<float>(dd.x()) * sensitivity();
float y = static_cast<float>(dd.y()) * sensitivity();
if (IsFreeCamera()) {
free_camera_.Starfe(-x);
free_camera_.Lift(y);
emit CameraPosChanged(free_camera_.position());
} else {
x = target_camera_.yaw() - x;
y = target_camera_.pitch() - y;
if (x > 360.0f) {
x -= 360.0f;
}
if (x < -360.0f) {
x += 360.0f;
}
if (y > 90.0f) {
y = 90.0f;
}
if (y < -90.0f) {
y = 90.0f;
}
target_camera_.set_yaw(x);
target_camera_.set_pitch(y);
emit CameraAttitudeChanged(target_camera_.attitude());
}
goto _label1;
} else if (mouseEvent->buttons() == Qt::RightButton) {
right_key_is_moved_ = true;
if (IsFreeCamera()) {
{
float tmp = static_cast<float>(QCursor::pos().y());
float dd = right_key_last_y_ - tmp;
right_key_last_y_ = tmp;
float z = dd * sensitivity();
free_camera_.Walk(z);
emit CameraPosChanged(free_camera_.position());
}
_label1:
UpdateCameraWorld();
update();
}
}
QOpenGLWidget::mousePressEvent(mouseEvent);
}
void SceneViewer::wheelEvent(QWheelEvent *event) {
float delta = static_cast<float>(event->angleDelta().y());
delta *= sensitivity();
target_camera_.set_distance(target_camera_.distance() + delta);
delta += free_camera_.pitch();
if (delta > 90.0f) {
delta = 90.0f;
}
if (delta < -90.0f) {
delta = -90.0f;
}
free_camera_.set_pitch(delta);
if (IsFreeCamera()) {
emit CameraAttitudeChanged(free_camera_.attitude());
} else {
emit CameraPosChanged(target_camera_.position());
}
UpdateCameraWorld();
update();
QOpenGLWidget::wheelEvent(event);
}
void SceneViewer::mouseReleaseEvent(QMouseEvent *event) {
if (!right_key_is_moved_ && event->button() == Qt::RightButton) {
if (camera_dialog_ == nullptr) {
camera_dialog_ = new SceneCameraDialog(this);
if (!camera_dialog_) {
QMessageBox::warning(this, tr("Error"),
tr("No Enough for creating Camera Dialog!!!"),
QMessageBox::Ok);
goto retLabel;
} else {
connect(camera_dialog_, SIGNAL(resetcamera()), this,
SLOT(ResetCameraPosAttitude()));
connect(camera_dialog_, SIGNAL(xValueChanged(double)), this,
SLOT(UpdateCameraX(double)));
connect(camera_dialog_, SIGNAL(yValueChanged(double)), this,
SLOT(UpdateCameraY(double)));
connect(camera_dialog_, SIGNAL(zValueChanged(double)), this,
SLOT(UpdateCameraZ(double)));
connect(camera_dialog_, SIGNAL(yawValueChanged(double)), this,
SLOT(UpdateCameraYaw(double)));
connect(camera_dialog_, SIGNAL(pitchValueChanged(double)), this,
SLOT(UpdateCameraPitch(double)));
connect(camera_dialog_, SIGNAL(rollValueChanged(double)), this,
SLOT(UpdateCameraRoll(double)));
connect(camera_dialog_, SIGNAL(cameraTypeChanged(int)), this,
SLOT(ChangeCameraType(int)));
connect(camera_dialog_, SIGNAL(sensitivityChanged(float)), this,
SLOT(set_sensitivity(float)));
connect(this, SIGNAL(CameraAttitudeChanged(QVector3D)), camera_dialog_,
SLOT(updateCameraAttitude(QVector3D)));
connect(this, SIGNAL(CameraPosChanged(QVector3D)), camera_dialog_,
SLOT(updateCameraPos(QVector3D)));
}
}
camera_dialog_->updateCameraPos(current_cameraPtr_->position());
camera_dialog_->updateCameraAttitude(current_cameraPtr_->attitude());
camera_dialog_->move(event->globalPos());
camera_dialog_->show();
}
retLabel:
QOpenGLWidget::mouseReleaseEvent(event);
}
| 0
|
apollo_public_repos/apollo/modules/tools/visualizer
|
apollo_public_repos/apollo/modules/tools/visualizer/shaders/grid.vert
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#version 330 core
layout(location = 0) in vec2 vertPos;
uniform mat4 mvp;
uniform vec3 color;
out vec3 Color;
void main(void)
{
gl_Position = mvp * vec4(vertPos.x, 0.0, vertPos.y, 1.0);
Color = color;
}
| 0
|
apollo_public_repos/apollo/modules/tools/visualizer
|
apollo_public_repos/apollo/modules/tools/visualizer/shaders/video_image_plane.frag
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#version 330 core
in vec2 TexCoord;
out vec4 FragColor;
uniform sampler2D texture;
void main(void) {
FragColor = texture2D(texture, TexCoord);
}
| 0
|
apollo_public_repos/apollo/modules/tools/visualizer
|
apollo_public_repos/apollo/modules/tools/visualizer/shaders/grid_pointcloud.frag
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#version 330 core
in vec3 Color;
out vec4 FragColor;
void main(void)
{
FragColor = vec4(Color, 1.0);
}
| 0
|
apollo_public_repos/apollo/modules/tools/visualizer
|
apollo_public_repos/apollo/modules/tools/visualizer/shaders/radarpoints.frag
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#version 330 core
in vec3 Color;
out vec4 FragColor;
void main(void)
{
FragColor = vec4(Color, 1.0);
}
| 0
|
apollo_public_repos/apollo/modules/tools/visualizer
|
apollo_public_repos/apollo/modules/tools/visualizer/shaders/video_image_plane.vert
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#version 330 core
layout(location = 0) in vec2 vertPos;
layout(location = 1) in vec2 texCoord;
out vec2 TexCoord;
void main(void)
{
gl_Position = vec4(vertPos.x, vertPos.y, 0.0, 1.0);
TexCoord = vec2(texCoord.x, 1.0 - texCoord.y);
}
| 0
|
apollo_public_repos/apollo/modules/tools/visualizer
|
apollo_public_repos/apollo/modules/tools/visualizer/shaders/radarpoints.vert
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#version 330 core
layout(location = 0) in vec3 vertPos;
uniform mat4 mvp;
uniform vec3 color;
out vec3 Color;
void main(void)
{
gl_Position = mvp * vec4(vertPos.x, 0.0, vertPos.y, 1.0);
gl_PointSize = 2.8f;
Color = color;
}
| 0
|
apollo_public_repos/apollo/modules/tools/visualizer
|
apollo_public_repos/apollo/modules/tools/visualizer/shaders/pointcloud.vert
|
/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
#version 330 core
layout(location = 0) in vec4 vertPos;
uniform mat4 mvp;
out vec3 Color;
void main(void)
{
gl_Position = mvp * vec4(vertPos.xyz, 1.0);
float g = smoothstep(0.0, 256, vertPos.w);
float r = 0.0;
float b = 0.0;
if(g <= 0.25)
{
r = g * 4.0;
g = 0.0;
}
if(g > 0.75)
{
g = 0.0;
b = g * 4.0 - 3.0; // b = g;
}
else
{
// g = g + 0.25;
// g = g + 0.45;
g = g + 0.35;
}
Color = vec3(r,g,b);
}
| 0
|
apollo_public_repos/apollo/modules/tools/visualizer
|
apollo_public_repos/apollo/modules/tools/visualizer/uis/main_window.ui
|
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1139</width>
<height>754</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>CyberVisualizer</string>
</property>
<property name="windowIcon">
<iconset resource="../res.qrc">
<normaloff>:/images/app.ico</normaloff>:/images/app.ico</iconset>
</property>
<widget class="QWidget" name="centralWidget">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>100</width>
<height>100</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QSplitter" name="vSplitter">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<widget class="TreeWidget" name="treeWidget">
<property name="enabled">
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>320</width>
<height>16777215</height>
</size>
</property>
<property name="verticalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
<property name="horizontalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
<property name="sizeAdjustPolicy">
<enum>QAbstractScrollArea::AdjustIgnored</enum>
</property>
<property name="autoScroll">
<bool>false</bool>
</property>
<property name="horizontalScrollMode">
<enum>QAbstractItemView::ScrollPerItem</enum>
</property>
<column>
<property name="text">
<string>Title</string>
</property>
</column>
<column>
<property name="text">
<string>Description</string>
</property>
</column>
</widget>
<widget class="QSplitter" name="hSplitter">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<widget class="SceneViewer" name="sceneWidget" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
<widget class="QWidget" name="videoImageWidget" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<layout class="QGridLayout" name="videoImageGridLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
</layout>
</widget>
</widget>
</widget>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menuBar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1139</width>
<height>25</height>
</rect>
</property>
<widget class="QMenu" name="menuFile">
<property name="title">
<string>File</string>
</property>
<addaction name="actionGlobal"/>
<addaction name="separator"/>
<addaction name="actionAddGrid"/>
<addaction name="actionPointCloud"/>
<addaction name="separator"/>
<addaction name="actionExit"/>
</widget>
<widget class="QMenu" name="menuHelp">
<property name="title">
<string>Help</string>
</property>
<addaction name="actionLicense"/>
<addaction name="actionAbout"/>
</widget>
<widget class="QMenu" name="menuView">
<property name="title">
<string>View</string>
</property>
<addaction name="actionOpenImage"/>
<addaction name="actionOpenImages"/>
<addaction name="actionDelImage"/>
<!-- <addaction name="separator"/>
<addaction name="actionRadar"/> -->
</widget>
<widget class="QMenu" name="menuActions">
<property name="title">
<string>Actions</string>
</property>
<addaction name="actionPlay"/>
<addaction name="actionPause"/>
</widget>
<addaction name="menuFile"/>
<addaction name="menuView"/>
<addaction name="menuActions"/>
<addaction name="menuHelp"/>
</widget>
<widget class="QToolBar" name="mainToolBar">
<property name="movable">
<bool>false</bool>
</property>
<property name="toolButtonStyle">
<enum>Qt::ToolButtonTextBesideIcon</enum>
</property>
<property name="floatable">
<bool>false</bool>
</property>
<attribute name="toolBarArea">
<enum>TopToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
</widget>
<action name="actionExit">
<property name="text">
<string>Exit</string>
</property>
<property name="shortcut">
<string>F10</string>
</property>
</action>
<action name="actionAbout">
<property name="text">
<string>About</string>
</property>
</action>
<action name="actionPointCloud">
<property name="icon">
<iconset resource="../res.qrc">
<normaloff>:/images/pointcloud.png</normaloff>:/images/pointcloud.png</iconset>
</property>
<property name="text">
<string>Show PointCloud</string>
</property>
<property name="shortcut">
<string>F4</string>
</property>
</action>
<action name="actionGlobal">
<property name="checkable">
<bool>true</bool>
</property>
<property name="checked">
<bool>true</bool>
</property>
<property name="text">
<string>Global</string>
</property>
<property name="shortcut">
<string>F2</string>
</property>
</action>
<action name="actionDelImage">
<property name="enabled">
<bool>false</bool>
</property>
<property name="icon">
<iconset resource="../res.qrc">
<normaloff>:/images/closeimage.png</normaloff>:/images/closeimage.png</iconset>
</property>
<property name="text">
<string>Del Image</string>
</property>
<property name="shortcut">
<string>F7</string>
</property>
</action>
<action name="actionAddGrid">
<property name="icon">
<iconset resource="../res.qrc">
<normaloff>:/images/grid.png</normaloff>:/images/grid.png</iconset>
</property>
<property name="text">
<string>Show Grid</string>
</property>
<property name="shortcut">
<string>F3</string>
</property>
</action>
<action name="actionOpenImages">
<property name="icon">
<iconset resource="../res.qrc">
<normaloff>:/images/images.png</normaloff>:/images/images.png</iconset>
</property>
<property name="text">
<string>Add Images</string>
</property>
<property name="shortcut">
<string>F6</string>
</property>
</action>
<action name="actionOpenImage">
<property name="icon">
<iconset resource="../res.qrc">
<normaloff>:/images/image.png</normaloff>:/images/image.png</iconset>
</property>
<property name="text">
<string>Add Image</string>
</property>
<property name="shortcut">
<string>F5</string>
</property>
</action>
<action name="actionLicense">
<property name="text">
<string>License</string>
</property>
</action>
<action name="actionPlay">
<property name="icon">
<iconset resource="../res.qrc">
<normaloff>:/images/play.png</normaloff>:/images/play.png</iconset>
</property>
<property name="text">
<string>Play</string>
</property>
<property name="shortcut">
<string>F8</string>
</property>
</action>
<action name="actionPause">
<property name="enabled">
<bool>true</bool>
</property>
<property name="icon">
<iconset resource="../res.qrc">
<normaloff>:/images/pause.png</normaloff>:/images/pause.png</iconset>
</property>
<property name="text">
<string>Pause</string>
</property>
<property name="shortcut">
<string>F9</string>
</property>
</action>
<!-- <action name="actionRadar">
<property name="text">
<string>Radar</string>
</property>
</action> -->
</widget>
<layoutdefault spacing="6" margin="11"/>
<customwidgets>
<customwidget>
<class>SceneViewer</class>
<extends>QWidget</extends>
<header>scene_viewer.h</header>
<container>1</container>
<slots>
<slot>ChangeCameraType(int)</slot>
<slot>ResetCameraPosAttitude()</slot>
</slots>
</customwidget>
<customwidget>
<class>TreeWidget</class>
<extends>QTreeWidget</extends>
<header location="global">treewidget.h</header>
</customwidget>
</customwidgets>
<resources>
<include location="../res.qrc"/>
</resources>
<connections>
<connection>
<sender>actionExit</sender>
<signal>triggered()</signal>
<receiver>MainWindow</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>-1</x>
<y>-1</y>
</hint>
<hint type="destinationlabel">
<x>199</x>
<y>149</y>
</hint>
</hints>
</connection>
<connection>
<sender>actionOpenImage</sender>
<signal>triggered()</signal>
<receiver>MainWindow</receiver>
<slot>ActionOpenImage()</slot>
<hints>
<hint type="sourcelabel">
<x>-1</x>
<y>-1</y>
</hint>
<hint type="destinationlabel">
<x>579</x>
<y>409</y>
</hint>
</hints>
</connection>
<connection>
<sender>actionPointCloud</sender>
<signal>triggered()</signal>
<receiver>MainWindow</receiver>
<slot>ActionOpenPointCloud()</slot>
<hints>
<hint type="sourcelabel">
<x>-1</x>
<y>-1</y>
</hint>
<hint type="destinationlabel">
<x>579</x>
<y>409</y>
</hint>
</hints>
</connection>
<connection>
<sender>actionDelImage</sender>
<signal>triggered()</signal>
<receiver>MainWindow</receiver>
<slot>ActionDelVideoImage()</slot>
<hints>
<hint type="sourcelabel">
<x>-1</x>
<y>-1</y>
</hint>
<hint type="destinationlabel">
<x>423</x>
<y>350</y>
</hint>
</hints>
</connection>
<connection>
<sender>actionAddGrid</sender>
<signal>triggered()</signal>
<receiver>MainWindow</receiver>
<slot>ActionAddGrid()</slot>
<hints>
<hint type="sourcelabel">
<x>-1</x>
<y>-1</y>
</hint>
<hint type="destinationlabel">
<x>423</x>
<y>350</y>
</hint>
</hints>
</connection>
<connection>
<sender>actionOpenImages</sender>
<signal>triggered()</signal>
<receiver>MainWindow</receiver>
<slot>ActionOpenImages()</slot>
<hints>
<hint type="sourcelabel">
<x>-1</x>
<y>-1</y>
</hint>
<hint type="destinationlabel">
<x>471</x>
<y>379</y>
</hint>
</hints>
</connection>
<connection>
<sender>actionDelImage</sender>
<signal>toggled(bool)</signal>
<receiver>MainWindow</receiver>
<slot>CloseVideoImgViewer(bool)</slot>
<hints>
<hint type="sourcelabel">
<x>-1</x>
<y>-1</y>
</hint>
<hint type="destinationlabel">
<x>489</x>
<y>400</y>
</hint>
</hints>
</connection>
<connection>
<sender>actionGlobal</sender>
<signal>triggered(bool)</signal>
<receiver>treeWidget</receiver>
<slot>setVisible(bool)</slot>
<hints>
<hint type="sourcelabel">
<x>-1</x>
<y>-1</y>
</hint>
<hint type="destinationlabel">
<x>148</x>
<y>413</y>
</hint>
</hints>
</connection>
<!-- <connection>
<sender>actionRadar</sender>
<signal>triggered()</signal>
<receiver>MainWindow</receiver>
<slot>ActionOpenRadarChannel()</slot>
<hints>
<hint type="sourcelabel">
<x>-1</x>
<y>-1</y>
</hint>
<hint type="destinationlabel">
<x>569</x>
<y>376</y>
</hint>
</hints>
</connection> -->
</connections>
<slots>
<slot>ActionOpenImage()</slot>
<slot>ActionOpenPointCloud()</slot>
<slot>ActionDelVideoImage()</slot>
<slot>ActionAddGrid()</slot>
<slot>ActionOpenImages()</slot>
<slot>CloseVideoImgViewer(bool)</slot>
<!-- <slot>ActionOpenRadarChannel()</slot> -->
</slots>
</ui>
| 0
|
apollo_public_repos/apollo/modules/tools/visualizer
|
apollo_public_repos/apollo/modules/tools/visualizer/uis/video_images_dialog.ui
|
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>VideoImagesDialog</class>
<widget class="QDialog" name="VideoImagesDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>194</width>
<height>78</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>194</width>
<height>78</height>
</size>
</property>
<property name="windowTitle">
<string>Video Image Count Dialog</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>Count:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QSpinBox" name="spinBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimum">
<number>1</number>
</property>
<property name="maximum">
<number>10</number>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QPushButton" name="cancelPushButton">
<property name="text">
<string>&Cancel</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QPushButton" name="okPushButton">
<property name="text">
<string>&Ok</string>
</property>
<property name="checkable">
<bool>false</bool>
</property>
<property name="checked">
<bool>false</bool>
</property>
<property name="default">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>cancelPushButton</sender>
<signal>clicked()</signal>
<receiver>VideoImagesDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>72</x>
<y>71</y>
</hint>
<hint type="destinationlabel">
<x>141</x>
<y>8</y>
</hint>
</hints>
</connection>
<connection>
<sender>okPushButton</sender>
<signal>clicked()</signal>
<receiver>VideoImagesDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>171</x>
<y>71</y>
</hint>
<hint type="destinationlabel">
<x>219</x>
<y>36</y>
</hint>
</hints>
</connection>
</connections>
</ui>
| 0
|
apollo_public_repos/apollo/modules/tools/visualizer
|
apollo_public_repos/apollo/modules/tools/visualizer/uis/msg_dialog.ui
|
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MessageDialog</class>
<widget class="QDialog" name="MessageDialog">
<property name="windowModality">
<enum>Qt::ApplicationModal</enum>
</property>
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>438</width>
<height>172</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="msgLabel">
<property name="text">
<string>CyberVisualizer
One Visualization Tool for Presenting Cyber Channel Data
F5 Play | Pause
Main View PointCloud view
Other Views have right button Menu</string>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="closePushButton">
<property name="text">
<string>close</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>closePushButton</sender>
<signal>clicked()</signal>
<receiver>MessageDialog</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>416</x>
<y>232</y>
</hint>
<hint type="destinationlabel">
<x>456</x>
<y>250</y>
</hint>
</hints>
</connection>
</connections>
</ui>
| 0
|
apollo_public_repos/apollo/modules/tools/visualizer
|
apollo_public_repos/apollo/modules/tools/visualizer/uis/scene_camera_dialog.ui
|
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SceneCameraDialog</class>
<widget class="QDialog" name="SceneCameraDialog">
<property name="windowModality">
<enum>Qt::NonModal</enum>
</property>
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>287</width>
<height>214</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>287</width>
<height>214</height>
</size>
</property>
<property name="contextMenuPolicy">
<enum>Qt::DefaultContextMenu</enum>
</property>
<property name="windowTitle">
<string>SceneCamera</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>Type</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="0" column="1" colspan="2">
<widget class="QComboBox" name="cameraTypeComboBox">
<property name="maxVisibleItems">
<number>5</number>
</property>
<property name="maxCount">
<number>5</number>
</property>
<property name="frame">
<bool>true</bool>
</property>
<item>
<property name="text">
<string>Target</string>
</property>
</item>
<item>
<property name="text">
<string>FREE</string>
</property>
</item>
</widget>
</item>
<item row="0" column="3">
<widget class="QLabel" name="label_5">
<property name="text">
<string>Step</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="0" column="5">
<widget class="QSlider" name="stepSlider">
<property name="minimum">
<number>1</number>
</property>
<property name="maximum">
<number>100</number>
</property>
<property name="singleStep">
<number>1</number>
</property>
<property name="pageStep">
<number>5</number>
</property>
<property name="value">
<number>8</number>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>X:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="1" column="1" colspan="2">
<widget class="QDoubleSpinBox" name="cameraX">
<property name="minimum">
<double>-1000.000000000000000</double>
</property>
<property name="maximum">
<double>1000.000000000000000</double>
</property>
<property name="value">
<double>0.000000000000000</double>
</property>
</widget>
</item>
<item row="1" column="3">
<widget class="QLabel" name="label_3">
<property name="text">
<string>Y:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="1" column="5">
<widget class="QDoubleSpinBox" name="cameraY">
<property name="minimum">
<double>-1000.000000000000000</double>
</property>
<property name="maximum">
<double>1000.000000000000000</double>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="label_4">
<property name="text">
<string>Z:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="2" column="1" colspan="2">
<widget class="QDoubleSpinBox" name="cameraZ">
<property name="minimum">
<double>-1000.000000000000000</double>
</property>
<property name="maximum">
<double>1000.000000000000000</double>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="label_6">
<property name="text">
<string>Yaw:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="3" column="1" colspan="2">
<widget class="QDoubleSpinBox" name="cameraYaw">
<property name="decimals">
<number>3</number>
</property>
<property name="minimum">
<double>-360.000000000000000</double>
</property>
<property name="maximum">
<double>360.000000000000000</double>
</property>
<property name="singleStep">
<double>0.050000000000000</double>
</property>
</widget>
</item>
<item row="3" column="3" colspan="2">
<widget class="QLabel" name="label_7">
<property name="text">
<string>Pitch:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="3" column="5">
<widget class="QDoubleSpinBox" name="cameraPitch">
<property name="decimals">
<number>3</number>
</property>
<property name="minimum">
<double>-90.000000000000000</double>
</property>
<property name="maximum">
<double>90.000000000000000</double>
</property>
<property name="singleStep">
<double>0.050000000000000</double>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="label_8">
<property name="text">
<string>Roll:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="4" column="1" colspan="2">
<widget class="QDoubleSpinBox" name="cameraRoll">
<property name="enabled">
<bool>false</bool>
</property>
<property name="decimals">
<number>3</number>
</property>
<property name="minimum">
<double>-90.000000000000000</double>
</property>
<property name="maximum">
<double>90.000000000000000</double>
</property>
<property name="singleStep">
<double>0.050000000000000</double>
</property>
<property name="value">
<double>0.000000000000000</double>
</property>
</widget>
</item>
<item row="5" column="0" colspan="2">
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>36</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="5" column="2">
<widget class="QPushButton" name="resetButton">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>&Reset</string>
</property>
</widget>
</item>
<item row="5" column="3">
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>29</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="5" column="4" colspan="2">
<widget class="QPushButton" name="okButton">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>&Ok</string>
</property>
<property name="default">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>okButton</sender>
<signal>clicked()</signal>
<receiver>SceneCameraDialog</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>210</x>
<y>192</y>
</hint>
<hint type="destinationlabel">
<x>188</x>
<y>210</y>
</hint>
</hints>
</connection>
</connections>
<slots>
<signal>resetcamera()</signal>
</slots>
</ui>
| 0
|
apollo_public_repos/apollo/modules
|
apollo_public_repos/apollo/modules/monitor/cyberfile.xml
|
<package format="2">
<name>monitor</name>
<version>local</version>
<description>
This module contains system level software such as code to check hardware status
and monitor system health.
</description>
<maintainer email="apollo-support@baidu.com">Apollo</maintainer>
<license>Apache License 2.0</license>
<url type="website">https://www.apollo.auto/</url>
<url type="repository">https://github.com/ApolloAuto/apollo</url>
<url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url>
<type>module</type>
<depend type="binary" repo_name="cyber">cyber-dev</depend>
<depend type="binary" repo_name="common" lib_names="common">common-dev</depend>
<depend repo_name="common-msgs" lib_names="common-msgs">common-msgs-dev</depend>
<depend repo_name="com_github_gflags_gflags" lib_names="gflags">3rd-gflags-dev</depend>
<depend repo_name="com_google_googletest" lib_names="gtest,gtest_main">3rd-gtest-dev</depend>
<depend repo_name="com_google_absl" lib_names="absl">3rd-absl-dev</depend>
<depend repo_name="com_github_google_glog" lib_names="glog">3rd-glog-dev</depend>
<depend type="binary" repo_name="dreamview" lib_names="dreamview">dreamview-dev</depend>
<depend lib_names="protobuf" repo_name="com_google_protobuf">3rd-protobuf-dev</depend>
<src_path url="https://github.com/ApolloAuto/apollo">//modules/monitor</src_path>
</package>
| 0
|
apollo_public_repos/apollo/modules
|
apollo_public_repos/apollo/modules/monitor/README.md
|
# Monitor
## Introduction
This module contains system level software such as code to check hardware status
and monitor system health.
In Apollo 5.5, the monitor module now performs the following checks among others:
1. Status of running modules
2. Monitoring data integrity
3. Monitoring data frequency
4. Monitoring system health (e.g. CPU, memory, disk usage, etc)
5. Generating end-to-end latency stats report
```
Note: You can configure the modules that you would like to monitor for the first 3 capabilities mentioned above.
```
## Hardware Monitors
Hardware related monitoring, e.g. CAN card / GPS status health check. Check
results are reported back to HMI.
## Software Monitors
### Process Monitor
It checks if a process is running or not. Config it with
apollo::monitor::ProcessConf proto, which works similar to
```bash
ps aux | grep <keyword1> | grep <keyword2> | ...
```
### Topic Monitor
It checks if a given topic is updated normally. Config it with
apollo::monitor::TopicConf proto.
### Summary Monitor
It summarizes all other specific monitor's results to a simple conclusion such
as OK, WARN, ERROR or FATAL.
| 0
|
apollo_public_repos/apollo/modules
|
apollo_public_repos/apollo/modules/monitor/monitor.h
|
/******************************************************************************
* 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.
*****************************************************************************/
#pragma once
#include <memory>
#include <vector>
#include "cyber/component/timer_component.h"
#include "cyber/cyber.h"
#include "modules/monitor/common/recurrent_runner.h"
/**
* @namespace apollo::monitor
* @brief apollo::monitor
*/
namespace apollo {
namespace monitor {
class Monitor : public apollo::cyber::TimerComponent {
public:
bool Init() override;
bool Proc() override;
private:
std::vector<std::shared_ptr<RecurrentRunner>> runners_;
};
CYBER_REGISTER_COMPONENT(Monitor)
} // namespace monitor
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules
|
apollo_public_repos/apollo/modules/monitor/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library")
load("//tools/install:install.bzl", "install", "install_src_files")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
MONITOR_COPTS = ['-DMODULE_NAME=\\"monitor\\"']
cc_binary(
name = "libmonitor.so",
linkshared = True,
linkstatic = True,
deps = [
":monitor_lib",
],
)
cc_library(
name = "monitor_lib",
srcs = ["monitor.cc"],
hdrs = ["monitor.h"],
copts = MONITOR_COPTS,
visibility = ["//visibility:private"],
deps = [
"//cyber",
"//modules/common/util:util_tool",
"//modules/monitor/common:recurrent_runner",
"//modules/monitor/hardware:esdcan_monitor",
"//modules/monitor/hardware:gps_monitor",
"//modules/monitor/hardware:resource_monitor",
"//modules/monitor/hardware:socket_can_monitor",
"//modules/monitor/software:camera_monitor",
"//modules/monitor/software:channel_monitor",
"//modules/monitor/software:functional_safety_monitor",
"//modules/monitor/software:latency_monitor",
"//modules/monitor/software:localization_monitor",
"//modules/monitor/software:module_monitor",
"//modules/monitor/software:process_monitor",
"//modules/monitor/software:recorder_monitor",
"//modules/monitor/software:summary_monitor",
],
alwayslink = True,
)
filegroup(
name = "runtime_data",
srcs = glob([
"dag/*.dag",
"launch/*.launch",
]),
)
install(
name = "install",
library_dest = "monitor/lib",
data_dest = "monitor",
targets = [
":libmonitor.so",
],
data = [
":runtime_data",
":cyberfile.xml",
":monitor.BUILD",
],
)
install_src_files(
name = "install_src",
deps = [
":install_monitor_src",
":install_monitor_hdrs"
],
)
install_src_files(
name = "install_monitor_src",
src_dir = ["."],
dest = "monitor/src",
filter = "*",
)
install_src_files(
name = "install_monitor_hdrs",
src_dir = ["."],
dest = "monitor/include",
filter = "*.h",
)
cpplint()
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.