Skip to content

Instantly share code, notes, and snippets.

@jonasbark
Last active March 31, 2022 16:00
Show Gist options
  • Save jonasbark/85e2bd34cfeacabecdd32e09c4b2232f to your computer and use it in GitHub Desktop.
Save jonasbark/85e2bd34cfeacabecdd32e09c4b2232f to your computer and use it in GitHub Desktop.
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:convert';
import 'dart:typed_data';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Offset convertMapToPixelSystem(Offset point, ProscenicMap proscenicMap) {
final world = convertMapToWorldSystem(point, proscenicMap);
final map_x = (world.dx - proscenicMap.data!.xmin) / proscenicMap.data!.resolution;
final map_y = (world.dy - proscenicMap.data!.ymin) / proscenicMap.data!.resolution;
return Offset(map_x, map_y);
}
// official
Offset convertMapToWorldSystem(Offset point, ProscenicMap proscenicMap) {
final x = point.dx * proscenicMap.data!.resolution + proscenicMap.data!.xmin;
final y = point.dy * proscenicMap.data!.resolution + proscenicMap.data!.ymin;
return Offset(x, y);
}
void main() async {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Proscenic Map Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Test'),
),
body: Center(
child: FutureBuilder<String>(
future: http.read(Uri.parse(
'https://gist.githubusercontent.com/jonasbark/ff4f8d66ac4e30d3e5560896cfbc6dc6/raw/6cac80a3c91806d6a7aa8f11564c21992e6630f0/map.json')),
builder: (context, snapshot) {
if (snapshot.hasData) {
final map = ProscenicMap.fromJson(jsonDecode(snapshot.data!));
return ProscenicMapView(
proscenicMap: map,
height: map.data!.height.toDouble(),
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
} else {
return const CircularProgressIndicator();
}
}),
),
),
);
}
}
class ProscenicMapView extends StatelessWidget {
final ProscenicMap? proscenicMap;
final double height;
ProscenicMapView({
Key? key,
required this.proscenicMap,
required this.height,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
height: height,
child: Builder(
builder: (context) {
final firstMap = proscenicMap!.data!;
final resolution = firstMap.resolution;
final decoded = base64Decode(firstMap.map);
final pixelsByRow = List.generate(
firstMap.height, (index) => decoded.sublist(index * firstMap.width, (index + 1) * firstMap.width));
final List<Offset> walls = [];
final List<Offset> noclue = [];
final List<Offset> unknown = [];
final Map<int, List<Offset>> partitions = {};
for (int y = 0; y < pixelsByRow.length; y++) {
final row = pixelsByRow[y];
for (int x = 0; x < row.length; x++) {
final pixel = row[x];
switch (pixel) {
case 127: // 127: Unknown District City
unknown.add(Offset(x.toDouble(), y.toDouble()));
break;
case 255: // Jidancheng District
noclue.add(Offset(x.toDouble(), y.toDouble()));
break;
case 0: // unknown
walls.add(Offset(x.toDouble(), y.toDouble()));
break;
default:
(partitions[pixel] ??= []).add(Offset(x.toDouble(), y.toDouble()));
break;
}
}
}
return Container(
height: height,
width: height,
child: CustomPaint(
size: Size(height, height),
painter: _MapPainter(
context: context,
proscenicMap: proscenicMap!,
walls: walls,
outside: unknown,
noclue: noclue,
decodedMap: decoded,
partitions: partitions,
bounds: Rect.fromPoints(Offset.zero, Offset(firstMap.width.toDouble(), firstMap.height.toDouble())),
),
),
);
},
),
);
}
}
class _MapPainter extends CustomPainter {
final ProscenicMap proscenicMap;
final Rect bounds;
final Uint8List decodedMap;
final BuildContext context;
final List<Offset> walls;
final List<Offset> outside;
final List<Offset> noclue;
final Map<int, List<Offset>> partitions;
_MapPainter({
required this.proscenicMap,
required this.decodedMap,
required this.bounds,
required this.walls,
required this.outside,
required this.noclue,
required this.partitions,
required this.context,
});
@override
void paint(Canvas canvas, Size size) {
if (walls.isNotEmpty) {
canvas.drawPoints(
PointMode.points,
walls,
Paint()
..color = Colors.black54
..strokeWidth = 1,
);
}
if (noclue.isNotEmpty) {
canvas.drawPoints(
PointMode.points,
noclue,
Paint()
..color = Colors.black
..strokeWidth = 1,
);
}
canvas.drawPoints(
PointMode.points,
outside,
Paint()
..color = Colors.black12
..strokeWidth = 1,
);
if (partitions.isNotEmpty) {
partitions.forEach((key, value) {
final regions = proscenicMap.data!.autoAreaValue?.where((element) => element.id == key);
final region = regions?.isNotEmpty == true ? regions!.first : null;
canvas.drawPoints(
PointMode.points,
value,
Paint()
..color = colorFromText(key.toString())
..strokeWidth = 1,
);
if (region != null) {
final points = value;
final path = Path()..addPolygon(points, true);
final TextPainter textPainter = TextPainter(
text: TextSpan(
text: region.name,
style: TextStyle(
color: Colors.black87,
fontSize: 8,
),
),
textAlign: TextAlign.center,
textDirection: TextDirection.ltr)
..layout(maxWidth: 60);
final center = path.getBounds().center;
final rrect = RRect.fromRectAndRadius(
Rect.fromCenter(center: center, width: textPainter.width + 5, height: textPainter.height + 3),
Radius.circular(4),
);
canvas.drawRRect(
rrect,
Paint()..color = Colors.white,
);
canvas.drawRRect(
rrect,
Paint()
..color = Colors.black26
..strokeWidth = 1
..style = PaintingStyle.stroke,
);
textPainter.paint(
canvas,
center.translate(-textPainter.width / 2, -textPainter.height / 2),
);
}
});
}
// charger location
canvas.drawCircle(
convertMapToPixelSystem(
Offset(proscenicMap.data!.chargeHandlePos[0].toDouble(), proscenicMap.data!.chargeHandlePos[1].toDouble()),
proscenicMap),
5,
Paint()
..style = PaintingStyle.fill
..color = Colors.redAccent
..strokeWidth = 1);
if (proscenicMap.data!.position != null) {
// robot location
canvas.drawCircle(
convertMapToPixelSystem(
Offset(proscenicMap.data!.position![0].toDouble(), proscenicMap.data!.position![1].toDouble()),
proscenicMap),
5,
Paint()
..style = PaintingStyle.fill
..color = Colors.lightBlueAccent
..strokeWidth = 1);
}
// coverages
if (proscenicMap.data!.posArray?.isNotEmpty == true) {
canvas.drawPoints(
PointMode.polygon,
proscenicMap.data!.posArray!
.map((pos) => convertMapToPixelSystem(Offset(pos[0].toDouble(), pos[1].toDouble()), proscenicMap))
.toList(),
Paint()
..style = PaintingStyle.fill
..color = Colors.blue
..strokeWidth = 1,
);
}
// regions
if (proscenicMap.data!.area.isNotEmpty) {
// doors
for (final door in proscenicMap.data!.area.where((element) => element.isWall == true)) {
final points = door.vertexs!
.map((e) => convertMapToPixelSystem(Offset(e[0].toDouble(), e[1].toDouble()), proscenicMap))
.toList();
canvas.drawPoints(
PointMode.polygon,
points,
Paint()
..color = Colors.pinkAccent
..strokeWidth = 1,
);
}
final zones = [
...proscenicMap.data!.area.where((element) => element.isWall == false),
];
// keep out
for (final zone in zones) {
final points = zone.vertexs!
.map((e) => convertMapToPixelSystem(Offset(e[0].toDouble(), e[1].toDouble()), proscenicMap))
.toList();
canvas.drawPath(
Path()..addPolygon(points, true),
Paint()
..style = PaintingStyle.stroke
..color = Colors.red
..strokeWidth = 15,
);
}
}
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}
Color colorFromText(String text) {
const colors = [
Color(0xFF44D7B6),
Color(0xFF6236FF),
Color(0xFFead014),
Color(0xFF89c212),
Color(0xFFcd1719),
];
final charCodes = text
.split('') // => [
.take(2) // "A", "A"]
.map((char) => char.codeUnits.first) // => [65, 65]
.join(); // => "6565"
final color = int.parse(charCodes, radix: 10);
return colors[color % colors.length];
}
class ProscenicMap {
ProscenicMap({
required this.data,
required this.infoType,
});
late final Data? data;
late final int infoType;
ProscenicMap.fromJson(Map<String, dynamic> json) {
data = json['data'] != null ? Data.fromJson(json['data']) : null;
infoType = json['infoType'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['data'] = data?.toJson();
_data['infoType'] = infoType;
return _data;
}
}
class AutoAreaValue {
final String? active;
final String? cleanType;
final int? id;
final String? mode;
final String? name;
final String? tag;
final List<dynamic>? vertexs;
final String? workNoisy;
AutoAreaValue({
this.active,
this.cleanType,
this.id,
this.mode,
this.name,
this.tag,
this.vertexs,
this.workNoisy,
});
AutoAreaValue.fromJson(Map<String, dynamic> json)
: active = json['active'] as String?,
cleanType = json['cleanType'] as String?,
id = json['id'] as int?,
mode = json['mode'] as String?,
name = json['name'] as String?,
tag = json['tag'] as String?,
vertexs = json['vertexs'] as List?,
workNoisy = json['workNoisy'] as String?;
Map<String, dynamic> toJson() => {
'active': active,
'cleanType': cleanType,
'id': id,
'mode': mode,
'name': name,
'tag': tag,
'vertexs': vertexs,
'workNoisy': workNoisy
};
}
class Value {
final String? active;
final String? forbidType;
final int? id;
final bool? isWall;
final String? tag;
List<List<int>>? vertexs;
Value({
this.active,
this.forbidType,
this.id,
this.isWall,
this.tag,
this.vertexs,
});
Value.fromJson(Map<String, dynamic> json)
: active = json['active'] as String?,
forbidType = json['forbidType'] as String?,
id = json['id'] as int?,
isWall = json['isWall'] as bool?,
tag = json['tag'] as String?,
vertexs = ((json['vertexs'] as List<dynamic>).map((e) => (e as List<dynamic>).map((e) => e as int).toList()))
.toList();
Map<String, dynamic> toJson() =>
{'active': active, 'forbidType': forbidType, 'id': id, 'isWall': isWall, 'tag': tag, 'vertexs': vertexs};
}
class Data {
Data({
required this.AllowForbidArea,
required this.area,
required this.autoAreaId,
required this.base64Len,
required this.chargeHandlePhi,
required this.chargeHandlePos,
required this.chargeHandleState,
required this.height,
required this.lz4Len,
required this.map,
required this.mapId,
required this.pathId,
required this.resolution,
required this.width,
required this.xmin,
required this.ymin,
});
late final bool AllowForbidArea;
late final List<Value> area;
late final List<AutoAreaValue>? autoAreaValue;
late final int autoAreaId;
late final int base64Len;
late final int chargeHandlePhi;
late final List<int> chargeHandlePos;
late final List<int>? position;
late final List<List<int>>? posArray;
late final String chargeHandleState;
late final int height;
late final int lz4Len;
late final String map;
late final int mapId;
late final int pathId;
late final double resolution;
late final int width;
late final double xmin;
late final double ymin;
Data.fromJson(Map<String, dynamic> json) {
AllowForbidArea = json['AllowForbidArea'];
area = json['area'] != null
? (json['area'] as List).map((dynamic e) => Value.fromJson(e as Map<String, dynamic>)).toList()
: [];
autoAreaValue = json['autoAreaValue'] != null
? (json['autoAreaValue'] as List).map((dynamic e) => AutoAreaValue.fromJson(e as Map<String, dynamic>)).toList()
: null;
posArray = json['posArray'] != null
? (json['posArray'] as List).map((dynamic e) => (e as List<dynamic>).map((e) => e as int).toList()).toList()
: null;
autoAreaId = json['autoAreaId'];
base64Len = json['base64_len'];
chargeHandlePhi = json['chargeHandlePhi'];
chargeHandlePos = List.castFrom<dynamic, int>(json['chargeHandlePos']);
position = json['position'] != null ? List.castFrom<dynamic, int>(json['position']) : null;
chargeHandleState = json['chargeHandleState'];
height = json['height'];
lz4Len = json['lz4_len'];
map = json['map'];
mapId = json['mapId'] ?? json['mapID'];
pathId = json['pathId'];
resolution = json['resolution'];
width = json['width'];
xmin = json['xmin'];
ymin = json['ymin'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['AllowForbidArea'] = AllowForbidArea;
_data['area'] = area;
_data['autoAreaId'] = autoAreaId;
_data['base64_len'] = base64Len;
_data['chargeHandlePhi'] = chargeHandlePhi;
_data['chargeHandlePos'] = chargeHandlePos;
_data['chargeHandleState'] = chargeHandleState;
_data['height'] = height;
_data['lz4_len'] = lz4Len;
_data['map'] = map;
_data['mapId'] = mapId;
_data['pathId'] = pathId;
_data['resolution'] = resolution;
_data['width'] = width;
_data['xmin'] = xmin;
_data['ymin'] = ymin;
return _data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment