| 1 | #include "convert.hpp" |
| 2 | #include "binarize/binarize.hpp" |
| 3 | |
| 4 | #include <boost/beast/core/detail/base64.hpp> |
| 5 | |
| 6 | #include <optional> |
| 7 | #include <functional> |
| 8 | #include <charconv> |
| 9 | #include <memory> |
| 10 | |
| 11 | namespace bgcode { |
| 12 | using namespace core; |
| 13 | using namespace binarize; |
| 14 | namespace convert { |
| 15 | |
| 16 | class GCodeReader |
| 17 | { |
| 18 | public: |
| 19 | struct GCodeLine |
| 20 | { |
| 21 | std::string raw; |
| 22 | void reset() { raw.clear(); } |
| 23 | }; |
| 24 | |
| 25 | GCodeReader(FILE& file) : m_file(file) {} |
| 26 | |
| 27 | typedef std::function<void(GCodeReader&, const GCodeLine&)> ParseLineCallback; |
| 28 | typedef std::function<void(const char*, const char*)> InternalParseLineCallback; |
| 29 | |
| 30 | // Returns false if reading the file failed. |
| 31 | bool parse(ParseLineCallback callback) { |
| 32 | GCodeLine gline; |
| 33 | m_parsing = true; |
| 34 | return parse_internal([this, &gline, callback](const char* begin, const char* end) { |
| 35 | gline.reset(); |
| 36 | parse_line(begin, end, gline, callback); |
| 37 | }); |
| 38 | } |
| 39 | |
| 40 | void quit_parsing() { m_parsing = false; } |
| 41 | |
| 42 | private: |
| 43 | FILE& m_file; |
| 44 | bool m_parsing{ false }; |
| 45 | |
| 46 | bool parse_internal(InternalParseLineCallback parse_line_callback) { |
| 47 | // Read the input stream 64kB at a time, extract lines and process them. |
| 48 | std::vector<char> buffer(65536 * 10, 0); |
| 49 | // Line buffer. |
| 50 | std::string gcode_line; |
| 51 | size_t file_pos = 0; |
| 52 | for (;;) { |
| 53 | size_t cnt_read = ::fread(buffer.data(), 1, buffer.size(), &m_file); |
| 54 | if (::ferror(&m_file)) { |
| 55 | m_parsing = false; |
| 56 | return false; |
| 57 | } |
| 58 | bool eof = cnt_read == 0; |
| 59 | auto it = buffer.begin(); |
| 60 | auto it_bufend = buffer.begin() + cnt_read; |
| 61 | while (it != it_bufend || (eof && !gcode_line.empty())) { |
| 62 | // Find end of line. |
| 63 | bool eol = false; |
| 64 | auto it_end = it; |
| 65 | for (; it_end != it_bufend && !(eol = *it_end == '\r' || *it_end == '\n'); ++it_end) |
| 66 | ; // silence -Wempty-body |
| 67 | // End of line is indicated also if end of file was reached. |
| 68 | eol |= eof && it_end == it_bufend; |
| 69 | if (eol) { |
| 70 | if (gcode_line.empty()) |
| 71 | parse_line_callback(&(*it), &(*it_end)); |
| 72 | else { |
| 73 | gcode_line.insert(gcode_line.end(), it, it_end); |
| 74 | parse_line_callback(gcode_line.c_str(), gcode_line.c_str() + gcode_line.size()); |
| 75 | gcode_line.clear(); |
| 76 | } |
| 77 | if (!m_parsing) |
| 78 | // The callback wishes to exit. |
| 79 | return true; |
| 80 | } |
| 81 | else |
| 82 | gcode_line.insert(gcode_line.end(), it, it_end); |
| 83 | // Skip EOL. |
| 84 | it = it_end; |
| 85 | if (it != it_bufend && *it == '\r') |
| 86 | ++it; |
| 87 | if (it != it_bufend && *it == '\n') |
| 88 | ++it; |
| 89 | } |
| 90 | if (eof) |
| 91 | break; |
| 92 | file_pos += cnt_read; |
| 93 | } |
| 94 | m_parsing = false; |
| 95 | return true; |
| 96 | } |
| 97 | |
| 98 | const char* parse_line(const char* ptr, const char* end, GCodeLine& gline, ParseLineCallback callback) { |
| 99 | std::pair<const char*, const char*> cmd; |
| 100 | const char* line_end = parse_line_internal(ptr, end, gline, cmd); |
| 101 | callback(*this, gline); |
| 102 | return line_end; |
| 103 | } |
| 104 | |
| 105 | const char* parse_line_internal(const char* ptr, const char* end, GCodeLine& gline, std::pair<const char*, const char*>& command) { |
| 106 | // command and args |
| 107 | const char* c = ptr; |
| 108 | { |
| 109 | // Skip the whitespaces. |
| 110 | command.first = skip_whitespaces(c); |
| 111 | // Skip the command. |
| 112 | c = command.second = skip_word(command.first); |
| 113 | // Up to the end of line or comment. |
| 114 | while (!is_end_of_gcode_line(*c)) { |
| 115 | // Skip whitespaces. |
| 116 | c = skip_whitespaces(c); |
| 117 | if (is_end_of_gcode_line(*c)) |
| 118 | break; |
| 119 | // Skip the rest of the word. |
| 120 | c = skip_word(c); |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | // Skip the rest of the line. |
| 125 | for (; !is_end_of_line(*c); ++c); |
| 126 | |
| 127 | // Copy the raw string including the comment, without the trailing newlines. |
| 128 | if (c > ptr) |
| 129 | gline.raw.assign(ptr, c); |
| 130 | |
| 131 | // Skip the trailing newlines. |
| 132 | if (*c == '\r') |
| 133 | ++c; |
| 134 | if (*c == '\n') |
| 135 | ++c; |
| 136 | |
| 137 | return c; |
| 138 | } |
| 139 | |
| 140 | static bool is_whitespace(char c) { return c == ' ' || c == '\t'; } |
| 141 | static bool is_end_of_line(char c) { return c == '\r' || c == '\n' || c == 0; } |
| 142 | static bool is_end_of_gcode_line(char c) { return c == ';' || is_end_of_line(c); } |
| 143 | static bool is_end_of_word(char c) { return is_whitespace(c) || is_end_of_gcode_line(c); } |
| 144 | static const char* skip_whitespaces(const char* c) { |
| 145 | for (; is_whitespace(*c); ++c) |
| 146 | ; // silence -Wempty-body |
| 147 | return c; |
| 148 | } |
| 149 | static const char* skip_word(const char* c) { |
| 150 | for (; !is_end_of_word(*c); ++c) |
| 151 | ; // silence -Wempty-body |
| 152 | return c; |
| 153 | } |
| 154 | }; |
| 155 | |
| 156 | static std::string_view trim(const std::string_view& str) |
| 157 | { |
| 158 | if (str.empty()) |
| 159 | return std::string_view(); |
| 160 | size_t start = 0; |
| 161 | while (start < str.size() - 1 && (str[start] == ' ' || str[start] == '\t')) { ++start; } |
| 162 | size_t end = str.size() - 1; |
| 163 | while (end > 0 && (str[end] == ' ' || str[end] == '\t')) { --end; } |
| 164 | if ((start == end && (str[end] == ' ' || str[end] == '\t')) || (start > end)) |
| 165 | return std::string_view(); |
| 166 | else |
| 167 | return std::string_view(&str[start], end - start + 1); |
| 168 | } |
| 169 | |
| 170 | static std::string_view uncomment(const std::string_view& str) |
| 171 | { |
| 172 | return (!str.empty() && str[0] == ';') ? trim(str.substr(1)) : str; |
| 173 | } |
| 174 | |
| 175 | template<typename Integer> |
| 176 | static void to_int(const std::string_view& str, Integer& out) { |
| 177 | const std::from_chars_result result = std::from_chars(str.data(), str.data() + str.size(), out); |
| 178 | if (result.ec == std::errc::invalid_argument || result.ec == std::errc::result_out_of_range) |
| 179 | out = 0; |
| 180 | } |
| 181 | |
| 182 | BGCODE_CONVERT_EXPORT EResult from_ascii_to_binary(FILE& src_file, FILE& dst_file, const BinarizerConfig& config) |
| 183 | { |
| 184 | using namespace std::literals; |
| 185 | static constexpr const std::string_view GeneratedByPrusaSlicer = "generated by PrusaSlicer"sv; |
| 186 | static constexpr const std::string_view PreparedBy = "prepared by"sv; |
| 187 | |
| 188 | static constexpr const std::string_view PrinterModel = "printer_model"sv; |
| 189 | static constexpr const std::string_view FilamentType = "filament_type"sv; |
| 190 | static constexpr const std::string_view FilamentAbrasive = "filament_abrasive"sv; |
| 191 | static constexpr const std::string_view NozzleDiameter = "nozzle_diameter"sv; |
| 192 | static constexpr const std::string_view NozzleHighFlow = "nozzle_high_flow"sv; |
| 193 | static constexpr const std::string_view BedTemperature = "bed_temperature"sv; |
| 194 | static constexpr const std::string_view BrimWidth = "brim_width"sv; |
| 195 | static constexpr const std::string_view FillDensity = "fill_density"sv; |
| 196 | static constexpr const std::string_view LayerHeight = "layer_height"sv; |
| 197 | static constexpr const std::string_view Temperature = "temperature"sv; |
| 198 | static constexpr const std::string_view Ironing = "ironing"sv; |
| 199 | static constexpr const std::string_view SupportMaterial = "support_material"sv; |
| 200 | static constexpr const std::string_view MaxLayerZ = "max_layer_z"sv; |
| 201 | static constexpr const std::string_view ExtruderColour = "extruder_colour"sv; |
| 202 | static constexpr const std::string_view FilamentUsedMm = "filament used [mm]"sv; |
| 203 | static constexpr const std::string_view FilamentUsedG = "filament used [g]"sv; |
| 204 | static constexpr const std::string_view EstimatedPrintingTimeNormal = "estimated printing time (normal mode)"sv; |
| 205 | static constexpr const std::string_view FilamentUsedCm3 = "filament used [cm3]"sv; |
| 206 | static constexpr const std::string_view FilamentCost = "filament cost"sv; |
| 207 | static constexpr const std::string_view TotalFilamentUsedG = "total filament used [g]"sv; |
| 208 | static constexpr const std::string_view TotalFilamentCost = "total filament cost"sv; |
| 209 | static constexpr const std::string_view TotalFilamentUsedWipeTower = "total filament used for wipe tower [g]"sv; |
| 210 | static constexpr const std::string_view EstimatedPrintingTimeSilent = "estimated printing time (silent mode)"sv; |
| 211 | static constexpr const std::string_view Estimated1stLayerPrintingTimeNormal = "estimated first layer printing time (normal mode)"sv; |
| 212 | static constexpr const std::string_view Estimated1stLayerPrintingTimeSilent = "estimated first layer printing time (silent mode)"sv; |
| 213 | static constexpr const std::string_view ObjectsInfo = "objects_info"sv; |
| 214 | static constexpr const std::string_view TotalToolChanges = "total toolchanges"sv; |
| 215 | |
| 216 | static constexpr const std::string_view ThumbnailPNGBegin = "thumbnail begin"sv; |
| 217 | static constexpr const std::string_view ThumbnailPNGEnd = "thumbnail end"sv; |
| 218 | static constexpr const std::string_view ThumbnailJPGBegin = "thumbnail_JPG begin"sv; |
| 219 | static constexpr const std::string_view ThumbnailJPGEnd = "thumbnail_JPG end"sv; |
| 220 | static constexpr const std::string_view ThumbnailQOIBegin = "thumbnail_QOI begin"sv; |
| 221 | static constexpr const std::string_view ThumbnailQOIEnd = "thumbnail_QOI end"sv; |
| 222 | |
| 223 | static constexpr const std::string_view PrusaSlicerConfig = "prusaslicer_config"sv; |
| 224 | static constexpr const std::string_view PrusaSlicerConfigJson = "prusaslicer_json_config"sv; |
| 225 | |
| 226 | auto search_metadata_value = [&](const std::string_view& str, const std::string_view& key) { |
| 227 | std::string ret; |
| 228 | if (str.find(key) == 0) { |
| 229 | const size_t pos = str.find("="); |
| 230 | if (pos != std::string_view::npos) |
| 231 | ret = trim(str.substr(pos + 1)); |
| 232 | } |
| 233 | return ret; |
| 234 | }; |
| 235 | auto extract_thumbnail_rect = [](const std::string_view& str) { |
| 236 | std::pair<uint16_t, uint16_t> ret = { 0, 0 }; |
| 237 | const size_t pos = str.find('x'); |
| 238 | if (pos != std::string_view::npos) { |
| 239 | to_int(str.substr(0, pos), ret.first); |
| 240 | to_int(str.substr(pos + 1), ret.second); |
| 241 | } |
| 242 | return ret; |
| 243 | }; |
| 244 | |
| 245 | EResult res = is_valid_binary_gcode(src_file); |
| 246 | if (res == EResult::Success) |
| 247 | return EResult::AlreadyBinarized; |
| 248 | |
| 249 | Binarizer binarizer; |
| 250 | binarizer.set_enabled(true); |
| 251 | BinaryData& binary_data = binarizer.get_binary_data(); |
| 252 | |
| 253 | std::string printer_model; |
| 254 | std::string filament_type; |
| 255 | std::string filament_abrasive; |
| 256 | std::string nozzle_diameter; |
| 257 | std::string nozzle_high_flow; |
| 258 | std::string bed_temperature; |
| 259 | std::string brim_width; |
| 260 | std::string fill_density; |
| 261 | std::string layer_height; |
| 262 | std::string temperature; |
| 263 | std::string ironing; |
| 264 | std::string support_material; |
| 265 | std::string max_layer_z; |
| 266 | std::string extruder_colour; |
| 267 | std::string filament_used_mm; |
| 268 | std::string filament_used_g; |
| 269 | std::string estimated_printing_time_normal; |
| 270 | std::string filament_used_cm3; |
| 271 | std::string filament_cost; |
| 272 | std::string total_filament_used_g; |
| 273 | std::string total_filament_cost; |
| 274 | std::string total_filament_used_wipe_tower; |
| 275 | std::string estimated_printing_time_silent; |
| 276 | std::string estimated_1st_layer_printing_time_normal; |
| 277 | std::string estimated_1st_layer_printing_time_silent; |
| 278 | std::string objects_info; |
| 279 | std::string total_tool_changes; |
| 280 | |
| 281 | std::optional<EThumbnailFormat> reading_thumbnail; |
| 282 | size_t curr_thumbnail_data_size = 0; |
| 283 | size_t curr_thumbnail_data_loaded = 0; |
| 284 | |
| 285 | std::optional<std::string> slicer_json; |
| 286 | |
| 287 | bool producer_found = false; |
| 288 | bool reading_config = false; |
| 289 | |
| 290 | std::vector<size_t> processed_lines; |
| 291 | |
| 292 | EResult parse_res = EResult::Success; |
| 293 | GCodeReader parser(src_file); |
| 294 | size_t lines_counter = 0; |
| 295 | if (!parser.parse([&](GCodeReader& r, const GCodeReader::GCodeLine& line) { |
| 296 | if (parse_res != EResult::Success) |
| 297 | r.quit_parsing(); |
| 298 | |
| 299 | const std::string_view sv_line = uncomment(trim(line.raw)); |
| 300 | if (sv_line.empty()) { |
| 301 | processed_lines.emplace_back(lines_counter++); |
| 302 | return; |
| 303 | } |
| 304 | |
| 305 | // update file metadata |
| 306 | size_t pos = sv_line.find(GeneratedByPrusaSlicer); |
| 307 | if (pos != std::string_view::npos) { |
| 308 | std::string_view version = trim(sv_line.substr(pos + GeneratedByPrusaSlicer.length())); |
| 309 | std::string_view time; |
| 310 | pos = version.find(" "); |
| 311 | if (pos != std::string_view::npos) { |
| 312 | if (version.substr(pos, 4) == " on ") |
| 313 | time = version.substr(pos + 4); |
| 314 | version = version.substr(0, pos); |
| 315 | |
| 316 | } |
| 317 | binary_data.file_metadata.raw_data.emplace_back("Producer", "PrusaSlicer " + std::string(version)); |
| 318 | if (!time.empty()) |
| 319 | binary_data.file_metadata.raw_data.emplace_back("Produced on", time); |
| 320 | producer_found = true; |
| 321 | processed_lines.emplace_back(lines_counter++); |
| 322 | return; |
| 323 | } |
| 324 | |
| 325 | pos = sv_line.find(PreparedBy); |
| 326 | if (lines_counter < 5 && pos != std::string_view::npos) { |
| 327 | std::string_view prep = trim(sv_line.substr(pos + PreparedBy.size())); |
| 328 | if (! prep.empty()) |
| 329 | binary_data.file_metadata.raw_data.emplace_back("Prepared by", prep); |
| 330 | processed_lines.emplace_back(lines_counter++); |
| 331 | return; |
| 332 | } |
| 333 | |
| 334 | // collect print + printer metadata |
| 335 | // to keep the proper order they will be set into binary_data later |
| 336 | auto collect_metadata = [&](const std::string_view& key, std::string& value, bool shared_in_config = false) { |
| 337 | const std::string str = search_metadata_value(sv_line, key); |
| 338 | if (!str.empty()) { |
| 339 | if (value.empty()) |
| 340 | value = str; |
| 341 | if (!shared_in_config) { |
| 342 | processed_lines.emplace_back(lines_counter++); |
| 343 | return true; |
| 344 | } |
| 345 | if (shared_in_config && !reading_config) { |
| 346 | processed_lines.emplace_back(lines_counter++); |
| 347 | return true; |
| 348 | } |
| 349 | } |
| 350 | return false; |
| 351 | }; |
| 352 | |
| 353 | if (collect_metadata(PrinterModel, printer_model, true)) return; |
| 354 | if (collect_metadata(FilamentType, filament_type, true)) return; |
| 355 | if (collect_metadata(FilamentAbrasive, filament_abrasive, true)) return; |
| 356 | if (collect_metadata(NozzleDiameter, nozzle_diameter, true)) return; |
| 357 | if (collect_metadata(NozzleHighFlow, nozzle_high_flow, true)) return; |
| 358 | if (collect_metadata(BedTemperature, bed_temperature, true)) return; |
| 359 | if (collect_metadata(BrimWidth, brim_width, true)) return; |
| 360 | if (collect_metadata(FillDensity, fill_density, true)) return; |
| 361 | if (collect_metadata(LayerHeight, layer_height, true)) return; |
| 362 | if (collect_metadata(Temperature, temperature, true)) return; |
| 363 | if (collect_metadata(Ironing, ironing, true)) return; |
| 364 | if (collect_metadata(SupportMaterial, support_material, true)) return; |
| 365 | if (collect_metadata(MaxLayerZ, max_layer_z)) return; |
| 366 | if (collect_metadata(ExtruderColour, extruder_colour, true)) return; |
| 367 | if (collect_metadata(FilamentUsedMm, filament_used_mm)) return; |
| 368 | if (collect_metadata(FilamentUsedG, filament_used_g)) return; |
| 369 | if (collect_metadata(EstimatedPrintingTimeNormal, estimated_printing_time_normal)) return; |
| 370 | if (collect_metadata(FilamentUsedCm3, filament_used_cm3)) return; |
| 371 | if (collect_metadata(FilamentCost, filament_cost)) return; |
| 372 | if (collect_metadata(TotalFilamentUsedG, total_filament_used_g)) return; |
| 373 | if (collect_metadata(TotalFilamentCost, total_filament_cost)) return; |
| 374 | if (collect_metadata(TotalFilamentUsedWipeTower, total_filament_used_wipe_tower)) return; |
| 375 | if (collect_metadata(EstimatedPrintingTimeSilent, estimated_printing_time_silent)) return; |
| 376 | if (collect_metadata(Estimated1stLayerPrintingTimeNormal, estimated_1st_layer_printing_time_normal)) return; |
| 377 | if (collect_metadata(Estimated1stLayerPrintingTimeSilent, estimated_1st_layer_printing_time_silent)) return; |
| 378 | if (collect_metadata(ObjectsInfo, objects_info)) return; |
| 379 | if (collect_metadata(TotalToolChanges, total_tool_changes)) return; |
| 380 | |
| 381 | // update slicer metadata |
| 382 | if (!reading_config) { |
| 383 | if (search_metadata_value(sv_line, PrusaSlicerConfig) == "begin") { |
| 384 | reading_config = true; |
| 385 | processed_lines.emplace_back(lines_counter++); |
| 386 | return; |
| 387 | } |
| 388 | } |
| 389 | else { |
| 390 | if (search_metadata_value(sv_line, PrusaSlicerConfig) == "end") { |
| 391 | reading_config = false; |
| 392 | processed_lines.emplace_back(lines_counter++); |
| 393 | return; |
| 394 | } |
| 395 | else { |
| 396 | const size_t pos = sv_line.find("="); |
| 397 | if (pos == std::string_view::npos) { |
| 398 | parse_res = EResult::InvalidAsciiGCodeFile; |
| 399 | return; |
| 400 | } |
| 401 | const std::string_view key = trim(sv_line.substr(0, pos)); |
| 402 | const std::string_view value = trim(sv_line.substr(pos + 1)); |
| 403 | if (key.empty()) { |
| 404 | parse_res = EResult::InvalidAsciiGCodeFile; |
| 405 | return; |
| 406 | } |
| 407 | binary_data.slicer_metadata.raw_data.emplace_back(std::string(key), std::string(value)); |
| 408 | processed_lines.emplace_back(lines_counter++); |
| 409 | return; |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | // update thumbnails |
| 414 | if (!reading_thumbnail.has_value()) { |
| 415 | std::string_view sv_thumbnail_str; |
| 416 | if (sv_line.find(ThumbnailPNGBegin) == 0) { |
| 417 | reading_thumbnail = EThumbnailFormat::PNG; |
| 418 | sv_thumbnail_str = trim(sv_line.substr(ThumbnailPNGBegin.size())); |
| 419 | } |
| 420 | else if (sv_line.find(ThumbnailJPGBegin) == 0) { |
| 421 | reading_thumbnail = EThumbnailFormat::JPG; |
| 422 | sv_thumbnail_str = trim(sv_line.substr(ThumbnailJPGBegin.size())); |
| 423 | } |
| 424 | else if (sv_line.find(ThumbnailQOIBegin) == 0) { |
| 425 | reading_thumbnail = EThumbnailFormat::QOI; |
| 426 | sv_thumbnail_str = trim(sv_line.substr(ThumbnailQOIBegin.size())); |
| 427 | } |
| 428 | if (reading_thumbnail.has_value()) { |
| 429 | ThumbnailBlock& thumbnail = binary_data.thumbnails.emplace_back(ThumbnailBlock()); |
| 430 | thumbnail.params.format = (uint16_t)*reading_thumbnail; |
| 431 | pos = sv_thumbnail_str.find(" "); |
| 432 | if (pos == std::string_view::npos) { |
| 433 | parse_res = EResult::InvalidAsciiGCodeFile; |
| 434 | return; |
| 435 | } |
| 436 | const std::string_view sv_rect_str = trim(sv_thumbnail_str.substr(0, pos)); |
| 437 | std::pair<uint16_t, uint16_t> rect = extract_thumbnail_rect(sv_rect_str); |
| 438 | if (rect.first == 0 || rect.second == 0) { |
| 439 | parse_res = EResult::InvalidAsciiGCodeFile; |
| 440 | return; |
| 441 | } |
| 442 | thumbnail.params.width = rect.first; |
| 443 | thumbnail.params.height = rect.second; |
| 444 | const std::string_view sv_data_size_str = trim(sv_thumbnail_str.substr(pos + 1)); |
| 445 | size_t data_size; |
| 446 | to_int(sv_data_size_str, data_size); |
| 447 | if (data_size == 0) { |
| 448 | parse_res = EResult::InvalidAsciiGCodeFile; |
| 449 | return; |
| 450 | } |
| 451 | curr_thumbnail_data_size = data_size; |
| 452 | curr_thumbnail_data_loaded = 0; |
| 453 | thumbnail.data.resize(data_size); |
| 454 | processed_lines.emplace_back(lines_counter++); |
| 455 | return; |
| 456 | } |
| 457 | } |
| 458 | else { |
| 459 | bool thumbnail_end = false; |
| 460 | if (sv_line.find(ThumbnailPNGEnd) == 0) { |
| 461 | if (*reading_thumbnail != EThumbnailFormat::PNG) { |
| 462 | parse_res = EResult::InvalidAsciiGCodeFile; |
| 463 | return; |
| 464 | } |
| 465 | thumbnail_end = true; |
| 466 | } |
| 467 | else if (sv_line.find(ThumbnailJPGEnd) == 0) { |
| 468 | if (*reading_thumbnail != EThumbnailFormat::JPG) { |
| 469 | parse_res = EResult::InvalidAsciiGCodeFile; |
| 470 | return; |
| 471 | } |
| 472 | thumbnail_end = true; |
| 473 | } |
| 474 | else if (sv_line.find(ThumbnailQOIEnd) == 0) { |
| 475 | if (*reading_thumbnail != EThumbnailFormat::QOI) { |
| 476 | parse_res = EResult::InvalidAsciiGCodeFile; |
| 477 | return; |
| 478 | } |
| 479 | thumbnail_end = true; |
| 480 | } |
| 481 | |
| 482 | if (thumbnail_end) { |
| 483 | reading_thumbnail.reset(); |
| 484 | if (curr_thumbnail_data_loaded != curr_thumbnail_data_size) { |
| 485 | parse_res = EResult::InvalidAsciiGCodeFile; |
| 486 | return; |
| 487 | } |
| 488 | ThumbnailBlock& thumbnail = binary_data.thumbnails.back(); |
| 489 | if (thumbnail.data.size() > curr_thumbnail_data_loaded) |
| 490 | thumbnail.data.resize(curr_thumbnail_data_loaded); |
| 491 | std::vector<std::byte> decoded(boost::beast::detail::base64::decoded_size(thumbnail.data.size())); |
| 492 | auto thumbnail_buf = reinterpret_cast<const char *>(thumbnail.data.data()); |
| 493 | decoded.resize(boost::beast::detail::base64::decode(decoded.data(), thumbnail_buf, thumbnail.data.size()).first); |
| 494 | thumbnail.data.clear(); |
| 495 | std::copy(decoded.begin(), decoded.end(), std::back_inserter(thumbnail.data)); |
| 496 | processed_lines.emplace_back(lines_counter++); |
| 497 | return; |
| 498 | } |
| 499 | else { |
| 500 | if (curr_thumbnail_data_loaded + sv_line.size() > curr_thumbnail_data_size) { |
| 501 | parse_res = EResult::InvalidAsciiGCodeFile; |
| 502 | return; |
| 503 | } |
| 504 | ThumbnailBlock& thumbnail = binary_data.thumbnails.back(); |
| 505 | auto sv_line_bytes = reinterpret_cast<const std::byte*>(sv_line.data()); |
| 506 | thumbnail.data.insert(thumbnail.data.begin() + curr_thumbnail_data_loaded, sv_line_bytes, sv_line_bytes + sv_line.size()); |
| 507 | curr_thumbnail_data_loaded += sv_line.size(); |
| 508 | processed_lines.emplace_back(lines_counter++); |
| 509 | return; |
| 510 | } |
| 511 | } |
| 512 | |
| 513 | if (!slicer_json.has_value()) { |
| 514 | if (search_metadata_value(sv_line, PrusaSlicerConfigJson) == "begin") { |
| 515 | slicer_json = ""; |
| 516 | processed_lines.emplace_back(lines_counter++); |
| 517 | return; |
| 518 | } |
| 519 | } |
| 520 | else { |
| 521 | if (search_metadata_value(sv_line, PrusaSlicerConfigJson) == "end") { |
| 522 | binary_data.slicer3_metadata.set_json(slicer_json.value()); |
| 523 | processed_lines.emplace_back(lines_counter++); |
| 524 | return; |
| 525 | } |
| 526 | else { |
| 527 | slicer_json.value() += sv_line; |
| 528 | processed_lines.emplace_back(lines_counter++); |
| 529 | return; |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | ++lines_counter; |
| 534 | })) |
| 535 | return EResult::ReadError; |
| 536 | |
| 537 | if (parse_res != EResult::Success) |
| 538 | // propagate error |
| 539 | return parse_res; |
| 540 | |
| 541 | if (reading_config) |
| 542 | return EResult::InvalidAsciiGCodeFile; |
| 543 | |
| 544 | if (reading_thumbnail.has_value()) |
| 545 | return EResult::InvalidAsciiGCodeFile; |
| 546 | |
| 547 | if (!producer_found) |
| 548 | return EResult::InvalidAsciiGCodeFile; |
| 549 | |
| 550 | auto append_metadata = [](std::vector<std::pair<std::string, std::string>>& dst, const std::string& key, const std::string& value) { |
| 551 | if (!value.empty()) dst.emplace_back(key, value); |
| 552 | }; |
| 553 | |
| 554 | // update printer metadata |
| 555 | append_metadata(binary_data.printer_metadata.raw_data, std::string(PrinterModel), printer_model); |
| 556 | append_metadata(binary_data.printer_metadata.raw_data, std::string(FilamentType), filament_type); |
| 557 | append_metadata(binary_data.printer_metadata.raw_data, std::string(FilamentAbrasive), filament_abrasive); |
| 558 | append_metadata(binary_data.printer_metadata.raw_data, std::string(NozzleDiameter), nozzle_diameter); |
| 559 | append_metadata(binary_data.printer_metadata.raw_data, std::string(NozzleHighFlow), nozzle_high_flow); |
| 560 | append_metadata(binary_data.printer_metadata.raw_data, std::string(BedTemperature), bed_temperature); |
| 561 | append_metadata(binary_data.printer_metadata.raw_data, std::string(BrimWidth), brim_width); |
| 562 | append_metadata(binary_data.printer_metadata.raw_data, std::string(FillDensity), fill_density); |
| 563 | append_metadata(binary_data.printer_metadata.raw_data, std::string(LayerHeight), layer_height); |
| 564 | append_metadata(binary_data.printer_metadata.raw_data, std::string(Temperature), temperature); |
| 565 | append_metadata(binary_data.printer_metadata.raw_data, std::string(Ironing), ironing); |
| 566 | append_metadata(binary_data.printer_metadata.raw_data, std::string(SupportMaterial), support_material); |
| 567 | append_metadata(binary_data.printer_metadata.raw_data, std::string(MaxLayerZ), max_layer_z); |
| 568 | append_metadata(binary_data.printer_metadata.raw_data, std::string(ExtruderColour), extruder_colour); |
| 569 | append_metadata(binary_data.printer_metadata.raw_data, std::string(FilamentUsedMm), filament_used_mm); |
| 570 | append_metadata(binary_data.printer_metadata.raw_data, std::string(FilamentUsedCm3), filament_used_cm3); |
| 571 | append_metadata(binary_data.printer_metadata.raw_data, std::string(FilamentUsedG), filament_used_g); |
| 572 | append_metadata(binary_data.printer_metadata.raw_data, std::string(FilamentCost), filament_cost); |
| 573 | append_metadata(binary_data.printer_metadata.raw_data, std::string(EstimatedPrintingTimeNormal), estimated_printing_time_normal); |
| 574 | append_metadata(binary_data.printer_metadata.raw_data, std::string(EstimatedPrintingTimeSilent), estimated_printing_time_silent); |
| 575 | append_metadata(binary_data.printer_metadata.raw_data, std::string(TotalFilamentUsedWipeTower), total_filament_used_wipe_tower); |
| 576 | append_metadata(binary_data.printer_metadata.raw_data, std::string(TotalToolChanges), total_tool_changes); |
| 577 | append_metadata(binary_data.printer_metadata.raw_data, std::string(ObjectsInfo), objects_info); |
| 578 | |
| 579 | // update print metadata |
| 580 | append_metadata(binary_data.print_metadata.raw_data, std::string(TotalToolChanges), total_tool_changes); |
| 581 | append_metadata(binary_data.print_metadata.raw_data, std::string(FilamentUsedMm), filament_used_mm); |
| 582 | append_metadata(binary_data.print_metadata.raw_data, std::string(FilamentUsedCm3), filament_used_cm3); |
| 583 | append_metadata(binary_data.print_metadata.raw_data, std::string(FilamentUsedG), filament_used_g); |
| 584 | append_metadata(binary_data.print_metadata.raw_data, std::string(FilamentCost), filament_cost); |
| 585 | append_metadata(binary_data.print_metadata.raw_data, std::string(TotalFilamentUsedG), total_filament_used_g); |
| 586 | append_metadata(binary_data.print_metadata.raw_data, std::string(TotalFilamentCost), total_filament_cost); |
| 587 | append_metadata(binary_data.print_metadata.raw_data, std::string(TotalFilamentUsedWipeTower), total_filament_used_wipe_tower); |
| 588 | append_metadata(binary_data.print_metadata.raw_data, std::string(EstimatedPrintingTimeNormal), estimated_printing_time_normal); |
| 589 | append_metadata(binary_data.print_metadata.raw_data, std::string(EstimatedPrintingTimeSilent), estimated_printing_time_silent); |
| 590 | append_metadata(binary_data.print_metadata.raw_data, std::string(Estimated1stLayerPrintingTimeNormal), estimated_1st_layer_printing_time_normal); |
| 591 | append_metadata(binary_data.print_metadata.raw_data, std::string(Estimated1stLayerPrintingTimeSilent), estimated_1st_layer_printing_time_silent); |
| 592 | |
| 593 | res = binarizer.initialize(dst_file, config); |
| 594 | if (res != EResult::Success) |
| 595 | // propagate error |
| 596 | return res; |
| 597 | |
| 598 | // reparse the file to extract the gcode |
| 599 | rewind(&src_file); |
| 600 | parse_res = EResult::Success; |
| 601 | lines_counter = 0; |
| 602 | if (!parser.parse([&](GCodeReader& r, const GCodeReader::GCodeLine& line) { |
| 603 | if (parse_res != EResult::Success) |
| 604 | r.quit_parsing(); |
| 605 | |
| 606 | if (!std::binary_search(processed_lines.begin(), processed_lines.end(), lines_counter)) |
| 607 | binarizer.append_gcode(line.raw + "\n"); |
| 608 | |
| 609 | ++lines_counter; |
| 610 | })) |
| 611 | return EResult::ReadError; |
| 612 | |
| 613 | if (parse_res != EResult::Success) |
| 614 | // propagate error |
| 615 | return parse_res; |
| 616 | |
| 617 | res = binarizer.finalize(); |
| 618 | if (res != EResult::Success) |
| 619 | // propagate error |
| 620 | return res; |
| 621 | |
| 622 | return EResult::Success; |
| 623 | } |
| 624 | |
| 625 | BGCODE_CONVERT_EXPORT EResult from_binary_to_ascii(FILE& src_file, FILE& dst_file, bool verify_checksum) |
| 626 | { |
| 627 | // initialize buffer for checksum calculation, if verify_checksum is true |
| 628 | std::vector<std::byte> checksum_buffer; |
| 629 | if (verify_checksum) |
| 630 | checksum_buffer.resize(65535); |
| 631 | |
| 632 | auto write_line = [&](const std::string& line) { |
| 633 | const size_t wsize = fwrite(line.data(), 1, line.length(), &dst_file); |
| 634 | return !ferror(&dst_file) && wsize == line.length(); |
| 635 | }; |
| 636 | |
| 637 | auto write_metadata = [&](const std::vector<std::pair<std::string, std::string>>& data) { |
| 638 | for (const auto& [key, value] : data) { |
| 639 | if (!write_line("; " + key + " = " + value + "\n")) |
| 640 | return false; |
| 641 | } |
| 642 | return !ferror(&dst_file); |
| 643 | }; |
| 644 | |
| 645 | EResult res = is_valid_binary_gcode(src_file, true); |
| 646 | if (res != EResult::Success) |
| 647 | // propagate error |
| 648 | return res; |
| 649 | |
| 650 | fseek(&src_file, 0, SEEK_END); |
| 651 | const long file_size = ftell(&src_file); |
| 652 | rewind(&src_file); |
| 653 | |
| 654 | // |
| 655 | // read file header |
| 656 | // |
| 657 | FileHeader file_header; |
| 658 | res = read_header(src_file, file_header, nullptr); |
| 659 | if (res != EResult::Success) |
| 660 | // propagate error |
| 661 | return res; |
| 662 | |
| 663 | // |
| 664 | // convert file metadata block, if present |
| 665 | // |
| 666 | BlockHeader block_header; |
| 667 | res = read_next_block_header(src_file, file_header, block_header, checksum_buffer.data(), checksum_buffer.size()); |
| 668 | if (res != EResult::Success) |
| 669 | // propagate error |
| 670 | return res; |
| 671 | if ((EBlockType)block_header.type != EBlockType::FileMetadata && |
| 672 | (EBlockType)block_header.type != EBlockType::PrinterMetadata) |
| 673 | return EResult::InvalidSequenceOfBlocks; |
| 674 | if ((EBlockType)block_header.type == EBlockType::FileMetadata) { |
| 675 | FileMetadataBlock file_metadata_block; |
| 676 | res = file_metadata_block.read_data(src_file, file_header, block_header); |
| 677 | if (res != EResult::Success) |
| 678 | // propagate error |
| 679 | return res; |
| 680 | |
| 681 | auto producer_it = std::find_if(file_metadata_block.raw_data.begin(), file_metadata_block.raw_data.end(), |
| 682 | [](const std::pair<std::string, std::string>& item) { return item.first == "Producer"; }); |
| 683 | auto prepared_it = std::find_if(file_metadata_block.raw_data.begin(), file_metadata_block.raw_data.end(), |
| 684 | [](const std::pair<std::string, std::string>& item) { return item.first == "Prepared by"; }); |
| 685 | auto produced_on_it = std::find_if(file_metadata_block.raw_data.begin(), file_metadata_block.raw_data.end(), |
| 686 | [](const auto& item) { return item.first == "Produced on"; }); |
| 687 | |
| 688 | std::string producer_str = (producer_it != file_metadata_block.raw_data.end()) ? producer_it->second : "Unknown"; |
| 689 | if (produced_on_it != file_metadata_block.raw_data.end()) |
| 690 | producer_str += " on " + produced_on_it->second; |
| 691 | if (prepared_it != file_metadata_block.raw_data.end()) |
| 692 | producer_str += "\n; prepared by " + prepared_it->second; |
| 693 | |
| 694 | if (!write_line("; generated by " + producer_str + "\n\n\n")) |
| 695 | return EResult::WriteError; |
| 696 | |
| 697 | res = read_next_block_header(src_file, file_header, block_header, checksum_buffer.data(), checksum_buffer.size()); |
| 698 | if (res != EResult::Success) |
| 699 | // propagate error |
| 700 | return res; |
| 701 | if ((EBlockType)block_header.type != EBlockType::PrinterMetadata) |
| 702 | return EResult::InvalidSequenceOfBlocks; |
| 703 | } |
| 704 | |
| 705 | // |
| 706 | // convert printer metadata block |
| 707 | // |
| 708 | PrinterMetadataBlock printer_metadata_block; |
| 709 | res = printer_metadata_block.read_data(src_file, file_header, block_header); |
| 710 | if (res != EResult::Success) |
| 711 | // propagate error |
| 712 | return res; |
| 713 | if (!write_metadata(printer_metadata_block.raw_data)) |
| 714 | return EResult::WriteError; |
| 715 | |
| 716 | // |
| 717 | // convert thumbnail blocks, if present |
| 718 | // |
| 719 | long restore_position = ftell(&src_file); |
| 720 | res = read_next_block_header(src_file, file_header, block_header, checksum_buffer.data(), checksum_buffer.size()); |
| 721 | if (res != EResult::Success) |
| 722 | // propagate error |
| 723 | return res; |
| 724 | while ((EBlockType)block_header.type == EBlockType::Thumbnail) { |
| 725 | ThumbnailBlock thumbnail_block; |
| 726 | res = thumbnail_block.read_data(src_file, file_header, block_header); |
| 727 | if (res != EResult::Success) |
| 728 | // propagate error |
| 729 | return res; |
| 730 | static constexpr const size_t max_row_length = 78; |
| 731 | std::string encoded; |
| 732 | encoded.resize(boost::beast::detail::base64::encoded_size(thumbnail_block.data.size())); |
| 733 | encoded.resize(boost::beast::detail::base64::encode((void*)encoded.data(), (const void*)thumbnail_block.data.data(), thumbnail_block.data.size())); |
| 734 | std::string format; |
| 735 | switch ((EThumbnailFormat)thumbnail_block.params.format) |
| 736 | { |
| 737 | default: |
| 738 | case EThumbnailFormat::PNG: { format = "thumbnail"; break; } |
| 739 | case EThumbnailFormat::JPG: { format = "thumbnail_JPG"; break; } |
| 740 | case EThumbnailFormat::QOI: { format = "thumbnail_QOI"; break; } |
| 741 | } |
| 742 | if (!write_line("\n;\n; " + format + " begin " + std::to_string(thumbnail_block.params.width) + "x" + std::to_string(thumbnail_block.params.height) + |
| 743 | " " + std::to_string(encoded.length()) + "\n")) |
| 744 | return EResult::WriteError; |
| 745 | while (encoded.size() > max_row_length) { |
| 746 | if (!write_line("; " + encoded.substr(0, max_row_length) + "\n")) |
| 747 | return EResult::WriteError; |
| 748 | encoded = encoded.substr(max_row_length); |
| 749 | } |
| 750 | if (encoded.size() > 0) { |
| 751 | if (!write_line("; " + encoded + "\n")) |
| 752 | return EResult::WriteError; |
| 753 | } |
| 754 | if (!write_line("; " + format + " end\n;\n")) |
| 755 | return EResult::WriteError; |
| 756 | |
| 757 | restore_position = ftell(&src_file); |
| 758 | res = read_next_block_header(src_file, file_header, block_header, checksum_buffer.data(), checksum_buffer.size()); |
| 759 | if (res != EResult::Success) |
| 760 | // propagate error |
| 761 | return res; |
| 762 | } |
| 763 | |
| 764 | // |
| 765 | // convert gcode blocks |
| 766 | // |
| 767 | auto remove_empty_lines = [](const std::string& data) { |
| 768 | std::string ret; |
| 769 | auto begin_it = data.begin(); |
| 770 | auto end_it = data.begin(); |
| 771 | while (end_it != data.end()) { |
| 772 | while (end_it != data.end() && *end_it != '\n') { |
| 773 | ++end_it; |
| 774 | } |
| 775 | |
| 776 | const size_t pos = std::distance(data.begin(), begin_it); |
| 777 | const size_t line_length = std::distance(begin_it, end_it); |
| 778 | const std::string_view original_line(&data[pos], line_length); |
| 779 | const std::string_view reduced_line = uncomment(trim(original_line)); |
| 780 | if (!reduced_line.empty()) |
| 781 | ret += std::string(original_line) + "\n"; |
| 782 | begin_it = ++end_it; |
| 783 | } |
| 784 | |
| 785 | return ret; |
| 786 | }; |
| 787 | |
| 788 | if (!write_line("\n")) |
| 789 | return EResult::WriteError; |
| 790 | res = skip_block(src_file, file_header, block_header); |
| 791 | if (res != EResult::Success) |
| 792 | // propagate error |
| 793 | return res; |
| 794 | res = read_next_block_header(src_file, file_header, block_header, EBlockType::GCode, checksum_buffer.data(), checksum_buffer.size()); |
| 795 | if (res != EResult::Success) |
| 796 | // propagate error |
| 797 | return res; |
| 798 | while ((EBlockType)block_header.type == EBlockType::GCode) { |
| 799 | GCodeBlock block; |
| 800 | res = block.read_data(src_file, file_header, block_header); |
| 801 | if (res != EResult::Success) |
| 802 | // propagate error |
| 803 | return res; |
| 804 | const std::string out_str = remove_empty_lines(block.raw_data); |
| 805 | if (!out_str.empty()) { |
| 806 | if (!write_line(out_str)) |
| 807 | return EResult::WriteError; |
| 808 | } |
| 809 | if (ftell(&src_file) == file_size) |
| 810 | break; |
| 811 | res = read_next_block_header(src_file, file_header, block_header, checksum_buffer.data(), checksum_buffer.size()); |
| 812 | if (res != EResult::Success) |
| 813 | // propagate error |
| 814 | return res; |
| 815 | } |
| 816 | |
| 817 | // |
| 818 | // convert print metadata block |
| 819 | // |
| 820 | fseek(&src_file, restore_position, SEEK_SET); |
| 821 | res = read_next_block_header(src_file, file_header, block_header, checksum_buffer.data(), checksum_buffer.size()); |
| 822 | if (res != EResult::Success) |
| 823 | // propagate error |
| 824 | return res; |
| 825 | if ((EBlockType)block_header.type != EBlockType::PrintMetadata) |
| 826 | return EResult::InvalidSequenceOfBlocks; |
| 827 | PrintMetadataBlock print_metadata_block; |
| 828 | res = print_metadata_block.read_data(src_file, file_header, block_header); |
| 829 | if (res != EResult::Success) |
| 830 | // propagate error |
| 831 | return res; |
| 832 | if (!write_line("\n")) |
| 833 | return EResult::WriteError; |
| 834 | if (!write_metadata(print_metadata_block.raw_data)) |
| 835 | return EResult::WriteError; |
| 836 | |
| 837 | // |
| 838 | // convert slicer metadata blocks |
| 839 | // |
| 840 | std::optional<SlicerMetadataBlock> slicer_legacy_metadata_block; |
| 841 | std::optional<Slicer3MetadataBlock> slicer_metadata_block; |
| 842 | |
| 843 | for (size_t i = 0; i < 2; i++) { |
| 844 | res = read_next_block_header(src_file, file_header, block_header, checksum_buffer.data(), checksum_buffer.size()); |
| 845 | if (res != EResult::Success) |
| 846 | // propagate error |
| 847 | return res; |
| 848 | // at least one slicer metadata block is required |
| 849 | if ((EBlockType)block_header.type != EBlockType::SlicerMetadata && i == 0) { |
| 850 | return EResult::InvalidSequenceOfBlocks; |
| 851 | } |
| 852 | auto peek_result = peek_slicer_metadata_block(src_file, block_header); |
| 853 | switch (peek_result) { |
| 854 | case EPeekSlicerMetadataResult::ReadError: |
| 855 | return EResult::ReadError; |
| 856 | |
| 857 | case EPeekSlicerMetadataResult::Slicer3MetadataFound: |
| 858 | { |
| 859 | Slicer3MetadataBlock block; |
| 860 | res = block.read_data(src_file, file_header, block_header); |
| 861 | slicer_metadata_block = std::move(block); |
| 862 | |
| 863 | break; |
| 864 | } |
| 865 | |
| 866 | case EPeekSlicerMetadataResult::SlicerMetadataFound: |
| 867 | { |
| 868 | SlicerMetadataBlock block; |
| 869 | res = block.read_data(src_file, file_header, block_header); |
| 870 | slicer_legacy_metadata_block = std::move(block); |
| 871 | break; |
| 872 | } |
| 873 | |
| 874 | case EPeekSlicerMetadataResult::OtherBlockFound: |
| 875 | break;; |
| 876 | |
| 877 | } |
| 878 | |
| 879 | if (res != EResult::Success) |
| 880 | // propagate error |
| 881 | return res; |
| 882 | } |
| 883 | if (slicer_metadata_block.has_value()) { |
| 884 | if (!write_line("\n; prusaslicer_json_config = begin\n")) |
| 885 | return EResult::WriteError; |
| 886 | if (!write_line("; " + slicer_metadata_block->json() + "\n")) |
| 887 | return EResult::WriteError; |
| 888 | if (!write_line("; prusaslicer_json_config = end\n")) |
| 889 | return EResult::WriteError; |
| 890 | } |
| 891 | if (slicer_legacy_metadata_block.has_value()) { |
| 892 | if (!write_line("\n; prusaslicer_config = begin\n")) |
| 893 | return EResult::WriteError; |
| 894 | if (!write_metadata(slicer_legacy_metadata_block->raw_data)) |
| 895 | return EResult::WriteError; |
| 896 | if (!write_line("; prusaslicer_config = end\n\n")) |
| 897 | return EResult::WriteError; |
| 898 | } |
| 899 | |
| 900 | return EResult::Success; |
| 901 | } |
| 902 | |
| 903 | } // namespace core |
| 904 | } // namespace bgcode |