Merge with master

This commit is contained in:
Lukas Matena 2018-02-21 13:22:51 +01:00
commit de92f45eaf
125 changed files with 38665 additions and 4069 deletions

View file

@ -311,5 +311,6 @@ One may save compilation time by compiling just what Slic3r needs.
./bootstrap.sh --with-libraries=system,filesystem,thread,log,locale,regex
The -fPIC flag is required on Linux to make the static libraries rellocatable,
so they could be embedded into a shared library.
./bjam -a link=static variant=release threading=multi cxxflags=-fPIC cflags=-fPIC
It is important to disable boost.locale.icu=off when compiling the static boost library.
./bjam -a link=static variant=release threading=multi boost.locale.icu=off --with-locale cxxflags=-fPIC cflags=-fPIC
To install on Linux to /usr/local/..., run the line above with the additional install keyword and with sudo.

View file

@ -43,6 +43,7 @@ use FindBin;
# Let the XS module know where the GUI resources reside.
set_resources_dir(decode_path($FindBin::Bin) . (($^O eq 'darwin') ? '/../Resources' : '/resources'));
set_var_dir(resources_dir() . "/icons");
set_local_dir(resources_dir() . "/localization/");
use Moo 1.003001;
@ -136,6 +137,7 @@ sub thread_cleanup {
*Slic3r::Flow::DESTROY = sub {};
*Slic3r::GCode::DESTROY = sub {};
*Slic3r::GCode::PlaceholderParser::DESTROY = sub {};
*Slic3r::GCode::PreviewData::DESTROY = sub {};
*Slic3r::GCode::Sender::DESTROY = sub {};
*Slic3r::Geometry::BoundingBox::DESTROY = sub {};
*Slic3r::Geometry::BoundingBoxf::DESTROY = sub {};

View file

@ -31,7 +31,6 @@ use Slic3r::GUI::ProgressStatusBar;
use Slic3r::GUI::OptionsGroup;
use Slic3r::GUI::OptionsGroup::Field;
use Slic3r::GUI::SystemInfo;
use Slic3r::GUI::Tab;
our $have_OpenGL = eval "use Slic3r::GUI::3DScene; 1";
our $have_LWP = eval "use LWP::UserAgent; 1";
@ -41,16 +40,17 @@ use Wx::Event qw(EVT_IDLE EVT_COMMAND EVT_MENU);
use base 'Wx::App';
use constant FILE_WILDCARDS => {
known => 'Known files (*.stl, *.obj, *.amf, *.xml, *.prusa)|*.stl;*.STL;*.obj;*.OBJ;*.amf;*.AMF;*.xml;*.XML;*.prusa;*.PRUSA',
known => 'Known files (*.stl, *.obj, *.amf, *.xml, *.3mf, *.prusa)|*.stl;*.STL;*.obj;*.OBJ;*.amf;*.AMF;*.xml;*.XML;*.3mf;*.3MF;*.prusa;*.PRUSA',
stl => 'STL files (*.stl)|*.stl;*.STL',
obj => 'OBJ files (*.obj)|*.obj;*.OBJ',
amf => 'AMF files (*.amf)|*.amf;*.AMF;*.xml;*.XML',
threemf => '3MF files (*.3mf)|*.3mf;*.3MF',
prusa => 'Prusa Control files (*.prusa)|*.prusa;*.PRUSA',
ini => 'INI files *.ini|*.ini;*.INI',
gcode => 'G-code files (*.gcode, *.gco, *.g, *.ngc)|*.gcode;*.GCODE;*.gco;*.GCO;*.g;*.G;*.ngc;*.NGC',
svg => 'SVG files *.svg|*.svg;*.SVG',
};
use constant MODEL_WILDCARD => join '|', @{&FILE_WILDCARDS}{qw(known stl obj amf prusa)};
use constant MODEL_WILDCARD => join '|', @{&FILE_WILDCARDS}{qw(known stl obj amf threemf prusa)};
# Datadir provided on the command line.
our $datadir;
@ -67,6 +67,10 @@ our $medium_font = Wx::SystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
$medium_font->SetPointSize(12);
our $grey = Wx::Colour->new(200,200,200);
# Events to be sent from a C++ menu implementation:
# 1) To inform about a change of the application language.
our $LANGUAGE_CHANGE_EVENT = Wx::NewEventType;
sub OnInit {
my ($self) = @_;
@ -80,6 +84,7 @@ sub OnInit {
# Mac: "~/Library/Application Support/Slic3r"
Slic3r::set_data_dir($datadir || Wx::StandardPaths::Get->GetUserDataDir);
Slic3r::GUI::set_wxapp($self);
Slic3r::GUI::load_language();
$self->{notifier} = Slic3r::GUI::Notifier->new;
$self->{app_config} = Slic3r::GUI::AppConfig->new;
@ -114,10 +119,12 @@ sub OnInit {
# If set, the "Controller" tab for the control of the printer over serial line and the serial port settings are hidden.
no_controller => $self->{app_config}->get('no_controller'),
no_plater => $no_plater,
lang_ch_event => $LANGUAGE_CHANGE_EVENT,
);
$self->SetTopWindow($frame);
EVT_IDLE($frame, sub {
#EVT_IDLE($frame, sub {
EVT_IDLE($self->{mainframe}, sub {
while (my $cb = shift @cb) {
$cb->();
}
@ -132,10 +139,42 @@ sub OnInit {
$self->{mainframe}->config_wizard(1);
});
}
# The following event is emited by the C++ menu implementation of application language change.
EVT_COMMAND($self, -1, $LANGUAGE_CHANGE_EVENT, sub{
$self->recreate_GUI;
});
return 1;
}
sub recreate_GUI{
my ($self) = @_;
my $topwindow = $self->GetTopWindow();
$self->{mainframe} = my $frame = Slic3r::GUI::MainFrame->new(
# If set, the "Controller" tab for the control of the printer over serial line and the serial port settings are hidden.
no_controller => $self->{app_config}->get('no_controller'),
no_plater => $no_plater,
lang_ch_event => $LANGUAGE_CHANGE_EVENT,
);
if($topwindow)
{
$self->SetTopWindow($frame);
$topwindow->Destroy;
}
my $run_wizard = 1 if $self->{preset_bundle}->has_defauls_only;
if ($run_wizard) {
# On OSX the UI was not initialized correctly if the wizard was called
# before the UI was up and running.
$self->CallAfter(sub {
# Run the config wizard, don't offer the "reset user profile" checkbox.
$self->{mainframe}->config_wizard(1);
});
}
}
sub about {
my ($self) = @_;
my $about = Slic3r::GUI::AboutDialog->new(undef);

View file

@ -4,7 +4,7 @@
# Slic3r::GUI::3DScene;
#
# Slic3r::GUI::Plater::3D derives from Slic3r::GUI::3DScene,
# Slic3r::GUI::Plater::3DPreview, Slic3r::GUI::Plater::3DToolpaths,
# Slic3r::GUI::Plater::3DPreview,
# Slic3r::GUI::Plater::ObjectCutDialog and Slic3r::GUI::Plater::ObjectPartsPanel
# own $self->{canvas} of the Slic3r::GUI::3DScene type.
#
@ -66,8 +66,12 @@ __PACKAGE__->mk_accessors( qw(_quat _dirty init
_camera_target
_camera_distance
_zoom
_legend_enabled
_apply_zoom_to_volumes_filter
) );
use constant TRACKBALLSIZE => 0.8;
use constant TURNTABLE_MODE => 1;
use constant GROUND_Z => -0.02;
@ -137,7 +141,9 @@ sub new {
$self->_stheta(45);
$self->_sphi(45);
$self->_zoom(1);
$self->_legend_enabled(0);
$self->use_plain_shader(0);
$self->_apply_zoom_to_volumes_filter(0);
# Collection of GLVolume objects
$self->volumes(Slic3r::GUI::_3DScene::GLVolume::Collection->new);
@ -209,6 +215,11 @@ sub new {
return $self;
}
sub set_legend_enabled {
my ($self, $value) = @_;
$self->_legend_enabled($value);
}
sub Destroy {
my ($self) = @_;
$self->{layer_height_edit_timer}->Stop;
@ -695,14 +706,18 @@ sub zoom_to_volume {
sub zoom_to_volumes {
my ($self) = @_;
$self->_apply_zoom_to_volumes_filter(1);
$self->zoom_to_bounding_box($self->volumes_bounding_box);
$self->_apply_zoom_to_volumes_filter(0);
}
sub volumes_bounding_box {
my ($self) = @_;
my $bb = Slic3r::Geometry::BoundingBoxf3->new;
$bb->merge($_->transformed_bounding_box) for @{$self->volumes};
foreach my $v (@{$self->volumes}) {
$bb->merge($v->transformed_bounding_box) if (! $self->_apply_zoom_to_volumes_filter || $v->zoom_to_volumes);
}
return $bb;
}
@ -1316,6 +1331,9 @@ sub Render {
glDisable(GL_BLEND);
}
# draw gcode preview legend
$self->draw_legend;
$self->draw_active_object_annotations;
$self->SwapBuffers();
@ -1449,12 +1467,18 @@ sub _variable_layer_thickness_load_reset_image {
# Paint the tooltip.
sub _render_image {
my ($self, $image, $l, $r, $b, $t) = @_;
$self->_render_texture($image->{texture_id}, $l, $r, $b, $t);
}
sub _render_texture {
my ($self, $tex_id, $l, $r, $b, $t) = @_;
glColor4f(1.,1.,1.,1.);
glDisable(GL_LIGHTING);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, $image->{texture_id});
glBindTexture(GL_TEXTURE_2D, $tex_id);
glBegin(GL_QUADS);
glTexCoord2d(0.,1.); glVertex3f($l, $b, 0);
glTexCoord2d(1.,1.); glVertex3f($r, $b, 0);
@ -1579,6 +1603,38 @@ sub draw_active_object_annotations {
glEnable(GL_DEPTH_TEST);
}
sub draw_legend {
my ($self) = @_;
if ($self->_legend_enabled)
{
# If the legend texture has not been loaded into the GPU, do it now.
my $tex_id = Slic3r::GUI::_3DScene::finalize_legend_texture;
if ($tex_id > 0)
{
my $tex_w = Slic3r::GUI::_3DScene::get_legend_texture_width;
my $tex_h = Slic3r::GUI::_3DScene::get_legend_texture_height;
if (($tex_w > 0) && ($tex_h > 0))
{
glDisable(GL_DEPTH_TEST);
glPushMatrix();
glLoadIdentity();
my ($cw, $ch) = $self->GetSizeWH;
my $l = (-0.5 * $cw) / $self->_zoom;
my $t = (0.5 * $ch) / $self->_zoom;
my $r = $l + $tex_w / $self->_zoom;
my $b = $t - $tex_h / $self->_zoom;
$self->_render_texture($tex_id, $l, $r, $b, $t);
glPopMatrix();
glEnable(GL_DEPTH_TEST);
}
}
}
}
sub opengl_info
{
my ($self, %params) = @_;
@ -1979,9 +2035,20 @@ sub load_wipe_tower_toolpaths {
if ($print->step_done(STEP_WIPE_TOWER));
}
sub load_gcode_preview {
my ($self, $print, $gcode_preview_data, $colors) = @_;
$self->SetCurrent($self->GetContext) if $self->UseVBOs;
Slic3r::GUI::_3DScene::load_gcode_preview($print, $gcode_preview_data, $self->volumes, $colors, $self->UseVBOs);
}
sub set_toolpaths_range {
my ($self, $min_z, $max_z) = @_;
$self->volumes->set_range($min_z, $max_z);
}
sub reset_legend_texture {
Slic3r::GUI::_3DScene::reset_legend_texture();
}
1;

View file

@ -11,13 +11,23 @@ use List::Util qw(min first);
use Slic3r::Geometry qw(X Y);
use Wx qw(:frame :bitmap :id :misc :notebook :panel :sizer :menu :dialog :filedialog
:font :icon wxTheApp);
use Wx::Event qw(EVT_CLOSE EVT_MENU EVT_NOTEBOOK_PAGE_CHANGED);
use Wx::Event qw(EVT_CLOSE EVT_COMMAND EVT_MENU EVT_NOTEBOOK_PAGE_CHANGED);
use base 'Wx::Frame';
our $qs_last_input_file;
our $qs_last_output_file;
our $last_config;
# Events to be sent from a C++ Tab implementation:
# 1) To inform about a change of a configuration value.
our $VALUE_CHANGE_EVENT = Wx::NewEventType;
# 2) To inform about a preset selection change or a "modified" status change.
our $PRESETS_CHANGED_EVENT = Wx::NewEventType;
# 3) To inform about a click on Browse button
our $BUTTON_BROWSE_EVENT = Wx::NewEventType;
# 4) To inform about a click on Test button
our $BUTTON_TEST_EVENT = Wx::NewEventType;
sub new {
my ($class, %params) = @_;
@ -37,6 +47,7 @@ sub new {
$self->{no_controller} = $params{no_controller};
$self->{no_plater} = $params{no_plater};
$self->{loaded} = 0;
$self->{lang_ch_event} = $params{lang_ch_event};
# initialize tabpanel and menubar
$self->_init_tabpanel;
@ -106,33 +117,41 @@ sub _init_tabpanel {
$panel->AddPage($self->{controller} = Slic3r::GUI::Controller->new($panel), "Controller");
}
}
$self->{options_tabs} = {};
for my $tab_name (qw(print filament printer)) {
my $tab;
$tab = $self->{options_tabs}{$tab_name} = ("Slic3r::GUI::Tab::" . ucfirst $tab_name)->new(
$panel,
no_controller => $self->{no_controller});
# Callback to be executed after any of the configuration fields (Perl class Slic3r::GUI::OptionsGroup::Field) change their value.
$tab->on_value_change(sub {
my ($opt_key, $value) = @_;
my $config = $tab->{presets}->get_current_preset->config;
if ($self->{plater}) {
$self->{plater}->on_config_change($config); # propagate config change events to the plater
$self->{plater}->on_extruders_change($value) if $opt_key eq 'extruders_count';
#TODO this is an example of a Slic3r XS interface call to add a new preset editor page to the main view.
# The following event is emited by the C++ Tab implementation on config value change.
EVT_COMMAND($self, -1, $VALUE_CHANGE_EVENT, sub {
my ($self, $event) = @_;
my $str = $event->GetString;
my ($opt_key, $name) = ($str =~ /(.*) (.*)/);
#print "VALUE_CHANGE_EVENT: ", $opt_key, "\n";
my $tab = Slic3r::GUI::get_preset_tab($name);
my $config = $tab->get_config;
if ($self->{plater}) {
$self->{plater}->on_config_change($config); # propagate config change events to the plater
if ($opt_key eq 'extruders_count'){
my $value = $event->GetInt();
$self->{plater}->on_extruders_change($value);
}
# don't save while loading for the first time
$self->config->save($Slic3r::GUI::autosave) if $Slic3r::GUI::autosave && $self->{loaded};
});
# Install a callback for the tab to update the platter and print controller presets, when
# a preset changes at Slic3r::GUI::Tab.
$tab->on_presets_changed(sub {
if ($self->{plater}) {
# Update preset combo boxes (Print settings, Filament, Printer) from their respective tabs.
$self->{plater}->update_presets($tab_name, @_);
}
# don't save while loading for the first time
$self->config->save($Slic3r::GUI::autosave) if $Slic3r::GUI::autosave && $self->{loaded};
});
# The following event is emited by the C++ Tab implementation on preset selection,
# or when the preset's "modified" status changes.
EVT_COMMAND($self, -1, $PRESETS_CHANGED_EVENT, sub {
my ($self, $event) = @_;
my $tab_name = $event->GetString;
my $tab = Slic3r::GUI::get_preset_tab($tab_name);
if ($self->{plater}) {
# Update preset combo boxes (Print settings, Filament, Printer) from their respective tabs.
my $presets = $tab->get_presets;
if (defined $presets){
my $reload_dependent_tabs = $tab->get_dependent_tabs;
$self->{plater}->update_presets($tab_name, $reload_dependent_tabs, $presets);
if ($tab_name eq 'printer') {
# Printer selected at the Printer tab, update "compatible" marks at the print and filament selectors.
my ($presets, $reload_dependent_tabs) = @_;
for my $tab_name_other (qw(print filament)) {
# If the printer tells us that the print or filament preset has been switched or invalidated,
# refresh the print or filament tab page. Otherwise just refresh the combo box.
@ -141,23 +160,76 @@ sub _init_tabpanel {
$self->{options_tabs}{$tab_name_other}->$update_action;
}
# Update the controller printers.
$self->{controller}->update_presets(@_) if $self->{controller};
$self->{controller}->update_presets($presets) if $self->{controller};
}
$self->{plater}->on_config_change($tab->{presets}->get_current_preset->config);
$self->{plater}->on_config_change($tab->get_config);
}
});
# Load the currently selected preset into the GUI, update the preset selection box.
$tab->load_current_preset;
$panel->AddPage($tab, $tab->title);
}
}
});
# The following event is emited by the C++ Tab implementation ,
# when the Browse button was clicked
EVT_COMMAND($self, -1, $BUTTON_BROWSE_EVENT, sub {
my ($self, $event) = @_;
my $msg = $event->GetString;
print "BUTTON_BROWSE_EVENT: ", $msg, "\n";
#TODO this is an example of a Slic3r XS interface call to add a new preset editor page to the main view.
# Slic3r::GUI::create_preset_tab("print");
# look for devices
my $entries;
{
my $res = Net::Bonjour->new('http');
$res->discover;
$entries = [ $res->entries ];
}
if (@{$entries}) {
my $dlg = Slic3r::GUI::BonjourBrowser->new($self, $entries);
my $tab = Slic3r::GUI::get_preset_tab("printer");
$tab->load_key_value('octoprint_host', $dlg->GetValue . ":" . $dlg->GetPort)
if $dlg->ShowModal == wxID_OK;
} else {
Wx::MessageDialog->new($self, 'No Bonjour device found', 'Device Browser', wxOK | wxICON_INFORMATION)->ShowModal;
}
});
# The following event is emited by the C++ Tab implementation ,
# when the Test button was clicked
EVT_COMMAND($self, -1, $BUTTON_TEST_EVENT, sub {
my ($self, $event) = @_;
my $msg = $event->GetString;
print "BUTTON_TEST_EVENT: ", $msg, "\n";
my $ua = LWP::UserAgent->new;
$ua->timeout(10);
my $config = Slic3r::GUI::get_preset_tab("printer")->get_config;
my $res = $ua->get(
"http://" . $config->octoprint_host . "/api/version",
'X-Api-Key' => $config->octoprint_apikey,
);
if ($res->is_success) {
Slic3r::GUI::show_info($self, "Connection to OctoPrint works correctly.", "Success!");
} else {
Slic3r::GUI::show_error($self,
"I wasn't able to connect to OctoPrint (" . $res->status_line . "). "
. "Check hostname and OctoPrint version (at least 1.1.0 is required).");
}
});
# A variable to inform C++ Tab implementation about disabling of Browse button
$self->{is_disabled_button_browse} = (!eval "use Net::Bonjour; 1") ? 1 : 0 ;
# A variable to inform C++ Tab implementation about user_agent
$self->{is_user_agent} = (eval "use LWP::UserAgent; 1") ? 1 : 0 ;
Slic3r::GUI::create_preset_tabs(wxTheApp->{preset_bundle}, wxTheApp->{app_config},
$self->{no_controller}, $self->{is_disabled_button_browse},
$self->{is_user_agent},
$VALUE_CHANGE_EVENT, $PRESETS_CHANGED_EVENT,
$BUTTON_BROWSE_EVENT, $BUTTON_TEST_EVENT);
$self->{options_tabs} = {};
for my $tab_name (qw(print filament printer)) {
$self->{options_tabs}{$tab_name} = Slic3r::GUI::get_preset_tab("$tab_name");
}
if ($self->{plater}) {
$self->{plater}->on_select_preset(sub {
my ($group, $name) = @_;
$self->{options_tabs}{$group}->select_preset($name);
$self->{options_tabs}{$group}->select_preset($name);
});
# load initial config
my $full_config = wxTheApp->{preset_bundle}->full_config;
@ -244,6 +316,9 @@ sub _init_menubar {
$self->_append_menu_item($self->{plater_menu}, "Export plate as AMF...", 'Export current plate as AMF', sub {
$plater->export_amf;
}, undef, 'brick_go.png');
$self->_append_menu_item($self->{plater_menu}, "Export plate as 3MF...", 'Export current plate as 3MF', sub {
$plater->export_3mf;
}, undef, 'brick_go.png');
$self->{object_menu} = $self->{plater}->object_menu;
$self->on_plater_selection_changed(0);
@ -341,9 +416,11 @@ sub _init_menubar {
$menubar->Append($self->{object_menu}, "&Object") if $self->{object_menu};
$menubar->Append($windowMenu, "&Window");
$menubar->Append($self->{viewMenu}, "&View") if $self->{viewMenu};
# Add an optional debug menu
# (Select application language from the list of installed languages)
# In production code, the add_debug_menu() call should do nothing.
Slic3r::GUI::add_debug_menu($menubar, $self->{lang_ch_event});
$menubar->Append($helpMenu, "&Help");
# Add an optional debug menu. In production code, the add_debug_menu() call should do nothing.
Slic3r::GUI::add_debug_menu($menubar);
$self->SetMenuBar($menubar);
}
}
@ -374,7 +451,7 @@ sub quick_slice {
# select input file
my $input_file;
if (!$params{reslice}) {
my $dialog = Wx::FileDialog->new($self, 'Choose a file to slice (STL/OBJ/AMF/PRUSA):',
my $dialog = Wx::FileDialog->new($self, 'Choose a file to slice (STL/OBJ/AMF/3MF/PRUSA):',
wxTheApp->{app_config}->get_last_dir, "",
&Slic3r::GUI::MODEL_WILDCARD, wxFD_OPEN | wxFD_FILE_MUST_EXIST);
if ($dialog->ShowModal != wxID_OK) {
@ -596,7 +673,7 @@ sub load_configbundle {
wxTheApp->{app_config}->update_config_dir(dirname($file));
my $presets_imported = 0;
eval { $presets_imported = wxTheApp->{preset_bundle}->load_configbundle($file, $reset_user_profile ? 1 : 0); };
eval { $presets_imported = wxTheApp->{preset_bundle}->load_configbundle($file); };
Slic3r::GUI::catch_error($self) and return;
# Load the currently selected preset into the GUI, update the preset selection box.
@ -611,7 +688,7 @@ sub load_configbundle {
# Load a provied DynamicConfig into the Print / Filament / Printer tabs, thus modifying the active preset.
# Also update the platter with the new presets.
sub load_config {
my ($self, $config) = @_;
my ($self, $config) = @_;
$_->load_config($config) foreach values %{$self->{options_tabs}};
$self->{plater}->on_config_change($config) if $self->{plater};
}
@ -661,7 +738,7 @@ sub check_unsaved_changes {
my @dirty = ();
foreach my $tab (values %{$self->{options_tabs}}) {
push @dirty, $tab->title if $tab->{presets}->current_is_dirty;
push @dirty, $tab->title if $tab->current_preset_is_dirty;
}
if (@dirty) {

View file

@ -158,7 +158,9 @@ sub _build_field {
my $opt_id = $opt->opt_id;
my $on_change = sub {
#! This function will be called from Field.
my ($opt_id, $value) = @_;
#! Call OptionGroup._on_change(...)
$self->_on_change($opt_id, $value)
unless $self->_disabled;
};
@ -213,6 +215,8 @@ sub _build_field {
}
return undef if !$field;
#! setting up a function that will be triggered when the field changes
#! think of it as $field->on_change = ($on_change)
$field->on_change($on_change);
$field->on_kill_focus($on_kill_focus);
$self->_fields->{$opt_id} = $field;

View file

@ -60,10 +60,14 @@ sub new {
$self->{print} = Slic3r::Print->new;
# List of Perl objects Slic3r::GUI::Plater::Object, representing a 2D preview of the platter.
$self->{objects} = [];
$self->{gcode_preview_data} = Slic3r::GCode::PreviewData->new;
$self->{print}->set_status_cb(sub {
my ($percent, $message) = @_;
Wx::PostEvent($self, Wx::PlThreadEvent->new(-1, $PROGRESS_BAR_EVENT, shared_clone([$percent, $message])));
my $event = Wx::CommandEvent->new($PROGRESS_BAR_EVENT);
$event->SetString($message);
$event->SetInt($percent);
Wx::PostEvent($self, $event);
});
# Initialize preview notebook
@ -137,7 +141,7 @@ sub new {
# Initialize 3D toolpaths preview
if ($Slic3r::GUI::have_OpenGL) {
$self->{preview3D} = Slic3r::GUI::Plater::3DPreview->new($self->{preview_notebook}, $self->{print}, $self->{config});
$self->{preview3D} = Slic3r::GUI::Plater::3DPreview->new($self->{preview_notebook}, $self->{print}, $self->{gcode_preview_data}, $self->{config});
$self->{preview3D}->canvas->on_viewport_changed(sub {
$self->{canvas3D}->set_viewport_from_scene($self->{preview3D}->canvas);
});
@ -153,8 +157,15 @@ sub new {
EVT_NOTEBOOK_PAGE_CHANGED($self, $self->{preview_notebook}, sub {
my $preview = $self->{preview_notebook}->GetCurrentPage;
$self->{preview3D}->load_print(1) if ($preview == $self->{preview3D});
$preview->OnActivate if $preview->can('OnActivate');
if ($preview == $self->{preview3D})
{
$self->{preview3D}->canvas->set_legend_enabled(1);
$self->{preview3D}->load_print(1);
} else {
$self->{preview3D}->canvas->set_legend_enabled(0);
}
$preview->OnActivate if $preview->can('OnActivate');
});
# toolbar for object manipulation
@ -307,23 +318,22 @@ sub new {
EVT_COMMAND($self, -1, $PROGRESS_BAR_EVENT, sub {
my ($self, $event) = @_;
my ($percent, $message) = @{$event->GetData};
$self->on_progress_event($percent, $message);
$self->on_progress_event($event->GetInt, $event->GetString);
});
EVT_COMMAND($self, -1, $ERROR_EVENT, sub {
my ($self, $event) = @_;
Slic3r::GUI::show_error($self, @{$event->GetData});
Slic3r::GUI::show_error($self, $event->GetString);
});
EVT_COMMAND($self, -1, $EXPORT_COMPLETED_EVENT, sub {
my ($self, $event) = @_;
$self->on_export_completed($event->GetData);
$self->on_export_completed($event->GetInt);
});
EVT_COMMAND($self, -1, $PROCESS_COMPLETED_EVENT, sub {
my ($self, $event) = @_;
$self->on_process_completed($event->GetData);
$self->on_process_completed($event->GetInt ? undef : $event->GetString);
});
{
@ -365,7 +375,9 @@ sub new {
my $text = Wx::StaticText->new($self, -1, "$group_labels{$group}:", wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT);
$text->SetFont($Slic3r::GUI::small_font);
my $choice = Wx::BitmapComboBox->new($self, -1, "", wxDefaultPosition, wxDefaultSize, [], wxCB_READONLY);
EVT_LEFT_DOWN($choice, sub { $self->filament_color_box_lmouse_down(0, @_); } );
if ($group eq 'filament') {
EVT_LEFT_DOWN($choice, sub { $self->filament_color_box_lmouse_down(0, @_); } );
}
$self->{preset_choosers}{$group} = [$choice];
# setup the listener
EVT_COMBOBOX($choice, $choice, sub {
@ -431,9 +443,10 @@ sub new {
$print_info_sizer->Add($grid_sizer, 0, wxEXPAND);
my @info = (
fil_m => "Used Filament (m)",
fil_mm3 => "Used Filament (mm^3)",
fil_mm3 => "Used Filament (mm\x{00B3})",
fil_g => "Used Filament (g)",
cost => "Cost",
time => "Estimated printing time",
);
while (my $field = shift @info) {
my $label = shift @info;
@ -609,7 +622,7 @@ sub load_files {
# One of the files is potentionally a bundle of files. Don't bundle them, but load them one by one.
# Only bundle .stls or .objs if the printer has multiple extruders.
my $one_by_one = (@$nozzle_dmrs <= 1) || (@$input_files == 1) ||
defined(first { $_ =~ /.[aA][mM][fF]$/ || $_ =~ /.3[mM][fF]$/ || $_ =~ /.[pP][rR][uI][sS][aA]$/ } @$input_files);
defined(first { $_ =~ /.[aA][mM][fF]$/ || $_ =~ /.[aA][mM][fF].[xX][mM][lL]$/ || $_ =~ /.[zZ][iI][pP].[aA][mM][fF]$/ || $_ =~ /.3[mM][fF]$/ || $_ =~ /.[pP][rR][uI][sS][aA]$/ } @$input_files);
my $process_dialog = Wx::ProgressDialog->new('Loading…', "Processing input file\n" . basename($input_files->[0]), 100, $self, 0);
$process_dialog->Pulse;
@ -627,8 +640,19 @@ sub load_files {
my $input_file = $input_files->[$i];
$process_dialog->Update(100. * $i / @$input_files, "Processing input file\n" . basename($input_file));
my $model = eval { Slic3r::Model->read_from_file($input_file, 0) };
Slic3r::GUI::show_error($self, $@) if $@;
my $model;
if (($input_file =~ /.3[mM][fF]$/) || ($input_file =~ /.[zZ][iI][pP].[aA][mM][fF]$/))
{
$model = eval { Slic3r::Model->read_from_archive($input_file, wxTheApp->{preset_bundle}, 0) };
Slic3r::GUI::show_error($self, $@) if $@;
$_->load_current_preset for (values %{$self->GetFrame->{options_tabs}});
wxTheApp->{app_config}->update_config_dir(dirname($input_file));
}
else
{
$model = eval { Slic3r::Model->read_from_file($input_file, 0) };
Slic3r::GUI::show_error($self, $@) if $@;
}
next if ! defined $model;
@ -1148,6 +1172,7 @@ sub async_apply_config {
# Reset preview canvases. If the print has been invalidated, the preview canvases will be cleared.
# Otherwise they will be just refreshed.
if ($invalidated) {
$self->{gcode_preview_data}->reset;
$self->{toolpaths2D}->reload_print if $self->{toolpaths2D};
$self->{preview3D}->reload_print if $self->{preview3D};
}
@ -1183,12 +1208,15 @@ sub start_background_process {
eval {
$self->{print}->process;
};
my $event = Wx::CommandEvent->new($PROCESS_COMPLETED_EVENT);
if ($@) {
Slic3r::debugf "Background process error: $@\n";
Wx::PostEvent($self, Wx::PlThreadEvent->new(-1, $PROCESS_COMPLETED_EVENT, $@));
$event->SetInt(0);
$event->SetString($@);
} else {
Wx::PostEvent($self, Wx::PlThreadEvent->new(-1, $PROCESS_COMPLETED_EVENT, undef));
$event->SetInt(1);
}
Wx::PostEvent($self, $event);
Slic3r::thread_cleanup();
});
Slic3r::debugf "Background processing started.\n";
@ -1364,14 +1392,21 @@ sub on_process_completed {
$self->{export_thread} = Slic3r::spawn_thread(sub {
eval {
$_thread_self->{print}->export_gcode(output_file => $_thread_self->{export_gcode_output_file});
$_thread_self->{print}->export_gcode(output_file => $_thread_self->{export_gcode_output_file}, gcode_preview_data => $_thread_self->{gcode_preview_data});
};
my $export_completed_event = Wx::CommandEvent->new($EXPORT_COMPLETED_EVENT);
if ($@) {
Wx::PostEvent($_thread_self, Wx::PlThreadEvent->new(-1, $ERROR_EVENT, shared_clone([ $@ ])));
Wx::PostEvent($_thread_self, Wx::PlThreadEvent->new(-1, $EXPORT_COMPLETED_EVENT, 0));
{
my $error_event = Wx::CommandEvent->new($ERROR_EVENT);
$error_event->SetString($@);
Wx::PostEvent($_thread_self, $error_event);
}
$export_completed_event->SetInt(0);
$export_completed_event->SetString($@);
} else {
Wx::PostEvent($_thread_self, Wx::PlThreadEvent->new(-1, $EXPORT_COMPLETED_EVENT, 1));
$export_completed_event->SetInt(1);
}
Wx::PostEvent($_thread_self, $export_completed_event);
Slic3r::thread_cleanup();
});
Slic3r::debugf "Background G-code export started.\n";
@ -1428,11 +1463,16 @@ sub on_export_completed {
$self->{"print_info_cost"}->SetLabel(sprintf("%.2f" , $self->{print}->total_cost));
$self->{"print_info_fil_g"}->SetLabel(sprintf("%.2f" , $self->{print}->total_weight));
$self->{"print_info_fil_mm3"}->SetLabel(sprintf("%.2f" , $self->{print}->total_extruded_volume));
$self->{"print_info_time"}->SetLabel($self->{print}->estimated_print_time);
$self->{"print_info_fil_m"}->SetLabel(sprintf("%.2f" , $self->{print}->total_used_filament / 1000));
$self->{"print_info_box_show"}->(1);
# this updates buttons status
$self->object_list_changed;
# refresh preview
$self->{toolpaths2D}->reload_print if $self->{toolpaths2D};
$self->{preview3D}->reload_print if $self->{preview3D};
}
sub do_print {
@ -1460,15 +1500,19 @@ sub send_gcode {
my $ua = LWP::UserAgent->new;
$ua->timeout(180);
my $enc_path = Slic3r::encode_path($self->{send_gcode_file});
my $res = $ua->post(
"http://" . $self->{config}->octoprint_host . "/api/files/local",
Content_Type => 'form-data',
'X-Api-Key' => $self->{config}->octoprint_apikey,
Content => [
# OctoPrint doesn't like Windows paths so we use basename()
# Also, since we need to read from filesystem we process it through encode_path()
file => [ $enc_path, basename($enc_path) ],
file => [
# On Windows, the path has to be encoded in local code page for perl to be able to open it.
Slic3r::encode_path($self->{send_gcode_file}),
# Remove the UTF-8 flag from the perl string, so the LWP::UserAgent can insert
# the UTF-8 encoded string into the request as a byte stream.
Slic3r::path_to_filename_raw($self->{send_gcode_file})
],
print => $self->{send_gcode_file_print} ? 1 : 0,
],
);
@ -1540,15 +1584,50 @@ sub export_amf {
return if !@{$self->{objects}};
# Ask user for a file name to write into.
my $output_file = $self->_get_export_file('AMF') or return;
$self->{model}->store_amf($output_file);
$self->statusbar->SetStatusText("AMF file exported to $output_file");
my $res = $self->{model}->store_amf($output_file, $self->{print});
if ($res)
{
$self->statusbar->SetStatusText("AMF file exported to $output_file");
}
else
{
$self->statusbar->SetStatusText("Error exporting AMF file $output_file");
}
}
sub export_3mf {
my ($self) = @_;
return if !@{$self->{objects}};
# Ask user for a file name to write into.
my $output_file = $self->_get_export_file('3MF') or return;
my $res = $self->{model}->store_3mf($output_file, $self->{print});
if ($res)
{
$self->statusbar->SetStatusText("3MF file exported to $output_file");
}
else
{
$self->statusbar->SetStatusText("Error exporting 3MF file $output_file");
}
}
# Ask user to select an output file for a given file format (STl, AMF, 3MF).
# Propose a default file name based on the 'output_filename_format' configuration value.
sub _get_export_file {
my ($self, $format) = @_;
my $suffix = $format eq 'STL' ? '.stl' : '.amf.xml';
my $suffix = '';
if ($format eq 'STL')
{
$suffix = '.stl';
}
elsif ($format eq 'AMF')
{
$suffix = '.zip.amf';
}
elsif ($format eq '3MF')
{
$suffix = '.3mf';
}
my $output_file = eval { $self->{print}->output_filepath($main::opt{output} // '') };
Slic3r::GUI::catch_error($self) and return undef;
$output_file =~ s/\.[gG][cC][oO][dD][eE]$/$suffix/;
@ -2057,8 +2136,8 @@ sub OnDropFiles {
# stop scalars leaking on older perl
# https://rt.perl.org/rt3/Public/Bug/Display.html?id=70602
@_ = ();
# only accept STL, OBJ and AMF files
return 0 if grep !/\.(?:[sS][tT][lL]|[oO][bB][jJ]|[aA][mM][fF](?:\.[xX][mM][lL])?|[pP][rR][uU][sS][aA])$/, @$filenames;
# only accept STL, OBJ, AMF, 3MF and PRUSA files
return 0 if grep !/\.(?:[sS][tT][lL]|[oO][bB][jJ]|[aA][mM][fF]|[3][mM][fF]|[aA][mM][fF].[xX][mM][lL]|[zZ][iI][pP].[aA][mM][lL]|[pP][rR][uU][sS][aA])$/, @$filenames;
$self->{window}->load_files($filenames);
}

View file

@ -4,20 +4,22 @@ use warnings;
use utf8;
use Slic3r::Print::State ':steps';
use Wx qw(:misc :sizer :slider :statictext :keycode wxWHITE);
use Wx::Event qw(EVT_SLIDER EVT_KEY_DOWN EVT_CHECKBOX);
use Wx qw(:misc :sizer :slider :statictext :keycode wxWHITE wxCB_READONLY);
use Wx::Event qw(EVT_SLIDER EVT_KEY_DOWN EVT_CHECKBOX EVT_CHOICE EVT_CHECKLISTBOX);
use base qw(Wx::Panel Class::Accessor);
__PACKAGE__->mk_accessors(qw(print enabled _loaded canvas slider_low slider_high single_layer));
__PACKAGE__->mk_accessors(qw(print gcode_preview_data enabled _loaded canvas slider_low slider_high single_layer auto_zoom));
sub new {
my $class = shift;
my ($parent, $print, $config) = @_;
my ($parent, $print, $gcode_preview_data, $config) = @_;
my $self = $class->SUPER::new($parent, -1, wxDefaultPosition);
$self->{config} = $config;
$self->{number_extruders} = 1;
# Show by feature type by default.
$self->{preferred_color_mode} = 'feature';
$self->auto_zoom(1);
# init GUI elements
my $canvas = Slic3r::GUI::3DScene->new($self);
@ -56,10 +58,35 @@ sub new {
$z_label_high->SetFont($Slic3r::GUI::small_font);
$self->single_layer(0);
$self->{color_by_extruder} = 0;
my $checkbox_singlelayer = $self->{checkbox_singlelayer} = Wx::CheckBox->new($self, -1, "1 Layer");
my $checkbox_color_by_extruder = $self->{checkbox_color_by_extruder} = Wx::CheckBox->new($self, -1, "Tool");
my $label_view_type = $self->{label_view_type} = Wx::StaticText->new($self, -1, "View");
my $choice_view_type = $self->{choice_view_type} = Wx::Choice->new($self, -1);
$choice_view_type->Append("Feature type");
$choice_view_type->Append("Height");
$choice_view_type->Append("Width");
$choice_view_type->Append("Speed");
$choice_view_type->Append("Tool");
$choice_view_type->SetSelection(0);
my $label_show_features = $self->{label_show_features} = Wx::StaticText->new($self, -1, "Show");
my $combochecklist_features = $self->{combochecklist_features} = Wx::ComboCtrl->new();
$combochecklist_features->Create($self, -1, "Feature types", wxDefaultPosition, [200, -1], wxCB_READONLY);
#FIXME If the following line is removed, the combo box popup list will not react to mouse clicks.
# On the other side, with this line the combo box popup cannot be closed by clicking on the combo button on Windows 10.
$combochecklist_features->UseAltPopupWindow();
$combochecklist_features->EnablePopupAnimation(0);
my $feature_text = "Feature types";
my $feature_items = "Perimeter|External perimeter|Overhang perimeter|Internal infill|Solid infill|Top solid infill|Bridge infill|Gap fill|Skirt|Support material|Support material interface|Wipe tower";
Slic3r::GUI::create_combochecklist($combochecklist_features, $feature_text, $feature_items, 1);
my $checkbox_travel = $self->{checkbox_travel} = Wx::CheckBox->new($self, -1, "Travel");
my $checkbox_retractions = $self->{checkbox_retractions} = Wx::CheckBox->new($self, -1, "Retractions");
my $checkbox_unretractions = $self->{checkbox_unretractions} = Wx::CheckBox->new($self, -1, "Unretractions");
my $checkbox_shells = $self->{checkbox_shells} = Wx::CheckBox->new($self, -1, "Shells");
my $hsizer = Wx::BoxSizer->new(wxHORIZONTAL);
my $vsizer = Wx::BoxSizer->new(wxVERTICAL);
my $vsizer_outer = Wx::BoxSizer->new(wxVERTICAL);
@ -72,11 +99,29 @@ sub new {
$hsizer->Add($vsizer, 0, wxEXPAND, 0);
$vsizer_outer->Add($hsizer, 3, wxALIGN_CENTER_HORIZONTAL, 0);
$vsizer_outer->Add($checkbox_singlelayer, 0, wxTOP | wxALIGN_CENTER_HORIZONTAL, 5);
$vsizer_outer->Add($checkbox_color_by_extruder, 0, wxTOP | wxALIGN_CENTER_HORIZONTAL, 5);
my $bottom_sizer = Wx::BoxSizer->new(wxHORIZONTAL);
$bottom_sizer->Add($label_view_type, 0, wxALIGN_CENTER_VERTICAL, 5);
$bottom_sizer->Add($choice_view_type, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5);
$bottom_sizer->AddSpacer(10);
$bottom_sizer->Add($label_show_features, 0, wxALIGN_CENTER_VERTICAL, 5);
$bottom_sizer->Add($combochecklist_features, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5);
$bottom_sizer->AddSpacer(20);
$bottom_sizer->Add($checkbox_travel, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5);
$bottom_sizer->AddSpacer(10);
$bottom_sizer->Add($checkbox_retractions, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5);
$bottom_sizer->AddSpacer(10);
$bottom_sizer->Add($checkbox_unretractions, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5);
$bottom_sizer->AddSpacer(10);
$bottom_sizer->Add($checkbox_shells, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5);
my $sizer = Wx::BoxSizer->new(wxHORIZONTAL);
$sizer->Add($canvas, 1, wxALL | wxEXPAND, 0);
$sizer->Add($vsizer_outer, 0, wxTOP | wxBOTTOM | wxEXPAND, 5);
my $main_sizer = Wx::BoxSizer->new(wxVERTICAL);
$main_sizer->Add($sizer, 1, wxALL | wxEXPAND, 0);
$main_sizer->Add($bottom_sizer, 0, wxALL | wxEXPAND, 0);
EVT_SLIDER($self, $slider_low, sub {
$slider_high->SetValue($slider_low->GetValue) if $self->single_layer;
@ -147,18 +192,73 @@ sub new {
$self->set_z_idx_high($slider_high->GetValue);
}
});
EVT_CHECKBOX($self, $checkbox_color_by_extruder, sub {
$self->{color_by_extruder} = $checkbox_color_by_extruder->GetValue();
$self->{preferred_color_mode} = $self->{color_by_extruder} ? 'tool' : 'feature';
EVT_CHOICE($self, $choice_view_type, sub {
my $selection = $choice_view_type->GetCurrentSelection();
$self->{preferred_color_mode} = ($selection == 4) ? 'tool' : 'feature';
$self->gcode_preview_data->set_type($selection);
$self->auto_zoom(0);
$self->reload_print;
$self->auto_zoom(1);
});
EVT_CHECKLISTBOX($self, $combochecklist_features, sub {
my $flags = Slic3r::GUI::combochecklist_get_flags($combochecklist_features);
$self->gcode_preview_data->set_extrusion_flags($flags);
$self->auto_zoom(0);
$self->refresh_print;
$self->auto_zoom(1);
});
EVT_CHECKBOX($self, $checkbox_travel, sub {
$self->gcode_preview_data->set_travel_visible($checkbox_travel->IsChecked());
$self->auto_zoom(0);
$self->refresh_print;
$self->auto_zoom(1);
});
EVT_CHECKBOX($self, $checkbox_retractions, sub {
$self->gcode_preview_data->set_retractions_visible($checkbox_retractions->IsChecked());
$self->auto_zoom(0);
$self->refresh_print;
$self->auto_zoom(1);
});
EVT_CHECKBOX($self, $checkbox_unretractions, sub {
$self->gcode_preview_data->set_unretractions_visible($checkbox_unretractions->IsChecked());
$self->auto_zoom(0);
$self->refresh_print;
$self->auto_zoom(1);
});
EVT_CHECKBOX($self, $checkbox_shells, sub {
$self->gcode_preview_data->set_shells_visible($checkbox_shells->IsChecked());
$self->auto_zoom(0);
$self->refresh_print;
$self->auto_zoom(1);
});
$self->SetSizer($sizer);
$self->SetSizer($main_sizer);
$self->SetMinSize($self->GetSize);
$sizer->SetSizeHints($self);
# init canvas
$self->print($print);
$self->gcode_preview_data($gcode_preview_data);
# sets colors for gcode preview extrusion roles
my @extrusion_roles_colors = (
'Perimeter' => 'FFA500',
'External perimeter' => 'FFFF66',
'Overhang perimeter' => '0000FF',
'Internal infill' => 'FF0000',
'Solid infill' => 'CD00CD',
'Top solid infill' => 'FF3333',
'Bridge infill' => '9999FF',
'Gap fill' => 'FFFFFF',
'Skirt' => '7F0000',
'Support material' => '00FF00',
'Support material interface' => '008000',
'Wipe tower' => 'B3E3AB',
);
$self->gcode_preview_data->set_extrusion_paths_colors(\@extrusion_roles_colors);
$self->show_hide_ui_elements('none');
$self->reload_print;
return $self;
@ -171,7 +271,19 @@ sub reload_print {
$self->_loaded(0);
if (! $self->IsShown && ! $force) {
$self->{reload_delayed} = 1;
# $self->{reload_delayed} = 1;
return;
}
$self->load_print;
}
sub refresh_print {
my ($self) = @_;
$self->_loaded(0);
if (! $self->IsShown) {
return;
}
@ -203,6 +315,9 @@ sub load_print {
$self->set_z_range(0,0);
$self->slider_low->Hide;
$self->slider_high->Hide;
$self->{z_label_low}->SetLabel("");
$self->{z_label_high}->SetLabel("");
$self->canvas->reset_legend_texture();
$self->canvas->Refresh; # clears canvas
return;
}
@ -232,21 +347,20 @@ sub load_print {
$self->slider_high->Show;
$self->Layout;
my $by_tool = $self->{color_by_extruder};
if ($self->{preferred_color_mode} eq 'tool_or_feature') {
# It is left to Slic3r to decide whether the print shall be colored by the tool or by the feature.
# Color by feature if it is a single extruder print.
my $extruders = $self->{print}->extruders;
$by_tool = scalar(@{$extruders}) > 1;
$self->{color_by_extruder} = $by_tool;
$self->{checkbox_color_by_extruder}->SetValue($by_tool);
my $type = (scalar(@{$extruders}) > 1) ? 4 : 0;
$self->gcode_preview_data->set_type($type);
$self->{choice_view_type}->SetSelection($type);
# If the ->SetSelection changed the following line, revert it to "decide yourself".
$self->{preferred_color_mode} = 'tool_or_feature';
}
# Collect colors per extruder.
# Leave it empty, if the print should be colored by a feature.
my @colors = ();
if ($by_tool) {
if (! $self->gcode_preview_data->empty() || $self->gcode_preview_data->type == 4) {
my @extruder_colors = @{$self->{config}->extruder_colour};
my @filament_colors = @{$self->{config}->filament_colour};
for (my $i = 0; $i <= $#extruder_colors; $i += 1) {
@ -258,18 +372,24 @@ sub load_print {
}
if ($self->IsShown) {
# load skirt and brim
$self->canvas->load_print_toolpaths($self->print, \@colors);
$self->canvas->load_wipe_tower_toolpaths($self->print, \@colors);
foreach my $object (@{$self->print->objects}) {
$self->canvas->load_print_object_toolpaths($object, \@colors);
# Show the objects in very transparent color.
#my @volume_ids = $self->canvas->load_object($object->model_object);
#$self->canvas->volumes->[$_]->color->[3] = 0.2 for @volume_ids;
if ($self->gcode_preview_data->empty) {
# load skirt and brim
$self->canvas->load_print_toolpaths($self->print, \@colors);
$self->canvas->load_wipe_tower_toolpaths($self->print, \@colors);
foreach my $object (@{$self->print->objects}) {
$self->canvas->load_print_object_toolpaths($object, \@colors);
# Show the objects in very transparent color.
#my @volume_ids = $self->canvas->load_object($object->model_object);
#$self->canvas->volumes->[$_]->color->[3] = 0.2 for @volume_ids;
}
$self->show_hide_ui_elements('simple');
} else {
$self->canvas->load_gcode_preview($self->print, $self->gcode_preview_data, \@colors);
$self->show_hide_ui_elements('full');
}
if ($self->auto_zoom) {
$self->canvas->zoom_to_volumes;
}
$self->canvas->zoom_to_volumes;
$self->_loaded(1);
}
@ -322,17 +442,27 @@ sub set_number_extruders {
my ($self, $number_extruders) = @_;
if ($self->{number_extruders} != $number_extruders) {
$self->{number_extruders} = $number_extruders;
my $by_tool = $number_extruders > 1;
$self->{color_by_extruder} = $by_tool;
$self->{checkbox_color_by_extruder}->SetValue($by_tool);
$self->{preferred_color_mode} = $by_tool ? 'tool_or_feature' : 'feature';
my $type = ($number_extruders > 1) ?
4 # color by a tool number
: 0; # color by a feature type
$self->{choice_view_type}->SetSelection($type);
$self->gcode_preview_data->set_type($type);
$self->{preferred_color_mode} = ($type == 4) ? 'tool_or_feature' : 'feature';
}
}
sub show_hide_ui_elements {
my ($self, $what) = @_;
my $method = ($what eq 'full') ? 'Enable' : 'Disable';
$self->{$_}->$method for qw(label_show_features combochecklist_features checkbox_travel checkbox_retractions checkbox_unretractions checkbox_shells);
$method = ($what eq 'none') ? 'Disable' : 'Enable';
$self->{$_}->$method for qw(label_view_type choice_view_type);
}
# Called by the Platter wxNotebook when this page is activated.
sub OnActivate {
my ($self) = @_;
$self->reload_print(1) if ($self->{reload_delayed});
# my ($self) = @_;
# $self->reload_print(1) if ($self->{reload_delayed});
}
1;

View file

@ -1,156 +0,0 @@
package Slic3r::GUI::Plater::3DToolpaths;
use strict;
use warnings;
use utf8;
use Slic3r::Print::State ':steps';
use Wx qw(:misc :sizer :slider :statictext wxWHITE);
use Wx::Event qw(EVT_SLIDER EVT_KEY_DOWN);
use base qw(Wx::Panel Class::Accessor);
__PACKAGE__->mk_accessors(qw(print enabled _loaded canvas slider));
sub new {
my $class = shift;
my ($parent, $print) = @_;
my $self = $class->SUPER::new($parent, -1, wxDefaultPosition);
# init GUI elements
my $canvas = Slic3r::GUI::3DScene->new($self);
$self->canvas($canvas);
my $slider = Wx::Slider->new(
$self, -1,
0, # default
0, # min
# we set max to a bogus non-zero value because the MSW implementation of wxSlider
# will skip drawing the slider if max <= min:
1, # max
wxDefaultPosition,
wxDefaultSize,
wxVERTICAL | wxSL_INVERSE,
);
$self->slider($slider);
my $z_label = $self->{z_label} = Wx::StaticText->new($self, -1, "", wxDefaultPosition,
[40,-1], wxALIGN_CENTRE_HORIZONTAL);
$z_label->SetFont($Slic3r::GUI::small_font);
my $vsizer = Wx::BoxSizer->new(wxVERTICAL);
$vsizer->Add($slider, 1, wxALL | wxEXPAND | wxALIGN_CENTER, 3);
$vsizer->Add($z_label, 0, wxALL | wxEXPAND | wxALIGN_CENTER, 3);
my $sizer = Wx::BoxSizer->new(wxHORIZONTAL);
$sizer->Add($canvas, 1, wxALL | wxEXPAND, 0);
$sizer->Add($vsizer, 0, wxTOP | wxBOTTOM | wxEXPAND, 5);
EVT_SLIDER($self, $slider, sub {
$self->set_z($self->{layers_z}[$slider->GetValue])
if $self->enabled;
});
EVT_KEY_DOWN($canvas, sub {
my ($s, $event) = @_;
if ($event->HasModifiers) {
$event->Skip;
} else {
my $key = $event->GetKeyCode;
if ($key == 85 || $key == 315) {
$slider->SetValue($slider->GetValue + 1);
$self->set_z($self->{layers_z}[$slider->GetValue]);
} elsif ($key == 68 || $key == 317) {
$slider->SetValue($slider->GetValue - 1);
$self->set_z($self->{layers_z}[$slider->GetValue]);
} else {
$event->Skip;
}
}
});
$self->SetSizer($sizer);
$self->SetMinSize($self->GetSize);
$sizer->SetSizeHints($self);
# init canvas
$self->print($print);
$self->reload_print;
return $self;
}
sub reload_print {
my ($self) = @_;
$self->canvas->reset_objects;
$self->_loaded(0);
$self->load_print;
}
sub load_print {
my ($self) = @_;
return if $self->_loaded;
# we require that there's at least one object and the posSlice step
# is performed on all of them (this ensures that _shifted_copies was
# populated and we know the number of layers)
if (!$self->print->object_step_done(STEP_SLICE)) {
$self->enabled(0);
$self->slider->Hide;
$self->canvas->Refresh; # clears canvas
return;
}
my $z_idx;
{
my %z = (); # z => 1
foreach my $object (@{$self->{print}->objects}) {
foreach my $layer (@{$object->layers}, @{$object->support_layers}) {
$z{$layer->print_z} = 1;
}
}
$self->enabled(1);
$self->{layers_z} = [ sort { $a <=> $b } keys %z ];
$self->slider->SetRange(0, scalar(@{$self->{layers_z}})-1);
if (($z_idx = $self->slider->GetValue) <= $#{$self->{layers_z}} && $self->slider->GetValue != 0) {
# use $z_idx
} else {
$self->slider->SetValue(scalar(@{$self->{layers_z}})-1);
$z_idx = @{$self->{layers_z}} ? -1 : undef;
}
$self->slider->Show;
$self->Layout;
}
if ($self->IsShown) {
# load skirt and brim
$self->canvas->load_print_toolpaths($self->print);
foreach my $object (@{$self->print->objects}) {
$self->canvas->load_print_object_toolpaths($object);
# Show the objects in very transparent color.
#my @volume_ids = $self->canvas->load_object($object->model_object);
#$self->canvas->volumes->[$_]->color->[3] = 0.2 for @volume_ids;
}
$self->canvas->zoom_to_volumes;
$self->_loaded(1);
}
$self->set_z($self->{layers_z}[$z_idx]);
}
sub set_z {
my ($self, $z) = @_;
return if !$self->enabled;
$self->{z_label}->SetLabel(sprintf '%.2f', $z);
$self->canvas->set_toolpaths_range(0, $z);
$self->canvas->Refresh if $self->IsShown;
}
sub set_bed_shape {
my ($self, $bed_shape) = @_;
$self->canvas->set_bed_shape($bed_shape);
}
1;

File diff suppressed because it is too large Load diff

View file

@ -81,13 +81,20 @@ sub export_gcode {
$self->status_cb->(90, "Exporting G-code" . ($output_file ? " to $output_file" : ""));
# The following line may die for multiple reasons.
Slic3r::GCode->new->do_export($self, $output_file);
my $gcode = Slic3r::GCode->new;
if (defined $params{gcode_preview_data}) {
$gcode->do_export_w_preview($self, $output_file, $params{gcode_preview_data});
} else {
$gcode->do_export($self, $output_file);
}
# run post-processing scripts
if (@{$self->config->post_process}) {
$self->status_cb->(95, "Running post-processing scripts");
$self->config->setenv;
for my $script (@{$self->config->post_process}) {
# Ignore empty post processing script lines.
next if $script =~ /^\s*$/;
Slic3r::debugf " '%s' '%s'\n", $script, $output_file;
# -x doesn't return true on Windows except for .exe files
if (($^O eq 'MSWin32') ? !(-e $script) : !(-x $script)) {

Binary file not shown.

File diff suppressed because it is too large Load diff

Binary file not shown.

File diff suppressed because it is too large Load diff

Binary file not shown.

View file

@ -0,0 +1,538 @@
# This file is distributed under the same license as the Slic3rPE package.
# Oleksandra Iushchenko <yusanka@gmail.com>, 2018.
#
msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2018-02-07 20:20+0100\n"
"PO-Revision-Date: 2018-02-08 01:41+0100\n"
"Last-Translator: Oleksandra Iushchenko <yusanka@gmail.com>\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.0.6\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n"
"%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"
"Language: uk\n"
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.cpp:81
msgid "Default"
msgstr "За замовчуванням"
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.cpp:109
msgid "Shape"
msgstr "Вигляд (Форма)"
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.cpp:116
msgid "Rectangular"
msgstr "Прямокутний"
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.cpp:132
msgid "Circular"
msgstr "Круговий"
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.cpp:141
msgid "Custom"
msgstr "Користувацький"
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.cpp:145
msgid "Load shape from STL..."
msgstr "Завантажте форму з STL ..."
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.cpp:190
msgid "Settings"
msgstr "Налаштування"
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.cpp:368
msgid "Choose a file to import bed shape from (STL/OBJ/AMF/PRUSA):"
msgstr "Виберіть файл, щоб імпортувати форму подложки з (STL/OBJ/AMF/PRUSA):"
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.cpp:385
msgid "Error! "
msgstr "Помилка! "
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.cpp:394
msgid "The selected file contains no geometry."
msgstr "Обратний файл не містить геометрії."
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.cpp:398
msgid ""
"The selected file contains several disjoint areas. This is not supported."
msgstr "Обраний файл містить декілька непересічних областей. Не підтримується."
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.hpp:45
msgid "Bed Shape"
msgstr "Форма полотна"
#: c:\src\Slic3r\xs\src\slic3r\GUI\GUI.cpp:318
msgid "Error"
msgstr "Помилка"
#: c:\src\Slic3r\xs\src\slic3r\GUI\GUI.cpp:323
msgid "Notice"
msgstr "Зауваження"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:51
msgid "Save current "
msgstr "Зберегти поточний "
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:52
msgid "Delete this preset"
msgstr "Видалити це налаштування"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:324
msgid "Layers and perimeters"
msgstr "Шари та периметри"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:325
msgid "Layer height"
msgstr "Висота шару"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:329
msgid "Vertical shells"
msgstr "Вертикальні оболонки"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:340
msgid "Horizontal shells"
msgstr "Горизонтальні оболонки"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:341
msgid "Solid layers"
msgstr "Тверді шари"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:346
msgid "Quality (slower slicing)"
msgstr "Якість (повільне нарізання)"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:353
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:367
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:460
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:463
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:839
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1122
msgid "Advanced"
msgstr "Розширений"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:357
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:358
msgid "Infill"
msgstr "Заповнення"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:363
msgid "Reducing printing time"
msgstr "Зниження часу друку"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:375
msgid "Skirt and brim"
msgstr "Плінтус та край"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:376
msgid "Skirt"
msgstr "Плінтус"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:382
msgid "Brim"
msgstr "Край"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:385
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:386
msgid "Support material"
msgstr "Опорний матеріал"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:391
msgid "Raft"
msgstr "Пліт"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:395
msgid "Options for support material and raft"
msgstr "Варіанти для опорного матеріалу та плоту"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:409
msgid "Speed"
msgstr "Швидкість"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:410
msgid "Speed for print moves"
msgstr "Швидкість друкарських рухів"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:422
msgid "Speed for non-print moves"
msgstr "Швидкість недрукарських рухів"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:425
msgid "Modifiers"
msgstr "Модифікатори"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:428
msgid "Acceleration control (advanced)"
msgstr "Контроль прискорення (розширений)"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:435
msgid "Autospeed (advanced)"
msgstr "Автоматична швидкість (розширена)"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:441
msgid "Multiple Extruders"
msgstr "Кілька екструдерів"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:442
msgid "Extruders"
msgstr "Екструдери"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:449
msgid "Ooze prevention"
msgstr "Профілактика ?Ooze?"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:453
msgid "Wipe tower"
msgstr "Вежа очищення"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:464
msgid "Extrusion width"
msgstr "Ширина екструзії"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:474
msgid "Overlap"
msgstr "Перекриття"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:477
msgid "Flow"
msgstr "Потік"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:480
msgid "Other"
msgstr "Інше"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:487
msgid "Output options"
msgstr "Параметри виводу"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:488
msgid "Sequential printing"
msgstr "Послідовне друкування"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:499
msgid "Output file"
msgstr "Вихідний файл"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:505
msgid "Post-processing scripts"
msgstr "Скрипти пост-обробки"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:511
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:512
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:867
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:868
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1165
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1166
msgid "Notes"
msgstr "Примітки"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:518
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:875
msgid "Dependencies"
msgstr "Залежності"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:519
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:876
msgid "Profile dependencies"
msgstr "Залежності профілю"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:794
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:795
msgid "Filament"
msgstr "Філаметн"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:802
msgid "Temperature"
msgstr "Температура"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:803
msgid "Extruder"
msgstr "Екструдер"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:808
msgid "Bed"
msgstr "Полотно"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:813
msgid "Cooling"
msgstr "Охолодження"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:814
msgid "Enable"
msgstr "Увімкнути"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:825
msgid "Fan settings"
msgstr "Налаштування вентилятора"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:834
msgid "Cooling thresholds"
msgstr "Пороги охолодження"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:840
msgid "Filament properties"
msgstr "Властивості філаменту"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:844
msgid "Print speed override"
msgstr "Перевизначення швидкості друку"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:854
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1128
msgid "Custom G-code"
msgstr "Користувацький G-код"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:855
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1129
msgid "Start G-code"
msgstr "Початок G-коду"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:861
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1135
msgid "End G-code"
msgstr "Закінчення G-коду"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:945
msgid "General"
msgstr "Загальне"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:946
msgid "Size and coordinates"
msgstr "Розмір і координати"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:948
msgid "Bed shape"
msgstr "Форма полотна"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:950
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1649
msgid "Set"
msgstr "Встановити"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:971
msgid "Capabilities"
msgstr "Можливості"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:998
msgid "USB/Serial connection"
msgstr "USB/послідовне з'єднання"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1004
msgid "Rescan serial ports"
msgstr "Сканувати ще раз послідовні порти"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1013
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1081
msgid "Test"
msgstr "Перевірити"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1026
msgid "Connection to printer works correctly."
msgstr "Підключення до принтера працює коректно."
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1026
msgid "Success!"
msgstr "Успіх!"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1029
msgid "Connection failed."
msgstr "Підключення не вдалося."
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1041
msgid "OctoPrint upload"
msgstr "Завантаження OctoPrint"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1044
msgid "Browse"
msgstr "Переглянути"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1119
msgid "Firmware"
msgstr "Прошивка"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1141
msgid "Before layer change G-code"
msgstr "G-код перед зміною шару "
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1147
msgid "After layer change G-code"
msgstr "G-код після зміни шару"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1153
msgid "Tool change G-code"
msgstr "G-код зміни інструменту "
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1159
msgid "Between objects G-code (for sequential printing)"
msgstr "G-код між об'єктами (для послідовного друку)"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1195
msgid "Extruder "
msgstr "Екструдер "
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1198
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.cpp:120
msgid "Size"
msgstr "Розмір"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1201
msgid "Layer height limits"
msgstr "Межі висоти шару"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1206
msgid "Position (for multi-extruder printers)"
msgstr "Позиція (для мульти-екструдерних принтерів)"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1209
msgid "Retraction"
msgstr "Утягування/відкликання"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1212
msgid "Only lift Z"
msgstr "Межі підняття Z"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1225
msgid ""
"Retraction when tool is disabled (advanced settings for multi-extruder "
"setups)"
msgstr ""
"Утягування/відкликання при відключенні інструмента (додаткові налаштування "
"для налагодження мульти-екструдерів)"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1229
msgid "Preview"
msgstr "Попередній перегляд"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1320
msgid ""
"The Wipe option is not available when using the Firmware Retraction mode.\n"
"\n"
"Shall I disable it in order to enable Firmware Retraction?"
msgstr ""
"Параметр «Очистити» недоступний при використанні режиму програмного "
"утягування/відкликання.\n"
"\n"
"Відключити його для увімкнення програмного утягування/відкликання?"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1322
msgid "Firmware Retraction"
msgstr "Програмне утягування/відкликання"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1565
msgid "The supplied name is empty. It can't be saved."
msgstr "Надане ім'я порожнє. Не вдається зберегти."
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1576
msgid "Something is wrong. It can't be saved."
msgstr "Щось не так. Не вдається зберегти."
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1593
msgid "remove"
msgstr "перемістити"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1593
msgid "delete"
msgstr "видалити"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1594
msgid "Are you sure you want to "
msgstr "Ви впевнені, що хочете "
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1594
msgid " the selected preset?"
msgstr "вибране налаштування?"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1595
msgid "Remove"
msgstr "Перемістити"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1595
msgid "Delete"
msgstr "Видалити"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1596
msgid " Preset"
msgstr " Налаштування"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1648
msgid "All"
msgstr "Всі"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1679
msgid "Select the printers this profile is compatible with."
msgstr "Оберіть принтери, сумісні з цим профілем."
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1680
msgid "Compatible printers"
msgstr "Сумісні принтери"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1763
msgid "Save "
msgstr "Зберегти "
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1763
msgid " as:"
msgstr " як:"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1797
msgid ""
"The supplied name is not valid; the following characters are not allowed:"
msgstr "Надане ім'я недійсне; такі символи не допускаються:"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.cpp:1800
msgid "The supplied name is not available."
msgstr "Надане ім'я недійсне."
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.hpp:178
msgid "Print Settings"
msgstr "Налаштування друку"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.hpp:198
msgid "Filament Settings"
msgstr "Налаштування філаменту"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.hpp:224
msgid "Printer Settings"
msgstr "Налаштування принтеру"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Tab.hpp:244
msgid "Save preset"
msgstr "Зберегти налаштування"
#: c:\src\Slic3r\xs\src\slic3r\GUI\Field.cpp:35
msgid "default"
msgstr "за замовчуванням"
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.cpp:121
msgid "Size in X and Y of the rectangular plate."
msgstr "Розмір прямокутної подложки за X та Y."
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.cpp:127
msgid "Origin"
msgstr "Початок координат"
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.cpp:128
msgid ""
"Distance of the 0,0 G-code coordinate from the front left corner of the "
"rectangle."
msgstr "Відстань координат 0,0 G-коду від нижнього лівого кута прямокутника."
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.cpp:135
msgid "mm"
msgstr "мм"
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.cpp:136
msgid "Diameter"
msgstr "Діаметр"
#: c:\src\Slic3r\xs\src\slic3r\GUI\BedShapeDialog.cpp:137
msgid ""
"Diameter of the print bed. It is assumed that origin (0,0) is located in the "
"center."
msgstr ""
"Діаметр подложки. Передбачається, що початок координат (0,0) знаходиться в "
"центрі."

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,4 +1,4 @@
use Test::More tests => 71;
use Test::More tests => 77;
use strict;
use warnings;
@ -87,12 +87,18 @@ use Slic3r::Test;
is $parser->evaluate_boolean_expression('(12 == 12) and not (13 == 14)'), 1, 'boolean expression parser: (12 == 12) and not (13 == 14)';
is $parser->evaluate_boolean_expression('(12 == 12) ? (1 - 1 == 0) : (2 * 2 == 3)'), 1, 'boolean expression parser: ternary true';
is $parser->evaluate_boolean_expression('(12 == 21/2) ? (1 - 1 == 0) : (2 * 2 == 3)'), 0, 'boolean expression parser: ternary false';
is $parser->evaluate_boolean_expression('(12 == 13) ? (1 - 1 == 3) : (2 * 2 == 4)"'), 1, 'boolean expression parser: ternary false';
is $parser->evaluate_boolean_expression('(12 == 2 * 6) ? (1 - 1 == 3) : (2 * 2 == 4)"'), 0, 'boolean expression parser: ternary true';
is $parser->evaluate_boolean_expression('(12 == 13) ? (1 - 1 == 3) : (2 * 2 == 4)'), 1, 'boolean expression parser: ternary false';
is $parser->evaluate_boolean_expression('(12 == 2 * 6) ? (1 - 1 == 3) : (2 * 2 == 4)'), 0, 'boolean expression parser: ternary true';
is $parser->evaluate_boolean_expression('12 < 3'), 0, 'boolean expression parser: lower than - false';
is $parser->evaluate_boolean_expression('12 < 22'), 1, 'boolean expression parser: lower than - true';
is $parser->evaluate_boolean_expression('12 > 3'), 1, 'boolean expression parser: lower than - true';
is $parser->evaluate_boolean_expression('12 > 22'), 0, 'boolean expression parser: lower than - false';
is $parser->evaluate_boolean_expression('12 > 3'), 1, 'boolean expression parser: greater than - true';
is $parser->evaluate_boolean_expression('12 > 22'), 0, 'boolean expression parser: greater than - false';
is $parser->evaluate_boolean_expression('12 <= 3'), 0, 'boolean expression parser: lower than or equal- false';
is $parser->evaluate_boolean_expression('12 <= 22'), 1, 'boolean expression parser: lower than or equal - true';
is $parser->evaluate_boolean_expression('12 >= 3'), 1, 'boolean expression parser: greater than or equal - true';
is $parser->evaluate_boolean_expression('12 >= 22'), 0, 'boolean expression parser: greater than or equal - false';
is $parser->evaluate_boolean_expression('12 <= 12'), 1, 'boolean expression parser: lower than or equal (same values) - true';
is $parser->evaluate_boolean_expression('12 >= 12'), 1, 'boolean expression parser: greater than or equal (same values) - true';
is $parser->evaluate_boolean_expression('printer_notes=~/.*PRINTER_VENDOR_PRUSA3D.*/ and printer_notes=~/.*PRINTER_MODEL_MK2.*/ and nozzle_diameter[0]==0.6 and num_extruders>1'), 1, 'complex expression';
is $parser->evaluate_boolean_expression('printer_notes=~/.*PRINTER_VEwerfNDOR_PRUSA3D.*/ or printer_notes=~/.*PRINTertER_MODEL_MK2.*/ or (nozzle_diameter[0]==0.6 and num_extruders>1)'), 1, 'complex expression2';

View file

@ -25,7 +25,7 @@ while (<>) {
my $mm_per_mm = $e_length / $dist; # dE/dXY
my $mm3_per_mm = ($filament_diameter[$T] ** 2) * PI/4 * $mm_per_mm;
my $vol_speed = $F/60 * $mm3_per_mm;
my $comment = sprintf ' ; dXY = %.3fmm ; dE = %.5fmm ; dE/XY = %.5fmm/mm; volspeed = %.5fmm^3/sec',
my $comment = sprintf ' ; dXY = %.3fmm ; dE = %.5fmm ; dE/XY = %.5fmm/mm; volspeed = %.5fmm\x{00B3}/sec',
$dist, $e_length, $mm_per_mm, $vol_speed;
s/(\R+)/$comment$1/;
}

View file

@ -74,6 +74,8 @@ add_library(libslic3r STATIC
${LIBDIR}/libslic3r/Fill/FillRectilinear3.hpp
${LIBDIR}/libslic3r/Flow.cpp
${LIBDIR}/libslic3r/Flow.hpp
${LIBDIR}/libslic3r/Format/3mf.cpp
${LIBDIR}/libslic3r/Format/3mf.hpp
${LIBDIR}/libslic3r/Format/AMF.cpp
${LIBDIR}/libslic3r/Format/AMF.hpp
${LIBDIR}/libslic3r/Format/OBJ.cpp
@ -90,6 +92,8 @@ add_library(libslic3r STATIC
${LIBDIR}/libslic3r/GCode/CoolingBuffer.hpp
${LIBDIR}/libslic3r/GCode/PressureEqualizer.cpp
${LIBDIR}/libslic3r/GCode/PressureEqualizer.hpp
${LIBDIR}/libslic3r/GCode/PreviewData.cpp
${LIBDIR}/libslic3r/GCode/PreviewData.hpp
${LIBDIR}/libslic3r/GCode/PrintExtents.cpp
${LIBDIR}/libslic3r/GCode/PrintExtents.hpp
${LIBDIR}/libslic3r/GCode/SpiralVase.cpp
@ -177,6 +181,20 @@ add_library(libslic3r_gui STATIC
${LIBDIR}/slic3r/GUI/PresetHints.hpp
${LIBDIR}/slic3r/GUI/GUI.cpp
${LIBDIR}/slic3r/GUI/GUI.hpp
${LIBDIR}/slic3r/GUI/Tab.cpp
${LIBDIR}/slic3r/GUI/Tab.hpp
${LIBDIR}/slic3r/GUI/TabIface.cpp
${LIBDIR}/slic3r/GUI/TabIface.hpp
${LIBDIR}/slic3r/GUI/Field.cpp
${LIBDIR}/slic3r/GUI/Field.hpp
${LIBDIR}/slic3r/GUI/OptionsGroup.cpp
${LIBDIR}/slic3r/GUI/OptionsGroup.hpp
${LIBDIR}/slic3r/GUI/BedShapeDialog.cpp
${LIBDIR}/slic3r/GUI/BedShapeDialog.hpp
${LIBDIR}/slic3r/GUI/2DBed.cpp
${LIBDIR}/slic3r/GUI/2DBed.hpp
${LIBDIR}/slic3r/GUI/wxExtensions.cpp
${LIBDIR}/slic3r/GUI/wxExtensions.hpp
)
add_library(admesh STATIC
@ -189,6 +207,18 @@ add_library(admesh STATIC
${LIBDIR}/admesh/util.cpp
)
add_library(miniz STATIC
${LIBDIR}/miniz/miniz.h
${LIBDIR}/miniz/miniz_common.h
${LIBDIR}/miniz/miniz_tdef.h
${LIBDIR}/miniz/miniz_tinfl.h
${LIBDIR}/miniz/miniz_zip.h
${LIBDIR}/miniz/miniz.cpp
${LIBDIR}/miniz/miniz_tdef.cpp
${LIBDIR}/miniz/miniz_tinfl.cpp
${LIBDIR}/miniz/miniz_zip.cpp
)
add_library(clipper STATIC
${LIBDIR}/clipper.cpp
${LIBDIR}/clipper.hpp
@ -289,6 +319,7 @@ set(XS_XSP_FILES
${XSP_DIR}/GUI_AppConfig.xsp
${XSP_DIR}/GUI_3DScene.xsp
${XSP_DIR}/GUI_Preset.xsp
${XSP_DIR}/GUI_Tab.xsp
${XSP_DIR}/Layer.xsp
${XSP_DIR}/Line.xsp
${XSP_DIR}/Model.xsp
@ -348,9 +379,9 @@ if(APPLE)
# Ignore undefined symbols of the perl interpreter, they will be found in the caller image.
target_link_libraries(XS "-undefined dynamic_lookup")
endif()
target_link_libraries(XS libslic3r libslic3r_gui admesh clipper nowide polypartition poly2tri)
if(SLIC3R_DEBUG)
target_link_libraries(Shiny)
target_link_libraries(XS libslic3r libslic3r_gui admesh miniz clipper nowide polypartition poly2tri)
if(SLIC3R_PROFILE)
target_link_libraries(XS Shiny)
endif()
# Add the OpenGL and GLU libraries.
@ -393,7 +424,7 @@ endif ()
if (SLIC3R_PROFILE)
message("Slic3r will be built with a Shiny invasive profiler")
target_compile_definitions(XS PRIVATE -DSLIC3R_PROFILE)
add_definitions(-DSLIC3R_PROFILE)
endif ()
if (SLIC3R_HAS_BROKEN_CROAK)
@ -551,8 +582,8 @@ endif()
# Create a slic3r executable
add_executable(slic3r ${PROJECT_SOURCE_DIR}/src/slic3r.cpp)
target_include_directories(XS PRIVATE src src/libslic3r)
target_link_libraries(slic3r libslic3r libslic3r_gui admesh ${Boost_LIBRARIES} clipper ${EXPAT_LIBRARIES} ${GLEW_LIBRARIES} polypartition poly2tri ${TBB_LIBRARIES} ${wxWidgets_LIBRARIES})
if(SLIC3R_DEBUG)
target_link_libraries(slic3r libslic3r libslic3r_gui admesh miniz ${Boost_LIBRARIES} clipper ${EXPAT_LIBRARIES} ${GLEW_LIBRARIES} polypartition poly2tri ${TBB_LIBRARIES} ${wxWidgets_LIBRARIES})
if(SLIC3R_PROFILE)
target_link_libraries(Shiny)
endif()
if (APPLE)

View file

@ -283,6 +283,7 @@ for my $class (qw(
Slic3r::GUI::_3DScene::GLVolume
Slic3r::GUI::Preset
Slic3r::GUI::PresetCollection
Slic3r::GUI::Tab
Slic3r::Layer
Slic3r::Layer::Region
Slic3r::Layer::Support

View file

@ -90,8 +90,8 @@ ShinyNode* _ShinyManager_dummyNodeTable[] = { NULL };
/* primary hash function */
SHINY_INLINE uint32_t hash_value(void* a_pParent, void* a_pZone) {
// uint32_t a = (uint32_t) a_pParent + (uint32_t) a_pZone;
uint32_t a = *reinterpret_cast<uint32_t*>(&a_pParent) + *reinterpret_cast<uint32_t*>(&a_pZone);
uint32_t a = (uint32_t) a_pParent + (uint32_t) a_pZone;
// uint32_t a = *reinterpret_cast<uint32_t*>(&a_pParent) + *reinterpret_cast<uint32_t*>(&a_pZone);
a = (a+0x7ed55d16) + (a<<12);
a = (a^0xc761c23c) ^ (a>>19);

View file

@ -171,12 +171,11 @@ stl_scale(stl_file *stl, float factor) {
}
static void calculate_normals(stl_file *stl) {
long i;
float normal[3];
if (stl->error) return;
for(i = 0; i < stl->stats.number_of_facets; i++) {
for(uint32_t i = 0; i < stl->stats.number_of_facets; i++) {
stl_calculate_normal(normal, &stl->facet_start[i]);
stl_normalize_vector(normal);
stl->facet_start[i].normal.x = normal[0];
@ -381,7 +380,6 @@ stl_mirror_xz(stl_file *stl) {
}
static float get_volume(stl_file *stl) {
long i;
stl_vertex p0;
stl_vertex p;
stl_normal n;
@ -396,7 +394,7 @@ static float get_volume(stl_file *stl) {
p0.y = stl->facet_start[0].vertex[0].y;
p0.z = stl->facet_start[0].vertex[0].z;
for(i = 0; i < stl->stats.number_of_facets; i++) {
for(uint32_t i = 0; i < stl->stats.number_of_facets; i++) {
p.x = stl->facet_start[i].vertex[0].x - p0.x;
p.y = stl->facet_start[i].vertex[0].y - p0.y;
p.z = stl->facet_start[i].vertex[0].z - p0.z;

View file

@ -561,7 +561,7 @@ inline void RangeTest(const IntPoint& Pt, bool& useFullRange)
if (useFullRange)
{
if (Pt.X > hiRange || Pt.Y > hiRange || -Pt.X > hiRange || -Pt.Y > hiRange)
throw "Coordinate outside allowed range";
throw clipperException("Coordinate outside allowed range");
}
else if (Pt.X > loRange|| Pt.Y > loRange || -Pt.X > loRange || -Pt.Y > loRange)
{
@ -2386,8 +2386,8 @@ void Clipper::ProcessHorizontal(TEdge *horzEdge)
void Clipper::UpdateEdgeIntoAEL(TEdge *&e)
{
if( !e->NextInLML ) throw
clipperException("UpdateEdgeIntoAEL: invalid call");
if( !e->NextInLML )
throw clipperException("UpdateEdgeIntoAEL: invalid call");
e->NextInLML->OutIdx = e->OutIdx;
TEdge* AelPrev = e->PrevInAEL;

View file

@ -4,38 +4,9 @@
namespace Slic3r {
template <class PointClass>
BoundingBoxBase<PointClass>::BoundingBoxBase(const std::vector<PointClass> &points)
{
if (points.empty())
CONFESS("Empty point set supplied to BoundingBoxBase constructor");
typename std::vector<PointClass>::const_iterator it = points.begin();
this->min.x = this->max.x = it->x;
this->min.y = this->max.y = it->y;
for (++it; it != points.end(); ++it) {
this->min.x = std::min(it->x, this->min.x);
this->min.y = std::min(it->y, this->min.y);
this->max.x = std::max(it->x, this->max.x);
this->max.y = std::max(it->y, this->max.y);
}
this->defined = true;
}
template BoundingBoxBase<Point>::BoundingBoxBase(const std::vector<Point> &points);
template BoundingBoxBase<Pointf>::BoundingBoxBase(const std::vector<Pointf> &points);
template <class PointClass>
BoundingBox3Base<PointClass>::BoundingBox3Base(const std::vector<PointClass> &points)
: BoundingBoxBase<PointClass>(points)
{
if (points.empty())
CONFESS("Empty point set supplied to BoundingBox3Base constructor");
typename std::vector<PointClass>::const_iterator it = points.begin();
this->min.z = this->max.z = it->z;
for (++it; it != points.end(); ++it) {
this->min.z = std::min(it->z, this->min.z);
this->max.z = std::max(it->z, this->max.z);
}
}
template BoundingBox3Base<Pointf3>::BoundingBox3Base(const std::vector<Pointf3> &points);
BoundingBox::BoundingBox(const Lines &lines)

View file

@ -23,7 +23,23 @@ public:
BoundingBoxBase() : defined(false) {};
BoundingBoxBase(const PointClass &pmin, const PointClass &pmax) :
min(pmin), max(pmax), defined(pmin.x < pmax.x && pmin.y < pmax.y) {}
BoundingBoxBase(const std::vector<PointClass> &points);
BoundingBoxBase(const std::vector<PointClass>& points)
{
if (points.empty())
CONFESS("Empty point set supplied to BoundingBoxBase constructor");
typename std::vector<PointClass>::const_iterator it = points.begin();
this->min.x = this->max.x = it->x;
this->min.y = this->max.y = it->y;
for (++it; it != points.end(); ++it)
{
this->min.x = std::min(it->x, this->min.x);
this->min.y = std::min(it->y, this->min.y);
this->max.x = std::max(it->x, this->max.x);
this->max.y = std::max(it->y, this->max.y);
}
this->defined = (this->min.x < this->max.x) && (this->min.y < this->max.y);
}
void merge(const PointClass &point);
void merge(const std::vector<PointClass> &points);
void merge(const BoundingBoxBase<PointClass> &bb);
@ -54,7 +70,21 @@ public:
BoundingBox3Base(const PointClass &pmin, const PointClass &pmax) :
BoundingBoxBase<PointClass>(pmin, pmax)
{ if (pmin.z >= pmax.z) BoundingBoxBase<PointClass>::defined = false; }
BoundingBox3Base(const std::vector<PointClass> &points);
BoundingBox3Base(const std::vector<PointClass>& points)
: BoundingBoxBase<PointClass>(points)
{
if (points.empty())
CONFESS("Empty point set supplied to BoundingBox3Base constructor");
typename std::vector<PointClass>::const_iterator it = points.begin();
this->min.z = this->max.z = it->z;
for (++it; it != points.end(); ++it)
{
this->min.z = std::min(it->z, this->min.z);
this->max.z = std::max(it->z, this->max.z);
}
this->defined &= (this->min.z < this->max.z);
}
void merge(const PointClass &point);
void merge(const std::vector<PointClass> &points);
void merge(const BoundingBox3Base<PointClass> &bb);
@ -92,7 +122,7 @@ class BoundingBox3 : public BoundingBox3Base<Point3>
public:
BoundingBox3() : BoundingBox3Base<Point3>() {};
BoundingBox3(const Point3 &pmin, const Point3 &pmax) : BoundingBox3Base<Point3>(pmin, pmax) {};
BoundingBox3(const std::vector<Point3> &points) : BoundingBox3Base<Point3>(points) {};
BoundingBox3(const Points3& points) : BoundingBox3Base<Point3>(points) {};
};
class BoundingBoxf : public BoundingBoxBase<Pointf>

View file

@ -18,10 +18,6 @@
#include <boost/property_tree/ini_parser.hpp>
#include <string.h>
#if defined(_WIN32) && !defined(setenv) && defined(_putenv_s)
#define setenv(k, v, o) _putenv_s(k, v)
#endif
namespace Slic3r {
std::string escape_string_cstyle(const std::string &str)
@ -309,7 +305,6 @@ double ConfigBase::get_abs_value(const t_config_option_key &opt_key, double rati
void ConfigBase::setenv_()
{
#ifdef setenv
t_config_option_keys opt_keys = this->keys();
for (t_config_option_keys::const_iterator it = opt_keys.begin(); it != opt_keys.end(); ++it) {
// prepend the SLIC3R_ prefix
@ -322,15 +317,14 @@ void ConfigBase::setenv_()
for (size_t i = 0; i < envname.size(); ++i)
envname[i] = (envname[i] <= 'z' && envname[i] >= 'a') ? envname[i]-('a'-'A') : envname[i];
setenv(envname.c_str(), this->serialize(*it).c_str(), 1);
boost::nowide::setenv(envname.c_str(), this->serialize(*it).c_str(), 1);
}
#endif
}
void ConfigBase::load(const std::string &file)
{
if (boost::iends_with(file, ".gcode") || boost::iends_with(file, ".g"))
this->load_from_gcode(file);
this->load_from_gcode_file(file);
else
this->load_from_ini(file);
}
@ -355,10 +349,10 @@ void ConfigBase::load(const boost::property_tree::ptree &tree)
}
}
// Load the config keys from the tail of a G-code.
void ConfigBase::load_from_gcode(const std::string &file)
// Load the config keys from the tail of a G-code file.
void ConfigBase::load_from_gcode_file(const std::string &file)
{
// 1) Read a 64k block from the end of the G-code.
// Read a 64k block from the end of the G-code.
boost::nowide::ifstream ifs(file);
{
const char slic3r_gcode_header[] = "; generated by Slic3r ";
@ -371,30 +365,39 @@ void ConfigBase::load_from_gcode(const std::string &file)
auto file_length = ifs.tellg();
auto data_length = std::min<std::fstream::streampos>(65535, file_length);
ifs.seekg(file_length - data_length, ifs.beg);
std::vector<char> data(size_t(data_length) + 1, 0);
ifs.read(data.data(), data_length);
std::vector<char> data(size_t(data_length) + 1, 0);
ifs.read(data.data(), data_length);
ifs.close();
// 2) Walk line by line in reverse until a non-configuration key appears.
char *data_start = data.data();
load_from_gcode_string(data.data());
}
// Load the config keys from the given string.
void ConfigBase::load_from_gcode_string(const char* str)
{
if (str == nullptr)
return;
// Walk line by line in reverse until a non-configuration key appears.
char *data_start = const_cast<char*>(str);
// boost::nowide::ifstream seems to cook the text data somehow, so less then the 64k of characters may be retrieved.
char *end = data_start + strlen(data.data());
char *end = data_start + strlen(str);
size_t num_key_value_pairs = 0;
for (;;) {
// Extract next line.
for (-- end; end > data_start && (*end == '\r' || *end == '\n'); -- end);
for (--end; end > data_start && (*end == '\r' || *end == '\n'); --end);
if (end == data_start)
break;
char *start = end;
*(++ end) = 0;
for (; start > data_start && *start != '\r' && *start != '\n'; -- start);
*(++end) = 0;
for (; start > data_start && *start != '\r' && *start != '\n'; --start);
if (start == data_start)
break;
// Extracted a line from start to end. Extract the key = value pair.
if (end - (++ start) < 10 || start[0] != ';' || start[1] != ' ')
if (end - (++start) < 10 || start[0] != ';' || start[1] != ' ')
break;
char *key = start + 2;
if (! (*key >= 'a' && *key <= 'z') || (*key >= 'A' && *key <= 'Z'))
if (!(*key >= 'a' && *key <= 'z') || (*key >= 'A' && *key <= 'Z'))
// A key must start with a letter.
break;
char *sep = strchr(key, '=');
@ -408,8 +411,8 @@ void ConfigBase::load_from_gcode(const std::string &file)
break;
*key_end = 0;
// The key may contain letters, digits and underscores.
for (char *c = key; c != key_end; ++ c)
if (! ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <= 'Z') || (*c >= '0' && *c <= '9') || *c == '_')) {
for (char *c = key; c != key_end; ++c)
if (!((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <= 'Z') || (*c >= '0' && *c <= '9') || *c == '_')) {
key = nullptr;
break;
}
@ -417,8 +420,9 @@ void ConfigBase::load_from_gcode(const std::string &file)
break;
try {
this->set_deserialize(key, value);
++ num_key_value_pairs;
} catch (UnknownOptionException & /* e */) {
++num_key_value_pairs;
}
catch (UnknownOptionException & /* e */) {
// ignore
}
end = start;

View file

@ -582,6 +582,13 @@ public:
ConfigOptionType type() const override { return static_type(); }
ConfigOption* clone() const override { return new ConfigOptionFloatOrPercent(*this); }
ConfigOptionFloatOrPercent& operator=(const ConfigOption *opt) { this->set(opt); return *this; }
bool operator==(const ConfigOption &rhs) const override
{
if (rhs.type() != this->type())
throw std::runtime_error("ConfigOptionFloatOrPercent: Comparing incompatible types");
assert(dynamic_cast<const ConfigOptionFloatOrPercent*>(&rhs));
return *this == *static_cast<const ConfigOptionFloatOrPercent*>(&rhs);
}
bool operator==(const ConfigOptionFloatOrPercent &rhs) const
{ return this->value == rhs.value && this->percent == rhs.percent; }
double get_abs_value(double ratio_over) const
@ -1049,7 +1056,8 @@ public:
void setenv_();
void load(const std::string &file);
void load_from_ini(const std::string &file);
void load_from_gcode(const std::string &file);
void load_from_gcode_file(const std::string &file);
void load_from_gcode_string(const char* str);
void load(const boost::property_tree::ptree &tree);
void save(const std::string &file) const;
@ -1161,6 +1169,8 @@ public:
const ConfigDef* def() const override { return nullptr; };
template<class T> T* opt(const t_config_option_key &opt_key, bool create = false)
{ return dynamic_cast<T*>(this->option(opt_key, create)); }
template<class T> const T* opt(const t_config_option_key &opt_key) const
{ return dynamic_cast<const T*>(this->option(opt_key)); }
// Overrides ConfigBase::optptr(). Find ando/or create a ConfigOption instance for a given name.
ConfigOption* optptr(const t_config_option_key &opt_key, bool create = false) override;
// Overrides ConfigBase::keys(). Collect names of all configuration values maintained by this configuration store.

View file

@ -25,6 +25,7 @@ enum ExtrusionRole {
erSkirt,
erSupportMaterial,
erSupportMaterialInterface,
erWipeTower,
// Extrusion role for a collection with multiple extrusion roles.
erMixed,
};
@ -104,15 +105,19 @@ public:
float width;
// Height of the extrusion, used for visualization purposed.
float height;
ExtrusionPath(ExtrusionRole role) : mm3_per_mm(-1), width(-1), height(-1), m_role(role) {};
ExtrusionPath(ExtrusionRole role, double mm3_per_mm, float width, float height) : mm3_per_mm(mm3_per_mm), width(width), height(height), m_role(role) {};
ExtrusionPath(const ExtrusionPath &rhs) : polyline(rhs.polyline), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), m_role(rhs.m_role) {}
ExtrusionPath(ExtrusionPath &&rhs) : polyline(std::move(rhs.polyline)), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), m_role(rhs.m_role) {}
// ExtrusionPath(ExtrusionRole role, const Flow &flow) : m_role(role), mm3_per_mm(flow.mm3_per_mm()), width(flow.width), height(flow.height) {};
// Feedrate of the extrusion, used for visualization purposed.
float feedrate;
// Id of the extruder, used for visualization purposed.
unsigned int extruder_id;
ExtrusionPath& operator=(const ExtrusionPath &rhs) { this->m_role = rhs.m_role; this->mm3_per_mm = rhs.mm3_per_mm; this->width = rhs.width; this->height = rhs.height; this->polyline = rhs.polyline; return *this; }
ExtrusionPath& operator=(ExtrusionPath &&rhs) { this->m_role = rhs.m_role; this->mm3_per_mm = rhs.mm3_per_mm; this->width = rhs.width; this->height = rhs.height; this->polyline = std::move(rhs.polyline); return *this; }
ExtrusionPath(ExtrusionRole role) : mm3_per_mm(-1), width(-1), height(-1), feedrate(0.0f), extruder_id(0), m_role(role) {};
ExtrusionPath(ExtrusionRole role, double mm3_per_mm, float width, float height) : mm3_per_mm(mm3_per_mm), width(width), height(height), feedrate(0.0f), extruder_id(0), m_role(role) {};
ExtrusionPath(const ExtrusionPath &rhs) : polyline(rhs.polyline), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), feedrate(rhs.feedrate), extruder_id(rhs.extruder_id), m_role(rhs.m_role) {}
ExtrusionPath(ExtrusionPath &&rhs) : polyline(std::move(rhs.polyline)), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), feedrate(rhs.feedrate), extruder_id(rhs.extruder_id), m_role(rhs.m_role) {}
// ExtrusionPath(ExtrusionRole role, const Flow &flow) : m_role(role), mm3_per_mm(flow.mm3_per_mm()), width(flow.width), height(flow.height), feedrate(0.0f), extruder_id(0) {};
ExtrusionPath& operator=(const ExtrusionPath &rhs) { this->m_role = rhs.m_role; this->mm3_per_mm = rhs.mm3_per_mm; this->width = rhs.width; this->height = rhs.height; this->feedrate = rhs.feedrate, this->extruder_id = rhs.extruder_id, this->polyline = rhs.polyline; return *this; }
ExtrusionPath& operator=(ExtrusionPath &&rhs) { this->m_role = rhs.m_role; this->mm3_per_mm = rhs.mm3_per_mm; this->width = rhs.width; this->height = rhs.height; this->feedrate = rhs.feedrate, this->extruder_id = rhs.extruder_id, this->polyline = std::move(rhs.polyline); return *this; }
ExtrusionPath* clone() const { return new ExtrusionPath (*this); }
void reverse() { this->polyline.reverse(); }

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,19 @@
#ifndef slic3r_Format_3mf_hpp_
#define slic3r_Format_3mf_hpp_
namespace Slic3r {
class Model;
class Print;
class PresetBundle;
// Load the content of a 3mf file into the given model and preset bundle.
extern bool load_3mf(const char* path, PresetBundle* bundle, Model* model);
// Save the given model and the config data contained in the given Print into a 3mf file.
// The model could be modified during the export process if meshes are not repaired or have no shared vertices
extern bool store_3mf(const char* path, Model* model, Print* print);
}; // namespace Slic3r
#endif /* slic3r_Format_3mf_hpp_ */

View file

@ -7,8 +7,14 @@
#include "../libslic3r.h"
#include "../Model.hpp"
#include "../GCode.hpp"
#include "../slic3r/GUI/PresetBundle.hpp"
#include "AMF.hpp"
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string.hpp>
#include <miniz/miniz_zip.h>
#if 0
// Enable debugging and assert in this file.
#define DEBUG
@ -18,18 +24,22 @@
#include <assert.h>
const char* SLIC3R_CONFIG_TYPE = "slic3rpe_config";
namespace Slic3r
{
struct AMFParserContext
{
AMFParserContext(XML_Parser parser, Model *model) :
AMFParserContext(XML_Parser parser, const std::string& archive_filename, PresetBundle* preset_bundle, Model *model) :
m_parser(parser),
m_model(*model),
m_object(nullptr),
m_volume(nullptr),
m_material(nullptr),
m_instance(nullptr)
m_instance(nullptr),
m_preset_bundle(preset_bundle),
m_archive_filename(archive_filename)
{
m_path.reserve(12);
}
@ -149,6 +159,10 @@ struct AMFParserContext
Instance *m_instance;
// Generic string buffer for vertices, face indices, metadata etc.
std::string m_value[3];
// Pointer to preset bundle to update if config data are stored inside the amf file
PresetBundle* m_preset_bundle;
// Fullpath name of the amf file
std::string m_archive_filename;
private:
AMFParserContext& operator=(AMFParserContext&);
@ -403,7 +417,10 @@ void AMFParserContext::endElement(const char * /* name */)
break;
case NODE_TYPE_METADATA:
if (strncmp(m_value[0].c_str(), "slic3r.", 7) == 0) {
if ((m_preset_bundle != nullptr) && strncmp(m_value[0].c_str(), SLIC3R_CONFIG_TYPE, strlen(SLIC3R_CONFIG_TYPE)) == 0) {
m_preset_bundle->load_config_string(m_value[1].c_str(), m_archive_filename.c_str());
}
else if (strncmp(m_value[0].c_str(), "slic3r.", 7) == 0) {
const char *opt_key = m_value[0].c_str() + 7;
if (print_config_def.options.find(opt_key) != print_config_def.options.end()) {
DynamicPrintConfig *config = nullptr;
@ -474,10 +491,13 @@ void AMFParserContext::endDocument()
}
// Load an AMF file into a provided model.
bool load_amf(const char *path, Model *model)
bool load_amf_file(const char *path, PresetBundle* bundle, Model *model)
{
if ((path == nullptr) || (model == nullptr))
return false;
XML_Parser parser = XML_ParserCreate(nullptr); // encoding
if (! parser) {
if (!parser) {
printf("Couldn't allocate memory for parser\n");
return false;
}
@ -488,7 +508,7 @@ bool load_amf(const char *path, Model *model)
return false;
}
AMFParserContext ctx(parser, model);
AMFParserContext ctx(parser, path, bundle, model);
XML_SetUserData(parser, (void*)&ctx);
XML_SetElementHandler(parser, AMFParserContext::startElement, AMFParserContext::endElement);
XML_SetCharacterDataHandler(parser, AMFParserContext::characters);
@ -519,49 +539,163 @@ bool load_amf(const char *path, Model *model)
if (result)
ctx.endDocument();
return result;
}
bool store_amf(const char *path, Model *model)
// Load an AMF archive into a provided model.
bool load_amf_archive(const char *path, PresetBundle* bundle, Model *model)
{
FILE *file = boost::nowide::fopen(path, "wb");
if (file == nullptr)
if ((path == nullptr) || (model == nullptr))
return false;
fprintf(file, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
fprintf(file, "<amf unit=\"millimeter\">\n");
fprintf(file, "<metadata type=\"cad\">Slic3r %s</metadata>\n", SLIC3R_VERSION);
mz_zip_archive archive;
mz_zip_zero_struct(&archive);
mz_bool res = mz_zip_reader_init_file(&archive, path, 0);
if (res == 0)
{
printf("Unable to init zip reader\n");
return false;
}
mz_uint num_entries = mz_zip_reader_get_num_files(&archive);
if (num_entries != 1)
{
printf("Found invalid number of entries\n");
mz_zip_reader_end(&archive);
return false;
}
mz_zip_archive_file_stat stat;
res = mz_zip_reader_file_stat(&archive, 0, &stat);
if (res == 0)
{
printf("Unable to extract entry statistics\n");
mz_zip_reader_end(&archive);
return false;
}
std::string internal_amf_filename = boost::ireplace_last_copy(boost::filesystem::path(path).filename().string(), ".zip.amf", ".amf");
if (internal_amf_filename != stat.m_filename)
{
printf("Found invalid internal filename\n");
mz_zip_reader_end(&archive);
return false;
}
if (stat.m_uncomp_size == 0)
{
printf("Found invalid size\n");
mz_zip_reader_end(&archive);
return false;
}
XML_Parser parser = XML_ParserCreate(nullptr); // encoding
if (!parser) {
printf("Couldn't allocate memory for parser\n");
mz_zip_reader_end(&archive);
return false;
}
AMFParserContext ctx(parser, path, bundle, model);
XML_SetUserData(parser, (void*)&ctx);
XML_SetElementHandler(parser, AMFParserContext::startElement, AMFParserContext::endElement);
XML_SetCharacterDataHandler(parser, AMFParserContext::characters);
void* parser_buffer = XML_GetBuffer(parser, (int)stat.m_uncomp_size);
if (parser_buffer == nullptr)
{
printf("Unable to create buffer\n");
mz_zip_reader_end(&archive);
return false;
}
res = mz_zip_reader_extract_file_to_mem(&archive, stat.m_filename, parser_buffer, (size_t)stat.m_uncomp_size, 0);
if (res == 0)
{
printf("Error while reading model data to buffer\n");
mz_zip_reader_end(&archive);
return false;
}
if (!XML_ParseBuffer(parser, (int)stat.m_uncomp_size, 1))
{
printf("Error (%s) while parsing xml file at line %d\n", XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser));
mz_zip_reader_end(&archive);
return false;
}
ctx.endDocument();
mz_zip_reader_end(&archive);
return true;
}
// Load an AMF file into a provided model.
// If bundle is not a null pointer, updates it if the amf file/archive contains config data
bool load_amf(const char *path, PresetBundle* bundle, Model *model)
{
if (boost::iends_with(path, ".zip.amf"))
return load_amf_archive(path, bundle, model);
else if (boost::iends_with(path, ".amf") || boost::iends_with(path, ".amf.xml"))
return load_amf_file(path, bundle, model);
else
return false;
}
bool store_amf(const char *path, Model *model, Print* print)
{
if ((path == nullptr) || (model == nullptr) || (print == nullptr))
return false;
mz_zip_archive archive;
mz_zip_zero_struct(&archive);
mz_bool res = mz_zip_writer_init_file(&archive, path, 0);
if (res == 0)
return false;
std::stringstream stream;
stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
stream << "<amf unit=\"millimeter\">\n";
stream << "<metadata type=\"cad\">Slic3r " << SLIC3R_VERSION << "</metadata>\n";
std::string config = "\n";
GCode::append_full_config(*print, config);
stream << "<metadata type=\"" << SLIC3R_CONFIG_TYPE << "\">" << config << "</metadata>\n";
for (const auto &material : model->materials) {
if (material.first.empty())
continue;
// note that material-id must never be 0 since it's reserved by the AMF spec
fprintf(file, " <material id=\"%s\">\n", material.first.c_str());
stream << " <material id=\"" << material.first << "\">\n";
for (const auto &attr : material.second->attributes)
fprintf(file, " <metadata type=\"%s\">%s</metadata>\n", attr.first.c_str(), attr.second.c_str());
stream << " <metadata type=\"" << attr.first << "\">" << attr.second << "</metadata>\n";
for (const std::string &key : material.second->config.keys())
fprintf(file, " <metadata type=\"slic3r.%s\">%s</metadata>\n", key.c_str(), material.second->config.serialize(key).c_str());
fprintf(file, " </material>\n");
stream << " <metadata type=\"slic3r." << key << "\">" << material.second->config.serialize(key) << "</metadata>\n";
stream << " </material>\n";
}
std::string instances;
for (size_t object_id = 0; object_id < model->objects.size(); ++ object_id) {
ModelObject *object = model->objects[object_id];
fprintf(file, " <object id=\"" PRINTF_ZU "\">\n", object_id);
stream << " <object id=\"" << object_id << "\">\n";
for (const std::string &key : object->config.keys())
fprintf(file, " <metadata type=\"slic3r.%s\">%s</metadata>\n", key.c_str(), object->config.serialize(key).c_str());
if (! object->name.empty())
fprintf(file, " <metadata type=\"name\">%s</metadata>\n", object->name.c_str());
stream << " <metadata type=\"slic3r." << key << "\">" << object->config.serialize(key) << "</metadata>\n";
if (!object->name.empty())
stream << " <metadata type=\"name\">" << object->name << "</metadata>\n";
std::vector<double> layer_height_profile = object->layer_height_profile_valid ? object->layer_height_profile : std::vector<double>();
if (layer_height_profile.size() >= 4 && (layer_height_profile.size() % 2) == 0) {
// Store the layer height profile as a single semicolon separated list.
fprintf(file, " <metadata type=\"slic3r.layer_height_profile\">");
fprintf(file, "%f", layer_height_profile.front());
for (size_t i = 1; i < layer_height_profile.size(); ++ i)
fprintf(file, ";%f", layer_height_profile[i]);
fprintf(file, "\n </metadata>\n");
stream << " <metadata type=\"slic3r.layer_height_profile\">";
stream << layer_height_profile.front();
for (size_t i = 1; i < layer_height_profile.size(); ++i)
stream << ";" << layer_height_profile[i];
stream << "\n </metadata>\n";
}
//FIXME Store the layer height ranges (ModelObject::layer_height_ranges)
fprintf(file, " <mesh>\n");
fprintf(file, " <vertices>\n");
stream << " <mesh>\n";
stream << " <vertices>\n";
std::vector<int> vertices_offsets;
int num_vertices = 0;
for (ModelVolume *volume : object->volumes) {
@ -572,41 +706,41 @@ bool store_amf(const char *path, Model *model)
if (stl.v_shared == nullptr)
stl_generate_shared_vertices(&stl);
for (size_t i = 0; i < stl.stats.shared_vertices; ++ i) {
fprintf(file, " <vertex>\n");
fprintf(file, " <coordinates>\n");
fprintf(file, " <x>%f</x>\n", stl.v_shared[i].x);
fprintf(file, " <y>%f</y>\n", stl.v_shared[i].y);
fprintf(file, " <z>%f</z>\n", stl.v_shared[i].z);
fprintf(file, " </coordinates>\n");
fprintf(file, " </vertex>\n");
stream << " <vertex>\n";
stream << " <coordinates>\n";
stream << " <x>" << stl.v_shared[i].x << "</x>\n";
stream << " <y>" << stl.v_shared[i].y << "</y>\n";
stream << " <z>" << stl.v_shared[i].z << "</z>\n";
stream << " </coordinates>\n";
stream << " </vertex>\n";
}
num_vertices += stl.stats.shared_vertices;
}
fprintf(file, " </vertices>\n");
for (size_t i_volume = 0; i_volume < object->volumes.size(); ++ i_volume) {
stream << " </vertices>\n";
for (size_t i_volume = 0; i_volume < object->volumes.size(); ++i_volume) {
ModelVolume *volume = object->volumes[i_volume];
int vertices_offset = vertices_offsets[i_volume];
if (volume->material_id().empty())
fprintf(file, " <volume>\n");
stream << " <volume>\n";
else
fprintf(file, " <volume materialid=\"%s\">\n", volume->material_id().c_str());
stream << " <volume materialid=\"" << volume->material_id() << "\">\n";
for (const std::string &key : volume->config.keys())
fprintf(file, " <metadata type=\"slic3r.%s\">%s</metadata>\n", key.c_str(), volume->config.serialize(key).c_str());
if (! volume->name.empty())
fprintf(file, " <metadata type=\"name\">%s</metadata>\n", volume->name.c_str());
stream << " <metadata type=\"slic3r." << key << "\">" << volume->config.serialize(key) << "</metadata>\n";
if (!volume->name.empty())
stream << " <metadata type=\"name\">" << volume->name << "</metadata>\n";
if (volume->modifier)
fprintf(file, " <metadata type=\"slic3r.modifier\">1</metadata>\n");
for (int i = 0; i < volume->mesh.stl.stats.number_of_facets; ++ i) {
fprintf(file, " <triangle>\n");
for (int j = 0; j < 3; ++ j)
fprintf(file, " <v%d>%d</v%d>\n", j+1, volume->mesh.stl.v_indices[i].vertex[j] + vertices_offset, j+1);
fprintf(file, " </triangle>\n");
stream << " <metadata type=\"slic3r.modifier\">1</metadata>\n";
for (int i = 0; i < volume->mesh.stl.stats.number_of_facets; ++i) {
stream << " <triangle>\n";
for (int j = 0; j < 3; ++j)
stream << " <v" << j + 1 << ">" << volume->mesh.stl.v_indices[i].vertex[j] + vertices_offset << "</v" << j + 1 << ">\n";
stream << " </triangle>\n";
}
fprintf(file, " </volume>\n");
stream << " </volume>\n";
}
fprintf(file, " </mesh>\n");
fprintf(file, " </object>\n");
if (! object->instances.empty()) {
stream << " </mesh>\n";
stream << " </object>\n";
if (!object->instances.empty()) {
for (ModelInstance *instance : object->instances) {
char buf[512];
sprintf(buf,
@ -627,12 +761,31 @@ bool store_amf(const char *path, Model *model)
}
}
if (! instances.empty()) {
fprintf(file, " <constellation id=\"1\">\n");
fwrite(instances.data(), instances.size(), 1, file);
fprintf(file, " </constellation>\n");
stream << " <constellation id=\"1\">\n";
stream << instances;
stream << " </constellation>\n";
}
fprintf(file, "</amf>\n");
fclose(file);
stream << "</amf>\n";
std::string internal_amf_filename = boost::ireplace_last_copy(boost::filesystem::path(path).filename().string(), ".zip.amf", ".amf");
std::string out = stream.str();
if (!mz_zip_writer_add_mem(&archive, internal_amf_filename.c_str(), (const void*)out.data(), out.length(), MZ_DEFAULT_COMPRESSION))
{
mz_zip_writer_end(&archive);
boost::filesystem::remove(path);
return false;
}
if (!mz_zip_writer_finalize_archive(&archive))
{
mz_zip_writer_end(&archive);
boost::filesystem::remove(path);
return false;
}
mz_zip_writer_end(&archive);
return true;
}

View file

@ -4,11 +4,15 @@
namespace Slic3r {
class Model;
class Print;
class PresetBundle;
// Load an AMF file into a provided model.
extern bool load_amf(const char *path, Model *model);
// Load the content of an amf file into the given model and preset bundle.
extern bool load_amf(const char *path, PresetBundle* bundle, Model *model);
extern bool store_amf(const char *path, Model *model);
// Save the given model and the config data contained in the given Print into an amf file.
// The model could be modified during the export process if meshes are not repaired or have no shared vertices
extern bool store_amf(const char *path, Model *model, Print* print);
}; // namespace Slic3r

View file

@ -148,7 +148,7 @@ bool load_prus(const char *path, Model *model)
if (scene_xml_data.size() < size_last + size_incr)
scene_xml_data.resize(size_last + size_incr);
}
size_last += size_last + zip.LastRead();
size_last += zip.LastRead();
if (scene_xml_data.size() == size_last)
scene_xml_data.resize(size_last + 1);
else if (scene_xml_data.size() > size_last + 1)

View file

@ -13,6 +13,7 @@
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/find.hpp>
#include <boost/foreach.hpp>
#include <boost/log/trivial.hpp>
#include <boost/nowide/iostream.hpp>
#include <boost/nowide/cstdio.hpp>
@ -20,6 +21,8 @@
#include "SVG.hpp"
#include <Shiny/Shiny.h>
#if 0
// Enable debugging and asserts, even in the release build.
#define DEBUG
@ -267,22 +270,6 @@ std::string WipeTowerIntegration::finalize(GCode &gcodegen)
#define EXTRUDER_CONFIG(OPT) m_config.OPT.get_at(m_writer.extruder()->id())
inline void write(FILE *file, const std::string &what)
{
fwrite(what.data(), 1, what.size(), file);
}
// Write a string into a file. Add a newline, if the string does not end with a newline already.
// Used to export a custom G-code section processed by the PlaceholderParser.
inline void writeln(FILE *file, const std::string &what)
{
if (! what.empty()) {
write(file, what);
if (what.back() != '\n')
fprintf(file, "\n");
}
}
// Collect pairs of object_layer + support_layer sorted by print_z.
// object_layer & support_layer are considered to be on the same print_z, if they are not further than EPSILON.
std::vector<GCode::LayerToPrint> GCode::collect_layers_to_print(const PrintObject &object)
@ -362,8 +349,12 @@ std::vector<std::pair<coordf_t, std::vector<GCode::LayerToPrint>>> GCode::collec
return layers_to_print;
}
void GCode::do_export(Print *print, const char *path)
void GCode::do_export(Print *print, const char *path, GCodePreviewData *preview_data)
{
PROFILE_CLEAR();
BOOST_LOG_TRIVIAL(info) << "Exporting G-code...";
// Remove the old g-code if it exists.
boost::nowide::remove(path);
@ -375,7 +366,7 @@ void GCode::do_export(Print *print, const char *path)
throw std::runtime_error(std::string("G-code export to ") + path + " failed.\nCannot open the file for writing.\n");
this->m_placeholder_parser_failed_templates.clear();
this->_do_export(*print, file);
this->_do_export(*print, file, preview_data);
fflush(file);
if (ferror(file)) {
fclose(file);
@ -395,14 +386,36 @@ void GCode::do_export(Print *print, const char *path)
msg += " !!!!! End of an error report for the custom G-code template ...\n";
throw std::runtime_error(msg);
}
if (boost::nowide::rename(path_tmp.c_str(), path) != 0)
throw std::runtime_error(
std::string("Failed to rename the output G-code file from ") + path_tmp + " to " + path + '\n' +
"Is " + path_tmp + " locked?" + '\n');
BOOST_LOG_TRIVIAL(info) << "Exporting G-code finished";
// Write the profiler measurements to file
PROFILE_UPDATE();
PROFILE_OUTPUT(debug_out_path("gcode-export-profile.txt").c_str());
}
void GCode::_do_export(Print &print, FILE *file)
void GCode::_do_export(Print &print, FILE *file, GCodePreviewData *preview_data)
{
PROFILE_FUNC();
// resets time estimator
m_time_estimator.reset();
m_time_estimator.set_dialect(print.config.gcode_flavor);
// resets analyzer
m_analyzer.reset();
m_enable_analyzer = preview_data != nullptr;
// resets analyzer's tracking data
m_last_mm3_per_mm = GCodeAnalyzer::Default_mm3_per_mm;
m_last_width = GCodeAnalyzer::Default_Width;
m_last_height = GCodeAnalyzer::Default_Height;
// How many times will be change_layer() called?
// change_layer() in turn increments the progress bar status.
m_layer_count = 0;
@ -486,7 +499,7 @@ void GCode::_do_export(Print &print, FILE *file)
m_enable_extrusion_role_markers = (bool)m_pressure_equalizer;
// Write information on the generator.
fprintf(file, "; %s\n\n", Slic3r::header_slic3r_generated().c_str());
_write_format(file, "; %s\n\n", Slic3r::header_slic3r_generated().c_str());
// Write notes (content of the Print Settings tab -> Notes)
{
std::list<std::string> lines;
@ -495,10 +508,10 @@ void GCode::_do_export(Print &print, FILE *file)
// Remove the trailing '\r' from the '\r\n' sequence.
if (! line.empty() && line.back() == '\r')
line.pop_back();
fprintf(file, "; %s\n", line.c_str());
_write_format(file, "; %s\n", line.c_str());
}
if (! lines.empty())
fprintf(file, "\n");
_write(file, "\n");
}
// Write some terse information on the slicing parameters.
const PrintObject *first_object = print.objects.front();
@ -506,16 +519,16 @@ void GCode::_do_export(Print &print, FILE *file)
const double first_layer_height = first_object->config.first_layer_height.get_abs_value(layer_height);
for (size_t region_id = 0; region_id < print.regions.size(); ++ region_id) {
auto region = print.regions[region_id];
fprintf(file, "; external perimeters extrusion width = %.2fmm\n", region->flow(frExternalPerimeter, layer_height, false, false, -1., *first_object).width);
fprintf(file, "; perimeters extrusion width = %.2fmm\n", region->flow(frPerimeter, layer_height, false, false, -1., *first_object).width);
fprintf(file, "; infill extrusion width = %.2fmm\n", region->flow(frInfill, layer_height, false, false, -1., *first_object).width);
fprintf(file, "; solid infill extrusion width = %.2fmm\n", region->flow(frSolidInfill, layer_height, false, false, -1., *first_object).width);
fprintf(file, "; top infill extrusion width = %.2fmm\n", region->flow(frTopSolidInfill, layer_height, false, false, -1., *first_object).width);
_write_format(file, "; external perimeters extrusion width = %.2fmm\n", region->flow(frExternalPerimeter, layer_height, false, false, -1., *first_object).width);
_write_format(file, "; perimeters extrusion width = %.2fmm\n", region->flow(frPerimeter, layer_height, false, false, -1., *first_object).width);
_write_format(file, "; infill extrusion width = %.2fmm\n", region->flow(frInfill, layer_height, false, false, -1., *first_object).width);
_write_format(file, "; solid infill extrusion width = %.2fmm\n", region->flow(frSolidInfill, layer_height, false, false, -1., *first_object).width);
_write_format(file, "; top infill extrusion width = %.2fmm\n", region->flow(frTopSolidInfill, layer_height, false, false, -1., *first_object).width);
if (print.has_support_material())
fprintf(file, "; support material extrusion width = %.2fmm\n", support_material_flow(first_object).width);
_write_format(file, "; support material extrusion width = %.2fmm\n", support_material_flow(first_object).width);
if (print.config.first_layer_extrusion_width.value > 0)
fprintf(file, "; first layer extrusion width = %.2fmm\n", region->flow(frPerimeter, first_layer_height, false, true, -1., *first_object).width);
fprintf(file, "\n");
_write_format(file, "; first layer extrusion width = %.2fmm\n", region->flow(frPerimeter, first_layer_height, false, true, -1., *first_object).width);
_write_format(file, "\n");
}
// Prepare the helper object for replacing placeholders in custom G-code and output filename.
@ -558,7 +571,7 @@ void GCode::_do_export(Print &print, FILE *file)
// Disable fan.
if (! print.config.cooling.get_at(initial_extruder_id) || print.config.disable_fan_first_layers.get_at(initial_extruder_id))
write(file, m_writer.set_fan(0, true));
_write(file, m_writer.set_fan(0, true));
// Let the start-up script prime the 1st printing tool.
m_placeholder_parser.set("initial_tool", initial_extruder_id);
@ -575,24 +588,24 @@ void GCode::_do_export(Print &print, FILE *file)
// Set extruder(s) temperature before and after start G-code.
this->_print_first_layer_extruder_temperatures(file, print, start_gcode, initial_extruder_id, false);
// Write the custom start G-code
writeln(file, start_gcode);
_writeln(file, start_gcode);
// Process filament-specific gcode in extruder order.
if (print.config.single_extruder_multi_material) {
if (has_wipe_tower) {
// Wipe tower will control the extruder switching, it will call the start_filament_gcode.
} else {
// Only initialize the initial extruder.
writeln(file, this->placeholder_parser_process("start_filament_gcode", print.config.start_filament_gcode.values[initial_extruder_id], initial_extruder_id));
_writeln(file, this->placeholder_parser_process("start_filament_gcode", print.config.start_filament_gcode.values[initial_extruder_id], initial_extruder_id));
}
} else {
for (const std::string &start_gcode : print.config.start_filament_gcode.values)
writeln(file, this->placeholder_parser_process("start_gcode", start_gcode, (unsigned int)(&start_gcode - &print.config.start_filament_gcode.values.front())));
_writeln(file, this->placeholder_parser_process("start_gcode", start_gcode, (unsigned int)(&start_gcode - &print.config.start_filament_gcode.values.front())));
}
this->_print_first_layer_extruder_temperatures(file, print, start_gcode, initial_extruder_id, true);
// Set other general things.
write(file, this->preamble());
_write(file, this->preamble());
// Initialize a motion planner for object-to-object travel moves.
if (print.config.avoid_crossing_perimeters.value) {
// Collect outer contours of all objects over all layers.
@ -640,7 +653,7 @@ void GCode::_do_export(Print &print, FILE *file)
}
// Set initial extruder only after custom start G-code.
write(file, this->set_extruder(initial_extruder_id));
_write(file, this->set_extruder(initial_extruder_id));
// Do all objects for each layer.
if (print.config.complete_objects.value) {
@ -670,8 +683,8 @@ void GCode::_do_export(Print &print, FILE *file)
// This happens before Z goes down to layer 0 again, so that no collision happens hopefully.
m_enable_cooling_markers = false; // we're not filtering these moves through CoolingBuffer
m_avoid_crossing_perimeters.use_external_mp_once = true;
write(file, this->retract());
write(file, this->travel_to(Point(0, 0), erNone, "move to origin position for next object"));
_write(file, this->retract());
_write(file, this->travel_to(Point(0, 0), erNone, "move to origin position for next object"));
m_enable_cooling_markers = true;
// Disable motion planner when traveling to first object point.
m_avoid_crossing_perimeters.disable_once = true;
@ -683,7 +696,7 @@ void GCode::_do_export(Print &print, FILE *file)
// Set first layer bed and extruder temperatures, don't wait for it to reach the temperature.
this->_print_first_layer_bed_temperature(file, print, between_objects_gcode, initial_extruder_id, false);
this->_print_first_layer_extruder_temperatures(file, print, between_objects_gcode, initial_extruder_id, false);
writeln(file, between_objects_gcode);
_writeln(file, between_objects_gcode);
}
// Reset the cooling buffer internal state (the current position, feed rate, accelerations).
m_cooling_buffer->reset();
@ -696,7 +709,7 @@ void GCode::_do_export(Print &print, FILE *file)
this->process_layer(file, print, lrs, tool_ordering.tools_for_layer(ltp.print_z()), &copy - object._shifted_copies.data());
}
if (m_pressure_equalizer)
write(file, m_pressure_equalizer->process("", true));
_write(file, m_pressure_equalizer->process("", true));
++ finished_objects;
// Flag indicating whether the nozzle temperature changes from 1st to 2nd layer were performed.
// Reset it when starting another object from 1st layer.
@ -716,8 +729,8 @@ void GCode::_do_export(Print &print, FILE *file)
// Prusa Multi-Material wipe tower.
if (has_wipe_tower && ! layers_to_print.empty()) {
m_wipe_tower.reset(new WipeTowerIntegration(print.config, *print.m_wipe_tower_priming.get(), print.m_wipe_tower_tool_changes, *print.m_wipe_tower_final_purge.get()));
write(file, m_writer.travel_to_z(first_layer_height + m_config.z_offset.value, "Move to the first layer height"));
write(file, m_wipe_tower->prime(*this));
_write(file, m_writer.travel_to_z(first_layer_height + m_config.z_offset.value, "Move to the first layer height"));
_write(file, m_wipe_tower->prime(*this));
// Verify, whether the print overaps the priming extrusions.
BoundingBoxf bbox_print(get_print_extrusions_extents(print));
coordf_t twolayers_printz = ((layers_to_print.size() == 1) ? layers_to_print.front() : layers_to_print[1]).first + EPSILON;
@ -727,16 +740,17 @@ void GCode::_do_export(Print &print, FILE *file)
BoundingBoxf bbox_prime(get_wipe_tower_priming_extrusions_extents(print));
bbox_prime.offset(0.5f);
// Beep for 500ms, tone 800Hz. Yet better, play some Morse.
write(file, this->retract());
fprintf(file, "M300 S800 P500\n");
_write(file, this->retract());
_write(file, "M300 S800 P500\n");
if (bbox_prime.overlap(bbox_print)) {
// Wait for the user to remove the priming extrusions, otherwise they would
// get covered by the print.
fprintf(file, "M1 Remove priming towers and click button.\n");
} else {
_write(file, "M1 Remove priming towers and click button.\n");
}
else {
// Just wait for a bit to let the user check, that the priming succeeded.
//TODO Add a message explaining what the printer is waiting for. This needs a firmware fix.
fprintf(file, "M1 S10\n");
_write(file, "M1 S10\n");
}
}
// Extrude the layers.
@ -747,26 +761,29 @@ void GCode::_do_export(Print &print, FILE *file)
this->process_layer(file, print, layer.second, layer_tools, size_t(-1));
}
if (m_pressure_equalizer)
write(file, m_pressure_equalizer->process("", true));
_write(file, m_pressure_equalizer->process("", true));
if (m_wipe_tower)
// Purge the extruder, pull out the active filament.
write(file, m_wipe_tower->finalize(*this));
_write(file, m_wipe_tower->finalize(*this));
}
// Write end commands to file.
write(file, this->retract());
write(file, m_writer.set_fan(false));
_write(file, this->retract());
_write(file, m_writer.set_fan(false));
// Process filament-specific gcode in extruder order.
if (print.config.single_extruder_multi_material) {
// Process the end_filament_gcode for the active filament only.
writeln(file, this->placeholder_parser_process("end_filament_gcode", print.config.end_filament_gcode.get_at(m_writer.extruder()->id()), m_writer.extruder()->id()));
_writeln(file, this->placeholder_parser_process("end_filament_gcode", print.config.end_filament_gcode.get_at(m_writer.extruder()->id()), m_writer.extruder()->id()));
} else {
for (const std::string &end_gcode : print.config.end_filament_gcode.values)
writeln(file, this->placeholder_parser_process("end_gcode", end_gcode, (unsigned int)(&end_gcode - &print.config.end_filament_gcode.values.front())));
_writeln(file, this->placeholder_parser_process("end_filament_gcode", end_gcode, (unsigned int)(&end_gcode - &print.config.end_filament_gcode.values.front())));
}
writeln(file, this->placeholder_parser_process("end_gcode", print.config.end_gcode, m_writer.extruder()->id()));
write(file, m_writer.update_progress(m_layer_count, m_layer_count, true)); // 100%
write(file, m_writer.postamble());
_writeln(file, this->placeholder_parser_process("end_gcode", print.config.end_gcode, m_writer.extruder()->id()));
_write(file, m_writer.update_progress(m_layer_count, m_layer_count, true)); // 100%
_write(file, m_writer.postamble());
// calculates estimated printing time
m_time_estimator.calculate_time();
// Get filament stats.
print.filament_stats.clear();
@ -774,37 +791,40 @@ void GCode::_do_export(Print &print, FILE *file)
print.total_extruded_volume = 0.;
print.total_weight = 0.;
print.total_cost = 0.;
print.estimated_print_time = m_time_estimator.get_time_hms();
for (const Extruder &extruder : m_writer.extruders()) {
double used_filament = extruder.used_filament();
double extruded_volume = extruder.extruded_volume();
double filament_weight = extruded_volume * extruder.filament_density() * 0.001;
double filament_cost = filament_weight * extruder.filament_cost() * 0.001;
print.filament_stats.insert(std::pair<size_t,float>(extruder.id(), used_filament));
fprintf(file, "; filament used = %.1lfmm (%.1lfcm3)\n", used_filament, extruded_volume * 0.001);
_write_format(file, "; filament used = %.1lfmm (%.1lfcm3)\n", used_filament, extruded_volume * 0.001);
if (filament_weight > 0.) {
print.total_weight = print.total_weight + filament_weight;
fprintf(file, "; filament used = %.1lf\n", filament_weight);
_write_format(file, "; filament used = %.1lf\n", filament_weight);
if (filament_cost > 0.) {
print.total_cost = print.total_cost + filament_cost;
fprintf(file, "; filament cost = %.1lf\n", filament_cost);
_write_format(file, "; filament cost = %.1lf\n", filament_cost);
}
}
print.total_used_filament = print.total_used_filament + used_filament;
print.total_used_filament = print.total_used_filament + used_filament;
print.total_extruded_volume = print.total_extruded_volume + extruded_volume;
}
fprintf(file, "; total filament cost = %.1lf\n", print.total_cost);
_write_format(file, "; total filament cost = %.1lf\n", print.total_cost);
_write_format(file, "; estimated printing time = %s\n", m_time_estimator.get_time_hms().c_str());
// Append full config.
fprintf(file, "\n");
_write(file, "\n");
{
StaticPrintConfig *configs[] = { &print.config, &print.default_object_config, &print.default_region_config };
for (size_t i = 0; i < sizeof(configs) / sizeof(configs[0]); ++ i) {
StaticPrintConfig *cfg = configs[i];
for (const std::string &key : cfg->keys())
if (key != "compatible_printers")
fprintf(file, "; %s = %s\n", key.c_str(), cfg->serialize(key).c_str());
}
std::string full_config = "";
append_full_config(print, full_config);
if (!full_config.empty())
_write(file, full_config);
}
// starts analizer calculations
if (preview_data != nullptr)
m_analyzer.calc_gcode_preview_data(*preview_data);
}
std::string GCode::placeholder_parser_process(const std::string &name, const std::string &templ, unsigned int current_extruder_id, const DynamicConfig *config_override)
@ -893,7 +913,7 @@ void GCode::_print_first_layer_bed_temperature(FILE *file, Print &print, const s
// the custom start G-code emited these.
std::string set_temp_gcode = m_writer.set_bed_temperature(temp, wait);
if (! temp_set_by_gcode)
write(file, set_temp_gcode);
_write(file, set_temp_gcode);
}
// Write 1st layer extruder temperatures into the G-code.
@ -916,7 +936,7 @@ void GCode::_print_first_layer_extruder_temperatures(FILE *file, Print &print, c
// Set temperature of the first printing extruder only.
int temp = print.config.first_layer_temperature.get_at(first_printing_extruder_id);
if (temp > 0)
write(file, m_writer.set_temperature(temp, wait, first_printing_extruder_id));
_write(file, m_writer.set_temperature(temp, wait, first_printing_extruder_id));
} else {
// Set temperatures of all the printing extruders.
for (unsigned int tool_id : print.extruders()) {
@ -924,7 +944,7 @@ void GCode::_print_first_layer_extruder_temperatures(FILE *file, Print &print, c
if (print.config.ooze_prevention.value)
temp += print.config.standby_temperature_delta.value;
if (temp > 0)
write(file, m_writer.set_temperature(temp, wait, tool_id));
_write(file, m_writer.set_temperature(temp, wait, tool_id));
}
}
}
@ -1296,12 +1316,7 @@ void GCode::process_layer(
if (print_object == nullptr)
// This layer is empty for this particular object, it has neither object extrusions nor support extrusions at this print_z.
continue;
if (m_enable_analyzer_markers) {
// Store the binary pointer to the layer object directly into the G-code to be accessed by the GCodeAnalyzer.
char buf[64];
sprintf(buf, ";_LAYEROBJ:%p\n", m_layer);
gcode += buf;
}
m_config.apply(print_object->config, true);
m_layer = layers[layer_id].layer();
if (m_config.avoid_crossing_perimeters)
@ -1358,7 +1373,7 @@ void GCode::process_layer(
gcode = m_pressure_equalizer->process(gcode.c_str(), false);
// printf("G-code after filter:\n%s\n", out.c_str());
write(file, gcode);
_write(file, gcode);
}
void GCode::apply_print_config(const PrintConfig &print_config)
@ -1367,6 +1382,24 @@ void GCode::apply_print_config(const PrintConfig &print_config)
m_config.apply(print_config);
}
void GCode::append_full_config(const Print& print, std::string& str)
{
char buff[4096];
const StaticPrintConfig *configs[] = { &print.config, &print.default_object_config, &print.default_region_config };
for (size_t i = 0; i < sizeof(configs) / sizeof(configs[0]); ++i) {
const StaticPrintConfig *cfg = configs[i];
for (const std::string &key : cfg->keys())
{
if (key != "compatible_printers")
{
sprintf(buff, "; %s = %s\n", key.c_str(), cfg->serialize(key).c_str());
str += buff;
}
}
}
}
void GCode::set_extruders(const std::vector<unsigned int> &extruder_ids)
{
m_writer.set_extruders(extruder_ids);
@ -1443,7 +1476,9 @@ static inline const char* ExtrusionRole2String(const ExtrusionRole role)
case erSkirt: return "erSkirt";
case erSupportMaterial: return "erSupportMaterial";
case erSupportMaterialInterface: return "erSupportMaterialInterface";
case erWipeTower: return "erWipeTower";
case erMixed: return "erMixed";
default: return "erInvalid";
};
}
@ -1993,6 +2028,57 @@ std::string GCode::extrude_support(const ExtrusionEntityCollection &support_fill
return gcode;
}
void GCode::_write(FILE* file, const char *what)
{
if (what != nullptr) {
// apply analyzer, if enabled
const char* gcode = m_enable_analyzer ? m_analyzer.process_gcode(what).c_str() : what;
// writes string to file
fwrite(gcode, 1, ::strlen(gcode), file);
// updates time estimator and gcode lines vector
m_time_estimator.add_gcode_block(gcode);
}
}
void GCode::_writeln(FILE* file, const std::string &what)
{
if (! what.empty())
_write(file, (what.back() == '\n') ? what : (what + '\n'));
}
void GCode::_write_format(FILE* file, const char* format, ...)
{
va_list args;
va_start(args, format);
int buflen;
{
va_list args2;
va_copy(args2, args);
buflen =
#ifdef _MSC_VER
::_vscprintf(format, args2)
#else
::vsnprintf(nullptr, 0, format, args2)
#endif
+ 1;
va_end(args2);
}
char buffer[1024];
bool buffer_dynamic = buflen > 1024;
char *bufptr = buffer_dynamic ? (char*)malloc(buflen) : buffer;
int res = ::vsnprintf(bufptr, buflen, format, args);
if (res > 0)
_write(file, bufptr);
if (buffer_dynamic)
free(bufptr);
va_end(args);
}
std::string GCode::_extrude(const ExtrusionPath &path, std::string description, double speed)
{
std::string gcode;
@ -2071,14 +2157,57 @@ std::string GCode::_extrude(const ExtrusionPath &path, std::string description,
double F = speed * 60; // convert mm/sec to mm/min
// extrude arc or line
if (m_enable_extrusion_role_markers || m_enable_analyzer_markers) {
if (path.role() != m_last_extrusion_role) {
if (m_enable_extrusion_role_markers || m_enable_analyzer)
{
if (path.role() != m_last_extrusion_role)
{
m_last_extrusion_role = path.role();
if (m_enable_extrusion_role_markers)
{
char buf[32];
sprintf(buf, ";_EXTRUSION_ROLE:%d\n", int(m_last_extrusion_role));
gcode += buf;
}
if (m_enable_analyzer)
{
char buf[32];
sprintf(buf, ";%s%d\n", GCodeAnalyzer::Extrusion_Role_Tag.c_str(), int(m_last_extrusion_role));
gcode += buf;
}
}
}
// adds analyzer tags and updates analyzer's tracking data
if (m_enable_analyzer)
{
if (m_last_mm3_per_mm != path.mm3_per_mm)
{
m_last_mm3_per_mm = path.mm3_per_mm;
char buf[32];
sprintf(buf, ";_EXTRUSION_ROLE:%d\n", int(path.role()));
sprintf(buf, ";%s%f\n", GCodeAnalyzer::Mm3_Per_Mm_Tag.c_str(), m_last_mm3_per_mm);
gcode += buf;
}
if (m_last_width != path.width)
{
m_last_width = path.width;
char buf[32];
sprintf(buf, ";%s%f\n", GCodeAnalyzer::Width_Tag.c_str(), m_last_width);
gcode += buf;
}
if (m_last_height != path.height)
{
m_last_height = path.height;
char buf[32];
sprintf(buf, ";%s%f\n", GCodeAnalyzer::Height_Tag.c_str(), m_last_height);
gcode += buf;
}
}
std::string comment;
if (m_enable_cooling_markers) {
if (is_bridge(path.role()))
@ -2182,8 +2311,7 @@ bool GCode::needs_retraction(const Polyline &travel, ExtrusionRole role)
return true;
}
std::string
GCode::retract(bool toolchange)
std::string GCode::retract(bool toolchange)
{
std::string gcode;

View file

@ -15,7 +15,9 @@
#include "GCode/SpiralVase.hpp"
#include "GCode/ToolOrdering.hpp"
#include "GCode/WipeTower.hpp"
#include "GCodeTimeEstimator.hpp"
#include "EdgeGrid.hpp"
#include "GCode/Analyzer.hpp"
#include <memory>
#include <string>
@ -24,6 +26,7 @@ namespace Slic3r {
// Forward declarations.
class GCode;
class GCodePreviewData;
class AvoidCrossingPerimeters {
public:
@ -117,13 +120,16 @@ public:
m_enable_loop_clipping(true),
m_enable_cooling_markers(false),
m_enable_extrusion_role_markers(false),
m_enable_analyzer_markers(false),
m_enable_analyzer(false),
m_layer_count(0),
m_layer_index(-1),
m_layer(nullptr),
m_volumetric_speed(0),
m_last_pos_defined(false),
m_last_extrusion_role(erNone),
m_last_mm3_per_mm(GCodeAnalyzer::Default_mm3_per_mm),
m_last_width(GCodeAnalyzer::Default_Width),
m_last_height(GCodeAnalyzer::Default_Height),
m_brim_done(false),
m_second_layer_things_done(false),
m_last_obj_copy(nullptr, Point(std::numeric_limits<coord_t>::max(), std::numeric_limits<coord_t>::max()))
@ -131,7 +137,7 @@ public:
~GCode() {}
// throws std::runtime_exception
void do_export(Print *print, const char *path);
void do_export(Print *print, const char *path, GCodePreviewData *preview_data = nullptr);
// Exported for the helper classes (OozePrevention, Wipe) and for the Perl binding for unit tests.
const Pointf& origin() const { return m_origin; }
@ -154,8 +160,11 @@ public:
void set_layer_count(unsigned int value) { m_layer_count = value; }
void apply_print_config(const PrintConfig &print_config);
// append full config to the given string
static void append_full_config(const Print& print, std::string& str);
protected:
void _do_export(Print &print, FILE *file);
void _do_export(Print &print, FILE *file, GCodePreviewData *preview_data);
// Object and support extrusions of the same PrintObject at the same print_z.
struct LayerToPrint
@ -240,9 +249,10 @@ protected:
// Markers for the Pressure Equalizer to recognize the extrusion type.
// The Pressure Equalizer removes the markers from the final G-code.
bool m_enable_extrusion_role_markers;
// Extended markers for the G-code Analyzer.
// Enableds the G-code Analyzer.
// Extended markers will be added during G-code generation.
// The G-code Analyzer will remove these comments from the final G-code.
bool m_enable_analyzer_markers;
bool m_enable_analyzer;
// How many times will change_layer() be called?
// change_layer() will update the progress bar.
unsigned int m_layer_count;
@ -255,6 +265,10 @@ protected:
double m_volumetric_speed;
// Support for the extrusion role markers. Which marker is active?
ExtrusionRole m_last_extrusion_role;
// Support for G-Code Analyzer
double m_last_mm3_per_mm;
float m_last_width;
float m_last_height;
Point m_last_pos;
bool m_last_pos_defined;
@ -273,6 +287,24 @@ protected:
// Index of a last object copy extruded.
std::pair<const PrintObject*, Point> m_last_obj_copy;
// Time estimator
GCodeTimeEstimator m_time_estimator;
// Analyzer
GCodeAnalyzer m_analyzer;
// Write a string into a file.
void _write(FILE* file, const std::string& what) { this->_write(file, what.c_str()); }
void _write(FILE* file, const char *what);
// Write a string into a file.
// Add a newline, if the string does not end with a newline already.
// Used to export a custom G-code section processed by the PlaceholderParser.
void _writeln(FILE* file, const std::string& what);
// Formats and write into a file the given data.
void _write_format(FILE* file, const char* format, ...);
std::string _extrude(const ExtrusionPath &path, std::string description = "", double speed = -1);
void _print_first_layer_bed_temperature(FILE *file, Print &print, const std::string &gcode, unsigned int first_printing_extruder_id, bool wait);
void _print_first_layer_extruder_temperatures(FILE *file, Print &print, const std::string &gcode, unsigned int first_printing_extruder_id, bool wait);

File diff suppressed because it is too large Load diff

View file

@ -1,152 +1,227 @@
#ifndef slic3r_GCode_PressureEqualizer_hpp_
#define slic3r_GCode_PressureEqualizer_hpp_
#ifndef slic3r_GCode_Analyzer_hpp_
#define slic3r_GCode_Analyzer_hpp_
#include "../libslic3r.h"
#include "../PrintConfig.hpp"
#include "../ExtrusionEntity.hpp"
#include "Point.hpp"
#include "GCodeReader.hpp"
namespace Slic3r {
enum GCodeMoveType
{
GCODE_MOVE_TYPE_NOOP,
GCODE_MOVE_TYPE_RETRACT,
GCODE_MOVE_TYPE_UNRETRACT,
GCODE_MOVE_TYPE_TOOL_CHANGE,
GCODE_MOVE_TYPE_MOVE,
GCODE_MOVE_TYPE_EXTRUDE,
};
class GCodePreviewData;
// For visualization purposes, for the purposes of the G-code analysis and timing.
// The size of this structure is 56B.
// Keep the size of this structure as small as possible, because all moves of a complete print
// may be held in RAM.
struct GCodeMove
{
bool moving_xy(const float* pos_start) const { return fabs(pos_end[0] - pos_start[0]) > 0.f || fabs(pos_end[1] - pos_start[1]) > 0.f; }
bool moving_xy() const { return moving_xy(get_pos_start()); }
bool moving_z (const float* pos_start) const { return fabs(pos_end[2] - pos_start[2]) > 0.f; }
bool moving_z () const { return moving_z(get_pos_start()); }
bool extruding(const float* pos_start) const { return moving_xy() && pos_end[3] > pos_start[3]; }
bool extruding() const { return extruding(get_pos_start()); }
bool retracting(const float* pos_start) const { return pos_end[3] < pos_start[3]; }
bool retracting() const { return retracting(get_pos_start()); }
bool deretracting(const float* pos_start) const { return ! moving_xy() && pos_end[3] > pos_start[3]; }
bool deretracting() const { return deretracting(get_pos_start()); }
float dist_xy2(const float* pos_start) const { return (pos_end[0] - pos_start[0]) * (pos_end[0] - pos_start[0]) + (pos_end[1] - pos_start[1]) * (pos_end[1] - pos_start[1]); }
float dist_xy2() const { return dist_xy2(get_pos_start()); }
float dist_xyz2(const float* pos_start) const { return (pos_end[0] - pos_start[0]) * (pos_end[0] - pos_start[0]) + (pos_end[1] - pos_start[1]) * (pos_end[1] - pos_start[1]) + (pos_end[2] - pos_start[2]) * (pos_end[2] - pos_start[2]); }
float dist_xyz2() const { return dist_xyz2(get_pos_start()); }
float dist_xy(const float* pos_start) const { return sqrt(dist_xy2(pos_start)); }
float dist_xy() const { return dist_xy(get_pos_start()); }
float dist_xyz(const float* pos_start) const { return sqrt(dist_xyz2(pos_start)); }
float dist_xyz() const { return dist_xyz(get_pos_start()); }
float dist_e(const float* pos_start) const { return fabs(pos_end[3] - pos_start[3]); }
float dist_e() const { return dist_e(get_pos_start()); }
float feedrate() const { return pos_end[4]; }
float time(const float* pos_start) const { return dist_xyz(pos_start) / feedrate(); }
float time() const { return time(get_pos_start()); }
float time_inv(const float* pos_start) const { return feedrate() / dist_xyz(pos_start); }
float time_inv() const { return time_inv(get_pos_start()); }
const float* get_pos_start() const { assert(type != GCODE_MOVE_TYPE_NOOP); return this[-1].pos_end; }
// Pack the enums to conserve space. With C++x11 the allocation size could be declared for enums, but for old C++ this is the only portable way.
// GCodeLineType
uint8_t type;
// Index of the active extruder.
uint8_t extruder_id;
// ExtrusionRole
uint8_t extrusion_role;
// For example, is it a bridge flow? Is the fan on?
uint8_t flags;
// X,Y,Z,E,F. Storing the state of the currently active extruder only.
float pos_end[5];
// Extrusion width, height for this segment in um.
uint16_t extrusion_width;
uint16_t extrusion_height;
};
typedef std::vector<GCodeMove> GCodeMoves;
struct GCodeLayer
{
// Index of an object printed.
size_t object_idx;
// Index of an object instance printed.
size_t object_instance_idx;
// Index of the layer printed.
size_t layer_idx;
// Top z coordinate of the layer printed.
float layer_z_top;
// Moves over this layer. The 0th move is always of type GCODELINETYPE_NOOP and
// it sets the initial position and tool for the layer.
GCodeMoves moves;
// Indices into m_moves, where the tool changes happen.
// This is useful, if one wants to display just only a piece of the path quickly.
std::vector<size_t> tool_changes;
};
typedef std::vector<GCodeLayer*> GCodeLayerPtrs;
class GCodeMovesDB
{
public:
GCodeMovesDB() {};
~GCodeMovesDB() { reset(); }
void reset();
GCodeLayerPtrs m_layers;
};
// Processes a G-code to extract moves and their types.
// This information is then used to render the print simulation colored by the extrusion type
// or various speeds.
// The GCodeAnalyzer is employed as a G-Code filter. It reads the G-code as it is generated,
// parses the comments generated by Slic3r just for the analyzer, and removes these comments.
class GCodeAnalyzer
{
public:
GCodeAnalyzer(const Slic3r::GCodeConfig *config);
~GCodeAnalyzer();
static const std::string Extrusion_Role_Tag;
static const std::string Mm3_Per_Mm_Tag;
static const std::string Width_Tag;
static const std::string Height_Tag;
void reset();
static const double Default_mm3_per_mm;
static const float Default_Width;
static const float Default_Height;
// Process a next batch of G-code lines. Flush the internal buffers if asked for.
const char* process(const char *szGCode, bool flush);
// Length of the buffer returned by process().
size_t get_output_buffer_length() const { return output_buffer_length; }
enum EUnits : unsigned char
{
Millimeters,
Inches
};
enum EAxis : unsigned char
{
X,
Y,
Z,
E,
Num_Axis
};
enum EPositioningType : unsigned char
{
Absolute,
Relative
};
struct Metadata
{
ExtrusionRole extrusion_role;
unsigned int extruder_id;
double mm3_per_mm;
float width; // mm
float height; // mm
float feedrate; // mm/s
Metadata();
Metadata(ExtrusionRole extrusion_role, unsigned int extruder_id, double mm3_per_mm, float width, float height, float feedrate);
bool operator != (const Metadata& other) const;
};
struct GCodeMove
{
enum EType : unsigned char
{
Noop,
Retract,
Unretract,
Tool_change,
Move,
Extrude,
Num_Types
};
EType type;
Metadata data;
Pointf3 start_position;
Pointf3 end_position;
float delta_extruder;
GCodeMove(EType type, ExtrusionRole extrusion_role, unsigned int extruder_id, double mm3_per_mm, float width, float height, float feedrate, const Pointf3& start_position, const Pointf3& end_position, float delta_extruder);
GCodeMove(EType type, const Metadata& data, const Pointf3& start_position, const Pointf3& end_position, float delta_extruder);
};
typedef std::vector<GCodeMove> GCodeMovesList;
typedef std::map<GCodeMove::EType, GCodeMovesList> TypeToMovesMap;
private:
// Keeps the reference, does not own the config.
const Slic3r::GCodeConfig *m_config;
struct State
{
EUnits units;
EPositioningType positioning_xyz_type;
EPositioningType positioning_e_type;
Metadata data;
Pointf3 start_position;
float start_extrusion;
float position[Num_Axis];
};
// Internal data.
// X,Y,Z,E,F
float m_current_pos[5];
size_t m_current_extruder;
ExtrusionRole m_current_extrusion_role;
uint16_t m_current_extrusion_width;
uint16_t m_current_extrusion_height;
bool m_retracted;
private:
State m_state;
GCodeReader m_parser;
TypeToMovesMap m_moves_map;
GCodeMovesDB *m_moves;
// The output of process_layer()
std::string m_process_output;
// Output buffer will only grow. It will not be reallocated over and over.
std::vector<char> output_buffer;
size_t output_buffer_length;
public:
GCodeAnalyzer();
bool process_line(const char *line, const size_t len);
// Reinitialize the analyzer
void reset();
// Push the text to the end of the output_buffer.
void push_to_output(const char *text, const size_t len, bool add_eol = true);
// Adds the gcode contained in the given string to the analysis and returns it after removing the workcodes
const std::string& process_gcode(const std::string& gcode);
// Calculates all data needed for gcode visualization
void calc_gcode_preview_data(GCodePreviewData& preview_data);
static bool is_valid_extrusion_role(ExtrusionRole role);
private:
// Processes the given gcode line
void _process_gcode_line(GCodeReader& reader, const GCodeReader::GCodeLine& line);
// Move
void _processG1(const GCodeReader::GCodeLine& line);
// Firmware controlled Retract
void _processG22(const GCodeReader::GCodeLine& line);
// Firmware controlled Unretract
void _processG23(const GCodeReader::GCodeLine& line);
// Set to Absolute Positioning
void _processG90(const GCodeReader::GCodeLine& line);
// Set to Relative Positioning
void _processG91(const GCodeReader::GCodeLine& line);
// Set Position
void _processG92(const GCodeReader::GCodeLine& line);
// Set extruder to absolute mode
void _processM82(const GCodeReader::GCodeLine& line);
// Set extruder to relative mode
void _processM83(const GCodeReader::GCodeLine& line);
// Processes T line (Select Tool)
void _processT(const GCodeReader::GCodeLine& line);
// Processes the tags
// Returns true if any tag has been processed
bool _process_tags(const GCodeReader::GCodeLine& line);
// Processes extrusion role tag
void _process_extrusion_role_tag(const std::string& comment, size_t pos);
// Processes mm3_per_mm tag
void _process_mm3_per_mm_tag(const std::string& comment, size_t pos);
// Processes width tag
void _process_width_tag(const std::string& comment, size_t pos);
// Processes height tag
void _process_height_tag(const std::string& comment, size_t pos);
void _set_units(EUnits units);
EUnits _get_units() const;
void _set_positioning_xyz_type(EPositioningType type);
EPositioningType _get_positioning_xyz_type() const;
void _set_positioning_e_type(EPositioningType type);
EPositioningType _get_positioning_e_type() const;
void _set_extrusion_role(ExtrusionRole extrusion_role);
ExtrusionRole _get_extrusion_role() const;
void _set_extruder_id(unsigned int id);
unsigned int _get_extruder_id() const;
void _set_mm3_per_mm(double value);
double _get_mm3_per_mm() const;
void _set_width(float width);
float _get_width() const;
void _set_height(float height);
float _get_height() const;
void _set_feedrate(float feedrate_mm_sec);
float _get_feedrate() const;
void _set_axis_position(EAxis axis, float position);
float _get_axis_position(EAxis axis) const;
// Sets axes position to zero
void _reset_axes_position();
void _set_start_position(const Pointf3& position);
const Pointf3& _get_start_position() const;
void _set_start_extrusion(float extrusion);
float _get_start_extrusion() const;
float _get_delta_extrusion() const;
// Returns current xyz position (from m_state.position[])
Pointf3 _get_end_position() const;
// Adds a new move with the given data
void _store_move(GCodeMove::EType type);
// Checks if the given int is a valid extrusion role (contained into enum ExtrusionRole)
bool _is_valid_extrusion_role(int value) const;
void _calc_gcode_preview_extrusion_layers(GCodePreviewData& preview_data);
void _calc_gcode_preview_travel(GCodePreviewData& preview_data);
void _calc_gcode_preview_retractions(GCodePreviewData& preview_data);
void _calc_gcode_preview_unretractions(GCodePreviewData& preview_data);
};
} // namespace Slic3r
#endif /* slic3r_GCode_PressureEqualizer_hpp_ */
#endif /* slic3r_GCode_Analyzer_hpp_ */

View file

@ -0,0 +1,408 @@
#include "Analyzer.hpp"
#include "PreviewData.hpp"
#include <float.h>
namespace Slic3r {
const GCodePreviewData::Color GCodePreviewData::Color::Dummy(0.0f, 0.0f, 0.0f, 0.0f);
GCodePreviewData::Color::Color()
{
rgba[0] = 1.0f;
rgba[1] = 1.0f;
rgba[2] = 1.0f;
rgba[3] = 1.0f;
}
GCodePreviewData::Color::Color(float r, float g, float b, float a)
{
rgba[0] = r;
rgba[1] = g;
rgba[2] = b;
rgba[3] = a;
}
std::vector<unsigned char> GCodePreviewData::Color::as_bytes() const
{
std::vector<unsigned char> ret;
for (unsigned int i = 0; i < 4; ++i)
{
ret.push_back((unsigned char)(255.0f * rgba[i]));
}
return ret;
}
GCodePreviewData::Extrusion::Layer::Layer(float z, const ExtrusionPaths& paths)
: z(z)
, paths(paths)
{
}
GCodePreviewData::Travel::Polyline::Polyline(EType type, EDirection direction, float feedrate, unsigned int extruder_id, const Polyline3& polyline)
: type(type)
, direction(direction)
, feedrate(feedrate)
, extruder_id(extruder_id)
, polyline(polyline)
{
}
const GCodePreviewData::Color GCodePreviewData::Range::Default_Colors[Colors_Count] =
{
Color(0.043f, 0.173f, 0.478f, 1.0f),
Color(0.075f, 0.349f, 0.522f, 1.0f),
Color(0.110f, 0.533f, 0.569f, 1.0f),
Color(0.016f, 0.839f, 0.059f, 1.0f),
Color(0.667f, 0.949f, 0.000f, 1.0f),
Color(0.988f, 0.975f, 0.012f, 1.0f),
Color(0.961f, 0.808f, 0.039f, 1.0f),
Color(0.890f, 0.533f, 0.125f, 1.0f),
Color(0.820f, 0.408f, 0.188f, 1.0f),
Color(0.761f, 0.322f, 0.235f, 1.0f)
};
GCodePreviewData::Range::Range()
{
reset();
}
void GCodePreviewData::Range::reset()
{
min = FLT_MAX;
max = -FLT_MAX;
}
bool GCodePreviewData::Range::empty() const
{
return min == max;
}
void GCodePreviewData::Range::update_from(float value)
{
min = std::min(min, value);
max = std::max(max, value);
}
void GCodePreviewData::Range::set_from(const Range& other)
{
min = other.min;
max = other.max;
}
float GCodePreviewData::Range::step_size() const
{
return (max - min) / (float)Colors_Count;
}
const GCodePreviewData::Color& GCodePreviewData::Range::get_color_at_max() const
{
return colors[Colors_Count - 1];
}
const GCodePreviewData::Color& GCodePreviewData::Range::get_color_at(float value) const
{
return empty() ? get_color_at_max() : colors[clamp((unsigned int)0, Colors_Count - 1, (unsigned int)((value - min) / step_size()))];
}
GCodePreviewData::LegendItem::LegendItem(const std::string& text, const GCodePreviewData::Color& color)
: text(text)
, color(color)
{
}
const GCodePreviewData::Color GCodePreviewData::Extrusion::Default_Extrusion_Role_Colors[Num_Extrusion_Roles] =
{
Color(0.0f, 0.0f, 0.0f, 1.0f), // erNone
Color(1.0f, 0.0f, 0.0f, 1.0f), // erPerimeter
Color(0.0f, 1.0f, 0.0f, 1.0f), // erExternalPerimeter
Color(0.0f, 0.0f, 1.0f, 1.0f), // erOverhangPerimeter
Color(1.0f, 1.0f, 0.0f, 1.0f), // erInternalInfill
Color(1.0f, 0.0f, 1.0f, 1.0f), // erSolidInfill
Color(0.0f, 1.0f, 1.0f, 1.0f), // erTopSolidInfill
Color(0.5f, 0.5f, 0.5f, 1.0f), // erBridgeInfill
Color(1.0f, 1.0f, 1.0f, 1.0f), // erGapFill
Color(0.5f, 0.0f, 0.0f, 1.0f), // erSkirt
Color(0.0f, 0.5f, 0.0f, 1.0f), // erSupportMaterial
Color(0.0f, 0.0f, 0.5f, 1.0f), // erSupportMaterialInterface
Color(0.7f, 0.89f, 0.67f, 1.0f), // erWipeTower
Color(0.0f, 0.0f, 0.0f, 1.0f) // erMixed
};
// todo: merge with Slic3r::ExtrusionRole2String() from GCode.cpp
const std::string GCodePreviewData::Extrusion::Default_Extrusion_Role_Names[Num_Extrusion_Roles]
{
"None",
"Perimeter",
"External perimeter",
"Overhang perimeter",
"Internal infill",
"Solid infill",
"Top solid infill",
"Bridge infill",
"Gap fill",
"Skirt",
"Support material",
"Support material interface",
"Wipe tower",
"Mixed"
};
const GCodePreviewData::Extrusion::EViewType GCodePreviewData::Extrusion::Default_View_Type = GCodePreviewData::Extrusion::FeatureType;
void GCodePreviewData::Extrusion::set_default()
{
view_type = Default_View_Type;
::memcpy((void*)role_colors, (const void*)Default_Extrusion_Role_Colors, Num_Extrusion_Roles * sizeof(Color));
::memcpy((void*)ranges.height.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color));
::memcpy((void*)ranges.width.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color));
::memcpy((void*)ranges.feedrate.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color));
for (unsigned int i = 0; i < Num_Extrusion_Roles; ++i)
{
role_names[i] = Default_Extrusion_Role_Names[i];
}
role_flags = 0;
for (unsigned int i = 0; i < Num_Extrusion_Roles; ++i)
{
role_flags |= 1 << i;
}
}
bool GCodePreviewData::Extrusion::is_role_flag_set(ExtrusionRole role) const
{
return is_role_flag_set(role_flags, role);
}
bool GCodePreviewData::Extrusion::is_role_flag_set(unsigned int flags, ExtrusionRole role)
{
return GCodeAnalyzer::is_valid_extrusion_role(role) && (flags & (1 << (role - erPerimeter))) != 0;
}
const float GCodePreviewData::Travel::Default_Width = 0.075f;
const float GCodePreviewData::Travel::Default_Height = 0.075f;
const GCodePreviewData::Color GCodePreviewData::Travel::Default_Type_Colors[Num_Types] =
{
Color(0.0f, 0.0f, 0.75f, 1.0f), // Move
Color(0.0f, 0.75f, 0.0f, 1.0f), // Extrude
Color(0.75f, 0.0f, 0.0f, 1.0f), // Retract
};
void GCodePreviewData::Travel::set_default()
{
width = Default_Width;
height = Default_Height;
::memcpy((void*)type_colors, (const void*)Default_Type_Colors, Num_Types * sizeof(Color));
is_visible = false;
}
const GCodePreviewData::Color GCodePreviewData::Retraction::Default_Color = GCodePreviewData::Color(1.0f, 1.0f, 1.0f, 1.0f);
GCodePreviewData::Retraction::Position::Position(const Point3& position, float width, float height)
: position(position)
, width(width)
, height(height)
{
}
void GCodePreviewData::Retraction::set_default()
{
color = Default_Color;
is_visible = false;
}
void GCodePreviewData::Shell::set_default()
{
is_visible = false;
}
GCodePreviewData::GCodePreviewData()
{
set_default();
}
void GCodePreviewData::set_default()
{
extrusion.set_default();
travel.set_default();
retraction.set_default();
unretraction.set_default();
shell.set_default();
}
void GCodePreviewData::reset()
{
extrusion.layers.clear();
travel.polylines.clear();
retraction.positions.clear();
unretraction.positions.clear();
}
bool GCodePreviewData::empty() const
{
return extrusion.layers.empty() && travel.polylines.empty() && retraction.positions.empty() && unretraction.positions.empty();
}
const GCodePreviewData::Color& GCodePreviewData::get_extrusion_role_color(ExtrusionRole role) const
{
return extrusion.role_colors[role];
}
const GCodePreviewData::Color& GCodePreviewData::get_extrusion_height_color(float height) const
{
return extrusion.ranges.height.get_color_at(height);
}
const GCodePreviewData::Color& GCodePreviewData::get_extrusion_width_color(float width) const
{
return extrusion.ranges.width.get_color_at(width);
}
const GCodePreviewData::Color& GCodePreviewData::get_extrusion_feedrate_color(float feedrate) const
{
return extrusion.ranges.feedrate.get_color_at(feedrate);
}
void GCodePreviewData::set_extrusion_role_color(const std::string& role_name, float red, float green, float blue, float alpha)
{
for (unsigned int i = 0; i < Extrusion::Num_Extrusion_Roles; ++i)
{
if (role_name == extrusion.role_names[i])
{
extrusion.role_colors[i] = Color(red, green, blue, alpha);
break;
}
}
}
void GCodePreviewData::set_extrusion_paths_colors(const std::vector<std::string>& colors)
{
unsigned int size = (unsigned int)colors.size();
if (size % 2 != 0)
return;
for (unsigned int i = 0; i < size; i += 2)
{
const std::string& color_str = colors[i + 1];
if (color_str.size() == 6)
{
bool valid = true;
for (int c = 0; c < 6; ++c)
{
if (::isxdigit(color_str[c]) == 0)
{
valid = false;
break;
}
}
if (valid)
{
unsigned int color;
std::stringstream ss;
ss << std::hex << color_str;
ss >> color;
float den = 1.0f / 255.0f;
float r = (float)((color & 0xFF0000) >> 16) * den;
float g = (float)((color & 0x00FF00) >> 8) * den;
float b = (float)(color & 0x0000FF) * den;
this->set_extrusion_role_color(colors[i], r, g, b, 1.0f);
}
}
}
}
std::string GCodePreviewData::get_legend_title() const
{
switch (extrusion.view_type)
{
case Extrusion::FeatureType:
return "Feature type";
case Extrusion::Height:
return "Height (mm)";
case Extrusion::Width:
return "Width (mm)";
case Extrusion::Feedrate:
return "Speed (mm/s)";
case Extrusion::Tool:
return "Tool";
}
return "";
}
GCodePreviewData::LegendItemsList GCodePreviewData::get_legend_items(const std::vector<float>& tool_colors) const
{
struct Helper
{
static void FillListFromRange(LegendItemsList& list, const Range& range, unsigned int decimals, float scale_factor)
{
list.reserve(Range::Colors_Count);
float step = range.step_size();
for (unsigned int i = 0; i < Range::Colors_Count; ++i)
{
char buf[32];
sprintf(buf, "%.*f/%.*f", decimals, scale_factor * (range.min + (float)i * step), decimals, scale_factor * (range.min + (float)(i + 1) * step));
list.emplace_back(buf, range.colors[i]);
}
}
};
LegendItemsList items;
switch (extrusion.view_type)
{
case Extrusion::FeatureType:
{
items.reserve(erMixed - erPerimeter + 1);
for (unsigned int i = (unsigned int)erPerimeter; i < (unsigned int)erMixed; ++i)
{
items.emplace_back(extrusion.role_names[i], extrusion.role_colors[i]);
}
break;
}
case Extrusion::Height:
{
Helper::FillListFromRange(items, extrusion.ranges.height, 3, 1.0f);
break;
}
case Extrusion::Width:
{
Helper::FillListFromRange(items, extrusion.ranges.width, 3, 1.0f);
break;
}
case Extrusion::Feedrate:
{
Helper::FillListFromRange(items, extrusion.ranges.feedrate, 0, 1.0f);
break;
}
case Extrusion::Tool:
{
unsigned int tools_colors_count = tool_colors.size() / 4;
items.reserve(tools_colors_count);
for (unsigned int i = 0; i < tools_colors_count; ++i)
{
char buf[32];
sprintf(buf, "Extruder %d", i + 1);
GCodePreviewData::Color color;
::memcpy((void*)color.rgba, (const void*)(tool_colors.data() + i * 4), 4 * sizeof(float));
items.emplace_back(buf, color);
}
break;
}
}
return items;
}
} // namespace Slic3r

View file

@ -0,0 +1,205 @@
#ifndef slic3r_GCode_PreviewData_hpp_
#define slic3r_GCode_PreviewData_hpp_
#include "../libslic3r.h"
#include "../ExtrusionEntity.hpp"
#include "Point.hpp"
namespace Slic3r {
class GCodePreviewData
{
public:
struct Color
{
float rgba[4];
Color();
Color(float r, float g, float b, float a);
std::vector<unsigned char> as_bytes() const;
static const Color Dummy;
};
struct Range
{
static const unsigned int Colors_Count = 10;
static const Color Default_Colors[Colors_Count];
Color colors[Colors_Count];
float min;
float max;
Range();
void reset();
bool empty() const;
void update_from(float value);
void set_from(const Range& other);
float step_size() const;
const Color& get_color_at(float value) const;
const Color& get_color_at_max() const;
};
struct LegendItem
{
std::string text;
Color color;
LegendItem(const std::string& text, const Color& color);
};
typedef std::vector<LegendItem> LegendItemsList;
struct Extrusion
{
enum EViewType : unsigned char
{
FeatureType,
Height,
Width,
Feedrate,
Tool,
Num_View_Types
};
static const unsigned int Num_Extrusion_Roles = (unsigned int)erMixed + 1;
static const Color Default_Extrusion_Role_Colors[Num_Extrusion_Roles];
static const std::string Default_Extrusion_Role_Names[Num_Extrusion_Roles];
static const EViewType Default_View_Type;
struct Ranges
{
Range height;
Range width;
Range feedrate;
};
struct Layer
{
float z;
ExtrusionPaths paths;
Layer(float z, const ExtrusionPaths& paths);
};
typedef std::vector<Layer> LayersList;
EViewType view_type;
Color role_colors[Num_Extrusion_Roles];
std::string role_names[Num_Extrusion_Roles];
Ranges ranges;
LayersList layers;
unsigned int role_flags;
void set_default();
bool is_role_flag_set(ExtrusionRole role) const;
static bool is_role_flag_set(unsigned int flags, ExtrusionRole role);
};
struct Travel
{
enum EType : unsigned char
{
Move,
Extrude,
Retract,
Num_Types
};
static const float Default_Width;
static const float Default_Height;
static const Color Default_Type_Colors[Num_Types];
struct Polyline
{
enum EDirection
{
Vertical,
Generic,
Num_Directions
};
EType type;
EDirection direction;
float feedrate;
unsigned int extruder_id;
Polyline3 polyline;
Polyline(EType type, EDirection direction, float feedrate, unsigned int extruder_id, const Polyline3& polyline);
};
typedef std::vector<Polyline> PolylinesList;
PolylinesList polylines;
float width;
float height;
Color type_colors[Num_Types];
bool is_visible;
void set_default();
};
struct Retraction
{
static const Color Default_Color;
struct Position
{
Point3 position;
float width;
float height;
Position(const Point3& position, float width, float height);
};
typedef std::vector<Position> PositionsList;
PositionsList positions;
Color color;
bool is_visible;
void set_default();
};
struct Shell
{
bool is_visible;
void set_default();
};
Extrusion extrusion;
Travel travel;
Retraction retraction;
Retraction unretraction;
Shell shell;
GCodePreviewData();
void set_default();
void reset();
bool empty() const;
const Color& get_extrusion_role_color(ExtrusionRole role) const;
const Color& get_extrusion_height_color(float height) const;
const Color& get_extrusion_width_color(float width) const;
const Color& get_extrusion_feedrate_color(float feedrate) const;
void set_extrusion_role_color(const std::string& role_name, float red, float green, float blue, float alpha);
void set_extrusion_paths_colors(const std::vector<std::string>& colors);
std::string get_legend_title() const;
LegendItemsList get_legend_items(const std::vector<float>& tool_colors) const;
};
GCodePreviewData::Color operator + (const GCodePreviewData::Color& c1, const GCodePreviewData::Color& c2);
GCodePreviewData::Color operator * (float f, const GCodePreviewData::Color& color);
} // namespace Slic3r
#endif /* slic3r_GCode_PreviewData_hpp_ */

View file

@ -4,17 +4,7 @@
namespace Slic3r {
std::string
_format_z(float z)
{
std::ostringstream ss;
ss << std::fixed << std::setprecision(3)
<< z;
return ss.str();
}
std::string
SpiralVase::process_layer(const std::string &gcode)
std::string SpiralVase::process_layer(const std::string &gcode)
{
/* This post-processor relies on several assumptions:
- all layers are processed through it, including those that are not supposed
@ -27,7 +17,7 @@ SpiralVase::process_layer(const std::string &gcode)
// If we're not going to modify G-code, just feed it to the reader
// in order to update positions.
if (!this->enable) {
this->_reader.parse(gcode, {});
this->_reader.parse_buffer(gcode);
return gcode;
}
@ -38,16 +28,17 @@ SpiralVase::process_layer(const std::string &gcode)
bool set_z = false;
{
//FIXME Performance warning: This copies the GCodeConfig of the reader.
GCodeReader r = this->_reader; // clone
r.parse(gcode, [&total_layer_length, &layer_height, &z, &set_z]
(GCodeReader &, const GCodeReader::GCodeLine &line) {
if (line.cmd == "G1") {
if (line.extruding()) {
total_layer_length += line.dist_XY();
} else if (line.has('Z')) {
layer_height += line.dist_Z();
r.parse_buffer(gcode, [&total_layer_length, &layer_height, &z, &set_z]
(GCodeReader &reader, const GCodeReader::GCodeLine &line) {
if (line.cmd_is("G1")) {
if (line.extruding(reader)) {
total_layer_length += line.dist_XY(reader);
} else if (line.has(Z)) {
layer_height += line.dist_Z(reader);
if (!set_z) {
z = line.new_Z();
z = line.new_Z(reader);
set_z = true;
}
}
@ -59,23 +50,23 @@ SpiralVase::process_layer(const std::string &gcode)
z -= layer_height;
std::string new_gcode;
this->_reader.parse(gcode, [&new_gcode, &z, &layer_height, &total_layer_length]
(GCodeReader &, GCodeReader::GCodeLine line) {
if (line.cmd == "G1") {
if (line.has('Z')) {
this->_reader.parse_buffer(gcode, [&new_gcode, &z, &layer_height, &total_layer_length]
(GCodeReader &reader, GCodeReader::GCodeLine line) {
if (line.cmd_is("G1")) {
if (line.has_z()) {
// If this is the initial Z move of the layer, replace it with a
// (redundant) move to the last Z of previous layer.
line.set('Z', _format_z(z));
new_gcode += line.raw + '\n';
line.set(reader, Z, z);
new_gcode += line.raw() + '\n';
return;
} else {
float dist_XY = line.dist_XY();
float dist_XY = line.dist_XY(reader);
if (dist_XY > 0) {
// horizontal move
if (line.extruding()) {
if (line.extruding(reader)) {
z += dist_XY * layer_height / total_layer_length;
line.set('Z', _format_z(z));
new_gcode += line.raw + '\n';
line.set(reader, Z, z);
new_gcode += line.raw() + '\n';
}
return;
@ -87,7 +78,7 @@ SpiralVase::process_layer(const std::string &gcode)
}
}
}
new_gcode += line.raw + '\n';
new_gcode += line.raw() + '\n';
});
return new_gcode;

View file

@ -13,7 +13,7 @@ class SpiralVase {
SpiralVase(const PrintConfig &config)
: enable(false), _config(&config)
{
this->_reader.Z = this->_config->z_offset;
this->_reader.z() = this->_config->z_offset;
this->_reader.apply_config(*this->_config);
};
std::string process_layer(const std::string &gcode);

View file

@ -21,6 +21,8 @@ TODO LIST
#include <iostream>
#include <vector>
#include "Analyzer.hpp"
#if defined(__linux) || defined(__GNUC__ )
#include <strings.h>
#endif /* __linux */
@ -510,6 +512,11 @@ WipeTower::ToolChangeResult WipeTowerPrusaMM::prime(
.travel(cleaning_box.ld, 7200)
.set_extruder_trimpot(750); // Increase the extruder driver current to allow fast ramming.
// adds tag for analyzer
char buf[32];
sprintf(buf, ";%s%d\n", GCodeAnalyzer::Extrusion_Role_Tag.c_str(), erWipeTower);
writer.append(buf);
if (purpose == PURPOSE_EXTRUDE || purpose == PURPOSE_MOVE_TO_TOWER_AND_EXTRUDE) {
for (size_t idx_tool = 0; idx_tool < tools.size(); ++ idx_tool) {
unsigned int tool = tools[idx_tool];
@ -658,6 +665,11 @@ WipeTower::ToolChangeResult WipeTowerPrusaMM::tool_change(unsigned int tool, boo
writer.set_initial_position(initial_position);
}
// adds tag for analyzer
char buf[32];
sprintf(buf, ";%s%d\n", GCodeAnalyzer::Extrusion_Role_Tag.c_str(), erWipeTower);
writer.append(buf);
if (purpose == PURPOSE_EXTRUDE || purpose == PURPOSE_MOVE_TO_TOWER_AND_EXTRUDE) {
// Increase the extruder driver current to allow fast ramming.
writer.set_extruder_trimpot(750);
@ -735,6 +747,11 @@ WipeTower::ToolChangeResult WipeTowerPrusaMM::toolchange_Brim(Purpose purpose, b
else
writer.set_initial_position(initial_position);
// adds tag for analyzer
char buf[32];
sprintf(buf, ";%s%d\n", GCodeAnalyzer::Extrusion_Role_Tag.c_str(), erWipeTower);
writer.append(buf);
if (purpose == PURPOSE_EXTRUDE || purpose == PURPOSE_MOVE_TO_TOWER_AND_EXTRUDE) {
writer.extrude_explicit(wipeTower_box.ld - xy(m_perimeter_width * 6.f, 0), // Prime the extruder left of the wipe tower.

View file

@ -4,6 +4,8 @@
#include <fstream>
#include <iostream>
#include <Shiny/Shiny.h>
namespace Slic3r {
void GCodeReader::apply_config(const GCodeConfig &config)
@ -18,66 +20,89 @@ void GCodeReader::apply_config(const DynamicPrintConfig &config)
m_extrusion_axis = m_config.get_extrusion_axis()[0];
}
void GCodeReader::parse(const std::string &gcode, callback_t callback)
const char* GCodeReader::parse_line_internal(const char *ptr, GCodeLine &gline, std::pair<const char*, const char*> &command)
{
std::istringstream ss(gcode);
std::string line;
while (std::getline(ss, line))
this->parse_line(line, callback);
}
void GCodeReader::parse_line(std::string line, callback_t callback)
{
GCodeLine gline(this);
gline.raw = line;
if (this->verbose)
std::cout << line << std::endl;
// strip comment
{
size_t pos = line.find(';');
if (pos != std::string::npos) {
gline.comment = line.substr(pos+1);
line.erase(pos);
}
}
PROFILE_FUNC();
// command and args
const char *c = ptr;
{
std::vector<std::string> args;
boost::split(args, line, boost::is_any_of(" "));
// first one is cmd
gline.cmd = args.front();
args.erase(args.begin());
for (std::string &arg : args) {
if (arg.size() < 2) continue;
gline.args.insert(std::make_pair(arg[0], arg.substr(1)));
PROFILE_BLOCK(command_and_args);
// Skip the whitespaces.
command.first = skip_whitespaces(c);
// Skip the command.
c = command.second = skip_word(command.first);
// Up to the end of line or comment.
while (! is_end_of_gcode_line(*c)) {
// Skip whitespaces.
c = skip_whitespaces(c);
if (is_end_of_gcode_line(*c))
break;
// Check the name of the axis.
Axis axis = NUM_AXES;
switch (*c) {
case 'X': axis = X; break;
case 'Y': axis = Y; break;
case 'Z': axis = Z; break;
case 'F': axis = F; break;
default:
if (*c == m_extrusion_axis)
axis = E;
break;
}
if (axis != NUM_AXES) {
// Try to parse the numeric value.
char *pend = nullptr;
double v = strtod(++ c, &pend);
if (pend != nullptr && is_end_of_word(*pend)) {
// The axis value has been parsed correctly.
gline.m_axis[int(axis)] = float(v);
gline.m_mask |= 1 << int(axis);
c = pend;
} else
// Skip the rest of the word.
c = skip_word(c);
} else
// Skip the rest of the word.
c = skip_word(c);
}
}
// convert extrusion axis
if (m_extrusion_axis != 'E') {
const auto it = gline.args.find(m_extrusion_axis);
if (it != gline.args.end()) {
std::swap(gline.args['E'], it->second);
gline.args.erase(it);
}
if (gline.has(E) && m_config.use_relative_e_distances)
m_position[E] = 0;
// Skip the rest of the line.
for (; ! is_end_of_line(*c); ++ c);
// Copy the raw string including the comment, without the trailing newlines.
if (c > ptr) {
PROFILE_BLOCK(copy_raw_string);
gline.m_raw.assign(ptr, c);
}
if (gline.has('E') && m_config.use_relative_e_distances)
this->E = 0;
if (callback) callback(*this, gline);
// update coordinates
if (gline.cmd == "G0" || gline.cmd == "G1" || gline.cmd == "G92") {
this->X = gline.new_X();
this->Y = gline.new_Y();
this->Z = gline.new_Z();
this->E = gline.new_E();
this->F = gline.new_F();
// Skip the trailing newlines.
if (*c == '\r')
++ c;
if (*c == '\n')
++ c;
if (m_verbose)
std::cout << gline.m_raw << std::endl;
return c;
}
void GCodeReader::update_coordinates(GCodeLine &gline, std::pair<const char*, const char*> &command)
{
PROFILE_FUNC();
if (*command.first == 'G') {
int cmd_len = int(command.second - command.first);
if ((cmd_len == 2 && (command.first[1] == '0' || command.first[1] == '1')) ||
(cmd_len == 3 && command.first[1] == '9' && command.first[2] == '2')) {
for (size_t i = 0; i < NUM_AXES; ++ i)
if (gline.has(Axis(i)))
this->m_position[i] = gline.value(Axis(i));
}
}
}
@ -89,22 +114,64 @@ void GCodeReader::parse_file(const std::string &file, callback_t callback)
this->parse_line(line, callback);
}
void GCodeReader::GCodeLine::set(char arg, std::string value)
bool GCodeReader::GCodeLine::has_value(char axis, float &value) const
{
const std::string space(" ");
if (this->has(arg)) {
size_t pos = this->raw.find(space + arg)+2;
size_t end = this->raw.find(' ', pos+1);
this->raw = this->raw.replace(pos, end-pos, value);
} else {
size_t pos = this->raw.find(' ');
if (pos == std::string::npos) {
this->raw += space + arg + value;
} else {
this->raw = this->raw.replace(pos, 0, space + arg + value);
const char *c = m_raw.c_str();
// Skip the whitespaces.
c = skip_whitespaces(c);
// Skip the command.
c = skip_word(c);
// Up to the end of line or comment.
while (! is_end_of_gcode_line(*c)) {
// Skip whitespaces.
c = skip_whitespaces(c);
if (is_end_of_gcode_line(*c))
break;
// Check the name of the axis.
if (*c == axis) {
// Try to parse the numeric value.
char *pend = nullptr;
double v = strtod(++ c, &pend);
if (pend != nullptr && is_end_of_word(*pend)) {
// The axis value has been parsed correctly.
value = float(v);
return true;
}
}
// Skip the rest of the word.
c = skip_word(c);
}
this->args[arg] = value;
return false;
}
void GCodeReader::GCodeLine::set(const GCodeReader &reader, const Axis axis, const float new_value, const int decimal_digits)
{
std::ostringstream ss;
ss << std::fixed << std::setprecision(decimal_digits) << new_value;
char match[3] = " X";
if (int(axis) < 3)
match[1] += int(axis);
else if (axis == F)
match[1] = 'F';
else {
assert(axis == E);
match[1] = reader.extrusion_axis();
}
if (this->has(axis)) {
size_t pos = m_raw.find(match)+2;
size_t end = m_raw.find(' ', pos+1);
m_raw = m_raw.replace(pos, end-pos, ss.str());
} else {
size_t pos = m_raw.find(' ');
if (pos == std::string::npos)
m_raw += std::string(match) + ss.str();
else
m_raw = m_raw.replace(pos, 0, std::string(match) + ss.str());
}
m_axis[axis] = new_value;
m_mask |= 1 << int(axis);
}
}

View file

@ -11,54 +11,127 @@
namespace Slic3r {
class GCodeReader {
public:
public:
class GCodeLine {
public:
GCodeReader* reader;
std::string raw;
std::string cmd;
std::string comment;
std::map<char,std::string> args;
GCodeLine(GCodeReader* _reader) : reader(_reader) {};
bool has(char arg) const { return this->args.count(arg) > 0; };
float get_float(char arg) const { return float(atof(this->args.at(arg).c_str())); };
float new_X() const { return this->has('X') ? float(atof(this->args.at('X').c_str())) : this->reader->X; };
float new_Y() const { return this->has('Y') ? float(atof(this->args.at('Y').c_str())) : this->reader->Y; };
float new_Z() const { return this->has('Z') ? float(atof(this->args.at('Z').c_str())) : this->reader->Z; };
float new_E() const { return this->has('E') ? float(atof(this->args.at('E').c_str())) : this->reader->E; };
float new_F() const { return this->has('F') ? float(atof(this->args.at('F').c_str())) : this->reader->F; };
float dist_X() const { return this->new_X() - this->reader->X; };
float dist_Y() const { return this->new_Y() - this->reader->Y; };
float dist_Z() const { return this->new_Z() - this->reader->Z; };
float dist_E() const { return this->new_E() - this->reader->E; };
float dist_XY() const {
float x = this->dist_X();
float y = this->dist_Y();
GCodeLine() { reset(); }
void reset() { m_mask = 0; memset(m_axis, 0, sizeof(m_axis)); m_raw.clear(); }
const std::string& raw() const { return m_raw; }
const std::string cmd() const {
const char *cmd = GCodeReader::skip_whitespaces(m_raw.c_str());
return std::string(cmd, GCodeReader::skip_word(cmd));
}
const std::string comment() const
{ size_t pos = m_raw.find(';'); return (pos == std::string::npos) ? "" : m_raw.substr(pos + 1); }
bool has(Axis axis) const { return (m_mask & (1 << int(axis))) != 0; }
float value(Axis axis) const { return m_axis[axis]; }
bool has_value(char axis, float &value) const;
float new_Z(const GCodeReader &reader) const { return this->has(Z) ? this->z() : reader.z(); }
float new_E(const GCodeReader &reader) const { return this->has(E) ? this->e() : reader.e(); }
float new_F(const GCodeReader &reader) const { return this->has(F) ? this->f() : reader.f(); }
float dist_X(const GCodeReader &reader) const { return this->has(X) ? (this->x() - reader.x()) : 0; }
float dist_Y(const GCodeReader &reader) const { return this->has(Y) ? (this->y() - reader.y()) : 0; }
float dist_Z(const GCodeReader &reader) const { return this->has(Z) ? (this->z() - reader.z()) : 0; }
float dist_E(const GCodeReader &reader) const { return this->has(E) ? (this->e() - reader.e()) : 0; }
float dist_XY(const GCodeReader &reader) const {
float x = this->has(X) ? (this->x() - reader.x()) : 0;
float y = this->has(Y) ? (this->y() - reader.y()) : 0;
return sqrt(x*x + y*y);
};
bool extruding() const { return this->cmd == "G1" && this->dist_E() > 0; };
bool retracting() const { return this->cmd == "G1" && this->dist_E() < 0; };
bool travel() const { return this->cmd == "G1" && ! this->has('E'); };
void set(char arg, std::string value);
}
bool cmd_is(const char *cmd_test) const {
const char *cmd = GCodeReader::skip_whitespaces(m_raw.c_str());
int len = strlen(cmd_test);
return strncmp(cmd, cmd_test, len) == 0 && GCodeReader::is_end_of_word(cmd[len]);
}
bool extruding(const GCodeReader &reader) const { return this->cmd_is("G1") && this->dist_E(reader) > 0; }
bool retracting(const GCodeReader &reader) const { return this->cmd_is("G1") && this->dist_E(reader) < 0; }
bool travel() const { return this->cmd_is("G1") && ! this->has(E); }
void set(const GCodeReader &reader, const Axis axis, const float new_value, const int decimal_digits = 3);
bool has_x() const { return this->has(X); }
bool has_y() const { return this->has(Y); }
bool has_z() const { return this->has(Z); }
bool has_e() const { return this->has(E); }
bool has_f() const { return this->has(F); }
float x() const { return m_axis[X]; }
float y() const { return m_axis[Y]; }
float z() const { return m_axis[Z]; }
float e() const { return m_axis[E]; }
float f() const { return m_axis[F]; }
private:
std::string m_raw;
float m_axis[NUM_AXES];
uint32_t m_mask;
friend class GCodeReader;
};
typedef std::function<void(GCodeReader&, const GCodeLine&)> callback_t;
float X, Y, Z, E, F;
bool verbose;
callback_t callback;
GCodeReader() : X(0), Y(0), Z(0), E(0), F(0), verbose(false), m_extrusion_axis('E') {};
GCodeReader() : m_verbose(false), m_extrusion_axis('E') { memset(m_position, 0, sizeof(m_position)); }
void apply_config(const GCodeConfig &config);
void apply_config(const DynamicPrintConfig &config);
void parse(const std::string &gcode, callback_t callback);
void parse_line(std::string line, callback_t callback);
template<typename Callback>
void parse_buffer(const std::string &buffer, Callback callback)
{
const char *ptr = buffer.c_str();
GCodeLine gline;
while (*ptr != 0) {
gline.reset();
ptr = this->parse_line(ptr, gline, callback);
}
}
void parse_buffer(const std::string &buffer)
{ this->parse_buffer(buffer, [](GCodeReader&, const GCodeReader::GCodeLine&){}); }
template<typename Callback>
const char* parse_line(const char *ptr, GCodeLine &gline, Callback &callback)
{
std::pair<const char*, const char*> cmd;
const char *end = parse_line_internal(ptr, gline, cmd);
callback(*this, gline);
update_coordinates(gline, cmd);
return end;
}
template<typename Callback>
void parse_line(const std::string &line, Callback callback)
{ GCodeLine gline; this->parse_line(line.c_str(), gline, callback); }
void parse_file(const std::string &file, callback_t callback);
float& x() { return m_position[X]; }
float x() const { return m_position[X]; }
float& y() { return m_position[Y]; }
float y() const { return m_position[Y]; }
float& z() { return m_position[Z]; }
float z() const { return m_position[Z]; }
float& e() { return m_position[E]; }
float e() const { return m_position[E]; }
float& f() { return m_position[F]; }
float f() const { return m_position[F]; }
char extrusion_axis() const { return m_extrusion_axis; }
private:
const char* parse_line_internal(const char *ptr, GCodeLine &gline, std::pair<const char*, const char*> &command);
void update_coordinates(GCodeLine &gline, std::pair<const char*, const char*> &command);
static bool is_whitespace(char c) { return c == ' ' || c == '\t'; }
static bool is_end_of_line(char c) { return c == '\r' || c == '\n' || c == 0; }
static bool is_end_of_gcode_line(char c) { return c == ';' || is_end_of_line(c); }
static bool is_end_of_word(char c) { return is_whitespace(c) || is_end_of_gcode_line(c); }
static const char* skip_whitespaces(const char *c) { for (; is_whitespace(*c); ++ c); return c; }
static const char* skip_word(const char *c) { for (; ! is_end_of_word(*c); ++ c); return c; }
GCodeConfig m_config;
char m_extrusion_axis;
char m_extrusion_axis;
float m_position[NUM_AXES];
bool m_verbose;
};
} /* namespace Slic3r */

View file

@ -7,16 +7,36 @@
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/lexical_cast.hpp>
#if defined(__APPLE__) || defined(__linux) || defined(__OpenBSD__)
#if defined(__APPLE__) || defined(__OpenBSD__)
#include <termios.h>
#endif
#if __APPLE__
#ifdef __APPLE__
#include <sys/ioctl.h>
#include <IOKit/serial/ioss.h>
#endif
#ifdef __linux
#ifdef __linux__
#include <sys/ioctl.h>
#include <linux/serial.h>
#include <fcntl.h>
#include "/usr/include/asm-generic/ioctls.h"
/* The following definitions are kindly borrowed from:
/usr/include/asm-generic/termbits.h
Unfortunately we cannot just include that one because
it would redefine the "struct termios" already defined
the <termios.h> already included by Boost.ASIO. */
#define K_NCCS 19
struct termios2 {
tcflag_t c_iflag;
tcflag_t c_oflag;
tcflag_t c_cflag;
tcflag_t c_lflag;
cc_t c_line;
cc_t c_cc[K_NCCS];
speed_t c_ispeed;
speed_t c_ospeed;
};
#define BOTHER CBAUDEX
#endif
//#define DEBUG_SERIAL
@ -47,26 +67,26 @@ GCodeSender::connect(std::string devname, unsigned int baud_rate)
this->set_error_status(false);
try {
this->serial.open(devname);
this->serial.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::odd));
this->serial.set_option(boost::asio::serial_port_base::character_size(boost::asio::serial_port_base::character_size(8)));
this->serial.set_option(boost::asio::serial_port_base::flow_control(boost::asio::serial_port_base::flow_control::none));
this->serial.set_option(boost::asio::serial_port_base::stop_bits(boost::asio::serial_port_base::stop_bits::one));
this->set_baud_rate(baud_rate);
this->serial.close();
this->serial.open(devname);
this->serial.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::none));
// set baud rate again because set_option overwrote it
this->set_baud_rate(baud_rate);
this->open = true;
this->reset();
} catch (boost::system::system_error &) {
this->set_error_status(true);
return false;
}
this->serial.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::odd));
this->serial.set_option(boost::asio::serial_port_base::character_size(boost::asio::serial_port_base::character_size(8)));
this->serial.set_option(boost::asio::serial_port_base::flow_control(boost::asio::serial_port_base::flow_control::none));
this->serial.set_option(boost::asio::serial_port_base::stop_bits(boost::asio::serial_port_base::stop_bits::one));
this->set_baud_rate(baud_rate);
this->serial.close();
this->serial.open(devname);
this->serial.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::none));
// set baud rate again because set_option overwrote it
this->set_baud_rate(baud_rate);
this->open = true;
this->reset();
// a reset firmware expect line numbers to start again from 1
this->sent = 0;
this->last_sent.clear();
@ -84,6 +104,11 @@ GCodeSender::connect(std::string devname, unsigned int baud_rate)
boost::thread t(boost::bind(&boost::asio::io_service::run, &this->io));
this->background_thread.swap(t);
// always send a M105 to check for connection because firmware might be silent on connect
//FIXME Vojtech: This is being sent too early, leading to line number synchronization issues,
// from which the GCodeSender never recovers.
// this->send("M105", true);
return true;
}
@ -104,27 +129,17 @@ GCodeSender::set_baud_rate(unsigned int baud_rate)
ioctl(handle, IOSSIOSPEED, &newSpeed);
::tcsetattr(handle, TCSANOW, &ios);
#elif __linux
termios ios;
::tcgetattr(handle, &ios);
::cfsetispeed(&ios, B38400);
::cfsetospeed(&ios, B38400);
::tcflush(handle, TCIFLUSH);
::tcsetattr(handle, TCSANOW, &ios);
struct serial_struct ss;
ioctl(handle, TIOCGSERIAL, &ss);
ss.flags = (ss.flags & ~ASYNC_SPD_MASK) | ASYNC_SPD_CUST;
ss.custom_divisor = (ss.baud_base + (baud_rate / 2)) / baud_rate;
//cout << "bbase " << ss.baud_base << " div " << ss.custom_divisor;
long closestSpeed = ss.baud_base / ss.custom_divisor;
//cout << " Closest speed " << closestSpeed << endl;
ss.reserved_char[0] = 0;
if (closestSpeed < baud_rate * 98 / 100 || closestSpeed > baud_rate * 102 / 100) {
printf("Failed to set baud rate\n");
}
ioctl(handle, TIOCSSERIAL, &ss);
printf("< set_baud_rate: %u\n", baud_rate);
termios2 ios;
if (ioctl(handle, TCGETS2, &ios))
printf("Error in TCGETS2: %s\n", strerror(errno));
ios.c_ispeed = ios.c_ospeed = baud_rate;
ios.c_cflag &= ~CBAUD;
ios.c_cflag |= BOTHER | CLOCAL | CREAD;
ios.c_cc[VMIN] = 1; // Minimum of characters to read, prevents eof errors when 0 bytes are read
ios.c_cc[VTIME] = 1;
if (ioctl(handle, TCSETS2, &ios))
printf("Error in TCSETS2: %s\n", strerror(errno));
#elif __OpenBSD__
struct termios ios;
::tcgetattr(handle, &ios);
@ -154,6 +169,7 @@ GCodeSender::disconnect()
*/
#ifdef DEBUG_SERIAL
fs << "DISCONNECTED" << std::endl << std::flush;
fs.close();
#endif
}
@ -292,17 +308,20 @@ GCodeSender::on_read(const boost::system::error_code& error,
{
this->set_error_status(false);
if (error) {
#ifdef __APPLE__
if (error.value() == 45) {
// OS X bug: http://osdir.com/ml/lib.boost.asio.user/2008-08/msg00004.html
this->do_read();
} else {
// printf("ERROR: [%d] %s\n", error.value(), error.message().c_str());
// error can be true even because the serial port was closed.
// In this case it is not a real error, so ignore.
if (this->open) {
this->do_close();
this->set_error_status(true);
}
return;
}
#endif
// printf("ERROR: [%d] %s\n", error.value(), error.message().c_str());
// error can be true even because the serial port was closed.
// In this case it is not a real error, so ignore.
if (this->open) {
this->do_close();
this->set_error_status(true);
}
return;
}
@ -339,7 +358,8 @@ GCodeSender::on_read(const boost::system::error_code& error,
// extract the first number from line
boost::algorithm::trim_left_if(line, !boost::algorithm::is_digit());
size_t toresend = boost::lexical_cast<size_t>(line.substr(0, line.find_first_not_of("0123456789")));
if (toresend >= this->sent - this->last_sent.size()) {
++ toresend; // N is 0-based
if (toresend >= this->sent - this->last_sent.size() && toresend < this->last_sent.size()) {
{
boost::lock_guard<boost::mutex> l(this->queue_mutex);
@ -457,8 +477,8 @@ GCodeSender::do_send()
if (line.empty()) return;
// compute full line
this->sent++;
std::string full_line = "N" + boost::lexical_cast<std::string>(this->sent) + " " + line;
++ this->sent;
// calculate checksum
int cs = 0;

File diff suppressed because it is too large Load diff

View file

@ -2,22 +2,323 @@
#define slic3r_GCodeTimeEstimator_hpp_
#include "libslic3r.h"
#include "PrintConfig.hpp"
#include "GCodeReader.hpp"
namespace Slic3r {
class GCodeTimeEstimator : public GCodeReader {
//
// Some of the algorithms used by class GCodeTimeEstimator were inpired by
// Cura Engine's class TimeEstimateCalculator
// https://github.com/Ultimaker/CuraEngine/blob/master/src/timeEstimate.h
//
class GCodeTimeEstimator
{
public:
float time = 0; // in seconds
void parse(const std::string &gcode);
void parse_file(const std::string &file);
protected:
float acceleration = 9000;
void _parser(GCodeReader&, const GCodeReader::GCodeLine &line);
static float _accelerated_move(double length, double v, double acceleration);
};
enum EUnits : unsigned char
{
Millimeters,
Inches
};
enum EAxis : unsigned char
{
X,
Y,
Z,
E,
Num_Axis
};
enum EPositioningType : unsigned char
{
Absolute,
Relative
};
private:
struct Axis
{
float position; // mm
float max_feedrate; // mm/s
float max_acceleration; // mm/s^2
float max_jerk; // mm/s
};
struct Feedrates
{
float feedrate; // mm/s
float axis_feedrate[Num_Axis]; // mm/s
float abs_axis_feedrate[Num_Axis]; // mm/s
float safe_feedrate; // mm/s
void reset();
};
struct State
{
GCodeFlavor dialect;
EUnits units;
EPositioningType positioning_xyz_type;
EPositioningType positioning_e_type;
Axis axis[Num_Axis];
float feedrate; // mm/s
float acceleration; // mm/s^2
float retract_acceleration; // mm/s^2
float additional_time; // s
float minimum_feedrate; // mm/s
float minimum_travel_feedrate; // mm/s
float extrude_factor_override_percentage;
};
public:
struct Block
{
struct FeedrateProfile
{
float entry; // mm/s
float cruise; // mm/s
float exit; // mm/s
};
struct Trapezoid
{
float distance; // mm
float accelerate_until; // mm
float decelerate_after; // mm
FeedrateProfile feedrate;
float acceleration_time(float acceleration) const;
float cruise_time() const;
float deceleration_time(float acceleration) const;
float cruise_distance() const;
// This function gives the time needed to accelerate from an initial speed to reach a final distance.
static float acceleration_time_from_distance(float initial_feedrate, float distance, float acceleration);
// This function gives the final speed while accelerating at the given constant acceleration from the given initial speed along the given distance.
static float speed_from_distance(float initial_feedrate, float distance, float acceleration);
};
struct Flags
{
bool recalculate;
bool nominal_length;
};
Flags flags;
float delta_pos[Num_Axis]; // mm
float acceleration; // mm/s^2
float max_entry_speed; // mm/s
float safe_feedrate; // mm/s
FeedrateProfile feedrate;
Trapezoid trapezoid;
// Returns the length of the move covered by this block, in mm
float move_length() const;
// Returns true if this block is a retract/unretract move only
float is_extruder_only_move() const;
// Returns true if this block is a move with no extrusion
float is_travel_move() const;
// Returns the time spent accelerating toward cruise speed, in seconds
float acceleration_time() const;
// Returns the time spent at cruise speed, in seconds
float cruise_time() const;
// Returns the time spent decelerating from cruise speed, in seconds
float deceleration_time() const;
// Returns the distance covered at cruise speed, in mm
float cruise_distance() const;
// Calculates this block's trapezoid
void calculate_trapezoid();
// Calculates the maximum allowable speed at this point when you must be able to reach target_velocity using the
// acceleration within the allotted distance.
static float max_allowable_speed(float acceleration, float target_velocity, float distance);
// Calculates the distance (not time) it takes to accelerate from initial_rate to target_rate using the given acceleration:
static float estimate_acceleration_distance(float initial_rate, float target_rate, float acceleration);
// This function gives you the point at which you must start braking (at the rate of -acceleration) if
// you started at speed initial_rate and accelerated until this point and want to end at the final_rate after
// a total travel of distance. This can be used to compute the intersection point between acceleration and
// deceleration in the cases where the trapezoid has no plateau (i.e. never reaches maximum speed)
static float intersection_distance(float initial_rate, float final_rate, float acceleration, float distance);
};
typedef std::vector<Block> BlocksList;
private:
GCodeReader _parser;
State _state;
Feedrates _curr;
Feedrates _prev;
BlocksList _blocks;
float _time; // s
public:
GCodeTimeEstimator();
// Calculates the time estimate from the given gcode in string format
void calculate_time_from_text(const std::string& gcode);
// Calculates the time estimate from the gcode contained in the file with the given filename
void calculate_time_from_file(const std::string& file);
// Calculates the time estimate from the gcode contained in given list of gcode lines
void calculate_time_from_lines(const std::vector<std::string>& gcode_lines);
// Adds the given gcode line
void add_gcode_line(const std::string& gcode_line);
void add_gcode_block(const char *ptr);
void add_gcode_block(const std::string &str) { this->add_gcode_block(str.c_str()); }
// Calculates the time estimate from the gcode lines added using add_gcode_line()
void calculate_time();
// Set current position on the given axis with the given value
void set_axis_position(EAxis axis, float position);
void set_axis_max_feedrate(EAxis axis, float feedrate_mm_sec);
void set_axis_max_acceleration(EAxis axis, float acceleration);
void set_axis_max_jerk(EAxis axis, float jerk);
// Returns current position on the given axis
float get_axis_position(EAxis axis) const;
float get_axis_max_feedrate(EAxis axis) const;
float get_axis_max_acceleration(EAxis axis) const;
float get_axis_max_jerk(EAxis axis) const;
void set_feedrate(float feedrate_mm_sec);
float get_feedrate() const;
void set_acceleration(float acceleration_mm_sec2);
float get_acceleration() const;
void set_retract_acceleration(float acceleration_mm_sec2);
float get_retract_acceleration() const;
void set_minimum_feedrate(float feedrate_mm_sec);
float get_minimum_feedrate() const;
void set_minimum_travel_feedrate(float feedrate_mm_sec);
float get_minimum_travel_feedrate() const;
void set_extrude_factor_override_percentage(float percentage);
float get_extrude_factor_override_percentage() const;
void set_dialect(GCodeFlavor dialect);
GCodeFlavor get_dialect() const;
void set_units(EUnits units);
EUnits get_units() const;
void set_positioning_xyz_type(EPositioningType type);
EPositioningType get_positioning_xyz_type() const;
void set_positioning_e_type(EPositioningType type);
EPositioningType get_positioning_e_type() const;
void add_additional_time(float timeSec);
void set_additional_time(float timeSec);
float get_additional_time() const;
void set_default();
// Call this method before to start adding lines using add_gcode_line() when reusing an instance of GCodeTimeEstimator
void reset();
// Returns the estimated time, in seconds
float get_time() const;
// Returns the estimated time, in format HHh MMm SSs
std::string get_time_hms() const;
private:
void _reset();
void _reset_blocks();
// Calculates the time estimate
void _calculate_time();
// Processes the given gcode line
void _process_gcode_line(GCodeReader&, const GCodeReader::GCodeLine& line);
// Move
void _processG1(const GCodeReader::GCodeLine& line);
// Dwell
void _processG4(const GCodeReader::GCodeLine& line);
// Set Units to Inches
void _processG20(const GCodeReader::GCodeLine& line);
// Set Units to Millimeters
void _processG21(const GCodeReader::GCodeLine& line);
// Move to Origin (Home)
void _processG28(const GCodeReader::GCodeLine& line);
// Set to Absolute Positioning
void _processG90(const GCodeReader::GCodeLine& line);
// Set to Relative Positioning
void _processG91(const GCodeReader::GCodeLine& line);
// Set Position
void _processG92(const GCodeReader::GCodeLine& line);
// Sleep or Conditional stop
void _processM1(const GCodeReader::GCodeLine& line);
// Set extruder to absolute mode
void _processM82(const GCodeReader::GCodeLine& line);
// Set extruder to relative mode
void _processM83(const GCodeReader::GCodeLine& line);
// Set Extruder Temperature and Wait
void _processM109(const GCodeReader::GCodeLine& line);
// Set max printing acceleration
void _processM201(const GCodeReader::GCodeLine& line);
// Set maximum feedrate
void _processM203(const GCodeReader::GCodeLine& line);
// Set default acceleration
void _processM204(const GCodeReader::GCodeLine& line);
// Advanced settings
void _processM205(const GCodeReader::GCodeLine& line);
// Set extrude factor override percentage
void _processM221(const GCodeReader::GCodeLine& line);
// Set allowable instantaneous speed change
void _processM566(const GCodeReader::GCodeLine& line);
// Simulates firmware st_synchronize() call
void _simulate_st_synchronize();
void _forward_pass();
void _reverse_pass();
void _planner_forward_pass_kernel(Block& prev, Block& curr);
void _planner_reverse_pass_kernel(Block& curr, Block& next);
void _recalculate_trapezoids();
};
} /* namespace Slic3r */

View file

@ -42,7 +42,7 @@ std::string GCodeWriter::preamble()
gcode << "G21 ; set units to millimeters\n";
gcode << "G90 ; use absolute coordinates\n";
}
if (FLAVOR_IS(gcfRepRap) || FLAVOR_IS(gcfTeacup) || FLAVOR_IS(gcfRepetier) || FLAVOR_IS(gcfSmoothie)) {
if (FLAVOR_IS(gcfRepRap) || FLAVOR_IS(gcfMarlin) || FLAVOR_IS(gcfTeacup) || FLAVOR_IS(gcfRepetier) || FLAVOR_IS(gcfSmoothie)) {
if (this->config.use_relative_e_distances) {
gcode << "M83 ; use relative distances for extrusion\n";
} else {

View file

@ -218,6 +218,16 @@ Line::ccw(const Point& point) const
return point.ccw(*this);
}
double Line3::length() const
{
return a.distance_to(b);
}
Vector3 Line3::vector() const
{
return Vector3(b.x - a.x, b.y - a.y, b.z - a.z);
}
Pointf3
Linef3::intersect_plane(double z) const
{

View file

@ -7,10 +7,12 @@
namespace Slic3r {
class Line;
class Line3;
class Linef3;
class Polyline;
class ThickLine;
typedef std::vector<Line> Lines;
typedef std::vector<Line3> Lines3;
typedef std::vector<ThickLine> ThickLines;
class Line
@ -56,6 +58,19 @@ class ThickLine : public Line
ThickLine(Point _a, Point _b) : Line(_a, _b), a_width(0), b_width(0) {};
};
class Line3
{
public:
Point3 a;
Point3 b;
Line3() {}
Line3(const Point3& _a, const Point3& _b) : a(_a), b(_b) {}
double length() const;
Vector3 vector() const;
};
class Linef
{
public:

View file

@ -5,6 +5,7 @@
#include "Format/OBJ.hpp"
#include "Format/PRUS.hpp"
#include "Format/STL.hpp"
#include "Format/3mf.hpp"
#include <float.h>
@ -46,16 +47,16 @@ Model Model::read_from_file(const std::string &input_file, bool add_default_inst
result = load_stl(input_file.c_str(), &model);
else if (boost::algorithm::iends_with(input_file, ".obj"))
result = load_obj(input_file.c_str(), &model);
else if (boost::algorithm::iends_with(input_file, ".amf") ||
boost::algorithm::iends_with(input_file, ".amf.xml"))
result = load_amf(input_file.c_str(), &model);
else if (!boost::algorithm::iends_with(input_file, ".zip.amf") && (boost::algorithm::iends_with(input_file, ".amf") ||
boost::algorithm::iends_with(input_file, ".amf.xml")))
result = load_amf(input_file.c_str(), nullptr, &model);
#ifdef SLIC3R_PRUS
else if (boost::algorithm::iends_with(input_file, ".prusa"))
result = load_prus(input_file.c_str(), &model);
#endif /* SLIC3R_PRUS */
else
throw std::runtime_error("Unknown file format. Input file must have .stl, .obj, .amf(.xml) or .prusa extension.");
if (! result)
throw std::runtime_error("Loading of a model file failed.");
@ -71,6 +72,33 @@ Model Model::read_from_file(const std::string &input_file, bool add_default_inst
return model;
}
Model Model::read_from_archive(const std::string &input_file, PresetBundle* bundle, bool add_default_instances)
{
Model model;
bool result = false;
if (boost::algorithm::iends_with(input_file, ".3mf"))
result = load_3mf(input_file.c_str(), bundle, &model);
else if (boost::algorithm::iends_with(input_file, ".zip.amf"))
result = load_amf(input_file.c_str(), bundle, &model);
else
throw std::runtime_error("Unknown file format. Input file must have .3mf or .zip.amf extension.");
if (!result)
throw std::runtime_error("Loading of a model file failed.");
if (model.objects.empty())
throw std::runtime_error("The supplied file couldn't be read because it's empty");
for (ModelObject *o : model.objects)
o->input_file = input_file;
if (add_default_instances)
model.add_default_instances();
return model;
}
ModelObject* Model::add_object()
{
this->objects.emplace_back(new ModelObject(this));
@ -115,6 +143,23 @@ void Model::delete_object(size_t idx)
this->objects.erase(i);
}
void Model::delete_object(ModelObject* object)
{
if (object == nullptr)
return;
for (ModelObjectPtrs::iterator it = objects.begin(); it != objects.end(); ++it)
{
ModelObject* obj = *it;
if (obj == object)
{
delete obj;
objects.erase(it);
return;
}
}
}
void Model::clear_objects()
{
for (ModelObject *o : this->objects)
@ -607,6 +652,20 @@ void ModelObject::rotate(float angle, const Axis &axis)
this->invalidate_bounding_box();
}
void ModelObject::transform(const float* matrix3x4)
{
if (matrix3x4 == nullptr)
return;
for (ModelVolume* v : volumes)
{
v->mesh.transform(matrix3x4);
}
origin_translation = Pointf3(0.0f, 0.0f, 0.0f);
invalidate_bounding_box();
}
void ModelObject::mirror(const Axis &axis)
{
for (ModelVolume *v : this->volumes)

View file

@ -19,6 +19,7 @@ class ModelInstance;
class ModelMaterial;
class ModelObject;
class ModelVolume;
class PresetBundle;
typedef std::string t_model_material_id;
typedef std::string t_model_material_attribute;
@ -119,6 +120,7 @@ public:
void translate(coordf_t x, coordf_t y, coordf_t z);
void scale(const Pointf3 &versor);
void rotate(float angle, const Axis &axis);
void transform(const float* matrix3x4);
void mirror(const Axis &axis);
size_t materials_count() const;
size_t facets_count() const;
@ -238,12 +240,14 @@ public:
~Model() { this->clear_objects(); this->clear_materials(); }
static Model read_from_file(const std::string &input_file, bool add_default_instances = true);
static Model read_from_archive(const std::string &input_file, PresetBundle* bundle, bool add_default_instances = true);
ModelObject* add_object();
ModelObject* add_object(const char *name, const char *path, const TriangleMesh &mesh);
ModelObject* add_object(const char *name, const char *path, TriangleMesh &&mesh);
ModelObject* add_object(const ModelObject &other, bool copy_volumes = true);
void delete_object(size_t idx);
void delete_object(ModelObject* object);
void clear_objects();
ModelMaterial* add_material(t_model_material_id material_id);

View file

@ -214,6 +214,61 @@ MultiPoint::_douglas_peucker(const Points &points, const double tolerance)
return results;
}
void MultiPoint3::translate(double x, double y)
{
for (Point3& p : points)
{
p.translate(x, y);
}
}
void MultiPoint3::translate(const Point& vector)
{
translate(vector.x, vector.y);
}
double MultiPoint3::length() const
{
Lines3 lines = this->lines();
double len = 0.0;
for (const Line3& line : lines)
{
len += line.length();
}
return len;
}
BoundingBox3 MultiPoint3::bounding_box() const
{
return BoundingBox3(points);
}
bool MultiPoint3::remove_duplicate_points()
{
size_t j = 0;
for (size_t i = 1; i < points.size(); ++i)
{
if (points[j].coincides_with(points[i]))
{
// Just increase index i.
}
else
{
++j;
if (j < i)
points[j] = points[i];
}
}
if (++j < points.size())
{
points.erase(points.begin() + j, points.end());
return true;
}
return false;
}
BoundingBox get_extents(const MultiPoint &mp)
{
return BoundingBox(mp.points);

View file

@ -10,6 +10,7 @@
namespace Slic3r {
class BoundingBox;
class BoundingBox3;
class MultiPoint
{
@ -79,6 +80,25 @@ public:
static Points _douglas_peucker(const Points &points, const double tolerance);
};
class MultiPoint3
{
public:
Points3 points;
void append(const Point3& point) { this->points.push_back(point); }
void translate(double x, double y);
void translate(const Point& vector);
virtual Lines3 lines() const = 0;
double length() const;
bool is_valid() const { return this->points.size() >= 2; }
BoundingBox3 bounding_box() const;
// Remove exact duplicates, return true if any duplicate has been removed.
bool remove_duplicate_points();
};
extern BoundingBox get_extents(const MultiPoint &mp);
extern BoundingBox get_extents_rotated(const std::vector<Point> &points, double angle);
extern BoundingBox get_extents_rotated(const MultiPoint &mp, double angle);

View file

@ -483,8 +483,9 @@ PerimeterGenerator::_variable_width(const ThickPolylines &polylines, ExtrusionRo
if (path.polyline.points.empty()) {
path.polyline.append(line.a);
path.polyline.append(line.b);
flow.width = unscale(w);
// Convert from spacing to extrusion width based on the extrusion model
// of a square extrusion ended with semi circles.
flow.width = unscale(w) + flow.height * (1. - 0.25 * PI);
#ifdef SLIC3R_DEBUG
printf(" filling %f gap\n", flow.width);
#endif

View file

@ -3,6 +3,7 @@
#include <ctime>
#include <iomanip>
#include <sstream>
#include <map>
#ifdef _MSC_VER
#include <stdlib.h> // provides **_environ
#else
@ -520,6 +521,9 @@ namespace client
bool just_boolean_expression = false;
std::string error_message;
// Table to translate symbol tag to a human readable error message.
static std::map<std::string, std::string> tag_to_error_message;
static void evaluate_full_macro(const MyContext *ctx, bool &result) { result = ! ctx->just_boolean_expression; }
const ConfigOption* resolve_symbol(const std::string &opt_key) const
@ -619,7 +623,7 @@ namespace client
expr<Iterator> &output)
{
if (opt.opt->is_vector())
ctx->throw_exception("Referencing a scalar variable in a vector context", opt.it_range);
ctx->throw_exception("Referencing a vector variable when scalar is expected", opt.it_range);
switch (opt.opt->type()) {
case coFloat: output.set_d(opt.opt->getFloat()); break;
case coInt: output.set_i(opt.opt->getInt()); break;
@ -644,7 +648,7 @@ namespace client
expr<Iterator> &output)
{
if (opt.opt->is_scalar())
ctx->throw_exception("Referencing a vector variable in a scalar context", opt.it_range);
ctx->throw_exception("Referencing a scalar variable when vector is expected", opt.it_range);
const ConfigOptionVectorBase *vec = static_cast<const ConfigOptionVectorBase*>(opt.opt);
if (vec->empty())
ctx->throw_exception("Indexing an empty vector variable", opt.it_range);
@ -707,9 +711,16 @@ namespace client
msg += ": ";
msg += info.tag.substr(1);
} else {
// A generic error report based on the nonterminal or terminal symbol name.
msg += ". Expecting tag ";
msg += info.tag;
auto it = tag_to_error_message.find(info.tag);
if (it == tag_to_error_message.end()) {
// A generic error report based on the nonterminal or terminal symbol name.
msg += ". Expecting tag ";
msg += info.tag;
} else {
// Use the human readable error message.
msg += ". ";
msg + it->second;
}
}
msg += '\n';
msg += error_line;
@ -720,6 +731,31 @@ namespace client
}
};
// Table to translate symbol tag to a human readable error message.
std::map<std::string, std::string> MyContext::tag_to_error_message = {
{ "eoi", "Unknown syntax error" },
{ "start", "Unknown syntax error" },
{ "text", "Invalid text." },
{ "text_block", "Invalid text block." },
{ "macro", "Invalid macro." },
{ "if_else_output", "Not an {if}{else}{endif} macro." },
{ "switch_output", "Not a {switch} macro." },
{ "legacy_variable_expansion", "Expecting a legacy variable expansion format" },
{ "identifier", "Expecting an identifier." },
{ "conditional_expression", "Expecting a conditional expression." },
{ "logical_or_expression", "Expecting a boolean expression." },
{ "logical_and_expression", "Expecting a boolean expression." },
{ "equality_expression", "Expecting an expression." },
{ "bool_expr_eval", "Expecting a boolean expression."},
{ "relational_expression", "Expecting an expression." },
{ "additive_expression", "Expecting an expression." },
{ "multiplicative_expression", "Expecting an expression." },
{ "unary_expression", "Expecting an expression." },
{ "scalar_variable_reference", "Expecting a scalar variable reference."},
{ "variable_reference", "Expecting a variable reference."},
{ "regular_expression", "Expecting a regular expression."}
};
// For debugging the boost::spirit parsers. Print out the string enclosed in it_range.
template<typename Iterator>
std::ostream& operator<<(std::ostream& os, const boost::iterator_range<Iterator> &it_range)
@ -822,7 +858,8 @@ namespace client
spirit::int_type int_;
spirit::double_type double_;
spirit::ascii::string_type string;
spirit::repository::qi::iter_pos_type iter_pos;
spirit::eoi_type eoi;
spirit::repository::qi::iter_pos_type iter_pos;
auto kw = spirit::repository::qi::distinct(qi::copy(alnum | '_'));
qi::_val_type _val;
@ -843,7 +880,7 @@ namespace client
start = eps[px::bind(&MyContext::evaluate_full_macro, _r1, _a)] >
( eps(_a==true) > text_block(_r1) [_val=_1]
| conditional_expression(_r1) [ px::bind(&expr<Iterator>::evaluate_boolean_to_string, _1, _val) ]
);
) > eoi;
start.name("start");
qi::on_error<qi::fail>(start, px::bind(&MyContext::process_error_message<Iterator>, _r1, _4, _1, _2, _3));
@ -866,7 +903,7 @@ namespace client
// The macro expansion may contain numeric or string expressions, ifs and cases.
macro =
(kw["if"] > if_else_output(_r1) [_val = _1])
| (kw["switch"] > switch_output(_r1) [_val = _1])
// | (kw["switch"] > switch_output(_r1) [_val = _1])
| additive_expression(_r1) [ px::bind(&expr<Iterator>::to_string2, _1, _val) ];
macro.name("macro");
@ -908,14 +945,17 @@ namespace client
conditional_expression =
logical_or_expression(_r1) [_val = _1]
>> -('?' > conditional_expression(_r1) > ':' > conditional_expression(_r1)) [px::bind(&expr<Iterator>::ternary_op, _val, _1, _2)];
conditional_expression.name("conditional_expression");
logical_or_expression =
logical_and_expression(_r1) [_val = _1]
>> *( ((kw["or"] | "||") > logical_and_expression(_r1) ) [px::bind(&expr<Iterator>::logical_or, _val, _1)] );
logical_or_expression.name("logical_or_expression");
logical_and_expression =
equality_expression(_r1) [_val = _1]
>> *( ((kw["and"] | "&&") > equality_expression(_r1) ) [px::bind(&expr<Iterator>::logical_and, _val, _1)] );
logical_and_expression.name("logical_and_expression");
equality_expression =
relational_expression(_r1) [_val = _1]
@ -934,11 +974,12 @@ namespace client
relational_expression =
additive_expression(_r1) [_val = _1]
>> *( (lit('<') > additive_expression(_r1) ) [px::bind(&expr<Iterator>::lower, _val, _1)]
| (lit('>') > additive_expression(_r1) ) [px::bind(&expr<Iterator>::greater, _val, _1)]
| ("<=" > additive_expression(_r1) ) [px::bind(&expr<Iterator>::leq, _val, _1)]
>> *( ("<=" > additive_expression(_r1) ) [px::bind(&expr<Iterator>::leq, _val, _1)]
| (">=" > additive_expression(_r1) ) [px::bind(&expr<Iterator>::geq, _val, _1)]
| (lit('<') > additive_expression(_r1) ) [px::bind(&expr<Iterator>::lower, _val, _1)]
| (lit('>') > additive_expression(_r1) ) [px::bind(&expr<Iterator>::greater, _val, _1)]
);
relational_expression.name("relational_expression");
additive_expression =
multiplicative_expression(_r1) [_val = _1]
@ -1020,7 +1061,7 @@ namespace client
debug(text_block);
debug(macro);
debug(if_else_output);
debug(switch_output);
// debug(switch_output);
debug(legacy_variable_expansion);
debug(identifier);
debug(conditional_expression);
@ -1079,7 +1120,7 @@ namespace client
qi::rule<Iterator, OptWithPos<Iterator>(const MyContext*), spirit::ascii::space_type> variable_reference;
qi::rule<Iterator, std::string(const MyContext*), qi::locals<bool, bool>, spirit::ascii::space_type> if_else_output;
qi::rule<Iterator, std::string(const MyContext*), qi::locals<expr<Iterator>, bool, std::string>, spirit::ascii::space_type> switch_output;
// qi::rule<Iterator, std::string(const MyContext*), qi::locals<expr<Iterator>, bool, std::string>, spirit::ascii::space_type> switch_output;
qi::symbols<char> keywords;
};
@ -1102,7 +1143,7 @@ static std::string process_macro(const std::string &templ, client::MyContext &co
// Accumulator for the processed template.
std::string output;
bool res = phrase_parse(iter, end, macro_processor_instance(&context), space, output);
if (! context.error_message.empty()) {
if (!context.error_message.empty()) {
if (context.error_message.back() != '\n' && context.error_message.back() != '\r')
context.error_message += '\n';
throw std::runtime_error(context.error_message);

View file

@ -14,14 +14,17 @@ class Line;
class Linef;
class MultiPoint;
class Point;
class Point3;
class Pointf;
class Pointf3;
typedef Point Vector;
typedef Point3 Vector3;
typedef Pointf Vectorf;
typedef Pointf3 Vectorf3;
typedef std::vector<Point> Points;
typedef std::vector<Point*> PointPtrs;
typedef std::vector<const Point*> PointConstPtrs;
typedef std::vector<Point3> Points3;
typedef std::vector<Pointf> Pointfs;
typedef std::vector<Pointf3> Pointf3s;
@ -32,8 +35,7 @@ public:
coord_t x;
coord_t y;
Point(coord_t _x = 0, coord_t _y = 0): x(_x), y(_y) {};
Point(int _x, int _y): x(_x), y(_y) {};
Point(long long _x, long long _y): x(coord_t(_x)), y(coord_t(_y)) {}; // for Clipper
Point(int64_t _x, int64_t _y): x(coord_t(_x)), y(coord_t(_y)) {}; // for Clipper
Point(double x, double y);
static Point new_scale(coordf_t x, coordf_t y) { return Point(coord_t(scale_(x)), coord_t(scale_(y))); }
@ -186,10 +188,11 @@ public:
static Point3 new_scale(coordf_t x, coordf_t y, coordf_t z) { return Point3(coord_t(scale_(x)), coord_t(scale_(y)), coord_t(scale_(z))); }
bool operator==(const Point3 &rhs) const { return this->x == rhs.x && this->y == rhs.y && this->z == rhs.z; }
bool operator!=(const Point3 &rhs) const { return ! (*this == rhs); }
bool coincides_with(const Point3& rhs) const { return this->x == rhs.x && this->y == rhs.y && this->z == rhs.z; }
private:
// Hide the following inherited methods:
bool operator==(const Point &rhs);
bool operator!=(const Point &rhs);
bool operator==(const Point &rhs) const;
bool operator!=(const Point &rhs) const;
};
std::ostream& operator<<(std::ostream &stm, const Pointf &pointf);
@ -244,6 +247,7 @@ public:
static Pointf3 new_unscale(coord_t x, coord_t y, coord_t z) {
return Pointf3(unscale(x), unscale(y), unscale(z));
};
static Pointf3 new_unscale(const Point3& p) { return Pointf3(unscale(p.x), unscale(p.y), unscale(p.z)); }
void scale(double factor);
void translate(const Vectorf3 &vector);
void translate(double x, double y, double z);
@ -256,10 +260,23 @@ public:
private:
// Hide the following inherited methods:
bool operator==(const Pointf &rhs);
bool operator!=(const Pointf &rhs);
bool operator==(const Pointf &rhs) const;
bool operator!=(const Pointf &rhs) const;
};
inline Pointf3 operator+(const Pointf3& p1, const Pointf3& p2) { return Pointf3(p1.x + p2.x, p1.y + p2.y, p1.z + p2.z); }
inline Pointf3 operator-(const Pointf3& p1, const Pointf3& p2) { return Pointf3(p1.x - p2.x, p1.y - p2.y, p1.z - p2.z); }
inline Pointf3 operator-(const Pointf3& p) { return Pointf3(-p.x, -p.y, -p.z); }
inline Pointf3 operator*(double scalar, const Pointf3& p) { return Pointf3(scalar * p.x, scalar * p.y, scalar * p.z); }
inline Pointf3 operator*(const Pointf3& p, double scalar) { return Pointf3(scalar * p.x, scalar * p.y, scalar * p.z); }
inline Pointf3 cross(const Pointf3& v1, const Pointf3& v2) { return Pointf3(v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z, v1.x * v2.y - v1.y * v2.x); }
inline coordf_t dot(const Pointf3& v1, const Pointf3& v2) { return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z; }
inline Pointf3 normalize(const Pointf3& v)
{
coordf_t len = ::sqrt(sqr(v.x) + sqr(v.y) + sqr(v.z));
return (len != 0.0) ? 1.0 / len * v : Pointf3(0.0, 0.0, 0.0);
}
template<typename TO> inline TO convert_to(const Point &src) { return TO(typename TO::coord_type(src.x), typename TO::coord_type(src.y)); }
template<typename TO> inline TO convert_to(const Pointf &src) { return TO(typename TO::coord_type(src.x), typename TO::coord_type(src.y)); }
template<typename TO> inline TO convert_to(const Point3 &src) { return TO(typename TO::coord_type(src.x), typename TO::coord_type(src.y), typename TO::coord_type(src.z)); }
@ -271,23 +288,6 @@ template<typename TO> inline TO convert_to(const Pointf3 &src) { return TO(typen
#include <boost/version.hpp>
#include <boost/polygon/polygon.hpp>
namespace boost { namespace polygon {
template <>
struct geometry_concept<coord_t> { typedef coordinate_concept type; };
/* Boost.Polygon already defines a specialization for coordinate_traits<long> as of 1.60:
https://github.com/boostorg/polygon/commit/0ac7230dd1f8f34cb12b86c8bb121ae86d3d9b97 */
#if BOOST_VERSION < 106000
template <>
struct coordinate_traits<coord_t> {
typedef coord_t coordinate_type;
typedef long double area_type;
typedef long long manhattan_area_type;
typedef unsigned long long unsigned_area_type;
typedef long long coordinate_difference;
typedef long double coordinate_distance;
};
#endif
template <>
struct geometry_concept<Slic3r::Point> { typedef point_concept type; };

View file

@ -24,6 +24,12 @@ public:
explicit Polygon(const Points &points): MultiPoint(points) {}
Polygon(const Polygon &other) : MultiPoint(other.points) {}
Polygon(Polygon &&other) : MultiPoint(std::move(other.points)) {}
static Polygon new_scale(std::vector<Pointf> points) {
Points int_points;
for (auto pt : points)
int_points.push_back(Point::new_scale(pt.x, pt.y));
return Polygon(int_points);
}
Polygon& operator=(const Polygon &other) { points = other.points; return *this; }
Polygon& operator=(Polygon &&other) { points = std::move(other.points); return *this; }

View file

@ -278,4 +278,18 @@ ThickPolyline::reverse()
std::swap(this->endpoints.first, this->endpoints.second);
}
Lines3 Polyline3::lines() const
{
Lines3 lines;
if (points.size() >= 2)
{
lines.reserve(points.size() - 1);
for (Points3::const_iterator it = points.begin(); it != points.end() - 1; ++it)
{
lines.emplace_back(*it, *(it + 1));
}
}
return lines;
}
}

View file

@ -21,6 +21,14 @@ public:
Polyline(Polyline &&other) : MultiPoint(std::move(other.points)) {}
Polyline& operator=(const Polyline &other) { points = other.points; return *this; }
Polyline& operator=(Polyline &&other) { points = std::move(other.points); return *this; }
static Polyline new_scale(std::vector<Pointf> points) {
Polyline pl;
Points int_points;
for (auto pt : points)
int_points.push_back(Point::new_scale(pt.x, pt.y));
pl.append(int_points);
return pl;
}
void append(const Point &point) { this->points.push_back(point); }
void append(const Points &src) { this->append(src.begin(), src.end()); }
@ -129,6 +137,14 @@ class ThickPolyline : public Polyline {
void reverse();
};
class Polyline3 : public MultiPoint3
{
public:
virtual Lines3 lines() const;
};
typedef std::vector<Polyline3> Polylines3;
}
#endif

View file

@ -568,8 +568,8 @@ std::string Print::validate() const
if (std::abs(dmr - 0.4) > EPSILON)
return "The Wipe Tower is currently only supported for the 0.4mm nozzle diameter.";
#endif
if (this->config.gcode_flavor != gcfRepRap)
return "The Wipe Tower is currently only supported for the RepRap (Marlin / Sprinter) G-code flavor.";
if (this->config.gcode_flavor != gcfRepRap && this->config.gcode_flavor != gcfMarlin)
return "The Wipe Tower is currently only supported for the Marlin and RepRap/Sprinter G-code flavors.";
if (! this->config.use_relative_e_distances)
return "The Wipe Tower is currently only supported with the relative extruder addressing (use_relative_e_distances=1).";
SlicingParameters slicing_params0 = this->objects.front()->slicing_parameters();
@ -998,7 +998,8 @@ void Print::_make_wipe_tower()
// Find the position in this->objects.first()->support_layers to insert these new support layers.
double wipe_tower_new_layer_print_z_first = m_tool_ordering.layer_tools()[idx_begin].print_z;
SupportLayerPtrs::iterator it_layer = this->objects.front()->support_layers.begin();
for (; (*it_layer)->print_z - EPSILON < wipe_tower_new_layer_print_z_first; ++ it_layer) ;
SupportLayerPtrs::iterator it_end = this->objects.front()->support_layers.end();
for (; it_layer != it_end && (*it_layer)->print_z - EPSILON < wipe_tower_new_layer_print_z_first; ++ it_layer);
// Find the stopper of the sequence of wipe tower layers, which do not have a counterpart in an object or a support layer.
for (size_t i = idx_begin; i < idx_end; ++ i) {
ToolOrdering::LayerTools &lt = const_cast<ToolOrdering::LayerTools&>(m_tool_ordering.layer_tools()[i]);
@ -1006,9 +1007,9 @@ void Print::_make_wipe_tower()
break;
lt.has_support = true;
// Insert the new support layer.
//FIXME the support layer ID is duplicated, but Vojtech hopes it is not being used anywhere anyway.
double height = lt.print_z - m_tool_ordering.layer_tools()[i-1].print_z;
auto *new_layer = new SupportLayer((*it_layer)->id(), this->objects.front(),
//FIXME the support layer ID is set to -1, as Vojtech hopes it is not being used anyway.
auto *new_layer = new SupportLayer(size_t(-1), this->objects.front(),
height, lt.print_z, lt.print_z - 0.5 * height);
it_layer = this->objects.front()->support_layers.insert(it_layer, new_layer);
++ it_layer;

View file

@ -233,8 +233,9 @@ public:
PrintRegionPtrs regions;
PlaceholderParser placeholder_parser;
// TODO: status_cb
std::string estimated_print_time;
double total_used_filament, total_extruded_volume, total_cost, total_weight;
std::map<size_t,float> filament_stats;
std::map<size_t, float> filament_stats;
PrintState<PrintStep, psCount> state;
// ordered collections of extrusion paths to build skirt loops and brim

File diff suppressed because it is too large Load diff

View file

@ -23,7 +23,8 @@
namespace Slic3r {
enum GCodeFlavor {
gcfRepRap, gcfTeacup, gcfMakerWare, gcfSailfish, gcfMach3, gcfMachinekit, gcfNoExtrusion, gcfSmoothie, gcfRepetier,
gcfRepRap, gcfRepetier, gcfTeacup, gcfMakerWare, gcfMarlin, gcfSailfish, gcfMach3, gcfMachinekit,
gcfSmoothie, gcfNoExtrusion,
};
enum InfillPattern {
@ -50,6 +51,7 @@ template<> inline t_config_enum_values& ConfigOptionEnum<GCodeFlavor>::get_enum_
keys_map["repetier"] = gcfRepetier;
keys_map["teacup"] = gcfTeacup;
keys_map["makerware"] = gcfMakerWare;
keys_map["marlin"] = gcfMarlin;
keys_map["sailfish"] = gcfSailfish;
keys_map["smoothie"] = gcfSmoothie;
keys_map["mach3"] = gcfMach3;

View file

@ -197,10 +197,11 @@ TriangleMesh::repair() {
stl_fill_holes(&stl);
stl_clear_error(&stl);
}
// normal_directions
stl_fix_normal_directions(&stl);
// commenting out the following call fixes: #574, #413, #269, #262, #259, #230, #228, #206
// // normal_directions
// stl_fix_normal_directions(&stl);
// normal_values
stl_fix_normal_values(&stl);
@ -374,6 +375,15 @@ void TriangleMesh::mirror_z()
this->mirror(Z);
}
void TriangleMesh::transform(const float* matrix3x4)
{
if (matrix3x4 == nullptr)
return;
stl_transform(&stl, const_cast<float*>(matrix3x4));
stl_invalidate_shared_vertices(&stl);
}
void TriangleMesh::align_to_origin()
{
this->translate(

View file

@ -47,6 +47,7 @@ public:
void mirror_x();
void mirror_y();
void mirror_z();
void transform(const float* matrix3x4);
void align_to_origin();
void rotate(double angle, Point* center);
TriangleMeshPtrs split() const;

View file

@ -20,21 +20,49 @@ void set_resources_dir(const std::string &path);
// Return a full path to the resources directory.
const std::string& resources_dir();
// Set a path with GUI localization files.
void set_local_dir(const std::string &path);
// Return a full path to the localization directory.
const std::string& localization_dir();
// Set a path with preset files.
void set_data_dir(const std::string &path);
// Return a full path to the GUI resource files.
const std::string& data_dir();
extern std::string encode_path(const char *src);
// A special type for strings encoded in the local Windows 8-bit code page.
// This type is only needed for Perl bindings to relay to Perl that the string is raw, not UTF-8 encoded.
typedef std::string local_encoded_string;
// Convert an UTF-8 encoded string into local coding.
// On Windows, the UTF-8 string is converted to a local 8-bit code page.
// On OSX and Linux, this function does no conversion and returns a copy of the source string.
extern local_encoded_string encode_path(const char *src);
extern std::string decode_path(const char *src);
extern std::string normalize_utf8_nfc(const char *src);
// File path / name / extension splitting utilities, working with UTF-8,
// to be published to Perl.
namespace PerlUtils {
// Get a file name including the extension.
extern std::string path_to_filename(const char *src);
// Get a file name without the extension.
extern std::string path_to_stem(const char *src);
// Get just the extension.
extern std::string path_to_extension(const char *src);
// Get a directory without the trailing slash.
extern std::string path_to_parent_path(const char *src);
};
// Timestamp formatted for header_slic3r_generated().
extern std::string timestamp_str();
// Standard "generated by Slic3r version xxx timestamp xxx" header string,
// to be placed at the top of Slic3r generated files.
inline std::string header_slic3r_generated() { return std::string("generated by " SLIC3R_FORK_NAME " " SLIC3R_VERSION " " ) + timestamp_str(); }
// Encode a file into a multi-part HTTP response with a given boundary.
std::string octoprint_encode_file_send_request_content(const char *path, bool select, bool print, const char *boundary);
// Compute the next highest power of 2 of 32-bit v
// http://graphics.stanford.edu/~seander/bithacks.html
template<typename T>

View file

@ -14,11 +14,11 @@
#include <boost/thread.hpp>
#define SLIC3R_FORK_NAME "Slic3r Prusa Edition"
#define SLIC3R_VERSION "1.38.4"
#define SLIC3R_VERSION "1.39.0"
#define SLIC3R_BUILD "UNKNOWN"
typedef long coord_t;
typedef double coordf_t;
typedef int32_t coord_t;
typedef double coordf_t;
//FIXME This epsilon value is used for many non-related purposes:
// For a threshold of a squared Euclidean distance,
@ -102,7 +102,7 @@ inline std::string debug_out_path(const char *name, ...)
namespace Slic3r {
enum Axis { X=0, Y, Z };
enum Axis { X=0, Y, Z, E, F, NUM_AXES };
template <class T>
inline void append_to(std::vector<T> &dst, const std::vector<T> &src)
@ -163,11 +163,11 @@ static inline T clamp(const T low, const T high, const T value)
return std::max(low, std::min(high, value));
}
template <typename T>
static inline T lerp(const T a, const T b, const T t)
template <typename T, typename Number>
static inline T lerp(const T& a, const T& b, Number t)
{
assert(t >= T(-EPSILON) && t <= T(1.+EPSILON));
return (1. - t) * a + t * b;
assert((t >= Number(-EPSILON)) && (t <= Number(1) + Number(EPSILON)));
return (Number(1) - t) * a + t * b;
}
} // namespace Slic3r

View file

@ -10,6 +10,8 @@
#include <boost/algorithm/string/predicate.hpp>
#include <boost/date_time/local_time/local_time.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/nowide/fstream.hpp>
#include <boost/nowide/integration/filesystem.hpp>
#include <boost/nowide/convert.hpp>
@ -101,6 +103,18 @@ const std::string& resources_dir()
return g_resources_dir;
}
static std::string g_local_dir;
void set_local_dir(const std::string &dir)
{
g_local_dir = dir;
}
const std::string& localization_dir()
{
return g_local_dir;
}
static std::string g_data_dir;
void set_data_dir(const std::string &dir)
@ -235,6 +249,17 @@ std::string normalize_utf8_nfc(const char *src)
return boost::locale::normalize(src, boost::locale::norm_nfc, locale_utf8);
}
namespace PerlUtils {
// Get a file name including the extension.
std::string path_to_filename(const char *src) { return boost::filesystem::path(src).filename().string(); }
// Get a file name without the extension.
std::string path_to_stem(const char *src) { return boost::filesystem::path(src).stem().string(); }
// Get just the extension.
std::string path_to_extension(const char *src) { return boost::filesystem::path(src).extension().string(); }
// Get a directory without the trailing slash.
std::string path_to_parent_path(const char *src) { return boost::filesystem::path(src).parent_path().string(); }
};
std::string timestamp_str()
{
const auto now = boost::posix_time::second_clock::local_time();
@ -247,4 +272,31 @@ std::string timestamp_str()
return buf;
}
std::string octoprint_encode_file_send_request_content(const char *cpath, bool select, bool print, const char *boundary)
{
// Read the complete G-code string into a string buffer.
// It will throw if the file cannot be open or read.
std::stringstream str_stream;
{
boost::nowide::ifstream ifs(cpath);
str_stream << ifs.rdbuf();
}
boost::filesystem::path path(cpath);
std::string request = boundary + '\n';
request += "Content-Disposition: form-data; name=\"";
request += path.stem().string() + "\"; filename=\"" + path.filename().string() + "\"\n";
request += "Content-Type: application/octet-stream\n\n";
request += str_stream.str();
request += boundary + '\n';
request += "Content-Disposition: form-data; name=\"select\"\n\n";
request += select ? "true\n" : "false\n";
request += boundary + '\n';
request += "Content-Disposition: form-data; name=\"print\"\n\n";
request += print ? "true\n" : "false\n";
request += boundary + '\n';
return request;
}
}; // namespace Slic3r

594
xs/src/miniz/miniz.cpp Normal file
View file

@ -0,0 +1,594 @@
/**************************************************************************
*
* Copyright 2013-2014 RAD Game Tools and Valve Software
* Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#include "miniz.h"
typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1];
typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1];
typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1];
/* ------------------- zlib-style API's */
mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len)
{
mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16);
size_t block_len = buf_len % 5552;
if (!ptr)
return MZ_ADLER32_INIT;
while (buf_len)
{
for (i = 0; i + 7 < block_len; i += 8, ptr += 8)
{
s1 += ptr[0], s2 += s1;
s1 += ptr[1], s2 += s1;
s1 += ptr[2], s2 += s1;
s1 += ptr[3], s2 += s1;
s1 += ptr[4], s2 += s1;
s1 += ptr[5], s2 += s1;
s1 += ptr[6], s2 += s1;
s1 += ptr[7], s2 += s1;
}
for (; i < block_len; ++i)
s1 += *ptr++, s2 += s1;
s1 %= 65521U, s2 %= 65521U;
buf_len -= block_len;
block_len = 5552;
}
return (s2 << 16) + s1;
}
/* Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ */
#if 0
mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len)
{
static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c };
mz_uint32 crcu32 = (mz_uint32)crc;
if (!ptr)
return MZ_CRC32_INIT;
crcu32 = ~crcu32;
while (buf_len--)
{
mz_uint8 b = *ptr++;
crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)];
crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)];
}
return ~crcu32;
}
#else
/* Faster, but larger CPU cache footprint.
*/
mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len)
{
static const mz_uint32 s_crc_table[256] =
{
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535,
0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD,
0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D,
0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4,
0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C,
0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC,
0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB,
0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F,
0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB,
0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA,
0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE,
0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A,
0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409,
0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81,
0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739,
0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268,
0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0,
0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8,
0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF,
0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703,
0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7,
0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE,
0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6,
0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D,
0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5,
0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605,
0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
};
mz_uint32 crc32 = (mz_uint32)crc ^ 0xFFFFFFFF;
const mz_uint8 *pByte_buf = (const mz_uint8 *)ptr;
while (buf_len >= 4)
{
crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF];
crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[1]) & 0xFF];
crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[2]) & 0xFF];
crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[3]) & 0xFF];
pByte_buf += 4;
buf_len -= 4;
}
while (buf_len)
{
crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF];
++pByte_buf;
--buf_len;
}
return ~crc32;
}
#endif
void mz_free(void *p)
{
MZ_FREE(p);
}
void *miniz_def_alloc_func(void *opaque, size_t items, size_t size)
{
(void)opaque, (void)items, (void)size;
return MZ_MALLOC(items * size);
}
void miniz_def_free_func(void *opaque, void *address)
{
(void)opaque, (void)address;
MZ_FREE(address);
}
void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size)
{
(void)opaque, (void)address, (void)items, (void)size;
return MZ_REALLOC(address, items * size);
}
const char *mz_version(void)
{
return MZ_VERSION;
}
#ifndef MINIZ_NO_ZLIB_APIS
int mz_deflateInit(mz_streamp pStream, int level)
{
return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY);
}
int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy)
{
tdefl_compressor *pComp;
mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy);
if (!pStream)
return MZ_STREAM_ERROR;
if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)))
return MZ_PARAM_ERROR;
pStream->data_type = 0;
pStream->adler = MZ_ADLER32_INIT;
pStream->msg = NULL;
pStream->reserved = 0;
pStream->total_in = 0;
pStream->total_out = 0;
if (!pStream->zalloc)
pStream->zalloc = miniz_def_alloc_func;
if (!pStream->zfree)
pStream->zfree = miniz_def_free_func;
pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor));
if (!pComp)
return MZ_MEM_ERROR;
pStream->state = (struct mz_internal_state *)pComp;
if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY)
{
mz_deflateEnd(pStream);
return MZ_PARAM_ERROR;
}
return MZ_OK;
}
int mz_deflateReset(mz_streamp pStream)
{
if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree))
return MZ_STREAM_ERROR;
pStream->total_in = pStream->total_out = 0;
tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags);
return MZ_OK;
}
int mz_deflate(mz_streamp pStream, int flush)
{
size_t in_bytes, out_bytes;
mz_ulong orig_total_in, orig_total_out;
int mz_status = MZ_OK;
if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out))
return MZ_STREAM_ERROR;
if (!pStream->avail_out)
return MZ_BUF_ERROR;
if (flush == MZ_PARTIAL_FLUSH)
flush = MZ_SYNC_FLUSH;
if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE)
return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR;
orig_total_in = pStream->total_in;
orig_total_out = pStream->total_out;
for (;;)
{
tdefl_status defl_status;
in_bytes = pStream->avail_in;
out_bytes = pStream->avail_out;
defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush);
pStream->next_in += (mz_uint)in_bytes;
pStream->avail_in -= (mz_uint)in_bytes;
pStream->total_in += (mz_uint)in_bytes;
pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state);
pStream->next_out += (mz_uint)out_bytes;
pStream->avail_out -= (mz_uint)out_bytes;
pStream->total_out += (mz_uint)out_bytes;
if (defl_status < 0)
{
mz_status = MZ_STREAM_ERROR;
break;
}
else if (defl_status == TDEFL_STATUS_DONE)
{
mz_status = MZ_STREAM_END;
break;
}
else if (!pStream->avail_out)
break;
else if ((!pStream->avail_in) && (flush != MZ_FINISH))
{
if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out))
break;
return MZ_BUF_ERROR; /* Can't make forward progress without some input.
*/
}
}
return mz_status;
}
int mz_deflateEnd(mz_streamp pStream)
{
if (!pStream)
return MZ_STREAM_ERROR;
if (pStream->state)
{
pStream->zfree(pStream->opaque, pStream->state);
pStream->state = NULL;
}
return MZ_OK;
}
mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len)
{
(void)pStream;
/* This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) */
return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5);
}
int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level)
{
int status;
mz_stream stream;
memset(&stream, 0, sizeof(stream));
/* In case mz_ulong is 64-bits (argh I hate longs). */
if ((source_len | *pDest_len) > 0xFFFFFFFFU)
return MZ_PARAM_ERROR;
stream.next_in = pSource;
stream.avail_in = (mz_uint32)source_len;
stream.next_out = pDest;
stream.avail_out = (mz_uint32)*pDest_len;
status = mz_deflateInit(&stream, level);
if (status != MZ_OK)
return status;
status = mz_deflate(&stream, MZ_FINISH);
if (status != MZ_STREAM_END)
{
mz_deflateEnd(&stream);
return (status == MZ_OK) ? MZ_BUF_ERROR : status;
}
*pDest_len = stream.total_out;
return mz_deflateEnd(&stream);
}
int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len)
{
return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION);
}
mz_ulong mz_compressBound(mz_ulong source_len)
{
return mz_deflateBound(NULL, source_len);
}
typedef struct
{
tinfl_decompressor m_decomp;
mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed;
int m_window_bits;
mz_uint8 m_dict[TINFL_LZ_DICT_SIZE];
tinfl_status m_last_status;
} inflate_state;
int mz_inflateInit2(mz_streamp pStream, int window_bits)
{
inflate_state *pDecomp;
if (!pStream)
return MZ_STREAM_ERROR;
if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))
return MZ_PARAM_ERROR;
pStream->data_type = 0;
pStream->adler = 0;
pStream->msg = NULL;
pStream->total_in = 0;
pStream->total_out = 0;
pStream->reserved = 0;
if (!pStream->zalloc)
pStream->zalloc = miniz_def_alloc_func;
if (!pStream->zfree)
pStream->zfree = miniz_def_free_func;
pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state));
if (!pDecomp)
return MZ_MEM_ERROR;
pStream->state = (struct mz_internal_state *)pDecomp;
tinfl_init(&pDecomp->m_decomp);
pDecomp->m_dict_ofs = 0;
pDecomp->m_dict_avail = 0;
pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;
pDecomp->m_first_call = 1;
pDecomp->m_has_flushed = 0;
pDecomp->m_window_bits = window_bits;
return MZ_OK;
}
int mz_inflateInit(mz_streamp pStream)
{
return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS);
}
int mz_inflate(mz_streamp pStream, int flush)
{
inflate_state *pState;
mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32;
size_t in_bytes, out_bytes, orig_avail_in;
tinfl_status status;
if ((!pStream) || (!pStream->state))
return MZ_STREAM_ERROR;
if (flush == MZ_PARTIAL_FLUSH)
flush = MZ_SYNC_FLUSH;
if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH))
return MZ_STREAM_ERROR;
pState = (inflate_state *)pStream->state;
if (pState->m_window_bits > 0)
decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER;
orig_avail_in = pStream->avail_in;
first_call = pState->m_first_call;
pState->m_first_call = 0;
if (pState->m_last_status < 0)
return MZ_DATA_ERROR;
if (pState->m_has_flushed && (flush != MZ_FINISH))
return MZ_STREAM_ERROR;
pState->m_has_flushed |= (flush == MZ_FINISH);
if ((flush == MZ_FINISH) && (first_call))
{
/* MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. */
decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF;
in_bytes = pStream->avail_in;
out_bytes = pStream->avail_out;
status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags);
pState->m_last_status = status;
pStream->next_in += (mz_uint)in_bytes;
pStream->avail_in -= (mz_uint)in_bytes;
pStream->total_in += (mz_uint)in_bytes;
pStream->adler = tinfl_get_adler32(&pState->m_decomp);
pStream->next_out += (mz_uint)out_bytes;
pStream->avail_out -= (mz_uint)out_bytes;
pStream->total_out += (mz_uint)out_bytes;
if (status < 0)
return MZ_DATA_ERROR;
else if (status != TINFL_STATUS_DONE)
{
pState->m_last_status = TINFL_STATUS_FAILED;
return MZ_BUF_ERROR;
}
return MZ_STREAM_END;
}
/* flush != MZ_FINISH then we must assume there's more input. */
if (flush != MZ_FINISH)
decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT;
if (pState->m_dict_avail)
{
n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
pStream->next_out += n;
pStream->avail_out -= n;
pStream->total_out += n;
pState->m_dict_avail -= n;
pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK;
}
for (;;)
{
in_bytes = pStream->avail_in;
out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs;
status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags);
pState->m_last_status = status;
pStream->next_in += (mz_uint)in_bytes;
pStream->avail_in -= (mz_uint)in_bytes;
pStream->total_in += (mz_uint)in_bytes;
pStream->adler = tinfl_get_adler32(&pState->m_decomp);
pState->m_dict_avail = (mz_uint)out_bytes;
n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
pStream->next_out += n;
pStream->avail_out -= n;
pStream->total_out += n;
pState->m_dict_avail -= n;
pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
if (status < 0)
return MZ_DATA_ERROR; /* Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). */
else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in))
return MZ_BUF_ERROR; /* Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. */
else if (flush == MZ_FINISH)
{
/* The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. */
if (status == TINFL_STATUS_DONE)
return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END;
/* status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. */
else if (!pStream->avail_out)
return MZ_BUF_ERROR;
}
else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail))
break;
}
return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK;
}
int mz_inflateEnd(mz_streamp pStream)
{
if (!pStream)
return MZ_STREAM_ERROR;
if (pStream->state)
{
pStream->zfree(pStream->opaque, pStream->state);
pStream->state = NULL;
}
return MZ_OK;
}
int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len)
{
mz_stream stream;
int status;
memset(&stream, 0, sizeof(stream));
/* In case mz_ulong is 64-bits (argh I hate longs). */
if ((source_len | *pDest_len) > 0xFFFFFFFFU)
return MZ_PARAM_ERROR;
stream.next_in = pSource;
stream.avail_in = (mz_uint32)source_len;
stream.next_out = pDest;
stream.avail_out = (mz_uint32)*pDest_len;
status = mz_inflateInit(&stream);
if (status != MZ_OK)
return status;
status = mz_inflate(&stream, MZ_FINISH);
if (status != MZ_STREAM_END)
{
mz_inflateEnd(&stream);
return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status;
}
*pDest_len = stream.total_out;
return mz_inflateEnd(&stream);
}
const char *mz_error(int err)
{
static struct
{
int m_err;
const char *m_pDesc;
} s_error_descs[] =
{
{ MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" }
};
mz_uint i;
for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i)
if (s_error_descs[i].m_err == err)
return s_error_descs[i].m_pDesc;
return NULL;
}
#endif /*MINIZ_NO_ZLIB_APIS */
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
*/

462
xs/src/miniz/miniz.h Normal file
View file

@ -0,0 +1,462 @@
/* miniz.c 2.0.6 beta - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing
See "unlicense" statement at the end of this file.
Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013
Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt
Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define
MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros).
* Low-level Deflate/Inflate implementation notes:
Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or
greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses
approximately as well as zlib.
Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function
coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory
block large enough to hold the entire file.
The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation.
* zlib-style API notes:
miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in
zlib replacement in many apps:
The z_stream struct, optional memory allocation callbacks
deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound
inflateInit/inflateInit2/inflate/inflateEnd
compress, compress2, compressBound, uncompress
CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines.
Supports raw deflate streams or standard zlib streams with adler-32 checking.
Limitations:
The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries.
I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but
there are no guarantees that miniz.c pulls this off perfectly.
* PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by
Alex Evans. Supports 1-4 bytes/pixel images.
* ZIP archive API notes:
The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to
get the job done with minimal fuss. There are simple API's to retrieve file information, read files from
existing archives, create new archives, append new files to existing archives, or clone archive data from
one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h),
or you can specify custom file read/write callbacks.
- Archive reading: Just call this function to read a single file from a disk archive:
void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name,
size_t *pSize, mz_uint zip_flags);
For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central
directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files.
- Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file:
int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags);
The locate operation can optionally check file comments too, which (as one example) can be used to identify
multiple versions of the same file in an archive. This function uses a simple linear search through the central
directory, so it's not very fast.
Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and
retrieve detailed info on each file by calling mz_zip_reader_file_stat().
- Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data
to disk and builds an exact image of the central directory in memory. The central directory image is written
all at once at the end of the archive file when the archive is finalized.
The archive writer can optionally align each file's local header and file data to any power of 2 alignment,
which can be useful when the archive will be read from optical media. Also, the writer supports placing
arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still
readable by any ZIP tool.
- Archive appending: The simple way to add a single file to an archive is to call this function:
mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name,
const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
The archive will be created if it doesn't already exist, otherwise it'll be appended to.
Note the appending is done in-place and is not an atomic operation, so if something goes wrong
during the operation it's possible the archive could be left without a central directory (although the local
file headers and file data will be fine, so the archive will be recoverable).
For more complex archive modification scenarios:
1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to
preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the
compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and
you're done. This is safe but requires a bunch of temporary disk space or heap memory.
2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(),
append new files as needed, then finalize the archive which will write an updated central directory to the
original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a
possibility that the archive's central directory could be lost with this method if anything goes wrong, though.
- ZIP archive support limitations:
No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files.
Requires streams capable of seeking.
* This is a header file library, like stb_image.c. To get only a header file, either cut and paste the
below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it.
* Important: For best perf. be sure to customize the below macros for your target platform:
#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
#define MINIZ_LITTLE_ENDIAN 1
#define MINIZ_HAS_64BIT_REGISTERS 1
* On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz
uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files
(i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes).
*/
#pragma once
#include "miniz_common.h"
#include "miniz_tdef.h"
#include "miniz_tinfl.h"
/* Defines to completely disable specific portions of miniz.c:
If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. */
/* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. */
/*#define MINIZ_NO_STDIO */
/* If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or */
/* get/set file times, and the C run-time funcs that get/set times won't be called. */
/* The current downside is the times written to your archives will be from 1979. */
/*#define MINIZ_NO_TIME */
/* Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. */
/*#define MINIZ_NO_ARCHIVE_APIS */
/* Define MINIZ_NO_ARCHIVE_WRITING_APIS to disable all writing related ZIP archive API's. */
/*#define MINIZ_NO_ARCHIVE_WRITING_APIS */
/* Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. */
/*#define MINIZ_NO_ZLIB_APIS */
/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. */
/*#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES */
/* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc
callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user
functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. */
/*#define MINIZ_NO_MALLOC */
#if defined(__TINYC__) && (defined(__linux) || defined(__linux__))
/* TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux */
#define MINIZ_NO_TIME
#endif
#include <stddef.h>
#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
#include <time.h>
#endif
#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__)
/* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */
#define MINIZ_X86_OR_X64_CPU 1
#else
#define MINIZ_X86_OR_X64_CPU 0
#endif
#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
/* Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. */
#define MINIZ_LITTLE_ENDIAN 1
#else
#define MINIZ_LITTLE_ENDIAN 0
#endif
#if MINIZ_X86_OR_X64_CPU
/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. */
#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
#else
#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0
#endif
#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__)
/* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). */
#define MINIZ_HAS_64BIT_REGISTERS 1
#else
#define MINIZ_HAS_64BIT_REGISTERS 0
#endif
/* ------------------- zlib-style API Definitions. */
/* For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! */
typedef unsigned long mz_ulong;
/* mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. */
void mz_free(void *p);
#define MZ_ADLER32_INIT (1)
/* mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. */
mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);
#define MZ_CRC32_INIT (0)
/* mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. */
mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);
/* Compression strategies. */
enum
{
MZ_DEFAULT_STRATEGY = 0,
MZ_FILTERED = 1,
MZ_HUFFMAN_ONLY = 2,
MZ_RLE = 3,
MZ_FIXED = 4
};
/* Method */
#define MZ_DEFLATED 8
/* Heap allocation callbacks.
Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. */
typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
typedef void (*mz_free_func)(void *opaque, void *address);
typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size);
/* Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. */
enum
{
MZ_NO_COMPRESSION = 0,
MZ_BEST_SPEED = 1,
MZ_BEST_COMPRESSION = 9,
MZ_UBER_COMPRESSION = 10,
MZ_DEFAULT_LEVEL = 6,
MZ_DEFAULT_COMPRESSION = -1
};
#define MZ_VERSION "10.0.1"
#define MZ_VERNUM 0xA010
#define MZ_VER_MAJOR 10
#define MZ_VER_MINOR 0
#define MZ_VER_REVISION 1
#define MZ_VER_SUBREVISION 0
#ifndef MINIZ_NO_ZLIB_APIS
/* Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). */
enum
{
MZ_NO_FLUSH = 0,
MZ_PARTIAL_FLUSH = 1,
MZ_SYNC_FLUSH = 2,
MZ_FULL_FLUSH = 3,
MZ_FINISH = 4,
MZ_BLOCK = 5
};
/* Return status codes. MZ_PARAM_ERROR is non-standard. */
enum
{
MZ_OK = 0,
MZ_STREAM_END = 1,
MZ_NEED_DICT = 2,
MZ_ERRNO = -1,
MZ_STREAM_ERROR = -2,
MZ_DATA_ERROR = -3,
MZ_MEM_ERROR = -4,
MZ_BUF_ERROR = -5,
MZ_VERSION_ERROR = -6,
MZ_PARAM_ERROR = -10000
};
/* Window bits */
#define MZ_DEFAULT_WINDOW_BITS 15
struct mz_internal_state;
/* Compression/decompression stream struct. */
typedef struct mz_stream_s
{
const unsigned char *next_in; /* pointer to next byte to read */
unsigned int avail_in; /* number of bytes available at next_in */
mz_ulong total_in; /* total number of bytes consumed so far */
unsigned char *next_out; /* pointer to next byte to write */
unsigned int avail_out; /* number of bytes that can be written to next_out */
mz_ulong total_out; /* total number of bytes produced so far */
char *msg; /* error msg (unused) */
struct mz_internal_state *state; /* internal state, allocated by zalloc/zfree */
mz_alloc_func zalloc; /* optional heap allocation function (defaults to malloc) */
mz_free_func zfree; /* optional heap free function (defaults to free) */
void *opaque; /* heap alloc function user pointer */
int data_type; /* data_type (unused) */
mz_ulong adler; /* adler32 of the source or uncompressed data */
mz_ulong reserved; /* not used */
} mz_stream;
typedef mz_stream *mz_streamp;
/* Returns the version string of miniz.c. */
const char *mz_version(void);
/* mz_deflateInit() initializes a compressor with default options: */
/* Parameters: */
/* pStream must point to an initialized mz_stream struct. */
/* level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. */
/* level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. */
/* (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) */
/* Return values: */
/* MZ_OK on success. */
/* MZ_STREAM_ERROR if the stream is bogus. */
/* MZ_PARAM_ERROR if the input parameters are bogus. */
/* MZ_MEM_ERROR on out of memory. */
int mz_deflateInit(mz_streamp pStream, int level);
/* mz_deflateInit2() is like mz_deflate(), except with more control: */
/* Additional parameters: */
/* method must be MZ_DEFLATED */
/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) */
/* mem_level must be between [1, 9] (it's checked but ignored by miniz.c) */
int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy);
/* Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). */
int mz_deflateReset(mz_streamp pStream);
/* mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. */
/* Parameters: */
/* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */
/* flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. */
/* Return values: */
/* MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). */
/* MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. */
/* MZ_STREAM_ERROR if the stream is bogus. */
/* MZ_PARAM_ERROR if one of the parameters is invalid. */
/* MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) */
int mz_deflate(mz_streamp pStream, int flush);
/* mz_deflateEnd() deinitializes a compressor: */
/* Return values: */
/* MZ_OK on success. */
/* MZ_STREAM_ERROR if the stream is bogus. */
int mz_deflateEnd(mz_streamp pStream);
/* mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. */
mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
/* Single-call compression functions mz_compress() and mz_compress2(): */
/* Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. */
int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);
int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level);
/* mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). */
mz_ulong mz_compressBound(mz_ulong source_len);
/* Initializes a decompressor. */
int mz_inflateInit(mz_streamp pStream);
/* mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: */
/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). */
int mz_inflateInit2(mz_streamp pStream, int window_bits);
/* Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. */
/* Parameters: */
/* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */
/* flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. */
/* On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). */
/* MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. */
/* Return values: */
/* MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. */
/* MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. */
/* MZ_STREAM_ERROR if the stream is bogus. */
/* MZ_DATA_ERROR if the deflate stream is invalid. */
/* MZ_PARAM_ERROR if one of the parameters is invalid. */
/* MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again */
/* with more input data, or with more room in the output buffer (except when using single call decompression, described above). */
int mz_inflate(mz_streamp pStream, int flush);
/* Deinitializes a decompressor. */
int mz_inflateEnd(mz_streamp pStream);
/* Single-call decompression. */
/* Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. */
int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);
/* Returns a string description of the specified error code, or NULL if the error code is invalid. */
const char *mz_error(int err);
/* Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. */
/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. */
#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
typedef unsigned char Byte;
typedef unsigned int uInt;
typedef mz_ulong uLong;
typedef Byte Bytef;
typedef uInt uIntf;
typedef char charf;
typedef int intf;
typedef void *voidpf;
typedef uLong uLongf;
typedef void *voidp;
typedef void *const voidpc;
#define Z_NULL 0
#define Z_NO_FLUSH MZ_NO_FLUSH
#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH
#define Z_SYNC_FLUSH MZ_SYNC_FLUSH
#define Z_FULL_FLUSH MZ_FULL_FLUSH
#define Z_FINISH MZ_FINISH
#define Z_BLOCK MZ_BLOCK
#define Z_OK MZ_OK
#define Z_STREAM_END MZ_STREAM_END
#define Z_NEED_DICT MZ_NEED_DICT
#define Z_ERRNO MZ_ERRNO
#define Z_STREAM_ERROR MZ_STREAM_ERROR
#define Z_DATA_ERROR MZ_DATA_ERROR
#define Z_MEM_ERROR MZ_MEM_ERROR
#define Z_BUF_ERROR MZ_BUF_ERROR
#define Z_VERSION_ERROR MZ_VERSION_ERROR
#define Z_PARAM_ERROR MZ_PARAM_ERROR
#define Z_NO_COMPRESSION MZ_NO_COMPRESSION
#define Z_BEST_SPEED MZ_BEST_SPEED
#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION
#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY
#define Z_FILTERED MZ_FILTERED
#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY
#define Z_RLE MZ_RLE
#define Z_FIXED MZ_FIXED
#define Z_DEFLATED MZ_DEFLATED
#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
#define alloc_func mz_alloc_func
#define free_func mz_free_func
#define internal_state mz_internal_state
#define z_stream mz_stream
#define deflateInit mz_deflateInit
#define deflateInit2 mz_deflateInit2
#define deflateReset mz_deflateReset
#define deflate mz_deflate
#define deflateEnd mz_deflateEnd
#define deflateBound mz_deflateBound
#define compress mz_compress
#define compress2 mz_compress2
#define compressBound mz_compressBound
#define inflateInit mz_inflateInit
#define inflateInit2 mz_inflateInit2
#define inflate mz_inflate
#define inflateEnd mz_inflateEnd
#define uncompress mz_uncompress
#define crc32 mz_crc32
#define adler32 mz_adler32
#define MAX_WBITS 15
#define MAX_MEM_LEVEL 9
#define zError mz_error
#define ZLIB_VERSION MZ_VERSION
#define ZLIB_VERNUM MZ_VERNUM
#define ZLIB_VER_MAJOR MZ_VER_MAJOR
#define ZLIB_VER_MINOR MZ_VER_MINOR
#define ZLIB_VER_REVISION MZ_VER_REVISION
#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION
#define zlibVersion mz_version
#define zlib_version mz_version()
#endif /* #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES */
#endif /* MINIZ_NO_ZLIB_APIS */

View file

@ -0,0 +1,83 @@
#pragma once
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
/* ------------------- Types and macros */
typedef unsigned char mz_uint8;
typedef signed short mz_int16;
typedef unsigned short mz_uint16;
typedef unsigned int mz_uint32;
typedef unsigned int mz_uint;
typedef int64_t mz_int64;
typedef uint64_t mz_uint64;
typedef int mz_bool;
#define MZ_FALSE (0)
#define MZ_TRUE (1)
/* Works around MSVC's spammy "warning C4127: conditional expression is constant" message. */
#ifdef _MSC_VER
#define MZ_MACRO_END while (0, 0)
#else
#define MZ_MACRO_END while (0)
#endif
#ifdef MINIZ_NO_STDIO
#define MZ_FILE void *
#else
#include <stdio.h>
#define MZ_FILE FILE
#endif /* #ifdef MINIZ_NO_STDIO */
#ifdef MINIZ_NO_TIME
typedef struct mz_dummy_time_t_tag
{
int m_dummy;
} mz_dummy_time_t;
#define MZ_TIME_T mz_dummy_time_t
#else
#define MZ_TIME_T time_t
#endif
#define MZ_ASSERT(x) assert(x)
#ifdef MINIZ_NO_MALLOC
#define MZ_MALLOC(x) NULL
#define MZ_FREE(x) (void)x, ((void)0)
#define MZ_REALLOC(p, x) NULL
#else
#define MZ_MALLOC(x) malloc(x)
#define MZ_FREE(x) free(x)
#define MZ_REALLOC(p, x) realloc(p, x)
#endif
#define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b))
#define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b))
#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
#define MZ_READ_LE16(p) *((const mz_uint16 *)(p))
#define MZ_READ_LE32(p) *((const mz_uint32 *)(p))
#else
#define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
#define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
#endif
#define MZ_READ_LE64(p) (((mz_uint64)MZ_READ_LE32(p)) | (((mz_uint64)MZ_READ_LE32((const mz_uint8 *)(p) + sizeof(mz_uint32))) << 32U))
#ifdef _MSC_VER
#define MZ_FORCEINLINE __forceinline
#elif defined(__GNUC__)
#define MZ_FORCEINLINE __inline__ __attribute__((__always_inline__))
#else
#define MZ_FORCEINLINE inline
#endif
extern void *miniz_def_alloc_func(void *opaque, size_t items, size_t size);
extern void miniz_def_free_func(void *opaque, void *address);
extern void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size);
#define MZ_UINT16_MAX (0xFFFFU)
#define MZ_UINT32_MAX (0xFFFFFFFFU)

1555
xs/src/miniz/miniz_tdef.cpp Normal file

File diff suppressed because it is too large Load diff

181
xs/src/miniz/miniz_tdef.h Normal file
View file

@ -0,0 +1,181 @@
#pragma once
#include "miniz_common.h"
/* ------------------- Low-level Compression API Definitions */
/* Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). */
#define TDEFL_LESS_MEMORY 0
/* tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): */
/* TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). */
enum
{
TDEFL_HUFFMAN_ONLY = 0,
TDEFL_DEFAULT_MAX_PROBES = 128,
TDEFL_MAX_PROBES_MASK = 0xFFF
};
/* TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. */
/* TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). */
/* TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. */
/* TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). */
/* TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) */
/* TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. */
/* TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. */
/* TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. */
/* The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). */
enum
{
TDEFL_WRITE_ZLIB_HEADER = 0x01000,
TDEFL_COMPUTE_ADLER32 = 0x02000,
TDEFL_GREEDY_PARSING_FLAG = 0x04000,
TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
TDEFL_RLE_MATCHES = 0x10000,
TDEFL_FILTER_MATCHES = 0x20000,
TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
};
/* High level compression functions: */
/* tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). */
/* On entry: */
/* pSrc_buf, src_buf_len: Pointer and size of source block to compress. */
/* flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. */
/* On return: */
/* Function returns a pointer to the compressed data, or NULL on failure. */
/* *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. */
/* The caller must free() the returned block when it's no longer needed. */
void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
/* tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. */
/* Returns 0 on failure. */
size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);
/* Compresses an image to a compressed PNG file in memory. */
/* On entry: */
/* pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. */
/* The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. */
/* level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL */
/* If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). */
/* On return: */
/* Function returns a pointer to the compressed data, or NULL on failure. */
/* *pLen_out will be set to the size of the PNG image file. */
/* The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. */
void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip);
void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out);
/* Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. */
typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser);
/* tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. */
mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
enum
{
TDEFL_MAX_HUFF_TABLES = 3,
TDEFL_MAX_HUFF_SYMBOLS_0 = 288,
TDEFL_MAX_HUFF_SYMBOLS_1 = 32,
TDEFL_MAX_HUFF_SYMBOLS_2 = 19,
TDEFL_LZ_DICT_SIZE = 32768,
TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1,
TDEFL_MIN_MATCH_LEN = 3,
TDEFL_MAX_MATCH_LEN = 258
};
/* TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). */
#if TDEFL_LESS_MEMORY
enum
{
TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024,
TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
TDEFL_MAX_HUFF_SYMBOLS = 288,
TDEFL_LZ_HASH_BITS = 12,
TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
};
#else
enum
{
TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024,
TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
TDEFL_MAX_HUFF_SYMBOLS = 288,
TDEFL_LZ_HASH_BITS = 15,
TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
};
#endif
/* The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. */
typedef enum {
TDEFL_STATUS_BAD_PARAM = -2,
TDEFL_STATUS_PUT_BUF_FAILED = -1,
TDEFL_STATUS_OKAY = 0,
TDEFL_STATUS_DONE = 1
} tdefl_status;
/* Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums */
typedef enum {
TDEFL_NO_FLUSH = 0,
TDEFL_SYNC_FLUSH = 2,
TDEFL_FULL_FLUSH = 3,
TDEFL_FINISH = 4
} tdefl_flush;
/* tdefl's compression state structure. */
typedef struct
{
tdefl_put_buf_func_ptr m_pPut_buf_func;
void *m_pPut_buf_user;
mz_uint m_flags, m_max_probes[2];
int m_greedy_parsing;
mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer;
mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish;
tdefl_status m_prev_return_status;
const void *m_pIn_buf;
void *m_pOut_buf;
size_t *m_pIn_buf_size, *m_pOut_buf_size;
tdefl_flush m_flush;
const mz_uint8 *m_pSrc;
size_t m_src_buf_left, m_out_buf_ofs;
mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
} tdefl_compressor;
/* Initializes the compressor. */
/* There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. */
/* pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. */
/* If pBut_buf_func is NULL the user should always call the tdefl_compress() API. */
/* flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) */
tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
/* Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. */
tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush);
/* tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. */
/* tdefl_compress_buffer() always consumes the entire input buffer. */
tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush);
tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
/* Create tdefl_compress() flags given zlib-style compression parameters. */
/* level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) */
/* window_bits may be -15 (raw deflate) or 15 (zlib) */
/* strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED */
mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy);
/* Allocate the tdefl_compressor structure in C so that */
/* non-C language bindings to tdefl_ API don't need to worry about */
/* structure size and allocation mechanism. */
tdefl_compressor *tdefl_compressor_alloc();
void tdefl_compressor_free(tdefl_compressor *pComp);

View file

@ -0,0 +1,725 @@
/**************************************************************************
*
* Copyright 2013-2014 RAD Game Tools and Valve Software
* Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#include "miniz_tinfl.h"
/* ------------------- Low-level Decompression (completely independent from all compression API's) */
#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
#define TINFL_MEMSET(p, c, l) memset(p, c, l)
#define TINFL_CR_BEGIN \
switch (r->m_state) \
{ \
case 0:
#define TINFL_CR_RETURN(state_index, result) \
do \
{ \
status = result; \
r->m_state = state_index; \
goto common_exit; \
case state_index:; \
} \
MZ_MACRO_END
#define TINFL_CR_RETURN_FOREVER(state_index, result) \
do \
{ \
for (;;) \
{ \
TINFL_CR_RETURN(state_index, result); \
} \
} \
MZ_MACRO_END
#define TINFL_CR_FINISH }
#define TINFL_GET_BYTE(state_index, c) \
do \
{ \
while (pIn_buf_cur >= pIn_buf_end) \
{ \
TINFL_CR_RETURN(state_index, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); \
} \
c = *pIn_buf_cur++; \
} \
MZ_MACRO_END
#define TINFL_NEED_BITS(state_index, n) \
do \
{ \
mz_uint c; \
TINFL_GET_BYTE(state_index, c); \
bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
num_bits += 8; \
} while (num_bits < (mz_uint)(n))
#define TINFL_SKIP_BITS(state_index, n) \
do \
{ \
if (num_bits < (mz_uint)(n)) \
{ \
TINFL_NEED_BITS(state_index, n); \
} \
bit_buf >>= (n); \
num_bits -= (n); \
} \
MZ_MACRO_END
#define TINFL_GET_BITS(state_index, b, n) \
do \
{ \
if (num_bits < (mz_uint)(n)) \
{ \
TINFL_NEED_BITS(state_index, n); \
} \
b = bit_buf & ((1 << (n)) - 1); \
bit_buf >>= (n); \
num_bits -= (n); \
} \
MZ_MACRO_END
/* TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. */
/* It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a */
/* Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the */
/* bit buffer contains >=15 bits (deflate's max. Huffman code size). */
#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \
do \
{ \
temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \
if (temp >= 0) \
{ \
code_len = temp >> 9; \
if ((code_len) && (num_bits >= code_len)) \
break; \
} \
else if (num_bits > TINFL_FAST_LOOKUP_BITS) \
{ \
code_len = TINFL_FAST_LOOKUP_BITS; \
do \
{ \
temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
} while ((temp < 0) && (num_bits >= (code_len + 1))); \
if (temp >= 0) \
break; \
} \
TINFL_GET_BYTE(state_index, c); \
bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
num_bits += 8; \
} while (num_bits < 15);
/* TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read */
/* beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully */
/* decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. */
/* The slow path is only executed at the very end of the input buffer. */
/* v1.16: The original macro handled the case at the very end of the passed-in input buffer, but we also need to handle the case where the user passes in 1+zillion bytes */
/* following the deflate data and our non-conservative read-ahead path won't kick in here on this code. This is much trickier. */
#define TINFL_HUFF_DECODE(state_index, sym, pHuff) \
do \
{ \
int temp; \
mz_uint code_len, c; \
if (num_bits < 15) \
{ \
if ((pIn_buf_end - pIn_buf_cur) < 2) \
{ \
TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \
} \
else \
{ \
bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \
pIn_buf_cur += 2; \
num_bits += 16; \
} \
} \
if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \
code_len = temp >> 9, temp &= 511; \
else \
{ \
code_len = TINFL_FAST_LOOKUP_BITS; \
do \
{ \
temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
} while (temp < 0); \
} \
sym = temp; \
bit_buf >>= code_len; \
num_bits -= code_len; \
} \
MZ_MACRO_END
tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags)
{
static const int s_length_base[31] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 };
static const int s_length_extra[31] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0 };
static const int s_dist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 };
static const int s_dist_extra[32] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 };
static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
static const int s_min_table_sizes[3] = { 257, 1, 4 };
tinfl_status status = TINFL_STATUS_FAILED;
mz_uint32 num_bits, dist, counter, num_extra;
tinfl_bit_buf_t bit_buf;
const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size;
mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size;
size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start;
/* Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). */
if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start))
{
*pIn_buf_size = *pOut_buf_size = 0;
return TINFL_STATUS_BAD_PARAM;
}
num_bits = r->m_num_bits;
bit_buf = r->m_bit_buf;
dist = r->m_dist;
counter = r->m_counter;
num_extra = r->m_num_extra;
dist_from_out_buf_start = r->m_dist_from_out_buf_start;
TINFL_CR_BEGIN
bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0;
r->m_z_adler32 = r->m_check_adler32 = 1;
if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)
{
TINFL_GET_BYTE(1, r->m_zhdr0);
TINFL_GET_BYTE(2, r->m_zhdr1);
counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));
if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4)))));
if (counter)
{
TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED);
}
}
do
{
TINFL_GET_BITS(3, r->m_final, 3);
r->m_type = r->m_final >> 1;
if (r->m_type == 0)
{
TINFL_SKIP_BITS(5, num_bits & 7);
for (counter = 0; counter < 4; ++counter)
{
if (num_bits)
TINFL_GET_BITS(6, r->m_raw_header[counter], 8);
else
TINFL_GET_BYTE(7, r->m_raw_header[counter]);
}
if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8))))
{
TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED);
}
while ((counter) && (num_bits))
{
TINFL_GET_BITS(51, dist, 8);
while (pOut_buf_cur >= pOut_buf_end)
{
TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT);
}
*pOut_buf_cur++ = (mz_uint8)dist;
counter--;
}
while (counter)
{
size_t n;
while (pOut_buf_cur >= pOut_buf_end)
{
TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT);
}
while (pIn_buf_cur >= pIn_buf_end)
{
TINFL_CR_RETURN(38, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS);
}
n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter);
TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n);
pIn_buf_cur += n;
pOut_buf_cur += n;
counter -= (mz_uint)n;
}
}
else if (r->m_type == 3)
{
TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);
}
else
{
if (r->m_type == 1)
{
mz_uint8 *p = r->m_tables[0].m_code_size;
mz_uint i;
r->m_table_sizes[0] = 288;
r->m_table_sizes[1] = 32;
TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);
for (i = 0; i <= 143; ++i)
*p++ = 8;
for (; i <= 255; ++i)
*p++ = 9;
for (; i <= 279; ++i)
*p++ = 7;
for (; i <= 287; ++i)
*p++ = 8;
}
else
{
for (counter = 0; counter < 3; counter++)
{
TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]);
r->m_table_sizes[counter] += s_min_table_sizes[counter];
}
MZ_CLEAR_OBJ(r->m_tables[2].m_code_size);
for (counter = 0; counter < r->m_table_sizes[2]; counter++)
{
mz_uint s;
TINFL_GET_BITS(14, s, 3);
r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s;
}
r->m_table_sizes[2] = 19;
}
for (; (int)r->m_type >= 0; r->m_type--)
{
int tree_next, tree_cur;
tinfl_huff_table *pTable;
mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16];
pTable = &r->m_tables[r->m_type];
MZ_CLEAR_OBJ(total_syms);
MZ_CLEAR_OBJ(pTable->m_look_up);
MZ_CLEAR_OBJ(pTable->m_tree);
for (i = 0; i < r->m_table_sizes[r->m_type]; ++i)
total_syms[pTable->m_code_size[i]]++;
used_syms = 0, total = 0;
next_code[0] = next_code[1] = 0;
for (i = 1; i <= 15; ++i)
{
used_syms += total_syms[i];
next_code[i + 1] = (total = ((total + total_syms[i]) << 1));
}
if ((65536 != total) && (used_syms > 1))
{
TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);
}
for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index)
{
mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index];
if (!code_size)
continue;
cur_code = next_code[code_size]++;
for (l = code_size; l > 0; l--, cur_code >>= 1)
rev_code = (rev_code << 1) | (cur_code & 1);
if (code_size <= TINFL_FAST_LOOKUP_BITS)
{
mz_int16 k = (mz_int16)((code_size << 9) | sym_index);
while (rev_code < TINFL_FAST_LOOKUP_SIZE)
{
pTable->m_look_up[rev_code] = k;
rev_code += (1 << code_size);
}
continue;
}
if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)]))
{
pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next;
tree_cur = tree_next;
tree_next -= 2;
}
rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);
for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--)
{
tree_cur -= ((rev_code >>= 1) & 1);
if (!pTable->m_tree[-tree_cur - 1])
{
pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next;
tree_cur = tree_next;
tree_next -= 2;
}
else
tree_cur = pTable->m_tree[-tree_cur - 1];
}
tree_cur -= ((rev_code >>= 1) & 1);
pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
}
if (r->m_type == 2)
{
for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);)
{
mz_uint s;
TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]);
if (dist < 16)
{
r->m_len_codes[counter++] = (mz_uint8)dist;
continue;
}
if ((dist == 16) && (!counter))
{
TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);
}
num_extra = "\02\03\07"[dist - 16];
TINFL_GET_BITS(18, s, num_extra);
s += "\03\03\013"[dist - 16];
TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s);
counter += s;
}
if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter)
{
TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);
}
TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]);
TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]);
}
}
for (;;)
{
mz_uint8 *pSrc;
for (;;)
{
if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2))
{
TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);
if (counter >= 256)
break;
while (pOut_buf_cur >= pOut_buf_end)
{
TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT);
}
*pOut_buf_cur++ = (mz_uint8)counter;
}
else
{
int sym2;
mz_uint code_len;
#if TINFL_USE_64BIT_BITBUF
if (num_bits < 30)
{
bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits);
pIn_buf_cur += 4;
num_bits += 32;
}
#else
if (num_bits < 15)
{
bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
pIn_buf_cur += 2;
num_bits += 16;
}
#endif
if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)
code_len = sym2 >> 9;
else
{
code_len = TINFL_FAST_LOOKUP_BITS;
do
{
sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
} while (sym2 < 0);
}
counter = sym2;
bit_buf >>= code_len;
num_bits -= code_len;
if (counter & 256)
break;
#if !TINFL_USE_64BIT_BITBUF
if (num_bits < 15)
{
bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
pIn_buf_cur += 2;
num_bits += 16;
}
#endif
if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)
code_len = sym2 >> 9;
else
{
code_len = TINFL_FAST_LOOKUP_BITS;
do
{
sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
} while (sym2 < 0);
}
bit_buf >>= code_len;
num_bits -= code_len;
pOut_buf_cur[0] = (mz_uint8)counter;
if (sym2 & 256)
{
pOut_buf_cur++;
counter = sym2;
break;
}
pOut_buf_cur[1] = (mz_uint8)sym2;
pOut_buf_cur += 2;
}
}
if ((counter &= 511) == 256)
break;
num_extra = s_length_extra[counter - 257];
counter = s_length_base[counter - 257];
if (num_extra)
{
mz_uint extra_bits;
TINFL_GET_BITS(25, extra_bits, num_extra);
counter += extra_bits;
}
TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);
num_extra = s_dist_extra[dist];
dist = s_dist_base[dist];
if (num_extra)
{
mz_uint extra_bits;
TINFL_GET_BITS(27, extra_bits, num_extra);
dist += extra_bits;
}
dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
{
TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);
}
pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask);
if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end)
{
while (counter--)
{
while (pOut_buf_cur >= pOut_buf_end)
{
TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT);
}
*pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask];
}
continue;
}
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
else if ((counter >= 9) && (counter <= dist))
{
const mz_uint8 *pSrc_end = pSrc + (counter & ~7);
do
{
((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0];
((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1];
pOut_buf_cur += 8;
} while ((pSrc += 8) < pSrc_end);
if ((counter &= 7) < 3)
{
if (counter)
{
pOut_buf_cur[0] = pSrc[0];
if (counter > 1)
pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur += counter;
}
continue;
}
}
#endif
do
{
pOut_buf_cur[0] = pSrc[0];
pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur[2] = pSrc[2];
pOut_buf_cur += 3;
pSrc += 3;
} while ((int)(counter -= 3) > 2);
if ((int)counter > 0)
{
pOut_buf_cur[0] = pSrc[0];
if ((int)counter > 1)
pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur += counter;
}
}
}
} while (!(r->m_final & 1));
/* Ensure byte alignment and put back any bytes from the bitbuf if we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */
/* I'm being super conservative here. A number of simplifications can be made to the byte alignment part, and the Adler32 check shouldn't ever need to worry about reading from the bitbuf now. */
TINFL_SKIP_BITS(32, num_bits & 7);
while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8))
{
--pIn_buf_cur;
num_bits -= 8;
}
bit_buf &= (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1);
MZ_ASSERT(!num_bits); /* if this assert fires then we've read beyond the end of non-deflate/zlib streams with following data (such as gzip streams). */
if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)
{
for (counter = 0; counter < 4; ++counter)
{
mz_uint s;
if (num_bits)
TINFL_GET_BITS(41, s, 8);
else
TINFL_GET_BYTE(42, s);
r->m_z_adler32 = (r->m_z_adler32 << 8) | s;
}
}
TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);
TINFL_CR_FINISH
common_exit:
/* As long as we aren't telling the caller that we NEED more input to make forward progress: */
/* Put back any bytes from the bitbuf in case we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */
/* We need to be very careful here to NOT push back any bytes we definitely know we need to make forward progress, though, or we'll lock the caller up into an inf loop. */
if ((status != TINFL_STATUS_NEEDS_MORE_INPUT) && (status != TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS))
{
while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8))
{
--pIn_buf_cur;
num_bits -= 8;
}
}
r->m_num_bits = num_bits;
r->m_bit_buf = bit_buf & (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1);
r->m_dist = dist;
r->m_counter = counter;
r->m_num_extra = num_extra;
r->m_dist_from_out_buf_start = dist_from_out_buf_start;
*pIn_buf_size = pIn_buf_cur - pIn_buf_next;
*pOut_buf_size = pOut_buf_cur - pOut_buf_next;
if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0))
{
const mz_uint8 *ptr = pOut_buf_next;
size_t buf_len = *pOut_buf_size;
mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16;
size_t block_len = buf_len % 5552;
while (buf_len)
{
for (i = 0; i + 7 < block_len; i += 8, ptr += 8)
{
s1 += ptr[0], s2 += s1;
s1 += ptr[1], s2 += s1;
s1 += ptr[2], s2 += s1;
s1 += ptr[3], s2 += s1;
s1 += ptr[4], s2 += s1;
s1 += ptr[5], s2 += s1;
s1 += ptr[6], s2 += s1;
s1 += ptr[7], s2 += s1;
}
for (; i < block_len; ++i)
s1 += *ptr++, s2 += s1;
s1 %= 65521U, s2 %= 65521U;
buf_len -= block_len;
block_len = 5552;
}
r->m_check_adler32 = (s2 << 16) + s1;
if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32))
status = TINFL_STATUS_ADLER32_MISMATCH;
}
return status;
}
/* Higher level helper functions. */
void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags)
{
tinfl_decompressor decomp;
void *pBuf = NULL, *pNew_buf;
size_t src_buf_ofs = 0, out_buf_capacity = 0;
*pOut_len = 0;
tinfl_init(&decomp);
for (;;)
{
size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;
tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size,
(flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT))
{
MZ_FREE(pBuf);
*pOut_len = 0;
return NULL;
}
src_buf_ofs += src_buf_size;
*pOut_len += dst_buf_size;
if (status == TINFL_STATUS_DONE)
break;
new_out_buf_capacity = out_buf_capacity * 2;
if (new_out_buf_capacity < 128)
new_out_buf_capacity = 128;
pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity);
if (!pNew_buf)
{
MZ_FREE(pBuf);
*pOut_len = 0;
return NULL;
}
pBuf = pNew_buf;
out_buf_capacity = new_out_buf_capacity;
}
return pBuf;
}
size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags)
{
tinfl_decompressor decomp;
tinfl_status status;
tinfl_init(&decomp);
status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len;
}
int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
{
int result = 0;
tinfl_decompressor decomp;
mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE);
size_t in_buf_ofs = 0, dict_ofs = 0;
if (!pDict)
return TINFL_STATUS_FAILED;
tinfl_init(&decomp);
for (;;)
{
size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
(flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));
in_buf_ofs += in_buf_size;
if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))
break;
if (status != TINFL_STATUS_HAS_MORE_OUTPUT)
{
result = (status == TINFL_STATUS_DONE);
break;
}
dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);
}
MZ_FREE(pDict);
*pIn_buf_size = in_buf_ofs;
return result;
}
tinfl_decompressor *tinfl_decompressor_alloc()
{
tinfl_decompressor *pDecomp = (tinfl_decompressor *)MZ_MALLOC(sizeof(tinfl_decompressor));
if (pDecomp)
tinfl_init(pDecomp);
return pDecomp;
}
void tinfl_decompressor_free(tinfl_decompressor *pDecomp)
{
MZ_FREE(pDecomp);
}

137
xs/src/miniz/miniz_tinfl.h Normal file
View file

@ -0,0 +1,137 @@
#pragma once
#include "miniz_common.h"
/* ------------------- Low-level Decompression API Definitions */
/* Decompression flags used by tinfl_decompress(). */
/* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. */
/* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. */
/* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). */
/* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. */
enum
{
TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
TINFL_FLAG_HAS_MORE_INPUT = 2,
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
TINFL_FLAG_COMPUTE_ADLER32 = 8
};
/* High level decompression functions: */
/* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). */
/* On entry: */
/* pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. */
/* On return: */
/* Function returns a pointer to the decompressed data, or NULL on failure. */
/* *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. */
/* The caller must call mz_free() on the returned block when it's no longer needed. */
void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
/* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. */
/* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. */
#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);
/* tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. */
/* Returns 1 on success or 0 on failure. */
typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser);
int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
struct tinfl_decompressor_tag;
typedef struct tinfl_decompressor_tag tinfl_decompressor;
/* Allocate the tinfl_decompressor structure in C so that */
/* non-C language bindings to tinfl_ API don't need to worry about */
/* structure size and allocation mechanism. */
tinfl_decompressor *tinfl_decompressor_alloc();
void tinfl_decompressor_free(tinfl_decompressor *pDecomp);
/* Max size of LZ dictionary. */
#define TINFL_LZ_DICT_SIZE 32768
/* Return status. */
typedef enum {
/* This flags indicates the inflator needs 1 or more input bytes to make forward progress, but the caller is indicating that no more are available. The compressed data */
/* is probably corrupted. If you call the inflator again with more bytes it'll try to continue processing the input but this is a BAD sign (either the data is corrupted or you called it incorrectly). */
/* If you call it again with no input you'll just get TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */
TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4,
/* This flag indicates that one or more of the input parameters was obviously bogus. (You can try calling it again, but if you get this error the calling code is wrong.) */
TINFL_STATUS_BAD_PARAM = -3,
/* This flags indicate the inflator is finished but the adler32 check of the uncompressed data didn't match. If you call it again it'll return TINFL_STATUS_DONE. */
TINFL_STATUS_ADLER32_MISMATCH = -2,
/* This flags indicate the inflator has somehow failed (bad code, corrupted input, etc.). If you call it again without resetting via tinfl_init() it it'll just keep on returning the same status failure code. */
TINFL_STATUS_FAILED = -1,
/* Any status code less than TINFL_STATUS_DONE must indicate a failure. */
/* This flag indicates the inflator has returned every byte of uncompressed data that it can, has consumed every byte that it needed, has successfully reached the end of the deflate stream, and */
/* if zlib headers and adler32 checking enabled that it has successfully checked the uncompressed data's adler32. If you call it again you'll just get TINFL_STATUS_DONE over and over again. */
TINFL_STATUS_DONE = 0,
/* This flag indicates the inflator MUST have more input data (even 1 byte) before it can make any more forward progress, or you need to clear the TINFL_FLAG_HAS_MORE_INPUT */
/* flag on the next call if you don't have any more source data. If the source data was somehow corrupted it's also possible (but unlikely) for the inflator to keep on demanding input to */
/* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */
TINFL_STATUS_NEEDS_MORE_INPUT = 1,
/* This flag indicates the inflator definitely has 1 or more bytes of uncompressed data available, but it cannot write this data into the output buffer. */
/* Note if the source compressed data was corrupted it's possible for the inflator to return a lot of uncompressed data to the caller. I've been assuming you know how much uncompressed data to expect */
/* (either exact or worst case) and will stop calling the inflator and fail after receiving too much. In pure streaming scenarios where you have no idea how many bytes to expect this may not be possible */
/* so I may need to add some code to address this. */
TINFL_STATUS_HAS_MORE_OUTPUT = 2
} tinfl_status;
/* Initializes the decompressor to its initial state. */
#define tinfl_init(r) \
do \
{ \
(r)->m_state = 0; \
} \
MZ_MACRO_END
#define tinfl_get_adler32(r) (r)->m_check_adler32
/* Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. */
/* This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. */
tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags);
/* Internal/private bits follow. */
enum
{
TINFL_MAX_HUFF_TABLES = 3,
TINFL_MAX_HUFF_SYMBOLS_0 = 288,
TINFL_MAX_HUFF_SYMBOLS_1 = 32,
TINFL_MAX_HUFF_SYMBOLS_2 = 19,
TINFL_FAST_LOOKUP_BITS = 10,
TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
};
typedef struct
{
mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
} tinfl_huff_table;
#if MINIZ_HAS_64BIT_REGISTERS
#define TINFL_USE_64BIT_BITBUF 1
#else
#define TINFL_USE_64BIT_BITBUF 0
#endif
#if TINFL_USE_64BIT_BITBUF
typedef mz_uint64 tinfl_bit_buf_t;
#define TINFL_BITBUF_SIZE (64)
#else
typedef mz_uint32 tinfl_bit_buf_t;
#define TINFL_BITBUF_SIZE (32)
#endif
struct tinfl_decompressor_tag
{
mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES];
tinfl_bit_buf_t m_bit_buf;
size_t m_dist_from_out_buf_start;
tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
};

4659
xs/src/miniz/miniz_zip.cpp Normal file

File diff suppressed because it is too large Load diff

429
xs/src/miniz/miniz_zip.h Normal file
View file

@ -0,0 +1,429 @@
#pragma once
#include "miniz.h"
/* ------------------- ZIP archive reading/writing */
#ifndef MINIZ_NO_ARCHIVE_APIS
enum
{
/* Note: These enums can be reduced as needed to save memory or stack space - they are pretty conservative. */
MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024,
MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 512,
MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 512
};
typedef struct
{
/* Central directory file index. */
mz_uint32 m_file_index;
/* Byte offset of this entry in the archive's central directory. Note we currently only support up to UINT_MAX or less bytes in the central dir. */
mz_uint64 m_central_dir_ofs;
/* These fields are copied directly from the zip's central dir. */
mz_uint16 m_version_made_by;
mz_uint16 m_version_needed;
mz_uint16 m_bit_flag;
mz_uint16 m_method;
#ifndef MINIZ_NO_TIME
MZ_TIME_T m_time;
#endif
/* CRC-32 of uncompressed data. */
mz_uint32 m_crc32;
/* File's compressed size. */
mz_uint64 m_comp_size;
/* File's uncompressed size. Note, I've seen some old archives where directory entries had 512 bytes for their uncompressed sizes, but when you try to unpack them you actually get 0 bytes. */
mz_uint64 m_uncomp_size;
/* Zip internal and external file attributes. */
mz_uint16 m_internal_attr;
mz_uint32 m_external_attr;
/* Entry's local header file offset in bytes. */
mz_uint64 m_local_header_ofs;
/* Size of comment in bytes. */
mz_uint32 m_comment_size;
/* MZ_TRUE if the entry appears to be a directory. */
mz_bool m_is_directory;
/* MZ_TRUE if the entry uses encryption/strong encryption (which miniz_zip doesn't support) */
mz_bool m_is_encrypted;
/* MZ_TRUE if the file is not encrypted, a patch file, and if it uses a compression method we support. */
mz_bool m_is_supported;
/* Filename. If string ends in '/' it's a subdirectory entry. */
/* Guaranteed to be zero terminated, may be truncated to fit. */
char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
/* Comment field. */
/* Guaranteed to be zero terminated, may be truncated to fit. */
char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
} mz_zip_archive_file_stat;
typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n);
typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n);
typedef mz_bool (*mz_file_needs_keepalive)(void *pOpaque);
struct mz_zip_internal_state_tag;
typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
typedef enum {
MZ_ZIP_MODE_INVALID = 0,
MZ_ZIP_MODE_READING = 1,
MZ_ZIP_MODE_WRITING = 2,
MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
} mz_zip_mode;
typedef enum {
MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100,
MZ_ZIP_FLAG_IGNORE_PATH = 0x0200,
MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400,
MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800,
MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG = 0x1000, /* if enabled, mz_zip_reader_locate_file() will be called on each file as its validated to ensure the func finds the file in the central dir (intended for testing) */
MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY = 0x2000, /* validate the local headers, but don't decompress the entire file and check the crc32 */
MZ_ZIP_FLAG_WRITE_ZIP64 = 0x4000, /* always use the zip64 file format, instead of the original zip file format with automatic switch to zip64. Use as flags parameter with mz_zip_writer_init*_v2 */
MZ_ZIP_FLAG_WRITE_ALLOW_READING = 0x8000,
MZ_ZIP_FLAG_ASCII_FILENAME = 0x10000
} mz_zip_flags;
typedef enum {
MZ_ZIP_TYPE_INVALID = 0,
MZ_ZIP_TYPE_USER,
MZ_ZIP_TYPE_MEMORY,
MZ_ZIP_TYPE_HEAP,
MZ_ZIP_TYPE_FILE,
MZ_ZIP_TYPE_CFILE,
MZ_ZIP_TOTAL_TYPES
} mz_zip_type;
/* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or modify this enum. */
typedef enum {
MZ_ZIP_NO_ERROR = 0,
MZ_ZIP_UNDEFINED_ERROR,
MZ_ZIP_TOO_MANY_FILES,
MZ_ZIP_FILE_TOO_LARGE,
MZ_ZIP_UNSUPPORTED_METHOD,
MZ_ZIP_UNSUPPORTED_ENCRYPTION,
MZ_ZIP_UNSUPPORTED_FEATURE,
MZ_ZIP_FAILED_FINDING_CENTRAL_DIR,
MZ_ZIP_NOT_AN_ARCHIVE,
MZ_ZIP_INVALID_HEADER_OR_CORRUPTED,
MZ_ZIP_UNSUPPORTED_MULTIDISK,
MZ_ZIP_DECOMPRESSION_FAILED,
MZ_ZIP_COMPRESSION_FAILED,
MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE,
MZ_ZIP_CRC_CHECK_FAILED,
MZ_ZIP_UNSUPPORTED_CDIR_SIZE,
MZ_ZIP_ALLOC_FAILED,
MZ_ZIP_FILE_OPEN_FAILED,
MZ_ZIP_FILE_CREATE_FAILED,
MZ_ZIP_FILE_WRITE_FAILED,
MZ_ZIP_FILE_READ_FAILED,
MZ_ZIP_FILE_CLOSE_FAILED,
MZ_ZIP_FILE_SEEK_FAILED,
MZ_ZIP_FILE_STAT_FAILED,
MZ_ZIP_INVALID_PARAMETER,
MZ_ZIP_INVALID_FILENAME,
MZ_ZIP_BUF_TOO_SMALL,
MZ_ZIP_INTERNAL_ERROR,
MZ_ZIP_FILE_NOT_FOUND,
MZ_ZIP_ARCHIVE_TOO_LARGE,
MZ_ZIP_VALIDATION_FAILED,
MZ_ZIP_WRITE_CALLBACK_FAILED,
MZ_ZIP_TOTAL_ERRORS
} mz_zip_error;
typedef struct
{
mz_uint64 m_archive_size;
mz_uint64 m_central_directory_file_ofs;
/* We only support up to UINT32_MAX files in zip64 mode. */
mz_uint32 m_total_files;
mz_zip_mode m_zip_mode;
mz_zip_type m_zip_type;
mz_zip_error m_last_error;
mz_uint64 m_file_offset_alignment;
mz_alloc_func m_pAlloc;
mz_free_func m_pFree;
mz_realloc_func m_pRealloc;
void *m_pAlloc_opaque;
mz_file_read_func m_pRead;
mz_file_write_func m_pWrite;
mz_file_needs_keepalive m_pNeeds_keepalive;
void *m_pIO_opaque;
mz_zip_internal_state *m_pState;
} mz_zip_archive;
typedef struct
{
mz_zip_archive *pZip;
mz_uint flags;
int status;
#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS
mz_uint file_crc32;
#endif
mz_uint64 read_buf_size, read_buf_ofs, read_buf_avail, comp_remaining, out_buf_ofs, cur_file_ofs;
mz_zip_archive_file_stat file_stat;
void *pRead_buf;
void *pWrite_buf;
size_t out_blk_remain;
tinfl_decompressor inflator;
} mz_zip_reader_extract_iter_state;
/* -------- ZIP reading */
/* Inits a ZIP archive reader. */
/* These functions read and validate the archive's central directory. */
mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags);
mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags);
#ifndef MINIZ_NO_STDIO
/* Read a archive from a disk file. */
/* file_start_ofs is the file offset where the archive actually begins, or 0. */
/* actual_archive_size is the true total size of the archive, which may be smaller than the file's actual size on disk. If zero the entire file is treated as the archive. */
mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags);
mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size);
/* Read an archive from an already opened FILE, beginning at the current file position. */
/* The archive is assumed to be archive_size bytes long. If archive_size is < 0, then the entire rest of the file is assumed to contain the archive. */
/* The FILE will NOT be closed when mz_zip_reader_end() is called. */
mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags);
#endif
/* Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. */
mz_bool mz_zip_reader_end(mz_zip_archive *pZip);
/* -------- ZIP reading or writing */
/* Clears a mz_zip_archive struct to all zeros. */
/* Important: This must be done before passing the struct to any mz_zip functions. */
void mz_zip_zero_struct(mz_zip_archive *pZip);
mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip);
mz_zip_type mz_zip_get_type(mz_zip_archive *pZip);
/* Returns the total number of files in the archive. */
mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip);
mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip);
mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip);
MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip);
/* Reads n bytes of raw archive data, starting at file offset file_ofs, to pBuf. */
size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n);
/* Attempts to locates a file in the archive's central directory. */
/* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */
/* Returns -1 if the file cannot be found. */
int mz_zip_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags);
/* Returns MZ_FALSE if the file cannot be found. */
mz_bool mz_zip_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *pIndex);
/* All mz_zip funcs set the m_last_error field in the mz_zip_archive struct. These functions retrieve/manipulate this field. */
/* Note that the m_last_error functionality is not thread safe. */
mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num);
mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip);
mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip);
mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip);
const char *mz_zip_get_error_string(mz_zip_error mz_err);
/* MZ_TRUE if the archive file entry is a directory entry. */
mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index);
/* MZ_TRUE if the file is encrypted/strong encrypted. */
mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index);
/* MZ_TRUE if the compression method is supported, and the file is not encrypted, and the file is not a compressed patch file. */
mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index);
/* Retrieves the filename of an archive file entry. */
/* Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. */
mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size);
/* Attempts to locates a file in the archive's central directory. */
/* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */
/* Returns -1 if the file cannot be found. */
int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags);
int mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *file_index);
/* Returns detailed information about an archive file entry. */
mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat);
/* MZ_TRUE if the file is in zip64 format. */
/* A file is considered zip64 if it contained a zip64 end of central directory marker, or if it contained any zip64 extended file information fields in the central directory. */
mz_bool mz_zip_is_zip64(mz_zip_archive *pZip);
/* Returns the total central directory size in bytes. */
/* The current max supported size is <= MZ_UINT32_MAX. */
size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip);
/* Extracts a archive file to a memory buffer using no memory allocation. */
/* There must be at least enough room on the stack to store the inflator's state (~34KB or so). */
mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
/* Extracts a archive file to a memory buffer. */
mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags);
/* Extracts a archive file to a dynamically allocated heap buffer. */
/* The memory will be allocated via the mz_zip_archive's alloc/realloc functions. */
/* Returns NULL and sets the last error on failure. */
void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags);
void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags);
/* Extracts a archive file using a callback function to output the file's data. */
mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags);
/* Extract a file iteratively */
mz_zip_reader_extract_iter_state* mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags);
mz_zip_reader_extract_iter_state* mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags);
size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state* pState, void* pvBuf, size_t buf_size);
mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState);
#ifndef MINIZ_NO_STDIO
/* Extracts a archive file to a disk file and sets its last accessed and modified times. */
/* This function only extracts files, not archive directory records. */
mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags);
/* Extracts a archive file starting at the current position in the destination FILE stream. */
mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *File, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags);
#endif
#if 0
/* TODO */
typedef void *mz_zip_streaming_extract_state_ptr;
mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags);
uint64_t mz_zip_streaming_extract_get_size(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState);
uint64_t mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState);
mz_bool mz_zip_streaming_extract_seek(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, uint64_t new_ofs);
size_t mz_zip_streaming_extract_read(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, void *pBuf, size_t buf_size);
mz_bool mz_zip_streaming_extract_end(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState);
#endif
/* This function compares the archive's local headers, the optional local zip64 extended information block, and the optional descriptor following the compressed data vs. the data in the central directory. */
/* It also validates that each file can be successfully uncompressed unless the MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY is specified. */
mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags);
/* Validates an entire archive by calling mz_zip_validate_file() on each file. */
mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags);
/* Misc utils/helpers, valid for ZIP reading or writing */
mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr);
mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr);
/* Universal end function - calls either mz_zip_reader_end() or mz_zip_writer_end(). */
mz_bool mz_zip_end(mz_zip_archive *pZip);
/* -------- ZIP writing */
#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
/* Inits a ZIP archive writer. */
/*Set pZip->m_pWrite (and pZip->m_pIO_opaque) before calling mz_zip_writer_init or mz_zip_writer_init_v2*/
/*The output is streamable, i.e. file_ofs in mz_file_write_func always increases only by n*/
mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size);
mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags);
mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size);
mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags);
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning);
mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags);
mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags);
#endif
/* Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. */
/* For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. */
/* For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). */
/* Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. */
/* Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before */
/* the archive is finalized the file's central directory will be hosed. */
mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename);
mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags);
/* Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. */
/* To add a directory entry, call this method with an archive name ending in a forwardslash with an empty buffer. */
/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */
mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags);
/* Like mz_zip_writer_add_mem(), except you can specify a file comment field, and optionally supply the function with already compressed data. */
/* uncomp_size/uncomp_crc32 are only used if the MZ_ZIP_FLAG_COMPRESSED_DATA flag is specified. */
mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags,
mz_uint64 uncomp_size, mz_uint32 uncomp_crc32);
mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags,
mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, const char *user_extra_data_local, mz_uint user_extra_data_local_len,
const char *user_extra_data_central, mz_uint user_extra_data_central_len);
#ifndef MINIZ_NO_STDIO
/* Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. */
/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */
mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
/* Like mz_zip_writer_add_file(), except the file data is read from the specified FILE stream. */
mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 size_to_add,
const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len,
const char *user_extra_data_central, mz_uint user_extra_data_central_len);
#endif
/* Adds a file to an archive by fully cloning the data from another archive. */
/* This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data (it may add or modify the zip64 local header extra data field), and the optional descriptor following the compressed data. */
mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index);
/* Finalizes the archive by writing the central directory records followed by the end of central directory record. */
/* After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). */
/* An archive must be manually finalized by calling this function for it to be valid. */
mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip);
/* Finalizes a heap archive, returning a poiner to the heap block and its size. */
/* The heap block will be allocated using the mz_zip_archive's alloc/realloc callbacks. */
mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize);
/* Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. */
/* Note for the archive to be valid, it *must* have been finalized before ending (this function will not do it for you). */
mz_bool mz_zip_writer_end(mz_zip_archive *pZip);
/* -------- Misc. high-level helper functions: */
/* mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. */
/* Note this is NOT a fully safe operation. If it crashes or dies in some way your archive can be left in a screwed up state (without a central directory). */
/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */
/* TODO: Perhaps add an option to leave the existing central dir in place in case the add dies? We could then truncate the file (so the old central dir would be at the end) if something goes wrong. */
mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr);
/* Reads a single file from an archive into a heap block. */
/* If pComment is not NULL, only the file with the specified comment will be extracted. */
/* Returns NULL on failure. */
void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags);
void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr);
#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */
#endif /* MINIZ_NO_ARCHIVE_APIS */

View file

@ -15,6 +15,7 @@ REGISTER_CLASS(Filler, "Filler");
REGISTER_CLASS(Flow, "Flow");
REGISTER_CLASS(CoolingBuffer, "GCode::CoolingBuffer");
REGISTER_CLASS(GCode, "GCode");
REGISTER_CLASS(GCodePreviewData, "GCode::PreviewData");
REGISTER_CLASS(GCodeSender, "GCode::Sender");
REGISTER_CLASS(Layer, "Layer");
REGISTER_CLASS(SupportLayer, "Layer::Support");
@ -62,6 +63,7 @@ REGISTER_CLASS(Preset, "GUI::Preset");
REGISTER_CLASS(PresetCollection, "GUI::PresetCollection");
REGISTER_CLASS(PresetBundle, "GUI::PresetBundle");
REGISTER_CLASS(PresetHints, "GUI::PresetHints");
REGISTER_CLASS(TabIface, "GUI::Tab");
SV* ConfigBase__as_hash(ConfigBase* THIS)
{

189
xs/src/slic3r/GUI/2DBed.cpp Normal file
View file

@ -0,0 +1,189 @@
#include "2DBed.hpp";
#include <wx/dcbuffer.h>
#include "BoundingBox.hpp"
#include "Geometry.hpp"
#include "ClipperUtils.hpp"
namespace Slic3r {
namespace GUI {
void Bed_2D::repaint()
{
wxAutoBufferedPaintDC dc(this);
auto cw = GetSize().GetWidth();
auto ch = GetSize().GetHeight();
// when canvas is not rendered yet, size is 0, 0
if (cw == 0) return ;
if (m_user_drawn_background) {
// On all systems the AutoBufferedPaintDC() achieves double buffering.
// On MacOS the background is erased, on Windows the background is not erased
// and on Linux / GTK the background is erased to gray color.
// Fill DC with the background on Windows & Linux / GTK.
auto color = wxSystemSettings::GetColour(wxSYS_COLOUR_3DLIGHT); //GetSystemColour
dc.SetPen(*new wxPen(color, 1, wxPENSTYLE_SOLID));
dc.SetBrush(*new wxBrush(color, wxBRUSHSTYLE_SOLID));
auto rect = GetUpdateRegion().GetBox();
dc.DrawRectangle(rect.GetLeft(), rect.GetTop(), rect.GetWidth(), rect.GetHeight());
}
// turn cw and ch from sizes to max coordinates
cw--;
ch--;
auto cbb = BoundingBoxf(Pointf(0, 0),Pointf(cw, ch));
// leave space for origin point
cbb.min.translate(4, 0);
cbb.max.translate(-4, -4);
// leave space for origin label
cbb.max.translate(0, -13);
// read new size
cw = cbb.size().x;
ch = cbb.size().y;
auto ccenter = cbb.center();
// get bounding box of bed shape in G - code coordinates
auto bed_shape = m_bed_shape;
auto bed_polygon = Polygon::new_scale(m_bed_shape);
auto bb = BoundingBoxf(m_bed_shape);
bb.merge(Pointf(0, 0)); // origin needs to be in the visible area
auto bw = bb.size().x;
auto bh = bb.size().y;
auto bcenter = bb.center();
// calculate the scaling factor for fitting bed shape in canvas area
auto sfactor = std::min(cw/bw, ch/bh);
auto shift = Pointf(
ccenter.x - bcenter.x * sfactor,
ccenter.y - bcenter.y * sfactor
);
m_scale_factor = sfactor;
m_shift = Pointf(shift.x + cbb.min.x,
shift.y - (cbb.max.y - GetSize().GetHeight()));
// draw bed fill
dc.SetBrush(*new wxBrush(*new wxColour(255, 255, 255), wxSOLID));
wxPointList pt_list;
for (auto pt: m_bed_shape)
{
Point pt_pix = to_pixels(pt);
pt_list.push_back(new wxPoint(pt_pix.x, pt_pix.y));
}
dc.DrawPolygon(&pt_list, 0, 0);
// draw grid
auto step = 10; // 1cm grid
Polylines polylines;
for (auto x = bb.min.x - fmod(bb.min.x, step) + step; x < bb.max.x; x += step) {
Polyline pl = Polyline::new_scale({ Pointf(x, bb.min.y), Pointf(x, bb.max.y) });
polylines.push_back(pl);
}
for (auto y = bb.min.y - fmod(bb.min.y, step) + step; y < bb.max.y; y += step) {
polylines.push_back(Polyline::new_scale({ Pointf(bb.min.x, y), Pointf(bb.max.x, y) }));
}
polylines = intersection_pl(polylines, bed_polygon);
dc.SetPen(*new wxPen(*new wxColour(230, 230, 230), 1, wxSOLID));
for (auto pl : polylines)
{
for (size_t i = 0; i < pl.points.size()-1; i++){
Point pt1 = to_pixels(Pointf::new_unscale(pl.points[i]));
Point pt2 = to_pixels(Pointf::new_unscale(pl.points[i+1]));
dc.DrawLine(pt1.x, pt1.y, pt2.x, pt2.y);
}
}
// draw bed contour
dc.SetPen(*new wxPen(*new wxColour(0, 0, 0), 1, wxSOLID));
dc.SetBrush(*new wxBrush(*new wxColour(0, 0, 0), wxTRANSPARENT));
dc.DrawPolygon(&pt_list, 0, 0);
auto origin_px = to_pixels(Pointf(0, 0));
// draw axes
auto axes_len = 50;
auto arrow_len = 6;
auto arrow_angle = Geometry::deg2rad(45.0);
dc.SetPen(*new wxPen(*new wxColour(255, 0, 0), 2, wxSOLID)); // red
auto x_end = Pointf(origin_px.x + axes_len, origin_px.y);
dc.DrawLine(wxPoint(origin_px.x, origin_px.y), wxPoint(x_end.x, x_end.y));
for (auto angle : { -arrow_angle, arrow_angle }){
auto end = x_end;
end.translate(-arrow_len, 0);
end.rotate(angle, x_end);
dc.DrawLine(wxPoint(x_end.x, x_end.y), wxPoint(end.x, end.y));
}
dc.SetPen(*new wxPen(*new wxColour(0, 255, 0), 2, wxSOLID)); // green
auto y_end = Pointf(origin_px.x, origin_px.y - axes_len);
dc.DrawLine(wxPoint(origin_px.x, origin_px.y), wxPoint(y_end.x, y_end.y));
for (auto angle : { -arrow_angle, arrow_angle }) {
auto end = y_end;
end.translate(0, +arrow_len);
end.rotate(angle, y_end);
dc.DrawLine(wxPoint(y_end.x, y_end.y), wxPoint(end.x, end.y));
}
// draw origin
dc.SetPen(*new wxPen(*new wxColour(0, 0, 0), 1, wxSOLID));
dc.SetBrush(*new wxBrush(*new wxColour(0, 0, 0), wxSOLID));
dc.DrawCircle(origin_px.x, origin_px.y, 3);
dc.SetTextForeground(*new wxColour(0, 0, 0));
dc.SetFont(*new wxFont(10, wxDEFAULT, wxNORMAL, wxNORMAL));
dc.DrawText("(0,0)", origin_px.x + 1, origin_px.y + 2);
// draw current position
if (m_pos!= Pointf(0, 0)) {
auto pos_px = to_pixels(m_pos);
dc.SetPen(*new wxPen(*new wxColour(200, 0, 0), 2, wxSOLID));
dc.SetBrush(*new wxBrush(*new wxColour(200, 0, 0), wxTRANSPARENT));
dc.DrawCircle(pos_px.x, pos_px.y, 5);
dc.DrawLine(pos_px.x - 15, pos_px.y, pos_px.x + 15, pos_px.y);
dc.DrawLine(pos_px.x, pos_px.y - 15, pos_px.x, pos_px.y + 15);
}
m_painted = true;
}
// convert G - code coordinates into pixels
Point Bed_2D::to_pixels(Pointf point){
auto p = Pointf(point);
p.scale(m_scale_factor);
p.translate(m_shift);
return Point(p.x, GetSize().GetHeight() - p.y);
}
void Bed_2D::mouse_event(wxMouseEvent event){
if (!m_interactive) return;
if (!m_painted) return;
auto pos = event.GetPosition();
auto point = to_units(Point(pos.x, pos.y));
if (event.LeftDown() || event.Dragging()) {
if (m_on_move)
m_on_move(point) ;
Refresh();
}
}
// convert pixels into G - code coordinates
Pointf Bed_2D::to_units(Point point){
auto p = Pointf(point.x, GetSize().GetHeight() - point.y);
p.translate(m_shift.negative());
p.scale(1 / m_scale_factor);
return p;
}
void Bed_2D::set_pos(Pointf pos){
m_pos = pos;
Refresh();
}
} // GUI
} // Slic3r

View file

@ -0,0 +1,45 @@
#include <wx/wx.h>
#include "Config.hpp"
namespace Slic3r {
namespace GUI {
class Bed_2D : public wxPanel
{
bool m_user_drawn_background = false;
bool m_painted = false;
bool m_interactive = false;
double m_scale_factor;
Pointf m_shift;
Pointf m_pos;
std::function<void(Pointf)> m_on_move = nullptr;
Point to_pixels(Pointf point);
Pointf to_units(Point point);
void repaint();
void mouse_event(wxMouseEvent event);
void set_pos(Pointf pos);
public:
Bed_2D(wxWindow* parent)
{
Create(parent, wxID_ANY, wxDefaultPosition, wxSize(250, -1), wxTAB_TRAVERSAL);
// m_user_drawn_background = $^O ne 'darwin';
m_user_drawn_background = true;
Bind(wxEVT_PAINT, ([this](wxPaintEvent e) { repaint(); }));
// EVT_ERASE_BACKGROUND($self, sub{}) if $self->{user_drawn_background};
// Bind(EVT_MOUSE_EVENTS, ([this](wxMouseEvent event){/*mouse_event()*/; }));
Bind(wxEVT_LEFT_DOWN, ([this](wxMouseEvent event){ mouse_event(event); }));
Bind(wxEVT_MOTION, ([this](wxMouseEvent event){ mouse_event(event); }));
Bind(wxEVT_SIZE, ([this](wxSizeEvent e) { Refresh(); }));
}
~Bed_2D(){}
std::vector<Pointf> m_bed_shape;
};
} // GUI
} // Slic3r

File diff suppressed because it is too large Load diff

View file

@ -7,12 +7,15 @@
#include "../../libslic3r/TriangleMesh.hpp"
#include "../../libslic3r/Utils.hpp"
class wxBitmap;
namespace Slic3r {
class Print;
class PrintObject;
class Model;
class ModelObject;
class GCodePreviewData;
// A container for interleaved arrays of 3D vertices and normals,
// possibly indexed by triangles and / or quads.
@ -106,6 +109,10 @@ public:
push_geometry(float(x), float(y), float(z), float(nx), float(ny), float(nz));
}
inline void push_geometry(const Pointf3& p, const Vectorf3& n) {
push_geometry(p.x, p.y, p.z, n.x, n.y, n.z);
}
inline void push_triangle(int idx1, int idx2, int idx3) {
if (this->triangle_indices.size() + 3 > this->vertices_and_normals_interleaved.capacity())
this->triangle_indices.reserve(next_highest_power_of_2(this->triangle_indices.size() + 3));
@ -207,6 +214,8 @@ public:
select_group_id(-1),
drag_group_id(-1),
selected(false),
is_active(true),
zoom_to_volumes(true),
hover(false),
tverts_range(0, size_t(-1)),
qverts_range(0, size_t(-1))
@ -243,6 +252,10 @@ public:
int drag_group_id;
// Is this object selected?
bool selected;
// Whether or not this volume is active for rendering
bool is_active;
// Whether or not to use this volume when applying zoom_to_volumes()
bool zoom_to_volumes;
// Boolean: Is mouse over this object?
bool hover;
@ -258,6 +271,7 @@ public:
// Offset into qverts & tverts, or offsets into indices stored into an OpenGL name_index_buffer.
std::vector<size_t> offsets;
int object_idx() const { return this->composite_id / 1000000; }
int volume_idx() const { return (this->composite_id / 1000) % 1000; }
int instance_idx() const { return this->composite_id % 1000; }
@ -299,6 +313,28 @@ public:
class GLVolumeCollection
{
public:
struct RenderInterleavedOnlyVolumes
{
bool enabled;
float alpha; // [0..1]
RenderInterleavedOnlyVolumes()
: enabled(false)
, alpha(0.0f)
{
}
RenderInterleavedOnlyVolumes(bool enabled, float alpha)
: enabled(enabled)
, alpha(alpha)
{
}
};
private:
RenderInterleavedOnlyVolumes _render_interleaved_only_volumes;
public:
std::vector<GLVolume*> volumes;
@ -334,6 +370,8 @@ public:
bool empty() const { return volumes.empty(); }
void set_range(double low, double high) { for (GLVolume *vol : this->volumes) vol->set_range(low, high); }
void set_render_interleaved_only_volumes(const RenderInterleavedOnlyVolumes& render_interleaved_only_volumes) { _render_interleaved_only_volumes = render_interleaved_only_volumes; }
private:
GLVolumeCollection(const GLVolumeCollection &other);
GLVolumeCollection& operator=(const GLVolumeCollection &);
@ -341,9 +379,86 @@ private:
class _3DScene
{
struct GCodePreviewVolumeIndex
{
enum EType
{
Extrusion,
Travel,
Retraction,
Unretraction,
Shell,
Num_Geometry_Types
};
struct FirstVolume
{
EType type;
unsigned int flag;
// Index of the first volume in a GLVolumeCollection.
unsigned int id;
FirstVolume(EType type, unsigned int flag, unsigned int id) : type(type), flag(flag), id(id) {}
};
std::vector<FirstVolume> first_volumes;
void reset() { first_volumes.clear(); }
};
static GCodePreviewVolumeIndex s_gcode_preview_volume_index;
class LegendTexture
{
static const unsigned int Px_Title_Offset = 5;
static const unsigned int Px_Text_Offset = 5;
static const unsigned int Px_Square = 20;
static const unsigned int Px_Square_Contour = 1;
static const unsigned int Px_Border = Px_Square / 2;
static const unsigned char Squares_Border_Color[3];
static const unsigned char Background_Color[3];
static const unsigned char Opacity;
unsigned int m_tex_id;
unsigned int m_tex_width;
unsigned int m_tex_height;
public:
LegendTexture() : m_tex_id(0), m_tex_width(0), m_tex_height(0) {}
~LegendTexture() { _destroy_texture(); }
// Generate a texture data, but don't load it into the GPU yet, as the glcontext may not be valid yet.
bool generate(const GCodePreviewData& preview_data, const std::vector<float>& tool_colors);
// If not loaded, load the texture data into the GPU. Return a texture ID or 0 if the texture has zero size.
unsigned int finalize();
unsigned int get_texture_id() const { return m_tex_id; }
unsigned int get_texture_width() const { return m_tex_width; }
unsigned int get_texture_height() const { return m_tex_height; }
void reset_texture() { _destroy_texture(); }
private:
bool _create_texture(const GCodePreviewData& preview_data, const wxBitmap& bitmap);
void _destroy_texture();
// generate() fills in m_data with the pixels, while finalize() moves the data to the GPU before rendering.
std::vector<unsigned char> m_data;
};
static LegendTexture s_legend_texture;
public:
static void _glew_init();
static void load_gcode_preview(const Print* print, const GCodePreviewData* preview_data, GLVolumeCollection* volumes, const std::vector<std::string>& str_tool_colors, bool use_VBOs);
static unsigned int get_legend_texture_id();
static unsigned int get_legend_texture_width();
static unsigned int get_legend_texture_height();
static void reset_legend_texture();
static unsigned int finalize_legend_texture();
static void _load_print_toolpaths(
const Print *print,
GLVolumeCollection *volumes,
@ -356,12 +471,30 @@ public:
const std::vector<std::string> &tool_colors,
bool use_VBOs);
static void _load_wipe_tower_toolpaths(
const Print *print,
GLVolumeCollection *volumes,
const std::vector<std::string> &tool_colors_str,
bool use_VBOs);
private:
// generates gcode extrusion paths geometry
static void _load_gcode_extrusion_paths(const GCodePreviewData& preview_data, GLVolumeCollection& volumes, const std::vector<float>& tool_colors, bool use_VBOs);
// generates gcode travel paths geometry
static void _load_gcode_travel_paths(const GCodePreviewData& preview_data, GLVolumeCollection& volumes, const std::vector<float>& tool_colors, bool use_VBOs);
static bool _travel_paths_by_type(const GCodePreviewData& preview_data, GLVolumeCollection& volumes);
static bool _travel_paths_by_feedrate(const GCodePreviewData& preview_data, GLVolumeCollection& volumes);
static bool _travel_paths_by_tool(const GCodePreviewData& preview_data, GLVolumeCollection& volumes, const std::vector<float>& tool_colors);
// generates gcode retractions geometry
static void _load_gcode_retractions(const GCodePreviewData& preview_data, GLVolumeCollection& volumes, bool use_VBOs);
// generates gcode unretractions geometry
static void _load_gcode_unretractions(const GCodePreviewData& preview_data, GLVolumeCollection& volumes, bool use_VBOs);
// sets gcode geometry visibility according to user selection
static void _update_gcode_volumes_visibility(const GCodePreviewData& preview_data, GLVolumeCollection& volumes);
// generates the legend texture in dependence of the current shown view type
static void _generate_legend_texture(const GCodePreviewData& preview_data, const std::vector<float>& tool_colors);
// generates objects and wipe tower geometry
static void _load_shells(const Print& print, GLVolumeCollection& volumes, bool use_VBOs);
};
}

View file

@ -29,7 +29,7 @@ void AppConfig::set_defaults()
{
// Reset the empty fields to defaults.
if (get("autocenter").empty())
set("autocenter", "1");
set("autocenter", "0");
// Disable background processing by default as it is not stable.
if (get("background_processing").empty())
set("background_processing", "0");

View file

@ -0,0 +1,341 @@
#include "BedShapeDialog.hpp"
#include <wx/sizer.h>
#include <wx/statbox.h>
#include <wx/wx.h>
#include "Polygon.hpp"
#include "BoundingBox.hpp"
#include <wx/numformatter.h>
#include "Model.hpp"
#include "boost/nowide/iostream.hpp"
namespace Slic3r {
namespace GUI {
void BedShapeDialog::build_dialog(ConfigOptionPoints* default_pt)
{
m_panel = new BedShapePanel(this);
m_panel->build_panel(default_pt);
auto main_sizer = new wxBoxSizer(wxVERTICAL);
main_sizer->Add(m_panel, 1, wxEXPAND);
main_sizer->Add(CreateButtonSizer(wxOK | wxCANCEL), 0, wxALIGN_CENTER_HORIZONTAL | wxBOTTOM, 10);
SetSizer(main_sizer);
SetMinSize(GetSize());
main_sizer->SetSizeHints(this);
// needed to actually free memory
this->Bind(wxEVT_CLOSE_WINDOW, ([this](wxCloseEvent e){
EndModal(wxID_OK);
Destroy();
}));
}
void BedShapePanel::build_panel(ConfigOptionPoints* default_pt)
{
// on_change(nullptr);
auto box = new wxStaticBox(this, wxID_ANY, _L("Shape"));
auto sbsizer = new wxStaticBoxSizer(box, wxVERTICAL);
// shape options
m_shape_options_book = new wxChoicebook(this, wxID_ANY, wxDefaultPosition, wxSize(300, -1), wxCHB_TOP);
sbsizer->Add(m_shape_options_book);
auto optgroup = init_shape_options_page(_L("Rectangular"));
ConfigOptionDef def;
def.type = coPoints;
def.default_value = new ConfigOptionPoints{ Pointf(200, 200) };
def.label = _LU8("Size");
def.tooltip = _LU8("Size in X and Y of the rectangular plate.");
Option option(def, "rect_size");
optgroup->append_single_option_line(option);
def.type = coPoints;
def.default_value = new ConfigOptionPoints{ Pointf(0, 0) };
def.label = _LU8("Origin");
def.tooltip = _LU8("Distance of the 0,0 G-code coordinate from the front left corner of the rectangle.");
option = Option(def, "rect_origin");
optgroup->append_single_option_line(option);
optgroup = init_shape_options_page(_L("Circular"));
def.type = coFloat;
def.default_value = new ConfigOptionFloat(200);
def.sidetext = _LU8("mm");
def.label = _LU8("Diameter");
def.tooltip = _LU8("Diameter of the print bed. It is assumed that origin (0,0) is located in the center.");
option = Option(def, "diameter");
optgroup->append_single_option_line(option);
optgroup = init_shape_options_page(_L("Custom"));
Line line{ "", "" };
line.full_width = 1;
line.widget = [this](wxWindow* parent) {
auto btn = new wxButton(parent, wxID_ANY, _L("Load shape from STL..."), wxDefaultPosition, wxDefaultSize);
auto sizer = new wxBoxSizer(wxHORIZONTAL);
sizer->Add(btn);
btn->Bind(wxEVT_BUTTON, ([this](wxCommandEvent e)
{
load_stl();
}));
return sizer;
};
optgroup->append_line(line);
Bind(wxEVT_CHOICEBOOK_PAGE_CHANGED, ([this](wxCommandEvent e)
{
update_shape();
}));
// right pane with preview canvas
m_canvas = new Bed_2D(this);
m_canvas->m_bed_shape = default_pt->values;
// main sizer
auto top_sizer = new wxBoxSizer(wxHORIZONTAL);
top_sizer->Add(sbsizer, 0, wxEXPAND | wxLeft | wxTOP | wxBOTTOM, 10);
if (m_canvas)
top_sizer->Add(m_canvas, 1, wxEXPAND | wxALL, 10) ;
SetSizerAndFit(top_sizer);
set_shape(default_pt);
update_preview();
}
#define SHAPE_RECTANGULAR 0
#define SHAPE_CIRCULAR 1
#define SHAPE_CUSTOM 2
// Called from the constructor.
// Create a panel for a rectangular / circular / custom bed shape.
ConfigOptionsGroupShp BedShapePanel::init_shape_options_page(wxString title){
auto panel = new wxPanel(m_shape_options_book);
ConfigOptionsGroupShp optgroup;
optgroup = std::make_shared<ConfigOptionsGroup>(panel, _L("Settings"));
optgroup->label_width = 100;
optgroup->m_on_change = [this](t_config_option_key opt_key, boost::any value){
update_shape();
};
m_optgroups.push_back(optgroup);
panel->SetSizerAndFit(optgroup->sizer);
m_shape_options_book->AddPage(panel, title);
return optgroup;
}
// Called from the constructor.
// Set the initial bed shape from a list of points.
// Deduce the bed shape type(rect, circle, custom)
// This routine shall be smart enough if the user messes up
// with the list of points in the ini file directly.
void BedShapePanel::set_shape(ConfigOptionPoints* points)
{
auto polygon = Polygon::new_scale(points->values);
// is this a rectangle ?
if (points->size() == 4) {
auto lines = polygon.lines();
if (lines[0].parallel_to(lines[2]) && lines[1].parallel_to(lines[3])) {
// okay, it's a rectangle
// find origin
// the || 0 hack prevents "-0" which might confuse the user
int x_min, x_max, y_min, y_max;
x_max = x_min = points->values[0].x;
y_max = y_min = points->values[0].y;
for (auto pt : points->values){
if (x_min > pt.x) x_min = pt.x;
if (x_max < pt.x) x_max = pt.x;
if (y_min > pt.y) y_min = pt.y;
if (y_max < pt.y) y_max = pt.y;
}
if (x_min < 0) x_min = 0;
if (x_max < 0) x_max = 0;
if (y_min < 0) y_min = 0;
if (y_max < 0) y_max = 0;
auto origin = new ConfigOptionPoints{ Pointf(-x_min, -y_min) };
m_shape_options_book->SetSelection(SHAPE_RECTANGULAR);
auto optgroup = m_optgroups[SHAPE_RECTANGULAR];
optgroup->set_value("rect_size", new ConfigOptionPoints{ Pointf(x_max - x_min, y_max - y_min) });//[x_max - x_min, y_max - y_min]);
optgroup->set_value("rect_origin", origin);
update_shape();
return;
}
}
// is this a circle ?
{
// Analyze the array of points.Do they reside on a circle ?
auto center = polygon.bounding_box().center();
std::vector<double> vertex_distances;
double avg_dist = 0;
for (auto pt: polygon.points)
{
double distance = center.distance_to(pt);
vertex_distances.push_back(distance);
avg_dist += distance;
}
bool defined_value = true;
for (auto el: vertex_distances)
{
if (abs(el - avg_dist) > 10 * SCALED_EPSILON)
defined_value = false;
break;
}
if (defined_value) {
// all vertices are equidistant to center
m_shape_options_book->SetSelection(SHAPE_CIRCULAR);
auto optgroup = m_optgroups[SHAPE_CIRCULAR];
boost::any ret = wxNumberFormatter::ToString(unscale(avg_dist * 2), 0);
optgroup->set_value("diameter", ret);
update_shape();
return;
}
}
if (points->size() < 3) {
// Invalid polygon.Revert to default bed dimensions.
m_shape_options_book->SetSelection(SHAPE_RECTANGULAR);
auto optgroup = m_optgroups[SHAPE_RECTANGULAR];
optgroup->set_value("rect_size", new ConfigOptionPoints{ Pointf(200, 200) });
optgroup->set_value("rect_origin", new ConfigOptionPoints{ Pointf(0, 0) });
update_shape();
return;
}
// This is a custom bed shape, use the polygon provided.
m_shape_options_book->SetSelection(SHAPE_CUSTOM);
// Copy the polygon to the canvas, make a copy of the array.
m_canvas->m_bed_shape = points->values;
update_shape();
}
void BedShapePanel::update_preview()
{
if (m_canvas) m_canvas->Refresh();
Refresh();
}
// Update the bed shape from the dialog fields.
void BedShapePanel::update_shape()
{
auto page_idx = m_shape_options_book->GetSelection();
if (page_idx == SHAPE_RECTANGULAR) {
Pointf rect_size, rect_origin;
try{
rect_size = boost::any_cast<Pointf>(m_optgroups[SHAPE_RECTANGULAR]->get_value("rect_size")); }
catch (const std::exception &e){
return;}
try{
rect_origin = boost::any_cast<Pointf>(m_optgroups[SHAPE_RECTANGULAR]->get_value("rect_origin"));
}
catch (const std::exception &e){
return;}
auto x = rect_size.x;
auto y = rect_size.y;
// empty strings or '-' or other things
if (x == 0 || y == 0) return;
double x0 = 0.0;
double y0 = 0.0;
double x1 = x;
double y1 = y;
auto dx = rect_origin.x;
auto dy = rect_origin.y;
x0 -= dx;
x1 -= dx;
y0 -= dy;
y1 -= dy;
m_canvas->m_bed_shape = { Pointf(x0, y0),
Pointf(x1, y0),
Pointf(x1, y1),
Pointf(x0, y1)};
}
else if(page_idx == SHAPE_CIRCULAR) {
double diameter;
try{
diameter = boost::any_cast<double>(m_optgroups[SHAPE_CIRCULAR]->get_value("diameter"));
}
catch (const std::exception &e){
return;
}
if (diameter == 0.0) return ;
auto r = diameter / 2;
auto twopi = 2 * PI;
auto edges = 60;
std::vector<Pointf> points;
for (size_t i = 1; i <= 60; ++i){
auto angle = i * twopi / edges;
points.push_back(Pointf(r*cos(angle), r*sin(angle)));
}
m_canvas->m_bed_shape = points;
}
// $self->{on_change}->();
update_preview();
}
// Loads an stl file, projects it to the XY plane and calculates a polygon.
void BedShapePanel::load_stl()
{
t_file_wild_card vec_FILE_WILDCARDS = get_file_wild_card();
std::vector<std::string> file_types = { "known", "stl", "obj", "amf", "prusa"};
wxString MODEL_WILDCARD;
for (auto file_type: file_types)
MODEL_WILDCARD += vec_FILE_WILDCARDS.at(file_type) + "|";
auto dialog = new wxFileDialog(this, _L("Choose a file to import bed shape from (STL/OBJ/AMF/PRUSA):"), "", "",
MODEL_WILDCARD, wxFD_OPEN | wxFD_FILE_MUST_EXIST);
if (dialog->ShowModal() != wxID_OK) {
dialog->Destroy();
return;
}
wxArrayString input_file;
dialog->GetPaths(input_file);
dialog->Destroy();
std::string file_name = input_file[0].ToStdString();
Model model;
try {
model = Model::read_from_file(file_name);
}
catch (std::exception &e) {
auto msg = _L("Error! ") + file_name + " : " + e.what() + ".";
show_error(this, msg);
exit(1);
}
auto mesh = model.mesh();
auto expolygons = mesh.horizontal_projection();
if (expolygons.size() == 0) {
show_error(this, _L("The selected file contains no geometry."));
return;
}
if (expolygons.size() > 1) {
show_error(this, _L("The selected file contains several disjoint areas. This is not supported."));
return;
}
auto polygon = expolygons[0].contour;
std::vector<Pointf> points;
for (auto pt : polygon.points)
points.push_back(Pointf::new_unscale(pt));
m_canvas->m_bed_shape = points;
update_preview();
}
} // GUI
} // Slic3r

View file

@ -0,0 +1,51 @@
// The bed shape dialog.
// The dialog opens from Print Settins tab->Bed Shape : Set...
#include "OptionsGroup.hpp"
#include "2DBed.hpp"
#include <wx/dialog.h>
#include <wx/choicebk.h>
namespace Slic3r {
namespace GUI {
using ConfigOptionsGroupShp = std::shared_ptr<ConfigOptionsGroup>;
class BedShapePanel : public wxPanel
{
wxChoicebook* m_shape_options_book;
Bed_2D* m_canvas;
std::vector <ConfigOptionsGroupShp> m_optgroups;
public:
BedShapePanel(wxWindow* parent) : wxPanel(parent, wxID_ANY){}
~BedShapePanel(){}
void build_panel(ConfigOptionPoints* default_pt);
ConfigOptionsGroupShp init_shape_options_page(wxString title);
void set_shape(ConfigOptionPoints* points);
void update_preview();
void update_shape();
void load_stl();
// Returns the resulting bed shape polygon. This value will be stored to the ini file.
std::vector<Pointf> GetValue() { return m_canvas->m_bed_shape; }
};
class BedShapeDialog : public wxDialog
{
BedShapePanel* m_panel;
public:
BedShapeDialog(wxWindow* parent) : wxDialog(parent, wxID_ANY, _L("Bed Shape"),
wxDefaultPosition, wxSize(350, 700), wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER){}
~BedShapeDialog(){ }
void build_dialog(ConfigOptionPoints* default_pt);
std::vector<Pointf> GetValue() { return m_panel->GetValue(); }
};
} // GUI
} // Slic3r

View file

@ -0,0 +1,15 @@
#include <exception>
namespace Slic3r {
class ConfigError : public std::runtime_error {
using std::runtime_error::runtime_error;
};
namespace GUI {
class ConfigGUITypeError : public ConfigError {
using ConfigError::ConfigError;
};
}
}

570
xs/src/slic3r/GUI/Field.cpp Normal file
View file

@ -0,0 +1,570 @@
#include "GUI.hpp"//"slic3r_gui.hpp"
#include "Field.hpp"
//#include <wx/event.h>
#include <regex>
#include <wx/numformatter.h>
#include <wx/tooltip.h>
#include "PrintConfig.hpp"
#include <boost/algorithm/string/predicate.hpp>
namespace Slic3r { namespace GUI {
void Field::on_kill_focus(wxEvent& event) {
// Without this, there will be nasty focus bugs on Windows.
// Also, docs for wxEvent::Skip() say "In general, it is recommended to skip all
// non-command events to allow the default handling to take place."
event.Skip();
std::cerr << "calling Field::on_kill_focus from " << m_opt_id<< "\n";
// call the registered function if it is available
if (m_on_kill_focus!=nullptr)
m_on_kill_focus();
}
void Field::on_change_field()
{
// std::cerr << "calling Field::_on_change \n";
if (m_on_change != nullptr && !m_disable_change_event)
m_on_change(m_opt_id, get_value());
}
wxString Field::get_tooltip_text(const wxString& default_string)
{
wxString tooltip_text("");
wxString tooltip = wxString::FromUTF8(m_opt.tooltip.c_str());
if (tooltip.length() > 0)
tooltip_text = tooltip + "(" + _L("default") + ": " +
(boost::iends_with(m_opt_id, "_gcode") ? "\n" : "") +
default_string + ")";
return tooltip_text;
}
bool Field::is_matched(std::string string, std::string pattern)
{
std::regex regex_pattern(pattern, std::regex_constants::icase); // use ::icase to make the matching case insensitive like /i in perl
return std::regex_match(string, regex_pattern);
}
boost::any Field::get_value_by_opt_type(wxString str, ConfigOptionType type)
{
boost::any ret_val;
switch (m_opt.type){
case coInt:
ret_val = wxAtoi(str);
break;
case coPercent:
case coPercents:
case coFloats:
case coFloat:{
if (m_opt.type == coPercent) str.RemoveLast();
double val;
str.ToCDouble(&val);
ret_val = val;
break; }
case coString:
case coStrings:
ret_val = str.ToStdString();
break;
case coFloatOrPercent:{
if (str.Last() == '%')
str.RemoveLast();
double val;
str.ToCDouble(&val);
ret_val = val;
break;
}
default:
break;
}
return ret_val;
}
void TextCtrl::BUILD() {
auto size = wxSize(wxDefaultSize);
if (m_opt.height >= 0) size.SetHeight(m_opt.height);
if (m_opt.width >= 0) size.SetWidth(m_opt.width);
wxString text_value = wxString("");
switch (m_opt.type) {
case coFloatOrPercent:
{
if (static_cast<const ConfigOptionFloatOrPercent*>(m_opt.default_value)->percent)
{
text_value = wxString::Format(_T("%i"), int(m_opt.default_value->getFloat()));
text_value += "%";
}
else
text_value = wxNumberFormatter::ToString(m_opt.default_value->getFloat(), 2);
break;
}
case coPercent:
{
text_value = wxString::Format(_T("%i"), int(m_opt.default_value->getFloat()));
text_value += "%";
break;
}
case coPercents:
{
const ConfigOptionPercents *vec = static_cast<const ConfigOptionPercents*>(m_opt.default_value);
if (vec == nullptr || vec->empty()) break;
if (vec->size() > 1)
break;
double val = vec->get_at(0);
text_value = val - int(val) == 0 ? wxString::Format(_T("%i"), int(val)) : wxNumberFormatter::ToString(val, 2, wxNumberFormatter::Style_None);
break;
}
case coFloat:
{
double val = m_opt.default_value->getFloat();
text_value = (val - int(val)) == 0 ? wxString::Format(_T("%i"), int(val)) : wxNumberFormatter::ToString(val, 2, wxNumberFormatter::Style_None);
break;
}
case coFloats:
{
const ConfigOptionFloats *vec = static_cast<const ConfigOptionFloats*>(m_opt.default_value);
if (vec == nullptr || vec->empty()) break;
if (vec->size() > 1)
break;
double val = vec->get_at(0);
text_value = val - int(val) == 0 ? wxString::Format(_T("%i"), int(val)) : wxNumberFormatter::ToString(val, 2, wxNumberFormatter::Style_None);
break;
}
case coString:
text_value = static_cast<const ConfigOptionString*>(m_opt.default_value)->value;
break;
case coStrings:
{
const ConfigOptionStrings *vec = static_cast<const ConfigOptionStrings*>(m_opt.default_value);
if (vec == nullptr || vec->empty()) break;
if (vec->size() > 1)
break;
text_value = vec->values.at(0);
break;
}
default:
break;
}
auto temp = new wxTextCtrl(m_parent, wxID_ANY, text_value, wxDefaultPosition, size, (m_opt.multiline ? wxTE_MULTILINE : 0));
temp->SetToolTip(get_tooltip_text(text_value));
temp->Bind(wxEVT_LEFT_DOWN, ([temp](wxEvent& event)
{
//! to allow the default handling
event.Skip();
//! eliminating the g-code pop up text description
temp->GetToolTip()->Enable(false);
}), temp->GetId());
temp->Bind(wxEVT_KILL_FOCUS, ([this, temp](wxEvent& e)
{
on_kill_focus(e);
temp->GetToolTip()->Enable(true);
}), temp->GetId());
temp->Bind(wxEVT_TEXT, ([this](wxCommandEvent) { on_change_field(); }), temp->GetId());
// recast as a wxWindow to fit the calling convention
window = dynamic_cast<wxWindow*>(temp);
}
boost::any TextCtrl::get_value()
{
wxString ret_str = static_cast<wxTextCtrl*>(window)->GetValue();
boost::any ret_val = get_value_by_opt_type(ret_str, m_opt.type);
return ret_val;
}
void TextCtrl::enable() { dynamic_cast<wxTextCtrl*>(window)->Enable(); dynamic_cast<wxTextCtrl*>(window)->SetEditable(true); }
void TextCtrl::disable() { dynamic_cast<wxTextCtrl*>(window)->Disable(); dynamic_cast<wxTextCtrl*>(window)->SetEditable(false); }
void CheckBox::BUILD() {
auto size = wxSize(wxDefaultSize);
if (m_opt.height >= 0) size.SetHeight(m_opt.height);
if (m_opt.width >= 0) size.SetWidth(m_opt.width);
bool check_value = m_opt.type == coBool ?
m_opt.default_value->getBool() : m_opt.type == coBools ?
static_cast<ConfigOptionBools*>(m_opt.default_value)->values.at(0) :
false;
auto temp = new wxCheckBox(m_parent, wxID_ANY, wxString(""), wxDefaultPosition, size);
temp->SetValue(check_value);
if (m_opt.readonly) temp->Disable();
temp->Bind(wxEVT_CHECKBOX, ([this](wxCommandEvent e) { on_change_field(); }), temp->GetId());
temp->SetToolTip(get_tooltip_text(check_value ? "true" : "false"));
// recast as a wxWindow to fit the calling convention
window = dynamic_cast<wxWindow*>(temp);
}
int undef_spin_val = -9999; //! Probably, It's not necessary
void SpinCtrl::BUILD() {
auto size = wxSize(wxDefaultSize);
if (m_opt.height >= 0) size.SetHeight(m_opt.height);
if (m_opt.width >= 0) size.SetWidth(m_opt.width);
wxString text_value = wxString("");
int default_value = 0;
switch (m_opt.type) {
case coInt:
default_value = m_opt.default_value->getInt();
text_value = wxString::Format(_T("%i"), default_value);
break;
case coInts:
{
const ConfigOptionInts *vec = static_cast<const ConfigOptionInts*>(m_opt.default_value);
if (vec == nullptr || vec->empty()) break;
for (size_t id = 0; id < vec->size(); ++id)
{
default_value = vec->get_at(id);
text_value += wxString::Format(_T("%i"), default_value);
}
break;
}
default:
break;
}
auto temp = new wxSpinCtrl(m_parent, wxID_ANY, text_value, wxDefaultPosition, size,
0, m_opt.min >0 ? m_opt.min : 0, m_opt.max < 2147483647 ? m_opt.max : 2147483647, default_value);
temp->Bind(wxEVT_SPINCTRL, ([this](wxCommandEvent e) { tmp_value = undef_spin_val; on_change_field(); }), temp->GetId());
temp->Bind(wxEVT_KILL_FOCUS, ([this](wxEvent& e) { tmp_value = undef_spin_val; on_kill_focus(e); }), temp->GetId());
temp->Bind(wxEVT_TEXT, ([this](wxCommandEvent e)
{
// # On OSX / Cocoa, wxSpinCtrl::GetValue() doesn't return the new value
// # when it was changed from the text control, so the on_change callback
// # gets the old one, and on_kill_focus resets the control to the old value.
// # As a workaround, we get the new value from $event->GetString and store
// # here temporarily so that we can return it from $self->get_value
std::string value = e.GetString().utf8_str().data();
if (is_matched(value, "^\\d+$"))
tmp_value = std::stoi(value);
on_change_field();
// # We don't reset tmp_value here because _on_change might put callbacks
// # in the CallAfter queue, and we want the tmp value to be available from
// # them as well.
}), temp->GetId());
temp->SetToolTip(get_tooltip_text(text_value));
// recast as a wxWindow to fit the calling convention
window = dynamic_cast<wxWindow*>(temp);
}
void Choice::BUILD() {
auto size = wxSize(wxDefaultSize);
if (m_opt.height >= 0) size.SetHeight(m_opt.height);
if (m_opt.width >= 0) size.SetWidth(m_opt.width);
wxComboBox* temp;
if (!m_opt.gui_type.empty() && m_opt.gui_type.compare("select_open") != 0)
temp = new wxComboBox(m_parent, wxID_ANY, wxString(""), wxDefaultPosition, size);
else
temp = new wxComboBox(m_parent, wxID_ANY, wxString(""), wxDefaultPosition, size, 0, NULL, wxCB_READONLY);
// recast as a wxWindow to fit the calling convention
window = dynamic_cast<wxWindow*>(temp);
if (m_opt.enum_labels.empty() && m_opt.enum_values.empty()){
}
else{
for (auto el : m_opt.enum_labels.empty() ? m_opt.enum_values : m_opt.enum_labels)
temp->Append(wxString(el));
set_selection();
}
temp->Bind(wxEVT_TEXT, ([this](wxCommandEvent e) { on_change_field(); }), temp->GetId());
temp->Bind(wxEVT_COMBOBOX, ([this](wxCommandEvent e) { on_change_field(); }), temp->GetId());
temp->SetToolTip(get_tooltip_text(temp->GetValue()));
}
void Choice::set_selection()
{
wxString text_value = wxString("");
switch (m_opt.type){
case coFloat:
case coPercent: {
double val = m_opt.default_value->getFloat();
text_value = val - int(val) == 0 ? wxString::Format(_T("%i"), int(val)) : wxNumberFormatter::ToString(val, 1);
size_t idx = 0;
for (auto el : m_opt.enum_values)
{
if (el.compare(text_value) == 0)
break;
++idx;
}
if (m_opt.type == coPercent) text_value += "%";
idx == m_opt.enum_values.size() ?
dynamic_cast<wxComboBox*>(window)->SetValue(text_value) :
dynamic_cast<wxComboBox*>(window)->SetSelection(idx);
break;
}
case coEnum:{
int id_value = static_cast<const ConfigOptionEnum<SeamPosition>*>(m_opt.default_value)->value; //!!
dynamic_cast<wxComboBox*>(window)->SetSelection(id_value);
break;
}
case coInt:{
int val = m_opt.default_value->getInt(); //!!
text_value = wxString::Format(_T("%i"), int(val));
size_t idx = 0;
for (auto el : m_opt.enum_values)
{
if (el.compare(text_value) == 0)
break;
++idx;
}
idx == m_opt.enum_values.size() ?
dynamic_cast<wxComboBox*>(window)->SetValue(text_value) :
dynamic_cast<wxComboBox*>(window)->SetSelection(idx);
break;
}
case coStrings:{
text_value = static_cast<const ConfigOptionStrings*>(m_opt.default_value)->values.at(0);
size_t idx = 0;
for (auto el : m_opt.enum_values)
{
if (el.compare(text_value) == 0)
break;
++idx;
}
idx == m_opt.enum_values.size() ?
dynamic_cast<wxComboBox*>(window)->SetValue(text_value) :
dynamic_cast<wxComboBox*>(window)->SetSelection(idx);
break;
}
}
}
void Choice::set_value(const std::string value) //! Redundant?
{
m_disable_change_event = true;
size_t idx=0;
for (auto el : m_opt.enum_values)
{
if (el.compare(value) == 0)
break;
++idx;
}
idx == m_opt.enum_values.size() ?
dynamic_cast<wxComboBox*>(window)->SetValue(value) :
dynamic_cast<wxComboBox*>(window)->SetSelection(idx);
m_disable_change_event = false;
}
void Choice::set_value(boost::any value)
{
m_disable_change_event = true;
switch (m_opt.type){
case coInt:
case coFloat:
case coPercent:
case coStrings:{
wxString text_value;
if (m_opt.type == coInt)
text_value = wxString::Format(_T("%i"), int(boost::any_cast<int>(value)));
else
text_value = boost::any_cast<wxString>(value);
auto idx = 0;
for (auto el : m_opt.enum_values)
{
if (el.compare(text_value) == 0)
break;
++idx;
}
if (m_opt.type == coPercent) text_value += "%";
idx == m_opt.enum_values.size() ?
dynamic_cast<wxComboBox*>(window)->SetValue(text_value) :
dynamic_cast<wxComboBox*>(window)->SetSelection(idx);
break;
}
case coEnum:{
dynamic_cast<wxComboBox*>(window)->SetSelection(boost::any_cast<int>(value));
break;
}
default:
break;
}
m_disable_change_event = false;
}
//! it's needed for _update_serial_ports()
void Choice::set_values(const std::vector<std::string> values)
{
if (values.empty())
return;
m_disable_change_event = true;
// # it looks that Clear() also clears the text field in recent wxWidgets versions,
// # but we want to preserve it
auto ww = dynamic_cast<wxComboBox*>(window);
auto value = ww->GetValue();
ww->Clear();
for (auto el : values)
ww->Append(wxString(el));
ww->SetValue(value);
m_disable_change_event = false;
}
boost::any Choice::get_value()
{
boost::any ret_val;
wxString ret_str = static_cast<wxComboBox*>(window)->GetValue();
if (m_opt.type != coEnum)
ret_val = get_value_by_opt_type(ret_str, m_opt.type);
else
{
int ret_enum = static_cast<wxComboBox*>(window)->GetSelection();
if (m_opt_id.compare("external_fill_pattern") == 0)
{
if (!m_opt.enum_values.empty()){
std::string key = m_opt.enum_values[ret_enum];
t_config_enum_values map_names = ConfigOptionEnum<InfillPattern>::get_enum_values();
int value = map_names.at(key);
ret_val = static_cast<InfillPattern>(value);
}
else
ret_val = static_cast<InfillPattern>(0);
}
if (m_opt_id.compare("fill_pattern") == 0)
ret_val = static_cast<InfillPattern>(ret_enum);
else if (m_opt_id.compare("gcode_flavor") == 0)
ret_val = static_cast<GCodeFlavor>(ret_enum);
else if (m_opt_id.compare("support_material_pattern") == 0)
ret_val = static_cast<SupportMaterialPattern>(ret_enum);
else if (m_opt_id.compare("seam_position") == 0)
ret_val = static_cast<SeamPosition>(ret_enum);
}
return ret_val;
}
void ColourPicker::BUILD()
{
auto size = wxSize(wxDefaultSize);
if (m_opt.height >= 0) size.SetHeight(m_opt.height);
if (m_opt.width >= 0) size.SetWidth(m_opt.width);
wxString clr(static_cast<ConfigOptionStrings*>(m_opt.default_value)->values.at(0));
auto temp = new wxColourPickerCtrl(m_parent, wxID_ANY, clr, wxDefaultPosition, size);
// // recast as a wxWindow to fit the calling convention
window = dynamic_cast<wxWindow*>(temp);
temp->Bind(wxEVT_COLOURPICKER_CHANGED, ([this](wxCommandEvent e) { on_change_field(); }), temp->GetId());
temp->SetToolTip(get_tooltip_text(clr));
}
boost::any ColourPicker::get_value(){
boost::any ret_val;
auto colour = static_cast<wxColourPickerCtrl*>(window)->GetColour();
auto clr_str = wxString::Format(wxT("#%02X%02X%02X"), colour.Red(), colour.Green(), colour.Blue());
ret_val = clr_str.ToStdString();
return ret_val;
}
void PointCtrl::BUILD()
{
auto size = wxSize(wxDefaultSize);
if (m_opt.height >= 0) size.SetHeight(m_opt.height);
if (m_opt.width >= 0) size.SetWidth(m_opt.width);
auto temp = new wxBoxSizer(wxHORIZONTAL);
// $self->wxSizer($sizer);
//
wxSize field_size(40, -1);
auto default_pt = static_cast<ConfigOptionPoints*>(m_opt.default_value)->values.at(0);
double val = default_pt.x;
wxString X = val - int(val) == 0 ? wxString::Format(_T("%i"), int(val)) : wxNumberFormatter::ToString(val, 2, wxNumberFormatter::Style_None);
val = default_pt.y;
wxString Y = val - int(val) == 0 ? wxString::Format(_T("%i"), int(val)) : wxNumberFormatter::ToString(val, 2, wxNumberFormatter::Style_None);
x_textctrl = new wxTextCtrl(m_parent, wxID_ANY, X, wxDefaultPosition, field_size);
y_textctrl = new wxTextCtrl(m_parent, wxID_ANY, Y, wxDefaultPosition, field_size);
temp->Add(new wxStaticText(m_parent, wxID_ANY, "x : "), 0, wxALIGN_CENTER_VERTICAL, 0);
temp->Add(x_textctrl);
temp->Add(new wxStaticText(m_parent, wxID_ANY, " y : "), 0, wxALIGN_CENTER_VERTICAL, 0);
temp->Add(y_textctrl);
x_textctrl->Bind(wxEVT_TEXT, ([this](wxCommandEvent e) { on_change_field(); }), x_textctrl->GetId());
y_textctrl->Bind(wxEVT_TEXT, ([this](wxCommandEvent e) { on_change_field(); }), y_textctrl->GetId());
// // recast as a wxWindow to fit the calling convention
sizer = dynamic_cast<wxSizer*>(temp);
x_textctrl->SetToolTip(get_tooltip_text(X+", "+Y));
y_textctrl->SetToolTip(get_tooltip_text(X+", "+Y));
}
void PointCtrl::set_value(const Pointf value)
{
m_disable_change_event = true;
double val = value.x;
x_textctrl->SetValue(val - int(val) == 0 ? wxString::Format(_T("%i"), int(val)) : wxNumberFormatter::ToString(val, 2, wxNumberFormatter::Style_None));
val = value.y;
y_textctrl->SetValue(val - int(val) == 0 ? wxString::Format(_T("%i"), int(val)) : wxNumberFormatter::ToString(val, 2, wxNumberFormatter::Style_None));
m_disable_change_event = false;
}
void PointCtrl::set_value(boost::any value)
{
Pointf pt;
try
{
pt = boost::any_cast<ConfigOptionPoints*>(value)->values.at(0);
}
catch (const std::exception &e)
{
try{
pt = boost::any_cast<Pointf>(value);
}
catch (const std::exception &e)
{
std::cerr << "Error! Can't cast PointCtrl value" << m_opt_id << "\n";
return;
}
}
set_value(pt);
}
boost::any PointCtrl::get_value()
{
Pointf ret_point;
double val;
x_textctrl->GetValue().ToDouble(&val);
ret_point.x = val;
y_textctrl->GetValue().ToDouble(&val);
ret_point.y = val;
return ret_point;
}
} // GUI
} // Slic3r

270
xs/src/slic3r/GUI/Field.hpp Normal file
View file

@ -0,0 +1,270 @@
#ifndef SLIC3R_GUI_FIELD_HPP
#define SLIC3R_GUI_FIELD_HPP
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <memory>
#include <functional>
#include <boost/any.hpp>
#include <wx/spinctrl.h>
#include <wx/clrpicker.h>
#include "../../libslic3r/libslic3r.h"
#include "../../libslic3r/Config.hpp"
//#include "slic3r_gui.hpp"
#include "GUI.hpp"
namespace Slic3r { namespace GUI {
class Field;
using t_field = std::unique_ptr<Field>;
using t_kill_focus = std::function<void()>;
using t_change = std::function<void(t_config_option_key, boost::any)>;
class Field {
protected:
// factory function to defer and enforce creation of derived type.
virtual void PostInitialize() { BUILD(); }
/// Finish constructing the Field's wxWidget-related properties, including setting its own sizer, etc.
virtual void BUILD() = 0;
/// Call the attached on_kill_focus method.
//! It's important to use wxEvent instead of wxFocusEvent,
//! in another case we can't unfocused control at all
void on_kill_focus(wxEvent& event);
/// Call the attached on_change method.
void on_change_field();
public:
/// parent wx item, opportunity to refactor (probably not necessary - data duplication)
wxWindow* m_parent {nullptr};
/// Function object to store callback passed in from owning object.
t_kill_focus m_on_kill_focus {nullptr};
/// Function object to store callback passed in from owning object.
t_change m_on_change {nullptr};
// This is used to avoid recursive invocation of the field change/update by wxWidgets.
bool m_disable_change_event {false};
/// Copy of ConfigOption for deduction purposes
const ConfigOptionDef m_opt {ConfigOptionDef()};
const t_config_option_key m_opt_id;//! {""};
/// Sets a value for this control.
/// subclasses should overload with a specific version
/// Postcondition: Method does not fire the on_change event.
virtual void set_value(boost::any value) = 0;
/// Gets a boost::any representing this control.
/// subclasses should overload with a specific version
virtual boost::any get_value() = 0;
virtual void enable() = 0;
virtual void disable() = 0;
/// Fires the enable or disable function, based on the input.
inline void toggle(bool en) { en ? enable() : disable(); }
virtual wxString get_tooltip_text(const wxString& default_string);
Field(const ConfigOptionDef& opt, const t_config_option_key& id) : m_opt(opt), m_opt_id(id) {};
Field(wxWindow* parent, const ConfigOptionDef& opt, const t_config_option_key& id) : m_parent(parent), m_opt(opt), m_opt_id(id) {};
/// If you don't know what you are getting back, check both methods for nullptr.
virtual wxSizer* getSizer() { return nullptr; }
virtual wxWindow* getWindow() { return nullptr; }
bool is_matched(std::string string, std::string pattern);
boost::any get_value_by_opt_type(wxString str, ConfigOptionType type);
/// Factory method for generating new derived classes.
template<class T>
static t_field Create(wxWindow* parent, const ConfigOptionDef& opt, const t_config_option_key& id) // interface for creating shared objects
{
auto p = Slic3r::make_unique<T>(parent, opt, id);
p->PostInitialize();
return std::move(p); //!p;
}
};
/// Convenience function, accepts a const reference to t_field and checks to see whether
/// or not both wx pointers are null.
inline bool is_bad_field(const t_field& obj) { return obj->getSizer() == nullptr && obj->getWindow() == nullptr; }
/// Covenience function to determine whether this field is a valid window field.
inline bool is_window_field(const t_field& obj) { return !is_bad_field(obj) && obj->getWindow() != nullptr; }
/// Covenience function to determine whether this field is a valid sizer field.
inline bool is_sizer_field(const t_field& obj) { return !is_bad_field(obj) && obj->getSizer() != nullptr; }
class TextCtrl : public Field {
using Field::Field;
public:
TextCtrl(const ConfigOptionDef& opt, const t_config_option_key& id) : Field(opt, id) {}
TextCtrl(wxWindow* parent, const ConfigOptionDef& opt, const t_config_option_key& id) : Field(parent, opt, id) {}
void BUILD();
wxWindow* window {nullptr};
virtual void set_value(std::string value) {
m_disable_change_event = true;
dynamic_cast<wxTextCtrl*>(window)->SetValue(wxString(value));
m_disable_change_event = false;
}
virtual void set_value(boost::any value) {
m_disable_change_event = true;
dynamic_cast<wxTextCtrl*>(window)->SetValue(boost::any_cast<wxString>(value));
m_disable_change_event = false;
}
boost::any get_value() override;
virtual void enable();
virtual void disable();
virtual wxWindow* getWindow() { return window; }
};
class CheckBox : public Field {
using Field::Field;
public:
CheckBox(const ConfigOptionDef& opt, const t_config_option_key& id) : Field(opt, id) {}
CheckBox(wxWindow* parent, const ConfigOptionDef& opt, const t_config_option_key& id) : Field(parent, opt, id) {}
wxWindow* window{ nullptr };
void BUILD() override;
void set_value(const bool value) {
m_disable_change_event = true;
dynamic_cast<wxCheckBox*>(window)->SetValue(value);
m_disable_change_event = false;
}
void set_value(boost::any value) {
m_disable_change_event = true;
dynamic_cast<wxCheckBox*>(window)->SetValue(boost::any_cast<bool>(value));
m_disable_change_event = false;
}
boost::any get_value() override {
return boost::any(dynamic_cast<wxCheckBox*>(window)->GetValue());
}
void enable() override { dynamic_cast<wxCheckBox*>(window)->Enable(); }
void disable() override { dynamic_cast<wxCheckBox*>(window)->Disable(); }
wxWindow* getWindow() override { return window; }
};
class SpinCtrl : public Field {
using Field::Field;
public:
SpinCtrl(const ConfigOptionDef& opt, const t_config_option_key& id) : Field(opt, id), tmp_value(-9999) {}
SpinCtrl(wxWindow* parent, const ConfigOptionDef& opt, const t_config_option_key& id) : Field(parent, opt, id), tmp_value(-9999) {}
int tmp_value;
wxWindow* window{ nullptr };
void BUILD() override;
void set_value(const std::string value) {
m_disable_change_event = true;
dynamic_cast<wxSpinCtrl*>(window)->SetValue(value);
m_disable_change_event = false;
}
void set_value(boost::any value) {
m_disable_change_event = true;
dynamic_cast<wxSpinCtrl*>(window)->SetValue(boost::any_cast<int>(value));
m_disable_change_event = false;
}
boost::any get_value() override {
return boost::any(dynamic_cast<wxSpinCtrl*>(window)->GetValue());
}
void enable() override { dynamic_cast<wxSpinCtrl*>(window)->Enable(); }
void disable() override { dynamic_cast<wxSpinCtrl*>(window)->Disable(); }
wxWindow* getWindow() override { return window; }
};
class Choice : public Field {
using Field::Field;
public:
Choice(const ConfigOptionDef& opt, const t_config_option_key& id) : Field(opt, id) {}
Choice(wxWindow* parent, const ConfigOptionDef& opt, const t_config_option_key& id) : Field(parent, opt, id) {}
wxWindow* window{ nullptr };
void BUILD() override;
void set_selection();
void set_value(const std::string value);
void set_value(boost::any value);
void set_values(const std::vector<std::string> values);
boost::any get_value() override;
void enable() override { dynamic_cast<wxComboBox*>(window)->Enable(); };
void disable() override{ dynamic_cast<wxComboBox*>(window)->Disable(); };
wxWindow* getWindow() override { return window; }
};
class ColourPicker : public Field {
using Field::Field;
public:
ColourPicker(const ConfigOptionDef& opt, const t_config_option_key& id) : Field(opt, id) {}
ColourPicker(wxWindow* parent, const ConfigOptionDef& opt, const t_config_option_key& id) : Field(parent, opt, id) {}
wxWindow* window{ nullptr };
void BUILD() override;
void set_value(const std::string value) {
m_disable_change_event = true;
dynamic_cast<wxColourPickerCtrl*>(window)->SetColour(value);
m_disable_change_event = false;
}
void set_value(boost::any value) {
m_disable_change_event = true;
dynamic_cast<wxColourPickerCtrl*>(window)->SetColour(boost::any_cast<wxString>(value));
m_disable_change_event = false;
}
boost::any get_value() override;
void enable() override { dynamic_cast<wxColourPickerCtrl*>(window)->Enable(); };
void disable() override{ dynamic_cast<wxColourPickerCtrl*>(window)->Disable(); };
wxWindow* getWindow() override { return window; }
};
class PointCtrl : public Field {
using Field::Field;
public:
PointCtrl(const ConfigOptionDef& opt, const t_config_option_key& id) : Field(opt, id) {}
PointCtrl(wxWindow* parent, const ConfigOptionDef& opt, const t_config_option_key& id) : Field(parent, opt, id) {}
wxSizer* sizer{ nullptr };
wxTextCtrl* x_textctrl;
wxTextCtrl* y_textctrl;
void BUILD() override;
void set_value(const Pointf value);
void set_value(boost::any value);
boost::any get_value() override;
void enable() override {
x_textctrl->Enable();
y_textctrl->Enable(); };
void disable() override{
x_textctrl->Disable();
y_textctrl->Disable(); };
wxSizer* getSizer() override { return sizer; }
};
#endif
} // GUI
} // Slic3r

View file

@ -4,22 +4,47 @@
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#if __APPLE__
#import <IOKit/pwr_mgt/IOPMLib.h>
#elif _WIN32
#include <Windows.h>
// Undefine min/max macros incompatible with the standard library
// For example, std::numeric_limits<std::streamsize>::max()
// produces some weird errors
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
#include "boost/nowide/convert.hpp"
#pragma comment(lib, "user32.lib")
#endif
#include <wx/app.h>
#include <wx/button.h>
#include <wx/config.h>
#include <wx/dir.h>
#include <wx/filename.h>
#include <wx/frame.h>
#include <wx/menu.h>
#include <wx/notebook.h>
#include <wx/panel.h>
#include <wx/sizer.h>
#include <wx/combo.h>
#include <wx/window.h>
#include "wxExtensions.hpp"
#include "Tab.hpp"
#include "TabIface.hpp"
#include "AppConfig.hpp"
#include "Utils.hpp"
namespace Slic3r { namespace GUI {
@ -147,6 +172,10 @@ wxApp *g_wxApp = nullptr;
wxFrame *g_wxMainFrame = nullptr;
wxNotebook *g_wxTabPanel = nullptr;
std::vector<Tab *> g_tabs_list;
wxLocale* g_wxLocale;
void set_wxapp(wxApp *app)
{
g_wxApp = app;
@ -162,25 +191,337 @@ void set_tab_panel(wxNotebook *tab_panel)
g_wxTabPanel = tab_panel;
}
void add_debug_menu(wxMenuBar *menu)
std::vector<Tab *>& get_tabs_list()
{
#if 0
auto debug_menu = new wxMenu();
debug_menu->Append(wxWindow::NewControlId(1), "Some debug");
menu->Append(debug_menu, _T("&Debug"));
#endif
return g_tabs_list;
}
void create_preset_tab(const char *name)
bool checked_tab(Tab* tab)
{
auto *panel = new wxPanel(g_wxTabPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxBK_LEFT | wxTAB_TRAVERSAL);
// Vertical sizer to hold the choice menu and the rest of the page.
auto *sizer = new wxBoxSizer(wxVERTICAL);
sizer->SetSizeHints(panel);
panel->SetSizer(sizer);
auto *button = new wxButton(panel, wxID_ANY, "Hello World", wxDefaultPosition, wxDefaultSize, 0);
sizer->Add(button, 0, 0, 0);
g_wxTabPanel->AddPage(panel, name);
bool ret = true;
if (find(g_tabs_list.begin(), g_tabs_list.end(), tab) == g_tabs_list.end())
ret = false;
return ret;
}
void delete_tab_from_list(Tab* tab)
{
std::vector<Tab *>::iterator itr = find(g_tabs_list.begin(), g_tabs_list.end(), tab);
if (itr != g_tabs_list.end())
g_tabs_list.erase(itr);
}
bool select_language(wxArrayString & names,
wxArrayLong & identifiers)
{
wxCHECK_MSG(names.Count() == identifiers.Count(), false,
_L("Array of language names and identifiers should have the same size."));
int init_selection = 0;
long current_language = g_wxLocale ? g_wxLocale->GetLanguage() : wxLANGUAGE_UNKNOWN;
for (auto lang : identifiers){
if (lang == current_language)
break;
else
++init_selection;
}
if (init_selection == identifiers.size())
init_selection = 0;
long index = wxGetSingleChoiceIndex(_L("Select the language"), _L("Language"),
names, init_selection);
if (index != -1)
{
g_wxLocale = new wxLocale;
g_wxLocale->Init(identifiers[index]);
g_wxLocale->AddCatalogLookupPathPrefix(wxPathOnly(localization_dir()));
g_wxLocale->AddCatalog(g_wxApp->GetAppName());
return true;
}
return false;
}
bool load_language()
{
wxConfig config(g_wxApp->GetAppName());
long language;
if (!config.Read(wxT("wxTranslation_Language"),
&language, wxLANGUAGE_UNKNOWN))
{
language = wxLANGUAGE_UNKNOWN;
}
if (language == wxLANGUAGE_UNKNOWN)
return false;
wxArrayString names;
wxArrayLong identifiers;
get_installed_languages(names, identifiers);
for (size_t i = 0; i < identifiers.Count(); i++)
{
if (identifiers[i] == language)
{
g_wxLocale = new wxLocale;
g_wxLocale->Init(identifiers[i]);
g_wxLocale->AddCatalogLookupPathPrefix(wxPathOnly(localization_dir()));
g_wxLocale->AddCatalog(g_wxApp->GetAppName());
return true;
}
}
return false;
}
void save_language()
{
wxConfig config(g_wxApp->GetAppName());
long language = wxLANGUAGE_UNKNOWN;
if (g_wxLocale) {
language = g_wxLocale->GetLanguage();
}
config.Write(wxT("wxTranslation_Language"), language);
config.Flush();
}
void get_installed_languages(wxArrayString & names,
wxArrayLong & identifiers)
{
names.Clear();
identifiers.Clear();
wxDir dir(wxPathOnly(localization_dir()));
wxString filename;
const wxLanguageInfo * langinfo;
wxString name = wxLocale::GetLanguageName(wxLANGUAGE_DEFAULT);
if (!name.IsEmpty())
{
names.Add(_L("Default"));
identifiers.Add(wxLANGUAGE_DEFAULT);
}
for (bool cont = dir.GetFirst(&filename, wxEmptyString, wxDIR_DIRS);
cont; cont = dir.GetNext(&filename))
{
wxLogTrace(wxTraceMask(),
"L10n: Directory found = \"%s\"",
filename.GetData());
langinfo = wxLocale::FindLanguageInfo(filename);
if (langinfo != NULL)
{
auto full_file_name = dir.GetName() + wxFileName::GetPathSeparator() +
filename + wxFileName::GetPathSeparator() +
g_wxApp->GetAppName() + wxT(".mo");
if (wxFileExists(full_file_name))
{
names.Add(langinfo->Description);
identifiers.Add(langinfo->Language);
}
}
}
}
void add_debug_menu(wxMenuBar *menu, int event_language_change)
{
//#if 0
auto local_menu = new wxMenu();
local_menu->Append(wxWindow::NewControlId(1), _L("Change Application Language"));
local_menu->Bind(wxEVT_MENU, [event_language_change](wxEvent&){
wxArrayString names;
wxArrayLong identifiers;
get_installed_languages(names, identifiers);
if (select_language(names, identifiers)){
save_language();
show_info(g_wxTabPanel, "Application will be restarted", "Attention!");
if (event_language_change > 0) {
wxCommandEvent event(event_language_change);
g_wxApp->ProcessEvent(event);
}
}
});
menu->Append(local_menu, _T("&Localization"));
//#endif
}
void create_preset_tabs(PresetBundle *preset_bundle, AppConfig *app_config,
bool no_controller, bool is_disabled_button_browse, bool is_user_agent,
int event_value_change, int event_presets_changed,
int event_button_browse, int event_button_test)
{
add_created_tab(new TabPrint (g_wxTabPanel, no_controller), preset_bundle, app_config);
add_created_tab(new TabFilament (g_wxTabPanel, no_controller), preset_bundle, app_config);
add_created_tab(new TabPrinter (g_wxTabPanel, no_controller, is_disabled_button_browse, is_user_agent),
preset_bundle, app_config);
for (size_t i = 0; i < g_wxTabPanel->GetPageCount(); ++ i) {
Tab *tab = dynamic_cast<Tab*>(g_wxTabPanel->GetPage(i));
if (! tab)
continue;
tab->set_event_value_change(wxEventType(event_value_change));
tab->set_event_presets_changed(wxEventType(event_presets_changed));
if (tab->name() == "printer"){
TabPrinter* tab_printer = static_cast<TabPrinter*>(tab);
tab_printer->set_event_button_browse(wxEventType(event_button_browse));
tab_printer->set_event_button_test(wxEventType(event_button_test));
}
}
}
TabIface* get_preset_tab_iface(char *name)
{
for (size_t i = 0; i < g_wxTabPanel->GetPageCount(); ++ i) {
Tab *tab = dynamic_cast<Tab*>(g_wxTabPanel->GetPage(i));
if (! tab)
continue;
if (tab->name() == name) {
return new TabIface(tab);
}
}
return new TabIface(nullptr);
}
// opt_index = 0, by the reason of zero-index in ConfigOptionVector by default (in case only one element)
void change_opt_value(DynamicPrintConfig& config, t_config_option_key opt_key, boost::any value, int opt_index /*= 0*/)
{
try{
switch (config.def()->get(opt_key)->type){
case coFloatOrPercent:{
const auto &val = *config.option<ConfigOptionFloatOrPercent>(opt_key);
config.set_key_value(opt_key, new ConfigOptionFloatOrPercent(boost::any_cast<double>(value), val.percent));
break;}
case coPercent:
config.set_key_value(opt_key, new ConfigOptionPercent(boost::any_cast<double>(value)));
break;
case coFloat:{
double& val = config.opt_float(opt_key);
val = boost::any_cast<double>(value);
break;
}
case coPercents:
case coFloats:{
double& val = config.opt_float(opt_key, 0);
val = boost::any_cast<double>(value);
break;
}
case coString:
config.set_key_value(opt_key, new ConfigOptionString(boost::any_cast<std::string>(value)));
break;
case coStrings:{
if (opt_key.compare("compatible_printers") == 0){
config.option<ConfigOptionStrings>(opt_key)->values.resize(0);
for (auto el : boost::any_cast<std::vector<std::string>>(value))
config.option<ConfigOptionStrings>(opt_key)->values.push_back(el);
}
else{
ConfigOptionStrings* vec_new = new ConfigOptionStrings{ boost::any_cast<std::string>(value) };
config.option<ConfigOptionStrings>(opt_key)->set_at(vec_new, opt_index, opt_index);
}
}
break;
case coBool:
config.set_key_value(opt_key, new ConfigOptionBool(boost::any_cast<bool>(value)));
break;
case coBools:{
ConfigOptionBools* vec_new = new ConfigOptionBools{ boost::any_cast<bool>(value) };
config.option<ConfigOptionBools>(opt_key)->set_at(vec_new, opt_index, opt_index);
break;}
case coInt:
config.set_key_value(opt_key, new ConfigOptionInt(boost::any_cast<int>(value)));
break;
case coInts:{
ConfigOptionInts* vec_new = new ConfigOptionInts{ boost::any_cast<int>(value) };
config.option<ConfigOptionInts>(opt_key)->set_at(vec_new, opt_index, opt_index);
}
break;
case coEnum:{
if (opt_key.compare("external_fill_pattern") == 0 ||
opt_key.compare("fill_pattern") == 0)
config.set_key_value(opt_key, new ConfigOptionEnum<InfillPattern>(boost::any_cast<InfillPattern>(value)));
else if (opt_key.compare("gcode_flavor") == 0)
config.set_key_value(opt_key, new ConfigOptionEnum<GCodeFlavor>(boost::any_cast<GCodeFlavor>(value)));
else if (opt_key.compare("support_material_pattern") == 0)
config.set_key_value(opt_key, new ConfigOptionEnum<SupportMaterialPattern>(boost::any_cast<SupportMaterialPattern>(value)));
else if (opt_key.compare("seam_position") == 0)
config.set_key_value(opt_key, new ConfigOptionEnum<SeamPosition>(boost::any_cast<SeamPosition>(value)));
}
break;
case coPoints:{
ConfigOptionPoints points;
points.values = boost::any_cast<std::vector<Pointf>>(value);
config.set_key_value(opt_key, new ConfigOptionPoints(points));
}
break;
case coNone:
break;
default:
break;
}
}
catch (const std::exception &e)
{
int i = 0;//no reason, just experiment
}
}
void add_created_tab(Tab* panel, PresetBundle *preset_bundle, AppConfig *app_config)
{
panel->m_show_btn_incompatible_presets = app_config->get("show_incompatible_presets").empty();
panel->create_preset_tab(preset_bundle);
// Load the currently selected preset into the GUI, update the preset selection box.
panel->load_current_preset();
g_wxTabPanel->AddPage(panel, panel->title());
}
void show_error(wxWindow* parent, wxString message){
auto msg_wingow = new wxMessageDialog(parent, message, _L("Error"), wxOK | wxICON_ERROR);
msg_wingow->ShowModal();
}
void show_info(wxWindow* parent, wxString message, wxString title){
auto msg_wingow = new wxMessageDialog(parent, message, title.empty() ? _L("Notice") : title, wxOK | wxICON_INFORMATION);
msg_wingow->ShowModal();
}
wxApp* get_app(){
return g_wxApp;
}
void create_combochecklist(wxComboCtrl* comboCtrl, std::string text, std::string items, bool initial_value)
{
if (comboCtrl == nullptr)
return;
wxCheckListBoxComboPopup* popup = new wxCheckListBoxComboPopup;
if (popup != nullptr)
{
comboCtrl->SetPopupControl(popup);
popup->SetStringValue(text);
popup->Connect(wxID_ANY, wxEVT_CHECKLISTBOX, wxCommandEventHandler(wxCheckListBoxComboPopup::OnCheckListBox), nullptr, popup);
popup->Connect(wxID_ANY, wxEVT_LISTBOX, wxCommandEventHandler(wxCheckListBoxComboPopup::OnListBoxSelection), nullptr, popup);
std::vector<std::string> items_str;
boost::split(items_str, items, boost::is_any_of("|"), boost::token_compress_off);
for (const std::string& item : items_str)
{
popup->Append(item);
}
for (unsigned int i = 0; i < popup->GetCount(); ++i)
{
popup->Check(i, initial_value);
}
}
}
int combochecklist_get_flags(wxComboCtrl* comboCtrl)
{
int flags = 0;
wxCheckListBoxComboPopup* popup = wxDynamicCast(comboCtrl->GetPopupControl(), wxCheckListBoxComboPopup);
if (popup != nullptr)
{
for (unsigned int i = 0; i < popup->GetCount(); ++i)
{
if (popup->IsChecked(i))
flags |= 1 << i;
}
}
return flags;
}
} }

View file

@ -3,13 +3,50 @@
#include <string>
#include <vector>
#include "Config.hpp"
class wxApp;
class wxFrame;
class wxWindow;
class wxMenuBar;
class wxNotebook;
class wxComboCtrl;
class wxString;
class wxArrayString;
class wxArrayLong;
namespace Slic3r { namespace GUI {
namespace Slic3r {
class PresetBundle;
class PresetCollection;
class AppConfig;
class DynamicPrintConfig;
class TabIface;
//! macro used to localization, return wxString
#define _L(s) wxGetTranslation(s)
//! macro used to localization, return const CharType *
#define _LU8(s) wxGetTranslation(s).ToUTF8().data()
namespace GUI {
class Tab;
// Map from an file_type name to full file wildcard name.
typedef std::map<std::string, std::string> t_file_wild_card;
inline t_file_wild_card& get_file_wild_card() {
static t_file_wild_card FILE_WILDCARDS;
if (FILE_WILDCARDS.empty()){
FILE_WILDCARDS["known"] = "Known files (*.stl, *.obj, *.amf, *.xml, *.prusa)|*.stl;*.STL;*.obj;*.OBJ;*.amf;*.AMF;*.xml;*.XML;*.prusa;*.PRUSA";
FILE_WILDCARDS["stl"] = "STL files (*.stl)|*.stl;*.STL";
FILE_WILDCARDS["obj"] = "OBJ files (*.obj)|*.obj;*.OBJ";
FILE_WILDCARDS["amf"] = "AMF files (*.amf)|*.amf;*.AMF;*.xml;*.XML";
FILE_WILDCARDS["prusa"] = "Prusa Control files (*.prusa)|*.prusa;*.PRUSA";
FILE_WILDCARDS["ini"] = "INI files *.ini|*.ini;*.INI";
FILE_WILDCARDS["gcode"] = "G-code files (*.gcode, *.gco, *.g, *.ngc)|*.gcode;*.GCODE;*.gco;*.GCO;*.g;*.G;*.ngc;*.NGC";
FILE_WILDCARDS["svg"] = "SVG files *.svg|*.svg;*.SVG";
}
return FILE_WILDCARDS;
}
void disable_screensaver();
void enable_screensaver();
@ -22,11 +59,45 @@ void set_wxapp(wxApp *app);
void set_main_frame(wxFrame *main_frame);
void set_tab_panel(wxNotebook *tab_panel);
void add_debug_menu(wxMenuBar *menu);
// Create a new preset tab (print, filament or printer),
// add it at the end of the tab panel.
void create_preset_tab(const char *name);
void add_debug_menu(wxMenuBar *menu, int event_language_change);
// Create a new preset tab (print, filament and printer),
void create_preset_tabs(PresetBundle *preset_bundle, AppConfig *app_config,
bool no_controller, bool is_disabled_button_browse, bool is_user_agent,
int event_value_change, int event_presets_changed,
int event_button_browse, int event_button_test);
TabIface* get_preset_tab_iface(char *name);
} }
// add it at the end of the tab panel.
void add_created_tab(Tab* panel, PresetBundle *preset_bundle, AppConfig *app_config);
// Change option value in config
void change_opt_value(DynamicPrintConfig& config, t_config_option_key opt_key, boost::any value, int opt_index = 0);
void show_error(wxWindow* parent, wxString message);
void show_info(wxWindow* parent, wxString message, wxString title);
// load language saved at application config
bool load_language();
// save language at application config
void save_language();
// get list of installed languages
void get_installed_languages(wxArrayString & names, wxArrayLong & identifiers);
// select language from the list of installed languages
bool select_language(wxArrayString & names, wxArrayLong & identifiers);
std::vector<Tab *>& get_tabs_list();
bool checked_tab(Tab* tab);
void delete_tab_from_list(Tab* tab);
// Creates a wxCheckListBoxComboPopup inside the given wxComboCtrl, filled with the given text and items.
// Items are all initialized to the given value.
// Items must be separated by '|', for example "Item1|Item2|Item3", and so on.
void create_combochecklist(wxComboCtrl* comboCtrl, std::string text, std::string items, bool initial_value);
// Returns the current state of the items listed in the wxCheckListBoxComboPopup contained in the given wxComboCtrl,
// encoded inside an int.
int combochecklist_get_flags(wxComboCtrl* comboCtrl);
}
}
#endif

View file

@ -0,0 +1,410 @@
#include "OptionsGroup.hpp"
#include "ConfigExceptions.hpp"
#include <utility>
#include <wx/tooltip.h>
#include <wx/numformatter.h>
namespace Slic3r { namespace GUI {
const t_field& OptionsGroup::build_field(const Option& opt) {
return build_field(opt.opt_id, opt.opt);
}
const t_field& OptionsGroup::build_field(const t_config_option_key& id) {
const ConfigOptionDef& opt = m_options.at(id).opt;
return build_field(id, opt);
}
const t_field& OptionsGroup::build_field(const t_config_option_key& id, const ConfigOptionDef& opt) {
// Check the gui_type field first, fall through
// is the normal type.
if (opt.gui_type.compare("select") == 0) {
} else if (opt.gui_type.compare("select_open") == 0) {
m_fields.emplace(id, STDMOVE(Choice::Create<Choice>(m_parent, opt, id)));
} else if (opt.gui_type.compare("color") == 0) {
m_fields.emplace(id, STDMOVE(ColourPicker::Create<ColourPicker>(m_parent, opt, id)));
} else if (opt.gui_type.compare("f_enum_open") == 0 ||
opt.gui_type.compare("i_enum_open") == 0 ||
opt.gui_type.compare("i_enum_closed") == 0) {
m_fields.emplace(id, STDMOVE(Choice::Create<Choice>(m_parent, opt, id)));
} else if (opt.gui_type.compare("slider") == 0) {
} else if (opt.gui_type.compare("i_spin") == 0) { // Spinctrl
} else {
switch (opt.type) {
case coFloatOrPercent:
case coFloat:
case coFloats:
case coPercent:
case coPercents:
case coString:
case coStrings:
m_fields.emplace(id, STDMOVE(TextCtrl::Create<TextCtrl>(m_parent, opt, id)));
break;
case coBool:
case coBools:
m_fields.emplace(id, STDMOVE(CheckBox::Create<CheckBox>(m_parent, opt, id)));
break;
case coInt:
case coInts:
m_fields.emplace(id, STDMOVE(SpinCtrl::Create<SpinCtrl>(m_parent, opt, id)));
break;
case coEnum:
m_fields.emplace(id, STDMOVE(Choice::Create<Choice>(m_parent, opt, id)));
break;
case coPoints:
m_fields.emplace(id, STDMOVE(PointCtrl::Create<PointCtrl>(m_parent, opt, id)));
break;
case coNone: break;
default:
throw /*//!ConfigGUITypeError("")*/std::logic_error("This control doesn't exist till now"); break;
}
}
// Grab a reference to fields for convenience
const t_field& field = m_fields[id];
field->m_on_change = [this](std::string opt_id, boost::any value){
//! This function will be called from Field.
//! Call OptionGroup._on_change(...)
if (!this->m_disabled)
this->on_change_OG(opt_id, value);
};
field->m_on_kill_focus = [this](){
//! This function will be called from Field.
if (!this->m_disabled)
this->on_kill_focus();
};
field->m_parent = parent();
// assign function objects for callbacks, etc.
return field;
}
void OptionsGroup::append_line(const Line& line) {
//! if (line.sizer != nullptr || (line.widget != nullptr && line.full_width > 0)){
if ( (line.sizer != nullptr || line.widget != nullptr) && line.full_width){
if (line.sizer != nullptr) {
sizer->Add(line.sizer, 0, wxEXPAND | wxALL, wxOSX ? 0 : 15);
return;
}
if (line.widget != nullptr) {
sizer->Add(line.widget(m_parent), 0, wxEXPAND | wxALL, wxOSX ? 0 : 15);
return;
}
}
auto option_set = line.get_options();
for (auto opt : option_set)
m_options.emplace(opt.opt_id, opt);
// if we have a single option with no label, no sidetext just add it directly to sizer
if (option_set.size() == 1 && label_width == 0 && option_set.front().opt.full_width &&
option_set.front().opt.sidetext.size() == 0 && option_set.front().side_widget == nullptr &&
line.get_extra_widgets().size() == 0) {
const auto& option = option_set.front();
const auto& field = build_field(option);
if (is_window_field(field))
sizer->Add(field->getWindow(), 0, wxEXPAND | wxALL, wxOSX ? 0 : 5);
if (is_sizer_field(field))
sizer->Add(field->getSizer(), 0, wxEXPAND | wxALL, wxOSX ? 0 : 5);
return;
}
auto grid_sizer = m_grid_sizer;
// Build a label if we have it
if (label_width != 0) {
auto label = new wxStaticText(parent(), wxID_ANY, line.label + (line.label.IsEmpty() ? "" : ":"),
wxDefaultPosition, wxSize(label_width, -1));
label->SetFont(label_font);
label->Wrap(label_width); // avoid a Linux/GTK bug
grid_sizer->Add(label, 0, wxALIGN_CENTER_VERTICAL,0);
if (line.label_tooltip.compare("") != 0)
label->SetToolTip(line.label_tooltip);
}
// If there's a widget, build it and add the result to the sizer.
if (line.widget != nullptr) {
auto wgt = line.widget(parent());
grid_sizer->Add(wgt, 0, wxEXPAND | wxBOTTOM | wxTOP, wxOSX ? 0 : 5);
return;
}
// if we have a single option with no sidetext just add it directly to the grid sizer
if (option_set.size() == 1 && option_set.front().opt.sidetext.size() == 0 &&
option_set.front().side_widget == nullptr && line.get_extra_widgets().size() == 0) {
const auto& option = option_set.front();
const auto& field = build_field(option);
//! std::cerr << "single option, no sidetext.\n";
//! std::cerr << "field parent is not null?: " << (field->parent != nullptr) << "\n";
if (is_window_field(field))
grid_sizer->Add(field->getWindow(), 0, (option.opt.full_width ? wxEXPAND : 0) |
wxBOTTOM | wxTOP | wxALIGN_CENTER_VERTICAL, wxOSX ? 0 : 2);
if (is_sizer_field(field))
grid_sizer->Add(field->getSizer(), 0, (option.opt.full_width ? wxEXPAND : 0) | wxALIGN_CENTER_VERTICAL, 0);
return;
}
// if we're here, we have more than one option or a single option with sidetext
// so we need a horizontal sizer to arrange these things
auto sizer = new wxBoxSizer(wxHORIZONTAL);
grid_sizer->Add(sizer, 0, wxEXPAND | wxALL, 0);
for (auto opt : option_set) {
ConfigOptionDef option = opt.opt;
// add label if any
if (option.label != "") {
auto field_label = new wxStaticText(parent(), wxID_ANY, wxString::FromUTF8(option.label.c_str()) + ":", wxDefaultPosition, wxDefaultSize);
field_label->SetFont(label_font);
sizer->Add(field_label, 0, wxALIGN_CENTER_VERTICAL, 0);
}
// add field
const Option& opt_ref = opt;
auto& field = build_field(opt_ref);
is_sizer_field(field) ?
sizer->Add(field->getSizer(), 0, wxALIGN_CENTER_VERTICAL, 0) :
sizer->Add(field->getWindow(), 0, wxALIGN_CENTER_VERTICAL, 0);
// add sidetext if any
if (option.sidetext != "") {
auto sidetext = new wxStaticText(parent(), wxID_ANY, wxString::FromUTF8(option.sidetext.c_str()), wxDefaultPosition, wxDefaultSize);
sidetext->SetFont(sidetext_font);
sizer->Add(sidetext, 0, wxLEFT | wxALIGN_CENTER_VERTICAL, 4);
}
// add side widget if any
if (opt.side_widget != nullptr) {
sizer->Add(opt.side_widget(parent())/*!.target<wxWindow>()*/, 0, wxLEFT | wxALIGN_CENTER_VERTICAL, 1); //! requires verification
}
if (opt.opt_id != option_set.back().opt_id) //! istead of (opt != option_set.back())
{
sizer->AddSpacer(6);
}
}
// add extra sizers if any
for (auto extra_widget : line.get_extra_widgets()) {
sizer->Add(extra_widget(parent())/*!.target<wxWindow>()*/, 0, wxLEFT | wxALIGN_CENTER_VERTICAL, 4); //! requires verification
}
}
Line OptionsGroup::create_single_option_line(const Option& option) const {
Line retval{ wxString::FromUTF8(option.opt.label.c_str()), wxString::FromUTF8(option.opt.tooltip.c_str()) };
Option tmp(option);
tmp.opt.label = std::string("");
retval.append_option(tmp);
return retval;
}
void OptionsGroup::on_change_OG(t_config_option_key id, /*config_value*/boost::any value) {
if (m_on_change != nullptr)
m_on_change(id, value);
}
Option ConfigOptionsGroup::get_option(const std::string opt_key, int opt_index /*= -1*/)
{
if (!m_config->has(opt_key)) {
//! exception ("No $opt_key in ConfigOptionsGroup config");
}
std::string opt_id = opt_index == -1 ? opt_key : opt_key + "#" + std::to_string(opt_index);
std::pair<std::string, int> pair(opt_key, opt_index);
m_opt_map.emplace(opt_id, pair);
return Option(*m_config->def()->get(opt_key), opt_id);
}
void ConfigOptionsGroup::on_change_OG(t_config_option_key opt_id, boost::any value)
{
if (!m_opt_map.empty())
{
auto it = m_opt_map.find(opt_id);
if (it == m_opt_map.end())
{
OptionsGroup::on_change_OG(opt_id, value);
return;
}
auto itOption = it->second;
std::string opt_key = itOption.first;
int opt_index = itOption.second;
auto option = m_options.at(opt_id).opt;
// get value
//! auto field_value = get_value(opt_id);
if (option.gui_flags.compare("serialized")==0) {
if (opt_index != -1){
// die "Can't set serialized option indexed value" ;
}
// # Split a string to multiple strings by a semi - colon.This is the old way of storing multi - string values.
// # Currently used for the post_process config value only.
// my @values = split / ; / , $field_value;
// $self->config->set($opt_key, \@values);
}
else {
if (opt_index == -1) {
// change_opt_value(*m_config, opt_key, field_value);
//!? why field_value?? in this case changed value will be lose! No?
change_opt_value(*m_config, opt_key, value);
}
else {
change_opt_value(*m_config, opt_key, value, opt_index);
// auto value = m_config->get($opt_key);
// $value->[$opt_index] = $field_value;
// $self->config->set($opt_key, $value);
}
}
}
OptionsGroup::on_change_OG(opt_id, value); //!? Why doing this
}
void ConfigOptionsGroup::reload_config(){
for (std::map< std::string, std::pair<std::string, int> >::iterator it = m_opt_map.begin(); it != m_opt_map.end(); ++it) {
auto opt_id = it->first;
std::string opt_key = m_opt_map.at(opt_id).first;
int opt_index = m_opt_map.at(opt_id).second;
auto option = m_options.at(opt_id).opt;
set_value(opt_id, config_value(opt_key, opt_index, option.gui_flags.compare("serialized") == 0 ));
}
}
boost::any ConfigOptionsGroup::config_value(std::string opt_key, int opt_index, bool deserialize){
if (deserialize) {
// Want to edit a vector value(currently only multi - strings) in a single edit box.
// Aggregate the strings the old way.
// Currently used for the post_process config value only.
if (opt_index != -1)
throw std::out_of_range("Can't deserialize option indexed value");
// return join(';', m_config->get(opt_key)});
return get_config_value(*m_config, opt_key);
}
else {
// return opt_index == -1 ? m_config->get(opt_key) : m_config->get_at(opt_key, opt_index);
return get_config_value(*m_config, opt_key, opt_index);
}
}
wxString double_to_string(double const value)
{
int precision = 10 * value - int(10 * value) == 0 ? 1 : 2;
return value - int(value) == 0 ?
wxString::Format(_T("%i"), int(value)) :
wxNumberFormatter::ToString(value, precision, wxNumberFormatter::Style_None);
}
boost::any ConfigOptionsGroup::get_config_value(DynamicPrintConfig& config, std::string opt_key, int opt_index/* = -1*/)
{
size_t idx = opt_index == -1 ? 0 : opt_index;
boost::any ret;
wxString text_value = wxString("");
const ConfigOptionDef* opt = config.def()->get(opt_key);
switch (opt->type){
case coFloatOrPercent:{
const auto &value = *config.option<ConfigOptionFloatOrPercent>(opt_key);
if (value.percent)
{
text_value = wxString::Format(_T("%i"), int(value.value));
text_value += "%";
}
else
text_value = double_to_string(value.value);
ret = text_value;
break;
}
case coPercent:{
double val = config.option<ConfigOptionPercent>(opt_key)->value;
text_value = wxString::Format(_T("%i"), int(val));
ret = text_value;// += "%";
}
break;
case coPercents:
case coFloats:
case coFloat:{
double val = opt->type == coFloats ?
config.opt_float(opt_key, idx/*0opt_index*/) :
opt->type == coFloat ? config.opt_float(opt_key) :
config.option<ConfigOptionPercents>(opt_key)->values.at(idx/*0*/);
ret = double_to_string(val);
}
break;
case coString:
ret = static_cast<wxString>(config.opt_string(opt_key));
break;
case coStrings:
if (config.option<ConfigOptionStrings>(opt_key)->values.empty())
ret = text_value;
else
ret = static_cast<wxString>(config.opt_string(opt_key, static_cast<unsigned int>(idx/*0*/)/*opt_index*/));
break;
case coBool:
ret = config.opt_bool(opt_key);
break;
case coBools:
ret = config.opt_bool(opt_key, idx/*0opt_index*/);
break;
case coInt:
ret = config.opt_int(opt_key);
break;
case coInts:
ret = config.opt_int(opt_key, idx/*0/*opt_index*/);
break;
case coEnum:{
if (opt_key.compare("external_fill_pattern") == 0 ||
opt_key.compare("fill_pattern") == 0 ){
ret = static_cast<int>(config.option<ConfigOptionEnum<InfillPattern>>(opt_key)->value);
}
else if (opt_key.compare("gcode_flavor") == 0 ){
ret = static_cast<int>(config.option<ConfigOptionEnum<GCodeFlavor>>(opt_key)->value);
}
else if (opt_key.compare("support_material_pattern") == 0){
ret = static_cast<int>(config.option<ConfigOptionEnum<SupportMaterialPattern>>(opt_key)->value);
}
else if (opt_key.compare("seam_position") == 0)
ret = static_cast<int>(config.option<ConfigOptionEnum<SeamPosition>>(opt_key)->value);
}
break;
case coPoints:{
const auto &value = *config.option<ConfigOptionPoints>(opt_key);
ret = value.values.at(idx/*0*/);
}
break;
case coNone:
default:
break;
}
return ret;
}
Field* ConfigOptionsGroup::get_fieldc(t_config_option_key opt_key, int opt_index){
std::string opt_id = "";
for (std::map< std::string, std::pair<std::string, int> >::iterator it = m_opt_map.begin(); it != m_opt_map.end(); ++it) {
if (opt_key == m_opt_map.at(it->first).first && opt_index == m_opt_map.at(it->first).second){
opt_id = it->first;
break;
}
}
return opt_id.empty() ? nullptr : get_field(opt_id);
}
void ogStaticText::SetText(wxString value)
{
SetLabel(value);
Wrap(400);
GetParent()->Layout();
}
void Option::translate()
{
opt.label = _LU8(opt.label);
opt.tooltip = _LU8(opt.tooltip);
opt.sidetext = _LU8(opt.sidetext);
opt.full_label = _LU8(opt.full_label);
opt.category = _LU8(opt.category);
}
} // GUI
} // Slic3r

View file

@ -0,0 +1,181 @@
#include <wx/wx.h>
#include <wx/stattext.h>
#include <wx/settings.h>
//#include <wx/window.h>
#include <map>
#include <functional>
#include "libslic3r/Config.hpp"
#include "libslic3r/PrintConfig.hpp"
#include "libslic3r/libslic3r.h"
#include "Field.hpp"
// Translate the ifdef
#ifdef __WXOSX__
#define wxOSX true
#else
#define wxOSX false
#endif
#define BORDER(a, b) ((wxOSX ? a : b))
namespace Slic3r { namespace GUI {
/// Widget type describes a function object that returns a wxWindow (our widget) and accepts a wxWidget (parent window).
using widget_t = std::function<wxSizer*(wxWindow*)>;//!std::function<wxWindow*(wxWindow*)>;
using column_t = std::function<wxSizer*(const Line&)>;
/// Wraps a ConfigOptionDef and adds function object for creating a side_widget.
struct Option {
ConfigOptionDef opt { ConfigOptionDef() };
t_config_option_key opt_id;//! {""};
widget_t side_widget {nullptr};
bool readonly {false};
Option(const ConfigOptionDef& _opt, t_config_option_key id) :
opt(_opt), opt_id(id) { translate(); }
void translate();
};
using t_option = std::unique_ptr<Option>; //!
/// Represents option lines
class Line {
public:
wxString label {wxString("")};
wxString label_tooltip {wxString("")};
size_t full_width {0};
wxSizer* sizer {nullptr};
widget_t widget {nullptr};
void append_option(const Option& option) {
m_options.push_back(option);
}
void append_widget(const widget_t widget) {
m_extra_widgets.push_back(widget);
}
Line(wxString label, wxString tooltip) :
label(label), label_tooltip(tooltip) {}
const std::vector<widget_t>& get_extra_widgets() const {return m_extra_widgets;}
const std::vector<Option>& get_options() const { return m_options; }
private:
std::vector<Option> m_options;//! {std::vector<Option>()};
std::vector<widget_t> m_extra_widgets;//! {std::vector<widget_t>()};
};
using t_optionfield_map = std::map<t_config_option_key, t_field>;
class OptionsGroup {
public:
const bool staticbox {true};
const wxString title {wxString("")};
size_t label_width {200};
wxSizer* sizer {nullptr};
column_t extra_column {nullptr};
t_change m_on_change {nullptr};
wxFont sidetext_font {wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT) };
wxFont label_font {wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT) };
/// Returns a copy of the pointer of the parent wxWindow.
/// Accessor function is because users are not allowed to change the parent
/// but defining it as const means a lot of const_casts to deal with wx functions.
inline wxWindow* parent() const { return m_parent; }
void append_line(const Line& line);
Line create_single_option_line(const Option& option) const;
void append_single_option_line(const Option& option) { append_line(create_single_option_line(option)); }
// return a non-owning pointer reference
inline /*const*/ Field* get_field(t_config_option_key id) const { try { return m_fields.at(id).get(); } catch (std::out_of_range e) { return nullptr; } }
bool set_value(t_config_option_key id, boost::any value) { try { m_fields.at(id)->set_value(value); return true; } catch (std::out_of_range e) { return false; } }
boost::any get_value(t_config_option_key id) { boost::any out; try { out = m_fields.at(id)->get_value(); } catch (std::out_of_range e) { ; } return out; }
inline void enable() { for (auto& field : m_fields) field.second->enable(); }
inline void disable() { for (auto& field : m_fields) field.second->disable(); }
OptionsGroup(wxWindow* _parent, wxString title) :
m_parent(_parent), title(title) {
sizer = (staticbox ? new wxStaticBoxSizer(new wxStaticBox(_parent, wxID_ANY, title), wxVERTICAL) : new wxBoxSizer(wxVERTICAL));
auto num_columns = 1U;
if (label_width != 0) num_columns++;
if (extra_column != nullptr) num_columns++;
m_grid_sizer = new wxFlexGridSizer(0, num_columns, 0,0);
static_cast<wxFlexGridSizer*>(m_grid_sizer)->SetFlexibleDirection(wxHORIZONTAL);
static_cast<wxFlexGridSizer*>(m_grid_sizer)->AddGrowableCol(label_width != 0);
sizer->Add(m_grid_sizer, 0, wxEXPAND | wxALL, wxOSX ? 0: 5);
}
protected:
std::map<t_config_option_key, Option> m_options;
wxWindow* m_parent {nullptr};
/// Field list, contains unique_ptrs of the derived type.
/// using types that need to know what it is beyond the public interface
/// need to cast based on the related ConfigOptionDef.
t_optionfield_map m_fields;
bool m_disabled {false};
wxGridSizer* m_grid_sizer {nullptr};
/// Generate a wxSizer or wxWindow from a configuration option
/// Precondition: opt resolves to a known ConfigOption
/// Postcondition: fields contains a wx gui object.
const t_field& build_field(const t_config_option_key& id, const ConfigOptionDef& opt);
const t_field& build_field(const t_config_option_key& id);
const t_field& build_field(const Option& opt);
virtual void on_kill_focus (){};
virtual void on_change_OG(t_config_option_key opt_id, boost::any value);
};
class ConfigOptionsGroup: public OptionsGroup {
public:
ConfigOptionsGroup(wxWindow* parent, wxString title, DynamicPrintConfig* _config = nullptr) :
OptionsGroup(parent, title), m_config(_config) {}
/// reference to libslic3r config, non-owning pointer (?).
DynamicPrintConfig* m_config {nullptr};
bool m_full_labels {0};
std::map< std::string, std::pair<std::string, int> > m_opt_map;
Option get_option(const std::string opt_key, int opt_index = -1);
Line create_single_option_line(const std::string title, int idx = -1) /*const*/{
Option option = get_option(title, idx);
return OptionsGroup::create_single_option_line(option);
}
void append_single_option_line(const Option& option) {
OptionsGroup::append_single_option_line(option);
}
void append_single_option_line(const std::string title, int idx = -1)
{
Option option = get_option(title, idx);
append_single_option_line(option);
}
void on_change_OG(t_config_option_key opt_id, boost::any value) override;
void on_kill_focus() override
{
reload_config();
}
void reload_config();
boost::any config_value(std::string opt_key, int opt_index, bool deserialize);
// return option value from config
boost::any get_config_value(DynamicPrintConfig& config, std::string opt_key, int opt_index = -1);
Field* get_fieldc(t_config_option_key opt_key, int opt_index);
};
// Static text shown among the options.
class ogStaticText :public wxStaticText{
public:
ogStaticText() {}
ogStaticText(wxWindow* parent, const char *text) : wxStaticText(parent, wxID_ANY, text, wxDefaultPosition, wxDefaultSize){}
~ogStaticText(){}
void SetText(wxString value);
};
}}

View file

@ -226,7 +226,7 @@ private:
{
Preset key(m_type, name);
auto it = std::lower_bound(m_presets.begin() + 1, m_presets.end(), key);
return (it == m_presets.end() && m_presets.front().name == name) ? m_presets.begin() : it;
return ((it == m_presets.end() || it->name != name) && m_presets.front().name == name) ? m_presets.begin() : it;
}
std::deque<Preset>::const_iterator find_preset_internal(const std::string &name) const
{ return const_cast<PresetCollection*>(this)->find_preset_internal(name); }

View file

@ -280,8 +280,8 @@ void PresetBundle::load_config_file(const std::string &path)
if (boost::iends_with(path, ".gcode") || boost::iends_with(path, ".g")) {
DynamicPrintConfig config;
config.apply(FullPrintConfig::defaults());
config.load_from_gcode(path);
Preset::normalize(config);
config.load_from_gcode_file(path);
Preset::normalize(config);
load_config_file_config(path, true, std::move(config));
return;
}
@ -320,6 +320,18 @@ void PresetBundle::load_config_file(const std::string &path)
}
}
void PresetBundle::load_config_string(const char* str, const char* source_filename)
{
if (str != nullptr)
{
DynamicPrintConfig config;
config.apply(FullPrintConfig::defaults());
config.load_from_gcode_string(str);
Preset::normalize(config);
load_config_file_config((source_filename == nullptr) ? "" : source_filename, true, std::move(config));
}
}
// Load a config file from a boost property_tree. This is a private method called from load_config_file.
void PresetBundle::load_config_file_config(const std::string &name_or_path, bool is_external, DynamicPrintConfig &&config)
{

Some files were not shown because too many files have changed in this diff Show more